content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.maubis.markdown.spans
interface ICustomSpan {} | markdown/src/main/java/com/maubis/markdown/spans/ICustomSpan.kt | 1340553896 |
package com.nibado.projects.advent.y2018
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.collect.CharMap
import com.nibado.projects.advent.resourceLines
object Day18 : Day {
private val input = resourceLines(2018, 18)
private fun sim(minutes: Int): Int {
var map = CharMap.from(input)
for (i in 1..minutes) {
val nextMap = map.clone()
for (p in map.points()) {
val neighbors = p.neighbors().filter { map.inBounds(it) }
fun count(c: Char) = neighbors.count { map[it] == c }
if (map[p] == '.' && count('|') >= 3) {
nextMap[p] = '|'
} else if (map[p] == '|' && count('#') >= 3) {
nextMap[p] = '#'
} else if (map[p] == '#' && (count('#') < 1 || count('|') < 1)) {
nextMap[p] = '.'
}
}
map = nextMap
}
return map.count('|') * map.count('#')
}
override fun part1() = sim(10)
override fun part2() = sim(1000)
} | src/main/kotlin/com/nibado/projects/advent/y2018/Day18.kt | 1554561848 |
package tornadofx
import javafx.beans.property.SimpleDoubleProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import javafx.collections.FXCollections
import javafx.collections.ListChangeListener
import javafx.event.EventTarget
import javafx.scene.control.Button
import javafx.scene.control.Control
import javafx.scene.control.SkinBase
import javafx.scene.paint.Color
import javax.json.Json
import javax.json.JsonObject
fun EventTarget.keyboard(op: KeyboardLayout.() -> Unit) = opcr(this, KeyboardLayout(), op)
class KeyboardStyles : Stylesheet() {
init {
keyboard {
keyboardKey {
borderWidth += box(1.px)
borderColor += box(Color.BLACK)
borderRadius += box(3.px)
padding = box(3.px)
backgroundInsets += box(5.px)
backgroundRadius += box(5.px)
backgroundColor += Color.WHITE
and(armed) {
borderRadius += box(5.px)
backgroundInsets += box(7.px)
backgroundRadius += box(7.px)
}
}
}
}
}
class KeyboardLayout : Control() {
val rows = FXCollections.observableArrayList<KeyboardRow>()
val unitSizeProperty = SimpleDoubleProperty(50.0)
var unitSize by unitSizeProperty
init {
addClass(Stylesheet.keyboard)
}
override fun getUserAgentStylesheet() = KeyboardStyles().base64URL.toExternalForm()
override fun createDefaultSkin() = KeyboardSkin(this)
fun row(op: KeyboardRow.() -> Unit) = KeyboardRow(this).apply {
rows.add(this)
op(this)
}
fun load(json: JsonObject) {
json.getJsonArray("rows").mapTo(rows) {
KeyboardRow.fromJSON(this, it as JsonObject)
}
}
fun toJSON() = JsonBuilder()
.add("rows", Json.createArrayBuilder().let { jsonRows ->
rows.forEach { jsonRows.add(it.toJSON()) }
jsonRows.build()
})
.build()
fun toKeyboardLayoutEditorFormat(): String {
val output = StringBuilder()
rows.forEachIndexed { rowIndex, row ->
output.append("[")
row.keys.forEachIndexed { colIndex, key ->
if (colIndex > 0) output.append(",")
if (key is SpacerKeyboardKey) {
output.append("{x:${key.keyWidth}}")
} else {
if (key.keyWidth != 1.0 || key.keyHeight != 1.0) {
output.append("{")
if (key.keyWidth != 1.0) output.append("w:${key.keyWidth}")
if (key.keyHeight != 1.0) output.append("h:${key.keyHeight}")
output.append("},")
}
output.append("\"${key.text?.replace("\\", "\\\\") ?: ""}\"")
}
}
output.append("]")
if (rowIndex < rows.size - 1) output.append(",")
output.append("\n")
}
return output.toString()
}
internal fun addKeys(added: List<KeyboardKey>) = children.addAll(added)
internal fun removeKeys(removed: List<KeyboardKey>) = children.removeAll(removed)
}
class KeyboardSkin(control: KeyboardLayout) : SkinBase<KeyboardLayout>(control) {
val keyboard: KeyboardLayout = control
override fun layoutChildren(contentX: Double, contentY: Double, contentWidth: Double, contentHeight: Double) {
var currentX: Double
var currentY = contentY
keyboard.rows.forEach { row ->
currentX = contentX
row.keys.forEach { key ->
if (key !is SpacerKeyboardKey) key.resizeRelocate(currentX, currentY, key.prefWidth, key.prefHeight)
currentX += key.prefWidth
}
if (!row.keys.isEmpty()) {
currentY += row.keys.map { it.prefHeight(-1.0) }.min() ?: 0.0
}
}
}
override fun computePrefHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = keyboard.rows.sumByDouble { row ->
if (row.keys.isEmpty()) 0.0 else row.keys.map { it.prefHeight(width) }.min() ?: 0.0
} + topInset + bottomInset
override fun computePrefWidth(height: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = (keyboard.rows.map { row ->
if (row.keys.isEmpty()) 0.0 else row.keys.sumByDouble { it.prefWidth(height) }
}.max() ?: 0.0) + leftInset + rightInset
override fun computeMinWidth(height: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = computePrefWidth(height, topInset, rightInset, bottomInset, leftInset)
override fun computeMinHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = computePrefHeight(width, topInset, rightInset, bottomInset, leftInset)
}
class KeyboardRow(val keyboard: KeyboardLayout) {
val keys = FXCollections.observableArrayList<KeyboardKey>()
fun spacer(width: Number = 1.0, height: Number = 1.0) = SpacerKeyboardKey(keyboard, width, height).apply {
keys.add(this)
}
fun key(text: String? = null, svg: String? = null, code: Int? = null, width: Number = 1.0, height: Number = 1.0, op: KeyboardKey.() -> Unit = {}): KeyboardKey {
val key = KeyboardKey(keyboard, text, svg, code, width, height)
op(key)
keys.add(key)
return key
}
init {
keys.addListener(ListChangeListener {
while (it.next()) {
if (it.wasAdded()) keyboard.addKeys(it.addedSubList)
if (it.wasRemoved()) keyboard.removeKeys(it.removed)
}
})
}
companion object {
fun fromJSON(keyboard: KeyboardLayout, json: JsonObject) = KeyboardRow(keyboard).apply {
json.getJsonArray("keys").mapTo(keys) {
KeyboardKey.fromJSON(keyboard, it as JsonObject)
}
}
}
fun toJSON() = JsonBuilder()
.add("keys", Json.createArrayBuilder().let { jsonKeys ->
keys.forEach { jsonKeys.add(it.toJSON()) }
jsonKeys.build()
})
.build()
}
class SpacerKeyboardKey(keyboard: KeyboardLayout, width: Number, height: Number) : KeyboardKey(keyboard, null, null, null, width, height) {
init {
addClass(Stylesheet.keyboardSpacerKey)
}
constructor(keyboard: KeyboardLayout, json: JsonObject) : this(keyboard, json.getDouble("width"), json.getDouble("height"))
}
open class KeyboardKey(keyboard: KeyboardLayout, text: String?, svg: String?, code: Int? = null, width: Number, height: Number) : Button(text) {
val svgProperty = SimpleStringProperty(svg)
var svg by svgProperty
val keyWidthProperty = SimpleDoubleProperty(width.toDouble())
var keyWidth by keyWidthProperty
val keyHeightProperty = SimpleDoubleProperty(height.toDouble())
var keyHeight by keyHeightProperty
val codeProperty = SimpleObjectProperty<Int>(code)
var code by codeProperty
init {
addClass(Stylesheet.keyboardKey)
prefWidthProperty().bind(keyWidthProperty * keyboard.unitSizeProperty)
prefHeightProperty().bind(keyHeightProperty * keyboard.unitSizeProperty)
svgProperty.onChange { updateGraphic() }
updateGraphic()
}
private fun updateGraphic() {
graphic = if (svg != null) svgpath(svg) else null
}
fun toJSON() = JsonBuilder()
.add("type", if (this is SpacerKeyboardKey) "spacer" else null)
.add("text", text)
.add("svg", svg)
.add("code", code)
.add("width", keyWidth)
.add("height", keyHeight)
.build()
constructor(keyboard: KeyboardLayout, json: JsonObject) : this(keyboard, json.string("text"), json.string("svg"), json.int("code"), json.getDouble("width"), json.getDouble("height"))
companion object {
fun fromJSON(keyboard: KeyboardLayout, json: JsonObject): KeyboardKey =
if (json.getString("type", null) == "spacer") SpacerKeyboardKey(keyboard, json) else KeyboardKey(keyboard, json)
}
} | src/main/java/tornadofx/Keyboard.kt | 2464738410 |
package com.kamer.orny.data.room
import com.kamer.orny.data.room.entity.*
import com.kamer.orny.data.room.query.ExpenseWithEntities
import io.reactivex.Completable
import io.reactivex.Observable
interface DatabaseGateway {
fun getDefaultAuthor(): Observable<List<AuthorEntity>>
fun setAppSettings(appSettingsEntity: AppSettingsEntity): Completable
fun savePage(
pageSettingsEntity: PageSettingsEntity,
authors: List<AuthorEntity>,
expenses: List<ExpenseEntity>,
entries: List<ExpenseEntryEntity>
): Completable
fun getPageSettings(): Observable<PageSettingsEntity>
fun setPageSettings(pageSettingsEntity: PageSettingsEntity): Completable
fun addExpense(expense: ExpenseWithEntities): Completable
fun getAllExpensesWithEntities(): Observable<List<ExpenseWithEntities>>
fun getAllAuthors(): Observable<List<AuthorEntity>>
} | app/src/main/kotlin/com/kamer/orny/data/room/DatabaseGateway.kt | 2806654222 |
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import de.holisticon.ranked.model.TeamColor
import org.assertj.core.api.Assertions.assertThat
import org.junit.Ignore
import org.junit.Test
import java.time.LocalDateTime
class JacksonSerializationTest {
@Test
fun `serialize pair with enum and date`() {
val obj = Pair(TeamColor.RED, LocalDateTime.now())
val mapper = ObjectMapper()
.registerModule(JavaTimeModule())
.registerModule(KotlinModule())
val json = mapper.writer().writeValueAsString(obj)
assertThat(json).isEqualTo("{\"first\":\"RED\",\"second\":[2018,1,19,21,20,42,509000000]}")
}
}
| backend/model/src/test/kotlin/RestSpec.kt | 2902406698 |
package org.thoughtcrime.securesms.stories.viewer.reply.group
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import io.reactivex.rxjava3.kotlin.subscribeBy
import org.signal.paging.ProxyPagingController
import org.thoughtcrime.securesms.conversation.colors.NameColors
import org.thoughtcrime.securesms.database.model.MessageId
import org.thoughtcrime.securesms.groups.GroupId
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.util.rx.RxStore
class StoryGroupReplyViewModel(storyId: Long, repository: StoryGroupReplyRepository) : ViewModel() {
private val sessionMemberCache: MutableMap<GroupId, Set<Recipient>> = NameColors.createSessionMembersCache()
private val store = RxStore(StoryGroupReplyState())
private val disposables = CompositeDisposable()
val stateSnapshot: StoryGroupReplyState = store.state
val state: Flowable<StoryGroupReplyState> = store.stateFlowable
val pagingController: ProxyPagingController<MessageId> = ProxyPagingController()
init {
disposables += repository.getThreadId(storyId).subscribe { threadId ->
store.update { it.copy(threadId = threadId) }
}
disposables += repository.getPagedReplies(storyId)
.doOnNext { pagingController.set(it.controller) }
.flatMap { it.data }
.subscribeBy { data ->
store.update { state ->
state.copy(
replies = data,
loadState = StoryGroupReplyState.LoadState.READY
)
}
}
disposables += repository.getNameColorsMap(storyId, sessionMemberCache)
.subscribeBy { nameColors ->
store.update { state ->
state.copy(nameColors = nameColors)
}
}
}
override fun onCleared() {
disposables.clear()
store.dispose()
}
class Factory(private val storyId: Long, private val repository: StoryGroupReplyRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return modelClass.cast(StoryGroupReplyViewModel(storyId, repository)) as T
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/group/StoryGroupReplyViewModel.kt | 3049672684 |
package totoro.yui.util
import totoro.yui.Config
import totoro.yui.db.Database
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
@Suppress("unused")
object Markov {
private val splitPatternAllNonLetters = "[^\\p{L}0-9']+".toRegex()
private val splitPatternOnlySpaces = "\\s".toRegex()
const val beginning = "^"
const val chainDelimiter = " "
const val ending = "$"
/**
* First remove all chains data and the regenerate it anew
*/
fun regenerate(database: Database, progress: (String, Float) -> Unit): Boolean {
database.markov?.truncate()
database.markov?.setToConfig("first_unread", null)
return update(database, progress)
}
/**
* Read all files from the logs directory and build the probability tables
*/
fun update(database: Database, progress: (String, Float) -> Unit): Boolean {
if (!Config.markovPath.isNullOrEmpty()) {
val logsDir = File(Config.markovPath)
if (logsDir.exists()) {
var files = logsDir.listFiles().filter { !it.isDirectory }.sorted()
val firstUnread = database.markov?.getFromConfig("first_unread")
if (firstUnread != null && firstUnread != "null") files = files.dropWhile { it.name != firstUnread }
if (files.isNotEmpty()) {
// we will leave the last file because it's probably the today's log, and isn't finished yet
val theLastOne = files.last()
files = files.dropLast(1)
files.forEachIndexed { index, file ->
val stream = FileInputStream(file)
val reader = BufferedReader(InputStreamReader(stream, "UTF-8"))
database.markov?.prepareBatch()
reader.useLines { lines -> lines.forEach { line ->
if (line.contains('>') && !line.contains("***")) {
val words = splitToWords(line)
val author = line.substring(line.indexOf('<') + 1, line.indexOf('>'))
if (words.isNotEmpty() && (Config.markovAllowShortLines || words.size > 1)) {
sequencesBy(Config.markovOrder, words, { chain, word ->
database.markov?.addBatch(chain.replace("'", "''"), word.replace("'", "''"), author)
})
}
}
}}
database.markov?.commitBatch()
reader.close()
progress(file.name, index.toFloat() / files.size)
}
database.markov?.setToConfig("first_unread", theLastOne.name)
}
return true
}
}
return false
}
private fun splitToWords(line: String): List<String> =
listOf(beginning) +
line.drop(line.indexOf('>') + 1)
.split(if (Config.markovAllowNonLetters) splitPatternOnlySpaces else splitPatternAllNonLetters)
.filter { !it.isEmpty() } +
ending
private fun sequencesBy(order: Int, words: List<String>, block: (String, String) -> Unit) {
for (i in (-order + 1) until (words.size - order)) {
val key = (i..(i + order - 1))
.mapNotNull { words.getOrNull(it)?.toLowerCase() }
.joinToString(chainDelimiter)
val value = words[i + order].toLowerCase()
block(key, value)
}
}
/**
* Suggest the next word based on given chain
*/
fun suggest(database: Database, chain: String): String {
val suggestion = database.markov?.random(chain)
return suggestion?.word?.replace("''", "'") ?: ending
}
fun suggest(database: Database, chain: String, author: String): String {
val suggestion = database.markov?.random(chain, author)
return suggestion?.word?.replace("''", "'") ?: ending
}
}
| src/main/kotlin/totoro/yui/util/Markov.kt | 2149576786 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.gestures
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.positionChanged
import androidx.compose.ui.util.fastAny
import androidx.compose.ui.util.fastForEach
import androidx.compose.ui.util.fastSumBy
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
/**
* A gesture detector for rotation, panning, and zoom. Once touch slop has been reached, the
* user can use rotation, panning and zoom gestures. [onGesture] will be called when any of the
* rotation, zoom or pan occurs, passing the rotation angle in degrees, zoom in scale factor and
* pan as an offset in pixels. Each of these changes is a difference between the previous call
* and the current gesture. This will consume all position changes after touch slop has
* been reached. [onGesture] will also provide centroid of all the pointers that are down.
*
* If [panZoomLock] is `true`, rotation is allowed only if touch slop is detected for rotation
* before pan or zoom motions. If not, pan and zoom gestures will be detected, but rotation
* gestures will not be. If [panZoomLock] is `false`, once touch slop is reached, all three
* gestures are detected.
*
* Example Usage:
* @sample androidx.compose.foundation.samples.DetectTransformGestures
*/
suspend fun PointerInputScope.detectTransformGestures(
panZoomLock: Boolean = false,
onGesture: (centroid: Offset, pan: Offset, zoom: Float, rotation: Float) -> Unit
) {
awaitEachGesture {
var rotation = 0f
var zoom = 1f
var pan = Offset.Zero
var pastTouchSlop = false
val touchSlop = viewConfiguration.touchSlop
var lockedToPanZoom = false
awaitFirstDown(requireUnconsumed = false)
do {
val event = awaitPointerEvent()
val canceled = event.changes.fastAny { it.isConsumed }
if (!canceled) {
val zoomChange = event.calculateZoom()
val rotationChange = event.calculateRotation()
val panChange = event.calculatePan()
if (!pastTouchSlop) {
zoom *= zoomChange
rotation += rotationChange
pan += panChange
val centroidSize = event.calculateCentroidSize(useCurrent = false)
val zoomMotion = abs(1 - zoom) * centroidSize
val rotationMotion = abs(rotation * PI.toFloat() * centroidSize / 180f)
val panMotion = pan.getDistance()
if (zoomMotion > touchSlop ||
rotationMotion > touchSlop ||
panMotion > touchSlop
) {
pastTouchSlop = true
lockedToPanZoom = panZoomLock && rotationMotion < touchSlop
}
}
if (pastTouchSlop) {
val centroid = event.calculateCentroid(useCurrent = false)
val effectiveRotation = if (lockedToPanZoom) 0f else rotationChange
if (effectiveRotation != 0f ||
zoomChange != 1f ||
panChange != Offset.Zero
) {
onGesture(centroid, panChange, zoomChange, effectiveRotation)
}
event.changes.fastForEach {
if (it.positionChanged()) {
it.consume()
}
}
}
}
} while (!canceled && event.changes.fastAny { it.pressed })
}
}
/**
* Returns the rotation, in degrees, of the pointers between the
* [PointerInputChange.previousPosition] and [PointerInputChange.position] states. Only
* the pointers that are down in both previous and current states are considered.
*
* Example Usage:
* @sample androidx.compose.foundation.samples.CalculateRotation
*/
fun PointerEvent.calculateRotation(): Float {
val pointerCount = changes.fastSumBy { if (it.previousPressed && it.pressed) 1 else 0 }
if (pointerCount < 2) {
return 0f
}
val currentCentroid = calculateCentroid(useCurrent = true)
val previousCentroid = calculateCentroid(useCurrent = false)
var rotation = 0f
var rotationWeight = 0f
// We want to weigh each pointer differently so that motions farther from the
// centroid have more weight than pointers close to the centroid. Essentially,
// a small distance change near the centroid could equate to a large angle
// change and we don't want it to affect the rotation as much as pointers farther
// from the centroid, which should be more stable.
changes.fastForEach { change ->
if (change.pressed && change.previousPressed) {
val currentPosition = change.position
val previousPosition = change.previousPosition
val previousOffset = previousPosition - previousCentroid
val currentOffset = currentPosition - currentCentroid
val previousAngle = previousOffset.angle()
val currentAngle = currentOffset.angle()
val angleDiff = currentAngle - previousAngle
val weight = (currentOffset + previousOffset).getDistance() / 2f
// We weigh the rotation with the distance to the centroid. This gives
// more weight to angle changes from pointers farther from the centroid than
// those that are closer.
rotation += when {
angleDiff > 180f -> angleDiff - 360f
angleDiff < -180f -> angleDiff + 360f
else -> angleDiff
} * weight
// weight its contribution by the distance to the centroid
rotationWeight += weight
}
}
return if (rotationWeight == 0f) 0f else rotation / rotationWeight
}
/**
* Returns the angle of the [Offset] between -180 and 180, or 0 if [Offset.Zero].
*/
private fun Offset.angle(): Float =
if (x == 0f && y == 0f) 0f else -atan2(x, y) * 180f / PI.toFloat()
/**
* Uses the change of the centroid size between the [PointerInputChange.previousPosition] and
* [PointerInputChange.position] to determine how much zoom was intended.
*
* Example Usage:
* @sample androidx.compose.foundation.samples.CalculateZoom
*/
fun PointerEvent.calculateZoom(): Float {
val currentCentroidSize = calculateCentroidSize(useCurrent = true)
val previousCentroidSize = calculateCentroidSize(useCurrent = false)
if (currentCentroidSize == 0f || previousCentroidSize == 0f) {
return 1f
}
return currentCentroidSize / previousCentroidSize
}
/**
* Returns the change in the centroid location between the previous and the current pointers that
* are down. Pointers that are newly down or raised are not considered in the centroid
* movement.
*
* Example Usage:
* @sample androidx.compose.foundation.samples.CalculatePan
*/
fun PointerEvent.calculatePan(): Offset {
val currentCentroid = calculateCentroid(useCurrent = true)
if (currentCentroid == Offset.Unspecified) {
return Offset.Zero
}
val previousCentroid = calculateCentroid(useCurrent = false)
return currentCentroid - previousCentroid
}
/**
* Returns the average distance from the centroid for all pointers that are currently
* and were previously down. If no pointers are down, `0` is returned.
* If [useCurrent] is `true`, the size of the [PointerInputChange.position] is returned and
* if `false`, the size of [PointerInputChange.previousPosition] is returned. Only pointers that
* are down in both the previous and current state are used to calculate the centroid size.
*
* Example Usage:
* @sample androidx.compose.foundation.samples.CalculateCentroidSize
*/
fun PointerEvent.calculateCentroidSize(useCurrent: Boolean = true): Float {
val centroid = calculateCentroid(useCurrent)
if (centroid == Offset.Unspecified) {
return 0f
}
var distanceToCentroid = 0f
var distanceWeight = 0
changes.fastForEach { change ->
if (change.pressed && change.previousPressed) {
val position = if (useCurrent) change.position else change.previousPosition
distanceToCentroid += (position - centroid).getDistance()
distanceWeight++
}
}
return distanceToCentroid / distanceWeight.toFloat()
}
/**
* Returns the centroid of all pointers that are down and were previously down. If no pointers
* are down, [Offset.Unspecified] is returned. If [useCurrent] is `true`, the centroid of the
* [PointerInputChange.position] is returned and if `false`, the centroid of the
* [PointerInputChange.previousPosition] is returned. Only pointers that are down in both the
* previous and current state are used to calculate the centroid.
*
* Example Usage:
* @sample androidx.compose.foundation.samples.CalculateCentroidSize
*/
fun PointerEvent.calculateCentroid(
useCurrent: Boolean = true
): Offset {
var centroid = Offset.Zero
var centroidWeight = 0
changes.fastForEach { change ->
if (change.pressed && change.previousPressed) {
val position = if (useCurrent) change.position else change.previousPosition
centroid += position
centroidWeight++
}
}
return if (centroidWeight == 0) {
Offset.Unspecified
} else {
centroid / centroidWeight.toFloat()
}
}
| compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/gestures/TransformGestureDetector.kt | 1723361346 |
package com.simplemobiletools.notes.pro.adapters
import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.view.View
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.simplemobiletools.commons.extensions.adjustAlpha
import com.simplemobiletools.commons.extensions.setText
import com.simplemobiletools.commons.extensions.setTextSize
import com.simplemobiletools.commons.helpers.WIDGET_TEXT_COLOR
import com.simplemobiletools.notes.pro.R
import com.simplemobiletools.notes.pro.R.id.widget_text_holder
import com.simplemobiletools.notes.pro.extensions.config
import com.simplemobiletools.notes.pro.extensions.getPercentageFontSize
import com.simplemobiletools.notes.pro.extensions.notesDB
import com.simplemobiletools.notes.pro.helpers.*
import com.simplemobiletools.notes.pro.models.ChecklistItem
import com.simplemobiletools.notes.pro.models.Note
class WidgetAdapter(val context: Context, val intent: Intent) : RemoteViewsService.RemoteViewsFactory {
private val textIds = arrayOf(
R.id.widget_text_left, R.id.widget_text_center, R.id.widget_text_right,
R.id.widget_text_left_monospace, R.id.widget_text_center_monospace, R.id.widget_text_right_monospace
)
private val checklistIds = arrayOf(
R.id.checklist_text_left, R.id.checklist_text_center, R.id.checklist_text_right,
R.id.checklist_text_left_monospace, R.id.checklist_text_center_monospace, R.id.checklist_text_right_monospace
)
private var widgetTextColor = DEFAULT_WIDGET_TEXT_COLOR
private var note: Note? = null
private var checklistItems = ArrayList<ChecklistItem>()
override fun getViewAt(position: Int): RemoteViews {
val noteId = intent.getLongExtra(NOTE_ID, 0L)
val remoteView: RemoteViews
if (note == null) {
return RemoteViews(context.packageName, R.layout.widget_text_layout)
}
val textSize = context.getPercentageFontSize() / context.resources.displayMetrics.density
if (note!!.type == NoteType.TYPE_CHECKLIST.value) {
remoteView = RemoteViews(context.packageName, R.layout.item_checklist_widget).apply {
val checklistItem = checklistItems.getOrNull(position) ?: return@apply
val widgetNewTextColor = if (checklistItem.isDone) widgetTextColor.adjustAlpha(DONE_CHECKLIST_ITEM_ALPHA) else widgetTextColor
val paintFlags = if (checklistItem.isDone) Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG else Paint.ANTI_ALIAS_FLAG
for (id in checklistIds) {
setText(id, checklistItem.title)
setTextColor(id, widgetNewTextColor)
setTextSize(id, textSize)
setInt(id, "setPaintFlags", paintFlags)
setViewVisibility(id, View.GONE)
}
setViewVisibility(getProperChecklistTextView(context), View.VISIBLE)
Intent().apply {
putExtra(OPEN_NOTE_ID, noteId)
setOnClickFillInIntent(R.id.checklist_text_holder, this)
}
}
} else {
remoteView = RemoteViews(context.packageName, R.layout.widget_text_layout).apply {
val noteText = note!!.getNoteStoredValue(context) ?: ""
for (id in textIds) {
setText(id, noteText)
setTextColor(id, widgetTextColor)
setTextSize(id, textSize)
setViewVisibility(id, View.GONE)
}
setViewVisibility(getProperTextView(context), View.VISIBLE)
Intent().apply {
putExtra(OPEN_NOTE_ID, noteId)
setOnClickFillInIntent(widget_text_holder, this)
}
}
}
return remoteView
}
private fun getProperTextView(context: Context): Int {
val gravity = context.config.gravity
val isMonospaced = context.config.monospacedFont
return when {
gravity == GRAVITY_CENTER && isMonospaced -> R.id.widget_text_center_monospace
gravity == GRAVITY_CENTER -> R.id.widget_text_center
gravity == GRAVITY_RIGHT && isMonospaced -> R.id.widget_text_right_monospace
gravity == GRAVITY_RIGHT -> R.id.widget_text_right
isMonospaced -> R.id.widget_text_left_monospace
else -> R.id.widget_text_left
}
}
private fun getProperChecklistTextView(context: Context): Int {
val gravity = context.config.gravity
val isMonospaced = context.config.monospacedFont
return when {
gravity == GRAVITY_CENTER && isMonospaced -> R.id.checklist_text_center_monospace
gravity == GRAVITY_CENTER -> R.id.checklist_text_center
gravity == GRAVITY_RIGHT && isMonospaced -> R.id.checklist_text_right_monospace
gravity == GRAVITY_RIGHT -> R.id.checklist_text_right
isMonospaced -> R.id.checklist_text_left_monospace
else -> R.id.checklist_text_left
}
}
override fun onCreate() {}
override fun getLoadingView() = null
override fun getItemId(position: Int) = position.toLong()
override fun onDataSetChanged() {
widgetTextColor = intent.getIntExtra(WIDGET_TEXT_COLOR, DEFAULT_WIDGET_TEXT_COLOR)
val noteId = intent.getLongExtra(NOTE_ID, 0L)
note = context.notesDB.getNoteWithId(noteId)
if (note?.type == NoteType.TYPE_CHECKLIST.value) {
val checklistItemType = object : TypeToken<List<ChecklistItem>>() {}.type
checklistItems = Gson().fromJson<ArrayList<ChecklistItem>>(note!!.getNoteStoredValue(context), checklistItemType) ?: ArrayList(1)
// checklist title can be null only because of the glitch in upgrade to 6.6.0, remove this check in the future
checklistItems = checklistItems.filter { it.title != null }.toMutableList() as ArrayList<ChecklistItem>
}
}
override fun hasStableIds() = true
override fun getCount(): Int {
return if (note?.type == NoteType.TYPE_CHECKLIST.value) {
checklistItems.size
} else {
1
}
}
override fun getViewTypeCount() = 2
override fun onDestroy() {}
}
| app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/WidgetAdapter.kt | 2643517701 |
// 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.completion.handlers
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.renderer.render
open class BaseDeclarationInsertHandler : InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
val name = (item.`object` as? DeclarationLookupObject)?.name
if (name != null && !name.isSpecial) {
val startOffset = context.startOffset
if (startOffset > 0 && context.document.isTextAt(startOffset - 1, "`")) {
context.document.deleteString(startOffset - 1, startOffset)
}
context.document.replaceString(context.startOffset, context.tailOffset, name.render())
}
}
}
| plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/handlers/BaseDeclarationInsertHandler.kt | 127417683 |
// "Add 'kotlin.Any' as upper bound for E" "true"
class A<T : Any>
fun <E> bar(x: A<E<caret>>) {}
| plugins/kotlin/idea/tests/testData/quickfix/addGenericUpperBound/withinDeclaration.kt | 1830398191 |
// 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.ide.actions.tree
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.SwingActionDelegate
import com.intellij.util.ui.tree.EditableNode
import com.intellij.util.ui.tree.EditableTree
import com.intellij.util.ui.tree.TreeUtil
import javax.swing.JTree
internal class StartEditingAction : DumbAwareAction() {
private val AnActionEvent.contextTree
get() = getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as? JTree
private fun getEditableNode(node: Any?) = node as? EditableNode
?: TreeUtil.getUserObject(EditableNode::class.java, node)
private fun getEditableTree(tree: JTree) = tree.model as? EditableTree
?: tree as? EditableTree
?: tree.getClientProperty(EditableTree.KEY) as? EditableTree
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = false
val tree = event.contextTree ?: return
event.presentation.isVisible = true
// enable editing if the selected path is editable
val path = tree.leadSelectionPath ?: return
event.presentation.isEnabled = tree.run { isPathEditable(path) && cellEditor?.isCellEditable(null) == true }
// update action presentation according to the selected node
getEditableNode(path.lastPathComponent)?.updateAction(event.presentation)
?: getEditableTree(tree)?.updateAction(event.presentation, path)
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun actionPerformed(event: AnActionEvent) {
// javax.swing.plaf.basic.BasicTreeUI.Actions.START_EDITING
SwingActionDelegate.performAction("startEditing", event.contextTree)
}
init {
isEnabledInModalContext = true
}
}
| platform/platform-impl/src/com/intellij/ide/actions/tree/StartEditingAction.kt | 3034368961 |
fun main(): @Anno <caret>String {}
@Target(AnnotationTarget.TYPE)
annotation class Anno | plugins/kotlin/code-insight/inspections-k2/tests/testData/inspectionsLocal/mainFunctionReturnUnit/topLevel/annotatedReturnType.kt | 3537988952 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.analysis
import com.intellij.ProjectTopics
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.service
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressManager.checkCanceled
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.Disposer
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.util.containers.MultiMap
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.findModule
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity
import org.jetbrains.kotlin.idea.base.analysis.libraries.LibraryDependencyCandidate
import org.jetbrains.kotlin.idea.base.facet.isHMPPEnabled
import org.jetbrains.kotlin.idea.base.projectStructure.*
import org.jetbrains.kotlin.idea.base.projectStructure.LibraryDependenciesCache.LibraryDependencies
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibraryInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.allSdks
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.checkValidity
import org.jetbrains.kotlin.idea.base.util.caching.SynchronizedFineGrainedEntityCache
import org.jetbrains.kotlin.idea.base.util.caching.WorkspaceEntityChangeListener
import org.jetbrains.kotlin.idea.caches.project.*
import org.jetbrains.kotlin.idea.caches.trackers.ModuleModificationTracker
import org.jetbrains.kotlin.idea.configuration.isMavenized
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
typealias LibraryDependencyCandidatesAndSdkInfos = Pair<Set<LibraryDependencyCandidate>, Set<SdkInfo>>
class LibraryDependenciesCacheImpl(private val project: Project) : LibraryDependenciesCache, Disposable {
companion object {
fun getInstance(project: Project): LibraryDependenciesCache = project.service()
}
private val cache = LibraryDependenciesInnerCache()
private val moduleDependenciesCache = ModuleDependenciesCache()
init {
Disposer.register(this, cache)
Disposer.register(this, moduleDependenciesCache)
}
override fun getLibraryDependencies(library: LibraryInfo): LibraryDependencies = cache[library]
override fun dispose() = Unit
private fun computeLibrariesAndSdksUsedWith(libraryInfo: LibraryInfo): LibraryDependencies {
val (dependencyCandidates, sdks) = computeLibrariesAndSdksUsedWithNoFilter(libraryInfo)
// Maven is Gradle Metadata unaware, and therefore needs stricter filter. See KTIJ-15758
val libraryDependenciesFilter = if (project.isMavenized)
StrictEqualityForPlatformSpecificCandidatesFilter
else
DefaultLibraryDependenciesFilter union SharedNativeLibraryToNativeInteropFallbackDependenciesFilter
val libraries = libraryDependenciesFilter(libraryInfo.platform, dependencyCandidates).flatMap { it.libraries }
return LibraryDependencies(libraryInfo, libraries, sdks.toList())
}
//NOTE: used LibraryRuntimeClasspathScope as reference
private fun computeLibrariesAndSdksUsedWithNoFilter(libraryInfo: LibraryInfo): LibraryDependencyCandidatesAndSdkInfos {
val libraries = LinkedHashSet<LibraryDependencyCandidate>()
val sdks = LinkedHashSet<SdkInfo>()
val modulesLibraryIsUsedIn =
getLibraryUsageIndex().getModulesLibraryIsUsedIn(libraryInfo)
for (module in modulesLibraryIsUsedIn) {
checkCanceled()
val (moduleLibraries, moduleSdks) = moduleDependenciesCache[module]
libraries.addAll(moduleLibraries)
sdks.addAll(moduleSdks)
}
val filteredLibraries = filterForBuiltins(libraryInfo, libraries)
return filteredLibraries to sdks
}
private fun computeLibrariesAndSdksUsedIn(module: Module): LibraryDependencyCandidatesAndSdkInfos {
val libraries = LinkedHashSet<LibraryDependencyCandidate>()
val sdks = LinkedHashSet<SdkInfo>()
val processedModules = HashSet<Module>()
val condition = Condition<OrderEntry> { orderEntry ->
checkCanceled()
orderEntry.safeAs<ModuleOrderEntry>()?.let {
it.module?.run { this !in processedModules } ?: false
} ?: true
}
val infoCache = LibraryInfoCache.getInstance(project)
ModuleRootManager.getInstance(module).orderEntries()
// TODO: it results into O(n^2)
.recursively()
.satisfying(condition).process(object : RootPolicy<Unit>() {
override fun visitModuleSourceOrderEntry(moduleSourceOrderEntry: ModuleSourceOrderEntry, value: Unit) {
processedModules.add(moduleSourceOrderEntry.ownerModule)
}
override fun visitLibraryOrderEntry(libraryOrderEntry: LibraryOrderEntry, value: Unit) {
checkCanceled()
val libraryEx = libraryOrderEntry.library.safeAs<LibraryEx>()?.takeUnless { it.isDisposed } ?: return
val candidate = LibraryDependencyCandidate.fromLibraryOrNull(infoCache[libraryEx]) ?: return
libraries += candidate
}
override fun visitJdkOrderEntry(jdkOrderEntry: JdkOrderEntry, value: Unit) {
checkCanceled()
jdkOrderEntry.jdk?.let { jdk ->
sdks += SdkInfo(project, jdk)
}
}
}, Unit)
return libraries to sdks
}
/*
* When built-ins are created from module dependencies (as opposed to loading them from classloader)
* we must resolve Kotlin standard library containing some built-ins declarations in the same
* resolver for project as JDK. This comes from the following requirements:
* - JvmBuiltins need JDK and standard library descriptors -> resolver for project should be able to
* resolve them
* - Builtins are created in BuiltinsCache -> module descriptors should be resolved under lock of the
* SDK resolver to prevent deadlocks
* This means we have to maintain dependencies of the standard library manually or effectively drop
* resolver for SDK otherwise. Libraries depend on superset of their actual dependencies because of
* the inability to get real dependencies from IDEA model. So moving stdlib with all dependencies
* down is a questionable option.
*/
private fun filterForBuiltins(
libraryInfo: LibraryInfo,
dependencyLibraries: Set<LibraryDependencyCandidate>
): Set<LibraryDependencyCandidate> {
return if (!IdeBuiltInsLoadingState.isFromClassLoader && libraryInfo.isCoreKotlinLibrary(project)) {
dependencyLibraries.filterTo(mutableSetOf()) { dep ->
dep.libraries.any { it.isCoreKotlinLibrary(project) }
}
} else {
dependencyLibraries
}
}
private fun getLibraryUsageIndex(): LibraryUsageIndex =
CachedValuesManager.getManager(project).getCachedValue(project) {
CachedValueProvider.Result(
LibraryUsageIndex(),
ModuleModificationTracker.getInstance(project),
LibraryModificationTracker.getInstance(project)
)
}!!
private inner class LibraryDependenciesInnerCache :
SynchronizedFineGrainedEntityCache<LibraryInfo, LibraryDependencies>(project, cleanOnLowMemory = true),
LibraryInfoListener,
ModuleRootListener,
ProjectJdkTable.Listener {
override fun subscribe() {
val connection = project.messageBus.connect(this)
connection.subscribe(LibraryInfoListener.TOPIC, this)
connection.subscribe(ProjectTopics.PROJECT_ROOTS, this)
connection.subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, this)
}
override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) {
invalidateEntries({ k, v -> k in libraryInfos || v.libraries.any { it in libraryInfos } })
}
override fun jdkRemoved(jdk: Sdk) {
invalidateEntries({ _, v -> v.sdk.any { it.sdk == jdk } })
}
override fun jdkNameChanged(jdk: Sdk, previousName: String) {
jdkRemoved(jdk)
}
override fun calculate(key: LibraryInfo): LibraryDependencies =
computeLibrariesAndSdksUsedWith(key)
override fun checkKeyValidity(key: LibraryInfo) {
key.checkValidity()
}
override fun checkValueValidity(value: LibraryDependencies) {
value.libraries.forEach { it.checkValidity() }
}
override fun rootsChanged(event: ModuleRootEvent) {
if (event.isCausedByWorkspaceModelChangesOnly) return
// SDK could be changed (esp in tests) out of message bus subscription
val sdks = project.allSdks()
invalidateEntries(
{ _, value -> value.sdk.any { it.sdk !in sdks } },
// unable to check entities properly: an event could be not the last
validityCondition = null
)
}
}
private inner class ModuleDependenciesCache :
SynchronizedFineGrainedEntityCache<Module, LibraryDependencyCandidatesAndSdkInfos>(project),
ProjectJdkTable.Listener,
LibraryInfoListener,
ModuleRootListener {
override fun subscribe() {
val connection = project.messageBus.connect(this)
connection.subscribe(WorkspaceModelTopics.CHANGED, ModelChangeListener())
connection.subscribe(LibraryInfoListener.TOPIC, this)
connection.subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, this)
connection.subscribe(ProjectTopics.PROJECT_ROOTS, this)
}
override fun calculate(key: Module): LibraryDependencyCandidatesAndSdkInfos =
computeLibrariesAndSdksUsedIn(key)
override fun checkKeyValidity(key: Module) {
key.checkValidity()
}
override fun checkValueValidity(value: LibraryDependencyCandidatesAndSdkInfos) {
value.first.forEach { it.libraries.forEach { libraryInfo -> libraryInfo.checkValidity() } }
}
override fun jdkRemoved(jdk: Sdk) {
invalidateEntries({ _, candidates -> candidates.second.any { it.sdk == jdk } })
}
override fun jdkNameChanged(jdk: Sdk, previousName: String) {
jdkRemoved(jdk)
}
override fun rootsChanged(event: ModuleRootEvent) {
if (event.isCausedByWorkspaceModelChangesOnly) return
// SDK could be changed (esp in tests) out of message bus subscription
val sdks = project.allSdks()
invalidateEntries(
{ _, (_, sdkInfos) -> sdkInfos.any { it.sdk !in sdks } },
// unable to check entities properly: an event could be not the last
validityCondition = null
)
}
inner class ModelChangeListener : WorkspaceEntityChangeListener<ModuleEntity, Module>(project) {
override val entityClass: Class<ModuleEntity>
get() = ModuleEntity::class.java
override fun map(storage: EntityStorage, entity: ModuleEntity): Module? =
entity.findModule(storage)
override fun entitiesChanged(outdated: List<Module>) {
// TODO: incorrect in case of transitive module dependency
invalidateKeys(outdated) { _, _ -> false }
}
}
override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) {
val infos = libraryInfos.toHashSet()
invalidateEntries(
{ _, v ->
v.first.any { candidate -> candidate.libraries.any { it in infos } }
},
// unable to check entities properly: an event could be not the last
validityCondition = null
)
}
}
private inner class LibraryUsageIndex {
private val modulesLibraryIsUsedIn: MultiMap<Library, Module> = runReadAction {
val map: MultiMap<Library, Module> = MultiMap.createSet()
val libraryCache = LibraryInfoCache.getInstance(project)
for (module in ModuleManager.getInstance(project).modules) {
checkCanceled()
for (entry in ModuleRootManager.getInstance(module).orderEntries) {
if (entry !is LibraryOrderEntry) continue
val library = entry.library ?: continue
val keyLibrary = libraryCache.deduplicatedLibrary(library)
map.putValue(keyLibrary, module)
}
}
map
}
fun getModulesLibraryIsUsedIn(libraryInfo: LibraryInfo) = sequence<Module> {
val ideaModelInfosCache = getIdeaModelInfosCache(project)
for (module in modulesLibraryIsUsedIn[libraryInfo.library]) {
val mappedModuleInfos = ideaModelInfosCache.getModuleInfosForModule(module)
if (mappedModuleInfos.any { it.platform.canDependOn(libraryInfo, module.isHMPPEnabled) }) {
yield(module)
}
}
}
}
}
| plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/base/analysis/LibraryDependenciesCache.kt | 348825480 |
package id.kotlin.sample.room.main
import id.kotlin.sample.room.data.User
interface MainListener {
fun onItemClick(user: User)
fun onItemLongClick(user: User)
} | app/src/main/java/id/kotlin/sample/room/main/MainListener.kt | 2091826311 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.credentialStore.keePass
import com.intellij.credentialStore.*
import com.intellij.credentialStore.kdbx.IncorrectMasterPasswordException
import com.intellij.credentialStore.kdbx.KdbxPassword
import com.intellij.credentialStore.kdbx.KeePassDatabase
import com.intellij.credentialStore.kdbx.loadKdbx
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.NlsContexts.DialogMessage
import com.intellij.openapi.util.NlsContexts.DialogTitle
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import java.awt.Component
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.security.SecureRandom
open class KeePassFileManager(private val file: Path,
masterKeyFile: Path,
private val masterKeyEncryptionSpec: EncryptionSpec,
private val secureRandom: Lazy<SecureRandom>) {
private val masterKeyFileStorage = MasterKeyFileStorage(masterKeyFile)
fun clear() {
if (!file.exists()) {
return
}
try {
// don't create with preloaded empty db because "clear" action should remove only IntelliJ group from database,
// but don't remove other groups
val masterPassword = masterKeyFileStorage.load()
if (masterPassword != null) {
val db = loadKdbx(file, KdbxPassword.createAndClear(masterPassword))
val store = KeePassCredentialStore(file, masterKeyFileStorage, db)
store.clear()
store.save(masterKeyEncryptionSpec)
return
}
}
catch (e: Exception) {
// ok, just remove file
if (e !is IncorrectMasterPasswordException && ApplicationManager.getApplication()?.isUnitTestMode == false) {
LOG.error(e)
}
}
file.delete()
}
fun import(fromFile: Path, event: AnActionEvent?) {
if (file == fromFile) {
return
}
try {
doImportOrUseExisting(fromFile, event)
}
catch (e: IncorrectMasterPasswordException) {
throw e
}
catch (e: Exception) {
LOG.warn(e)
CredentialStoreUiService.getInstance().showErrorMessage(
event?.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT),
CredentialStoreBundle.message("kee.pass.dialog.title.cannot.import"),
CredentialStoreBundle.message("kee.pass.dialog.message"))
}
}
// throws IncorrectMasterPasswordException if user cancelled ask master password dialog
@Throws(IncorrectMasterPasswordException::class)
fun useExisting() {
if (file.exists()) {
if (!doImportOrUseExisting(file, event = null)) {
throw IncorrectMasterPasswordException()
}
}
else {
saveDatabase(file, KeePassDatabase(), generateRandomMasterKey(masterKeyEncryptionSpec, secureRandom.value), masterKeyFileStorage,
secureRandom.value)
}
}
private fun doImportOrUseExisting(file: Path, event: AnActionEvent?): Boolean {
val contextComponent = event?.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT)
// check master key file in parent dir of imported file
val possibleMasterKeyFile = file.parent.resolve(MASTER_KEY_FILE_NAME)
var masterPassword = MasterKeyFileStorage(possibleMasterKeyFile).load()
if (masterPassword != null) {
try {
loadKdbx(file, KdbxPassword(masterPassword))
}
catch (e: IncorrectMasterPasswordException) {
LOG.warn("On import \"$file\" found existing master key file \"$possibleMasterKeyFile\" but key is not correct")
masterPassword = null
}
}
if (masterPassword == null && !requestMasterPassword(CredentialStoreBundle.message("kee.pass.dialog.request.master.title"),
contextComponent = contextComponent) {
try {
loadKdbx(file, KdbxPassword(it))
masterPassword = it
null
}
catch (e: IncorrectMasterPasswordException) {
CredentialStoreBundle.message("dialog.message.master.password.not.correct")
}
}) {
return false
}
if (file !== this.file) {
Files.copy(file, this.file, StandardCopyOption.REPLACE_EXISTING)
}
masterKeyFileStorage.save(createMasterKey(masterPassword!!))
return true
}
fun askAndSetMasterKey(event: AnActionEvent?, @DialogMessage topNote: String? = null): Boolean {
val contextComponent = event?.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT)
// to open old database, key can be required, so, to avoid showing 2 dialogs, check it before
val db = try {
if (file.exists()) loadKdbx(file, KdbxPassword(
this.masterKeyFileStorage.load() ?: throw IncorrectMasterPasswordException(isFileMissed = true)))
else KeePassDatabase()
}
catch (e: IncorrectMasterPasswordException) {
// ok, old key is required
return requestCurrentAndNewKeys(contextComponent)
}
return requestMasterPassword(CredentialStoreBundle.message("kee.pass.dialog.title.set.master.password"), topNote = topNote,
contextComponent = contextComponent) {
saveDatabase(file, db, createMasterKey(it), masterKeyFileStorage, secureRandom.value)
null
}
}
protected open fun requestCurrentAndNewKeys(contextComponent: Component?): Boolean {
return CredentialStoreUiService.getInstance().showChangeMasterPasswordDialog(contextComponent, ::doSetNewMasterPassword)
}
@Suppress("MemberVisibilityCanBePrivate")
protected fun doSetNewMasterPassword(current: CharArray, new: CharArray): Boolean {
val db = loadKdbx(file, KdbxPassword.createAndClear(current.toByteArrayAndClear()))
saveDatabase(file, db, createMasterKey(new.toByteArrayAndClear()), masterKeyFileStorage, secureRandom.value)
return false
}
private fun createMasterKey(value: ByteArray, isAutoGenerated: Boolean = false) =
MasterKey(value, isAutoGenerated, masterKeyEncryptionSpec)
protected open fun requestMasterPassword(@DialogTitle title: String,
@DialogMessage topNote: String? = null,
contextComponent: Component? = null,
@DialogMessage ok: (value: ByteArray) -> String?): Boolean {
return CredentialStoreUiService.getInstance().showRequestMasterPasswordDialog(title, topNote, contextComponent, ok)
}
fun saveMasterKeyToApplyNewEncryptionSpec() {
// if null, master key file doesn't exist now, it will be saved later somehow, no need to re-save with a new encryption spec
val existing = masterKeyFileStorage.load() ?: return
// no need to re-save db file because master password is not changed, only master key encryption spec changed
masterKeyFileStorage.save(createMasterKey(existing, isAutoGenerated = masterKeyFileStorage.isAutoGenerated()))
}
fun setCustomMasterPasswordIfNeeded(defaultDbFile: Path) {
// https://youtrack.jetbrains.com/issue/IDEA-174581#focus=streamItem-27-3081868-0-0
// for custom location require to set custom master password to make sure that user will be able to reuse file on another machine
if (file == defaultDbFile) {
return
}
if (!masterKeyFileStorage.isAutoGenerated()) {
return
}
askAndSetMasterKey(null, topNote = CredentialStoreBundle.message("kee.pass.top.note"))
}
}
| platform/credential-store/src/keePass/KeePassFileManager.kt | 283731574 |
package com.maly.domain.order
import com.google.i18n.phonenumbers.NumberParseException
import com.google.i18n.phonenumbers.PhoneNumberUtil
import com.maly.domain.event.EventService
import com.maly.domain.order.dto.TicketDto
import com.maly.domain.room.Seat
import com.maly.domain.room.SeatRepository
import com.maly.extension.getDefaultMessage
import com.maly.presentation.error.BusinessException
import com.maly.presentation.order.BuyModel
import com.maly.presentation.order.ReservationModel
import org.springframework.context.MessageSource
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDateTime
/**
* @author Aleksander Brzozowski
*/
@Service
class OrderService(private val discountRepository: DiscountRepository,
private val saleFormRepository: SaleFormRepository,
private val reservationRepository: ReservationRepository,
private val seatRepository: SeatRepository,
private val eventService: EventService,
private val ticketRepository: TicketRepository,
private val messageSource: MessageSource,
private val saleRepository: SaleRepository) {
companion object {
const val SALE_FORM_NAME = "Internetowa"
const val EXPIRE_TIME_MINUTES = 30L
}
fun getDiscounts(): List<Discount> = discountRepository.findAll()
@Transactional
fun reserveEvent(model: ReservationModel): TicketDto {
validatePhoneNumber(model.telephone)
val saleForm = getSaleForm()
val now = LocalDateTime.now()
val event = eventService.getEvent(model.eventId)
val reservation = Reservation(saleForm = saleForm, expiryDate = event.date.minusMinutes(EXPIRE_TIME_MINUTES),
date = now, firstName = model.firstName, lastName = model.lastName, telephone = model.telephone)
.let { reservationRepository.save(it) }
return model.tickets.map { it.discountId?.let { getDiscountById(it) } to getSeatById(it.seatId) }
.map { (discount, seat) -> Ticket(reservation = reservation, seat = seat, discount = discount, event = event) }
.map { saveTicket(it) }
.let { TicketDto.of(it) }
}
fun buyEvent(model: BuyModel): TicketDto {
val saleForm = getSaleForm()
val sale = Sale(saleForm = saleForm).let { saleRepository.save(it) }
val event = eventService.getEvent(model.eventId)
return model.tickets.map { it.discountId?.let { getDiscountById(it) } to getSeatById(it.seatId) }
.map { (discount, seat) -> Ticket(sale = sale, seat = seat, discount = discount, event = event) }
.map { saveTicket(it) }
.let { TicketDto.of(it) }
}
private fun getSaleForm() = (saleFormRepository.findByName(SALE_FORM_NAME)
?: throw RuntimeException("SaleForm [$SALE_FORM_NAME] not found"))
private fun getDiscountById(id: Long): Discount {
return discountRepository.findOne(id) ?: throw RuntimeException("discount with id: [$id] not found")
}
private fun getSeatById(id: Long): Seat {
return seatRepository.findOne(id) ?: throw RuntimeException("seat with id: [$id] not found")
}
private fun saveTicket(ticket: Ticket): Ticket {
ticketRepository.findBySeatAndEvent(seat = ticket.seat, event = ticket.event)
?.let { ticket.seat.let { arrayOf(it.row.toString(), it.number.toString()) } }
?.let { messageSource.getDefaultMessage("seat", it) }
?.apply {
throw BusinessException(
messageCode = "seat.notFree.error",
params = arrayOf(this),
systemMessage = "Seat with id: ${ticket.seat.id} not free for event id: ${ticket.event.id}"
)
}
return ticketRepository.save(ticket)
}
private fun validatePhoneNumber(phoneNumber: String) {
val instance = PhoneNumberUtil.getInstance()
val wrongPhoneNumber = { throw BusinessException("phoneNumber.error", arrayOf(phoneNumber)) }
try {
instance.parse(phoneNumber, "PL")
.let { instance.isValidNumber(it) }
.apply { if (!this) wrongPhoneNumber.invoke() }
} catch (exc: NumberParseException) {
wrongPhoneNumber.invoke()
}
}
} | src/main/kotlin/com/maly/domain/order/OrderService.kt | 2517981314 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.util
import com.intellij.testFramework.runInEdtAndWait
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
class EdtRule : TestRule {
override fun apply(base: Statement, description: Description?): Statement = object : Statement() {
override fun evaluate() {
runInEdtAndWait {
base.evaluate()
}
}
}
}
| plugins/groovy/test/org/jetbrains/plugins/groovy/util/EdtRule.kt | 1558159360 |
class Outer {
fun f(a: Int) {
}
class F {
fun f(a: Int) {
if (a > 0) {
this.<lineMarker>f</lineMarker>(a - 1)
this@F.<lineMarker>f</lineMarker>(a - 1)
((this@F)).<lineMarker>f</lineMarker>(a - 1)
[email protected](a - 1)
}
}
}
}
| plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/recursiveCall/thisQualifier.kt | 674631627 |
// FIR_COMPARISON
object Obj {
class NestedInObject {
companion object {
val inCompanion = 0
}
}
}
typealias TA = Obj.NestedInObject
val usage = TA.<caret>
// EXIST: inCompanion | plugins/kotlin/completion/tests/testData/basic/common/objects/PropertyFromCompanionObjectFromTypeAliasToNestedInObjectClass.kt | 3502206565 |
// 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.migration
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
import org.jetbrains.kotlin.idea.intentions.declarations.ConvertMemberToExtensionIntention
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.quickfix.CleanupFix
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.js.PredefinedAnnotation
import org.jetbrains.kotlin.js.resolve.diagnostics.ErrorsJs
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class MigrateExternalExtensionFix(declaration: KtNamedDeclaration) : KotlinQuickFixAction<KtNamedDeclaration>(declaration), CleanupFix {
override fun getText() = KotlinBundle.message("fix.with.asdynamic")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val declaration = element ?: return
when {
isMemberExtensionDeclaration(declaration) -> fixExtensionMemberDeclaration(declaration, editor)
isMemberDeclaration(declaration) -> {
val containingClass = declaration.containingClassOrObject
if (containingClass != null) {
fixNativeClass(containingClass)
}
}
declaration is KtClassOrObject -> fixNativeClass(declaration)
}
}
private fun fixNativeClass(containingClass: KtClassOrObject) {
val membersToFix =
containingClass.declarations.asSequence().filterIsInstance<KtCallableDeclaration>()
.filter { isMemberDeclaration(it) && !isMemberExtensionDeclaration(it) }.map {
it to fetchJsNativeAnnotations(it)
}.filter {
it.second.annotations.isNotEmpty()
}.toList()
membersToFix.asReversed().forEach { (memberDeclaration, annotations) ->
if (annotations.nativeAnnotation != null && !annotations.isGetter && !annotations.isSetter && !annotations.isInvoke) {
convertNativeAnnotationToJsName(memberDeclaration, annotations)
annotations.nativeAnnotation.delete()
} else {
val externalDeclaration = ConvertMemberToExtensionIntention.convert(memberDeclaration)
fixExtensionMemberDeclaration(externalDeclaration, null) // editor is null as we are not going to open any live templates
}
}
// make class external
val classAnnotations = fetchJsNativeAnnotations(containingClass)
fixAnnotations(containingClass, classAnnotations, null)
}
private data class JsNativeAnnotations(
val annotations: List<KtAnnotationEntry>,
val nativeAnnotation: KtAnnotationEntry?,
val isGetter: Boolean,
val isSetter: Boolean,
val isInvoke: Boolean
)
private fun fetchJsNativeAnnotations(declaration: KtNamedDeclaration): JsNativeAnnotations {
var isGetter = false
var isSetter = false
var isInvoke = false
var nativeAnnotation: KtAnnotationEntry? = null
val nativeAnnotations = ArrayList<KtAnnotationEntry>()
declaration.modifierList?.annotationEntries?.forEach {
when {
it.isJsAnnotation(PredefinedAnnotation.NATIVE_GETTER) -> {
isGetter = true
nativeAnnotations.add(it)
}
it.isJsAnnotation(PredefinedAnnotation.NATIVE_SETTER) -> {
isSetter = true
nativeAnnotations.add(it)
}
it.isJsAnnotation(PredefinedAnnotation.NATIVE_INVOKE) -> {
isInvoke = true
nativeAnnotations.add(it)
}
it.isJsAnnotation(PredefinedAnnotation.NATIVE) -> {
nativeAnnotations.add(it)
nativeAnnotation = it
}
}
}
return JsNativeAnnotations(nativeAnnotations, nativeAnnotation, isGetter, isSetter, isInvoke)
}
private fun fixExtensionMemberDeclaration(declaration: KtNamedDeclaration, editor: Editor?) {
val name = declaration.nameAsSafeName
val annotations = fetchJsNativeAnnotations(declaration)
fixAnnotations(declaration, annotations, editor)
val ktPsiFactory = KtPsiFactory(declaration)
val body = ktPsiFactory.buildExpression {
appendName(Name.identifier("asDynamic"))
when {
annotations.isGetter -> {
appendFixedText("()")
if (declaration is KtNamedFunction) {
appendParameters(declaration, "[", "]")
}
}
annotations.isSetter -> {
appendFixedText("()")
if (declaration is KtNamedFunction) {
appendParameters(declaration, "[", "]", skipLast = true)
declaration.valueParameters.last().nameAsName?.let {
appendFixedText(" = ")
appendName(it)
}
}
}
annotations.isInvoke -> {
appendFixedText("()")
if (declaration is KtNamedFunction) {
appendParameters(declaration, "(", ")")
}
}
else -> {
appendFixedText("().")
appendName(name)
if (declaration is KtNamedFunction) {
appendParameters(declaration, "(", ")")
}
}
}
}
if (declaration is KtNamedFunction) {
declaration.bodyExpression?.delete()
declaration.equalsToken?.delete()
if (annotations.isSetter || annotations.isInvoke) {
val blockBody = ktPsiFactory.createSingleStatementBlock(body)
declaration.add(blockBody)
} else {
declaration.add(ktPsiFactory.createEQ())
declaration.add(body)
}
} else if (declaration is KtProperty) {
declaration.setter?.delete()
declaration.getter?.delete()
val getter = ktPsiFactory.createPropertyGetter(body)
declaration.add(getter)
if (declaration.isVar) {
val setterBody = ktPsiFactory.buildExpression {
appendName(Name.identifier("asDynamic"))
appendFixedText("().")
appendName(name)
appendFixedText(" = ")
appendName(Name.identifier("value"))
}
val setterStubProperty = ktPsiFactory.createProperty("val x: Unit set(value) { Unit }")
val block = setterStubProperty.setter!!.bodyBlockExpression!!
block.statements.single().replace(setterBody)
declaration.add(setterStubProperty.setter!!)
}
}
}
private fun fixAnnotations(declaration: KtNamedDeclaration, annotations: JsNativeAnnotations, editor: Editor?) {
annotations.annotations.forEach { it.delete() }
if (declaration is KtClassOrObject) {
declaration.addModifier(KtTokens.EXTERNAL_KEYWORD)
} else {
declaration.addModifier(KtTokens.INLINE_KEYWORD)
declaration.removeModifier(KtTokens.EXTERNAL_KEYWORD)
}
if (declaration is KtFunction) {
declaration.addAnnotation(StandardNames.FqNames.suppress, "\"NOTHING_TO_INLINE\"")
}
convertNativeAnnotationToJsName(declaration, annotations)
if (declaration is KtFunction && !declaration.hasDeclaredReturnType() && !annotations.isSetter && !annotations.isInvoke && editor != null) {
SpecifyTypeExplicitlyIntention.addTypeAnnotation(editor, declaration, declaration.builtIns.unitType)
}
}
private fun convertNativeAnnotationToJsName(declaration: KtNamedDeclaration, annotations: JsNativeAnnotations) {
val nativeAnnotation = annotations.nativeAnnotation
if (nativeAnnotation != null && nativeAnnotation.valueArguments.isNotEmpty()) {
declaration.addAnnotation(FqName("JsName"), nativeAnnotation.valueArguments.joinToString { it.asElement().text })
}
}
private fun BuilderByPattern<KtExpression>.appendParameters(
declaration: KtNamedFunction,
lParenth: String,
rParenth: String,
skipLast: Boolean = false
) {
appendFixedText(lParenth)
for ((index, param) in declaration.valueParameters.let { if (skipLast) it.take(it.size - 1) else it }.withIndex()) {
param.nameAsName?.let { paramName ->
if (index > 0) {
appendFixedText(",")
}
appendName(paramName)
}
}
appendFixedText(rParenth)
}
companion object : KotlinSingleIntentionActionFactory() {
private fun KtAnnotationEntry.isJsAnnotation(vararg predefinedAnnotations: PredefinedAnnotation): Boolean {
val bindingContext = analyze(BodyResolveMode.PARTIAL)
val annotationDescriptor = bindingContext[BindingContext.ANNOTATION, this]
return annotationDescriptor != null && predefinedAnnotations.any { annotationDescriptor.fqName == it.fqName }
}
private fun KtAnnotationEntry.isJsNativeAnnotation(): Boolean = isJsAnnotation(
PredefinedAnnotation.NATIVE,
PredefinedAnnotation.NATIVE_GETTER,
PredefinedAnnotation.NATIVE_SETTER,
PredefinedAnnotation.NATIVE_INVOKE
)
private fun isMemberExtensionDeclaration(psiElement: PsiElement): Boolean {
return (psiElement is KtNamedFunction && psiElement.receiverTypeReference != null) ||
(psiElement is KtProperty && psiElement.receiverTypeReference != null)
}
private fun isMemberDeclaration(psiElement: PsiElement): Boolean =
(psiElement is KtNamedFunction && psiElement.receiverTypeReference == null) || (psiElement is KtProperty && psiElement.receiverTypeReference == null)
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val e = diagnostic.psiElement
when (diagnostic.factory) {
ErrorsJs.WRONG_EXTERNAL_DECLARATION -> {
if (isMemberExtensionDeclaration(e) && e.getParentOfType<KtClassOrObject>(true) == null) {
return MigrateExternalExtensionFix(e as KtNamedDeclaration)
}
}
Errors.DEPRECATION_ERROR, Errors.DEPRECATION -> {
if (e.getParentOfType<KtAnnotationEntry>(false)?.isJsNativeAnnotation() == true) {
e.getParentOfType<KtNamedDeclaration>(false)?.let {
return MigrateExternalExtensionFix(it)
}
}
if ((e as? KtNamedDeclaration)?.modifierList?.annotationEntries?.any { it.isJsNativeAnnotation() } == true) {
return MigrateExternalExtensionFix(e)
}
}
}
return null
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateExternalExtensionFix.kt | 1201553902 |
//PARAM_TYPES: C, AImpl, A
//PARAM_DESCRIPTOR: value-parameter c: C defined in foo
interface A {
fun doA()
}
open class AImpl: A {
override fun doA() {
throw UnsupportedOperationException()
}
}
interface B {
fun doB()
}
class C: AImpl(), B {
override fun doA() {
throw UnsupportedOperationException()
}
override fun doB() {
throw UnsupportedOperationException()
}
fun doC() {
throw UnsupportedOperationException()
}
}
// SIBLING:
fun foo(c: C) {
<selection>c.doA()</selection>
c.doB()
c.doC()
} | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/parameters/candidateTypes/typeHierarchy1.kt | 162138798 |
fun main(args : Array<String>) {
for (i in 1..100) {
when {
i%3 == 0 -> {print("Fizz"); continue;}
i%5 == 0 -> {print("Buzz"); continue;}
(i%3 != 0 && i%5 != 0) -> {print(i); continue;}
else -> println()
}
}
}
fun foo() : Unit {
<selection> println() {
println()
pr<caret>intln()
println()
}
</selection>
println(array(1, 2, 3))
println()
} | plugins/kotlin/idea/tests/testData/wordSelection/Statements/8.kt | 2768273215 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class SafeCastWithReturnInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
binaryWithTypeRHSExpressionVisitor(fun(expression) {
if (expression.right == null) return
if (expression.operationReference.getReferencedName() != "as?") return
val parent = expression.getStrictParentOfType<KtBinaryExpression>() ?: return
if (KtPsiUtil.deparenthesize(parent.left) != expression) return
if (parent.operationReference.getReferencedName() != "?:") return
if (KtPsiUtil.deparenthesize(parent.right) !is KtReturnExpression) return
val context = expression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
if (parent.isUsedAsExpression(context)) {
val lambda = expression.getStrictParentOfType<KtLambdaExpression>() ?: return
if (lambda.functionLiteral.bodyExpression?.statements?.lastOrNull() != parent) return
val call = lambda.getStrictParentOfType<KtCallExpression>() ?: return
if (call.isUsedAsExpression(context)) return
}
if (context.diagnostics.forElement(expression.operationReference).any { it.factory == Errors.CAST_NEVER_SUCCEEDS }) return
holder.registerProblem(
parent,
KotlinBundle.message("should.be.replaced.with.if.type.check"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceWithIfFix()
)
})
}
private class ReplaceWithIfFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.if.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val elvisExpression = descriptor.psiElement as? KtBinaryExpression ?: return
val returnExpression = KtPsiUtil.deparenthesize(elvisExpression.right) ?: return
val safeCastExpression = KtPsiUtil.deparenthesize(elvisExpression.left) as? KtBinaryExpressionWithTypeRHS ?: return
val typeReference = safeCastExpression.right ?: return
elvisExpression.replace(
KtPsiFactory(elvisExpression).createExpressionByPattern(
"if ($0 !is $1) $2",
safeCastExpression.left,
typeReference,
returnExpression
)
)
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SafeCastWithReturnInspection.kt | 2787737647 |
package foo
fun test_a(a: A) {
a.commonFun()
a.platformFun()
a.b.commonFunB()
a.b.platformFunB()
a.bFun().commonFunB()
a.bFun().platformFunB()
}
fun test_c(c: Common) {
c.a.commonFun()
c.a.platformFun()
c.aFun().commonFun()
c.aFun().platformFun()
c.a.b.commonFunB()
c.a.b.platformFunB()
c.aFun().b.commonFunB()
c.aFun().b.platformFunB()
c.a.bFun().commonFunB()
c.a.bFun().platformFunB()
c.aFun().bFun().commonFunB()
c.aFun().bFun().platformFunB()
}
| plugins/kotlin/idea/tests/testData/multiplatform/qualifiedReceiver/main/main.kt | 4110105166 |
// "Create extension function 'X.Companion.callSomethingNew'" "true"
class X {
fun callee() {
X.<caret>callSomethingNew(123)
}
fun test(x:Int): Unit { | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/call/brokenPsi.kt | 4143498246 |
package org.jetbrains.kotlin.gradle.frontend
import org.jetbrains.kotlin.gradle.frontend.util.*
import org.junit.Test
import java.io.*
import kotlin.test.*
class OutputStreamBufferTest {
private val actualOutput = ByteArrayOutputStream()
private val buffered = OutputStreamWithBuffer(actualOutput, 10)
@Test
fun testSingleByteWrite() {
buffered.write(1)
buffered.write(2)
buffered.write(3)
assertTrue { byteArrayOf(1, 2, 3).contentEquals(buffered.lines()) }
buffered.write(0x0d)
buffered.write(15)
buffered.write(16)
buffered.write(17)
buffered.write(18)
buffered.write(19)
buffered.write(20)
assertTrue { byteArrayOf(1, 2, 3, 0x0d, 15, 16, 17, 18, 19, 20).contentEquals(buffered.lines()) }
buffered.write(21)
assertTrue { byteArrayOf(15, 16, 17, 18, 19, 20, 21).contentEquals(buffered.lines()) }
assertTrue { byteArrayOf(1, 2, 3, 0x0d, 15, 16, 17, 18, 19, 20, 21).contentEquals(actualOutput.toByteArray()) }
}
@Test
fun testBlockBytesWrite() {
buffered.write(byteArrayOf(1, 2, 3))
assertTrue { byteArrayOf(1, 2, 3).contentEquals(buffered.lines()) }
buffered.write(byteArrayOf(0x0d, 15, 16, 17, 18, 19, 20))
assertTrue { byteArrayOf(1, 2, 3, 0x0d, 15, 16, 17, 18, 19, 20).contentEquals(buffered.lines()) }
buffered.write(byteArrayOf(21))
assertTrue { byteArrayOf(15, 16, 17, 18, 19, 20, 21).contentEquals(buffered.lines()) }
assertTrue { byteArrayOf(1, 2, 3, 0x0d, 15, 16, 17, 18, 19, 20, 21).contentEquals(actualOutput.toByteArray()) }
}
} | kotlin-frontend/src/test/kotlin/org/jetbrains/kotlin/gradle/frontend/OutputStreamBufferTest.kt | 270087360 |
/*
*
* * 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.colormatchtabs.utils
import android.support.annotation.ColorRes
import android.support.annotation.DimenRes
import android.support.v4.content.ContextCompat
import android.view.View
/**
* Created by anna on 15.05.17.
*
*/
fun View.getDimenToFloat(@DimenRes res: Int) = context.resources.getDimensionPixelOffset(res).toFloat()
fun View.getDimen(@DimenRes res: Int) = context.resources.getDimensionPixelOffset(res)
fun View.getColor(@ColorRes res: Int) = ContextCompat.getColor(context, res) | presentation/src/main/java/com/sinyuk/fanfou/ui/colormatchtabs/utils/Extentions.kt | 2148228321 |
package com.cognifide.gradle.aem.common.instance.service.repository
@Suppress("TooManyFunctions")
class QueryCriteria : QueryParams(false) {
// Grouped params (logic statements)
fun or(paramsDefiner: QueryParams.() -> Unit) = group(true, paramsDefiner)
fun and(paramsDefiner: QueryParams.() -> Unit) = group(false, paramsDefiner)
private fun group(or: Boolean, paramsDefiner: QueryParams.() -> Unit) {
val params = QueryParams(true).apply(paramsDefiner).params
val index = groupIndex
this.params["${index}_group.p.or"] = or.toString()
this.params.putAll(params.mapKeys { "${index}_group.${it.key}" })
}
private val groupIndex: Int get() = (params.keys
.filter { it.matches(Regex("^\\d+_group\\..*")) }
.map { it.split("_")[0].toInt() }
.maxOrNull() ?: 0) + 1
// Multi-value shorthands
fun paths(vararg values: String) = paths(values.asIterable())
fun paths(values: Iterable<String>) = or { values.forEach { path(it) } }
fun types(vararg values: String) = types(values.asIterable())
fun types(values: Iterable<String>) = or { values.forEach { type(it) } }
fun names(vararg values: String) = names(values.asIterable())
fun names(values: Iterable<String>) = or { values.forEach { name(it) } }
fun fullTexts(vararg values: String, all: Boolean = false) = fullTexts(values.asIterable(), all)
fun fullTexts(values: Iterable<String>, all: Boolean = false) = group(all) { values.forEach { fullText(it) } }
fun tags(vararg values: String, all: Boolean = true) = tags(values.asIterable(), all)
fun tags(values: Iterable<String>, all: Boolean = true) = group(!all) { values.forEach { tag(it) } }
// Ordering params
fun orderBy(value: String, desc: Boolean = false) {
params["orderby"] = value
if (desc) {
params["orderby.sort"] = "desc"
}
}
fun orderByPath(desc: Boolean = false) = orderBy("path", desc)
fun orderByName(desc: Boolean = false) = orderBy("nodename", desc)
fun orderByProperty(name: String, desc: Boolean = false) = orderBy("@$name", desc)
fun orderByScore(desc: Boolean = true) = orderByProperty("jcr:score", desc)
fun orderByLastModified(desc: Boolean = true) = orderByProperty("cq:lastModified", desc)
fun orderByContentLastModified(desc: Boolean = true) = orderByProperty("jcr:content/cq:lastModified", desc)
// Paginating params
fun offset(value: Int) {
params["p.offset"] = value.toString()
}
val offset: Int get() = params["p.offset"]?.toInt() ?: 0
fun limit(value: Int) {
params["p.limit"] = value.toString()
}
val limit: Int get() = params["p.limit"]?.toInt() ?: 10
// Rest
val queryString get() = (params + FORCED_PARAMS).entries
.joinToString("&") { (k, v) -> "$k=$v" }
fun copy() = QueryCriteria().apply { params.putAll([email protected]) }
fun forMore() = copy().apply {
offset(offset + limit)
}
override fun toString(): String = "QueryCriteria($queryString)"
init {
limit(LIMIT_DEFAULT) // performance improvement (default is 10)
}
companion object {
const val LIMIT_DEFAULT = 100
private val FORCED_PARAMS = mapOf(
"p.guessTotal" to "true",
"p.hits" to "full"
)
}
}
| src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/repository/QueryCriteria.kt | 2683247688 |
package org.livingdoc.reports.confluence.tree
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.livingdoc.config.YamlUtils
internal class ConfluencePageTreeReportConfigTest {
@Test
fun `can parse config`() {
val parsedConfig = YamlUtils.toObject(mapOf(
"rootContentId" to 27,
"baseURL" to "https://internal.example.com/",
"username" to "livingdoc-reports",
"password" to "secure!p4ssw0rd",
"path" to "/confluence",
"comment" to "Jenkins from Staging"
), ConfluencePageTreeReportConfig::class)
assertThat(parsedConfig).isEqualTo(
ConfluencePageTreeReportConfig(
27,
"https://internal.example.com/",
"/confluence",
"livingdoc-reports",
"secure!p4ssw0rd",
"Jenkins from Staging"
)
)
}
}
| livingdoc-reports/src/test/kotlin/org/livingdoc/reports/confluence/tree/ConfluencePageTreeReportConfigTest.kt | 3214459218 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.internal.statistic.customUsageCollectors.ui
import com.intellij.ide.ui.UISettings
import com.intellij.internal.statistic.CollectUsagesException
import com.intellij.internal.statistic.UsagesCollector
import com.intellij.internal.statistic.beans.GroupDescriptor
import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions
/**
* @author Konstantin Bulenkov
*/
class FontSizeInfoUsageCollector : UsagesCollector() {
@Throws(CollectUsagesException::class)
override fun getUsages(): Set<UsageDescriptor> {
val scheme = EditorColorsManager.getInstance().globalScheme
val ui = UISettings.shadowInstance
var usages = setOf(
UsageDescriptor("UI font size: ${ui.fontSize}"),
UsageDescriptor("UI font name: ${ui.fontFace}"),
UsageDescriptor("Presentation mode font size: ${ui.presentationModeFontSize}")
)
if (!scheme.isUseAppFontPreferencesInEditor) {
usages += setOf(
UsageDescriptor("Editor font size: ${scheme.editorFontSize}"),
UsageDescriptor("Editor font name: ${scheme.editorFontName}")
)
}
else {
val appPrefs = AppEditorFontOptions.getInstance().fontPreferences
usages += setOf(
UsageDescriptor("IDE editor font size: ${appPrefs.getSize(appPrefs.fontFamily)}"),
UsageDescriptor("IDE editor font name: ${appPrefs.fontFamily}")
)
}
if (!scheme.isUseEditorFontPreferencesInConsole) {
usages += setOf(
UsageDescriptor("Console font size: ${scheme.consoleFontSize}"),
UsageDescriptor("Console font name: ${scheme.consoleFontName}")
)
}
return usages
}
override fun getGroupId(): GroupDescriptor {
return GroupDescriptor.create("Fonts")
}
}
| platform/platform-impl/src/com/intellij/internal/statistic/customUsageCollectors/ui/FontSizeInfoUsageCollector.kt | 4051104716 |
package org.maxur.mserv.frame.rest
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.capture
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import org.assertj.core.api.Assertions.assertThat
import org.glassfish.hk2.utilities.binding.AbstractBinder
import org.junit.Test
import org.junit.runner.RunWith
import org.maxur.mserv.core.command.CommandHandler
import org.maxur.mserv.frame.command.ServiceCommand
import org.mockito.ArgumentCaptor
import org.mockito.Captor
import org.mockito.junit.MockitoJUnitRunner
import java.io.IOException
import javax.ws.rs.client.Entity
import javax.ws.rs.core.MediaType
import kotlin.reflect.KClass
@RunWith(MockitoJUnitRunner::class)
class RunningCommandResourceIT : AbstractResourceAT() {
private var handler = mock<CommandHandler> {
on { withInjector() } doReturn it
on { withDelay(any()) } doReturn it
}
@Captor
private lateinit var captor: ArgumentCaptor<ServiceCommand>
override fun resourceClass(): KClass<out Any> = RunningCommandResource::class
override fun configurator(): Function1<AbstractBinder, Unit> = { binder: AbstractBinder ->
binder.bind(handler).to(CommandHandler::class.java)
}
@Test
@Throws(IOException::class)
fun testServiceResourceStop() {
val baseTarget = target("/service/command")
val response = baseTarget.request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.json("{ \"type\": \"stop\" }"))
assertThat(response.status).isEqualTo(204)
verify(handler).handle(capture(captor))
assertThat(captor.getValue().type).isEqualTo("stop")
}
@Test
@Throws(IOException::class)
fun testServiceResourceRestart() {
val baseTarget = target("/service/command")
val response = baseTarget.request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.json("{ \"type\": \"restart\" }"))
assertThat(response.status).isEqualTo(204)
verify(handler).handle(capture(captor))
assertThat(captor.getValue().type).isEqualTo("restart")
}
} | maxur-mserv-core/src/test/kotlin/org/maxur/mserv/frame/rest/RunningCommandResourceIT.kt | 1766256387 |
package pt.joaomneto.titancompanion.adventurecreation.impl
import android.view.View
import java.io.BufferedWriter
import java.io.IOException
import java.util.ArrayList
import java.util.HashMap
import pt.joaomneto.titancompanion.R
import pt.joaomneto.titancompanion.adventurecreation.AdventureCreation
import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.VitalStatisticsFragment
import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.tcoc.TCOCAdventureCreationSpellsFragment
import pt.joaomneto.titancompanion.util.AdventureFragmentRunner
import pt.joaomneto.titancompanion.util.DiceRoller
class TCOCAdventureCreation : AdventureCreation(
arrayOf(
AdventureFragmentRunner(
R.string.title_adventure_creation_vitalstats,
VitalStatisticsFragment::class
),
AdventureFragmentRunner(
R.string.spells,
TCOCAdventureCreationSpellsFragment::class
)
)
) {
var spells: MutableMap<String, Int> = HashMap()
private var internalSpellList: MutableList<String> = ArrayList()
var spellList: MutableList<String> = ArrayList()
get() {
spells.keys
.filterNot { this.internalSpellList.contains(it) }
.forEach { this.internalSpellList.add(it) }
this.internalSpellList.sort()
return this.internalSpellList
}
var spellValue = -1
private val tcocSpellsFragment: TCOCAdventureCreationSpellsFragment?
get() = getFragment()
val spellListSize: Int
get() {
var size = 0
spellList
.asSequence()
.map { spells[it] }
.forEach {
size += it ?: 1
}
return size
}
@Throws(IOException::class)
override fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) {
var spellsS = ""
if (spells.isNotEmpty()) {
for (spell in spellList) {
spellsS += spell + "§" + spells[spell] + "#"
}
spellsS = spellsS.substring(0, spellsS.length - 1)
}
bw.write("spellValue=$spellValue\n")
bw.write("spells=$spellsS\n")
bw.write("gold=0\n")
}
override fun validateCreationSpecificParameters(): String? {
val sb = StringBuilder()
var error = false
if (this.spellValue < 0) {
sb.append(getString(R.string.spellCount))
error = true
}
sb.append(if (error) "; " else "")
if (this.spells.isEmpty()) {
sb.append(getString(R.string.chosenSpells))
}
return sb.toString()
}
override fun rollGamebookSpecificStats(view: View) {
spellValue = DiceRoller.roll2D6().sum + 6
tcocSpellsFragment?.spellScoreValue?.text = "" + spellValue
}
fun addSpell(spell: String) {
if (!spells.containsKey(spell)) {
spells[spell] = 0
}
spells[spell] = spells[spell]!! + 1
}
fun removeSpell(position: Int) {
val spell = spellList[position]
val value = spells[spell]!! - 1
if (value == 0) {
spells.remove(spell)
spellList.removeAt(position)
} else {
spells[spell] = value
}
}
}
| src/main/java/pt/joaomneto/titancompanion/adventurecreation/impl/TCOCAdventureCreation.kt | 3452321214 |
package io.kotest.core.internal.tags
import io.kotest.core.Tags
fun Tags.parse(): Expression? {
val expr = this.expression
return if (expr == null) null else Parser.from(expr).expression()
}
class Parser(private val tokens: List<Token>) {
companion object {
fun from(input: String) = Parser(Lexer(input).lex())
}
private var cursor = 0
/**
* Returns true if we have reached the end of the token stream
*/
private fun isEof(): Boolean = cursor == tokens.size
fun skip() {
consume()
}
fun skip(type: TokenType) {
consume(type)
}
/**
* Consumes and returns the next [Token].
*/
fun consume(): Token {
val token = tokens[cursor]
cursor++
return token
}
/**
* Consumes the next token, throwing an error if the token
* is not of the given type.
*/
fun consume(type: TokenType): Token {
val next = consume()
if (next.type != type) {
error("Expected $type but was $next")
}
return next
}
/**
* Returns the next [Token] without consuming it, or null if the next token is eof
*/
fun peek(): Token? = if (isEof()) null else tokens[cursor]
fun skipIf(type: TokenType): Boolean {
return if (peek()?.type == type) {
skip()
true
} else {
false
}
}
}
| kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/internal/tags/Parser.kt | 2260672528 |
package com.piotrwalkusz.lebrb.lanlearn
import java.io.Reader
/*
Basic terms:
- lemma form - the lowercase lemma of word consisting of only letters, a user doesn't see this form,
only this form can be translated (e.g. hund; eat)
- representation form - the form of a foreign language word that user sees (eg. der Hund; essen / aß / gegessen)
- translated form - possible translation of words (e.g. dog; to eat, to dine)
A Translation Dictionary file consists of the header line describing source and destination language:
<source language>;<destination language>
followed by lines in format:
<lemma form>;<representation form>;<translated form>
for example:
german;polish
hund;der Hund;dog
essen;essen / aß / gegessen;to eat, to dine
*/
class TranslationDictionary(val sourceLanguage: Language,
val destinationLanguage: Language,
private val translations: Map<String, Pair<String, String>>) {
companion object {
fun createFromReader(reader: Reader): TranslationDictionary {
val lines = reader.readLines()
if (lines.isEmpty())
throw IllegalArgumentException("Translation Dictionary file is empty")
val headerLine = lines[0].split(';')
if (headerLine.size != 2)
throw IllegalArgumentException("Translation Dictionary has to have the header line in format " +
"'<source language>;<destination language>'")
val languages = headerLine.map { it to Language.valueOfIgnoreCase(it) }
val nonExistingLanguage = languages.find { it.second == null }
if (nonExistingLanguage != null)
throw IllegalArgumentException("Language ${nonExistingLanguage.first} in Translation Dictionary file " +
"does not exist")
val translations = lines.drop(1).map {
val forms = it.split(';')
if (forms.size != 3) {
throw IllegalArgumentException("Lines in Translation Dictionary has to be in format " +
"<lemma form>;<representation form>;<translated form>. Invalid line '$it' was founded.")
}
Pair(forms[0], Pair(forms[1], forms[2]))
}.toMap()
return TranslationDictionary(languages[0].second!!, languages[1].second!!, translations)
}
}
fun getTranslatableWords(): Set<String> {
return translations.keys
}
fun getRepresentation(word: String): String? {
return translations[word]?.first
}
fun translate(word: String): String? {
return translations[word]?.second
}
} | lanlearn/src/main/kotlin/com/piotrwalkusz/lebrb/lanlearn/TranslationDictionary.kt | 838628124 |
package io.sentry.android.core
import android.content.pm.ProviderInfo
import androidx.test.ext.junit.runners.AndroidJUnit4
import java.util.Date
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class SentryPerformanceProviderTest {
@BeforeTest
fun `set up`() {
AppStartState.getInstance().resetInstance()
}
@Test
fun `provider sets app start`() {
val providerInfo = ProviderInfo()
val mockContext = ContextUtilsTest.createMockContext()
providerInfo.authority = AUTHORITY
val providerAppStartMillis = 10L
val providerAppStartTime = Date(0)
SentryPerformanceProvider.setAppStartTime(providerAppStartMillis, providerAppStartTime)
val provider = SentryPerformanceProvider()
provider.attachInfo(mockContext, providerInfo)
// done by ActivityLifecycleIntegration so forcing it here
val lifecycleAppEndMillis = 20L
AppStartState.getInstance().setAppStartEnd(lifecycleAppEndMillis)
assertEquals(10L, AppStartState.getInstance().appStartInterval)
}
companion object {
private const val AUTHORITY = "io.sentry.sample.SentryPerformanceProvider"
}
}
| sentry-android-core/src/test/java/io/sentry/android/core/SentryPerformanceProviderTest.kt | 5944943 |
package com.byoutline.sampleapplication.networkchangereceiver
import android.os.Bundle
import com.byoutline.sampleapplication.ClassNameAsToolbarTitleActivity
import com.byoutline.sampleapplication.R
import com.byoutline.sampleapplication.databinding.NetworkActivityBinding
import com.byoutline.secretsauce.databinding.bindContentView
import com.byoutline.secretsauce.lifecycle.lazyViewModelWithAutoLifecycle
import com.byoutline.secretsauce.utils.NetworkChangeViewModel
/**
* Remember about permission (ACCESS_NETWORK_STATE)
* Disable or enable internet connection to see results
*/
class NetworkChangeActivity : ClassNameAsToolbarTitleActivity() {
private val viewModel by lazyViewModelWithAutoLifecycle(NetworkChangeViewModel::class)
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = bindContentView<NetworkActivityBinding>(R.layout.network_activity)
binding.connected = viewModel.connectedOrConnecting
}
}
| sampleapplication/src/main/java/com/byoutline/sampleapplication/networkchangereceiver/NetworkChangeActivity.kt | 2243790065 |
package com.claraboia.bibleandroid.services
import android.app.IntentService
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.support.v4.content.LocalBroadcastManager
import android.support.v7.app.NotificationCompat
import android.util.Log
import com.claraboia.bibleandroid.R
import com.claraboia.bibleandroid.bibleApplication
import com.claraboia.bibleandroid.helpers.*
import com.claraboia.bibleandroid.models.BibleTranslation
import java.io.BufferedInputStream
import java.io.DataInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLConnection
/**
* Created by lucas.batagliao on 01-Nov-16.
*/
const val EXTRA_TRANSLATION = "com.claraboia.bibleandroid.BibleTranslation.extra"
const val DOWNLOAD_TRANSLATION_PROGRESS_ACTION = "com.claraboia.bibleandroid.DownloadTranslation.ActionProgress"
const val DOWNLOAD_TRANSLATION_PROGRESS_VALUE = "com.claraboia.bibleandroid.DownloadTranslation.ProgressValue"
const val DOWNLOAD_TRANSLATION_NAME_VALUE = "com.claraboia.bibleandroid.DownloadTranslation.NameValue"
class DownloadTranslationService : IntentService("DownloadTranslationService") {
var notificationId = 0
override fun onHandleIntent(intent: Intent?) {
val translation = intent?.getParcelableExtra<BibleTranslation>(EXTRA_TRANSLATION)
val destfilepath = getBibleDir() + "/${translation?.getFileName()}"
translation?.localFile = destfilepath
notify(translation!!)
try {
downloadFile(translation.file, destfilepath, translation)
translation.addToLocalTranslations()
//TODO: increase download count on Firebase
postProgress(100, translation.abbreviation.toString())
}finally {
endNotification()
}
//TODO: notify on status bar when download finishes?
}
private fun downloadFile(source: String, target: String, translation: BibleTranslation?) {
var count = 0
try {
val url = URL(source)
val connection = url.openConnection()
connection.connect()
// this will be useful so that you can show a tipical 0-100%
// progress bar
// ---------
// unfortunatelly we are getting -1 because size is unknow
var lenghtOfFile = connection.contentLength
if(lenghtOfFile <= 0){
lenghtOfFile = tryGetFileSize(url)
}
// download the file
val input = BufferedInputStream(url.openStream(), 8192)
// Output stream
val output = FileOutputStream(target)
val data = ByteArray(1024)
var total: Long = 0
do {
count = input.read(data)
total += count
// publishing the progress....
// After this onProgressUpdate will be called
val progress = (total * 100 / lenghtOfFile).toInt()
postProgress(progress, translation?.abbreviation.toString())
if(count > 0) {
// writing data to file
output.write(data, 0, count)
}
} while (count > 0)
// flushing output
output.flush()
// closing streams
output.close()
input.close()
} finally {
}
}
private fun tryGetFileSize(url: URL): Int {
var conn: HttpURLConnection? = null
try {
conn = url.openConnection() as HttpURLConnection
conn.requestMethod = "HEAD"
conn.inputStream
return conn.contentLength
} catch (e: IOException) {
return -1
} finally {
conn!!.disconnect()
}
}
fun postProgress(progress: Int, target: String) {
val intent = Intent(DOWNLOAD_TRANSLATION_PROGRESS_ACTION)
.putExtra(DOWNLOAD_TRANSLATION_PROGRESS_VALUE, progress)
.putExtra(DOWNLOAD_TRANSLATION_NAME_VALUE, target)
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
}
private fun notify(translation : BibleTranslation){
val text = resources.getText(R.string.notification_downloading).toString() + " ${translation.name}"
val builder = NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_bible_notify)
.setContentTitle(translation.abbreviation)
.setContentText(text)
.setProgress(0, 0, true)
// // Creates an explicit intent for an Activity in your app
// val resultIntent = Intent(this, ResultActivity::class.java)
//
//// The stack builder object will contain an artificial back stack for the
//// started Activity.
//// This ensures that navigating backward from the Activity leads out of
//// your application to the Home screen.
// val stackBuilder = TaskStackBuilder.create(this)
//// Adds the back stack for the Intent (but not the Intent itself)
// stackBuilder.addParentStack(ResultActivity::class.java)
//// Adds the Intent that starts the Activity to the top of the stack
// stackBuilder.addNextIntent(resultIntent)
// val resultPendingIntent = stackBuilder.getPendingIntent(
// 0,
// PendingIntent.FLAG_UPDATE_CURRENT)
// mBuilder.setContentIntent(resultPendingIntent)
notificationId = translation.hashCode()
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(notificationId, builder.build())
}
private fun endNotification(){
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.cancel(notificationId)
}
} | app/src/main/java/com/claraboia/bibleandroid/services/DownloadTranslationService.kt | 396909161 |
/*
* 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
data class Color(val red: Int, val green: Int, val blue: Int, val alpha: Double = 1.0) | src/main/kotlin/com/charlatano/game/Color.kt | 3266914725 |
package com.foo.spring.rest.postgres.json
import com.foo.spring.rest.postgres.SwaggerConfiguration
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import springfox.documentation.swagger2.annotations.EnableSwagger2
import java.sql.Connection
import javax.sql.DataSource
/**
* Created by jgaleotti on 2-Sept-22.
*/
@EnableSwagger2
@SpringBootApplication(exclude = [SecurityAutoConfiguration::class])
@RequestMapping(path = ["/api/json"])
open class JsonColumnApp : SwaggerConfiguration() {
companion object {
@JvmStatic
fun main(args: Array<String>) {
SpringApplication.run(JsonColumnApp::class.java, *args)
}
}
@Autowired
private lateinit var dataSource: DataSource
private lateinit var connection: Connection
@GetMapping(path = ["/fromJson"])
open fun getComplexJSONTypes(): ResponseEntity<Any> {
if (!this::connection.isInitialized) {
connection = dataSource.connection
}
val rs = connection.createStatement().executeQuery("select jsonColumn from JSONSchemaTable where dummyColumn >0")
val status: Int
if (rs.next()) {
val jsonColumn = rs.getObject(1)
status = try {
val fromJsonDto = Gson().fromJson(jsonColumn.toString(), FooDto::class.java)
if (fromJsonDto.x>0) {
200
} else {
400
}
} catch (ex: JsonSyntaxException) {
400
}
} else {
status = 400
}
return ResponseEntity.status(status).build()
}
}
| e2e-tests/spring-rest-postgres/src/main/kotlin/com/foo/spring/rest/postgres/json/JsonColumnApp.kt | 1689157153 |
/*
Copyright 2015 Andreas Würl
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.blitzortung.android.jsonrpc
class JsonRpcException(msg: String) : RuntimeException(msg) {
companion object {
private const val serialVersionUID = -8108432807261988215L
}
}
| app/src/main/java/org/blitzortung/android/jsonrpc/JsonRpcException.kt | 302016390 |
/*
* Copyright (C) 2016/2022 Litote
*
* 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.litote.kmongo
import com.mongodb.client.MongoClient
import com.mongodb.client.model.Filters
import org.junit.Test
import org.litote.kmongo.model.Friend
import org.litote.kmongo.service.MongoClientProvider
import kotlin.test.assertEquals
/**
*
*/
class StandaloneEmbeddedMongoTest {
@Test
fun testStandalone() {
val friend = Friend("bob")
val mongoClient: MongoClient = MongoClientProvider.createMongoClient(
StandaloneEmbeddedMongo(defaultMongoTestVersion).connectionString { _, _, _ -> }
)
val col = mongoClient.getDatabase("test").getCollection("friend", Friend::class.java)
col.insertOne(friend)
assertEquals(friend, col.findOneAndDelete(Filters.eq("_id", friend._id!!)))
}
} | kmongo-flapdoodle/src/test/kotlin/org/litote/kmongo/StandaloneEmbeddedMongoTest.kt | 2864359614 |
package com.androidessence.cashcaretaker.ui.transfer
import android.app.DatePickerDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.DatePicker
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.androidessence.cashcaretaker.R
import com.androidessence.cashcaretaker.core.models.Account
import com.androidessence.cashcaretaker.databinding.DialogAddTransferBinding
import com.androidessence.cashcaretaker.ui.addtransaction.AddTransactionDialog
import com.androidessence.cashcaretaker.ui.views.DatePickerFragment
import com.androidessence.cashcaretaker.ui.views.SpinnerInputEditText
import com.androidessence.cashcaretaker.util.DecimalDigitsInputFilter
import com.androidessence.cashcaretaker.util.asUIString
import java.util.Calendar
import java.util.Date
import kotlinx.android.synthetic.main.dialog_add_transfer.transferAmount
import kotlinx.coroutines.launch
import org.koin.android.viewmodel.ext.android.viewModel
/**
* Dialog that allows a user to transfer money from one account to another.
*/
class AddTransferDialog : DialogFragment(), DatePickerDialog.OnDateSetListener {
private lateinit var binding: DialogAddTransferBinding
private lateinit var fromAccount: SpinnerInputEditText<Account>
private lateinit var toAccount: SpinnerInputEditText<Account>
private val viewModel: AddTransferViewModel by viewModel()
private var selectedDate: Date = Date()
set(value) {
binding.transferDate.setText(value.asUIString())
field = value
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DialogAddTransferBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fromAccount = view.findViewById(R.id.transferFromAccount)
toAccount = view.findViewById(R.id.transferToAccount)
binding.transferAmount.filters = arrayOf(DecimalDigitsInputFilter())
selectedDate = Date()
binding.transferDate.setOnClickListener { showDatePicker() }
binding.submitButton.setOnClickListener {
addTransfer(
fromAccount.selectedItem,
toAccount.selectedItem,
binding.transferAmount.text.toString(),
selectedDate
)
}
subscribeToViewModel()
}
override fun onResume() {
super.onResume()
dialog?.window?.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
}
private fun subscribeToViewModel() {
viewModel.viewState.observe(viewLifecycleOwner, Observer(this::processViewState))
lifecycleScope.launch {
val shouldDismiss = viewModel.dismissEventChannel.receive()
if (shouldDismiss) dismiss()
}
}
private fun processViewState(viewState: AddTransferViewState) {
viewState.accounts?.let { accounts ->
fromAccount.items = accounts
toAccount.items = accounts
}
viewState.fromAccountErrorRes
?.let(::getString)
.let(fromAccount::setError)
viewState.toAccountErrorRes
?.let(::getString)
.let(toAccount::setError)
viewState.amountErrorRes
?.let(::getString)
.let(binding.transferAmount::setError)
}
private fun addTransfer(
fromAccount: Account?,
toAccount: Account?,
amount: String,
date: Date
) {
viewModel.addTransfer(fromAccount, toAccount, amount, date)
}
private fun showDatePicker() {
val datePickerFragment = DatePickerFragment.newInstance(selectedDate)
datePickerFragment.setTargetFragment(this, REQUEST_DATE)
datePickerFragment.show(
childFragmentManager,
AddTransactionDialog::class.java.simpleName
)
}
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
val calendar = Calendar.getInstance()
calendar.set(year, month, dayOfMonth)
selectedDate = calendar.time
}
companion object {
private const val REQUEST_DATE = 0
}
}
| app/src/main/java/com/androidessence/cashcaretaker/ui/transfer/AddTransferDialog.kt | 1944789967 |
package chat.rocket.android.server.domain.model
import se.ansman.kotshi.JsonSerializable
@JsonSerializable
data class BasicAuth(
val host: String,
val credentials: String
)
| app/src/main/java/chat/rocket/android/server/domain/model/BasicAuth.kt | 2996674319 |
package ru.ustimov.weather.content.impl.glide
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import android.support.design.widget.TabLayout
import android.view.View
import com.bumptech.glide.request.target.BaseTarget
import com.bumptech.glide.request.target.SizeReadyCallback
import com.bumptech.glide.request.transition.Transition
class TabIconTarget(
private val tab: TabLayout.Tab,
private val width: Int,
private val height: Int
) : BaseTarget<Drawable>(), Transition.ViewAdapter {
private var animatable: Animatable? = null
override fun getView(): View? = tab.customView
override fun getCurrentDrawable(): Drawable? = tab.icon
override fun setDrawable(drawable: Drawable?) {
tab.icon = drawable
}
override fun getSize(cb: SizeReadyCallback?) {
cb?.onSizeReady(width, height)
}
override fun removeCallback(cb: SizeReadyCallback?) {
}
override fun onLoadStarted(placeholder: Drawable?) {
super.onLoadStarted(placeholder)
setResourceInternal(null)
setDrawable(placeholder)
}
override fun onLoadFailed(errorDrawable: Drawable?) {
super.onLoadFailed(errorDrawable)
setResourceInternal(null)
setDrawable(errorDrawable)
}
override fun onLoadCleared(placeholder: Drawable?) {
super.onLoadCleared(placeholder)
setResourceInternal(null)
setDrawable(placeholder)
}
override fun onResourceReady(resource: Drawable?, transition: Transition<in Drawable>?) {
if (transition == null || !transition.transition(resource, this)) {
setResourceInternal(resource)
} else {
maybeUpdateAnimatable(resource)
}
}
override fun onStart() {
animatable?.start()
}
override fun onStop() {
animatable?.stop()
}
private fun setResourceInternal(resource: Drawable?) {
maybeUpdateAnimatable(resource)
setDrawable(resource)
}
private fun maybeUpdateAnimatable(resource: Drawable?) {
if (resource is Animatable) {
animatable = resource
resource.start()
} else {
animatable = null
}
}
} | app/src/main/java/ru/ustimov/weather/content/impl/glide/TabIconTarget.kt | 2308707673 |
package asmble.util
fun <T : Any> Sequence<T?>.takeUntilNull(): Sequence<T> {
@Suppress("UNCHECKED_CAST") // who cares, it's erased and we know there aren't nulls
return this.takeWhile({ it != null }) as Sequence<T>
}
| compiler/src/main/kotlin/asmble/util/SequenceExt.kt | 3193018408 |
package com.github.davinkevin.podcastserver.extension.java.util
import java.util.*
/**
* Created by kevin on 02/11/2019
*/
fun <T> Optional<T>.orNull(): T? = this.orElse(null)
| backend/src/main/kotlin/com/github/davinkevin/podcastserver/extension/java/util/Optional.kt | 1224782474 |
/*
* Copyright 2019 Andrey Mukamolov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bookcrossing.mobile.models
import com.google.firebase.database.IgnoreExtraProperties
/** Entity to easily distinguish date when book went free in Firebase console */
@IgnoreExtraProperties
data class Date(
var year: Int? = 1970,
var month: Int? = 1,
var day: Int? = 1,
var timestamp: Long? = 0L
) | app/src/main/java/com/bookcrossing/mobile/models/Date.kt | 721519096 |
package com.github.davinkevin.podcastserver.messaging
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.github.davinkevin.podcastserver.entity.Status
import com.github.davinkevin.podcastserver.extension.json.assertThatJson
import com.github.davinkevin.podcastserver.manager.downloader.DownloadingItem
import org.mockito.kotlin.whenever
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.ImportAutoConfiguration
import org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.context.annotation.Import
import org.springframework.http.MediaType
import org.springframework.http.codec.ServerSentEvent
import org.springframework.test.web.reactive.server.WebTestClient
import org.springframework.test.web.reactive.server.returnResult
import reactor.core.publisher.Sinks
import reactor.test.StepVerifier
import java.net.URI
import java.util.*
/**
* Created by kevin on 02/05/2020
*/
@WebFluxTest(controllers = [MessageHandler::class])
@Import(MessagingRoutingConfig::class)
@AutoConfigureWebTestClient(timeout = "PT15S")
@ImportAutoConfiguration(ErrorWebFluxAutoConfiguration::class)
class MessageHandlerTest(
@Autowired val rest: WebTestClient,
@Autowired val mapper: ObjectMapper
) {
@MockBean
private lateinit var messageTemplate: MessagingTemplate
@Nested
@DisplayName("on streaming to client")
inner class OnStreamingToClient {
private val item1 = DownloadingItem(
id = UUID.randomUUID(),
title = "Title 1",
status = Status.NOT_DOWNLOADED,
url = URI("https://foo.bar.com/podcast/title-1"),
numberOfFail = 0,
progression = 0,
podcast = DownloadingItem.Podcast(UUID.randomUUID(), "podcast"),
cover = DownloadingItem.Cover(UUID.randomUUID(), URI("https://foo.bar.com/podcast/title-1.jpg"))
)
private val item2 = DownloadingItem(
id = UUID.randomUUID(),
title = "Title 2",
status = Status.STARTED,
url = URI("https://foo.bar.com/podcast/title-2"),
numberOfFail = 0,
progression = 50,
podcast = DownloadingItem.Podcast(UUID.randomUUID(), "podcast"),
cover = DownloadingItem.Cover(UUID.randomUUID(), URI("https://foo.bar.com/podcast/title-2.jpg"))
)
private val item3 = DownloadingItem(
id = UUID.randomUUID(),
title = "Title 3",
status = Status.STARTED,
url = URI("https://foo.bar.com/podcast/title-3"),
numberOfFail = 3,
progression = 75,
podcast = DownloadingItem.Podcast(UUID.randomUUID(), "podcast"),
cover = DownloadingItem.Cover(UUID.randomUUID(), URI("https://foo.bar.com/podcast/title-3.jpg"))
)
private val item4 = DownloadingItem(
id = UUID.randomUUID(),
title = "Title 4",
status = Status.FINISH,
url = URI("https://foo.bar.com/podcast/title-4"),
numberOfFail = 0,
progression = 100,
podcast = DownloadingItem.Podcast(UUID.randomUUID(), "podcast"),
cover = DownloadingItem.Cover(UUID.randomUUID(), URI("https://foo.bar.com/podcast/title-4.jpg"))
)
@Nested
@DisplayName("on downloading item")
inner class OnDownloadingItem {
@Test
fun `should receive items`() {
/* Given */
val messages = Sinks.many().multicast().directBestEffort<Message<out Any>>()
whenever(messageTemplate.messages).thenReturn(messages)
/* When */
StepVerifier.create(rest
.get()
.uri("/api/v1/sse")
.accept(MediaType.TEXT_EVENT_STREAM)
.exchange()
.expectStatus()
.isOk
.returnResult<ServerSentEvent<String>>()
.responseBody
.filter { it.event() != "heartbeat" }
.map { it.event() to mapper.readValue<DownloadingItemHAL>(it.data()!!) }
.take(2)
)
/* Then */
.expectSubscription()
.then {
messages.tryEmitNext(DownloadingItemMessage(item1))
messages.tryEmitNext(DownloadingItemMessage(item4))
}
.assertNext { (event, body) ->
assertThat(event).isEqualTo("downloading")
assertThat(body.id).isEqualTo(item1.id)
assertThat(body.title).isEqualTo(item1.title)
assertThat(body.status).isEqualTo(item1.status)
assertThat(body.url).isEqualTo(item1.url)
assertThat(body.progression).isEqualTo(item1.progression)
assertThat(body.podcast.id).isEqualTo(item1.podcast.id)
assertThat(body.podcast.title).isEqualTo(item1.podcast.title)
assertThat(body.cover.id).isEqualTo(item1.cover.id)
assertThat(body.cover.url).isEqualTo(item1.cover.url)
assertThat(body.isDownloaded).isEqualTo(false)
}
.assertNext { (event, body) ->
assertThat(event).isEqualTo("downloading")
assertThat(body.id).isEqualTo(item4.id)
assertThat(body.title).isEqualTo(item4.title)
assertThat(body.status).isEqualTo(item4.status)
assertThat(body.url).isEqualTo(item4.url)
assertThat(body.progression).isEqualTo(item4.progression)
assertThat(body.podcast.id).isEqualTo(item4.podcast.id)
assertThat(body.podcast.title).isEqualTo(item4.podcast.title)
assertThat(body.cover.id).isEqualTo(item4.cover.id)
assertThat(body.cover.url).isEqualTo(item4.cover.url)
assertThat(body.isDownloaded).isEqualTo(true)
}
.verifyComplete()
}
}
@Nested
@DisplayName("on update")
inner class OnUpdate {
@Test
fun `should receive updates`() {
/* Given */
val messages = Sinks.many().multicast().directBestEffort<Message<out Any>>()
whenever(messageTemplate.messages).thenReturn(messages)
/* When */
StepVerifier.create(rest
.get()
.uri("/api/v1/sse")
.accept(MediaType.TEXT_EVENT_STREAM)
.exchange()
.expectStatus()
.isOk
.returnResult<ServerSentEvent<String>>()
.responseBody
.filter { it.event() != "heartbeat" }
.take(2)
)
/* Then */
.expectSubscription()
.then {
messages.tryEmitNext(UpdateMessage(true))
messages.tryEmitNext(UpdateMessage(false))
}
.assertNext {
assertThat(it.event()).isEqualTo("updating")
assertThat(it.data()).isEqualTo("true")
}
.assertNext {
assertThat(it.event()).isEqualTo("updating")
assertThat(it.data()).isEqualTo("false")
}
.verifyComplete()
}
}
@Nested
@DisplayName("on waiting list change")
inner class OnWaitingListChange {
@Test
fun `should receive new waiting list`() {
/* Given */
val messages = Sinks.many().multicast().directBestEffort<Message<out Any>>()
whenever(messageTemplate.messages).thenReturn(messages)
/* When */
StepVerifier.create(rest
.get()
.uri("/api/v1/sse")
.accept(MediaType.TEXT_EVENT_STREAM)
.exchange()
.expectStatus()
.isOk
.returnResult<ServerSentEvent<String>>()
.responseBody
.filter { it.event() != "heartbeat" }
.map { it.event() to mapper.readValue<List<DownloadingItemHAL>>(it.data()!!) }
.take(4)
)
/* Then */
.expectSubscription()
.then {
messages.tryEmitNext(WaitingQueueMessage(listOf(item1, item2, item3)))
messages.tryEmitNext(WaitingQueueMessage(listOf(item2, item3)))
messages.tryEmitNext(WaitingQueueMessage(listOf(item3)))
messages.tryEmitNext(WaitingQueueMessage(emptyList()))
}
.assertNext { (event, body) ->
assertThat(event).isEqualTo("waiting")
assertThat(body).hasSize(3)
assertThat(body[0].id).isEqualTo(item1.id)
assertThat(body[1].id).isEqualTo(item2.id)
assertThat(body[2].id).isEqualTo(item3.id)
}
.assertNext { (event, body) ->
assertThat(event).isEqualTo("waiting")
assertThat(body).hasSize(2)
assertThat(body[0].id).isEqualTo(item2.id)
assertThat(body[1].id).isEqualTo(item3.id)
}
.assertNext { (event, body) ->
assertThat(event).isEqualTo("waiting")
assertThat(body).hasSize(1)
assertThat(body[0].id).isEqualTo(item3.id)
}
.assertNext { (event, body) ->
assertThat(event).isEqualTo("waiting")
assertThat(body).hasSize(0)
}
.verifyComplete()
}
}
@Test
fun `should receive heartbeat`() {
/* Given */
whenever(messageTemplate.messages)
.thenReturn(Sinks.many().multicast().directBestEffort())
/* When */
StepVerifier.create(rest
.get()
.uri("/api/v1/sse")
.accept(MediaType.TEXT_EVENT_STREAM)
.exchange()
.expectStatus()
.isOk
.returnResult<ServerSentEvent<Int>>()
.responseBody
.take(2)
)
/* Then */
.expectSubscription()
.assertNext {
assertThat(it.event()).isEqualTo("heartbeat")
}
.assertNext {
assertThat(it.event()).isEqualTo("heartbeat")
}
.verifyComplete()
}
}
}
| backend/src/test/kotlin/com/github/davinkevin/podcastserver/messaging/MessageHandlerTest.kt | 3462971224 |
/*
* Copyright 2017 Alexey Shtanko
*
* 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 io.shtanko.picasagallery.data.mapper
interface SimpleMapper<in F, out T> {
fun transform(from: F?): T
fun transform(fromCollection: Collection<F>): List<T>
} | app/src/main/kotlin/io/shtanko/picasagallery/data/mapper/SimpleMapper.kt | 3881311104 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.app.services
import com.almasb.fxgl.core.EngineService
import com.almasb.fxgl.core.concurrent.Async
import com.almasb.fxgl.core.concurrent.Executor
import com.almasb.fxgl.core.concurrent.IOTask
import com.almasb.fxgl.ui.DialogService
class IOTaskExecutorService : EngineService() {
private lateinit var dialogService: DialogService
private val executor: Executor = Async
fun <T> run(task: IOTask<T>): T {
return task.run()
}
/**
* Executes this task asynchronously on a background thread.
* All callbacks will be called on that background thread.
*/
fun <T> runAsync(task: IOTask<T>) {
executor.execute { task.run() }
}
/**
* Executes this task asynchronously on a background thread.
* All callbacks will be called on the JavaFX thread.
*/
fun <T> runAsyncFX(task: IOTask<T>) {
val fxTask = task.toJavaFXTask()
fxTask.setOnFailed {
if (!task.hasFailAction())
dialogService.showErrorBox(fxTask.exception ?: RuntimeException("Unknown error"))
}
executor.execute(fxTask)
}
/**
* Executes this task asynchronously on a background thread whilst showing a progress dialog.
* The dialog will be dismissed after task is completed, whether succeeded or failed.
* All callbacks will be called on the JavaFX thread.
*/
fun <T> runAsyncFXWithDialog(task: IOTask<T>, message: String) {
val dialog = dialogService.showProgressBox(message)
val fxTask = task.toJavaFXTask()
fxTask.setOnSucceeded {
dialog.close()
}
fxTask.setOnFailed {
dialog.close()
if (!task.hasFailAction())
dialogService.showErrorBox(fxTask.exception ?: RuntimeException("Unknown error"))
}
executor.execute(fxTask)
}
} | fxgl/src/main/kotlin/com/almasb/fxgl/app/services/IOTaskExecutorService.kt | 659196340 |
/*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.dryrun.stub
import com.netflix.spinnaker.orca.pipeline.model.Stage
import org.springframework.stereotype.Component
import java.util.UUID
@Component
class TitusRunJobOutputStub : OutputStub {
override fun supports(stage: Stage) =
stage.type == "runJob" && stage.context["cloudProvider"] == "titus"
override fun outputs(stage: Stage): Map<String, Any> {
val app = stage.execution.application
val account = stage.context["credentials"]
val cluster = stage.context["cluster"] as Map<String, Any>
val region = cluster["region"]
val jobId = UUID.randomUUID().toString()
val taskId = UUID.randomUUID().toString()
val instanceId = UUID.randomUUID().toString()
return mapOf(
"jobStatus" to mapOf(
"id" to jobId,
"name" to "$app-v000",
"type" to "titus",
"createdTime" to 0,
"provider" to "titus",
"account" to account,
"application" to app,
"region" to "$region",
"completionDetails" to mapOf(
"taskId" to taskId,
"instanceId" to instanceId
),
"jobState" to "Succeeded"
),
"completionDetails" to mapOf(
"taskId" to taskId,
"instanceId" to instanceId
)
)
}
}
| orca-dry-run/src/main/kotlin/com/netflix/spinnaker/orca/dryrun/stub/TitusRunJobOutputStub.kt | 718977087 |
package com.arcao.geocaching4locus.authentication.util
import android.content.Context
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import com.arcao.geocaching4locus.base.constants.AppConstants
import com.arcao.geocaching4locus.base.constants.PrefConstants
import com.arcao.geocaching4locus.data.api.model.User
import com.arcao.geocaching4locus.data.api.model.enums.MembershipType
import java.time.Duration
import java.time.Instant
class AccountRestrictions internal constructor(context: Context) {
private val context: Context = context.applicationContext
private val preferences =
this.context.getSharedPreferences(PrefConstants.RESTRICTION_STORAGE_NAME, Context.MODE_PRIVATE)
var maxFullGeocacheLimit: Int = 0
private set
var maxLiteGeocacheLimit: Int = 0
private set
var currentFullGeocacheLimit: Int = 0
private set
var currentLiteGeocacheLimit: Int = 0
private set
var renewFullGeocacheLimit: Instant = Instant.now()
get() {
val now = Instant.now()
if (field.isBefore(now)) {
field = now
}
return field
}
private set
var renewLiteGeocacheLimit: Instant = Instant.now()
get() {
val now = Instant.now()
if (field.isBefore(now)) {
field = now
}
return field
}
private set
init {
init()
}
fun remove() {
preferences.edit {
clear()
putInt(PrefConstants.PREF_VERSION, PrefConstants.CURRENT_PREF_VERSION)
}
init()
}
private fun init() {
val version = preferences.getInt(PrefConstants.PREF_VERSION, 0)
if (version != PrefConstants.CURRENT_PREF_VERSION) {
preferences.edit {
clear()
putInt(PrefConstants.PREF_VERSION, PrefConstants.CURRENT_PREF_VERSION)
}
}
maxFullGeocacheLimit = preferences.getInt(PrefConstants.RESTRICTION__MAX_FULL_GEOCACHE_LIMIT, 0)
currentFullGeocacheLimit = preferences.getInt(PrefConstants.RESTRICTION__CURRENT_FULL_GEOCACHE_LIMIT, 0)
renewFullGeocacheLimit = Instant.ofEpochSecond(preferences.getLong(PrefConstants.RESTRICTION__RENEW_FULL_GEOCACHE_LIMIT, 0))
maxLiteGeocacheLimit = preferences.getInt(PrefConstants.RESTRICTION__MAX_LITE_GEOCACHE_LIMIT, 0)
currentLiteGeocacheLimit = preferences.getInt(PrefConstants.RESTRICTION__CURRENT_LITE_GEOCACHE_LIMIT, 0)
renewLiteGeocacheLimit = Instant.ofEpochSecond(preferences.getLong(PrefConstants.RESTRICTION__RENEW_LITE_GEOCACHE_LIMIT, 0))
}
internal fun applyRestrictions(user: User) {
if (user.isPremium()) {
presetPremiumMembershipConfiguration()
} else {
presetBasicMembershipConfiguration()
}
}
private fun presetBasicMembershipConfiguration() {
PreferenceManager.getDefaultSharedPreferences(context).edit {
// DOWNLOADING
putBoolean(PrefConstants.DOWNLOADING_SIMPLE_CACHE_DATA, true)
putString(
PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW,
PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW__UPDATE_NEVER
)
putInt(PrefConstants.DOWNLOADING_COUNT_OF_LOGS, 0)
// LIVE MAP
putBoolean(PrefConstants.LIVE_MAP_DOWNLOAD_HINTS, false)
// FILTERS
putString(PrefConstants.FILTER_DIFFICULTY_MIN, "1")
putString(PrefConstants.FILTER_DIFFICULTY_MAX, "5")
putString(PrefConstants.FILTER_TERRAIN_MIN, "1")
putString(PrefConstants.FILTER_TERRAIN_MAX, "5")
// multi-select filters (select all)
for (i in AppConstants.GEOCACHE_TYPES.indices)
putBoolean(PrefConstants.FILTER_CACHE_TYPE_PREFIX + i, true)
for (i in AppConstants.GEOCACHE_SIZES.indices)
putBoolean(PrefConstants.FILTER_CONTAINER_TYPE_PREFIX + i, true)
}
}
private fun presetPremiumMembershipConfiguration() {
val defaultPreferences = PreferenceManager.getDefaultSharedPreferences(context)
defaultPreferences.edit {
// DOWNLOADING
putBoolean(PrefConstants.DOWNLOADING_SIMPLE_CACHE_DATA, false)
putString(
PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW,
PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW__UPDATE_ONCE
)
putInt(PrefConstants.DOWNLOADING_COUNT_OF_LOGS, 5)
}
}
fun updateLimits(user: User) {
maxFullGeocacheLimit = if (user.isPremium()) {
FULL_GEOCACHE_LIMIT_PREMIUM
} else {
FULL_GEOCACHE_LIMIT_BASIC
}
maxLiteGeocacheLimit = if (user.isPremium()) {
LITE_GEOCACHE_LIMIT_PREMIUM
} else {
LITE_GEOCACHE_LIMIT_BASIC
}
val limits = user.geocacheLimits ?: return
preferences.edit {
currentFullGeocacheLimit = limits.fullCallsRemaining
renewFullGeocacheLimit = Instant.now().plus(limits.fullCallsSecondsToLive ?: DEFAULT_RENEW_DURATION)
currentLiteGeocacheLimit = limits.liteCallsRemaining
renewLiteGeocacheLimit = Instant.now().plus(limits.liteCallsSecondsToLive ?: DEFAULT_RENEW_DURATION)
// store it to preferences
putInt(PrefConstants.RESTRICTION__MAX_FULL_GEOCACHE_LIMIT, maxFullGeocacheLimit)
putInt(PrefConstants.RESTRICTION__CURRENT_FULL_GEOCACHE_LIMIT, currentFullGeocacheLimit)
putLong(PrefConstants.RESTRICTION__RENEW_FULL_GEOCACHE_LIMIT, renewFullGeocacheLimit.epochSecond)
putInt(PrefConstants.RESTRICTION__MAX_LITE_GEOCACHE_LIMIT, maxLiteGeocacheLimit)
putInt(PrefConstants.RESTRICTION__CURRENT_LITE_GEOCACHE_LIMIT, currentLiteGeocacheLimit)
putLong(PrefConstants.RESTRICTION__RENEW_LITE_GEOCACHE_LIMIT, renewLiteGeocacheLimit.epochSecond)
}
}
companion object {
private const val FULL_GEOCACHE_LIMIT_PREMIUM = 16000
private const val FULL_GEOCACHE_LIMIT_BASIC = 3
private const val LITE_GEOCACHE_LIMIT_PREMIUM = 10000
private const val LITE_GEOCACHE_LIMIT_BASIC = 10000
val DEFAULT_RENEW_DURATION: Duration = Duration.ofDays(1)
}
private fun User.isPremium() = when (membership) {
MembershipType.UNKNOWN -> false
MembershipType.BASIC -> false
MembershipType.CHARTER -> true
MembershipType.PREMIUM -> true
}
}
| app/src/main/java/com/arcao/geocaching4locus/authentication/util/AccountRestrictions.kt | 3790294580 |
/*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.players.bukkit.event.minecraftprofile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile
interface RPKMinecraftProfileUpdateEvent : RPKMinecraftProfileEvent {
override val minecraftProfile: RPKMinecraftProfile
} | bukkit/rpk-player-lib-bukkit/src/main/kotlin/com/rpkit/players/bukkit/event/minecraftprofile/RPKMinecraftProfileUpdateEvent.kt | 750288188 |
package com.todoist.pojo
open class LiveNotification<C : Collaborator>(
id: Long,
var notificationType: String,
open var created: Long,
open var isUnread: Boolean,
// Optional fields, not set in all types.
open var fromUid: Long?,
open var projectId: Long?,
open var projectName: String?,
open var invitationId: Long?,
open var invitationSecret: String?,
open var state: String?,
open var itemId: Long?,
open var itemContent: String?,
open var responsibleUid: Long?,
open var noteId: Long?,
open var noteContent: String?,
open var removedUid: Long?,
open var fromUser: C?,
open var accountName: String?,
// Optional fields used in Karma notifications (which are set depends on the karma level).
open var karmaLevel: Int?,
open var completedTasks: Int?,
open var completedInDays: Int?,
open var completedLastMonth: Int?,
open var topProcent: Double?,
open var dateReached: Long?,
open var promoImg: String?,
isDeleted: Boolean
) : Model(id, isDeleted) {
open val isInvitation
get() = notificationType == TYPE_SHARE_INVITATION_SENT ||
notificationType == TYPE_BIZ_INVITATION_CREATED
open val isStatePending get() = state != STATE_ACCEPTED && state != STATE_REJECTED
companion object {
const val TYPE_SHARE_INVITATION_SENT = "share_invitation_sent"
const val TYPE_SHARE_INVITATION_ACCEPTED = "share_invitation_accepted"
const val TYPE_SHARE_INVITATION_REJECTED = "share_invitation_rejected"
const val TYPE_USER_LEFT_PROJECT = "user_left_project"
const val TYPE_USER_REMOVED_FROM_PROJECT = "user_removed_from_project"
const val TYPE_NOTE_ADDED = "note_added"
const val TYPE_ITEM_ASSIGNED = "item_assigned"
const val TYPE_ITEM_COMPLETED = "item_completed"
const val TYPE_ITEM_UNCOMPLETED = "item_uncompleted"
const val TYPE_KARMA_LEVEL = "karma_level"
const val TYPE_BIZ_POLICY_DISALLOWED_INVITATION = "biz_policy_disallowed_invitation"
const val TYPE_BIZ_POLICY_REJECTED_INVITATION = "biz_policy_rejected_invitation"
const val TYPE_BIZ_TRIAL_WILL_END = "biz_trial_will_end"
const val TYPE_BIZ_PAYMENT_FAILED = "biz_payment_failed"
const val TYPE_BIZ_ACCOUNT_DISABLED = "biz_account_disabled"
const val TYPE_BIZ_INVITATION_CREATED = "biz_invitation_created"
const val TYPE_BIZ_INVITATION_ACCEPTED = "biz_invitation_accepted"
const val TYPE_BIZ_INVITATION_REJECTED = "biz_invitation_rejected"
const val STATE_INVITED = "invited"
const val STATE_ACCEPTED = "accepted"
const val STATE_REJECTED = "rejected"
}
}
| src/main/java/com/todoist/pojo/LiveNotification.kt | 288403375 |
@file:Suppress("UsePropertyAccessSyntax")
package lunchbox.feed /* ktlint-disable max-line-length */
import com.ninjasquad.springmockk.MockkBean
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.verify
import lunchbox.domain.models.LunchLocation.NEUBRANDENBURG
import lunchbox.domain.models.LunchProvider.AOK_CAFETERIA
import lunchbox.domain.models.LunchProvider.SALT_N_PEPPER
import lunchbox.domain.models.LunchProvider.SUPPENKULTTOUR
import lunchbox.domain.models.createOffer
import lunchbox.repository.LunchOfferRepository
import org.assertj.core.api.Assertions.assertThat
import org.joda.money.CurrencyUnit
import org.joda.money.Money
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
import java.time.LocalDate
@WebMvcTest(FeedController::class)
class FeedControllerTest(
@Autowired val mockMvc: MockMvc,
@Autowired val testUnit: FeedController
) {
@MockkBean
lateinit var repo: LunchOfferRepository
@BeforeEach
fun before() {
clearAllMocks()
}
@Nested
inner class HttpCall {
@Test
fun success() {
every { repo.findAll() } returns listOf(offerYesterday, offerToday)
mockMvc.get("$URL_FEED?location=${NEUBRANDENBURG.label}")
.andExpect {
status { isOk() }
content { contentTypeCompatibleWith(MediaType.APPLICATION_ATOM_XML) }
xpath("/feed") { exists() }
xpath("/feed/entry") { nodeCount(2) }
xpath("/feed/link/@href") { string("http://localhost$URL_FEED?location=${NEUBRANDENBURG.label}") }
}
verify(exactly = 1) { repo.findAll() }
}
@Test
fun `WHEN param location is missing THEN return 400`() {
every { repo.findAll() } returns listOf(offerYesterday, offerToday)
mockMvc.get(URL_FEED)
.andExpect {
status { isBadRequest() }
}
}
}
@Nested
inner class CreateFeed {
@Test
fun success() {
every { repo.findAll() } returns listOf(offerToday)
val result = testUnit.createFeed(NEUBRANDENBURG, "http://example.com/feed")
assertThat(result.id).isNotEmpty()
assertThat(result.title).isEqualTo("Mittagstisch Neubrandenburg")
assertThat(result.alternateLinks).hasSize(1)
assertThat(result.alternateLinks[0].rel).isEqualTo("self")
assertThat(result.alternateLinks[0].href).isEqualTo("http://example.com/feed")
assertThat(result.authors).hasSize(1)
assertThat(result.authors[0].name).isEqualTo("Lunchbox")
assertThat(result.updated).isNotNull()
assertThat(result.entries).hasSize(1)
assertThat(result.entries[0].id).isEqualTo("urn:date:${offerToday.day}")
assertThat(result.entries[0].title).isNotEmpty()
assertThat(result.entries[0].authors).hasSize(1)
assertThat(result.entries[0].updated).isNotNull()
assertThat(result.entries[0].published).isNotNull()
assertThat(result.entries[0].contents).hasSize(1)
assertThat(result.entries[0].contents[0].value).contains(AOK_CAFETERIA.label)
assertThat(result.entries[0].contents[0].value).contains(offerToday.name)
assertThat(result.entries[0].contents[0].value).contains("2,50 €")
verify(exactly = 1) { repo.findAll() }
}
@Test
fun `create feed entry per day sorted descending`() {
every { repo.findAll() } returns listOf(offerYesterday, offerToday)
val result = testUnit.createFeed(NEUBRANDENBURG, "http://link")
assertThat(result.entries).hasSize(2)
assertThat(result.entries[0].id).isEqualTo("urn:date:${offerToday.day}")
assertThat(result.entries[1].id).isEqualTo("urn:date:${offerYesterday.day}")
verify(exactly = 1) { repo.findAll() }
}
@Test
fun `WHEN no offers THEN feed is empty`() {
every { repo.findAll() } returns emptyList()
val result = testUnit.createFeed(NEUBRANDENBURG, "http://link")
assertThat(result.entries).isEmpty()
verify(exactly = 1) { repo.findAll() }
}
@Test
fun `WHEN all offers are after today THEN feed is empty`() {
every { repo.findAll() } returns listOf(offerTomorrow)
val result = testUnit.createFeed(NEUBRANDENBURG, "http://link")
assertThat(result.entries).isEmpty()
verify(exactly = 1) { repo.findAll() }
}
@Test
fun `WHEN all offers in other location THEN feed is empty`() {
every { repo.findAll() } returns listOf(offerBerlin)
val result = testUnit.createFeed(NEUBRANDENBURG, "http://link")
assertThat(result.entries).isEmpty()
verify(exactly = 1) { repo.findAll() }
}
}
// --- mocks 'n' stuff
private val today = LocalDate.now()
private val tomorrow = today.plusDays(1)
private val yesterday = today.minusDays(1)
private val offerYesterday = createOffer(
provider = SUPPENKULTTOUR.id,
day = yesterday
)
private val offerToday = createOffer(
provider = AOK_CAFETERIA.id,
day = today,
price = Money.ofMinor(CurrencyUnit.EUR, 250)
)
private val offerTomorrow = createOffer(
provider = AOK_CAFETERIA.id,
day = tomorrow
)
private val offerBerlin = createOffer(
provider = SALT_N_PEPPER.id,
day = today
)
}
| backend-spring-kotlin/src/test/kotlin/lunchbox/feed/FeedControllerTest.kt | 3525310286 |
// DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2016 Konrad Jamrozik
//
// 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/>.
//
// email: [email protected]
// web: www.droidmate.org
package org.droidmate.report
import com.google.common.collect.Table
import org.droidmate.exploration.data_aggregators.IApkExplorationOutput2
class AggregateStatsTable private constructor(val table: Table<Int, String, String>) : Table<Int, String, String> by table {
constructor(data: List<IApkExplorationOutput2>) : this(AggregateStatsTable.build(data))
companion object {
val headerApkName = "file_name"
val headerPackageName = "package_name"
val headerExplorationTimeInSeconds = "exploration_seconds"
val headerActionsCount = "actions"
val headerResetActionsCount = "in_this_reset_actions"
val headerViewsSeenCount = "actionable_unique_views_seen_at_least_once"
val headerViewsClickedCount = "actionable_unique_views_clicked_or_long_clicked_at_least_once"
val headerApisSeenCount = "unique_apis"
val headerEventApiPairsSeenCount = "unique_event_api_pairs"
val headerException = "exception"
fun build(data: List<IApkExplorationOutput2>): Table<Int, String, String> {
return buildTable(
headers = listOf(
headerApkName,
headerPackageName,
headerExplorationTimeInSeconds,
headerActionsCount,
headerResetActionsCount,
headerViewsSeenCount,
headerViewsClickedCount,
headerApisSeenCount,
headerEventApiPairsSeenCount,
headerException
),
rowCount = data.size,
computeRow = { rowIndex ->
val apkData = data[rowIndex]
listOf(
apkData.apk.fileName,
apkData.packageName,
apkData.explorationDuration.seconds.toString(),
apkData.actions.size.toString(),
apkData.resetActionsCount.toString(),
apkData.uniqueActionableWidgets.size.toString(),
apkData.uniqueClickedWidgets.size.toString(),
apkData.uniqueApis.size.toString(),
apkData.uniqueEventApiPairs.size.toString(),
apkData.exception.toString()
)
}
)
}
}
} | dev/droidmate/projects/reporter/src/main/kotlin/org/droidmate/report/AggregateStatsTable.kt | 3336035902 |
package net.perfectdreams.loritta.cinnamon.pudding.entities
import net.perfectdreams.loritta.cinnamon.pudding.Pudding
import net.perfectdreams.loritta.cinnamon.pudding.data.ShipEffect
data class PuddingShipEffect(
private val pudding: Pudding,
val data: ShipEffect
) {
companion object;
val id by data::id
val buyerId by data::buyerId
val user1 by data::user1
val user2 by data::user2
val editedShipValue by data::editedShipValue
val expiresAt by data::expiresAt
} | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/entities/PuddingShipEffect.kt | 360643225 |
package com.kiwi.rnkiwimobile.hotels
import com.kiwi.rnkiwimobile.RNKiwiActivity
abstract class RNHotelsActivity(initialProperties: RNHotelsInitialProperties) : RNKiwiActivity(RNHotelsModule.getInitialProperties(initialProperties)) {
override fun getModuleName(): String {
return RNHotelsModule.moduleName
}
} | android/rnkiwimobile/src/main/java/com/kiwi/rnkiwimobile/hotels/RNHotelsActivity.kt | 2302346228 |
package swtlin
import org.eclipse.swt.SWT
import org.eclipse.swt.layout.FillLayout
import org.eclipse.swt.layout.FormData
import org.eclipse.swt.layout.FormLayout
import org.eclipse.swt.widgets.Composite
import org.eclipse.swt.widgets.Control
import org.eclipse.swt.widgets.Label
import org.eclipse.swt.widgets.Shell
import org.junit.After
import org.junit.Before
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class CompositeTest {
var shell: Shell? = null
@Before
fun createShell() {
shell = Shell()
}
@After
fun disposeShell() {
if (shell != null && !shell!!.isDisposed) {
shell?.dispose()
}
}
@Test
fun `Create empty Composite`() {
val result = composite().createControl(shell!!)
assertNotNull(result)
assertEquals(0, result.children.size)
}
@Test
fun `Create Composite with a Label`() {
val result = composite {
label {
text = "Hello World!"
}
}.createControl(shell!!)
assertEquals(1, result.children.size.toLong())
assertTrue(result.children[0] is Label)
assertEquals("Hello World!", (result.children[0] as Label).text)
}
@Test
fun `Create Composite with style`() {
val result = composite {
style = SWT.NO_FOCUS
}.createControl(shell!!)
assertTrue(result.style and SWT.NO_FOCUS == SWT.NO_FOCUS)
}
@Test
fun `Create Label with id`() {
val refs = mutableMapOf<String, Control>()
composite {
label("id") {
text = "Hello"
}
}.createControl(shell!!, refs)
assertTrue(refs["id"] is Label)
assertEquals((refs["id"] as Label).text, "Hello")
}
@Test
fun `Uses FormLayout by default`() {
val result = composite().createControl(shell!!)
assertTrue(result.layout is FormLayout)
}
@Test
fun `Apply layout to children`() {
val refs = mutableMapOf<String, Control>()
composite {
label("test") {
left = 5
top = 5
}
}.createControl(shell!!, refs)
val testLabel = refs["test"] as Label
assertTrue(testLabel.layoutData is FormData)
val formData = testLabel.layoutData as FormData
assertEquals(5, formData.left.offset)
assertEquals(5, formData.top.offset)
}
@Test
fun `Nested composite`() {
val refs = mutableMapOf<String, Control>()
composite {
label("test1") { text = "first" }
composite {
label("test2") { text = "second" }
}
}.createControl(shell!!, refs)
assertTrue(refs["test1"] is Label)
assertEquals("first", (refs["test1"] as Label).text)
assertTrue(refs["test2"] is Label)
assertEquals("second", (refs["test2"] as Label).text)
}
@Test
fun `Nested composite with id`() {
val refs = mutableMapOf<String, Control>()
composite {
label("test1") { text = "first" }
composite("comp") {
label("test2") { text = "second" }
}
}.createControl(shell!!, refs)
assertTrue(refs["test1"] is Label)
assertEquals("first", (refs["test1"] as Label).text)
assertTrue(refs["test2"] is Label)
assertEquals("second", (refs["test2"] as Label).text)
assertTrue(refs["comp"] is Composite)
assertEquals((refs["test2"] as Control).parent, refs["comp"])
}
@Test
fun `setUp block is executed after creation`() {
var ref: Composite? = null
val result = composite().also {
it.setUp { c -> ref = c }
}.createControl(shell!!)
assertEquals(result, ref)
}
@Test
fun `Use fillLayout`() {
val result = composite {
layout = fillLayout()
}.createControl(shell!!)
assertTrue(result.layout is FillLayout)
}
//
// @Test
// fun `Dispose disposable resources on dispose`() {
// val result = composite {
// background = rgba(128, 128, 128, 1)
// }.createControl(shell!!)
//
// val createdColor = result.background
// shell?.dispose()
// assertTrue(createdColor.isDisposed)
// }
}
| builder/src/test/kotlin/swtlin/CompositeTest.kt | 3265952719 |
package com.udit.shangri_la.data.repository.movies.models
/**
* Created by Udit on 31/10/17.
*/
data class MovieApiModel(val id:Int,
val original_title: String,
val release_date: String,
val runtime: Int,
val overview: String)
data class GetMovieResponseModel(val page: Int,
val total_results: Int,
val total_pages: Int,
val results: List<MovieApiModel>) | data/src/main/java/com/udit/shangri_la/data/repository/movies/models/MovieApiModel.kt | 597938442 |
package net.perfectdreams.loritta.cinnamon.discord.voice
import dev.kord.common.annotation.KordVoice
import dev.kord.voice.AudioFrame
import dev.kord.voice.AudioProvider
import kotlinx.coroutines.channels.Channel
@OptIn(KordVoice::class)
class LorittaAudioProvider(private val audioClipProviderNotificationChannel: Channel<Unit>) : AudioProvider {
companion object {
val SILENCE = AudioFrame(byteArrayOf()) // While Kord does have a "SILENCE", it shows the "Speaking" indicator
}
var audioFramesInOpusFormatQueue = Channel<ByteArray>(Channel.UNLIMITED)
var requestedNewAudioTracks = false
override suspend fun provide(): AudioFrame {
val audioDataInOpusFormatTryReceive = audioFramesInOpusFormatQueue.tryReceive()
if (audioDataInOpusFormatTryReceive.isFailure) {
if (requestedNewAudioTracks) // We already tried requesting it, so now we will wait...
return SILENCE
// isFailure == empty, then we need to request moar framez!! :3
audioClipProviderNotificationChannel.send(Unit) // Send a moar framez!! request...
requestedNewAudioTracks = true
// And then return SILENCE for now
return SILENCE
}
// If it is closed... then why are we here?
if (audioDataInOpusFormatTryReceive.isClosed)
return SILENCE
requestedNewAudioTracks = false
return AudioFrame(audioDataInOpusFormatTryReceive.getOrNull()!!)
}
/**
* Appends the [audioFramesInOpusFormat] in the current audio provider to the end of the [audioFramesInOpusFormat] queue
*
* @param audioFramesInOpusFormat the Opus audio frames
*/
suspend fun queue(audioFramesInOpusFormat: List<ByteArray>) {
for (frame in audioFramesInOpusFormat) {
this.audioFramesInOpusFormatQueue.send(frame)
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/voice/LorittaAudioProvider.kt | 713809208 |
package net.perfectdreams.loritta.morenitta.commands.vanilla.utils
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.common.locale.LocaleStringData
import net.perfectdreams.loritta.morenitta.utils.stripCodeMarks
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import org.apache.commons.codec.digest.DigestUtils
import java.util.*
import net.perfectdreams.loritta.morenitta.LorittaBot
class EncodeCommand(loritta: LorittaBot) : AbstractCommand(loritta, "encode", listOf("codificar", "encrypt", "criptografar", "hash"), net.perfectdreams.loritta.common.commands.CommandCategory.UTILS) {
override fun getDescriptionKey() = LocaleKeyData(
"commands.command.encode.description",
listOf(
LocaleStringData(
listOf("md2", "md5", "sha1", "sha256", "sha384", "sha512", "rot13", "uuid", "base64").joinToString(", ", transform = { "`$it`" })
)
)
)
override fun getExamplesKey() = LocaleKeyData("commands.command.encode.examples")
// TODO: Fix Detailed Usage
override fun getUsage() = arguments {
argument(ArgumentType.TEXT) {}
argument(ArgumentType.TEXT) {}
}
override suspend fun run(context: CommandContext, locale: BaseLocale) {
val args = context.rawArgs.toMutableList()
val encodeMode = context.rawArgs.getOrNull(0)?.toLowerCase()
if (encodeMode == null) {
context.explain()
return
}
args.removeAt(0)
val text = args.joinToString(" ")
if (text.isEmpty()) {
context.explain()
return
}
val encodedText = when (encodeMode) {
"md2" -> DigestUtils.md2Hex(text)
"md5" -> DigestUtils.md5Hex(text)
"sha1" -> DigestUtils.sha1Hex(text)
"sha256" -> DigestUtils.sha256Hex(text)
"sha384" -> DigestUtils.sha384Hex(text)
"sha512" -> DigestUtils.sha512Hex(text)
"rot13" -> rot13(text)
"uuid" -> UUID.nameUUIDFromBytes(text.toByteArray(Charsets.UTF_8)).toString()
"base64" -> {
val b64 = Base64.getEncoder().encode(text.toByteArray(Charsets.UTF_8))
String(b64)
}
else -> null
}
if (encodedText == null) {
context.reply(
locale["commands.command.encode.invalidMethod", encodeMode.stripCodeMarks()],
Constants.ERROR
)
return
}
context.reply(
true,
LorittaReply(
"**${locale["commands.command.encode.originalText"]}:** `${text.stripCodeMarks()}`",
"\uD83D\uDCC4",
mentionUser = false
),
LorittaReply(
"**${locale["commands.command.encode.encodedText"]}:** `${encodedText.stripCodeMarks()}`",
"<:blobspy:465979979876794368>",
mentionUser = false
)
)
}
fun rot13(input: String): String {
val sb = StringBuilder()
for (i in 0 until input.length) {
var c = input[i]
if (c in 'a'..'m')
c += 13
else if (c in 'A'..'M')
c += 13
else if (c in 'n'..'z')
c -= 13
else if (c in 'N'..'Z') c -= 13
sb.append(c)
}
return sb.toString()
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/utils/EncodeCommand.kt | 2692669841 |
/*
* Copyright @ 2018 Atlassian Pty Ltd
*
* 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.jitsi.jibri.util
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.shouldBe
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PipedInputStream
import java.io.PipedOutputStream
import kotlin.time.ExperimentalTime
import kotlin.time.Duration.Companion.seconds
internal class TeeLogicTest : ShouldSpec() {
override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf
private val outputStream = PipedOutputStream()
private val inputStream = PipedInputStream(outputStream)
private val tee = TeeLogic(inputStream)
private fun pushIncomingData(data: Byte) {
outputStream.write(data.toInt())
tee.read()
}
private fun pushIncomingData(data: String) {
data.toByteArray().forEach {
pushIncomingData(it)
}
}
init {
context("data written") {
context("after the creation of a branch") {
should("be received by that branch") {
val branch = tee.addBranch()
pushIncomingData("hello, world\n")
val reader = BufferedReader(InputStreamReader(branch))
reader.readLine() shouldBe "hello, world"
}
}
context("before the creation of a branch") {
should("not be received by that branch") {
pushIncomingData("hello, world\n")
val branch = tee.addBranch()
pushIncomingData("goodbye, world\n")
val reader = BufferedReader(InputStreamReader(branch))
reader.readLine() shouldBe "goodbye, world"
}
}
}
context("end of stream") {
should("throw EndOfStreamException") {
outputStream.close()
shouldThrow<EndOfStreamException> {
tee.read()
}
}
should("close all branches") {
val branch1 = tee.addBranch()
val branch2 = tee.addBranch()
outputStream.close()
shouldThrow<EndOfStreamException> {
tee.read()
}
val reader1 = BufferedReader(InputStreamReader(branch1))
reader1.readLine() shouldBe null
val reader2 = BufferedReader(InputStreamReader(branch2))
reader2.readLine() shouldBe null
}
}
}
}
@ExperimentalTime
internal class TeeTest : ShouldSpec() {
override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf
private val outputStream = PipedOutputStream()
private val inputStream = PipedInputStream(outputStream)
private val tee = Tee(inputStream)
init {
val branch = tee.addBranch()
context("stop") {
should("close downstream readers").config(timeout = 5.seconds) {
tee.stop()
// This is testing that it returns the proper value (to signal
// the stream was closed). But the timeout in the config tests
// is also critical because if the stream wasn't closed, then
// the read call will block indefinitely
branch.read() shouldBe -1
}
}
}
}
| src/test/kotlin/org/jitsi/jibri/util/TeeLogicTest.kt | 680505303 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.hints
import com.intellij.codeInsight.hints.HintInfo.MethodInfo
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiCallExpression
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
class JavaInlayParameterHintsProvider : InlayParameterHintsProvider {
companion object {
fun getInstance() = InlayParameterHintsExtension.forLanguage(JavaLanguage.INSTANCE) as JavaInlayParameterHintsProvider
}
override fun getHintInfo(element: PsiElement): MethodInfo? {
if (element is PsiCallExpression) {
val resolvedElement = element.resolveMethodGenerics().element
if (resolvedElement is PsiMethod) {
return getMethodInfo(resolvedElement)
}
}
return null
}
override fun getParameterHints(element: PsiElement): List<InlayInfo> {
if (element is PsiCallExpression) {
return JavaInlayHintsProvider.createHints(element).toList()
}
return emptyList()
}
fun getMethodInfo(method: PsiMethod): MethodInfo? {
val containingClass = method.containingClass ?: return null
val fullMethodName = StringUtil.getQualifiedName(containingClass.qualifiedName, method.name)
val paramNames: List<String> = method.parameterList.parameters.map { it.name ?: "" }
return MethodInfo(fullMethodName, paramNames)
}
override fun getDefaultBlackList() = defaultBlackList
private val defaultBlackList = setOf(
"(begin*, end*)",
"(start*, end*)",
"(first*, last*)",
"(first*, second*)",
"(from*, to*)",
"(min*, max*)",
"(key, value)",
"(format, arg*)",
"(message)",
"(message, error)",
"*Exception",
"*.set*(*)",
"*.add(*)",
"*.set(*,*)",
"*.get(*)",
"*.create(*)",
"*.getProperty(*)",
"*.setProperty(*,*)",
"*.print(*)",
"*.println(*)",
"*.append(*)",
"*.charAt(*)",
"*.indexOf(*)",
"*.contains(*)",
"*.startsWith(*)",
"*.endsWith(*)",
"*.equals(*)",
"*.equal(*)",
"java.lang.Math.*",
"org.slf4j.Logger.*",
"*.singleton(*)",
"*.singletonList(*)",
"*.Set.of",
"*.ImmutableList.of",
"*.ImmutableMultiset.of",
"*.ImmutableSortedMultiset.of",
"*.ImmutableSortedSet.of"
)
val isDoNotShowIfMethodNameContainsParameterName = Option("java.method.name.contains.parameter.name",
"Do not show if method name contains parameter name",
true)
val isShowForParamsWithSameType = Option("java.multiple.params.same.type",
"Show for non-literals in case of multiple params with the same type",
false)
val isDoNotShowForBuilderLikeMethods = Option("java.build.like.method",
"Do not show for builder-like methods",
true)
override fun getSupportedOptions(): List<Option> {
return listOf(
isDoNotShowIfMethodNameContainsParameterName,
isShowForParamsWithSameType,
isDoNotShowForBuilderLikeMethods
)
}
} | java/java-impl/src/com/intellij/codeInsight/hints/JavaInlayParameterHintsProvider.kt | 338507137 |
package net.perfectdreams.loritta.common.utils
import io.ktor.http.*
import net.perfectdreams.i18nhelper.core.keydata.StringI18nData
import net.perfectdreams.loritta.i18n.I18nKeysData
/**
* Google Analytics' campaigns to track where users are coming from
*/
object GACampaigns {
fun sonhosBundlesUpsellDiscordMessage(
lorittaWebsiteUrl: String,
medium: String,
campaignContent: String
): StringI18nData {
return I18nKeysData.Commands.WantingMoreSonhosBundlesUpsell(sonhosBundlesUpsellDiscordMessageUrl(lorittaWebsiteUrl, medium, campaignContent))
}
fun sonhosBundlesUpsellDiscordMessageUrl(
lorittaWebsiteUrl: String,
medium: String,
campaignContent: String
): String {
return "<${sonhosBundlesUpsellUrl(lorittaWebsiteUrl, "discord", medium, "sonhos-bundles-upsell", campaignContent)}>"
}
fun sonhosBundlesUpsellUrl(
lorittaWebsiteUrl: String,
source: String,
medium: String,
campaignName: String,
campaignContent: String
): String {
return "${lorittaWebsiteUrl}user/@me/dashboard/bundles?utm_source=$source&utm_medium=$medium&utm_campaign=$campaignName&utm_content=$campaignContent"
}
fun premiumUpsellDiscordMessageUrl(
lorittaWebsiteUrl: String,
medium: String,
campaignContent: String
): String {
return "<${premiumUpsellDiscordCampaignUrl(lorittaWebsiteUrl, medium, campaignContent)}>"
}
fun premiumUpsellDiscordCampaignUrl(
lorittaWebsiteUrl: String,
medium: String,
campaignContent: String
): String {
return premiumUrl(lorittaWebsiteUrl, "discord", medium, "premium-upsell", campaignContent)
}
fun premiumUrl(
lorittaWebsiteUrl: String,
source: String,
medium: String,
campaignName: String,
campaignContent: String
): String {
return "${lorittaWebsiteUrl}donate?utm_source=$source&utm_medium=$medium&utm_campaign=$campaignName&utm_content=$campaignContent"
}
fun dailyWebRewardDiscordCampaignUrl(
lorittaWebsiteUrl: String,
medium: String,
campaignContent: String
): String {
return dailyUrl(lorittaWebsiteUrl, "discord", medium, "daily-web-reward", campaignContent)
}
fun dailyUrl(
lorittaWebsiteUrl: String,
source: String,
medium: String,
campaignName: String,
campaignContent: String
): String {
return "${lorittaWebsiteUrl}daily?utm_source=$source&utm_medium=$medium&utm_campaign=$campaignName&utm_content=$campaignContent"
}
fun patchNotesUrl(
lorittaWebsiteUrl: String,
websiteLocaleId: String,
path: String,
source: String,
medium: String,
campaignName: String,
campaignContent: String
): String {
return "${lorittaWebsiteUrl}$websiteLocaleId$path?utm_source=$source&utm_medium=$medium&utm_campaign=$campaignName&utm_content=$campaignContent"
}
fun createUrlWithCampaign(
url: String,
source: String,
medium: String,
campaignName: String,
campaignContent: String
) = URLBuilder(url)
.apply {
parameters.append("utm_source", source)
parameters.append("utm_medium", medium)
parameters.append("utm_campaign", campaignName)
parameters.append("utm_content", campaignContent)
}.build()
} | common/src/commonMain/kotlin/net/perfectdreams/loritta/common/utils/GACampaigns.kt | 3183753490 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.impl
import com.intellij.execution.configurations.UnknownRunConfiguration
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.StateSplitterEx
import com.intellij.openapi.components.Storage
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.registry.Registry
import gnu.trove.THashSet
import org.jdom.Element
internal class ProjectRunConfigurationStartupActivity : StartupActivity, DumbAware {
override fun runActivity(project: Project) {
if (project.isDefault || !Registry.`is`("runManager.use.schemeManager", false)) {
return
}
val manager = RunManagerImpl.getInstanceImpl(project)
val schemeManager = SchemeManagerFactory.getInstance(manager.project).create("runConfigurations", RunConfigurationSchemeManager(manager, true), isUseOldFileNameSanitize = true)
manager.projectSchemeManager = schemeManager
schemeManager.loadSchemes()
manager.requestSort()
}
}
@State(name = "ProjectRunConfigurationManager", storages = arrayOf(Storage(value = "runConfigurations", stateSplitter = ProjectRunConfigurationManager.RunConfigurationStateSplitter::class)))
internal class ProjectRunConfigurationManager(private val manager: RunManagerImpl) : PersistentStateComponent<Element> {
override fun getState(): Element? {
if (Registry.`is`("runManager.use.schemeManager", false)) {
return null
}
val state = Element("state")
manager.writeConfigurations(state, manager.getSharedConfigurations())
return state
}
override fun loadState(state: Element) {
if (Registry.`is`("runManager.use.schemeManager", false)) {
return
}
val existing = THashSet<String>()
for (child in state.getChildren(RunManagerImpl.CONFIGURATION)) {
existing.add(manager.loadConfiguration(child, true).uniqueID)
}
manager.removeNotExistingSharedConfigurations(existing)
manager.requestSort()
if (manager.selectedConfiguration == null) {
for (settings in manager.allSettings) {
if (settings.type !is UnknownRunConfiguration) {
manager.selectedConfiguration = settings
break
}
}
}
}
internal class RunConfigurationStateSplitter : StateSplitterEx() {
override fun splitState(state: Element): List<Pair<Element, String>> {
return StateSplitterEx.splitState(state, RunManagerImpl.NAME_ATTR)
}
}
}
| platform/lang-impl/src/com/intellij/execution/impl/ProjectRunConfigurationManager.kt | 1516433062 |
package i_introduction._7_Data_Classes
import util.TODO
class Person1(val name: String, val age: Int)
//no 'new' keyword
fun create() = Person1("James Gosling", 58)
fun useFromJava() {
// property 'val name' = backing field + getter
// => from Java you access it through 'getName()'
JavaCode7().useKotlinClass(Person1("Martin Odersky", 55))
// property 'var mutable' = backing field + getter + setter
}
// It's the same as the following (getters are generated by default):
class Person2(_name: String, _age: Int) { //_name, _age are constructor parameters
val name: String = _name //property initialization is the part of constructor
get(): String {
return $name // you can access the backing field of property with '$' + property name
}
val age: Int = _age
get(): Int {
return $age
}
}
// If you add annotation 'data' for your class, some additional methods will be generated for you
// like 'equals', 'hashCode', 'toString'.
data class Person3(val name: String, val age: Int)
// This class is as good as Person4 (written in Java), 42 lines shorter. =)
fun todoTask7() = TODO(
"""
There is no task for you here.
Just make sure you're not forgetting to read carefully all code examples and comments and
ask questions if you have any. =) Then return 'true' from 'task7'.
More information about classes in kotlin can be found in syntax/classesObjectsInterfaces.kt
""",
references = { JavaCode7.Person4("???", -1) }
)
fun task7(): Boolean = true | src/i_introduction/_7_Data_Classes/DataClasses.kt | 3545510241 |
/*
* 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 java.io.Closeable
import java.io.EOFException
import java.io.File
import java.io.FileNotFoundException
import java.io.Flushable
import java.io.IOException
import java.util.ArrayList
import java.util.LinkedHashMap
import java.util.NoSuchElementException
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.io.FileSystem
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.ForwardingSource
import okio.Sink
import okio.Source
import okio.blackholeSink
import okio.buffer
/**
* 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.
*/
class DiskLruCache internal constructor(
internal val fileSystem: FileSystem,
/** Returns the directory where this cache stores its data. */
val directory: File,
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 {
/** 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: File
private val journalFileTmp: File
private val journalFileBackup: File
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 = File(directory, JOURNAL_FILE)
this.journalFileTmp = File(directory, JOURNAL_FILE_TEMP)
this.journalFileBackup = File(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.rename(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.source(journalFile).buffer().use { source ->
val magic = source.readUtf8LineStrict()
val version = source.readUtf8LineStrict()
val appVersionString = source.readUtf8LineStrict()
val valueCountString = source.readUtf8LineStrict()
val blank = source.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(source.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 (!source.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.delete(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.delete(entry.cleanFiles[t])
fileSystem.delete(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.sink(journalFileTmp).buffer().use { sink ->
sink.writeUtf8(MAGIC).writeByte('\n'.toInt())
sink.writeUtf8(VERSION_1).writeByte('\n'.toInt())
sink.writeDecimalLong(appVersion.toLong()).writeByte('\n'.toInt())
sink.writeDecimalLong(valueCount.toLong()).writeByte('\n'.toInt())
sink.writeByte('\n'.toInt())
for (entry in lruEntries.values) {
if (entry.currentEditor != null) {
sink.writeUtf8(DIRTY).writeByte(' '.toInt())
sink.writeUtf8(entry.key)
sink.writeByte('\n'.toInt())
} else {
sink.writeUtf8(CLEAN).writeByte(' '.toInt())
sink.writeUtf8(entry.key)
entry.writeLengths(sink)
sink.writeByte('\n'.toInt())
}
}
}
if (fileSystem.exists(journalFile)) {
fileSystem.rename(journalFile, journalFileBackup)
}
fileSystem.rename(journalFileTmp, journalFile)
fileSystem.delete(journalFileBackup)
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.rename(dirty, clean)
val oldLength = entry.lengths[i]
val newLength = fileSystem.size(clean)
entry.lengths[i] = newLength
size = size - oldLength + newLength
}
} else {
fileSystem.delete(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.delete(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<File>()
internal val dirtyFiles = mutableListOf<File>()
/** 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 += File(directory, fileBuilder.toString())
fileBuilder.append(".tmp")
dirtyFiles += File(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"
}
}
| okhttp/src/main/kotlin/okhttp3/internal/cache/DiskLruCache.kt | 2996845280 |
package com.rartworks.engine.tween
import aurelienribon.tweenengine.Tween
import com.rartworks.engine.rendering.Drawable
/**
* A [QuadTween] for [Drawable]s.
*/
class DrawableQuadTween(drawable: Drawable) : QuadTween<Drawable>(drawable) {
init {
Tween.registerAccessor(drawable.javaClass, DrawableAccessor())
}
fun start(newValue: Float, duration: Float, configure: (Tween) -> (Tween) = { it }, parameter: DrawableTweenParameter = DrawableTweenParameter.ALPHA, onFinish: () -> (Unit) = {}) {
super.start(newValue, duration, configure, parameter.id, onFinish)
}
}
| core/src/com/rartworks/engine/tween/DrawableQuadTween.kt | 431098913 |
package library.enrichment
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.nhaarman.mockitokotlin2.given
import com.nhaarman.mockitokotlin2.timeout
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.willReturn
import library.enrichment.core.BookAddedEvent
import library.enrichment.gateways.library.LibraryClient
import library.enrichment.gateways.library.UpdateAuthors
import library.enrichment.gateways.library.UpdateNumberOfPages
import library.enrichment.gateways.openlibrary.OpenLibraryClient
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.amqp.core.TopicExchange
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.junit.jupiter.SpringExtension
import utils.classification.AcceptanceTest
import utils.extensions.RabbitMqExtension
import utils.readFile
@AcceptanceTest
@ExtendWith(RabbitMqExtension::class, SpringExtension::class)
@SpringBootTest(
webEnvironment = NONE,
properties = ["spring.rabbitmq.port=\${RABBITMQ_PORT}"]
)
@ActiveProfiles("test", "unsecured")
internal class FunctionalAcceptanceTest {
companion object {
const val TIMEOUT = 5000L
const val routingKey = "book-added"
const val id = "dda05852-f6fe-4ba6-9ce2-6f3a73c664a9"
const val bookId = "175c5a7e-dd91-4d42-8c0d-6a97d8755231"
}
@Autowired lateinit var exchange: TopicExchange
@Autowired lateinit var objectMapper: ObjectMapper
@Autowired lateinit var rabbitTemplate: RabbitTemplate
@MockBean lateinit var openLibraryClient: OpenLibraryClient
@MockBean lateinit var libraryClient: LibraryClient
@Test fun `book added events are processed correctly`() {
given { openLibraryClient.searchBooks("9780261102354") } willReturn {
readFile("openlibrary/responses/200_isbn_9780261102354.json").toJson()
}
send(BookAddedEvent(
id = id,
bookId = bookId,
isbn = "9780261102354"
))
verify(libraryClient, timeout(TIMEOUT))
.updateAuthors(bookId, UpdateAuthors(listOf("J. R. R. Tolkien")))
verify(libraryClient, timeout(TIMEOUT))
.updateNumberOfPages(bookId, UpdateNumberOfPages(576))
}
fun String.toJson(): JsonNode = objectMapper.readTree(this)
fun send(event: BookAddedEvent) = rabbitTemplate.convertAndSend(exchange.name, routingKey, event)
} | library-enrichment/src/test/kotlin/library/enrichment/FunctionalAcceptanceTest.kt | 68140816 |
package ee.lang.fx.view
import ee.lang.ItemI
import ee.task.Result
import ee.task.TaskFactory
import ee.task.TaskRepository
import ee.task.print
import tornadofx.Controller
class TasksController : Controller() {
val tasksView: TasksView by inject()
val outputContainerView: OutputContainerView by inject()
val repo: TaskRepository by di()
var selectedElements: List<ItemI<*>> = emptyList()
fun onStructureUnitsSelected(elements: List<ItemI<*>>) {
selectedElements = elements
runAsync {
repo.find(elements)
} ui {
tasksView.refresh(it)
}
}
fun execute(taskFactory: TaskFactory<*>) {
runAsync {
val console = outputContainerView.takeConsole(this, taskFactory.name)
val results = arrayListOf<Result>()
val ret = Result(action = taskFactory.name, results = results)
taskFactory.create(selectedElements).forEach { task ->
console.title = task.name
val result = task.execute({ console.println(it) })
console.title = result.toString()
results.add(result)
}
ret.print({ console.println(it) })
outputContainerView.release(console)
}
}
}
| ee-lang_fx/src/main/kotlin/ee/lang/fx/view/TasksController.kt | 1295163001 |
/*-
* #%L
* Spring Auto REST Docs Kotlin Web MVC Example Project
* %%
* Copyright (C) 2015 - 2021 Scalable Capital GmbH
* %%
* 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.
* #L%
*/
package capital.scalable.restdocs.example.security
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service
@Service
internal class CustomUserDetailsService : UserDetailsService {
@Throws(UsernameNotFoundException::class)
override fun loadUserByUsername(username: String): UserDetails {
// Usually, you would consult a database, but for simplicity we hardcode a user
// with username "test" and password "test".
return if ("test" == username) {
User.withDefaultPasswordEncoder()
.username(username)
.password("test")
.authorities("USER")
.build()
} else {
throw UsernameNotFoundException(String.format("User %s does not exist!", username))
}
}
}
| samples/kotlin-webmvc/src/main/kotlin/capital/scalable/restdocs/example/security/CustomUserDetailsService.kt | 61961745 |
package com.github.christophpickl.kpotpourri.test4k
import org.testng.annotations.Test
@Test class AssertThrownTest {
private val ANY_MESSAGE = "testMessage"
fun `assertThrown without matcher - Given proper exception type, Should match type`() {
assertThrown<MyException> {
throw MyException(ANY_MESSAGE)
}
}
fun `assertThrown with matcher - Given exception matching message, Should match with same message`() {
assertThrown<MyException>({ it.message == "foo" }) {
throw MyException("foo")
}
}
@Test(expectedExceptions = arrayOf(AssertionError::class))
fun `assertThrown with matcher - Given exception not matching message, Should throw`() {
assertThrown<MyException>({ it.message == "foo" }) {
throw MyException("bar")
}
}
@Test(expectedExceptions = arrayOf(AssertionError::class))
fun `assertThrown - Given exception of different type, Should throw`() {
assertThrown<MyException> {
throw RuntimeException()
}
}
fun `assertThrown - Given exception of sub type, Should match because of the simple IS check inside`() {
assertThrown<MyException> {
throw MySubException(ANY_MESSAGE)
}
}
}
private open class MyException(message: String) : RuntimeException(message)
private class MySubException(message: String) : MyException(message)
| test4k/src/test/kotlin/com/github/christophpickl/kpotpourri/test4k/assertions_test.kt | 2659235830 |
/*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.types.ResourceCollection
import org.apache.tools.ant.types.TarFileSet
import org.apache.tools.ant.types.selectors.AndSelector
import org.apache.tools.ant.types.selectors.ContainsRegexpSelector
import org.apache.tools.ant.types.selectors.ContainsSelector
import org.apache.tools.ant.types.selectors.DateSelector
import org.apache.tools.ant.types.selectors.DependSelector
import org.apache.tools.ant.types.selectors.DepthSelector
import org.apache.tools.ant.types.selectors.DifferentSelector
import org.apache.tools.ant.types.selectors.ExecutableSelector
import org.apache.tools.ant.types.selectors.ExtendSelector
import org.apache.tools.ant.types.selectors.FileSelector
import org.apache.tools.ant.types.selectors.FilenameSelector
import org.apache.tools.ant.types.selectors.MajoritySelector
import org.apache.tools.ant.types.selectors.NoneSelector
import org.apache.tools.ant.types.selectors.NotSelector
import org.apache.tools.ant.types.selectors.OrSelector
import org.apache.tools.ant.types.selectors.OwnedBySelector
import org.apache.tools.ant.types.selectors.PresentSelector
import org.apache.tools.ant.types.selectors.ReadableSelector
import org.apache.tools.ant.types.selectors.SelectSelector
import org.apache.tools.ant.types.selectors.SizeSelector
import org.apache.tools.ant.types.selectors.SymlinkSelector
import org.apache.tools.ant.types.selectors.TypeSelector
import org.apache.tools.ant.types.selectors.WritableSelector
import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
interface ITarFileSetNested : INestedComponent {
fun tarfileset(
dir: String? = null,
file: String? = null,
includes: String? = null,
excludes: String? = null,
includesfile: String? = null,
excludesfile: String? = null,
defaultexcludes: Boolean? = null,
casesensitive: Boolean? = null,
followsymlinks: Boolean? = null,
maxlevelsofsymlinks: Int? = null,
erroronmissingdir: Boolean? = null,
src: String? = null,
erroronmissingarchive: Boolean? = null,
prefix: String? = null,
fullpath: String? = null,
encoding: String? = null,
filemode: String? = null,
dirmode: String? = null,
username: String? = null,
uid: Int? = null,
group: String? = null,
gid: Int? = null,
nested: (KTarFileSet.() -> Unit)? = null)
{
_addTarFileSet(TarFileSet().apply {
component.project.setProjectReference(this);
_init(dir, file, includes, excludes,
includesfile, excludesfile, defaultexcludes, casesensitive,
followsymlinks, maxlevelsofsymlinks, erroronmissingdir, src,
erroronmissingarchive, prefix, fullpath, encoding,
filemode, dirmode, username, uid,
group, gid, nested)
})
}
fun _addTarFileSet(value: TarFileSet)
}
fun IFileSetNested.tarfileset(
dir: String? = null,
file: String? = null,
includes: String? = null,
excludes: String? = null,
includesfile: String? = null,
excludesfile: String? = null,
defaultexcludes: Boolean? = null,
casesensitive: Boolean? = null,
followsymlinks: Boolean? = null,
maxlevelsofsymlinks: Int? = null,
erroronmissingdir: Boolean? = null,
src: String? = null,
erroronmissingarchive: Boolean? = null,
prefix: String? = null,
fullpath: String? = null,
encoding: String? = null,
filemode: String? = null,
dirmode: String? = null,
username: String? = null,
uid: Int? = null,
group: String? = null,
gid: Int? = null,
nested: (KTarFileSet.() -> Unit)? = null)
{
_addFileSet(TarFileSet().apply {
component.project.setProjectReference(this);
_init(dir, file, includes, excludes,
includesfile, excludesfile, defaultexcludes, casesensitive,
followsymlinks, maxlevelsofsymlinks, erroronmissingdir, src,
erroronmissingarchive, prefix, fullpath, encoding,
filemode, dirmode, username, uid,
group, gid, nested)
})
}
fun IResourceCollectionNested.tarfileset(
dir: String? = null,
file: String? = null,
includes: String? = null,
excludes: String? = null,
includesfile: String? = null,
excludesfile: String? = null,
defaultexcludes: Boolean? = null,
casesensitive: Boolean? = null,
followsymlinks: Boolean? = null,
maxlevelsofsymlinks: Int? = null,
erroronmissingdir: Boolean? = null,
src: String? = null,
erroronmissingarchive: Boolean? = null,
prefix: String? = null,
fullpath: String? = null,
encoding: String? = null,
filemode: String? = null,
dirmode: String? = null,
username: String? = null,
uid: Int? = null,
group: String? = null,
gid: Int? = null,
nested: (KTarFileSet.() -> Unit)? = null)
{
_addResourceCollection(TarFileSet().apply {
component.project.setProjectReference(this);
_init(dir, file, includes, excludes,
includesfile, excludesfile, defaultexcludes, casesensitive,
followsymlinks, maxlevelsofsymlinks, erroronmissingdir, src,
erroronmissingarchive, prefix, fullpath, encoding,
filemode, dirmode, username, uid,
group, gid, nested)
})
}
fun TarFileSet._init(
dir: String?,
file: String?,
includes: String?,
excludes: String?,
includesfile: String?,
excludesfile: String?,
defaultexcludes: Boolean?,
casesensitive: Boolean?,
followsymlinks: Boolean?,
maxlevelsofsymlinks: Int?,
erroronmissingdir: Boolean?,
src: String?,
erroronmissingarchive: Boolean?,
prefix: String?,
fullpath: String?,
encoding: String?,
filemode: String?,
dirmode: String?,
username: String?,
uid: Int?,
group: String?,
gid: Int?,
nested: (KTarFileSet.() -> Unit)?)
{
if (dir != null)
setDir(project.resolveFile(dir))
if (file != null)
setFile(project.resolveFile(file))
if (includes != null)
setIncludes(includes)
if (excludes != null)
setExcludes(excludes)
if (includesfile != null)
setIncludesfile(project.resolveFile(includesfile))
if (excludesfile != null)
setExcludesfile(project.resolveFile(excludesfile))
if (defaultexcludes != null)
setDefaultexcludes(defaultexcludes)
if (casesensitive != null)
setCaseSensitive(casesensitive)
if (followsymlinks != null)
setFollowSymlinks(followsymlinks)
if (maxlevelsofsymlinks != null)
setMaxLevelsOfSymlinks(maxlevelsofsymlinks)
if (erroronmissingdir != null)
setErrorOnMissingDir(erroronmissingdir)
if (src != null)
setSrc(project.resolveFile(src))
if (erroronmissingarchive != null)
setErrorOnMissingArchive(erroronmissingarchive)
if (prefix != null)
setPrefix(prefix)
if (fullpath != null)
setFullpath(fullpath)
if (encoding != null)
setEncoding(encoding)
if (filemode != null)
setFileMode(filemode)
if (dirmode != null)
setDirMode(dirmode)
if (username != null)
setUserName(username)
if (uid != null)
setUid(uid)
if (group != null)
setGroup(group)
if (gid != null)
setGid(gid)
if (nested != null)
nested(KTarFileSet(this))
}
class KTarFileSet(override val component: TarFileSet) :
IFileSelectorNested,
IResourceCollectionNested,
ISelectSelectorNested,
IAndSelectorNested,
IOrSelectorNested,
INotSelectorNested,
INoneSelectorNested,
IMajoritySelectorNested,
IDateSelectorNested,
ISizeSelectorNested,
IDifferentSelectorNested,
IFilenameSelectorNested,
ITypeSelectorNested,
IExtendSelectorNested,
IContainsSelectorNested,
IPresentSelectorNested,
IDepthSelectorNested,
IDependSelectorNested,
IContainsRegexpSelectorNested,
IModifiedSelectorNested,
IReadableSelectorNested,
IWritableSelectorNested,
IExecutableSelectorNested,
ISymlinkSelectorNested,
IOwnedBySelectorNested
{
fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) {
component.createPatternSet().apply {
component.project.setProjectReference(this)
_init(includes, excludes, includesfile, excludesfile, nested)
}
}
fun include(name: String? = null, If: String? = null, unless: String? = null) {
component.createInclude().apply {
_init(name, If, unless)
}
}
fun includesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createIncludesFile().apply {
_init(name, If, unless)
}
}
fun exclude(name: String? = null, If: String? = null, unless: String? = null) {
component.createExclude().apply {
_init(name, If, unless)
}
}
fun excludesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createExcludesFile().apply {
_init(name, If, unless)
}
}
override fun _addFileSelector(value: FileSelector) = component.add(value)
override fun _addResourceCollection(value: ResourceCollection) = component.addConfigured(value)
override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value)
override fun _addAndSelector(value: AndSelector) = component.addAnd(value)
override fun _addOrSelector(value: OrSelector) = component.addOr(value)
override fun _addNotSelector(value: NotSelector) = component.addNot(value)
override fun _addNoneSelector(value: NoneSelector) = component.addNone(value)
override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value)
override fun _addDateSelector(value: DateSelector) = component.addDate(value)
override fun _addSizeSelector(value: SizeSelector) = component.addSize(value)
override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value)
override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value)
override fun _addTypeSelector(value: TypeSelector) = component.addType(value)
override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value)
override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value)
override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value)
override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value)
override fun _addDependSelector(value: DependSelector) = component.addDepend(value)
override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value)
override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value)
override fun _addReadableSelector(value: ReadableSelector) = component.addReadable(value)
override fun _addWritableSelector(value: WritableSelector) = component.addWritable(value)
override fun _addExecutableSelector(value: ExecutableSelector) = component.addExecutable(value)
override fun _addSymlinkSelector(value: SymlinkSelector) = component.addSymlink(value)
override fun _addOwnedBySelector(value: OwnedBySelector) = component.addOwnedBy(value)
}
| src/main/kotlin/com/devcharly/kotlin/ant/types/tarfileset.kt | 4215233169 |
/*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.types.selectors.ReadableSelector
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
interface IReadableSelectorNested {
fun readable(
)
{
_addReadableSelector(ReadableSelector().apply {
_init()
})
}
fun _addReadableSelector(value: ReadableSelector)
}
fun ReadableSelector._init(
)
{
}
| src/main/kotlin/com/devcharly/kotlin/ant/selectors/readableselector.kt | 208872310 |
package com.sksamuel.kotest
import io.kotest.core.filters.TestCaseFilter
import io.kotest.core.filters.TestFilterResult
import io.kotest.core.test.Description
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
import io.kotest.core.test.TestStatus
import io.kotest.matchers.shouldBe
import io.kotest.core.spec.style.StringSpec
class TestCaseFilterTest : StringSpec() {
var a = false
var b = false
init {
"aa should run" {
a = true
}
// this test will be ignored the test case filter that we have registered in project config
"bb should be ignored" {
1 shouldBe 2
}
}
override fun afterTest(testCase: TestCase, result: TestResult) {
when (testCase.description.name) {
"aa should run" -> result.status shouldBe TestStatus.Success
"bb should be ignored" -> result.status shouldBe TestStatus.Ignored
}
a shouldBe true
}
}
object TestCaseFilterTestFilter : TestCaseFilter {
override fun filter(description: Description): TestFilterResult {
return when (description.name) {
"bb should be ignored" -> TestFilterResult.Exclude
else -> TestFilterResult.Include
}
}
}
| kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/TestCaseFilterTest.kt | 3947145783 |
/*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj.transform.node.incoming
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import org.jitsi.nlj.PacketInfo
import org.jitsi.rtp.rtp.RtpPacket
import org.jitsi.utils.MediaType
import java.time.Instant
private data class StatPacketInfo(
val packetInfo: PacketInfo,
val sentTime: Instant
)
private data class JitterPacketInfo(
val statPacketInfo: StatPacketInfo,
val expectedJitter: Double
)
private fun createStatPacketInfo(seqNum: Int, sentTime: Long, receivedTime: Long): StatPacketInfo {
val packetInfo = PacketInfo(RtpPacket(ByteArray(50), 0, 50))
packetInfo.packetAs<RtpPacket>().sequenceNumber = seqNum
packetInfo.receivedTime = Instant.ofEpochMilli(receivedTime)
return StatPacketInfo(packetInfo, Instant.ofEpochMilli(sentTime))
}
private fun createJitterPacketInfo(
seqNum: Int,
sentTime: Long,
receivedTime: Long,
expectedJitter: Double
): JitterPacketInfo {
val statPacketInfo = createStatPacketInfo(seqNum, sentTime, receivedTime)
return JitterPacketInfo(statPacketInfo, expectedJitter)
}
// Values taken from this example: http://toncar.cz/Tutorials/VoIP/VoIP_Basics_Jitter.html
private val initialJitterPacketInfo = createJitterPacketInfo(0, 0, 10, 0.0)
private val JitterPacketInfos = listOf(
createJitterPacketInfo(1, 20, 30, 0.0),
createJitterPacketInfo(2, 40, 49, .0625),
createJitterPacketInfo(3, 60, 74, .3711),
createJitterPacketInfo(4, 80, 90, .5979),
createJitterPacketInfo(5, 100, 111, .6230),
createJitterPacketInfo(6, 120, 139, 1.0841),
createJitterPacketInfo(7, 140, 150, 1.5788),
createJitterPacketInfo(8, 160, 170, 1.4802),
createJitterPacketInfo(9, 180, 191, 1.4501),
createJitterPacketInfo(10, 200, 210, 1.4220),
createJitterPacketInfo(11, 220, 229, 1.3956),
createJitterPacketInfo(12, 240, 250, 1.3709),
createJitterPacketInfo(13, 260, 271, 1.3477)
)
internal class IncomingSsrcStatsTest : ShouldSpec() {
override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf
init {
context("Expected packet count") {
should("Handle cases with no rollover") {
IncomingSsrcStats.calculateExpectedPacketCount(
0,
1,
0,
10
) shouldBe 10
}
should("handle cases with 1 rollover") {
IncomingSsrcStats.calculateExpectedPacketCount(
0,
65530,
1,
10
) shouldBe 17
}
should("handle cases with > 1 rollover") {
// Same as the scenario above but with another rollover
IncomingSsrcStats.calculateExpectedPacketCount(
0,
65530,
2,
10
) shouldBe 17 + 65536L
}
}
context("When receiving a series of packets with loss") {
// 17 packets between base and max sequence number, 6 packets lost
val packetSequence = listOf(
createStatPacketInfo(0, 0, 0),
createStatPacketInfo(1, 0, 0),
createStatPacketInfo(3, 0, 0),
createStatPacketInfo(5, 0, 0),
createStatPacketInfo(6, 0, 0),
createStatPacketInfo(7, 0, 0),
createStatPacketInfo(8, 0, 0),
createStatPacketInfo(9, 0, 0),
createStatPacketInfo(11, 0, 0),
createStatPacketInfo(13, 0, 0),
createStatPacketInfo(16, 0, 0)
)
val streamStatistics = IncomingSsrcStats(
123L,
packetSequence.first().packetInfo.packetAs<RtpPacket>().sequenceNumber,
mediaType = MediaType.VIDEO
)
packetSequence.forEach {
streamStatistics.packetReceived(
it.packetInfo.packetAs(),
it.sentTime,
it.packetInfo.receivedTime!!
)
}
val statSnapshot = streamStatistics.getSnapshotIfActive()
context("expected packets") {
should("be calculated correctly") {
statSnapshot?.numExpectedPackets shouldBe 17
}
}
context("cumulative lost") {
should("be calculated correctly") {
statSnapshot?.cumulativePacketsLost shouldBe 6
}
}
context("querying a second time with no update") {
should("be null") {
streamStatistics.getSnapshotIfActive() shouldBe null
}
}
val packetSequence2 = listOf(
createStatPacketInfo(17, 0, 0)
)
packetSequence2.forEach {
streamStatistics.packetReceived(
it.packetInfo.packetAs<RtpPacket>(),
it.sentTime,
it.packetInfo.receivedTime!!
)
}
context("querying after a new update") {
should("not be null") {
streamStatistics.getSnapshotIfActive() shouldNotBe null
}
}
}
}
}
| jitsi-media-transform/src/test/kotlin/org/jitsi/nlj/transform/node/incoming/IncomingSsrcStatsTest.kt | 163138158 |
package examples.kotlin.inaka.com.activities
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import examples.kotlin.inaka.com.R
import examples.kotlin.inaka.com.adapters.SlidingTabsAdapter
import kotlinx.android.synthetic.main.activity_sliding_tabs.*
import kotlinx.android.synthetic.main.content_sliding_tabs.*
class SlidingTabsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sliding_tabs)
setSupportActionBar(toolbar)
viewPagerSlidingTabs.adapter = SlidingTabsAdapter(supportFragmentManager)
tabs.setViewPager(viewPagerSlidingTabs)
}
}
| app/src/main/java/examples/kotlin/inaka/com/activities/SlidingTabsActivity.kt | 3679861266 |
package com.fk.fuckoffer.injection
import com.fk.fuckoffer.rest.FoaasRest
import dagger.Module
import dagger.Provides
import retrofit2.Retrofit
/**
* Created by fk on 22.10.17.
*/
@Module class ServicesModule {
@Provides fun foaasRest(retrofit: Retrofit) = retrofit.create(FoaasRest::class.java)
} | app/src/main/java/com/fk/fuckoffer/injection/ServicesModule.kt | 2865466824 |
/*
* Copyright 2022 The Cross-Media Measurement Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wfanet.measurement.common.db.r2dbc.postgres
import com.google.common.truth.Truth.assertThat
import com.google.type.DayOfWeek
import com.google.type.LatLng
import com.google.type.latLng
import java.nio.file.Path
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.wfanet.measurement.common.db.r2dbc.ReadWriteContext
import org.wfanet.measurement.common.db.r2dbc.ResultRow
import org.wfanet.measurement.common.db.r2dbc.boundStatement
import org.wfanet.measurement.common.db.r2dbc.postgres.testing.EmbeddedPostgresDatabaseProvider
import org.wfanet.measurement.common.getJarResourcePath
import org.wfanet.measurement.common.identity.InternalId
@RunWith(JUnit4::class)
class PostgresDatabaseClientTest {
private val dbClient = dbProvider.createNewDatabase()
@Test
fun `executeStatement returns result with updated rows`() {
val insertStatement =
boundStatement(
"""
INSERT INTO Cars (CarId, Year, Make, Model) VALUES
(1, 1990, 'Nissan', 'Stanza'),
(2, 1997, 'Honda', 'CR-V'),
(3, 2012, 'Audi', 'S4'),
(4, 2020, 'Tesla', 'Model 3')
"""
.trimIndent()
)
val result = runBlocking {
val txn = dbClient.readWriteTransaction()
try {
txn.executeStatement(insertStatement)
} finally {
txn.close()
}
}
assertThat(result.numRowsUpdated).isEqualTo(4L)
}
@Test
fun `bind binds parameters by name`(): Unit = runBlocking {
val car =
Car(
InternalId(123L),
2020,
"Tesla",
"Model 3",
null,
latLng {
latitude = 33.995325
longitude = -118.477021
},
DayOfWeek.TUESDAY
)
val insertStatement =
boundStatement("INSERT INTO Cars VALUES ($1, $2, $3, $4, $5, $6, $7)") {
bind("$1", car.carId)
bind("$2", car.year)
bind("$3", car.make)
bind("$4", car.model)
bind("$5", car.owner)
bind("$6", car.currentLocation)
bind("$7", car.weeklyWashDay)
}
with(dbClient.readWriteTransaction()) {
executeStatement(insertStatement)
commit()
}
val query = boundStatement("SELECT * FROM Cars")
val cars: Flow<Car> =
dbClient.singleUse().executeQuery(query).consume { row -> Car.parseFrom(row) }
assertThat(cars.toList()).containsExactly(car)
}
@Test
fun `addBinding adds bindings`() = runBlocking {
val cars =
listOf(
Car(carId = InternalId(1), year = 2012, make = "Audi", model = "S4"),
Car(carId = InternalId(2), year = 2020, make = "Tesla", model = "Model 3")
)
val insertStatement =
boundStatement("INSERT INTO Cars (CarId, Year, Make, Model) VALUES ($1, $2, $3, $4)") {
for (car in cars) {
addBinding {
bind("$1", car.carId)
bind("$2", car.year)
bind("$3", car.make)
bind("$4", car.model)
}
}
}
val statementResult =
with(dbClient.readWriteTransaction()) { executeStatement(insertStatement).also { commit() } }
assertThat(statementResult.numRowsUpdated).isEqualTo(2L)
val query = boundStatement("SELECT * FROM Cars ORDER BY CarId")
val result: Flow<Car> =
dbClient.singleUse().executeQuery(query).consume { row -> Car.parseFrom(row) }
assertThat(result.toList()).containsExactlyElementsIn(cars).inOrder()
}
@Test
fun `rollbackTransaction rolls back the transaction`() = runBlocking {
val car = Car(carId = InternalId(2), year = 2020, make = "Tesla", model = "Model 3")
val insertStatement =
boundStatement("INSERT INTO Cars (CarId, Year, Make, Model) VALUES ($1, $2, $3, $4)") {
addBinding {
bind("$1", car.carId)
bind("$2", car.year)
bind("$3", car.make)
bind("$4", car.model)
}
}
val readWriteContext = dbClient.readWriteTransaction()
val insertResult = readWriteContext.executeStatement(insertStatement)
assertThat(insertResult.numRowsUpdated).isEqualTo(1L)
val query = boundStatement("SELECT * FROM Cars")
var selectResult: Flow<Car> =
readWriteContext.executeQuery(query).consume { row -> Car.parseFrom(row) }
assertThat(selectResult.toList()).hasSize(1)
readWriteContext.rollback()
selectResult = readWriteContext.executeQuery(query).consume { row -> Car.parseFrom(row) }
assertThat(selectResult.toList()).hasSize(0)
}
@Test
fun `executeQuery reads writes from same transaction`(): Unit = runBlocking {
val insertStatement =
boundStatement(
"""
INSERT INTO Cars (CarId, Year, Make, Model) VALUES
(5, 2021, 'Tesla', 'Model Y'),
(1, 1990, 'Nissan', 'Stanza'),
(2, 1997, 'Honda', 'CR-V'),
(3, 2012, 'Audi', 'S4'),
(4, 2020, 'Tesla', 'Model 3')
"""
.trimIndent()
)
val txn: ReadWriteContext = dbClient.readWriteTransaction()
txn.executeStatement(insertStatement)
val query = boundStatement("SELECT * FROM Cars ORDER BY Year ASC")
val models: Flow<String> =
txn.executeQuery(query).consume<String> { row -> row["Model"] }.onCompletion { txn.close() }
assertThat(models.toList())
.containsExactly("Stanza", "CR-V", "S4", "Model 3", "Model Y")
.inOrder()
}
@Test
fun `executeQuery does not see writes from pending write transaction`(): Unit = runBlocking {
val insertStatement =
boundStatement(
"""
INSERT INTO Cars (CarId, Year, Make, Model) VALUES
(5, 2021, 'Tesla', 'Model Y'),
(1, 1990, 'Nissan', 'Stanza'),
(2, 1997, 'Honda', 'CR-V'),
(3, 2012, 'Audi', 'S4'),
(4, 2020, 'Tesla', 'Model 3')
"""
.trimIndent()
)
val writeTxn: ReadWriteContext = dbClient.readWriteTransaction()
writeTxn.executeStatement(insertStatement)
val query = boundStatement("SELECT * FROM CARS")
val models: Flow<String> =
with(dbClient.readTransaction()) {
executeQuery(query).consume<String> { row -> row["Model"] }.onCompletion { close() }
}
writeTxn.close()
assertThat(models.toList()).isEmpty()
}
companion object {
private val CHANGELOG_PATH: Path =
this::class.java.classLoader.getJarResourcePath("db/postgres/changelog.yaml")!!
private val dbProvider = EmbeddedPostgresDatabaseProvider(CHANGELOG_PATH)
}
}
private data class Car(
val carId: InternalId,
val year: Long,
val make: String,
val model: String,
val owner: String? = null,
val currentLocation: LatLng? = null,
val weeklyWashDay: DayOfWeek = DayOfWeek.DAY_OF_WEEK_UNSPECIFIED,
) {
companion object {
fun parseFrom(row: ResultRow): Car {
return with(row) {
Car(
get("CarId"),
get("Year"),
get("Make"),
get("Model"),
get("Owner"),
getProtoMessage("CurrentLocation", LatLng.parser()),
getProtoEnum("WeeklyWashDay", DayOfWeek::forNumber)
)
}
}
}
}
| src/test/kotlin/org/wfanet/measurement/common/db/r2dbc/postgres/PostgresDatabaseClientTest.kt | 2851218547 |
package org.gradle.kotlin.dsl.integration
import org.gradle.kotlin.dsl.fixtures.AbstractKotlinIntegrationTest
import org.hamcrest.CoreMatchers.containsString
import org.junit.Assert.assertThat
import org.junit.Test
/**
* See https://docs.gradle.org/current/userguide/build_environment.html
*/
class DelegatedGradlePropertiesIntegrationTest : AbstractKotlinIntegrationTest() {
@Test
fun `non-nullable delegated property access of non-existing gradle property throws`() {
withSettings("""
val nonExisting: String by settings
println(nonExisting)
""")
assertThat(
buildAndFail("help").error,
containsString("Cannot get non-null property 'nonExisting' on settings '${projectRoot.name}' as it does not exist"))
withSettings("")
withBuildScript("""
val nonExisting: String by project
println(nonExisting)
""")
assertThat(
buildAndFail("help").error,
containsString("Cannot get non-null property 'nonExisting' on root project '${projectRoot.name}' as it does not exist"))
}
@Test
fun `delegated properties follow Gradle mechanics and allow to model optional properties via nullable kotlin types`() {
// given: build root gradle.properties file
withFile("gradle.properties", """
setBuildProperty=build value
emptyBuildProperty=
userHomeOverriddenBuildProperty=build value
cliOverriddenBuildProperty=build value
projectMutatedBuildProperty=build value
""".trimIndent())
// and: gradle user home gradle.properties file
withFile("gradle-user-home/gradle.properties", """
setUserHomeProperty=user home value
emptyUserHomeProperty=
userHomeOverriddenBuildProperty=user home value
cliOverriddenUserHomeProperty=user home value
projectMutatedUserHomeProperty=user home value
""".trimIndent())
// and: isolated gradle user home
executer.withGradleUserHomeDir(existing("gradle-user-home"))
executer.requireIsolatedDaemons()
// and: gradle command line with properties
val buildArguments = arrayOf(
"-PsetCliProperty=cli value",
"-PemptyCliProperty=",
"-PcliOverriddenBuildProperty=cli value",
"-PcliOverriddenUserHomeProperty=cli value",
"-Dorg.gradle.project.setOrgGradleProjectSystemProperty=system property value",
"-Dorg.gradle.project.emptyOrgGradleProjectSystemProperty=",
"help")
// when: both settings and project scripts asserting on delegated properties
withSettings(requirePropertiesFromSettings())
withBuildScript(requirePropertiesFromProject())
// then:
build(*buildArguments)
// when: project script buildscript block asserting on delegated properties
withSettings("")
withBuildScript("""
buildscript {
${requirePropertiesFromProject()}
}
""")
// then:
build(*buildArguments)
}
private
fun requirePropertiesFromSettings() =
"""
${requireNotOverriddenPropertiesFrom("settings")}
${requireOverriddenPropertiesFrom("settings")}
${requireEnvironmentPropertiesFrom("settings")}
${requireProjectMutatedPropertiesOriginalValuesFrom("settings")}
""".trimIndent()
private
fun requirePropertiesFromProject() =
"""
${requireNotOverriddenPropertiesFrom("project")}
${requireOverriddenPropertiesFrom("project")}
${requireEnvironmentPropertiesFrom("project")}
${requireProjectExtraProperties()}
${requireProjectMutatedPropertiesOriginalValuesFrom("project")}
${requireProjectPropertiesMutation()}
""".trimIndent()
private
fun requireNotOverriddenPropertiesFrom(source: String) =
"""
${requireProperty<String>(source, "setUserHomeProperty", """"user home value"""")}
${requireProperty<String>(source, "emptyUserHomeProperty", """""""")}
${requireProperty<String>(source, "setBuildProperty", """"build value"""")}
${requireProperty<String>(source, "emptyBuildProperty", """""""")}
${requireProperty<String>(source, "setCliProperty", """"cli value"""")}
${requireProperty<String>(source, "emptyCliProperty", """""""")}
${requireNullableProperty<String>(source, "unsetProperty", "null")}
""".trimIndent()
private
fun requireOverriddenPropertiesFrom(source: String) =
"""
${requireProperty<String>(source, "userHomeOverriddenBuildProperty", """"user home value"""")}
${requireProperty<String>(source, "cliOverriddenBuildProperty", """"cli value"""")}
${requireProperty<String>(source, "cliOverriddenUserHomeProperty", """"cli value"""")}
""".trimIndent()
private
fun requireEnvironmentPropertiesFrom(source: String) =
"""
${requireProperty<String>(source, "setOrgGradleProjectSystemProperty", """"system property value"""")}
${requireProperty<String>(source, "emptyOrgGradleProjectSystemProperty", """""""")}
""".trimIndent()
private
fun requireProjectExtraProperties() =
"""
run {
extra["setExtraProperty"] = "extra value"
extra["emptyExtraProperty"] = ""
extra["unsetExtraProperty"] = null
val setExtraProperty: String by project
require(setExtraProperty == "extra value")
val emptyExtraProperty: String by project
require(emptyExtraProperty == "")
val unsetExtraProperty: String? by project
require(unsetExtraProperty == null)
setProperty("setExtraProperty", "mutated")
require(setExtraProperty == "mutated")
}
""".trimIndent()
private
fun requireProjectMutatedPropertiesOriginalValuesFrom(source: String) =
"""
${requireProperty<String>(source, "projectMutatedBuildProperty", """"build value"""")}
${requireProperty<String>(source, "projectMutatedUserHomeProperty", """"user home value"""")}
""".trimIndent()
private
fun requireProjectPropertiesMutation() =
"""
run {
val projectMutatedBuildProperty: String by project
require(projectMutatedBuildProperty == "build value")
setProperty("projectMutatedBuildProperty", "mutated")
require(projectMutatedBuildProperty == "mutated")
val projectMutatedUserHomeProperty: String by project
require(projectMutatedUserHomeProperty == "user home value")
setProperty("projectMutatedUserHomeProperty", "mutated")
require(projectMutatedUserHomeProperty == "mutated")
}
""".trimIndent()
private
inline fun <reified T : Any> requireProperty(source: String, name: String, valueRepresentation: String) =
requireProperty(source, name, T::class.qualifiedName!!, valueRepresentation)
private
inline fun <reified T : Any> requireNullableProperty(source: String, name: String, valueRepresentation: String) =
requireProperty(source, name, "${T::class.qualifiedName!!}?", valueRepresentation)
private
fun requireProperty(source: String, name: String, type: String, valueRepresentation: String) =
"""
run {
val $name: $type by $source
require($name == $valueRepresentation) {
${"\"".repeat(3)}expected $name to be '$valueRepresentation' but was '${'$'}$name'${"\"".repeat(3)}
}
}
""".trimIndent()
}
| subprojects/kotlin-dsl/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/DelegatedGradlePropertiesIntegrationTest.kt | 2844441960 |
/**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.tasks
import com.pokegoapi.api.map.fort.Pokestop
import ink.abb.pogo.scraper.Bot
import ink.abb.pogo.scraper.Context
import ink.abb.pogo.scraper.Settings
import ink.abb.pogo.scraper.Task
import ink.abb.pogo.scraper.util.Log
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Task that handles catching pokemon, activating stops, and walking to a new target.
*/
class ProcessPokestops(var pokestops: MutableCollection<Pokestop>) : Task {
val refetchTime = TimeUnit.SECONDS.toMillis(30)
var lastFetch: Long = 0
private val lootTimeouts = HashMap<String, Long>()
var startPokestop: Pokestop? = null
override fun run(bot: Bot, ctx: Context, settings: Settings) {
var writeCampStatus = false
if (lastFetch + refetchTime < bot.api.currentTimeMillis()) {
writeCampStatus = true
lastFetch = bot.api.currentTimeMillis()
if (settings.allowLeaveStartArea) {
try {
val newStops = ctx.api.map.mapObjects.pokestops
if (newStops.size > 0) {
pokestops = newStops
}
} catch (e: Exception) {
// ignored failed request
}
}
}
val sortedPokestops = pokestops.sortedWith(Comparator { a, b ->
a.distance.compareTo(b.distance)
})
if (startPokestop == null)
startPokestop = sortedPokestops.first()
if (settings.lootPokestop) {
val loot = LootOneNearbyPokestop(sortedPokestops, lootTimeouts)
try {
bot.task(loot)
} catch (e: Exception) {
ctx.pauseWalking.set(false)
}
}
if (settings.campLurePokestop > 0 && !ctx.pokemonInventoryFullStatus.get() && settings.catchPokemon) {
val luresInRange = sortedPokestops.filter {
it.inRangeForLuredPokemon() && it.fortData.hasLureInfo()
}.size
if (luresInRange >= settings.campLurePokestop) {
if (writeCampStatus) {
Log.green("$luresInRange lure(s) in range, pausing")
}
return
}
}
val walk = Walk(sortedPokestops, lootTimeouts)
bot.task(walk)
}
}
| src/main/kotlin/ink/abb/pogo/scraper/tasks/ProcessPokestops.kt | 2364094796 |
/*
* 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.collection
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.State
import com.facebook.litho.Style
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.useState
import com.facebook.litho.view.onClick
import com.facebook.litho.widget.collection.LazyList
import com.facebook.litho.widget.collection.LazyListScope
class ModularCollectionKComponent : KComponent() {
override fun ComponentScope.render(): Component {
val nestedContentVisible = useState { true }
return LazyList {
addHeader()
addBody(nestedContentVisible)
addFooter()
}
}
private fun LazyListScope.addHeader() {
child(isSticky = true, component = Text("Header"))
}
private fun LazyListScope.addBody(nestedContentVisible: State<Boolean>) {
child(
Text(
"${if (nestedContentVisible.value) "-" else "+"} Body",
style = Style.onClick { nestedContentVisible.update(!nestedContentVisible.value) }))
if (nestedContentVisible.value) {
children(items = listOf(0, 1, 2, 3), id = { it }) { Text(" Nested Body Item $it") }
}
}
private fun LazyListScope.addFooter() {
child(Text("Footer"))
}
}
| sample/src/main/java/com/facebook/samples/litho/kotlin/collection/ModularCollectionKComponent.kt | 218550066 |
package io.dev.temperature
import io.dev.temperature.model.Temperature
import io.dev.temperature.model.TemperatureCodec
import io.dev.temperature.verticles.*
import io.vertx.core.AbstractVerticle
import io.vertx.core.DeploymentOptions
import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.system.exitProcess
class TemperatureApp : AbstractVerticle() {
override fun start() {
val serialPortConfig = config().getJsonObject("serialPort", JsonObject().put("path", "/tmp/foo"))
val serialPortPath = serialPortConfig.getString("path", "/tmp/foo")
vertx.eventBus().registerDefaultCodec(Temperature::class.java, TemperatureCodec())
vertx.deployVerticle(MessageParsingVerticle())
vertx.deployVerticle(ScheduleVerticle())
vertx.deployVerticle(InMemoryTemperatureRepository())
vertx.deployVerticle(SerialPortTemperatureVerticle(serialPortPath), {
when (it.succeeded()) {
true -> {
vertx.deployVerticle(RESTVerticle(), {
if (it.failed()) {
log.error("Failed to start REST Verticle", it.cause())
exitProcess(-3)
}
})
}
false -> {
log.error("Unable to start Serial Port Verticle :(", it.cause())
exitProcess(-2)
}
}
})
val deploymentOptionsoptions = DeploymentOptions().setWorker(true)
vertx.deployVerticle(SQLTemperatureRepository(), deploymentOptionsoptions)
}
}
val log: Logger = LoggerFactory.getLogger(TemperatureApp::class.java)
fun main(args: Array<String>) {
val vertx = Vertx.vertx()
vertx.deployVerticle(TemperatureApp(), {
if (it.succeeded()) {
log.info("!!! Started the Top Level Verticle !!! ")
} else {
log.error("!!! Couldn't start the Top Level Verticle", it.cause())
exitProcess(-1)
}
})
}
| temperature-sensor-and-rest/src/main/kotlin/io/dev/temperature/TemperatureApp.kt | 1659389410 |
/*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package compiler.parser.rule
class MisconfigurationException(message: String) : RuntimeException(message) | src/compiler/parser/rule/MisconfigurationException.kt | 2915374063 |
package net.yslibrary.monotweety.data.settings
data class Settings(
val notificationEnabled: Boolean,
val footerEnabled: Boolean,
val footerText: String,
val timelineAppEnabled: Boolean,
val timelineAppPackageName: String,
)
| data/src/main/java/net/yslibrary/monotweety/data/settings/Settings.kt | 2320694051 |
package com.eden.orchid.swiftdoc.swift.members
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.swiftdoc.swift.SwiftAttributes
import com.eden.orchid.swiftdoc.swift.SwiftMember
import com.eden.orchid.swiftdoc.swift.SwiftStatement
import org.json.JSONObject
class SwiftClassVar(context: OrchidContext, data: JSONObject, origin: SwiftStatement)
: SwiftMember(context, data, "classVar", origin),
SwiftAttributes {
override lateinit var attributes: List<String>
var name: String? = null
var type: String? = null
override fun init() {
super.init()
initAttributes(data)
name = data.optString("key.name")
type = data.optString("key.typename")
}
} | plugins/OrchidSwiftdoc/src/main/kotlin/com/eden/orchid/swiftdoc/swift/members/SwiftClassVar.kt | 2727506755 |
package com.eden.orchid.api.options.archetypes
import com.eden.orchid.api.options.OptionArchetype
import com.eden.orchid.api.options.annotations.Description
@Description(value = "Loads additional values from secure environment variables.", name = "Environment Variables")
class EnvironmentVariableArchetype : OptionArchetype {
override fun getOptions(target: Any, archetypeKey: String): Map<String, Any> {
val vars = System.getenv()
return vars as Map<String, Any>
}
}
| OrchidCore/src/main/kotlin/com/eden/orchid/api/options/archetypes/EnvironmentVariableArchetype.kt | 488761633 |
/*
* Copyright 2019 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.vase4kin.teamcityapp.filter_builds.view
import android.view.View
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.closeSoftKeyboard
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.github.vase4kin.teamcityapp.R
import com.github.vase4kin.teamcityapp.TeamCityApplication
import com.github.vase4kin.teamcityapp.api.TeamCityService
import com.github.vase4kin.teamcityapp.buildlist.api.Builds
import com.github.vase4kin.teamcityapp.dagger.components.AppComponent
import com.github.vase4kin.teamcityapp.dagger.components.RestApiComponent
import com.github.vase4kin.teamcityapp.dagger.modules.AppModule
import com.github.vase4kin.teamcityapp.dagger.modules.FakeTeamCityServiceImpl
import com.github.vase4kin.teamcityapp.dagger.modules.Mocks
import com.github.vase4kin.teamcityapp.dagger.modules.RestApiModule
import com.github.vase4kin.teamcityapp.helper.CustomIntentsTestRule
import com.github.vase4kin.teamcityapp.helper.TestUtils
import com.github.vase4kin.teamcityapp.helper.eq
import com.github.vase4kin.teamcityapp.home.view.HomeActivity
import com.github.vase4kin.teamcityapp.runbuild.api.Branch
import com.github.vase4kin.teamcityapp.runbuild.api.Branches
import io.reactivex.Single
import it.cosenonjaviste.daggermock.DaggerMockRule
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.instanceOf
import org.hamcrest.Matchers.not
import org.hamcrest.core.AllOf.allOf
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Matchers.anyString
import org.mockito.Mockito.`when`
import org.mockito.Mockito.verify
import org.mockito.Spy
import java.util.ArrayList
/**
* Tests for [FilterBuildsActivity]
*/
@RunWith(AndroidJUnit4::class)
class FilterBuildsActivityTest {
@JvmField
@Rule
val daggerRule: DaggerMockRule<RestApiComponent> =
DaggerMockRule(RestApiComponent::class.java, RestApiModule(Mocks.URL))
.addComponentDependency(
AppComponent::class.java,
AppModule(InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication)
)
.set { restApiComponent ->
val app =
InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication
app.setRestApiInjector(restApiComponent)
}
@JvmField
@Rule
val activityRule: CustomIntentsTestRule<HomeActivity> =
CustomIntentsTestRule(HomeActivity::class.java)
@Spy
private val teamCityService: TeamCityService = FakeTeamCityServiceImpl()
companion object {
@JvmStatic
@BeforeClass
fun disableOnboarding() {
TestUtils.disableOnboarding()
}
}
@Before
fun setUp() {
val app =
InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication
app.restApiInjector.sharedUserStorage().clearAll()
app.restApiInjector.sharedUserStorage()
.saveGuestUserAccountAndSetItAsActive(Mocks.URL, false)
`when`(
teamCityService.listBuilds(
anyString(),
anyString()
)
).thenReturn(Single.just(Builds(0, emptyList())))
}
@Test
fun testUserCanFilterBuildsWithDefaultFilter() {
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Click on filter fab
onView(withId(R.id.fab_filter)).perform(click())
// Check data was loaded with new filter
verify(teamCityService).listBuilds(
anyString(),
eq("state:any,canceled:any,failedToStart:any,branch:default:any,personal:false,pinned:false,count:10")
)
}
@Test
fun testUserCanFilterBuildsByPinned() {
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Click on pin switcher
onView(withId(R.id.switcher_is_pinned)).perform(click())
// Click on filter fab
onView(withId(R.id.fab_filter)).perform(click())
// Check data was loaded with new filter
verify(teamCityService).listBuilds(
anyString(),
eq("state:any,canceled:any,failedToStart:any,branch:default:any,personal:false,pinned:true,count:10")
)
}
@Test
fun testUserCanFilterBuildsByPersonal() {
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Click on pin switcher
onView(withId(R.id.switcher_is_personal)).perform(click())
// Click on filter fab
onView(withId(R.id.fab_filter)).perform(click())
// Check data was loaded with new filter
verify<TeamCityService>(teamCityService).listBuilds(
anyString(),
eq("state:any,canceled:any,failedToStart:any,branch:default:any,personal:true,pinned:false,count:10")
)
}
@Test
fun testUserCanFilterBuildsByBranch() {
// Prepare mocks
val branches = ArrayList<Branch>()
branches.add(Branch("dev1"))
branches.add(Branch("dev2"))
`when`(teamCityService.listBranches(anyString())).thenReturn(Single.just(Branches(branches)))
// Starting the activity
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Choose branch from autocomplete and verify it is appeared
onView(withId(R.id.autocomplete_branches))
.perform(typeText("dev"))
onData(allOf(`is`(instanceOf<Any>(String::class.java)), `is`<String>("dev1")))
.inRoot(RootMatchers.withDecorView(not(`is`<View>(activityRule.activity.window.decorView))))
.perform(click())
onView(withText("dev1")).perform(click(), closeSoftKeyboard())
// Click on filter fab
onView(withId(R.id.fab_filter)).perform(click())
// Check data was loaded with new filter
verify(teamCityService).listBuilds(
anyString(),
eq("state:any,canceled:any,failedToStart:any,branch:name:dev1,personal:false,pinned:false,count:10")
)
}
@Test
fun testPinnedSwitchIsGoneWhenQueuedFilterIsChosen() {
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Check switchers are shown
onView(withId(R.id.switcher_is_pinned)).check(matches(isDisplayed()))
onView(withId(R.id.switcher_is_personal)).check(matches(isDisplayed()))
// Click on filter chooser
onView(withId(R.id.chooser_filter)).perform(click())
// Filter by queued
onView(withText("Queued")).perform(click())
// Check switchers
onView(withId(R.id.switcher_is_pinned)).check(matches(not(isDisplayed())))
onView(withId(R.id.divider_switcher_is_pinned)).check(matches(not(isDisplayed())))
onView(withId(R.id.switcher_is_personal)).check(matches(isDisplayed()))
}
@Test
fun testUserCanFilterBuildsWithSuccessFilter() {
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Click on filter chooser
onView(withId(R.id.chooser_filter)).perform(click())
// Filter by success
onView(withText("Success")).perform(click())
// Click on filter fab
onView(withId(R.id.fab_filter)).perform(click())
// Check data was loaded with new filter
verify(teamCityService).listBuilds(
anyString(),
eq("status:SUCCESS,branch:default:any,personal:false,pinned:false,count:10")
)
}
@Test
fun testUserCanFilterBuildsWithFailedFilter() {
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Click on filter chooser
onView(withId(R.id.chooser_filter)).perform(click())
// Filter by success
onView(withText("Failed")).perform(click())
// Click on filter fab
onView(withId(R.id.fab_filter)).perform(click())
// Check data was loaded with new filter
verify(teamCityService).listBuilds(
anyString(),
eq("status:FAILURE,branch:default:any,personal:false,pinned:false,count:10")
)
}
@Test
fun testUserCanFilterBuildsWithFailedServerErrorFilter() {
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Click on filter chooser
onView(withId(R.id.chooser_filter)).perform(click())
// Filter by success
onView(withText("Failed due server error")).perform(click())
// Click on filter fab
onView(withId(R.id.fab_filter)).perform(click())
// Check data was loaded with new filter
verify(teamCityService).listBuilds(
anyString(),
eq("status:ERROR,branch:default:any,personal:false,pinned:false,count:10")
)
}
@Test
fun testUserCanFilterBuildsWithCancelledFilter() {
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Click on filter chooser
onView(withId(R.id.chooser_filter)).perform(click())
// Filter by success
onView(withText("Cancelled")).perform(click())
// Click on filter fab
onView(withId(R.id.fab_filter)).perform(click())
// Check data was loaded with new filter
verify(teamCityService).listBuilds(
anyString(),
eq("canceled:true,branch:default:any,personal:false,pinned:false,count:10")
)
}
@Test
fun testUserCanFilterBuildsWithFailedToStartFilter() {
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Click on filter chooser
onView(withId(R.id.chooser_filter)).perform(click())
// Filter by success
onView(withText("Failed to start")).perform(click())
// Click on filter fab
onView(withId(R.id.fab_filter)).perform(click())
// Check data was loaded with new filter
verify(teamCityService).listBuilds(
anyString(),
eq("failedToStart:true,branch:default:any,personal:false,pinned:false,count:10")
)
}
@Test
fun testUserCanFilterBuildsWithRunningFilter() {
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Click on filter chooser
onView(withId(R.id.chooser_filter)).perform(click())
// Filter by success
onView(withText("Running")).perform(click())
// Click on filter fab
onView(withId(R.id.fab_filter)).perform(click())
// Check data was loaded with new filter
verify(teamCityService).listBuilds(
anyString(),
eq("running:true,branch:default:any,personal:false,pinned:false")
)
}
@Test
fun testUserCanFilterBuildsWithQueuedFilter() {
activityRule.launchActivity(null)
// Open build type
onView(withText("build type"))
.perform(click())
// Pressing filter builds toolbar item
onView(withId(R.id.filter_builds))
.perform(click())
// Click on filter chooser
onView(withId(R.id.chooser_filter)).perform(click())
// Filter by success
onView(withText("Queued")).perform(click())
// Click on filter fab
onView(withId(R.id.fab_filter)).perform(click())
// Check data was loaded with new filter
verify(teamCityService).listBuilds(
anyString(),
eq("state:queued,branch:default:any,personal:false,pinned:any")
)
}
}
| app/src/androidTest/java/com/github/vase4kin/teamcityapp/filter_builds/view/FilterBuildsActivityTest.kt | 2510209883 |
package content.params
import matchers.content.*
import org.jetbrains.dokka.Platform
import org.jetbrains.dokka.model.DFunction
import org.jetbrains.dokka.model.dfs
import org.jetbrains.dokka.model.doc.DocumentationNode
import org.jetbrains.dokka.model.doc.Param
import org.jetbrains.dokka.model.doc.Text
import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.jetbrains.dokka.pages.*
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.junit.jupiter.api.Test
import utils.*
import kotlin.test.assertEquals
class ContentForParamsTest : BaseAbstractTest() {
private val testConfiguration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/")
analysisPlatform = "jvm"
}
}
}
@Test
fun `undocumented function`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
|
|fun function(abc: String) {
| println(abc)
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(), "", "", emptySet(), "function", null, "abc" to ParamAttributes(
emptyMap(),
emptySet(),
"String"
)
)
}
}
}
}
}
}
}
@Test
fun `undocumented parameter`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
| /**
| * comment to function
| */
|fun function(abc: String) {
| println(abc)
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(),
"",
"",
emptySet(),
"function",
null,
"abc" to ParamAttributes(emptyMap(), emptySet(), "String")
)
}
after {
group { pWrapped("comment to function") }
}
}
}
}
}
}
}
@Test
fun `undocumented parameter and other tags without function comment`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
| /**
| * @author Kordyjan
| * @author Woolfy
| * @since 0.11
| */
|fun function(abc: String) {
| println(abc)
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(),
"",
"",
emptySet(),
"function",
null,
"abc" to ParamAttributes(emptyMap(), emptySet(), "String")
)
}
after {
unnamedTag("Author") {
comment {
+"Kordyjan"
}
comment {
+"Woolfy"
}
}
unnamedTag("Since") { comment { +"0.11" } }
}
}
}
}
}
}
}
@Test
fun `multiple authors`() {
testInline(
"""
|/src/main/java/sample/DocGenProcessor.java
|package sample;
|/**
| * Annotation processor which visits all classes.
| *
| * @author [email protected] (Googler 1)
| * @author [email protected] (Googler 2)
| */
| public class DocGenProcessor { }
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val classPage =
module.children.single { it.name == "sample" }.children.single { it.name == "DocGenProcessor" } as ContentPage
classPage.content.assertNode {
group {
header { +"DocGenProcessor" }
platformHinted {
group {
skipAllNotMatching() //Signature
}
group {
group {
group {
+"Annotation processor which visits all classes."
}
}
}
group {
header(4) { +"Author" }
comment { +"[email protected] (Googler 1)" }
comment { +"[email protected] (Googler 2)" }
}
}
}
skipAllNotMatching()
}
}
}
}
@Test
fun `author delimetered by space`() {
testInline(
"""
|/src/main/java/sample/DocGenProcessor.java
|package sample;
|/**
| * Annotation processor which visits all classes.
| *
| * @author Marcin Aman Senior
| */
| public class DocGenProcessor { }
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val classPage =
module.children.single { it.name == "sample" }.children.single { it.name == "DocGenProcessor" } as ContentPage
classPage.content.assertNode {
group {
header { +"DocGenProcessor" }
platformHinted {
group {
skipAllNotMatching() //Signature
}
group {
group {
group {
+"Annotation processor which visits all classes."
}
}
}
group {
header(4) { +"Author" }
comment { +"Marcin Aman Senior" }
}
}
}
skipAllNotMatching()
}
}
}
}
@Test
fun `deprecated with multiple links inside`() {
testInline(
"""
|/src/main/java/sample/DocGenProcessor.java
|package sample;
|/**
| * Return the target fragment set by {@link #setTargetFragment} or {@link
| * #setTargetFragment}.
| *
| * @deprecated Instead of using a target fragment to pass results, the fragment requesting a
| * result should use
| * {@link java.util.HashMap#containsKey(java.lang.Object) FragmentManager#setFragmentResult(String, Bundle)} to deliver results to
| * {@link java.util.HashMap#containsKey(java.lang.Object)
| * FragmentResultListener} instances registered by other fragments via
| * {@link java.util.HashMap#containsKey(java.lang.Object) FragmentManager#setFragmentResultListener(String, LifecycleOwner,
| * FragmentResultListener)}.
| */
| public class DocGenProcessor {
| public String setTargetFragment(){
| return "";
| }
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val classPage =
module.children.single { it.name == "sample" }.children.single { it.name == "DocGenProcessor" } as ContentPage
classPage.content.assertNode {
group {
header { +"DocGenProcessor" }
platformHinted {
group {
skipAllNotMatching() //Signature
}
group {
comment {
+"Return the target fragment set by "
link { +"setTargetFragment" }
+" or "
link { +"setTargetFragment" }
+"."
}
}
group {
header(4) { +"Deprecated" }
comment {
+"Instead of using a target fragment to pass results, the fragment requesting a result should use "
link { +"FragmentManager#setFragmentResult(String, Bundle)" }
+" to deliver results to "
link { +"FragmentResultListener" }
+" instances registered by other fragments via "
link { +"FragmentManager#setFragmentResultListener(String, LifecycleOwner, FragmentResultListener)" }
+"."
}
}
}
}
skipAllNotMatching()
}
}
}
}
@Test
fun `deprecated with an html link in multiple lines`() {
testInline(
"""
|/src/main/java/sample/DocGenProcessor.java
|package sample;
|/**
| * @deprecated Use
| * <a href="https://developer.android.com/guide/navigation/navigation-swipe-view ">
| * TabLayout and ViewPager</a> instead.
| */
| public class DocGenProcessor { }
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val classPage =
module.children.single { it.name == "sample" }.children.single { it.name == "DocGenProcessor" } as ContentPage
classPage.content.assertNode {
group {
header { +"DocGenProcessor" }
platformHinted {
group {
skipAllNotMatching() //Signature
}
group {
header(4) { +"Deprecated" }
comment {
+"Use "
link { +"TabLayout and ViewPager" }
+" instead."
}
}
}
}
skipAllNotMatching()
}
}
}
}
@Test
fun `deprecated with an multiple inline links`() {
testInline(
"""
|/src/main/java/sample/DocGenProcessor.java
|package sample;
|/**
| * FragmentManagerNonConfig stores the retained instance fragments across
| * activity recreation events.
| *
| * <p>Apps should treat objects of this type as opaque, returned by
| * and passed to the state save and restore process for fragments in
| * {@link java.util.HashMap#containsKey(java.lang.Object) FragmentController#retainNestedNonConfig()} and
| * {@link java.util.HashMap#containsKey(java.lang.Object) FragmentController#restoreAllState(Parcelable, FragmentManagerNonConfig)}.</p>
| *
| * @deprecated Have your {@link java.util.HashMap FragmentHostCallback} implement
| * {@link java.util.HashMap } to automatically retain the Fragment's
| * non configuration state.
| */
| public class DocGenProcessor { }
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val classPage =
module.children.single { it.name == "sample" }.children.single { it.name == "DocGenProcessor" } as ContentPage
classPage.content.assertNode {
group {
header { +"DocGenProcessor" }
platformHinted {
group {
skipAllNotMatching() //Signature
}
group {
comment {
group {
+"FragmentManagerNonConfig stores the retained instance fragments across activity recreation events. "
}
group {
+"Apps should treat objects of this type as opaque, returned by and passed to the state save and restore process for fragments in "
link { +"FragmentController#retainNestedNonConfig()" }
+" and "
link { +"FragmentController#restoreAllState(Parcelable, FragmentManagerNonConfig)" }
+"."
}
}
}
group {
header(4) { +"Deprecated" }
comment {
+"Have your "
link { +"FragmentHostCallback" }
+" implement "
link { +"java.util.HashMap" }
+" to automatically retain the Fragment's non configuration state."
}
}
}
}
skipAllNotMatching()
}
}
}
}
@Test
fun `multiline throws with comment`() {
testInline(
"""
|/src/main/java/sample/DocGenProcessor.java
|package sample;
| public class DocGenProcessor {
| /**
| * a normal comment
| *
| * @throws java.lang.IllegalStateException if the Dialog has not yet been created (before
| * onCreateDialog) or has been destroyed (after onDestroyView).
| * @throws java.lang.RuntimeException when {@link java.util.HashMap#containsKey(java.lang.Object) Hash
| * Map} doesn't contain value.
| */
| public static void sample(){ }
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val functionPage =
module.children.single { it.name == "sample" }.children.single { it.name == "DocGenProcessor" }.children.single { it.name == "sample" } as ContentPage
functionPage.content.assertNode {
group {
header(1) { +"sample" }
}
divergentGroup {
divergentInstance {
divergent {
skipAllNotMatching() //Signature
}
after {
group { pWrapped("a normal comment") }
header(4) { +"Throws" }
table {
group {
group {
link { +"IllegalStateException" }
}
comment { +"if the Dialog has not yet been created (before onCreateDialog) or has been destroyed (after onDestroyView)." }
}
group {
group {
link { +"RuntimeException" }
}
comment {
+"when "
link { +"Hash Map" }
+" doesn't contain value."
}
}
}
}
}
}
}
}
}
}
@Test
fun `multiline kotlin throws with comment`() {
testInline(
"""
|/src/main/kotlin/sample/sample.kt
|package sample;
| /**
| * a normal comment
| *
| * @throws java.lang.IllegalStateException if the Dialog has not yet been created (before
| * onCreateDialog) or has been destroyed (after onDestroyView).
| * @exception RuntimeException when [Hash Map][java.util.HashMap.containsKey] doesn't contain value.
| */
| fun sample(){ }
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val functionPage =
module.children.single { it.name == "sample" }.children.single { it.name == "sample" } as ContentPage
functionPage.content.assertNode {
group {
header(1) { +"sample" }
}
divergentGroup {
divergentInstance {
divergent {
skipAllNotMatching() //Signature
}
after {
group { pWrapped("a normal comment") }
header(4) { +"Throws" }
table {
group {
group {
link {
check {
assertEquals(
"java.lang/IllegalStateException///PointingToDeclaration/",
(this as ContentDRILink).address.toString()
)
}
+"IllegalStateException"
}
}
comment { +"if the Dialog has not yet been created (before onCreateDialog) or has been destroyed (after onDestroyView)." }
}
group {
group {
link {
check {
assertEquals(
"java.lang/RuntimeException///PointingToDeclaration/",
(this as ContentDRILink).address.toString()
)
}
+"RuntimeException"
}
}
comment {
+"when "
link { +"Hash Map" }
+" doesn't contain value."
}
}
}
}
}
}
}
}
}
}
@Test
fun `should display fully qualified throws name for unresolved class`() {
testInline(
"""
|/src/main/kotlin/sample/sample.kt
|package sample;
| /**
| * a normal comment
| *
| * @throws com.example.UnknownException description for non-resolved
| */
| fun sample(){ }
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val functionPage =
module.children.single { it.name == "sample" }.children.single { it.name == "sample" } as ContentPage
functionPage.content.assertNode {
group {
header(1) { +"sample" }
}
divergentGroup {
divergentInstance {
divergent {
skipAllNotMatching() //Signature
}
after {
group { pWrapped("a normal comment") }
header(4) { +"Throws" }
table {
group {
group {
+"com.example.UnknownException"
}
comment { +"description for non-resolved" }
}
}
}
}
}
}
}
}
}
@Test
fun `multiline throws where exception is not in the same line as description`() {
testInline(
"""
|/src/main/java/sample/DocGenProcessor.java
|package sample;
| public class DocGenProcessor {
| /**
| * a normal comment
| *
| * @throws java.lang.IllegalStateException if the Dialog has not yet been created (before
| * onCreateDialog) or has been destroyed (after onDestroyView).
| * @throws java.lang.RuntimeException when
| * {@link java.util.HashMap#containsKey(java.lang.Object) Hash
| * Map}
| * doesn't contain value.
| */
| public static void sample(){ }
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val functionPage =
module.children.single { it.name == "sample" }.children.single { it.name == "DocGenProcessor" }.children.single { it.name == "sample" } as ContentPage
functionPage.content.assertNode {
group {
header(1) { +"sample" }
}
divergentGroup {
divergentInstance {
divergent {
skipAllNotMatching() //Signature
}
after {
group { pWrapped("a normal comment") }
header(4) { +"Throws" }
table {
group {
group {
link {
check {
assertEquals(
"java.lang/IllegalStateException///PointingToDeclaration/",
(this as ContentDRILink).address.toString()
)
}
+"IllegalStateException"
}
}
comment { +"if the Dialog has not yet been created (before onCreateDialog) or has been destroyed (after onDestroyView)." }
}
group {
group {
link {
check {
assertEquals(
"java.lang/RuntimeException///PointingToDeclaration/",
(this as ContentDRILink).address.toString()
)
}
+"RuntimeException"
}
}
comment {
+"when "
link { +"Hash Map" }
+" doesn't contain value."
}
}
}
}
}
}
}
}
}
}
@Test
fun `documentation splitted in 2 using enters`() {
testInline(
"""
|/src/main/java/sample/DocGenProcessor.java
|package sample;
|/**
| * Listener for handling fragment results.
| *
| * This object should be passed to
| * {@link java.util.HashMap#containsKey(java.lang.Object) FragmentManager#setFragmentResultListener(String, LifecycleOwner, FragmentResultListener)}
| * and it will listen for results with the same key that are passed into
| * {@link java.util.HashMap#containsKey(java.lang.Object) FragmentManager#setFragmentResult(String, Bundle)}.
| *
| */
| public class DocGenProcessor { }
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val classPage =
module.children.single { it.name == "sample" }.children.single { it.name == "DocGenProcessor" } as ContentPage
classPage.content.assertNode {
group {
header { +"DocGenProcessor" }
platformHinted {
group {
skipAllNotMatching() //Signature
}
group {
comment {
+"Listener for handling fragment results. This object should be passed to "
link { +"FragmentManager#setFragmentResultListener(String, LifecycleOwner, FragmentResultListener)" }
+" and it will listen for results with the same key that are passed into "
link { +"FragmentManager#setFragmentResult(String, Bundle)" }
+"."
}
}
}
}
skipAllNotMatching()
}
}
}
}
@Test
fun `multiline return tag with param`() {
testInline(
"""
|/src/main/java/sample/DocGenProcessor.java
|package sample;
| public class DocGenProcessor {
| /**
| * a normal comment
| *
| * @param testParam Sample description for test param that has a type of {@link java.lang.String String}
| * @return empty string when
| * {@link java.util.HashMap#containsKey(java.lang.Object) Hash
| * Map}
| * doesn't contain value.
| */
| public static String sample(String testParam){
| return "";
| }
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val functionPage =
module.children.single { it.name == "sample" }.children.single { it.name == "DocGenProcessor" }.children.single { it.name == "sample" } as ContentPage
functionPage.content.assertNode {
group {
header(1) { +"sample" }
}
divergentGroup {
divergentInstance {
divergent {
skipAllNotMatching() //Signature
}
after {
group { pWrapped("a normal comment") }
group {
header(4) { +"Return" }
comment {
+"empty string when "
link { +"Hash Map" }
+" doesn't contain value."
}
}
header(4) { +"Parameters" }
group {
table {
group {
+"testParam"
comment {
+"Sample description for test param that has a type of "
link { +"String" }
}
}
}
}
}
}
}
}
}
}
}
@Test
fun `return tag in kotlin`() {
testInline(
"""
|/src/main/kotlin/sample/sample.kt
|package sample;
| /**
| * a normal comment
| *
| * @return empty string when [Hash Map](java.util.HashMap.containsKey) doesn't contain value.
| *
| */
|fun sample(): String {
| return ""
| }
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val functionPage =
module.children.single { it.name == "sample" }.children.single { it.name == "sample" } as ContentPage
functionPage.content.assertNode {
group {
header(1) { +"sample" }
}
divergentGroup {
divergentInstance {
divergent {
skipAllNotMatching() //Signature
}
after {
group { pWrapped("a normal comment") }
group {
header(4) { +"Return" }
comment {
+"empty string when "
link { +"Hash Map" }
+" doesn't contain value."
}
}
}
}
}
}
}
}
}
@Test
fun `list with links and description`() {
testInline(
"""
|/src/main/java/sample/DocGenProcessor.java
|package sample;
|/**
| * Static library support version of the framework's {@link java.lang.String}.
| * Used to write apps that run on platforms prior to Android 3.0. When running
| * on Android 3.0 or above, this implementation is still used; it does not try
| * to switch to the framework's implementation. See the framework {@link java.lang.String}
| * documentation for a class overview.
| *
| * <p>The main differences when using this support version instead of the framework version are:
| * <ul>
| * <li>Your activity must extend {@link java.lang.String FragmentActivity}
| * <li>You must call {@link java.util.HashMap#containsKey(java.lang.Object) FragmentActivity#getSupportFragmentManager} to get the
| * {@link java.util.HashMap FragmentManager}
| * </ul>
| *
| */
|public class DocGenProcessor { }
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val classPage =
module.children.single { it.name == "sample" }.children.single { it.name == "DocGenProcessor" } as ContentPage
classPage.content.assertNode {
group {
header { +"DocGenProcessor" }
platformHinted {
group {
skipAllNotMatching() //Signature
}
group {
comment {
group {
+"Static library support version of the framework's "
link { +"java.lang.String" }
+". Used to write apps that run on platforms prior to Android 3.0."
+" When running on Android 3.0 or above, this implementation is still used; it does not try to switch to the framework's implementation. See the framework "
link { +"java.lang.String" }
+" documentation for a class overview. " //TODO this probably shouldnt have a space but it is minor
}
group {
+"The main differences when using this support version instead of the framework version are: "
}
list {
group {
+"Your activity must extend "
link { +"FragmentActivity" }
}
group {
+"You must call "
link { +"FragmentActivity#getSupportFragmentManager" }
+" to get the "
link { +"FragmentManager" }
}
}
}
}
}
}
skipAllNotMatching()
}
}
}
}
@Test
fun `documentation with table`() {
testInline(
"""
|/src/main/java/sample/DocGenProcessor.java
|package sample;
|/**
| * <table>
| * <caption>List of supported types</caption>
| * <tr>
| * <td>cell 11</td> <td>cell 21</td>
| * </tr>
| * <tr>
| * <td>cell 12</td> <td>cell 22</td>
| * </tr>
| * </table>
| */
| public class DocGenProcessor { }
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val classPage =
module.children.single { it.name == "sample" }.children.single { it.name == "DocGenProcessor" } as ContentPage
classPage.content.assertNode {
group {
header { +"DocGenProcessor" }
platformHinted {
group {
skipAllNotMatching() //Signature
}
comment {
table {
check {
caption!!.assertNode {
caption {
+"List of supported types"
}
}
}
group {
group {
+"cell 11"
}
group {
+"cell 21"
}
}
group {
group {
+"cell 12"
}
group {
+"cell 22"
}
}
}
}
}
}
skipAllNotMatching()
}
}
}
}
@Test
fun `undocumented parameter and other tags`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
| /**
| * comment to function
| * @author Kordyjan
| * @since 0.11
| */
|fun function(abc: String) {
| println(abc)
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(),
"",
"",
emptySet(),
"function",
null,
"abc" to ParamAttributes(emptyMap(), emptySet(), "String")
)
}
after {
group { pWrapped("comment to function") }
unnamedTag("Author") { comment { +"Kordyjan" } }
unnamedTag("Since") { comment { +"0.11" } }
}
}
}
}
}
}
}
@Test
fun `single parameter`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
| /**
| * comment to function
| * @param abc comment to param
| */
|fun function(abc: String) {
| println(abc)
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(),
"",
"",
emptySet(),
"function",
null,
"abc" to ParamAttributes(emptyMap(), emptySet(), "String")
)
}
after {
group { pWrapped("comment to function") }
header(4) { +"Parameters" }
group {
table {
group {
+"abc"
check {
val textStyles = children.single { it is ContentText }.style
assertContains(textStyles, TextStyle.Underlined)
}
group { group { +"comment to param" } }
}
}
}
}
}
}
}
}
}
}
@Test
fun `multiple parameters`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
| /**
| * comment to function
| * @param first comment to first param
| * @param second comment to second param
| * @param[third] comment to third param
| */
|fun function(first: String, second: Int, third: Double) {
| println(abc)
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(), "", "", emptySet(), "function", null,
"first" to ParamAttributes(emptyMap(), emptySet(), "String"),
"second" to ParamAttributes(emptyMap(), emptySet(), "Int"),
"third" to ParamAttributes(emptyMap(), emptySet(), "Double")
)
}
after {
group { group { group { +"comment to function" } } }
header(4) { +"Parameters" }
group {
table {
group {
+"first"
check {
val textStyles = children.single { it is ContentText }.style
assertContains(textStyles, TextStyle.Underlined)
}
group { group { +"comment to first param" } }
}
group {
+"second"
check {
val textStyles = children.single { it is ContentText }.style
assertContains(textStyles, TextStyle.Underlined)
}
group { group { +"comment to second param" } }
}
group {
+"third"
check {
val textStyles = children.single { it is ContentText }.style
assertContains(textStyles, TextStyle.Underlined)
}
group { group { +"comment to third param" } }
}
}
}
}
}
}
}
}
}
}
@Test
fun `multiple parameters with not natural order`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
| /**
| * comment to function
| * @param c comment to c param
| * @param b comment to b param
| * @param[a] comment to a param
| */
|fun function(c: String, b: Int, a: Double) {
| println(abc)
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(), "", "", emptySet(), "function", null,
"c" to ParamAttributes(emptyMap(), emptySet(), "String"),
"b" to ParamAttributes(emptyMap(), emptySet(), "Int"),
"a" to ParamAttributes(emptyMap(), emptySet(), "Double")
)
}
after {
group { group { group { +"comment to function" } } }
header(4) { +"Parameters" }
group {
table {
group {
+"c"
group { group { +"comment to c param" } }
}
group {
+"b"
group { group { +"comment to b param" } }
}
group {
+"a"
group { group { +"comment to a param" } }
}
}
}
}
}
}
}
}
}
}
@Test
fun `multiple parameters without function description`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
| /**
| * @param first comment to first param
| * @param second comment to second param
| * @param[third] comment to third param
| */
|fun function(first: String, second: Int, third: Double) {
| println(abc)
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(), "", "", emptySet(), "function", null,
"first" to ParamAttributes(emptyMap(), emptySet(), "String"),
"second" to ParamAttributes(emptyMap(), emptySet(), "Int"),
"third" to ParamAttributes(emptyMap(), emptySet(), "Double")
)
}
after {
header(4) { +"Parameters" }
group {
table {
group {
+"first"
group { group { +"comment to first param" } }
}
group {
+"second"
group { group { +"comment to second param" } }
}
group {
+"third"
group { group { +"comment to third param" } }
}
}
}
}
}
}
}
}
}
}
@Test
fun `function with receiver`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
| /**
| * comment to function
| * @param abc comment to param
| * @receiver comment to receiver
| */
|fun String.function(abc: String) {
| println(abc)
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignatureWithReceiver(
emptyMap(),
"",
"",
emptySet(),
"String",
"function",
null,
"abc" to ParamAttributes(emptyMap(), emptySet(), "String")
)
}
after {
group { pWrapped("comment to function") }
group {
header(4) { +"Receiver" }
pWrapped("comment to receiver")
}
header(4) { +"Parameters" }
group {
table {
group {
+"abc"
group { group { +"comment to param" } }
}
}
}
}
}
}
}
}
}
}
@Test
fun `missing parameter documentation`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
| /**
| * comment to function
| * @param first comment to first param
| * @param[third] comment to third param
| */
|fun function(first: String, second: Int, third: Double) {
| println(abc)
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(), "", "", emptySet(), "function", null,
"first" to ParamAttributes(emptyMap(), emptySet(), "String"),
"second" to ParamAttributes(emptyMap(), emptySet(), "Int"),
"third" to ParamAttributes(emptyMap(), emptySet(), "Double")
)
}
after {
group { group { group { +"comment to function" } } }
header(4) { +"Parameters" }
group {
table {
group {
+"first"
group { group { +"comment to first param" } }
}
group {
+"third"
group { group { +"comment to third param" } }
}
}
}
}
}
}
}
}
}
}
@Test
fun `parameters mixed with other tags`() {
testInline(
"""
|/src/main/kotlin/test/source.kt
|package test
| /**
| * comment to function
| * @param first comment to first param
| * @author Kordyjan
| * @param second comment to second param
| * @since 0.11
| * @param[third] comment to third param
| */
|fun function(first: String, second: Int, third: Double) {
| println(abc)
|}
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val page = module.children.single { it.name == "test" }
.children.single { it.name == "function" } as ContentPage
page.content.assertNode {
group {
header(1) { +"function" }
}
divergentGroup {
divergentInstance {
divergent {
bareSignature(
emptyMap(), "", "", emptySet(), "function", null,
"first" to ParamAttributes(emptyMap(), emptySet(), "String"),
"second" to ParamAttributes(emptyMap(), emptySet(), "Int"),
"third" to ParamAttributes(emptyMap(), emptySet(), "Double")
)
}
after {
group { pWrapped("comment to function") }
unnamedTag("Author") { comment { +"Kordyjan" } }
unnamedTag("Since") { comment { +"0.11" } }
header(4) { +"Parameters" }
group {
table {
group {
+"first"
group { group { +"comment to first param" } }
}
group {
+"second"
group { group { +"comment to second param" } }
}
group {
+"third"
group { group { +"comment to third param" } }
}
}
}
}
}
}
}
}
}
}
@Test
fun javaDocCommentWithDocumentedParameters() {
testInline(
"""
|/src/main/java/test/Main.java
|package test
| public class Main {
|
| /**
| * comment to function
| * @param first comment to first param
| * @param second comment to second param
| */
| public void sample(String first, String second) {
|
| }
| }
""".trimIndent(), testConfiguration
) {
pagesTransformationStage = { module ->
val sampleFunction = module.dfs {
it is MemberPageNode && it.dri.first()
.toString() == "test/Main/sample/#java.lang.String#java.lang.String/PointingToDeclaration/"
} as MemberPageNode
val forJvm = (sampleFunction.documentables.firstOrNull() as DFunction).parameters.mapNotNull {
val jvm = it.documentation.keys.first { it.analysisPlatform == Platform.jvm }
it.documentation[jvm]
}
assert(forJvm.size == 2)
val (first, second) = forJvm.map { it.paramsDescription() }
assert(first == "comment to first param")
assert(second == "comment to second param")
}
}
}
private fun DocumentationNode.paramsDescription(): String =
children.firstIsInstanceOrNull<Param>()?.root?.children?.first()?.children?.firstIsInstanceOrNull<Text>()?.body.orEmpty()
}
| plugins/base/src/test/kotlin/content/params/ContentForParamsTest.kt | 846238534 |
package org.jetbrains.dokka.base.resolvers.local
import org.jetbrains.dokka.pages.RootPageNode
fun interface LocationProviderFactory {
fun getLocationProvider(pageNode: RootPageNode): LocationProvider
}
| plugins/base/src/main/kotlin/resolvers/local/LocationProviderFactory.kt | 4206446354 |
/*
* Copyright 2022 Google LLC
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* 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.
*/
// TEST PROCESSOR: InheritedTypeAliasProcessor
// EXPECTED:
// sub: arg :INVARIANT Float
// sub: prop :INVARIANT Int
// super: arg :INVARIANT Float
// super: prop :INVARIANT Int
// END
typealias AliasMap<T> = Map<String, T>
typealias AliasFun<T> = (T) -> Double
interface Sub : Super
interface Super {
val prop: AliasMap<Int>
fun foo(arg: AliasFun<Float>)
}
| test-utils/testData/api/inheritedTypeAlias.kt | 2324861771 |
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.ElementManipulators
import com.intellij.psi.LiteralTextEscaper
import com.intellij.psi.PsiElement
import com.vladsch.flexmark.util.sequence.BasedSequence
import com.vladsch.md.nav.actions.handlers.util.PsiEditAdjustment
import com.vladsch.md.nav.parser.MdFactoryContext
import com.vladsch.md.nav.psi.util.MdElementFactory
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.plugin.util.ifElse
import com.vladsch.plugin.util.toRich
open class MdInlineGitLabMathImpl(node: ASTNode) : MdInlineStyleCompositeImpl(node), MdInlineGitLabMath {
override fun getContent(): String {
return contentElement?.text ?: ""
}
override fun getContentElement(): ASTNode? {
return node.findChildByType(MdTypes.GITLAB_MATH_TEXT)
}
override fun setContent(content: String): PsiElement {
// REFACTOR: factor out common part. This is almost identical to MdInlineCodeImpl
val containingFile = containingFile
val editContext = PsiEditAdjustment(containingFile)
val paragraph = MdPsiImplUtil.getParagraphParent(this) ?: this
val indentPrefix = MdPsiImplUtil.getBlockPrefixes(paragraph, null, editContext).finalizePrefixes(editContext).childContPrefix
var convertedContent = content
val newElementText = getElementText(MdFactoryContext(this), convertedContent).toRich()
if (indentPrefix.isNotEmpty) {
// re-indent if there is an indent ahead of our content on the line
if (indentPrefix.isNotEmpty) {
val contentLines = newElementText.split("\n", 0, BasedSequence.SPLIT_INCLUDE_DELIMS)
val sb = StringBuilder()
val firstIndentPrefix = BasedSequence.EMPTY
var useIndentPrefix = firstIndentPrefix
for (line in contentLines) {
sb.append(useIndentPrefix)
useIndentPrefix = indentPrefix
sb.append(line)
}
convertedContent = sb.toString()
}
// we have no choice but to replace the element textually, because with all possible prefix combinations
// it will not parse, so we have to create a file with contents of the top parent element that contains us
// the easiest way is to just take the whole PsiFile and replace our content in it
val file = containingFile.originalFile
val fileText: String = file.text
val changedText = fileText.substring(0, this.node.startOffset) +
convertedContent +
fileText.substring(this.node.startOffset + this.textLength, fileText.length)
val factoryContext = MdFactoryContext(this)
val newFile = MdElementFactory.createFile(factoryContext, changedText)
val psiElement = newFile.findElementAt(node.startOffset)?.parent
if (psiElement is MdInlineGitLabMath) {
// NOTE: replacing the content node leaves the element unchanged and preserves the injection all the time
// if the element is changed, injection may be lost and will have to be initiated again by the user.
node.replaceAllChildrenToChildrenOf(psiElement.getNode())
}
} else {
MdPsiImplUtil.setContent(this, convertedContent)
}
return this
}
override fun getContentRange(inDocument: Boolean): TextRange {
val contentElement = contentElement
return if (contentElement != null) inDocument.ifElse(contentElement.textRange, TextRange(0, contentElement.textLength)).shiftRight(2)
else TextRange.EMPTY_RANGE
}
override fun isValidHost(): Boolean {
return isValid
}
override fun updateText(text: String): MdPsiLanguageInjectionHost? {
return ElementManipulators.handleContentChange(this, text)
}
override fun createLiteralTextEscaper(): LiteralTextEscaper<out MdPsiLanguageInjectionHost?> {
return object : LiteralTextEscaper<MdPsiLanguageInjectionHost?>(this) {
override fun decode(rangeInsideHost: TextRange, outChars: StringBuilder): Boolean {
outChars.append(rangeInsideHost.shiftLeft(2).substring((myHost as MdInlineGitLabMathImpl).contentElement!!.text))
return true
}
override fun getOffsetInHost(offsetInDecoded: Int, rangeInsideHost: TextRange): Int {
return rangeInsideHost.startOffset + offsetInDecoded
}
override fun getRelevantTextRange(): TextRange {
return contentRange
}
override fun isOneLine(): Boolean {
return true
}
}
}
companion object {
fun getElementText(factoryContext: MdFactoryContext, content: String): String {
return "\$`$content`\$"
}
}
}
| src/main/java/com/vladsch/md/nav/psi/element/MdInlineGitLabMathImpl.kt | 3571723381 |
/*
* Copyright (c) 2015-2019 Vladimir Schneider <[email protected]>, all rights reserved.
*
* This code is private property of the copyright holder and cannot be used without
* having obtained a license or prior written permission of the copyright holder.
*
* 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.vladsch.md.nav
import com.intellij.ide.BrowserUtil
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.notification.Notification
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.notification.impl.NotificationsManagerImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.Anchor
import com.intellij.openapi.actionSystem.Constraints
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.BaseComponent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.colors.EditorColorsListener
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.wm.IdeFrame
import com.intellij.openapi.wm.WindowManager
import com.intellij.ui.BalloonLayoutData
import com.intellij.ui.awt.RelativePoint
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.vladsch.md.nav.actions.ide.CopyFileBareNameProvider
import com.vladsch.md.nav.actions.ide.CopyFileNameProvider
import com.vladsch.md.nav.actions.ide.CopyFilePathWithLineNumbersProvider
import com.vladsch.md.nav.actions.ide.CopyUpsourceFilePathWithLineNumbersProvider
import com.vladsch.md.nav.highlighter.MdSyntaxHighlighter
import com.vladsch.md.nav.settings.MdApplicationSettings
import com.vladsch.md.nav.settings.MdDocumentSettings
import com.vladsch.md.nav.settings.SettingsChangedListener
import com.vladsch.md.nav.settings.api.MdExtensionInfoProvider
import com.vladsch.md.nav.util.DynamicNotificationText
import com.vladsch.md.nav.util.MdCancelableJobScheduler
import com.vladsch.plugin.util.*
import org.jetbrains.jps.service.SharedThreadPool
import java.awt.Color
import java.awt.Point
import java.util.function.Consumer
import javax.swing.UIManager
class MdPlugin : BaseComponent, Disposable {
private var projectLoaded = false
private val myNotificationRunnable: DelayedConsumerRunner<Project> = DelayedConsumerRunner()
var startupDocumentSettings: MdDocumentSettings = MdDocumentSettings()
private set
// var startupDebugSettings: MdDebugSettings = MdDebugSettings()
// private set
private val restartRequiredChecker = object : AppRestartRequiredCheckerBase<MdApplicationSettings>(MdBundle.message("settings.restart-required.title")) {
override fun getRestartNeededReasons(settings: MdApplicationSettings): Long {
val fullHighlightChanged = startupDocumentSettings.fullHighlightCombinations != settings.documentSettings.fullHighlightCombinations
return fullHighlightChanged.ifElse(1L, 0L)
}
}
override fun initComponent() {
val appSettings = MdApplicationSettings.instance
ApplicationManager.getApplication().invokeLater {
SharedThreadPool.getInstance().submit {
try {
val actionManager = ActionManager.getInstance()
// document options for copy path to turn visibility of these on, all are off by default
val action0 = CopyUpsourceFilePathWithLineNumbersProvider()
actionManager.registerAction("CopyUpsourceFilePathWithLineNumbersProvider", action0)
val action1 = CopyFilePathWithLineNumbersProvider()
actionManager.registerAction("MdCopyPathWithSelectionLineNumbers", action1)
val action2 = CopyFileNameProvider()
actionManager.registerAction("MdCopyPathFileName", action2)
val action3 = CopyFileBareNameProvider()
actionManager.registerAction("MdCopyCopyPathBareName", action3)
val referenceAction = actionManager.getAction("CopyFileReference")
if (referenceAction is DefaultActionGroup) {
referenceAction.add(action0, Constraints(Anchor.AFTER, "CopyPathWithLineNumber"))
referenceAction.add(action1, Constraints(Anchor.AFTER, "CopyPathWithLineNumber"))
referenceAction.add(action2, Constraints(Anchor.AFTER, "CopyPathWithLineNumber"))
referenceAction.add(action3, Constraints(Anchor.AFTER, "CopyPathWithLineNumber"))
}
} catch (e: Throwable) {
}
}
}
// make a copy so we can inform when it changes
val documentSettings = appSettings.documentSettings
startupDocumentSettings = MdDocumentSettings(documentSettings)
// startupDebugSettings = MdDebugSettings(appSettings.debugSettings)
LOG.info("Initializing Component: fullHighlights = ${documentSettings.fullHighlightCombinations}")
// QUERY: do we still need to init default project settings just in case they don't exist?
// MdProjectSettings.getInstance(ProjectManager.getInstance().defaultProject)
val settingsChangedListener = SettingsChangedListener { applicationSettings ->
ApplicationManager.getApplication().invokeLater {
informRestartIfNeeded(applicationSettings)
}
}
val settingsConnection = ApplicationManager.getApplication().messageBus.connect(this as Disposable)
settingsConnection.subscribe(SettingsChangedListener.TOPIC, settingsChangedListener)
@Suppress("DEPRECATION")
EditorColorsManager.getInstance().addEditorColorsListener(EditorColorsListener {
MdSyntaxHighlighter.computeMergedAttributes(true)
}, this)
// do initialization after first project is loaded
myNotificationRunnable.addRunnable {
AwtRunnable.schedule(MdCancelableJobScheduler.getInstance(), "New Features Notification", 1000) {
// To Show if enhanced plugin is not installed
val showAvailable = MdExtensionInfoProvider.EP_NAME.extensions.all {
if (it is MdEnhancedExtensionInfoProvider) it.showEnhancedPluginAvailable()
else true
}
if (showAvailable) {
notifyLicensedAvailableUpdate(fullProductVersion, MdResourceResolverImpl.instance.getResourceFileContent("/com/vladsch/md/nav/FEATURES.html"))
}
}
}
}
private fun informRestartIfNeeded(applicationSettings: MdApplicationSettings) {
restartRequiredChecker.informRestartIfNeeded(applicationSettings)
}
override fun dispose() {
}
fun projectLoaded(project: Project) {
if (!projectLoaded) {
projectLoaded = true
fullProductVersion // load version
myNotificationRunnable.runAll(project)
// allow extensions to perform when first project is loaded
MdExtensionInfoProvider.EP_NAME.extensions.forEach {
if (it is MdEnhancedExtensionInfoProvider) it.projectLoaded(project)
}
}
}
private fun addHtmlColors(dynamicText: DynamicNotificationText): DynamicNotificationText {
val isDarkUITheme = UIUtil.isUnderDarcula()
val enhColor = if (isDarkUITheme) "#B0A8E6" else "#6106A5"
val buyColor = if (isDarkUITheme) "#F0A8D4" else "#C02080"
val specialsColor = if (isDarkUITheme) "#A4EBC5" else "#04964F"
val linkColor = (UIManager.getColor("link.foreground") ?: Color(0x589df6)).toHtmlString()
return dynamicText.addText("[[ENHANCED]]") { enhColor }
.addText("[[BUY]]") { buyColor }
.addText("[[SPECIALS]]") { specialsColor }
.addText("[[LINK]]") { linkColor }
}
private fun addCommonLinks(dynamicText: DynamicNotificationText): DynamicNotificationText {
val settings = MdApplicationSettings.instance.getLocalState()
return dynamicText
.addLink(":DISABLE_ENHANCED") {
settings.wasShownSettings.licensedAvailable = true
it.expire()
}
.addLink(":BUY") { BrowserUtil.browse("https://vladsch.com/product/markdown-navigator/buy") }
.addLink(":TRY") { BrowserUtil.browse("https://vladsch.com/product/markdown-navigator/try") }
.addLink(":NAME_CHANGE") { BrowserUtil.browse("https://github.com/vsch/idea-multimarkdown/wiki/Settings-Affected-by-Plugin-Name-Change") }
.addLink(":SPECIALS") { BrowserUtil.browse("https://vladsch.com/product/markdown-navigator/specials") }
.addLink(":FEATURES") { BrowserUtil.browse("https://vladsch.com/product/markdown-navigator") }
.addLink(":REFERRALS") { BrowserUtil.browse("https://vladsch.com/product/markdown-navigator/referrals") }
.addLink(":VERSION") { BrowserUtil.browse("https://github.com/vsch/idea-multimarkdown/blob/master/VERSION.md") }
}
private fun showFullNotification(project: Project?, notification: Notification) {
val runnable = Consumer<IdeFrame> { frame ->
val bounds = frame.component.bounds
val target = RelativePoint(Point(bounds.x + bounds.width, 0))
var handled = false
try {
val balloon = NotificationsManagerImpl.createBalloon(frame, notification, true, true, BalloonLayoutData.fullContent(), { })
balloon.show(target, Balloon.Position.atRight)
handled = true
} catch (e: NoSuchMethodError) {
} catch (e: NoClassDefFoundError) {
} catch (e: NoSuchFieldError) {
}
if (!handled) {
try {
val layoutData = BalloonLayoutData()
try {
layoutData.groupId = ""
layoutData.showSettingButton = false
} catch (e: NoSuchFieldError) {
}
layoutData.showFullContent = true
val layoutDataRef = Ref(layoutData)
val balloon = NotificationsManagerImpl.createBalloon(frame, notification, true, true, layoutDataRef, { })
balloon.show(target, Balloon.Position.atRight)
} catch (e: NoSuchMethodError) {
// use normal balloons
notification.notify(project)
} catch (e: NoSuchFieldError) {
// use normal balloons
notification.notify(project)
} catch (e: NoClassDefFoundError) {
// use normal balloons
notification.notify(project)
}
}
}
if (project != null) {
if (project.isDisposed) return
val frame = WindowManager.getInstance().getIdeFrame(project)
if (frame != null) {
runnable.accept(frame)
return
}
}
var delayedRun: (project: Project) -> Unit = {}
delayedRun = {
if (!it.isDisposed) {
val frame = WindowManager.getInstance().getIdeFrame(it)
if (frame != null) {
runnable.accept(frame)
} else {
// reschedule for a bit later
AwtRunnable.schedule(MdCancelableJobScheduler.getInstance(), "New Features Notification", 1000) {
delayedRun.invoke(it)
}
}
}
}
myNotificationRunnable.addRunnable(delayedRun)
}
private fun notifyLicensedAvailableUpdate(currentVersion: String, html: String) {
val settings = MdApplicationSettings.instance.getLocalState()
if (settings.wasShownSettings.lastLicensedAvailableVersion != currentVersion) {
val notificationType = NotificationType.INFORMATION
settings.wasShownSettings.licensedAvailable = true
settings.wasShownSettings.lastLicensedAvailableVersion = currentVersion
val issueNotificationGroup = PluginNotifications.NOTIFICATION_GROUP_UPDATE
val title = MdBundle.message("plugin.licensed-available.notification.title", productDisplayName, currentVersion)
val content = html.replace("<ul", String.format("<ul style=\"margin-left: %dpx\"", JBUI.scale(10)))
val dynamicText = DynamicNotificationText()
addHtmlColors(dynamicText)
addCommonLinks(dynamicText)
val listener = NotificationListener { notification, hyperlinkEvent ->
if (hyperlinkEvent.url == null) {
val link = hyperlinkEvent.description
dynamicText.linkAction(notification, link)
} else {
BrowserUtil.browse(hyperlinkEvent.url.toString())
}
}
val messageText = dynamicText.replaceText(content)
val notification = issueNotificationGroup.createNotification(title, messageText, notificationType, listener) //.notify(null)
showFullNotification(null, notification)
}
}
override fun disposeComponent() {
// empty
}
override fun getComponentName(): String {
return this.javaClass.name
}
fun getLogger(): Logger {
return LOG
}
interface MdEnhancedExtensionInfoProvider : MdExtensionInfoProvider {
fun showEnhancedPluginAvailable(): Boolean
fun projectLoaded(project: Project)
}
companion object {
private const val PLUGIN_ID = "com.vladsch.idea.multimarkdown"
val LOG: Logger by lazy { Logger.getInstance(PLUGIN_ID) }
const val siteURL: String = "https://vladsch.com"
const val productPrefixURL: String = "/product/markdown-navigator"
const val altProductPrefixURL: String = "/product/multimarkdown"
const val patchRelease: String = "$siteURL$productPrefixURL/patch-release"
const val eapRelease: String = "$siteURL$productPrefixURL/eap-release"
const val altPatchRelease: String = "$siteURL$altProductPrefixURL/patch-release"
const val altEapRelease: String = "$siteURL$altProductPrefixURL/eap-release"
const val jbLegacyRelease: String = "https://plugins.jetbrains.com/plugins/LEGACY/7896"
const val jbLegacyEapRelease: String = "https://plugins.jetbrains.com/plugins/LEGACY-EAP/7896"
const val jbEapRelease: String = "https://plugins.jetbrains.com/plugins/EAP/7896"
const val PREVIEW_STYLESHEET_LAYOUT: String = "/com/vladsch/md/nav/layout.css"
const val PREVIEW_STYLESHEET_LIGHT: String = "/com/vladsch/md/nav/default.css"
const val PREVIEW_STYLESHEET_DARK: String = "/com/vladsch/md/nav/darcula.css"
const val PREVIEW_FX_STYLESHEET_LAYOUT: String = "/com/vladsch/md/nav/layout-fx.css"
const val PREVIEW_FX_STYLESHEET_LIGHT: String = "/com/vladsch/md/nav/default-fx.css"
const val PREVIEW_FX_STYLESHEET_DARK: String = "/com/vladsch/md/nav/darcula-fx.css"
const val PREVIEW_FX_JS: String = "/com/vladsch/md/nav/markdown-navigator.js"
const val PREVIEW_FX_HLJS_STYLESHEET_LIGHT: String = "/com/vladsch/md/nav/hljs-default.css"
const val PREVIEW_FX_HLJS_STYLESHEET_DARK: String = "/com/vladsch/md/nav/hljs-darcula.css"
const val PREVIEW_FX_PRISM_JS_STYLESHEET_LIGHT: String = "/com/vladsch/md/nav/prism-default.css"
const val PREVIEW_FX_PRISM_JS_STYLESHEET_DARK: String = "/com/vladsch/md/nav/prism-darcula.css"
const val PREVIEW_FX_HIGHLIGHT_JS: String = "/com/vladsch/md/nav/highlight.pack.js"
const val PREVIEW_FX_PRISM_JS: String = "/com/vladsch/md/nav/prism.pack.js"
const val PREVIEW_TASKITEMS_FONT: String = "/com/vladsch/md/nav/taskitems.ttf"
const val PREVIEW_NOTOMONO_REGULAR_FONT: String = "/com/vladsch/md/nav/noto/NotoMono-Regular.ttf"
const val PREVIEW_NOTOSANS_BOLD_FONT: String = "/com/vladsch/md/nav/noto/NotoSans-Bold.ttf"
const val PREVIEW_NOTOSANS_BOLDITALIC_FONT: String = "/com/vladsch/md/nav/noto/NotoSans-BoldItalic.ttf"
const val PREVIEW_NOTOSANS_ITALIC_FONT: String = "/com/vladsch/md/nav/noto/NotoSans-Italic.ttf"
const val PREVIEW_NOTOSANS_REGULAR_FONT: String = "/com/vladsch/md/nav/noto/NotoSans-Regular.ttf"
const val PREVIEW_NOTOSERIF_BOLD_FONT: String = "/com/vladsch/md/nav/noto/NotoSerif-Bold.ttf"
const val PREVIEW_NOTOSERIF_BOLDITALIC_FONT: String = "/com/vladsch/md/nav/noto/NotoSerif-BoldItalic.ttf"
const val PREVIEW_NOTOSERIF_ITALIC_FONT: String = "/com/vladsch/md/nav/noto/NotoSerif-Italic.ttf"
const val PREVIEW_NOTOSERIF_REGULAR_FONT: String = "/com/vladsch/md/nav/noto/NotoSerif-Regular.ttf"
const val PREVIEW_GITHUB_COLLAPSE_MARKDOWN_JS: String = "/com/vladsch/md/nav/github-collapse-markdown.js"
const val PREVIEW_GITHUB_COLLAPSE_IN_COMMENT_JS: String = "/com/vladsch/md/nav/github-collapse-in-comment.user.original.js"
const val PREVIEW_GITHUB_COLLAPSE_LIGHT: String = "/com/vladsch/md/nav/github-collapse.css"
const val PREVIEW_GITHUB_COLLAPSE_DARK: String = "/com/vladsch/md/nav/github-collapse.css"
const val TASK_ITEM: String = "/icons/svg/application-undone-task-list-item.svg"
const val TASK_ITEM_DARK: String = "/icons/svg/application-undone-task-list-item_dark.svg"
const val TASK_ITEM_DONE: String = "/icons/svg/application-done-task-list-item.svg"
const val TASK_ITEM_DONE_DARK: String = "/icons/svg/application-done-task-list-item_dark.svg"
const val productId: String = "idea-multimarkdown"
const val productDisplayName: String = "Markdown Navigator"
@JvmStatic
val pluginDescriptor: IdeaPluginDescriptor by lazy {
val plugins = PluginManagerCore.getPlugins()
var descriptor: IdeaPluginDescriptor? = null
for (plugin in plugins) {
if (PLUGIN_ID == plugin.pluginId.idString) {
descriptor = plugin
}
}
descriptor ?: throw IllegalStateException("Unexpected, plugin cannot find its own plugin descriptor")
// val pluginId = PluginId.findId(PLUGIN_ID)
// val pluginDescriptor = PluginManagerCore.getPlugin(pluginId)
// pluginDescriptor
}
@JvmStatic
fun getPluginDescriptor(pluginId: String): IdeaPluginDescriptor? {
val plugins = PluginManagerCore.getPlugins()
for (plugin in plugins) {
if (pluginId == plugin.pluginId.idString) {
return plugin
}
}
return null
}
@JvmStatic
val productVersion: String by lazy {
val pluginDescriptor = pluginDescriptor
val version = pluginDescriptor.version
// truncate version to 3 digits and if had more than 3 append .x, that way
// no separate product versions need to be created
val parts = version.split(delimiters = *charArrayOf('.'), limit = 4)
if (parts.size <= 3) {
version
} else {
val newVersion = parts.subList(0, 3).reduce { total, next -> "$total.$next" }
"$newVersion.x"
}
}
@JvmStatic
val fullProductVersion: String by lazy {
val pluginDescriptor = pluginDescriptor
pluginDescriptor.version
}
@JvmStatic
fun getPluginCustomPath(): String? {
val variants = arrayOf(PathManager.getHomePath(), PathManager.getPluginsPath())
for (variant in variants) {
val path = "$variant/$productId"
if (LocalFileSystem.getInstance().findFileByPath(path) != null) {
return path
}
}
return null
}
@JvmStatic
fun getPluginPath(): String? {
val variants = arrayOf(PathManager.getPluginsPath())
for (variant in variants) {
val path = "$variant/$productId"
if (LocalFileSystem.getInstance().findFileByPath(path) != null) {
return path
}
}
return null
}
@JvmStatic
val instance: MdPlugin
get() = ApplicationManager.getApplication().getComponent(MdPlugin::class.java) ?: throw IllegalStateException()
}
}
| src/main/java/com/vladsch/md/nav/MdPlugin.kt | 4075945204 |
/*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.browser.floating
import android.webkit.WebView
import androidx.fragment.app.FragmentActivity
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.unmockkAll
import io.mockk.verify
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.yobidashi.browser.block.AdRemover
import org.junit.After
import org.junit.Before
import org.junit.Test
class WebViewInitializerTest {
@InjectMockKs
private lateinit var webViewInitializer: WebViewInitializer
@MockK
private lateinit var preferenceApplier: PreferenceApplier
@MockK
private lateinit var viewModel: FloatingPreviewViewModel
@MockK
private lateinit var webView: WebView
@MockK
private lateinit var fragmentActivity: FragmentActivity
@Before
fun setUp() {
MockKAnnotations.init(this)
every { fragmentActivity.getAssets() }.returns(mockk())
every { webView.getContext() }.returns(fragmentActivity)
mockkObject(AdRemover)
every { AdRemover.make(any()) }.returns(mockk())
every { webView.setWebViewClient(any()) }.answers { Unit }
every { webView.setWebChromeClient(any()) }.answers { Unit }
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun invoke() {
webViewInitializer.invoke(webView)
verify(exactly = 1) { fragmentActivity.getAssets() }
verify(exactly = 1) { webView.getContext() }
verify(exactly = 1) { AdRemover.make(any()) }
verify(exactly = 1) { webView.setWebViewClient(any()) }
verify(exactly = 1) { webView.setWebChromeClient(any()) }
}
} | app/src/test/java/jp/toastkid/yobidashi/browser/floating/WebViewInitializerTest.kt | 3016698857 |
/*
* The MIT License
*
* Copyright 2015 Nathan Templon.
*
* 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.jupiter.europa.screen.dialog
import com.badlogic.gdx.Input
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.ui.*
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable
import com.badlogic.gdx.utils.Align
import com.jupiter.europa.EuropaGame
import com.jupiter.europa.scene2d.ui.EuropaButton
import com.jupiter.europa.scene2d.ui.EuropaButton.ClickEvent
import com.jupiter.europa.scene2d.ui.ObservableDialog
import com.jupiter.europa.screen.MainMenuScreen
import com.badlogic.gdx.scenes.scene2d.ui.List as GuiList
import com.badlogic.gdx.utils.Array as GdxArray
/**
* @author Nathan Templon
*/
public class LoadGameDialog : ObservableDialog(LoadGameDialog.DIALOG_NAME, LoadGameDialog.getDefaultSkin()) {
// Enumerations
public enum class LoadGameExitStates {
LOAD,
CANCEL
}
// Fields
private val skinInternal = getDefaultSkin()
private var mainTable: Table? = null
private var loadGameLabel: Label? = null
private var listTable: Table? = null
private var gameList: GuiList<String>? = null
private var gameListPane: ScrollPane? = null
private var buttonTableInternal: Table? = null
private var okButton: EuropaButton? = null
private var cancelButton: EuropaButton? = null
private var deleteButton: EuropaButton? = null
private var widthInternal: Float = 0.toFloat()
private var heightInternal: Float = 0.toFloat()
public var gameToLoad: String = ""
private set
public var exitState: LoadGameExitStates? = null
private set
private var confirmDeleteDialog: ConfirmDeleteSaveDialog? = null
init {
this.initComponents()
}
// Public Methods
override fun setSize(width: Float, height: Float) {
super.setSize(width, height)
if (this.confirmDeleteDialog != null) {
this.confirmDeleteDialog!!.setSize(width, this.heightInternal)
}
this.widthInternal = width
this.heightInternal = height
}
// Private Methods
private fun initComponents() {
this.mainTable = Table()
this.listTable = Table()
this.loadGameLabel = Label("Save Games", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<Label.LabelStyle>()))
this.gameList = GuiList(skinInternal.get<GuiList.ListStyle>(MainMenuScreen.DEFAULT_KEY, javaClass<GuiList.ListStyle>()))
this.gameList?.setItems(GdxArray(EuropaGame.game.getSaveNames()))
this.gameListPane = ScrollPane(this.gameList, skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<ScrollPane.ScrollPaneStyle>()))
this.listTable!!.add<ScrollPane>(this.gameListPane).pad(MainMenuScreen.LIST_WRAPPER_PADDING.toFloat()).expand().fill()
this.listTable!!.background(skinInternal.get(MainMenuScreen.LIST_BACKGROUND_KEY, javaClass<SpriteDrawable>()))
this.okButton = EuropaButton("Accept", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>()))
this.okButton!!.addClickListener { args -> this.onLoadClick(args) }
this.cancelButton = EuropaButton("Cancel", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>()))
this.cancelButton!!.addClickListener { args -> this.onCancelClick(args) }
this.deleteButton = EuropaButton("Delete", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>()))
this.deleteButton!!.addClickListener { args -> this.onDeleteClick(args) }
this.buttonTableInternal = Table()
this.buttonTableInternal!!.add<EuropaButton>(this.cancelButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right().expandX()
this.buttonTableInternal!!.add<EuropaButton>(this.deleteButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right()
this.buttonTableInternal!!.add<EuropaButton>(this.okButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right()
this.mainTable!!.pad(MainMenuScreen.TABLE_PADDING.toFloat())
this.mainTable!!.add<Label>(this.loadGameLabel).center().left()
this.mainTable!!.row()
this.mainTable!!.add<Table>(this.listTable).expandY().fill()
this.mainTable!!.row()
this.mainTable!!.add<Table>(this.buttonTableInternal).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).right().expandX().fillX()
this.mainTable!!.row()
this.mainTable!!.background(this.skinInternal.get(MainMenuScreen.DIALOG_BACKGROUND_KEY, javaClass<SpriteDrawable>()))
this.getContentTable().add<Table>(this.mainTable).center().expandY().fillY().width(MainMenuScreen.DIALOG_WIDTH.toFloat())
}
private fun onLoadClick(event: ClickEvent) {
this.gameToLoad = this.gameList!!.getSelected().toString()
this.exitState = LoadGameExitStates.LOAD
this.hide()
}
private fun onCancelClick(event: ClickEvent) {
this.gameToLoad = ""
this.exitState = LoadGameExitStates.CANCEL
this.hide()
}
private fun onDeleteClick(event: ClickEvent) {
this.confirmDeleteDialog = ConfirmDeleteSaveDialog(this.gameList!!.getSelected().toString(), this.skinInternal)
this.confirmDeleteDialog!!.addDialogListener({ args -> this.onConfirmDeleteSaveDialogClose(args) }, ObservableDialog.DialogEvents.HIDDEN)
this.confirmDeleteDialog!!.show(this.getStage())
this.confirmDeleteDialog!!.setSize(this.widthInternal, this.heightInternal)
}
private fun onConfirmDeleteSaveDialogClose(args: ObservableDialog.DialogEventArgs) {
if (this.confirmDeleteDialog!!.exitState === ConfirmDeleteSaveDialog.ConfirmDeleteExitStates.DELETE) {
EuropaGame.game.deleteSave(this.gameList!!.getSelected().toString())
this.gameList!!.setItems(GdxArray(EuropaGame.game.getSaveNames()))
this.okButton!!.setDisabled(EuropaGame.game.getSaveNames().size() == 0)
}
}
// Nested Classes
private class ConfirmDeleteSaveDialog(public val saveToDelete: String, private val skinInternal: Skin) : ObservableDialog(LoadGameDialog.ConfirmDeleteSaveDialog.DIALOG_NAME, skinInternal.get(MainMenuScreen.POPUP_DIALOG_STYLE_KEY, javaClass<Window.WindowStyle>())) {
// Enumerations
public enum class ConfirmDeleteExitStates {
DELETE,
CANCEL
}
private var titleLabelInternal: Label? = null
private var mainTable: Table? = null
private var yesButton: TextButton? = null
private var noButton: TextButton? = null
public var exitState: ConfirmDeleteExitStates? = null
private set
init {
this.initComponents()
}
// Public Methods
override fun setSize(width: Float, height: Float) {
super.setSize(width, height)
}
// Private Methods
private fun initComponents() {
this.titleLabelInternal = Label("Are you sure you want to delete the save game \"" + this.saveToDelete + "\"?", skinInternal.get(MainMenuScreen.INFO_STYLE_KEY, javaClass<Label.LabelStyle>()))
this.titleLabelInternal!!.setWrap(true)
this.titleLabelInternal!!.setAlignment(Align.center)
this.yesButton = TextButton("Yes", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>()))
this.yesButton!!.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
if (event!!.getButton() == Input.Buttons.LEFT && [email protected]!!.isDisabled()) {
[email protected]()
}
[email protected]!!.setChecked(false)
}
})
this.noButton = TextButton("No", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>()))
this.noButton!!.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
if (event!!.getButton() == Input.Buttons.LEFT && [email protected]!!.isDisabled()) {
[email protected]()
}
[email protected]!!.setChecked(false)
}
})
this.mainTable = Table()
this.mainTable!!.add<Label>(this.titleLabelInternal).colspan(2).width(MainMenuScreen.DIALOG_WIDTH.toFloat()).expandX().fillX()
this.mainTable!!.row()
this.mainTable!!.add<TextButton>(this.noButton).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).right()
this.mainTable!!.add<TextButton>(this.yesButton).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).left()
this.mainTable!!.padLeft(MainMenuScreen.TABLE_PADDING.toFloat())
this.mainTable!!.padRight(MainMenuScreen.TABLE_PADDING.toFloat())
this.mainTable!!.background(this.skinInternal.get(MainMenuScreen.POPUP_BACKGROUND_KEY, javaClass<SpriteDrawable>()))
this.getContentTable().add<Table>(this.mainTable).row()
}
private fun onYesButtonClick() {
this.exitState = ConfirmDeleteExitStates.DELETE
this.hide()
}
private fun onNoButtonClick() {
this.exitState = ConfirmDeleteExitStates.CANCEL
this.hide()
}
companion object {
// Constants
private val DIALOG_NAME = ""
}
}// Properties
companion object {
// Constants
private val DIALOG_NAME = ""
// Static Methods
private fun getDefaultSkin(): Skin {
return MainMenuScreen.createMainMenuSkin()
}
}
}
| core/src/com/jupiter/europa/screen/dialog/LoadGameDialog.kt | 1542087743 |
package curtains.internal
import android.os.Handler
import android.os.Looper
import android.view.FrameMetrics
import android.view.FrameMetrics.VSYNC_TIMESTAMP
import android.view.Window
import android.view.Window.OnFrameMetricsAvailableListener
import androidx.annotation.RequiresApi
import kotlin.LazyThreadSafetyMode.NONE
@RequiresApi(26)
internal class CurrentFrameMetricsListener(
private val frameTimeNanos: Long,
private val callback: (FrameMetrics) -> Unit
) : OnFrameMetricsAvailableListener {
private var removed = false
override fun onFrameMetricsAvailable(
window: Window,
frameMetrics: FrameMetrics,
dropCountSinceLastInvocation: Int
) {
if (!removed) {
removed = true
// We're on the frame metrics threads, the listener is stored in a non thread
// safe list so we need to jump back to the main thread to remove.
mainThreadHandler.post {
window.removeOnFrameMetricsAvailableListener(this)
}
}
val vsyncTimestamp = frameMetrics.getMetric(VSYNC_TIMESTAMP)
if (vsyncTimestamp == frameTimeNanos) {
callback(frameMetrics)
}
}
companion object {
private val mainThreadHandler by lazy(NONE) {
Handler(Looper.getMainLooper())
}
}
} | curtains/src/main/java/curtains/internal/CurrentFrameMetricsListener.kt | 131447820 |
package org.roylance.yaorm.services.postgres
import org.junit.Test
import org.roylance.yaorm.utilities.ConnectionUtilities
import org.roylance.yaorm.utilities.common.EntityMessageServiceTestUtilities
import org.roylance.yaorm.utilities.common.IEntityMessageServiceTest
class PostgresEntityMessageServiceTest: PostgresBase(), IEntityMessageServiceTest {
@Test
override fun simpleCreateTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.simpleCreateTest(buildEntityService())
}
@Test
override fun simpleLoadAndCreateTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.simpleLoadAndCreateTest(buildEntityService())
}
@Test
override fun complexLoadAndCreateTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.complexLoadAndCreateTest(buildEntityService())
}
@Test
override fun complexLoadAndCreate2Test() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.complexLoadAndCreate2Test(buildEntityService())
}
@Test
override fun complexLoadAndCreateProtectedTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.complexLoadAndCreateProtectedTest(buildEntityService())
}
@Test
override fun simpleGetTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.simpleGetTest(buildEntityService())
}
@Test
override fun bulkInsert1Test() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.bulkInsert1Test(buildEntityService())
}
@Test
override fun simplePassThroughWithReportTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.simplePassThroughWithReportTest(buildEntityService())
}
@Test
override fun simplePassThroughTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.simplePassThroughTest(buildEntityService())
}
@Test
override fun childAddThenDeleteTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.childAddThenDeleteTest(buildEntityService())
}
@Test
override fun verifyChildSerializedProperly() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.verifyChildSerializedProperly(buildEntityService())
}
@Test
override fun verifyChildChangedAfterMergeProperly() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.verifyChildChangedAfterMergeProperly(buildEntityService())
}
@Test
override fun additionalAddRemoveTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.additionalAddRemoveTest(buildEntityService())
}
@Test
override fun simplePersonTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.simplePersonTest(buildEntityService())
}
@Test
override fun simplePersonFriendsTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.simplePersonFriendsTest(buildEntityService())
}
@Test
override fun simpleDagTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.simpleDagTest(buildEntityService())
}
@Test
override fun moreComplexDagTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.moreComplexDagTest(buildEntityService())
}
@Test
override fun simpleUserAndUserDeviceTestTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.simpleUserAndUserDeviceTestTest(buildEntityService())
}
@Test
override fun simpleIndexTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.simpleIndexTest(buildEntityService())
}
@Test
override fun bulkInsertTest() {
if (!ConnectionUtilities.runPostgresTests()) {
return
}
EntityMessageServiceTestUtilities.bulkInsertTest(buildEntityService())
}
}
| yaorm/src/test/java/org/roylance/yaorm/services/postgres/PostgresEntityMessageServiceTest.kt | 1353194665 |
/*
* Copyright (c) 2017, Daniel Raniz Raneland
*/
package se.raneland.ffbe.ui
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.kotlin.readValue
import net.miginfocom.swing.MigLayout
import se.raneland.ffbe.state.MachineState
import se.raneland.ffbe.state.action.GameAction
import se.raneland.ffbe.state.transition.StateTransition
import se.raneland.ffbe.state.transition.TransitionTest
import java.awt.Dimension
import java.io.IOException
import java.io.InputStream
import java.time.Duration
import javax.swing.JButton
import javax.swing.JDialog
import javax.swing.JFrame
import javax.swing.JList
import javax.swing.JOptionPane
import javax.swing.JTextArea
val DESCRIPTIONS = listOf(
GraphDescription("Stage Grinding (Lapis Refresh)", """
Runs the second quest of any stage over and over again, refreshing NRG with lapis.
Navigate to any vortex or world stage and the script will repeatedly run the second stage.
""".trimIndent(),
"/machines/stage.yml"),
GraphDescription("Stage Grinding (No Lapis Refresh)", """
Runs the second quest of any stage over and over again, waiting for NRG to recover.
Navigate to any vortex or world stage and the script will repeatedly run the second stage.
""".trimIndent(),
"/machines/stage-no-lapis.yml"),
GraphDescription("Raid Summon", """
Performs Multi-Summon for raid coins over and over again
""".trimIndent(),
"/machines/raid-summon.yml")
)
data class StateGraph(val name: String, val description: String, val initialState: MachineState)
/**
* @author Raniz
* @since 2017-04-19.
*/
class GraphSelector(owner: JFrame) : JDialog(owner, "Select", true) {
val descriptions: JList<GraphDescription>
val descriptionField: JTextArea
val cancelButton: JButton
val okButton: JButton
var selectedGraph: StateGraph? = null
init {
layout = MigLayout(
"fill",
"[align left][align right]",
"[fill][grow 0, shrink 0]"
)
descriptions = JList(DESCRIPTIONS.toTypedArray())
descriptionField = JTextArea()
cancelButton = JButton("Cancel")
okButton = JButton("OK")
add(descriptions, "cell 0 0, growy")
add(descriptionField, "cell 1 0, grow")
add(cancelButton, "cell 0 1")
add(okButton, "cell 1 1")
descriptions.addListSelectionListener {
val selectedDescription = descriptions.selectedValue
if (selectedDescription == null) {
descriptionField.text = ""
okButton.isEnabled = false
} else {
descriptionField.text = selectedDescription.description
okButton.isEnabled = true
}
}
descriptions.selectedIndex = 0
descriptionField.lineWrap = true
descriptionField.isEditable = false
cancelButton.addActionListener {
selectedGraph = null
isVisible = false
}
okButton.addActionListener {
val selectedDescription = descriptions.selectedValue
if (selectedDescription == null) {
JOptionPane.showMessageDialog(this, "No graph selected", "Error", JOptionPane.ERROR_MESSAGE)
}
selectedGraph = getResource(selectedDescription.path).use {
if (it == null) {
JOptionPane.showMessageDialog(this, "Graph not found", "Error", JOptionPane.ERROR_MESSAGE)
return@use null
}
try {
return@use readStateGraph(it)
} catch(e: IOException) {
JOptionPane.showMessageDialog(this, "Could not read graph: ${e.message}", "Error", JOptionPane.ERROR_MESSAGE)
return@use null
}
}
if (selectedGraph != null) {
isVisible = false
}
}
pack()
minimumSize = Dimension(600, 600)
preferredSize = minimumSize
setLocationRelativeTo(owner)
}
fun select(): StateGraph? {
isVisible = true
return selectedGraph
}
}
data class GraphDescription(val name: String, val description: String, val path: String) {
override fun toString() = name
}
class DurationDeserialiser: JsonDeserializer<Duration>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Duration = Duration.parse(p.valueAsString)
}
private val yamlMapper = ObjectMapper(YAMLFactory()).apply {
findAndRegisterModules()
registerModule(object: SimpleModule() {
init {
addDeserializer(Duration::class.java, DurationDeserialiser())
}
})
enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
}
private fun getResource(path: String) = StringStateGraph::class.java.getResourceAsStream(path)
/**
* @author Raniz
* @since 2017-04-10.
*/
fun readStateGraph(yml: InputStream): StateGraph {
val graph = yamlMapper.readValue<StringStateGraph>(yml)
val states = graph.states.mapValues { (name, gState) -> MachineState(name, actions = gState.actions) }
graph.states.forEach { (name, gState) ->
val state = states[name]!!
gState.transitions
.map { (nextState, test) -> StateTransition(test, states[nextState] ?: error("State ${nextState} not found")) }
.forEach { state.transitions.add(it) }
}
return StateGraph(graph.name, graph.description, states[graph.initialState]!!)
}
data class StringStateGraph(val name: String, val description: String, val initialState: String, val states: Map<String, StringState>)
data class StringState(val transitions: Map<String, TransitionTest> = mapOf(), val actions: List<GameAction> = listOf())
| src/main/kotlin/se/raneland/ffbe/ui/GraphSelector.kt | 1557141529 |
Subsets and Splits