content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/* Telegram_Backup
* Copyright (C) 2016 Fabian Schlenz
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
package de.fabianonline.telegram_backup
import de.fabianonline.telegram_backup.DownloadProgressInterface
import de.fabianonline.telegram_backup.mediafilemanager.AbstractMediaFileManager
import de.fabianonline.telegram_backup.Utils
internal class CommandLineDownloadProgress : DownloadProgressInterface {
private var mediaCount = 0
private var i = 0
private var step = 0
private val chars = arrayOf("|", "/", "-", "\\")
override fun onMessageDownloadStart(count: Int, source: String?) {
i = 0
if (source == null) {
System.out.println("Downloading $count messages.")
} else {
System.out.println("Downloading " + count + " messages from " + source.anonymize())
}
}
override fun onMessageDownloaded(number: Int) {
i += number
print("..." + i)
}
override fun onMessageDownloadFinished() {
println(" done.")
}
override fun onMediaDownloadStart(count: Int) {
i = 0
mediaCount = count
println("Checking and downloading media.")
println("Legend:")
println("'V' - Video 'P' - Photo 'D' - Document")
println("'S' - Sticker 'A' - Audio 'G' - Geolocation")
println("'.' - Previously downloaded file 'e' - Empty file")
println("' ' - Ignored media type (weblinks or contacts, for example)")
println("'x' - File skipped (because of max_file_age or max_file_size)")
println("'!' - Download failed. Will be tried again at next run.")
println("" + count + " Files to check / download")
}
override fun onMediaDownloaded(file_manager: AbstractMediaFileManager) {
show(file_manager.letter.toUpperCase())
}
override fun onMediaFileDownloadStarted() {
step = 0
print(chars[step % chars.size])
}
override fun onMediaFileDownloadStep() {
step++
print("\b")
print(chars[step % chars.size])
}
override fun onMediaFileDownloadFinished() {
print("\b")
}
override fun onMediaDownloadedEmpty() {
show("e")
}
override fun onMediaAlreadyPresent(file_manager: AbstractMediaFileManager) {
show(".")
}
override fun onMediaSkipped() {
show("x")
}
override fun onMediaDownloadFinished() {
showNewLine()
println("Done.")
}
override fun onMediaFailed() = show("!")
private fun show(letter: String) {
print(letter)
i++
if (i % 100 == 0) showNewLine()
}
private fun showNewLine() {
println(" - $i/$mediaCount")
}
}
| src/main/kotlin/de/fabianonline/telegram_backup/CommandLineDownloadProgress.kt | 3036142290 |
/*
* Copyright 2014-2019 Julien Guerinet
*
* 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.guerinet.mymartlet.ui.wishlist
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import com.guerinet.mymartlet.R
import com.guerinet.mymartlet.model.CourseResult
import com.guerinet.mymartlet.model.Term
import com.guerinet.mymartlet.util.DayUtils
import com.guerinet.suitcase.ui.BaseListAdapter
import kotlinx.android.synthetic.main.item_course.view.*
/**
* Displays the list of courses in the user's wish list or after a course search
* @author Julien Guerinet
* @since 1.0.0
*/
internal class WishlistAdapter(private val empty: TextView) :
BaseListAdapter<CourseResult>(ItemCallback(), empty) {
val checkedCourses = mutableListOf<CourseResult>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CourseHolder =
CourseHolder(parent)
/**
* Updates the list of [courses] shown
*/
fun update(courses: List<CourseResult>) = submitList(courses.toMutableList())
/**
* Updates the list of courses shown for a [term] (null if no wishlist semesters available)
*/
fun update(term: Term?, courses: List<CourseResult>) {
if (term == null) {
// Hide all of the main content and show explanatory text if the currentTerm is null
empty.setText(R.string.registration_no_semesters)
submitList(mutableListOf())
return
}
submitList(courses.toMutableList())
}
internal inner class CourseHolder(parent: ViewGroup) :
BaseHolder<CourseResult>(parent, R.layout.item_course) {
override fun bind(position: Int, item: CourseResult) {
itemView.apply {
code.text = item.code
credits.text = context.getString(R.string.course_credits, item.credits.toString())
title.text = item.title
spots.visibility = View.VISIBLE
spots.text = context.getString(
R.string.registration_spots,
item.seatsRemaining.toString()
)
type.text = item.type
waitlistRemaining.visibility = View.VISIBLE
waitlistRemaining.text = context.getString(
R.string.registration_waitlist,
item.waitlistRemaining.toString()
)
days.text = DayUtils.getDayStrings(item.days)
hours.text = item.timeString
dates.text = item.dateString
checkBox.visibility = View.VISIBLE
// Remove any other listeners
checkBox.setOnCheckedChangeListener(null)
// Initial state
checkBox.isChecked = checkedCourses.contains(item)
checkBox.setOnCheckedChangeListener { _, checked ->
// If it becomes checked, add it to the list. If not, remove it
if (checked) {
checkedCourses.add(item)
} else {
checkedCourses.remove(item)
}
}
}
}
}
internal class ItemCallback : DiffUtil.ItemCallback<CourseResult>() {
override fun areItemsTheSame(oldItem: CourseResult, newItem: CourseResult): Boolean =
oldItem.term == newItem.term && oldItem.crn == newItem.crn
override fun areContentsTheSame(oldItem: CourseResult, newItem: CourseResult): Boolean =
oldItem == newItem
}
}
| app/src/main/java/ui/wishlist/WishlistAdapter.kt | 1372410552 |
class A
val <caret>foo = 1 | plugins/kotlin/idea/tests/testData/refactoring/moveHandler/declarations/topLevelVal/test.kt | 554995191 |
package com.chrhsmt.sisheng.debug
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.view.animation.AlphaAnimation
import android.widget.TextView
import android.widget.Toast
import com.chrhsmt.sisheng.*
import com.chrhsmt.sisheng.exception.AudioServiceException
import com.chrhsmt.sisheng.font.FontUtils
import com.chrhsmt.sisheng.network.RaspberryPi
import com.chrhsmt.sisheng.persistence.SDCardManager
import com.chrhsmt.sisheng.point.SimplePointCalculator
import com.chrhsmt.sisheng.ui.Chart
import com.chrhsmt.sisheng.ui.ScreenUtils
import com.github.mikephil.charting.charts.LineChart
import dmax.dialog.SpotsDialog
import kotlinx.android.synthetic.main.activity_analyze_compare.*
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException
class CompareActivity : AppCompatActivity() {
private val TAG: String = "CompareActivity"
private val PERMISSION_REQUEST_CODE = 1
private var service: AudioServiceInterface? = null
private var chart: Chart? = null
private var isRecording = false
enum class REIBUN_STATUS(val rawValue: Int) {
PREPARE(1),
NORMAL(2),
PLAYING(3),
RECODING(4),
ANALYZING(5),
ANALYZE_FINISH(6),
ANALYZE_ERROR_OCCUR(7),
}
private var nowStatus: REIBUN_STATUS = REIBUN_STATUS.NORMAL
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_analyze_compare)
// フルスクリーンにする
ScreenUtils.setFullScreen(this.window)
ScreenUtils.setScreenBackground(this)
// ピンイン、中文、英文の配置
val reibunInfo = ReibunInfo.getInstance(this)
txtDebugPinyin.text = ReibunInfo.replaceNewLine(reibunInfo.selectedItem!!.pinyin)
txtDebugChinese.text = ReibunInfo.replaceNewLine(reibunInfo.selectedItem!!.chinese)
// 音声再生、録画の準備
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO), PERMISSION_REQUEST_CODE)
//return
}
Settings.setDefaultValue(this, false)
// グラフの準備
this.chart = Chart()
this.chart!!.initChartView(this.findViewById<LineChart>(R.id.chart))
this.service = AudioService(this.chart!!, this)
// プログレスダイアログを表示する
val dialog = SpotsDialog(this@CompareActivity, getString(R.string.screen6_2), R.style.CustomSpotDialog)
dialog.show()
ScreenUtils.setFullScreen(dialog.window)
// お手本事前再生
nowStatus = REIBUN_STATUS.PREPARE
updateButtonStatus()
val fileName = reibunInfo.selectedItem!!.getMFSZExampleAudioFileName()
Settings.sampleAudioFileName = fileName
this.service!!.testPlay(fileName, playback = false, callback = object : Runnable {
override fun run() {
[email protected] {
// DEBUG解析
val analyzed = AnalyzedRecordedData.getSelected()
if (analyzed != null) {
val file = analyzed.file
val path= SDCardManager().copyAudioFile(file, this@CompareActivity)
[email protected]!!.debugTestPlay(file.name, path, callback = object : Runnable {
override fun run() {
val v2Point = [email protected]?.analyze()
val calcurator = SimplePointCalculator()
calcurator.setV1()
val v1Point = ([email protected] as AudioService)?.analyze(calcurator)
[email protected] {
([email protected] as? AudioService)?.addOtherChart(
v1Point?.analyzedFreqList,
"男女設定キャリブレーション",
Color.rgb(10, 255, 10))
([email protected] as? AudioService)?.addOtherChart(
v2Point?.analyzedFreqList,
"周波数キャリブレーション",
Color.rgb(255, 10, 255))
txtScore.text = String.format("Point: %s, F-Point: %s", v1Point?.score, v2Point?.score)
}
}
})
}
nowStatus = REIBUN_STATUS.NORMAL
updateButtonStatus()
dialog.dismiss()
}
}
})
// お手本再生
btnAnalyzeOtehon.setOnClickListener({
nowStatus = CompareActivity.REIBUN_STATUS.PLAYING
updateButtonStatus()
[email protected]!!.clearTestFrequencies()
[email protected]!!.clear()
val fileName = reibunInfo.selectedItem!!.getMFSZExampleAudioFileName()
Log.d(TAG, "Play " + fileName)
this.service!!.testPlay(fileName, callback = object : Runnable {
override fun run() {
Thread.sleep(300)
[email protected] {
// DEBUG解析
val analyzed = AnalyzedRecordedData.getSelected()
if (analyzed != null) {
val file = analyzed.file
val path= SDCardManager().copyAudioFile(file, this@CompareActivity)
[email protected]!!.clearFrequencies()
[email protected]!!.debugTestPlay(file.name, path, playback = true, callback = object : Runnable {
override fun run() {
val v2Point = [email protected]?.analyze()
val calcurator = SimplePointCalculator()
calcurator.setV1()
val v1Point = ([email protected] as AudioService)?.analyze(calcurator)
[email protected] {
([email protected] as? AudioService)?.addOtherChart(
v1Point?.analyzedFreqList,
"男女設定キャリブレーション",
Color.rgb(10, 255, 10))
([email protected] as? AudioService)?.addOtherChart(
v2Point?.analyzedFreqList,
"周波数キャリブレーション",
Color.rgb(255, 10, 255))
txtScore.text = String.format("Point: %s, F-Point: %s", v1Point?.score, v2Point?.score)
[email protected] = REIBUN_STATUS.NORMAL
[email protected]()
dialog.dismiss()
}
}
})
}
}
}
})
Thread(Runnable {
Thread.sleep(2000)
when ([email protected]!!.isRunning()) {
true -> Thread.sleep(1000)
}
[email protected] {
nowStatus = CompareActivity.REIBUN_STATUS.NORMAL
updateButtonStatus()
}
}).start()
})
// タイトル長押下された場合は、デバッグ画面に遷移する。
if (Settings.DEBUG_MODE) {
txtDebugReibun.setOnLongClickListener(View.OnLongClickListener {
val intent = Intent(this@CompareActivity, MainActivity::class.java)
startActivity(intent)
true
})
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
ScreenUtils.setFullScreen([email protected])
}
fun analyze() {
// プログレスダイアログを表示する
val dialog = SpotsDialog(this@CompareActivity, getString(R.string.screen6_3), R.style.CustomSpotDialog)
dialog.show()
FontUtils.changeFont(this@CompareActivity, dialog.findViewById<TextView>(dmax.dialog.R.id.dmax_spots_title), 1.1f)
ScreenUtils.setFullScreen(dialog.window)
// スレッドを開始する
Thread(Runnable {
Thread.sleep(1000 * 3)
try {
analyzeInner()
} catch (e: AudioServiceException) {
Log.e(TAG, e.message)
runOnUiThread {
dialog.dismiss()
txtDebugError.visibility = View.VISIBLE
nowStatus = REIBUN_STATUS.ANALYZE_ERROR_OCCUR
updateButtonStatus()
}
}
}).start()
}
@Throws(AudioServiceException::class)
private fun analyzeInner() {
val info = [email protected]!!.analyze()
// val info2 = [email protected]!!.analyze(FreqTransitionPointCalculator::class.qualifiedName!!)
// val info = [email protected]!!.analyze(NMultiplyLogarithmPointCalculator::class.qualifiedName!!)
if (info.success()) {
RaspberryPi().send(object: Callback {
override fun onFailure(call: Call?, e: IOException?) {
runOnUiThread {
Toast.makeText(this@CompareActivity, e!!.message, Toast.LENGTH_LONG).show()
}
}
override fun onResponse(call: Call?, response: Response?) {
runOnUiThread {
Toast.makeText(this@CompareActivity, response!!.body()!!.string(), Toast.LENGTH_LONG).show()
}
}
})
}
runOnUiThread {
nowStatus = REIBUN_STATUS.ANALYZE_FINISH
updateButtonStatus()
val intent = Intent(this@CompareActivity, ResultActivity::class.java)
intent.putExtra("result", info.success())
intent.putExtra("score", info.score.toString())
startActivity(intent)
overridePendingTransition(0, 0);
}
}
private fun updateButtonStatus() {
when (nowStatus) {
REIBUN_STATUS.PREPARE -> {
// 録音ボタン:録音可、再生ボタン:再生可
btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button)
btnAnalyzeOtehon.setEnabled(false)
}
REIBUN_STATUS.NORMAL -> {
// 録音ボタン:録音可、再生ボタン:再生可
btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button)
btnAnalyzeOtehon.setEnabled(true)
}
REIBUN_STATUS.PLAYING -> {
// 録音ボタン:利用不可、再生ボタン:再生中
btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button_press)
btnAnalyzeOtehon.setEnabled(false)
}
REIBUN_STATUS.RECODING -> {
// 録音ボタン:録音中、再生ボタン:再生不可
val alphaAnimation = AlphaAnimation(1.0f, 0.7f)
alphaAnimation.duration = 1000
alphaAnimation.fillAfter = true
alphaAnimation.repeatCount = -1
btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button_disable)
btnAnalyzeOtehon.setEnabled(false)
}
REIBUN_STATUS.ANALYZING -> {
// 録音ボタン:録音不可、再生ボタン:再生不可
btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button_disable)
btnAnalyzeOtehon.setEnabled(false)
}
REIBUN_STATUS.ANALYZE_FINISH -> {
//ボタン等のパーツの状態を戻さずに結果画面に遷移する想定。
//本画面に戻る時は、再度 onCreate から行われる想定。
}
REIBUN_STATUS.ANALYZE_ERROR_OCCUR -> {
// 録音ボタン:録音可、再生ボタン:再生不可
btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button_disable)
btnAnalyzeOtehon.setEnabled(false)
}
}
}
}
| app/src/main/java/com/chrhsmt/sisheng/debug/CompareActivity.kt | 2221138070 |
package com.jwu5.giphyapp.network.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import java.util.ArrayList
/**
* Created by Jiawei on 8/17/2017.
*/
class Datum {
@SerializedName("data")
@Expose
var data: ArrayList<GiphyModel>? = null
@SerializedName("pagination")
@Expose
var pagination: Pagination? = null
}
| app/src/main/java/com/jwu5/giphyapp/network/model/Datum.kt | 3609734619 |
package com.github.cdcalc.strategy
import com.github.cdcalc.configuration.EnvironmentConfiguration
import com.github.cdcalc.data.SemVer
import com.github.cdcalc.git.RefSemVer
import com.github.cdcalc.git.aheadOfTag
import com.github.cdcalc.git.processTags
import com.github.cdcalc.git.semVerTags
import org.eclipse.jgit.api.Git
fun versionForHotfixBranch(): (Git, EnvironmentConfiguration) -> SemVer {
return { git, branch ->
val semVer = SemVer.parse(branch.branch)
val tags = git.semVerTags()
.filterTagsDescending { versionFromTag ->
versionFromTag == semVer.copy(patch = Math.max(0, semVer.patch - 1))
}
val (_, ahead) = git.aheadOfTag(tags)
semVer.copy(identifiers = listOf("rc", ahead.toString()))
}
}
fun versionForReleaseBranch(): (Git, EnvironmentConfiguration) -> SemVer {
return { git, branch ->
val semVer = SemVer.parse(branch.branch)
val tags = git.semVerTags()
.filterTagsDescending { versionFromTag ->
versionFromTag == semVer.copy(identifiers = listOf("rc", "0"))
}
val (_, ahead) = git.aheadOfTag(tags)
semVer.copy(identifiers = listOf("rc", ahead.toString()))
}
}
fun versionForDevelopBranch(): (Git, EnvironmentConfiguration) -> SemVer {
return { git, _ ->
val tags = git.semVerTags()
.filterTagsDescending { versionFromTag ->
versionFromTag.identifiers == listOf("rc", "0")
}
val (semVer, ahead) = git.aheadOfTag(tags, true)
if (semVer == SemVer.Empty || ahead == 0) {
throw TrackingException("Couldn't find any reachable rc.0 tags before current commit")
}
semVer.bump().copy(identifiers = listOf("beta", (ahead - 1).toString()))
}
}
class TrackingException(message: String) : Throwable(message)
fun versionForMasterBranch(): (Git, EnvironmentConfiguration) -> SemVer {
return { git, _ ->
val tags = git.semVerTags()
.filterTagsDescending({ it.isStable() })
git.processTags(tags) { _, headCommit, list ->
list.firstOrNull { headCommit == it.commit }?.semVer ?: SemVer()
}
}
}
fun directTag(): (Git, EnvironmentConfiguration) -> SemVer {
return { _, config ->
SemVer.parse(config.tag)
}
}
fun versionForAnyBranch(): (Git, EnvironmentConfiguration) -> SemVer {
return { git, _ ->
val tags = git.semVerTags()
.filterTagsDescending({ versionFromTag ->
versionFromTag.identifiers == listOf("rc", "0") || versionFromTag.isStable()
})
val processTags: SemVer = git.processTags(tags) { walk, headCommit, list ->
val taggedCommit = list.firstOrNull {
walk.isMergedInto(it.commit, headCommit) && headCommit != it.commit
}?.semVer ?: SemVer()
taggedCommit.bump().copy(identifiers = listOf("alpha", headCommit.abbreviate(7).name().toUpperCase()))
}
processTags
}
}
private fun List<RefSemVer>.filterTagsDescending(tagFilter: (SemVer) -> Boolean) : List<RefSemVer> {
return this.filter { tag -> tagFilter(tag.semVer) }
.sortedByDescending { tag -> tag.semVer }
} | core/src/main/kotlin/com/github/cdcalc/strategy/GitFlowStrategies.kt | 33412236 |
// 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.application.options
/**
* Defining options that by default should be available in all products
*/
class GlobalOptionsApplicabilityFilter : OptionsApplicabilityFilter() {
override fun isOptionApplicable(optionId: OptionId?): Boolean {
if (optionId == OptionId.INSERT_PARENTHESES_AUTOMATICALLY) {
return true
}
return false
}
} | platform/lang-impl/src/com/intellij/application/options/GlobalOptionsApplicabilityFilter.kt | 3300054855 |
// ATTACH_LIBRARY: coroutines
package stepIntoSuspendFunctionSimple
import forTests.builder
private fun foo() {}
suspend fun second() {
}
suspend fun first(): Int {
second()
return 12
}
fun main(args: Array<String>) {
builder {
//Breakpoint!
first()
foo()
}
} | plugins/kotlin/jvm-debugger/test/testData/stepping/stepInto/stepIntoSuspendFunctionSimple.kt | 2608596820 |
package io.github.tobyhs.weatherweight.api.accuweather.locations
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* An administrative area (state, province, etc.) from AccuWeather's Locations API
*
* @property id ID for this admin area
*/
@JsonClass(generateAdapter = true)
data class AdministrativeArea(
@Json(name = "ID") val id: String
)
| app/src/main/java/io/github/tobyhs/weatherweight/api/accuweather/locations/AdministrativeArea.kt | 581397503 |
class C {
fun String.<caret>foo() {
1.bar()
}
fun Int.bar() {}
} | plugins/kotlin/idea/tests/testData/refactoring/changeSignature/ReceiverToParameterExplicitReceiverBefore.kt | 2855325469 |
// SUGGESTED_NAMES: i, getB
// PARAM_DESCRIPTOR: public fun A.ext(): kotlin.Unit defined in root package in file implicitThisWithSmartCast.kt
// PARAM_TYPES: B
fun main(args: Array<String>) {
val a: A = B()
a.ext()
}
fun A.ext() {
if (this !is B) return
val b = <selection>foo()</selection>
}
open class A
class B: A() {
fun foo() = 1
} | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/parameters/extractThis/implicitThisWithSmartCast.kt | 3668580139 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.ml.common
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiNamedElement
import com.intellij.textMatching.SimilarityScorer
object ContextSimilarityUtil {
val LINE_SIMILARITY_SCORER_KEY: Key<SimilarityScorer> = Key.create("LINE_SIMILARITY_SCORER")
val PARENT_SIMILARITY_SCORER_KEY: Key<SimilarityScorer> = Key.create("PARENT_SIMILARITY_SCORER")
fun createLineSimilarityScorer(line: String): SimilarityScorer = SimilarityScorer(StringUtil.getWordsIn(line))
fun createParentSimilarityScorer(element: PsiElement?): SimilarityScorer {
var curElement = element
val parents = mutableListOf<String>()
while (curElement != null && curElement !is PsiFile) {
if (curElement is PsiNamedElement) {
curElement.name?.let { parents.add(it) }
}
curElement = curElement.parent
}
return SimilarityScorer(parents)
}
}
| plugins/completion-ml-ranking/src/com/intellij/completion/ml/common/ContextSimilarityUtil.kt | 2069727278 |
package org.secfirst.umbrella.data.disk
import java.io.File
import javax.inject.Inject
class TentRepository @Inject constructor(private val tentDao: TentDao) : TentRepo {
override fun loadFormFile(path : String): List<File> = tentDao.filterForms(path)
override suspend fun updateRepository() = tentDao.rebaseBranch()
override suspend fun loadElementsFile(path : String) = tentDao.filterCategories(path)
override suspend fun fetchRepository(url: String) = tentDao.cloneRepository(url)
} | app/src/main/java/org/secfirst/umbrella/data/disk/TentRepository.kt | 2667249055 |
/*
* Copyright 2019 Eduard Scarlat
*
* 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 ro.edi.novelty.ui.adapter
import android.app.Activity
import android.app.ActivityOptions
import android.content.Intent
import android.view.View
import androidx.core.content.ContextCompat
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.recyclerview.widget.DiffUtil
import ro.edi.novelty.R
import ro.edi.novelty.databinding.NewsItemBinding
import ro.edi.novelty.model.News
import ro.edi.novelty.ui.NewsInfoActivity
import ro.edi.novelty.ui.viewmodel.NewsViewModel
class NewsAdapter(private val activity: Activity?, private val newsModel: NewsViewModel) :
BaseAdapter<News>(NewsDiffCallback()) {
companion object {
const val NEWS_PUB_DATE = "news_pub_date"
const val NEWS_FEED_TITLE = "news_feed_title"
const val NEWS_TITLE = "news_title"
const val NEWS_STATE = "news_state"
}
override fun getModel(): ViewModel {
return newsModel
}
override fun getItemId(position: Int): Long {
return getItem(position).id.toLong()
}
override fun getItemLayoutId(position: Int): Int {
return R.layout.news_item
}
override fun onItemClick(itemView: View, position: Int) {
newsModel.setIsRead(position, true)
val i = Intent(activity, NewsInfoActivity::class.java)
i.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
i.putExtra(NewsInfoActivity.EXTRA_NEWS_ID, getItem(position).id)
val options = ActivityOptions.makeSceneTransitionAnimation(
activity,
itemView,
"shared_news_container"
)
activity?.startActivity(i, options.toBundle())
}
override fun bind(binding: ViewDataBinding, position: Int, payloads: MutableList<Any>) {
val b = binding as NewsItemBinding
val payload = payloads.first() as Set<*>
payload.forEach {
when (it) {
NEWS_PUB_DATE -> b.date.text = newsModel.getDisplayDate(position)
NEWS_FEED_TITLE -> b.feed.text = getItem(position).feedTitle
NEWS_TITLE -> b.title.text = getItem(position).title
NEWS_STATE -> {
val colorInfo = ContextCompat.getColor(
binding.root.context,
newsModel.getInfoTextColorRes(binding.root.context, position)
)
val colorTitle = ContextCompat.getColor(
binding.root.context,
newsModel.getTitleTextColorRes(binding.root.context, position)
)
b.feed.setTextColor(colorInfo)
b.title.setTextColor(colorTitle)
b.date.setTextColor(colorInfo)
}
}
}
}
class NewsDiffCallback : DiffUtil.ItemCallback<News>() {
override fun areItemsTheSame(oldItem: News, newItem: News): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: News, newItem: News): Boolean {
return false // we do this because we want the shown date to always be updated
}
override fun getChangePayload(oldItem: News, newItem: News): Any? {
val payload = mutableSetOf<String>()
payload.add(NEWS_PUB_DATE) // always add this (because we show the relative date/time in the UI)
if (oldItem.feedTitle != newItem.feedTitle) {
payload.add(NEWS_FEED_TITLE)
}
if (oldItem.title != newItem.title) {
payload.add(NEWS_TITLE)
}
if (oldItem.isRead != newItem.isRead || oldItem.isStarred != newItem.isStarred) {
payload.add(NEWS_STATE)
}
if (payload.isEmpty()) {
return null
}
return payload
}
}
} | app/src/main/java/ro/edi/novelty/ui/adapter/NewsAdapter.kt | 2673042187 |
package org.amshove.kluent
import com.nhaarman.mockitokotlin2.*
import org.mockito.AdditionalAnswers.*
import org.mockito.Mockito.`when`
import org.mockito.internal.util.MockUtil
import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.Answer
import org.mockito.stubbing.OngoingStubbing
import kotlin.reflect.KClass
@Suppress("UNUSED_PARAMETER") // Backward compatibility
inline fun <reified T : Any> mock(targetClass: KClass<out T>): T = mock()
inline fun <reified T : Any> mock(): T = com.nhaarman.mockitokotlin2.mock()
infix fun VerifyKeyword.times(numInvocations: Int) = OngoingVerification(numInvocations)
infix fun <T> OngoingVerification.on(mock: T) = verify(mock, times(numInvocations))
infix fun <T> VerifyKeyword.on(mock: T) = verify(mock)
infix fun <T> VerifyNotCalledKeyword.on(mock: T) = verify(mock, never())
infix fun <T> T.that(mock: T): T {
ensureMock(this)
return this.apply { mock.run { Unit } }
}
infix fun <T : Any> VerifyNoInteractionsKeyword.on(mock: T) = verifyZeroInteractions(mock)
infix fun <T> VerifyNoFurtherInteractionsKeyword.on(mock: T) = verifyNoMoreInteractions(mock)
infix fun <T> T.was(n: CalledKeyword) = n
@Suppress("UNUSED_PARAMETER") // Backward compatibility
inline fun <reified T : Any> any(kClass: KClass<T>): T = any()
inline fun <reified T : Any> any(): T = com.nhaarman.mockitokotlin2.any()
infix fun <T> WhenKeyword.calling(methodCall: T): OngoingStubbing<T> = `when`(methodCall)
infix fun <T> OngoingStubbing<T>.itReturns(value: T): OngoingStubbing<T> = this.thenReturn(value)
infix fun <T> OngoingStubbing<T>.itThrows(value: Throwable): OngoingStubbing<T> = this.thenThrow(value)
infix fun <T> OngoingStubbing<T>.itAnswers(value: (InvocationOnMock) -> T): OngoingStubbing<T> = this.thenAnswer(value)
infix fun <T> OngoingStubbing<T>.itAnswers(value: Answer<T>): OngoingStubbing<T> = this.thenAnswer(value)
/**
* Returns the parameter of an invocation at the given position.
* @param position Location of the parameter to return, zero based.
* @see [returnsArgAt]
*/
fun <T> withArgAt(position: Int): Answer<T> = returnsArgAt(position)
fun <T> withFirstArg(): Answer<T> = returnsFirstArg()
fun <T> withSecondArg(): Answer<T> = returnsSecondArg()
fun <T> withThirdArg(): Answer<T> = withArgAt(2)
fun <T> withFourthArg(): Answer<T> = withArgAt(3)
fun <T> withLastArg(): Answer<T> = returnsLastArg()
private fun <T> ensureMock(obj: T) {
if (!MockUtil.isMock(obj)) {
throw Exception(
"""
$obj is no mock.
Ensure to always determine the mock with the `on` method.
Example:
Verify on myMock that myMock.getPerson() was called
/\
--------
"""
)
}
}
val When = WhenKeyword()
val Verify = VerifyKeyword()
val VerifyNotCalled = VerifyNotCalledKeyword()
val called = CalledKeyword()
val VerifyNoInteractions = VerifyNoInteractionsKeyword()
val VerifyNoFurtherInteractions = VerifyNoFurtherInteractionsKeyword()
class VerifyKeyword internal constructor()
class VerifyNotCalledKeyword internal constructor()
class CalledKeyword internal constructor()
class WhenKeyword internal constructor()
class VerifyNoInteractionsKeyword internal constructor()
class VerifyNoFurtherInteractionsKeyword internal constructor()
class OngoingVerification(val numInvocations: Int) | jvm/src/test/kotlin/org/amshove/kluent/tests/mocking/Mocking.kt | 196535538 |
// Tommy Li ([email protected]), 2017-03-10
package co.firefire.fenergy.nem12.domain
import java.math.BigDecimal
import java.time.Duration
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.*
import javax.persistence.CascadeType
import javax.persistence.Embedded
import javax.persistence.Entity
import javax.persistence.FetchType
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.JoinColumn
import javax.persistence.ManyToOne
import javax.persistence.MapKey
import javax.persistence.OneToMany
import javax.persistence.OrderBy
import org.hibernate.annotations.GenericGenerator as HbmGenericGenerator
import org.hibernate.annotations.Parameter as HbmParameter
import javax.persistence.Transient as JpaTransient
val MINUTES_IN_DAY: Int = Duration.ofDays(1).toMinutes().toInt()
@Entity
data class IntervalDay(
@ManyToOne(optional = false)
@JoinColumn(name = "nmi_meter_register", referencedColumnName = "id", nullable = false)
var nmiMeterRegister: NmiMeterRegister = NmiMeterRegister(),
var intervalDate: LocalDate = LocalDate.MIN,
@Embedded
var intervalQuality: IntervalQuality = IntervalQuality(Quality.A)
) {
@Id
@HbmGenericGenerator(
name = "IntervalDayIdSeq",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = arrayOf(
HbmParameter(name = "sequence_name", value = "interval_day_id_seq"),
HbmParameter(name = "initial_value", value = "1000"),
HbmParameter(name = "increment_size", value = "50")
)
)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "IntervalDayIdSeq")
var id: Long? = null
var version: Int? = 0
var updateDateTime: LocalDateTime? = null
var msatsLoadDateTime: LocalDateTime? = null
@JpaTransient
@Transient
var intervalEvents: MutableMap<IntRange, IntervalEvent> = mutableMapOf()
@OneToMany(mappedBy = "id.intervalDay", cascade = arrayOf(CascadeType.ALL), orphanRemoval = true, fetch = FetchType.EAGER)
@MapKey(name = "id.interval")
@OrderBy("id.interval")
var intervalValues: SortedMap<Int, IntervalValue> = TreeMap()
fun getTotal(): BigDecimal {
return intervalValues.values.sumByBigDecimal { it.value }
}
fun applyIntervalEvents() {
assert(intervalValues.all { it.value.intervalQuality.quality != Quality.V }, { "Individual values should never have V quality." })
if (intervalQuality.quality == Quality.V) {
intervalValues = TreeMap(intervalValues.mapValues { (interval, intervalValue) ->
val newQuality = intervalEvents.values.find { it.intervalRange.contains(interval) }?.intervalQuality ?: IntervalQuality(Quality.A)
IntervalValue(this, interval, intervalValue.value, newQuality)
})
}
}
fun addIntervalValue(newIntervalValue: IntervalValue) {
newIntervalValue.id = IntervalKey(this, newIntervalValue.interval)
intervalValues.put(newIntervalValue.interval, newIntervalValue)
}
fun replaceIntervalValues(newIntervalValues: Map<Int, IntervalValue>) {
newIntervalValues.forEach { interval: Int, newIntervalValue: IntervalValue ->
val existingIntervalValue = intervalValues.get(interval)
if (existingIntervalValue == null) {
addIntervalValue(newIntervalValue)
} else {
existingIntervalValue.value = newIntervalValue.value
existingIntervalValue.intervalQuality = newIntervalValue.intervalQuality
}
}
}
fun mergeNewIntervalValues(newIntervalValues: Map<Int, IntervalValue>, newUpdateDateTime: LocalDateTime?, newMsatsLoadDateTime: LocalDateTime?) {
val existingDateTime = updateDateTime ?: msatsLoadDateTime ?: LocalDateTime.now()
val newDateTime = newUpdateDateTime ?: newMsatsLoadDateTime ?: LocalDateTime.now()
validateIntervalValueQuality(intervalValues)
validateIntervalValueQuality(newIntervalValues)
newIntervalValues.forEach { newInterval: Int, newIntervalValue: IntervalValue ->
intervalValues.merge(newInterval, newIntervalValue, { existing: IntervalValue, new: IntervalValue ->
val existingQuality = TimestampedQuality(existing.intervalQuality.quality, existingDateTime)
val newQuality = TimestampedQuality(new.intervalQuality.quality, newDateTime)
if (newQuality >= existingQuality) {
existing.value = new.value
existing.intervalQuality = new.intervalQuality
existing
} else {
existing
}
})
}
}
fun appendIntervalEvent(intervalEvent: IntervalEvent) {
intervalEvents.put(intervalEvent.intervalRange, intervalEvent)
}
override fun toString(): String {
return "IntervalDay(id=$id, nmiMeterRegister=$nmiMeterRegister, intervalDate=$intervalDate)"
}
private fun validateIntervalValueQuality(intervalValues: Map<Int, IntervalValue>) {
assert(intervalValues.all { it.value.intervalQuality.quality != Quality.V }, { "Individual values should never have V quality." })
}
}
| fenergy-service/src/main/kotlin/co/firefire/fenergy/nem12/domain/IntervalDay.kt | 1601640899 |
package com.edreams.android.workshops.kotlin.data.common.cache
import android.arch.persistence.room.Database
import android.arch.persistence.room.RoomDatabase
import com.edreams.android.workshops.kotlin.data.venues.cache.dao.VenuesDao
import com.edreams.android.workshops.kotlin.data.venues.cache.entity.VenueEntity
@Database(entities = [
VenueEntity::class
], version = 1)
abstract class PlacesDatabase : RoomDatabase() {
abstract fun venuesDao(): VenuesDao
} | data/src/main/java/com/edreams/android/workshops/kotlin/data/common/cache/PlacesDatabase.kt | 3312906124 |
// Use of this source code is governed by The MIT License
// that can be found in the LICENSE file.
package taumechanica.ml
import kotlin.math.*
import taumechanica.ml.data.*
fun accuracy(frame: DataFrame, model: Predictor): Double {
var total = 0
var correct = 0
val domain = (frame.target as NominalAttribute).domain
for (i in 0 until frame.samples.size) if (frame.subset[i]) {
val sample = frame.samples[i]
val scores = model.predict(sample.values)
val decision = argmax(domain, scores)
if (decision == sample.values[frame.target.index]) correct++
total++
}
return 100.0 * correct / total
}
fun rmsle(frame: DataFrame, model: Predictor): Double {
var total = 0
var sum = 0.0
for (i in 0 until frame.samples.size) if (frame.subset[i]) {
val sample = frame.samples[i]
val prediction = model.predict(sample.values)[0]
sum += (ln(prediction + 1.0) - ln(sample.values[frame.target.index] + 1.0)).pow(2.0)
total++
}
return (sum / total).pow(0.5)
}
fun logloss(frame: DataFrame, model: Predictor, calibrate: Boolean = true): Double {
var total = 0
var logloss = 0.0
for (i in 0 until frame.samples.size) if (frame.subset[i]) {
val sample = frame.samples[i]
val scores = model.predict(sample.values)
val probabilities = if (calibrate) prob(scores) else scores
for ((k, p) in probabilities.withIndex()) {
logloss += 0.5 * (sample.actual[k] + 1.0) * ln(max(min(p, 1.0 - 1E-15), 1E-15))
}
total++
}
return logloss / -total
}
fun gini(frame: DataFrame, model: Predictor, calibrate: Boolean = true): Double {
val domain = (frame.target as NominalAttribute).domain
if (domain.size != 2) {
throw Exception("Could not calculate")
}
val values = mutableListOf<DoubleArray>()
for (i in 0 until frame.samples.size) if (frame.subset[i]) {
val sample = frame.samples[i]
val scores = model.predict(sample.values)
val probabilities = if (calibrate) prob(scores) else scores
values.add(doubleArrayOf(probabilities[0], 0.5 * (sample.actual[0] + 1.0), i.toDouble()))
}
val g: (Int) -> Double = { by ->
var losses = 0.0
val sorted = values.sortedWith(compareBy({ -it[by] }, { it[2] }))
for (row in sorted) losses += row[1]
var cum = 0.0
var sum = 0.0
for (row in sorted) {
cum += row[1] / losses
sum += cum
}
sum -= (sorted.size + 1.0) / 2.0
sum / sorted.size
}
return max(0.0, g(0) / g(1))
}
fun auc(frame: DataFrame, model: Predictor, calibrate: Boolean = true): Double {
return 0.5 * (gini(frame, model, calibrate) + 1.0)
}
| src/main/kotlin/ml/Metrics.kt | 854148160 |
package se.eelde.granter.app
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_regular_permission.*
class RegularPermissionActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_regular_permission)
regular_permission_button.setOnClickListener { checkPermissions() }
}
private fun moveToNextStep() {
supportFragmentManager
.beginTransaction()
.replace(fragment_container.id, DummyFragment.newInstance())
.commit()
}
private fun checkPermissions() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
AlertDialog.Builder(this)
.setTitle("title")
.setMessage("message")
.setPositiveButton("ok") { _, _ -> ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_PERMISSION_LOCATION_RATIONALE) }
.setNegativeButton("nah", null)
.create()
.show()
} else {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_PERMISSION_LOCATION)
}
} else {
moveToNextStep()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_PERMISSION_LOCATION -> {
run {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
moveToNextStep()
} else if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
AlertDialog.Builder(this)
.setTitle("title")
.setMessage("settings")
.setPositiveButton("ok", null)
.setNegativeButton("nah", null)
.create()
.show()
}
}
run {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
moveToNextStep()
}
}
run { super.onRequestPermissionsResult(requestCode, permissions, grantResults) }
}
REQUEST_PERMISSION_LOCATION_RATIONALE -> {
run {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
moveToNextStep()
}
}
run { super.onRequestPermissionsResult(requestCode, permissions, grantResults) }
}
else -> {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
}
companion object {
private const val REQUEST_PERMISSION_LOCATION_RATIONALE = 213
private const val REQUEST_PERMISSION_LOCATION = 212
fun start(context: Context) {
context.startActivity(Intent(context, RegularPermissionActivity::class.java))
}
}
}
| app/src/main/java/se/eelde/granter/app/RegularPermissionActivity.kt | 3242967452 |
package kontrol.hibernate
/*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @todo document.
* @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a>
*/
import kontrol.api.EventLog
import kontrol.api.LogContextualState
import kontrol.api.EventLogEntry
public class HibernateEventLog(url: String) : EventLog {
override fun log(targetName: String, state: Any?, contextState: LogContextualState, message: String) {
store.add(EventLogEntry(targetName, state, contextState, message))
}
override fun last(n: Int): List<EventLogEntry> {
return store.last(n)
}
val store: HibernateEventLogStore = HibernateEventLogStore(url);
} | hibernate/src/main/kotlin/HibernateEventLog.kt | 3081140415 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.changeReminder.stats
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger
import com.intellij.openapi.project.Project
import java.util.*
enum class ChangeReminderEvent {
HANDLER_REGISTERED,
PLUGIN_DISABLED,
PREDICTION_CALCULATED,
NOT_SHOWED,
DIALOG_CLOSED,
COMMITTED_ANYWAY,
COMMIT_CANCELED
}
enum class ChangeReminderData {
EXECUTION_TIME,
SHOW_DIALOG_TIME
}
fun <T : Enum<*>> T.getReportedId() = this.name.toLowerCase(Locale.ENGLISH).replace('_', '.')
fun logEvent(project: Project, event: ChangeReminderEvent, factor: ChangeReminderData, value: Long) =
logEvent(project, event, mapOf(factor to value))
fun logEvent(project: Project, event: ChangeReminderEvent, data: Map<ChangeReminderData, Long> = emptyMap()) {
val logData = FeatureUsageData()
data.forEach { (factor, value) ->
logData.addData(factor.getReportedId(), value)
}
FUCounterUsageLogger.getInstance().logEvent(project, "vcs.change.reminder", event.getReportedId(), logData)
} | plugins/changeReminder/src/com/jetbrains/changeReminder/stats/ChangeReminderStatsCollector.kt | 1994732822 |
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class NullableVFUEntityImpl(val dataSource: NullableVFUEntityData) : NullableVFUEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val data: String
get() = dataSource.data
override val fileProperty: VirtualFileUrl?
get() = dataSource.fileProperty
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: NullableVFUEntityData?) : ModifiableWorkspaceEntityBase<NullableVFUEntity>(), NullableVFUEntity.Builder {
constructor() : this(NullableVFUEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity NullableVFUEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "fileProperty", this.fileProperty)
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field NullableVFUEntity#data should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as NullableVFUEntity
this.entitySource = dataSource.entitySource
this.data = dataSource.data
this.fileProperty = dataSource.fileProperty
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override var fileProperty: VirtualFileUrl?
get() = getEntityData().fileProperty
set(value) {
checkModificationAllowed()
getEntityData().fileProperty = value
changedProperty.add("fileProperty")
val _diff = diff
if (_diff != null) index(this, "fileProperty", value)
}
override fun getEntityData(): NullableVFUEntityData = result ?: super.getEntityData() as NullableVFUEntityData
override fun getEntityClass(): Class<NullableVFUEntity> = NullableVFUEntity::class.java
}
}
class NullableVFUEntityData : WorkspaceEntityData<NullableVFUEntity>() {
lateinit var data: String
var fileProperty: VirtualFileUrl? = null
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<NullableVFUEntity> {
val modifiable = NullableVFUEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): NullableVFUEntity {
return getCached(snapshot) {
val entity = NullableVFUEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return NullableVFUEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return NullableVFUEntity(data, entitySource) {
this.fileProperty = [email protected]
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as NullableVFUEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
if (this.fileProperty != other.fileProperty) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as NullableVFUEntityData
if (this.data != other.data) return false
if (this.fileProperty != other.fileProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
result = 31 * result + fileProperty.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
result = 31 * result + fileProperty.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.fileProperty?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/NullableVFUEntityImpl.kt | 4151135556 |
// 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.intellij.build.impl
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.util.io.URLUtil
import org.jetbrains.intellij.build.BuildMessages
import org.jetbrains.jps.model.JpsGlobal
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.library.JpsOrderRootType
import java.io.File
import java.nio.file.Path
import java.util.*
import kotlin.io.path.exists
import kotlin.io.path.inputStream
object JdkUtils {
fun defineJdk(global: JpsGlobal, jdkName: String, jdkHomePath: String, messages: BuildMessages) {
val sdk = JpsJavaExtensionService.getInstance().addJavaSdk(global, jdkName, jdkHomePath)
val toolsJar = File(jdkHomePath, "lib/tools.jar")
if (toolsJar.exists()) {
sdk.addRoot(toolsJar, JpsOrderRootType.COMPILED)
}
messages.info("'$jdkName' Java SDK set to $jdkHomePath")
}
/**
* Code is copied from com.intellij.openapi.projectRoots.impl.JavaSdkImpl#findClasses(java.io.File, boolean)
*/
fun readModulesFromReleaseFile(jbrBaseDir: Path): List<String> {
val releaseFile = jbrBaseDir.resolve("release")
if (!releaseFile.exists()) {
throw IllegalStateException("JRE release file is missing: $releaseFile")
}
releaseFile.inputStream().use { stream ->
val p = Properties()
p.load(stream)
val jbrBaseUrl = "${URLUtil.JRT_PROTOCOL}${URLUtil.SCHEME_SEPARATOR}${FileUtilRt.toSystemIndependentName(jbrBaseDir.toAbsolutePath().toString())}${URLUtil.JAR_SEPARATOR}"
val modules = p.getProperty("MODULES") ?: return emptyList()
return StringUtilRt.unquoteString(modules).split(' ').map { jbrBaseUrl + it }
}
}
}
| platform/build-scripts/src/org/jetbrains/intellij/build/impl/JdkUtils.kt | 1404553128 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package quickbeer.android.feature.barcode.camera
import android.content.Context
import android.graphics.ImageFormat
import android.hardware.Camera
import android.hardware.Camera.CameraInfo
import android.hardware.Camera.Parameters
import android.view.Surface
import android.view.SurfaceHolder
import android.view.WindowManager
import com.google.android.gms.common.images.Size
import java.io.IOException
import java.nio.ByteBuffer
import java.util.IdentityHashMap
import kotlin.math.abs
import kotlin.math.ceil
import quickbeer.android.feature.barcode.detection.FrameMetadata
import quickbeer.android.feature.barcode.detection.FrameProcessor
import quickbeer.android.feature.barcode.graphic.GraphicOverlay
import quickbeer.android.feature.barcode.utils.ScannerUtils
import timber.log.Timber
/**
* Manages the camera and allows UI updates on top of it (e.g. overlaying extra Graphics). This
* receives preview frames from the camera at a specified rate, sends those frames to detector as
* fast as it is able to process.
*
*
* This camera source makes a best effort to manage processing on preview frames as fast as
* possible, while at the same time minimizing lag. As such, frames may be dropped if the detector
* is unable to keep up with the rate of frames generated by the camera.
*/
@Suppress("DEPRECATION")
class CameraSource(private val graphicOverlay: GraphicOverlay) {
internal var camera: Camera? = null
internal var rotationDegrees: Int = 0
/** Returns the preview size that is currently in use by the underlying camera. */
internal var previewSize: Size? = null
private set
/**
* Dedicated thread and associated runnable for calling into the detector with frames, as the
* frames become available from the camera.
*/
private var processingThread: Thread? = null
private val processingRunnable = FrameProcessingRunnable()
internal val processorLock = Object()
internal var frameProcessor: FrameProcessor? = null
/**
* Map to convert between a byte array, received from the camera, and its associated byte
* buffer. We use byte buffers internally because this is a more efficient way to call into
* native code later (avoids a potential copy).
*
*
* **Note:** uses IdentityHashMap here instead of HashMap because the behavior of an array's
* equals, hashCode and toString methods is both useless and unexpected. IdentityHashMap
* enforces identity ('==') check on the keys.
*/
internal val bytesToByteBuffer = IdentityHashMap<ByteArray, ByteBuffer>()
internal val context: Context = graphicOverlay.context
/**
* Opens the camera and starts sending preview frames to the underlying detector. The supplied
* surface holder is used for the preview so frames can be displayed to the user.
*
* @param surfaceHolder the surface holder to use for the preview frames.
* @throws IOException if the supplied surface holder could not be used as the preview display.
*/
@Synchronized
@Throws(IOException::class)
internal fun start(surfaceHolder: SurfaceHolder) {
if (camera != null) return
camera = createCamera().apply {
setPreviewDisplay(surfaceHolder)
startPreview()
}
processingThread = Thread(processingRunnable).apply {
processingRunnable.setActive(true)
start()
}
}
/**
* Closes the camera and stops sending frames to the underlying frame detector.
*
* This camera source may be restarted again by calling [.start].
*
* Call [.release] instead to completely shut down this camera source and release the
* resources of the underlying detector.
*/
@Synchronized
internal fun stop() {
processingRunnable.setActive(false)
processingThread?.let {
try {
// Waits for the thread to complete to ensure that we can't have multiple threads
// executing at the same time (i.e., which would happen if we called start too
// quickly after stop).
it.join()
} catch (e: InterruptedException) {
Timber.e("Frame processing thread interrupted on stop.")
}
processingThread = null
}
camera?.let {
it.stopPreview()
it.setPreviewCallbackWithBuffer(null)
try {
it.setPreviewDisplay(null)
} catch (e: IOException) {
Timber.e(e, "Failed to clear camera preview")
}
it.release()
camera = null
}
// Release the reference to any image buffers, since these will no longer be in use.
bytesToByteBuffer.clear()
}
/** Stops the camera and releases the resources of the camera and underlying detector. */
fun release() {
graphicOverlay.clear()
synchronized(processorLock) {
stop()
frameProcessor?.stop()
}
}
fun setFrameProcessor(processor: FrameProcessor) {
graphicOverlay.clear()
synchronized(processorLock) {
frameProcessor?.stop()
frameProcessor = processor
}
}
fun updateFlashMode(mode: String) {
camera?.parameters = camera?.parameters?.apply {
flashMode = mode
}
}
/**
* Opens the camera and applies the user settings.
*
* @throws IOException if camera cannot be found or preview cannot be processed.
*/
@Throws(IOException::class)
private fun createCamera(): Camera {
val camera = Camera.open()
?: throw IOException("There is no back-facing camera.")
val parameters = camera.parameters
setPreviewAndPictureSize(camera, parameters)
setRotation(camera, parameters)
val previewFpsRange = selectPreviewFpsRange(camera)
?: throw IOException("Could not find suitable preview frames per second range.")
parameters.setPreviewFpsRange(
previewFpsRange[Parameters.PREVIEW_FPS_MIN_INDEX],
previewFpsRange[Parameters.PREVIEW_FPS_MAX_INDEX]
)
parameters.previewFormat = IMAGE_FORMAT
if (parameters.supportedFocusModes.contains(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
parameters.focusMode = Parameters.FOCUS_MODE_CONTINUOUS_VIDEO
} else {
Timber.i("Camera auto focus is not supported on this device.")
}
camera.parameters = parameters
camera.setPreviewCallbackWithBuffer(processingRunnable::setNextFrame)
// Four frame buffers are needed for working with the camera:
//
// one for the frame that is currently being executed upon in doing detection
// one for the next pending frame to process immediately upon completing detection
// two for the frames that the camera uses to populate future preview images
//
// Through trial and error it appears that two free buffers, in addition to the two buffers
// used in this code, are needed for the camera to work properly. Perhaps the camera has one
// thread for acquiring images, and another thread for calling into user code. If only three
// buffers are used, then the camera will spew thousands of warning messages when detection
// takes a non-trivial amount of time.
previewSize?.let {
camera.addCallbackBuffer(createPreviewBuffer(it))
camera.addCallbackBuffer(createPreviewBuffer(it))
camera.addCallbackBuffer(createPreviewBuffer(it))
camera.addCallbackBuffer(createPreviewBuffer(it))
}
return camera
}
@Throws(IOException::class)
private fun setPreviewAndPictureSize(camera: Camera, parameters: Parameters) {
// Camera preview size is based on the landscape mode, so we need to also use the aspect
// ration of display in the same mode for comparison.
val displayAspectRatioInLandscape: Float =
if (ScannerUtils.isPortraitMode(graphicOverlay.context)) {
graphicOverlay.height.toFloat() / graphicOverlay.width
} else {
graphicOverlay.width.toFloat() / graphicOverlay.height
}
// Gives priority to the preview size specified by the user if exists.
val sizePair = selectSizePair(camera, displayAspectRatioInLandscape)
?: throw IOException("Could not find suitable preview size")
previewSize = sizePair.preview.also {
Timber.v("Camera preview size: $it")
parameters.setPreviewSize(it.width, it.height)
}
sizePair.picture?.let { pictureSize ->
Timber.v("Camera picture size: $pictureSize")
parameters.setPictureSize(pictureSize.width, pictureSize.height)
}
}
/**
* Calculates the correct rotation for the given camera id and sets the rotation in the
* parameters. It also sets the camera's display orientation and rotation.
*
* @param parameters the camera parameters for which to set the rotation.
*/
@Suppress("MagicNumber")
private fun setRotation(camera: Camera, parameters: Parameters) {
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val degrees = when (val deviceRotation = windowManager.defaultDisplay.rotation) {
Surface.ROTATION_0 -> 0
Surface.ROTATION_90 -> 90
Surface.ROTATION_180 -> 180
Surface.ROTATION_270 -> 270
else -> {
Timber.e("Bad device rotation value: $deviceRotation")
0
}
}
val cameraInfo = CameraInfo().also { Camera.getCameraInfo(CAMERA_FACING_BACK, it) }
val angle = (cameraInfo.orientation - degrees + 360) % 360
rotationDegrees = angle
camera.setDisplayOrientation(angle)
parameters.setRotation(angle)
}
/**
* Creates one buffer for the camera preview callback. The size of the buffer is based off of
* the camera preview size and the format of the camera image.
*
* @return a new preview buffer of the appropriate size for the current camera settings.
*/
@Suppress("MagicNumber")
private fun createPreviewBuffer(previewSize: Size): ByteArray {
val bitsPerPixel = ImageFormat.getBitsPerPixel(IMAGE_FORMAT)
val area = previewSize.height.toLong() * previewSize.width.toLong()
val sizeInBits = area * bitsPerPixel.toLong()
val bufferSize = ceil(sizeInBits / 8.0).toInt() + 1
// Creating the byte array this way and wrapping it, as opposed to using .allocate(),
// should guarantee that there will be an array to work with.
val byteArray = ByteArray(bufferSize)
val byteBuffer = ByteBuffer.wrap(byteArray)
check(!(!byteBuffer.hasArray() || !byteBuffer.array().contentEquals(byteArray))) {
// This should never happen. If it does, then we wouldn't be passing the preview content
// to the underlying detector later.
"Failed to create valid buffer for camera source."
}
bytesToByteBuffer[byteArray] = byteBuffer
return byteArray
}
/**
* This runnable controls access to the underlying receiver, calling it to process frames when
* available from the camera. This is designed to run detection on frames as fast as possible
* (i.e., without unnecessary context switching or waiting on the next frame).
*
* While detection is running on a frame, new frames may be received from the camera. As these
* frames come in, the most recent frame is held onto as pending. As soon as detection and its
* associated processing is done for the previous frame, detection on the mostly recently
* received frame will immediately start on the same thread.
*/
private inner class FrameProcessingRunnable : Runnable {
// This lock guards all of the member variables below.
private val lock = Object()
private var active = true
// These pending variables hold the state associated with the new frame awaiting processing.
private var pendingFrameData: ByteBuffer? = null
/** Marks the runnable as active/not active. Signals any blocked threads to continue. */
fun setActive(active: Boolean) {
synchronized(lock) {
this.active = active
lock.notifyAll()
}
}
/**
* Sets the frame data received from the camera. This adds the previous unused frame buffer
* (if present) back to the camera, and keeps a pending reference to the frame data for
* future use.
*/
fun setNextFrame(data: ByteArray, camera: Camera) {
synchronized(lock) {
pendingFrameData?.let {
camera.addCallbackBuffer(it.array())
pendingFrameData = null
}
if (!bytesToByteBuffer.containsKey(data)) {
Timber.d("Could not find ByteBuffer, skipping frame")
return
}
pendingFrameData = bytesToByteBuffer[data]
// Notify the processor thread if it is waiting on the next frame (see below).
lock.notifyAll()
}
}
/**
* As long as the processing thread is active, this executes detection on frames
* continuously. The next pending frame is either immediately available or hasn't been
* received yet. Once it is available, we transfer the frame info to local variables and run
* detection on that frame. It immediately loops back for the next frame without pausing.
*
* If detection takes longer than the time in between new frames from the camera, this will
* mean that this loop will run without ever waiting on a frame, avoiding any context
* switching or frame acquisition time latency.
*
* If you find that this is using more CPU than you'd like, you should probably decrease the
* FPS setting above to allow for some idle time in between frames.
*/
override fun run() {
var data: ByteBuffer?
while (true) {
synchronized(lock) {
while (active && pendingFrameData == null) {
try {
// Wait for the next frame to be received from the camera, since we
// don't have it yet.
lock.wait()
} catch (e: InterruptedException) {
Timber.e(e, "Frame processing loop terminated.")
return
}
}
if (!active) {
// Exit the loop once this camera source is stopped or released. We check
// this here, immediately after the wait() above, to handle the case where
// setActive(false) had been called, triggering termination of this loop.
return
}
// Hold onto the frame data locally, so that we can use this for detection
// below. We need to clear pendingFrameData to ensure that this buffer isn't
// recycled back to the camera before we are done using that data.
data = pendingFrameData
pendingFrameData = null
}
@Suppress("TooGenericExceptionCaught")
try {
synchronized(processorLock) {
val frameMetadata = FrameMetadata(
previewSize!!.width,
previewSize!!.height,
rotationDegrees
)
data?.let { frameProcessor?.process(it, frameMetadata, graphicOverlay) }
}
} catch (e: Exception) {
Timber.e(e, "Exception thrown from receiver.")
} finally {
data?.let { camera?.addCallbackBuffer(it.array()) }
}
}
}
}
companion object {
const val CAMERA_FACING_BACK = CameraInfo.CAMERA_FACING_BACK
private const val IMAGE_FORMAT = ImageFormat.NV21
private const val MIN_CAMERA_PREVIEW_WIDTH = 400
private const val MAX_CAMERA_PREVIEW_WIDTH = 1300
private const val DEFAULT_REQUESTED_CAMERA_PREVIEW_WIDTH = 640
private const val DEFAULT_REQUESTED_CAMERA_PREVIEW_HEIGHT = 360
private const val REQUESTED_CAMERA_FPS = 30.0f
/**
* Selects the most suitable preview and picture size, given the display aspect ratio in
* landscape mode.
*
* It's firstly trying to pick the one that has closest aspect ratio to display view with
* its width be in the specified range [[.MIN_CAMERA_PREVIEW_WIDTH],
* [ ][.MAX_CAMERA_PREVIEW_WIDTH]]. If there're multiple candidates, choose the one having
* longest width.
*
* If the above looking up failed, chooses the one that has the minimum sum of the
* differences between the desired values and the actual values for width and height.
*
* Even though we only need to find the preview size, it's necessary to find both the
* preview size and the picture size of the camera together, because these need to have the
* same aspect ratio. On some hardware, if you would only set the preview size, you will get
* a distorted image.
*
* @param camera the camera to select a preview size from
* @return the selected preview and picture size pair
*/
internal fun selectSizePair(
camera: Camera,
displayAspectRatioInLandscape: Float
): CameraSizePair? {
val validPreviewSizes = ScannerUtils.generateValidPreviewSizeList(camera)
var selectedPair: CameraSizePair? = null
// Picks the preview size that has closest aspect ratio to display view.
var minAspectRatioDiff = Float.MAX_VALUE
for (sizePair in validPreviewSizes) {
val previewSize = sizePair.preview
if (previewSize.width < MIN_CAMERA_PREVIEW_WIDTH ||
previewSize.width > MAX_CAMERA_PREVIEW_WIDTH
) {
continue
}
val previewAspectRatio = previewSize.width.toFloat() / previewSize.height.toFloat()
val aspectRatioDiff = abs(displayAspectRatioInLandscape - previewAspectRatio)
val aspectRatioFoo = abs(aspectRatioDiff - minAspectRatioDiff)
if (aspectRatioFoo < ScannerUtils.ASPECT_RATIO_TOLERANCE) {
if (selectedPair == null ||
selectedPair.preview.width < sizePair.preview.width
) {
selectedPair = sizePair
}
} else if (aspectRatioDiff < minAspectRatioDiff) {
minAspectRatioDiff = aspectRatioDiff
selectedPair = sizePair
}
}
if (selectedPair == null) {
// Picks the one that has the minimum sum of the differences between the desired
// values and the actual values for width and height.
var minDiff = Integer.MAX_VALUE
for (sizePair in validPreviewSizes) {
val size = sizePair.preview
val wDiff = abs(size.width - DEFAULT_REQUESTED_CAMERA_PREVIEW_WIDTH)
val hDiff = abs(size.height - DEFAULT_REQUESTED_CAMERA_PREVIEW_HEIGHT)
val diff = wDiff + hDiff
if (diff < minDiff) {
selectedPair = sizePair
minDiff = diff
}
}
}
return selectedPair
}
/**
* Selects the most suitable preview frames per second range.
*
* @param camera the camera to select a frames per second range from
* @return the selected preview frames per second range
*/
@Suppress("MagicNumber")
internal fun selectPreviewFpsRange(camera: Camera): IntArray? {
// The camera API uses integers scaled by a factor of 1000 instead of floating-point
// frame rates.
val desiredPreviewFpsScaled = (REQUESTED_CAMERA_FPS * 1000f).toInt()
// The method for selecting the best range is to minimize the sum of the differences
// between the desired value and the upper and lower bounds of the range. This may
// select a range that the desired value is outside of, but this is often preferred.
// For example, if the desired frame rate is 29.97, the range (30, 30) is probably more
// desirable than the range (15, 30).
var selectedFpsRange: IntArray? = null
var minDiff = Integer.MAX_VALUE
for (range in camera.parameters.supportedPreviewFpsRange) {
val deltaMin = desiredPreviewFpsScaled - range[Parameters.PREVIEW_FPS_MIN_INDEX]
val deltaMax = desiredPreviewFpsScaled - range[Parameters.PREVIEW_FPS_MAX_INDEX]
val diff = abs(deltaMin) + abs(deltaMax)
if (diff < minDiff) {
selectedFpsRange = range
minDiff = diff
}
}
return selectedFpsRange
}
}
}
| app/src/main/java/quickbeer/android/feature/barcode/camera/CameraSource.kt | 3145682052 |
package com.simplemobiletools.gallery.pro.activities
import android.content.res.Configuration
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.Window
import android.view.WindowInsetsController
import android.view.WindowManager
import android.widget.RelativeLayout
import android.widget.SeekBar
import com.google.vr.sdk.widgets.video.VrVideoEventListener
import com.google.vr.sdk.widgets.video.VrVideoView
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.isRPlus
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.extensions.hasNavBar
import com.simplemobiletools.gallery.pro.extensions.hideSystemUI
import com.simplemobiletools.gallery.pro.extensions.showSystemUI
import com.simplemobiletools.gallery.pro.helpers.MIN_SKIP_LENGTH
import com.simplemobiletools.gallery.pro.helpers.PATH
import kotlinx.android.synthetic.main.activity_panorama_video.*
import kotlinx.android.synthetic.main.bottom_video_time_holder.*
import java.io.File
open class PanoramaVideoActivity : SimpleActivity(), SeekBar.OnSeekBarChangeListener {
private val CARDBOARD_DISPLAY_MODE = 3
private var mIsFullscreen = false
private var mIsExploreEnabled = true
private var mIsRendering = false
private var mIsPlaying = false
private var mIsDragged = false
private var mPlayOnReady = false
private var mDuration = 0
private var mCurrTime = 0
private var mTimerHandler = Handler()
public override fun onCreate(savedInstanceState: Bundle?) {
useDynamicTheme = false
requestWindowFeature(Window.FEATURE_NO_TITLE)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_panorama_video)
checkNotchSupport()
checkIntent()
if (isRPlus()) {
window.insetsController?.setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS)
}
}
override fun onResume() {
super.onResume()
vr_video_view.resumeRendering()
mIsRendering = true
if (config.blackBackground) {
updateStatusbarColor(Color.BLACK)
}
window.statusBarColor = resources.getColor(R.color.circle_black_background)
if (config.maxBrightness) {
val attributes = window.attributes
attributes.screenBrightness = 1f
window.attributes = attributes
}
}
override fun onPause() {
super.onPause()
vr_video_view.pauseRendering()
mIsRendering = false
}
override fun onDestroy() {
super.onDestroy()
if (mIsRendering) {
vr_video_view.shutdown()
}
if (!isChangingConfigurations) {
mTimerHandler.removeCallbacksAndMessages(null)
}
}
private fun checkIntent() {
val path = intent.getStringExtra(PATH)
if (path == null) {
toast(R.string.invalid_image_path)
finish()
return
}
setupButtons()
intent.removeExtra(PATH)
video_curr_time.setOnClickListener { skip(false) }
video_duration.setOnClickListener { skip(true) }
try {
val options = VrVideoView.Options()
options.inputType = VrVideoView.Options.TYPE_MONO
val uri = if (path.startsWith("content://")) {
Uri.parse(path)
} else {
Uri.fromFile(File(path))
}
vr_video_view.apply {
loadVideo(uri, options)
pauseVideo()
setFlingingEnabled(true)
setPureTouchTracking(true)
// add custom buttons so we can position them and toggle visibility as desired
setFullscreenButtonEnabled(false)
setInfoButtonEnabled(false)
setTransitionViewEnabled(false)
setStereoModeButtonEnabled(false)
setOnClickListener {
handleClick()
}
setEventListener(object : VrVideoEventListener() {
override fun onClick() {
handleClick()
}
override fun onLoadSuccess() {
if (mDuration == 0) {
setupDuration(duration)
setupTimer()
}
if (mPlayOnReady || config.autoplayVideos) {
mPlayOnReady = false
mIsPlaying = true
resumeVideo()
} else {
video_toggle_play_pause.setImageResource(R.drawable.ic_play_outline_vector)
}
video_toggle_play_pause.beVisible()
}
override fun onCompletion() {
videoCompleted()
}
})
}
video_toggle_play_pause.setOnClickListener {
togglePlayPause()
}
} catch (e: Exception) {
showErrorToast(e)
}
window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
mIsFullscreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
toggleButtonVisibility()
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
setupButtons()
}
private fun setupDuration(duration: Long) {
mDuration = (duration / 1000).toInt()
video_seekbar.max = mDuration
video_duration.text = mDuration.getFormattedDuration()
setVideoProgress(0)
}
private fun setupTimer() {
runOnUiThread(object : Runnable {
override fun run() {
if (mIsPlaying && !mIsDragged) {
mCurrTime = (vr_video_view!!.currentPosition / 1000).toInt()
video_seekbar.progress = mCurrTime
video_curr_time.text = mCurrTime.getFormattedDuration()
}
mTimerHandler.postDelayed(this, 1000)
}
})
}
private fun togglePlayPause() {
mIsPlaying = !mIsPlaying
if (mIsPlaying) {
resumeVideo()
} else {
pauseVideo()
}
}
private fun resumeVideo() {
video_toggle_play_pause.setImageResource(R.drawable.ic_pause_outline_vector)
if (mCurrTime == mDuration) {
setVideoProgress(0)
mPlayOnReady = true
return
}
vr_video_view.playVideo()
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
private fun pauseVideo() {
vr_video_view.pauseVideo()
video_toggle_play_pause.setImageResource(R.drawable.ic_play_outline_vector)
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
private fun setVideoProgress(seconds: Int) {
vr_video_view.seekTo(seconds * 1000L)
video_seekbar.progress = seconds
mCurrTime = seconds
video_curr_time.text = seconds.getFormattedDuration()
}
private fun videoCompleted() {
mIsPlaying = false
mCurrTime = (vr_video_view.duration / 1000).toInt()
video_seekbar.progress = video_seekbar.max
video_curr_time.text = mDuration.getFormattedDuration()
pauseVideo()
}
private fun setupButtons() {
var right = 0
var bottom = 0
if (hasNavBar()) {
if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
bottom += navigationBarHeight
} else {
right += navigationBarWidth
bottom += navigationBarHeight
}
}
video_time_holder.setPadding(0, 0, right, bottom)
video_time_holder.background = resources.getDrawable(R.drawable.gradient_background)
video_time_holder.onGlobalLayout {
val newBottomMargin = video_time_holder.height - resources.getDimension(R.dimen.video_player_play_pause_size)
.toInt() - resources.getDimension(R.dimen.activity_margin).toInt()
(explore.layoutParams as RelativeLayout.LayoutParams).bottomMargin = newBottomMargin
(cardboard.layoutParams as RelativeLayout.LayoutParams).apply {
bottomMargin = newBottomMargin
rightMargin = navigationBarWidth
}
explore.requestLayout()
}
video_toggle_play_pause.setImageResource(R.drawable.ic_play_outline_vector)
cardboard.setOnClickListener {
vr_video_view.displayMode = CARDBOARD_DISPLAY_MODE
}
explore.setOnClickListener {
mIsExploreEnabled = !mIsExploreEnabled
vr_video_view.setPureTouchTracking(mIsExploreEnabled)
explore.setImageResource(if (mIsExploreEnabled) R.drawable.ic_explore_vector else R.drawable.ic_explore_off_vector)
}
}
private fun toggleButtonVisibility() {
val newAlpha = if (mIsFullscreen) 0f else 1f
arrayOf(cardboard, explore).forEach {
it.animate().alpha(newAlpha)
}
arrayOf(cardboard, explore, video_toggle_play_pause, video_curr_time, video_duration).forEach {
it.isClickable = !mIsFullscreen
}
video_seekbar.setOnSeekBarChangeListener(if (mIsFullscreen) null else this)
video_time_holder.animate().alpha(newAlpha).start()
}
private fun handleClick() {
mIsFullscreen = !mIsFullscreen
toggleButtonVisibility()
if (mIsFullscreen) {
hideSystemUI(false)
} else {
showSystemUI(false)
}
}
private fun skip(forward: Boolean) {
if (forward && mCurrTime == mDuration) {
return
}
val curr = vr_video_view.currentPosition
val twoPercents = Math.max((vr_video_view.duration / 50).toInt(), MIN_SKIP_LENGTH)
val newProgress = if (forward) curr + twoPercents else curr - twoPercents
val roundProgress = Math.round(newProgress / 1000f)
val limitedProgress = Math.max(Math.min(vr_video_view.duration.toInt(), roundProgress), 0)
setVideoProgress(limitedProgress)
if (!mIsPlaying) {
togglePlayPause()
}
}
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
if (fromUser) {
setVideoProgress(progress)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
vr_video_view.pauseVideo()
mIsDragged = true
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
mIsPlaying = true
resumeVideo()
mIsDragged = false
}
}
| app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PanoramaVideoActivity.kt | 1600424149 |
package com.kronos.router.model
import com.kronos.router.interceptor.Interceptor
/**
* Created by zhangyang on 16/7/16.
*/
class RouterParams {
var url: String = ""
var weight: Int = 0
var routerOptions: RouterOptions? = null
var openParams: HashMap<String, String> = hashMapOf()
val interceptors = mutableListOf<Interceptor>()
val realPath: String
get() {
try {
return url.let { it.subSequence(1, it.length).toString() }
} catch (e: Exception) {
e.printStackTrace()
}
return ""
}
fun put(key: String, value: String?) {
value?.apply {
openParams[key] = this
}
}
}
| RouterLib/src/main/java/com/kronos/router/model/RouterParams.kt | 4289518520 |
package com.apollographql.apollo3.ast
fun List<GQLDirective>.findDeprecationReason() = firstOrNull { it.name == "deprecated" }
?.let {
it.arguments
?.arguments
?.firstOrNull { it.name == "reason" }
?.value
?.let { value ->
if (value !is GQLStringValue) {
throw ConversionException("reason must be a string", it.sourceLocation)
}
value.value
}
?: "No longer supported"
}
/**
* @return `true` or `false` based on the `if` argument if the `optional` directive is present, `null` otherwise
*/
fun List<GQLDirective>.optionalValue(): Boolean? {
val directive = firstOrNull { it.name == "optional" } ?: return null
val argument = directive.arguments?.arguments?.firstOrNull { it.name == "if" }
// "if" argument defaults to true
return argument == null || argument.name == "if" && (argument.value as GQLBooleanValue).value
}
fun List<GQLDirective>.findNonnull() = any { it.name == "nonnull" }
fun GQLDirective.isApollo() = name in listOf("optional", "nonnull")
| apollo-ast/src/main/kotlin/com/apollographql/apollo3/ast/gqldirective.kt | 955234118 |
package org.jetbrains.completion.full.line.local
import kotlinx.coroutines.Dispatchers
object TestExecutionContext {
val default = ExecutionContext(Dispatchers.Default, checkCancelled = {})
}
| plugins/full-line/local/test/org/jetbrains/completion/full/line/local/TestExecutionContext.kt | 2908032569 |
package com.gimranov.zandy.app
import android.os.Build
import android.text.Html
import com.gimranov.zandy.app.data.Item
import org.json.JSONArray
import org.json.JSONObject
internal object ItemDisplayUtil {
fun datumDisplayComponents(label: String,
value: String): Pair<CharSequence, CharSequence> {
/* Since the field names are the API / internal form, we
* attempt to get a localized, human-readable version. */
val localizedLabel = Item.localizedStringForString(label)
if ("itemType" == label) {
return Pair(localizedLabel, Item.localizedStringForString(value))
}
if ("creators" == label) {
return Pair(localizedLabel, formatCreatorList(JSONArray(value)))
}
if ("title" == label || "note" == label || "abstractNote" == label) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Pair(localizedLabel, Html.fromHtml(value, Html.FROM_HTML_MODE_LEGACY))
} else {
@Suppress("DEPRECATION")
return Pair(localizedLabel, Html.fromHtml(value))
}
} else {
return Pair(localizedLabel, value)
}
}
fun formatCreatorList(creators: JSONArray): CharSequence {
/*
* Creators should be labeled with role and listed nicely
* This logic isn't as good as it could be.
*/
var creator: JSONObject
val sb = StringBuilder()
for (j in 0 until creators.length()) {
creator = creators.getJSONObject(j)
if (creator.getString("creatorType") == "author") {
if (creator.has("name"))
sb.append(creator.getString("name"))
else
sb.append(creator.getString("firstName") + " "
+ creator.getString("lastName"))
} else {
if (creator.has("name"))
sb.append(creator.getString("name"))
else
sb.append(creator.getString("firstName")
+ " "
+ creator.getString("lastName")
+ " ("
+ Item.localizedStringForString(creator
.getString("creatorType"))
+ ")")
}
if (j < creators.length() - 1)
sb.append(", ")
}
return sb.toString()
}
} | src/main/java/com/gimranov/zandy/app/ItemDisplayUtil.kt | 1969689134 |
package hello
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.context.annotation.Bean
import org.springframework.web.client.RestTemplate
@SpringBootApplication
class Application {
val log: Logger = LoggerFactory.getLogger(Application::class.java)
companion object {
@JvmStatic
fun main(args: Array<String>) {
SpringApplication.run(Application::class.java, *args)
}
}
@Bean
fun restTemplate(builder: RestTemplateBuilder): RestTemplate {
return builder.build()
}
@Bean
fun run(restTemplate: RestTemplate): CommandLineRunner {
return CommandLineRunner {
val quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote::class.java)
log.info(quote.toString())
}
}
} | gs-consuming-rest/src/main/kotlin/hello/Application.kt | 3633216663 |
/*
* 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.testGuiFramework.fixtures
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.terminal.JBTerminalPanel
import com.intellij.testGuiFramework.framework.Timeouts
import com.intellij.testGuiFramework.impl.GuiTestUtilKt
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitUntil
import com.intellij.ui.content.Content
import com.jediterm.terminal.model.TerminalTextBuffer
import org.fest.swing.core.Robot
import org.fest.swing.exception.ComponentLookupException
import org.fest.swing.exception.WaitTimedOutError
import org.fest.swing.timing.Timeout
class TerminalFixture(project: Project, robot: Robot, toolWindowId: String) : ToolWindowFixture(toolWindowId, project, robot) {
private val myJBTerminalPanel: JBTerminalPanel
private val terminalTextBuffer: TerminalTextBuffer
private val LOG: Logger = Logger.getInstance(TerminalFixture::class.java)
init {
val content: Content = this.getContent(getActiveTabName()) ?: throw Exception("Unable to get content of terminal tool window")
try {
myJBTerminalPanel = GuiTestUtilKt.withPauseWhenNull {
getJBTerminalPanel(content)
}
}
catch (e: WaitTimedOutError) {
throw ComponentLookupException("Unable to find JBTerminalPanel")
}
terminalTextBuffer = myJBTerminalPanel.terminalTextBuffer
}
fun getScreenLines(): String {
return terminalTextBuffer.screenLines
}
fun getLastLine(): String {
val lastLineIndex = terminalTextBuffer.height - 1
return terminalTextBuffer.getLine(lastLineIndex).text
}
fun waitUntilTextAppeared(text: String, timeout: Timeout = Timeouts.defaultTimeout) {
try {
waitUntil(condition = "'$text' appeared in terminal", timeout = timeout) {
terminalTextBuffer.screenLines.contains(text)
}
}
finally {
LOG.info("Text to find: $text")
LOG.info("Terminal text: ${terminalTextBuffer.historyBuffer.lines}")
}
}
fun waitUntilRegExAppeared(regex: Regex, timeout: Timeout = Timeouts.defaultTimeout) {
waitUntil(condition = "'$regex' appeared in terminal", timeout = timeout) {
terminalTextBuffer.screenLines.contains(regex)
}
}
private fun getActiveTabName(): String {
for (c in this.contents) {
if (c.isSelected) return c.tabName
}
return ""
}
private fun getJBTerminalPanel(content: Content): JBTerminalPanel? {
return try {
myRobot.finder().find(content.component) { component -> component is JBTerminalPanel } as JBTerminalPanel
}
catch (e: ComponentLookupException) {
null
}
}
}
| platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/TerminalFixture.kt | 3029192856 |
package ch.difty.scipamato.core.sync.jobs
import ch.difty.scipamato.common.logger
import org.jooq.DSLContext
import org.springframework.batch.item.ItemWriter
private val log = logger()
/**
* Base class for ItemWriter implementations.
*
* [T] the type of the entity to be written
*/
abstract class ScipamatoItemWriter<T> constructor(
protected val dslContext: DSLContext,
private val topic: String,
) : ItemWriter<T> {
override fun write(items: List<T>) {
var changeCount = 0
for (i in items) changeCount += executeUpdate(i)
log.info("$topic-sync: Successfully synced $changeCount $topic${if (changeCount == 1) "" else "s"}")
}
protected abstract fun executeUpdate(i: T): Int
}
| core/core-sync/src/main/kotlin/ch/difty/scipamato/core/sync/jobs/ScipamatoItemWriter.kt | 1900210717 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.ui.codereview.comment
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBInsets
import java.awt.*
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.geom.RoundRectangle2D
import javax.swing.JComponent
import javax.swing.JPanel
fun wrapComponentUsingRoundedPanel(component: JComponent): JComponent {
val wrapper = RoundedPanel(BorderLayout())
wrapper.add(component)
component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) =
wrapper.dispatchEvent(ComponentEvent(component, ComponentEvent.COMPONENT_RESIZED))
})
return wrapper
}
private class RoundedPanel(layout: LayoutManager?) : JPanel(layout) {
private var borderLineColor: Color? = null
init {
isOpaque = false
cursor = Cursor.getDefaultCursor()
updateColors()
}
override fun updateUI() {
super.updateUI()
updateColors()
}
private fun updateColors() {
val scheme = EditorColorsManager.getInstance().globalScheme
background = scheme.defaultBackground
borderLineColor = scheme.getColor(EditorColors.TEARLINE_COLOR)
}
override fun paintComponent(g: Graphics) {
GraphicsUtil.setupRoundedBorderAntialiasing(g)
val g2 = g as Graphics2D
val rect = Rectangle(size)
JBInsets.removeFrom(rect, insets)
// 2.25 scale is a @#$!% so we adjust sizes manually
val rectangle2d = RoundRectangle2D.Float(rect.x.toFloat() + 0.5f, rect.y.toFloat() + 0.5f,
rect.width.toFloat() - 1f, rect.height.toFloat() - 1f,
10f, 10f)
g2.color = background
g2.fill(rectangle2d)
borderLineColor?.let {
g2.color = borderLineColor
g2.draw(rectangle2d)
}
}
}
| platform/vcs-code-review/src/com/intellij/util/ui/codereview/comment/RoundedPanel.kt | 3401439991 |
package com.intellij.laf.macos
import com.intellij.ide.ui.laf.IntelliJLaf
import com.intellij.util.ui.UIUtil
import javax.swing.UIDefaults
import javax.swing.UIManager
class MacIntelliJLaf : IntelliJLaf() {
init {
putUserData(UIUtil.PLUGGABLE_LAF_KEY, name)
}
override fun getName(): String {
return MacLafProvider.LAF_NAME
}
override fun loadDefaults(defaults: UIDefaults) {
super.loadDefaults(defaults)
defaults["ClassLoader"] = javaClass.classLoader
}
override fun getPrefix(): String = "/com/intellij/ide/ui/laf/intellijlaf"
override fun getSystemPrefix(): String? = "macintellijlaf"
companion object {
fun isMacLaf() = UIManager.getLookAndFeel() is MacIntelliJLaf
}
} | plugins/laf/macos/src/com/intellij/laf/macos/MacIntelliJLaf.kt | 652172695 |
package com.trevjonez.ktor_playground.belongings
import com.trevjonez.ktor_playground.Validated
import java.time.ZonedDateTime
import java.util.UUID
interface ValidatedBelonging : Belonging, Validated {
override val id: UUID
override val createdOn: ZonedDateTime
override val updatedOn: ZonedDateTime
override val acquiredOn: ZonedDateTime
override val owner: UUID
} | src/main/kotlin/com/trevjonez/ktor_playground/belongings/ValidatedBelonging.kt | 1678806739 |
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.exceptions
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.intrinsics.*
import org.junit.Test
import java.lang.RuntimeException
import java.util.concurrent.*
import kotlin.concurrent.*
import kotlin.coroutines.*
import kotlin.test.*
/*
* All stacktrace validation skips line numbers
*/
class StackTraceRecoveryTest : TestBase() {
@Test
fun testAsync() = runTest {
fun createDeferred(depth: Int): Deferred<*> {
return if (depth == 0) {
async<Unit>(coroutineContext + NonCancellable) {
throw ExecutionException(null)
}
} else {
createDeferred(depth - 1)
}
}
val deferred = createDeferred(3)
val traces = listOf(
"java.util.concurrent.ExecutionException\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testAsync\$1\$createDeferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:99)\n" +
"\t(Coroutine boundary)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.oneMoreNestedMethod(StackTraceRecoveryTest.kt:49)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.nestedMethod(StackTraceRecoveryTest.kt:44)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testAsync\$1.invokeSuspend(StackTraceRecoveryTest.kt:17)\n",
"Caused by: java.util.concurrent.ExecutionException\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testAsync\$1\$createDeferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:21)\n" +
"\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)\n"
)
nestedMethod(deferred, *traces.toTypedArray())
deferred.join()
}
@Test
fun testCompletedAsync() = runTest {
val deferred = async<Unit>(coroutineContext + NonCancellable) {
throw ExecutionException(null)
}
deferred.join()
val stacktrace = listOf(
"java.util.concurrent.ExecutionException\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCompletedAsync\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:44)\n" +
"\t(Coroutine boundary)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.oneMoreNestedMethod(StackTraceRecoveryTest.kt:81)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.nestedMethod(StackTraceRecoveryTest.kt:75)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCompletedAsync\$1.invokeSuspend(StackTraceRecoveryTest.kt:71)",
"Caused by: java.util.concurrent.ExecutionException\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCompletedAsync\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:44)\n" +
"\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)"
)
nestedMethod(deferred, *stacktrace.toTypedArray())
}
private suspend fun nestedMethod(deferred: Deferred<*>, vararg traces: String) {
oneMoreNestedMethod(deferred, *traces)
assertTrue(true) // Prevent tail-call optimization
}
private suspend fun oneMoreNestedMethod(deferred: Deferred<*>, vararg traces: String) {
try {
deferred.await()
expectUnreached()
} catch (e: ExecutionException) {
verifyStackTrace(e, *traces)
}
}
@Test
fun testWithContext() = runTest {
val deferred = async<Unit>(NonCancellable, start = CoroutineStart.LAZY) {
throw RecoverableTestException()
}
outerMethod(deferred,
"kotlinx.coroutines.RecoverableTestException\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testWithContext\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:143)\n" +
"\t(Coroutine boundary)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.innerMethod(StackTraceRecoveryTest.kt:158)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$outerMethod\$2.invokeSuspend(StackTraceRecoveryTest.kt:151)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.outerMethod(StackTraceRecoveryTest.kt:150)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testWithContext\$1.invokeSuspend(StackTraceRecoveryTest.kt:141)\n",
"Caused by: kotlinx.coroutines.RecoverableTestException\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testWithContext\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:143)\n" +
"\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)\n")
deferred.join()
}
private suspend fun outerMethod(deferred: Deferred<*>, vararg traces: String) {
withContext(Dispatchers.IO) {
innerMethod(deferred, *traces)
}
assertTrue(true)
}
private suspend fun innerMethod(deferred: Deferred<*>, vararg traces: String) {
try {
deferred.await()
expectUnreached()
} catch (e: RecoverableTestException) {
verifyStackTrace(e, *traces)
}
}
@Test
fun testCoroutineScope() = runTest {
val deferred = async<Unit>(NonCancellable, start = CoroutineStart.LAZY) {
throw RecoverableTestException()
}
outerScopedMethod(deferred,
"kotlinx.coroutines.RecoverableTestException\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCoroutineScope\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:143)\n" +
"\t(Coroutine boundary)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.innerMethod(StackTraceRecoveryTest.kt:158)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$outerScopedMethod\$2\$1.invokeSuspend(StackTraceRecoveryTest.kt:193)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$outerScopedMethod\$2.invokeSuspend(StackTraceRecoveryTest.kt:151)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCoroutineScope\$1.invokeSuspend(StackTraceRecoveryTest.kt:141)\n",
"Caused by: kotlinx.coroutines.RecoverableTestException\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCoroutineScope\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:143)\n" +
"\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)\n")
deferred.join()
}
public class TrickyException() : Throwable() {
// To be sure ctor is never invoked
@Suppress("UNUSED", "UNUSED_PARAMETER")
private constructor(message: String, cause: Throwable): this() {
error("Should never be called")
}
override fun initCause(cause: Throwable?): Throwable {
error("Can't call initCause")
}
}
@Test
fun testThrowingInitCause() = runTest {
val deferred = async<Unit>(NonCancellable) {
expect(2)
throw TrickyException()
}
try {
expect(1)
deferred.await()
} catch (e: TrickyException) {
assertNull(e.cause)
finish(3)
}
}
private suspend fun outerScopedMethod(deferred: Deferred<*>, vararg traces: String) = coroutineScope {
supervisorScope {
innerMethod(deferred, *traces)
assertTrue(true)
}
assertTrue(true)
}
@Test
fun testSelfSuppression() = runTest {
try {
runBlocking {
val job = launch {
coroutineScope<Unit> {
throw RecoverableTestException()
}
}
job.join()
expectUnreached()
}
expectUnreached()
} catch (e: RecoverableTestException) {
checkCycles(e)
}
}
private suspend fun throws() {
yield() // TCE
throw RecoverableTestException()
}
private suspend fun awaiter() {
val task = GlobalScope.async(Dispatchers.Default, start = CoroutineStart.LAZY) { throws() }
task.await()
yield() // TCE
}
@Test
fun testNonDispatchedRecovery() {
val await = suspend { awaiter() }
val barrier = CyclicBarrier(2)
var exception: Throwable? = null
thread {
await.startCoroutineUnintercepted(Continuation(EmptyCoroutineContext) {
exception = it.exceptionOrNull()
barrier.await()
})
}
barrier.await()
val e = exception
assertNotNull(e)
verifyStackTrace(e, "kotlinx.coroutines.RecoverableTestException\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.throws(StackTraceRecoveryTest.kt:280)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.access\$throws(StackTraceRecoveryTest.kt:20)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$throws\$1.invokeSuspend(StackTraceRecoveryTest.kt)\n" +
"\t(Coroutine boundary)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.awaiter(StackTraceRecoveryTest.kt:285)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testNonDispatchedRecovery\$await\$1.invokeSuspend(StackTraceRecoveryTest.kt:291)\n" +
"Caused by: kotlinx.coroutines.RecoverableTestException")
}
private class Callback(val cont: CancellableContinuation<*>)
@Test
fun testCancellableContinuation() = runTest {
val channel = Channel<Callback>(1)
launch {
try {
awaitCallback(channel)
} catch (e: Throwable) {
verifyStackTrace(e, "kotlinx.coroutines.RecoverableTestException\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCancellableContinuation\$1.invokeSuspend(StackTraceRecoveryTest.kt:329)\n" +
"\t(Coroutine boundary)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.awaitCallback(StackTraceRecoveryTest.kt:348)\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCancellableContinuation\$1\$1.invokeSuspend(StackTraceRecoveryTest.kt:322)\n" +
"Caused by: kotlinx.coroutines.RecoverableTestException\n" +
"\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCancellableContinuation\$1.invokeSuspend(StackTraceRecoveryTest.kt:329)")
}
}
val callback = channel.receive()
callback.cont.resumeWithException(RecoverableTestException())
}
private suspend fun awaitCallback(channel: Channel<Callback>) {
suspendCancellableCoroutine<Unit> { cont ->
channel.trySend(Callback(cont))
}
yield() // nop to make sure it is not a tail call
}
}
| kotlinx-coroutines-core/jvm/test/exceptions/StackTraceRecoveryTest.kt | 2561270705 |
package com.jonathan.bogle.lurk
import android.app.Application
import com.jonathan.bogle.lurk.util.Prefs
import com.jonathan.bogle.lurk.util.TinyDB
import org.polaric.colorful.Colorful
/**
* Created by bogle on 7/25/17.
*/
class LurkApp: Application() {
override fun onCreate() {
super.onCreate()
Colorful.defaults()
.primaryColor(Colorful.ThemeColor.DEEP_ORANGE)
.accentColor(Colorful.ThemeColor.LIME)
.translucent(false)
.dark(true);
Colorful.init(this)
prefs = Prefs(applicationContext)
tinyDB = TinyDB(applicationContext)
}
companion object {
var prefs: Prefs? = null
var tinyDB: TinyDB? = null
}
}
val prefs: Prefs by lazy { LurkApp.prefs!! }
val tinyDB: TinyDB by lazy { LurkApp.tinyDB!! } | app/src/main/java/com/jonathan/bogle/lurk/LurkApp.kt | 2690718266 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots
import com.intellij.openapi.module.Module
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.testFramework.rules.TempDirectory
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.jps.model.module.UnknownSourceRootType
import org.jetbrains.jps.model.serialization.JpsModelSerializerExtension
import org.junit.*
class CustomSourceRootTypeTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@Rule
@JvmField
val projectModel = ProjectModelRule()
@Rule
@JvmField
val tempDirectory = TempDirectory()
@Rule
@JvmField
val disposable = DisposableRule()
lateinit var module: Module
@Before
fun setUp() {
module = projectModel.createModule()
JpsModelSerializerExtension.getExtensions()
}
@Test
fun `load unload custom source root`() {
val srcDir = projectModel.baseProjectDir.newVirtualDirectory("src")
runWithRegisteredExtension {
val model = createModifiableModel(module)
model.addContentEntry(srcDir).addSourceFolder(srcDir, TestCustomSourceRootType.INSTANCE, TestCustomSourceRootProperties("hello"))
val committed = commitModifiableRootModel(model)
val sourceFolder = committed.contentEntries.single().sourceFolders.single()
assertThat(sourceFolder.file).isEqualTo(srcDir)
assertThat(sourceFolder.rootType).isEqualTo(TestCustomSourceRootType.INSTANCE)
assertThat((sourceFolder.jpsElement.properties as TestCustomSourceRootProperties).testString).isEqualTo("hello")
}
val sourceFolderWithUnknownType = ModuleRootManager.getInstance(module).contentEntries.single().sourceFolders.single()
assertThat(sourceFolderWithUnknownType.file).isEqualTo(srcDir)
assertThat(sourceFolderWithUnknownType.rootType).isInstanceOf(UnknownSourceRootType::class.java)
TestCustomRootModelSerializerExtension.registerTestCustomSourceRootType(tempDirectory.newDirectory(), disposable.disposable)
val sourceFolder = ModuleRootManager.getInstance(module).contentEntries.single().sourceFolders.single()
assertThat(sourceFolder.file).isEqualTo(srcDir)
assertThat(sourceFolder.rootType).isEqualTo(TestCustomSourceRootType.INSTANCE)
assertThat((sourceFolder.jpsElement.properties as TestCustomSourceRootProperties).testString).isEqualTo("hello")
}
@Test
fun `edit custom root properties`() {
Assume.assumeTrue("Editing of custom root properties isn't correctly implemented in the current project model",
ProjectModelRule.isWorkspaceModelEnabled)
TestCustomRootModelSerializerExtension.registerTestCustomSourceRootType(tempDirectory.newDirectory(), disposable.disposable)
val srcDir = projectModel.baseProjectDir.newVirtualDirectory("src")
val committed = run {
val model = createModifiableModel(module)
model.addContentEntry(srcDir).addSourceFolder(srcDir, TestCustomSourceRootType.INSTANCE, TestCustomSourceRootProperties("foo"))
val sourceFolder = model.contentEntries.single().sourceFolders.single()
assertThat(sourceFolder.rootType).isEqualTo(TestCustomSourceRootType.INSTANCE)
assertThat(sourceFolder.customRootProperties).isEqualTo("foo")
sourceFolder.customRootProperties = "bar"
assertThat(model.contentEntries.single().sourceFolders.single().customRootProperties).isEqualTo("bar")
commitModifiableRootModel(model)
}
assertThat(committed.contentEntries.single().sourceFolders.single().customRootProperties).isEqualTo("bar")
val committed2 = run {
val model = createModifiableModel(module)
val contentEntry = model.contentEntries.single()
val sourceFolder = contentEntry.sourceFolders.single()
assertThat(sourceFolder.customRootProperties).isEqualTo("bar")
sourceFolder.customRootProperties = "baz"
assertThat(sourceFolder.customRootProperties).isEqualTo("baz")
assertThat(contentEntry.sourceFolders.single().customRootProperties).isEqualTo("baz")
assertThat(model.contentEntries.single().sourceFolders.single().customRootProperties).isEqualTo("baz")
commitModifiableRootModel(model)
}
assertThat(committed2.contentEntries.single().sourceFolders.single().customRootProperties).isEqualTo("baz")
}
@Test
fun `discard changes in custom properties if model is disposed`() {
TestCustomRootModelSerializerExtension.registerTestCustomSourceRootType(tempDirectory.newDirectory(), disposable.disposable)
val srcDir = projectModel.baseProjectDir.newVirtualDirectory("src")
val committed = run {
val model = createModifiableModel(module)
model.addContentEntry(srcDir).addSourceFolder(srcDir, TestCustomSourceRootType.INSTANCE, TestCustomSourceRootProperties("foo"))
commitModifiableRootModel(model)
}
assertThat(committed.contentEntries.single().sourceFolders.single().customRootProperties).isEqualTo("foo")
run {
val model = createModifiableModel(module)
model.contentEntries.single().sourceFolders.single().customRootProperties = "bar"
assertThat(model.contentEntries.single().sourceFolders.single().customRootProperties).isEqualTo("bar")
model.dispose()
}
assertThat(committed.contentEntries.single().sourceFolders.single().customRootProperties).isEqualTo("foo")
}
private var SourceFolder.customRootProperties: String?
get() = (jpsElement.properties as TestCustomSourceRootProperties).testString
set(value) {
(jpsElement.properties as TestCustomSourceRootProperties).testString = value
}
private fun runWithRegisteredExtension(action: () -> Unit) {
val disposable = Disposer.newDisposable()
TestCustomRootModelSerializerExtension.registerTestCustomSourceRootType(tempDirectory.newDirectory(), disposable)
try {
action()
}
finally {
Disposer.dispose(disposable)
}
}
} | platform/lang-impl/testSources/com/intellij/openapi/roots/CustomSourceRootTypeTest.kt | 3201364988 |
fun idiv(a: Int, b: Int): Int =
if (b == 0) throw Exception("Division by zero") else a / b
fun foo(): Int {
var sum = 0
var i = 2
while (i > -10) {
sum += try { idiv(100, i) } catch (e: Exception) { break }
i--
}
return sum
}
fun box(): String {
val test = foo()
if (test != 150) return "Failed, test=$test"
return "OK"
} | backend.native/tests/external/codegen/box/controlStructures/tryCatchInExpressions/tryAndBreak.kt | 2969757630 |
import kotlin.reflect.KMutableProperty
class Bar(name: String) {
var foo: String = name
private set
fun test() {
val p = Bar::foo
if (p !is KMutableProperty<*>) throw AssertionError("Fail: p is not a KMutableProperty")
p.set(this, "OK")
}
}
fun box(): String {
val bar = Bar("Fail")
bar.test()
return bar.foo
}
| backend.native/tests/external/codegen/box/callableReference/property/privateSetterInsideClass.kt | 1490321331 |
fun foo(): String {
val s = try {
"OK"
} catch (e: Exception) {
try {
""
} catch (ee: Exception) {
""
}
}
return s
}
fun box(): String {
return foo()
} | backend.native/tests/external/codegen/box/regressions/kt3107.kt | 1166270001 |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.platform.client.request
import android.os.Parcel
import androidx.health.platform.client.proto.DataProto
import androidx.health.platform.client.proto.RequestProto
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
// Checks ipc serialization/deserialization
@RunWith(AndroidJUnit4::class)
class DeleteDataRequestTest {
@Test
fun writeToParcel() {
val deleteDataRequest =
DeleteDataRequest(
uids =
listOf(
RequestProto.DataTypeIdPair.newBuilder()
.setDataType(DataProto.DataType.newBuilder().setName("Steps").build())
.setId("uid1")
.build(),
RequestProto.DataTypeIdPair.newBuilder()
.setDataType(DataProto.DataType.newBuilder().setName("Steps").build())
.setId("uid2")
.build(),
RequestProto.DataTypeIdPair.newBuilder()
.setDataType(DataProto.DataType.newBuilder().setName("Steps").build())
.setId("uid3")
.build(),
),
clientIds =
listOf(
RequestProto.DataTypeIdPair.newBuilder()
.setDataType(DataProto.DataType.newBuilder().setName("Steps").build())
.setId("clientId1")
.build(),
RequestProto.DataTypeIdPair.newBuilder()
.setDataType(DataProto.DataType.newBuilder().setName("Steps").build())
.setId("clientId2")
.build(),
RequestProto.DataTypeIdPair.newBuilder()
.setDataType(DataProto.DataType.newBuilder().setName("Steps").build())
.setId("clientId3")
.build(),
)
)
val parcel: Parcel = Parcel.obtain()
parcel.writeParcelable(deleteDataRequest, 0)
parcel.setDataPosition(0)
@Suppress("Deprecation") // readParcelable deprecated in T and introduced new methods
val out: DeleteDataRequest? =
parcel.readParcelable(DeleteDataRequest::class.java.classLoader)
assertThat(out?.uids).isEqualTo(deleteDataRequest.uids)
}
}
| health/connect/connect-client/src/test/java/androidx/health/platform/client/request/DeleteDataRequestTest.kt | 2812943222 |
/*
* 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.
*/
@file:JvmName("UastLiteralUtils")
package org.jetbrains.uast
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.psi.PsiReference
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.expressions.UInjectionHost
/**
* Checks if the [UElement] is a null literal.
*
* @return true if the receiver is a null literal, false otherwise.
*/
fun UElement.isNullLiteral(): Boolean = this is ULiteralExpression && this.isNull
/**
* Checks if the [UElement] is a boolean literal.
*
* @return true if the receiver is a boolean literal, false otherwise.
*/
fun UElement.isBooleanLiteral(): Boolean = this is ULiteralExpression && this.isBoolean
/**
* Checks if the [UElement] is a `true` boolean literal.
*
* @return true if the receiver is a `true` boolean literal, false otherwise.
*/
fun UElement.isTrueLiteral(): Boolean = this is ULiteralExpression && this.isBoolean && this.value == true
/**
* Checks if the [UElement] is a `false` boolean literal.
*
* @return true if the receiver is a `false` boolean literal, false otherwise.
*/
fun UElement.isFalseLiteral(): Boolean = this is ULiteralExpression && this.isBoolean && this.value == false
/**
* Checks if the [UElement] is a [String] literal.
*
* @return true if the receiver is a [String] literal, false otherwise.
*/
@Deprecated("doesn't support UInjectionHost, most likely it is not what you want", ReplaceWith("isInjectionHost()"))
fun UElement.isStringLiteral(): Boolean = this is ULiteralExpression && this.isString
/**
* Checks if the [UElement] is a [PsiLanguageInjectionHost] holder.
*
* NOTE: It is a transitional function until everything will migrate to [UInjectionHost]
*/
fun UElement?.isInjectionHost(): Boolean = this is UInjectionHost || (this is UExpression && this.sourceInjectionHost != null)
/**
* Returns the [String] literal value.
*
* @return literal text if the receiver is a valid [String] literal, null otherwise.
*/
@Deprecated("doesn't support UInjectionHost, most likely it is not what you want", ReplaceWith("UExpression.evaluateString()"))
@Suppress("Deprecation")
fun UElement.getValueIfStringLiteral(): String? =
if (isStringLiteral()) (this as ULiteralExpression).value as String else null
/**
* Checks if the [UElement] is a [Number] literal (Integer, Long, Float, Double, etc.).
*
* @return true if the receiver is a [Number] literal, false otherwise.
*/
fun UElement.isNumberLiteral(): Boolean = this is ULiteralExpression && this.value is Number
/**
* Checks if the [UElement] is an integral literal (is an [Integer], [Long], [Short], [Char] or [Byte]).
*
* @return true if the receiver is an integral literal, false otherwise.
*/
fun UElement.isIntegralLiteral(): Boolean = this is ULiteralExpression && when (value) {
is Int -> true
is Long -> true
is Short -> true
is Char -> true
is Byte -> true
else -> false
}
/**
* Returns the integral value of the literal.
*
* @return long representation of the literal expression value,
* 0 if the receiver literal expression is not a integral one.
*/
fun ULiteralExpression.getLongValue(): Long = value.let {
when (it) {
is Long -> it
is Int -> it.toLong()
is Short -> it.toLong()
is Char -> it.toLong()
is Byte -> it.toLong()
else -> 0
}
}
/**
* @return corresponding [PsiLanguageInjectionHost] for this [UExpression] if it exists.
* Tries to not return same [PsiLanguageInjectionHost] for different UElement-s, thus returns `null` if host could be obtained from
* another [UExpression].
*/
val UExpression.sourceInjectionHost: PsiLanguageInjectionHost?
get() {
(this.sourcePsi as? PsiLanguageInjectionHost)?.let { return it }
// following is a handling of KT-27283
if (this !is ULiteralExpression) return null
val parent = this.uastParent
if (parent is UPolyadicExpression && parent.sourcePsi is PsiLanguageInjectionHost) return null
(this.sourcePsi?.parent as? PsiLanguageInjectionHost)?.let { return it }
return null
}
val UExpression.allPsiLanguageInjectionHosts: List<PsiLanguageInjectionHost>
@ApiStatus.Experimental
get() {
sourceInjectionHost?.let { return listOf(it) }
(this as? UPolyadicExpression)?.let { return this.operands.mapNotNull { it.sourceInjectionHost } }
return emptyList()
}
@ApiStatus.Experimental
fun isConcatenation(uExpression: UElement?): Boolean {
if (uExpression !is UPolyadicExpression) return false
if (uExpression.operator != UastBinaryOperator.PLUS) return false
return true
}
/**
* @return a non-strict parent [PsiLanguageInjectionHost] for [ULiteralExpression.sourcePsi] of given literal expression if it exists.
*
* NOTE: consider using [sourceInjectionHost] as more performant. Probably will be deprecated in future.
*/
val ULiteralExpression.psiLanguageInjectionHost: PsiLanguageInjectionHost?
get() = this.sourcePsi?.let { PsiTreeUtil.getParentOfType(it, PsiLanguageInjectionHost::class.java, false) }
/**
* @return if given [uElement] is an [ULiteralExpression] but not a [UInjectionHost]
* (which could happen because of "KotlinULiteralExpression and PsiLanguageInjectionHost mismatch", see KT-27283 )
* then tries to convert it to [UInjectionHost] and return it,
* otherwise return [uElement] itself
*
* NOTE: when `kotlin.uast.force.uinjectionhost` flag is `true` this method is useless because there is no mismatch anymore
*/
@ApiStatus.Experimental
fun wrapULiteral(uElement: UExpression): UExpression {
if (uElement is ULiteralExpression && uElement !is UInjectionHost) {
uElement.sourceInjectionHost.toUElementOfType<UInjectionHost>()?.let { return it }
}
return uElement
}
/**
* @return all references injected into this [ULiteralExpression]
*
* Note: getting references simply from the `sourcePsi` will not work for Kotlin polyadic strings for instance
*/
val ULiteralExpression.injectedReferences: Iterable<PsiReference>
get() {
val element = this.psiLanguageInjectionHost ?: return emptyList()
val references = element.references.asSequence()
val innerReferences = element.children.asSequence().flatMap { e -> e.references.asSequence() }
return (references + innerReferences).asIterable()
}
@JvmOverloads
fun deepLiteralSearch(expression: UExpression, maxDepth: Int = 5): Sequence<ULiteralExpression> {
val visited = HashSet<UExpression>()
fun deepLiteralSearchInner(expression: UExpression, maxDepth: Int): Sequence<ULiteralExpression> {
if (maxDepth <= 0 || !visited.add(expression)) return emptySequence();
return when (expression) {
is ULiteralExpression -> sequenceOf(expression)
is UPolyadicExpression -> expression.operands.asSequence().flatMap { deepLiteralSearchInner(it, maxDepth - 1) }
is UReferenceExpression -> expression.resolve()
.toUElementOfType<UVariable>()
?.uastInitializer
?.let { deepLiteralSearchInner(it, maxDepth - 1) }.orEmpty()
else -> emptySequence()
}
}
return deepLiteralSearchInner(expression, maxDepth)
} | uast/uast-common/src/org/jetbrains/uast/expressions/uastLiteralUtils.kt | 2732555673 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore.schemeManager
import com.intellij.configurationStore.LOG
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.configurationStore.digest
import com.intellij.openapi.options.Scheme
import com.intellij.openapi.options.SchemeProcessor
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.WriteExternalException
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.util.ArrayUtilRt
import org.jdom.Element
internal class SchemeDataHolderImpl<out T: Scheme, in MUTABLE_SCHEME : T>(private val processor: SchemeProcessor<T, MUTABLE_SCHEME>,
private val bytes: ByteArray,
private val externalInfo: ExternalInfo) : SchemeDataHolder<MUTABLE_SCHEME> {
override fun read(): Element {
try {
return JDOMUtil.load(CharsetToolkit.inputStreamSkippingBOM(bytes.inputStream()))
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
throw RuntimeException("Cannot read ${externalInfo.fileName}", e)
}
}
override fun updateDigest(scheme: MUTABLE_SCHEME) {
try {
updateDigest(processor.writeScheme(scheme) as Element)
}
catch (e: WriteExternalException) {
LOG.error("Cannot update digest for ${externalInfo.fileName}", e)
}
}
override fun updateDigest(data: Element?) {
externalInfo.digest = data?.digest() ?: ArrayUtilRt.EMPTY_BYTE_ARRAY
}
} | platform/configuration-store-impl/src/schemeManager/SchemeDataHolderImpl.kt | 2947402711 |
// 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.refactoring.inline
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.codeInsight.TargetElementUtil.ELEMENT_NAME_ACCEPTED
import com.intellij.codeInsight.TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED
import com.intellij.lang.refactoring.InlineActionHandler
import com.intellij.openapi.util.io.FileUtil
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.testFramework.LightProjectDescriptor
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.idea.test.withCustomCompilerOptions
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
abstract class AbstractInlineTest : KotlinLightCodeInsightFixtureTestCase() {
protected fun doTest(unused: String) {
val testDataFile = testDataFile()
val afterFile = testDataFile("${fileName()}.after")
val mainFileName = testDataFile.name
val mainFileBaseName = FileUtil.getNameWithoutExtension(mainFileName)
val extraFiles = testDataFile.parentFile.listFiles { _, name ->
name != mainFileName && name.startsWith("$mainFileBaseName.") && (name.endsWith(".kt") || name.endsWith(".java"))
} ?: emptyArray()
val allFiles = (extraFiles + testDataFile).associateBy { myFixture.configureByFile(it.name) }
val fileWithCaret = allFiles.values.singleOrNull { "<caret>" in it.readText() } ?: error("Must have one <caret>")
val file = myFixture.configureByFile(fileWithCaret.name)
withCustomCompilerOptions(file.text, project, module) {
val afterFileExists = afterFile.exists()
val targetElement = TargetElementUtil.findTargetElement(
myFixture.editor,
ELEMENT_NAME_ACCEPTED or REFERENCED_ELEMENT_ACCEPTED
)
val handler = if (targetElement != null)
InlineActionHandler.EP_NAME.extensions.firstOrNull { it.canInlineElement(targetElement) }
else
null
val expectedErrors = InTextDirectivesUtils.findLinesWithPrefixesRemoved(myFixture.file.text, "// ERROR: ")
if (handler != null) {
try {
runWriteAction { handler.inlineElement(project, editor, targetElement) }
for ((extraPsiFile, extraFile) in allFiles) {
KotlinTestUtils.assertEqualsToFile(File("${extraFile.path}.after"), extraPsiFile.text)
}
} catch (e: CommonRefactoringUtil.RefactoringErrorHintException) {
TestCase.assertFalse("Refactoring not available: ${e.message}", afterFileExists)
TestCase.assertEquals("Expected errors", 1, expectedErrors.size)
TestCase.assertEquals("Error message", expectedErrors[0].replace("\\n", "\n"), e.message)
} catch (e: BaseRefactoringProcessor.ConflictsInTestsException) {
TestCase.assertFalse("Conflicts: ${e.message}", afterFileExists)
TestCase.assertEquals("Expected errors", 1, expectedErrors.size)
TestCase.assertEquals("Error message", expectedErrors[0].replace("\\n", "\n"), e.message)
}
} else {
TestCase.assertFalse("No refactoring handler available", afterFileExists)
}
}
}
override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
abstract class AbstractInlineTestWithSomeDescriptors : AbstractInlineTest() {
override fun getProjectDescriptor(): LightProjectDescriptor = getProjectDescriptorFromFileDirective()
}
| plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/inline/AbstractInlineTest.kt | 336837880 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui
import com.intellij.CommonBundle
import com.intellij.icons.AllIcons
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.collaboration.ui.codereview.InlineIconButton
import icons.CollaborationToolsIcons
import org.jetbrains.plugins.github.i18n.GithubBundle
import java.awt.event.ActionListener
import java.util.concurrent.CompletableFuture
import javax.swing.JComponent
internal object GHTextActions {
fun createDeleteButton(delete: () -> CompletableFuture<out Any?>): JComponent {
val icon = CollaborationToolsIcons.Delete
val hoverIcon = CollaborationToolsIcons.DeleteHovered
val button = InlineIconButton(icon, hoverIcon, tooltip = CommonBundle.message("button.delete"))
button.actionListener = ActionListener {
if (MessageDialogBuilder.yesNo(GithubBundle.message("pull.request.review.comment.delete.dialog.title"),
GithubBundle.message("pull.request.review.comment.delete.dialog.msg")).ask(button)) {
delete()
}
}
return button
}
fun createEditButton(paneHandle: GHEditableHtmlPaneHandle): JComponent {
val icon = AllIcons.General.Inline_edit
val hoverIcon = AllIcons.General.Inline_edit_hovered
val button = InlineIconButton(icon, hoverIcon, tooltip = CommonBundle.message("button.edit"))
button.actionListener = ActionListener {
paneHandle.showAndFocusEditor()
}
return button
}
} | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHTextActions.kt | 63814402 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.ml.local
import com.intellij.codeInsight.completion.CompletionLocation
import com.intellij.codeInsight.completion.ml.ContextFeatures
import com.intellij.codeInsight.completion.ml.ElementFeatureProvider
import com.intellij.codeInsight.completion.ml.MLFeatureValue
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.lang.java.JavaLanguage
import com.intellij.ml.local.models.LocalModelsManager
import com.intellij.ml.local.models.frequency.classes.ClassesFrequencyLocalModel
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
class JavaFrequencyElementFeatureProvider : ElementFeatureProvider {
override fun getName(): String = "local"
override fun calculateFeatures(element: LookupElement,
location: CompletionLocation,
contextFeatures: ContextFeatures): MutableMap<String, MLFeatureValue> {
val features = mutableMapOf<String, MLFeatureValue>()
val psi = element.psiElement
val receiverClassName = contextFeatures.getUserData(JavaFrequencyContextFeatureProvider.RECEIVER_CLASS_NAME_KEY)
val classFrequencies = contextFeatures.getUserData(JavaFrequencyContextFeatureProvider.RECEIVER_CLASS_FREQUENCIES_KEY)
if (psi is PsiMethod && receiverClassName != null && classFrequencies != null) {
psi.containingClass?.let { cls ->
JavaLocalModelsUtil.getClassName(cls)?.let { className ->
if (receiverClassName == className) {
JavaLocalModelsUtil.getMethodName(psi)?.let { methodName ->
val frequency = classFrequencies.getMethodFrequency(methodName)
if (frequency > 0) {
val totalUsages = classFrequencies.getTotalFrequency()
features["absolute_method_frequency"] = MLFeatureValue.numerical(frequency)
features["relative_method_frequency"] = MLFeatureValue.numerical(frequency.toDouble() / totalUsages)
}
}
}
}
}
}
val classesModel = LocalModelsManager.getInstance(location.project).getModel<ClassesFrequencyLocalModel>(JavaLanguage.INSTANCE)
if (psi is PsiClass && classesModel != null && classesModel.readyToUse()) {
JavaLocalModelsUtil.getClassName(psi)?.let { className ->
classesModel.getClass(className)?.let {
features["absolute_class_frequency"] = MLFeatureValue.numerical(it)
features["relative_class_frequency"] = MLFeatureValue.numerical(it.toDouble() / classesModel.totalClassesUsages())
}
}
}
return features
}
} | plugins/ml-local-models/java/src/com/intellij/java/ml/local/JavaFrequencyElementFeatureProvider.kt | 1994336484 |
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.highlighting
import com.intellij.codeInsight.daemon.RainbowVisitor
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.types.TypeEvalContext
class PyRainbowVisitor : RainbowVisitor() {
object Holder {
val IGNORED_NAMES = setOf(PyNames.NONE, PyNames.TRUE, PyNames.FALSE)
val DEFAULT_HIGHLIGHTING_KEY = DefaultLanguageHighlighterColors.LOCAL_VARIABLE
@JvmStatic
val HIGHLIGHTING_KEYS: Set<TextAttributesKey> = setOf(PyHighlighter.PY_PARAMETER, DEFAULT_HIGHLIGHTING_KEY)
}
override fun suitableForFile(file: PsiFile): Boolean = file is PyFile
override fun visit(element: PsiElement) {
when (element) {
is PyReferenceExpression -> processReference(element)
is PyTargetExpression -> processTarget(element)
is PyNamedParameter -> processNamedParameter(element)
}
}
override fun clone(): PyRainbowVisitor = PyRainbowVisitor()
private fun processReference(referenceExpression: PyReferenceExpression) {
val context = getReferenceContext(referenceExpression, mutableSetOf()) ?: return
val name = updateNameIfGlobal(context, referenceExpression.name) ?: return
addInfo(context, referenceExpression, name)
}
private fun processTarget(targetExpression: PyTargetExpression) {
val context = getTargetContext(targetExpression) ?: return
val name = updateNameIfGlobal(context, targetExpression.name) ?: return
addInfo(context, targetExpression, name)
}
private fun processNamedParameter(namedParameter: PyNamedParameter) {
val context = getNamedParameterContext(namedParameter) ?: return
val name = namedParameter.name ?: return
val element = namedParameter.nameIdentifier ?: return
addInfo(context, element, name, PyHighlighter.PY_PARAMETER)
}
private fun getReferenceContext(referenceExpression: PyReferenceExpression,
visitedReferenceExpressions: MutableSet<PyReferenceExpression>): PsiElement? {
if (referenceExpression.isQualified || referenceExpression.name in Holder.IGNORED_NAMES) return null
val resolved = referenceExpression.reference.resolve()
return when (resolved) {
is PyTargetExpression -> getTargetContext(resolved)
is PyNamedParameter -> getNamedParameterContext(resolved)
is PyReferenceExpression -> {
if (!visitedReferenceExpressions.add(resolved)) return getLeastCommonScope(visitedReferenceExpressions)
return if (resolved.parent is PyAugAssignmentStatement) getReferenceContext(resolved, visitedReferenceExpressions) else null
}
else -> null
}
}
private fun getTargetContext(targetExpression: PyTargetExpression): PsiElement? {
if (targetExpression.isQualified || targetExpression.name in Holder.IGNORED_NAMES) return null
val parent = targetExpression.parent
if (parent is PyGlobalStatement) return targetExpression.containingFile
if (parent is PyNonlocalStatement) {
val outerResolved = targetExpression.reference.resolve()
return if (outerResolved is PyTargetExpression) getTargetContext(outerResolved) else null
}
val context = TypeEvalContext.codeInsightFallback(targetExpression.project)
val resolveResults = targetExpression.getReference(PyResolveContext.defaultContext(context)).multiResolve(false)
val resolvesToGlobal = resolveResults
.asSequence()
.map { it.element }
.any { it is PyTargetExpression && it.parent is PyGlobalStatement }
if (resolvesToGlobal) return targetExpression.containingFile
val resolvedNonLocal = resolveResults
.asSequence()
.map { it.element }
.filterIsInstance<PyTargetExpression>()
.find { it.parent is PyNonlocalStatement }
if (resolvedNonLocal != null) return getTargetContext(resolvedNonLocal)
val scopeOwner = ScopeUtil.getScopeOwner(targetExpression)
return if (scopeOwner is PyFile || scopeOwner is PyFunction || scopeOwner is PyLambdaExpression) scopeOwner else null
}
private fun getNamedParameterContext(namedParameter: PyNamedParameter): PsiElement? {
if (namedParameter.isSelf) return null
val scopeOwner = ScopeUtil.getScopeOwner(namedParameter)
return if (scopeOwner is PyLambdaExpression || scopeOwner is PyFunction) scopeOwner else null
}
private fun updateNameIfGlobal(context: PsiElement, name: String?) = if (context is PyFile && name != null) "global_$name" else name
private fun addInfo(context: PsiElement, rainbowElement: PsiElement, name: String, key: TextAttributesKey? = Holder.DEFAULT_HIGHLIGHTING_KEY) {
addInfo(getInfo(context, rainbowElement, name, key))
}
private fun getLeastCommonScope(elements: Collection<PsiElement>): ScopeOwner? {
var result: ScopeOwner? = null
elements.forEach {
val currentScopeOwner = ScopeUtil.getScopeOwner(it)
if (result == null) {
result = currentScopeOwner
}
else if (result != currentScopeOwner && currentScopeOwner != null && PsiTreeUtil.isAncestor(result, currentScopeOwner, true)) {
result = currentScopeOwner
}
}
return result
}
}
| python/src/com/jetbrains/python/highlighting/PyRainbowVisitor.kt | 4026647920 |
// "Add annotation target" "false"
// ACTION: Create test
// ACTION: Extract 'Test' from current file
// ACTION: Make internal
// ACTION: Make private
// ERROR: This annotation is not applicable to target 'class' and use site target '@get'
annotation class Ann
<caret>@get:Ann
class Test(val foo: String) | plugins/kotlin/idea/tests/testData/quickfix/addAnnotationTarget/use-site_invalid.kt | 2254552496 |
/*
The MIT License (MIT)
FTL-Compiler Copyright (c) 2016 thoma
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.thomas.needham.ftl.backend
/**
* Container class for Opcodes Enum
*/
public class EnumOpcodes {
/**
* Enum containing a list of JVM 6 Opcodes
*/
enum class Opcodes(val value: Int) {
nop(0x00),
aconst_null(0x01),
iconst_m1(0x02),
iconst_0(0x03),
iconst_1(0x04),
iconst_2(0x05),
iconst_3(0x06),
iconst_4(0x07),
iconst_5(0x08),
lconst_0(0x09),
lconst_1(0x0a),
fconst_0(0x0b),
fconst_1(0x0c),
fconst_2(0x0d),
dconst_0(0x0e),
dconst_1(0x0f),
bipush(0x10),
sipush(0x11),
ldc(0x12),
ldc_w(0x13),
ldc2_w(0x14),
iload(0x15),
lload(0x16),
fload(0x17),
dload(0x18),
aload(0x19),
iload_0(0x1a),
iload_1(0x1b),
iload_2(0x1c),
iload_3(0x1d),
lload_0(0x1e),
lload_1(0x1f),
lload_2(0x20),
lload_3(0x21),
fload_0(0x22),
fload_1(0x23),
fload_2(0x24),
fload_3(0x25),
dload_0(0x26),
dload_1(0x27),
dload_2(0x28),
dload_3(0x29),
aload_0(0x2a),
aload_1(0x2b),
aload_2(0x2c),
aload_3(0x2d),
iaload(0x2e),
laload(0x2f),
faload(0x30),
daload(0x31),
aaload(0x32),
baload(0x33),
caload(0x34),
saload(0x35),
istore(0x36),
lstore(0x37),
fstore(0x38),
dstore(0x39),
astore(0x3a),
istore_0(0x3b),
istore_1(0x3c),
istore_2(0x3d),
istore_3(0x3e),
lstore_0(0x3f),
lstore_1(0x40),
lstore_2(0x41),
lstore_3(0x42),
fstore_0(0x43),
fstore_1(0x44),
fstore_2(0x45),
fstore_3(0x46),
dstore_0(0x47),
dstore_1(0x48),
dstore_2(0x49),
dstore_3(0x4a),
astore_0(0x4b),
astore_1(0x4c),
astore_2(0x4d),
astore_3(0x4e),
iastore(0x4f),
lastore(0x50),
fastore(0x51),
dastore(0x52),
aastore(0x53),
bastore(0x54),
castore(0x55),
sastore(0x56),
pop(0x57),
pop2(0x58),
dup(0x59),
dup_x1(0x5a),
dup_x2(0x5b),
dup2(0x5c),
dup2_x1(0x5d),
dup2_x2(0x5e),
swap(0x5f),
iadd(0x60),
ladd(0x61),
fadd(0x62),
dadd(0x63),
isub(0x64),
lsub(0x65),
fsub(0x66),
dsub(0x67),
imul(0x68),
lmul(0x69),
fmul(0x6a),
dmul(0x6b),
idiv(0x6c),
ldiv(0x6d),
fdiv(0x6e),
ddiv(0x6f),
irem(0x70),
lrem(0x71),
frem(0x72),
drem(0x73),
ineg(0x74),
lneg(0x75),
fneg(0x76),
dneg(0x77),
ishl(0x78),
lshl(0x79),
ishr(0x7a),
lshr(0x7b),
iushr(0x7c),
lushr(0x7d),
iand(0x7e),
land(0x7f),
ior(0x80),
lor(0x81),
ixor(0x82),
lxor(0x83),
iinc(0x84),
i2l(0x85),
i2f(0x86),
i2d(0x87),
l2i(0x88),
l2f(0x89),
l2d(0x8a),
f2i(0x8b),
f2l(0x8c),
f2d(0x8d),
d2i(0x8e),
d2l(0x8f),
d2f(0x90),
i2b(0x91),
i2c(0x92),
i2s(0x93),
lcmp(0x94),
fcmpl(0x95),
fcmpg(0x96),
dcmpl(0x97),
dcmpg(0x98),
ifeq(0x99),
ifne(0x9a),
iflt(0x9b),
ifge(0x9c),
ifgt(0x9d),
ifle(0x9e),
if_icmpeq(0x9f),
if_icmpne(0xa0),
if_icmplt(0xa1),
if_icmpge(0xa2),
if_icmpgt(0xa3),
if_icmple(0xa4),
if_acmpeq(0xa5),
if_acmpne(0xa6),
goto(0xa7),
jsr(0xa8),
ret(0xa9),
tableswitch(0xaa),
lookupswitch(0xab),
ireturn(0xac),
lreturn(0xad),
freturn(0xae),
dreturn(0xaf),
areturn(0xb0),
i_return(0xb1),
getstatic(0xb2),
putstatic(0xb3),
getfield(0xb4),
putfield(0xb5),
invokevirtual(0xb6),
invokespecial(0xb7),
invokestatic(0xb8),
invokeinterface(0xb9),
xxxunusedxxx1(0xba),
new(0xbb),
newarray(0xbc),
anewarray(0xbd),
arraylength(0xbe),
athrow(0xbf),
checkcast(0xc0),
instanceof(0xc1),
monitorenter(0xc2),
monitorexit(0xc3),
wide(0xc4),
multianewarray(0xc5),
ifnull(0xc6),
ifnonnull(0xc7),
goto_w(0xc8),
jsr_w(0xc9),
breakpoint(0xca),
impdep1(0xfe),
impdep2(0xff)
}
} | src/main/kotlin/com/thomas/needham/ftl/backend/EnumOpcodes.kt | 2049857209 |
package com.macoscope.ketchuplunch.di
import android.content.Context
import com.macoscope.ketchuplunch.LogOutUseCase
import com.macoscope.ketchuplunch.model.ScriptClient
import com.macoscope.ketchuplunch.model.lunch.WeeksService
import com.macoscope.ketchuplunch.presenter.WeeksPresenter
import com.macoscope.ketchuplunch.view.lunch.WeeksView
class WeekModule(context: Context, val scriptModule: ScriptModule, val weeksView: WeeksView) :
AccountModule(context) {
companion object {
var scriptClient: ScriptClient? = null
}
private fun provideWeeksService(): WeeksService = WeeksService(provideScriptClient())
private fun provideScriptClient(): ScriptClient {
return scriptClient ?: ScriptClient(provideGoogleCredentialWrapper().userCredential,
scriptModule.provideRootUrl())
}
private fun provideLogOutUseCase(): LogOutUseCase = LogOutUseCase(provideGoogleCredentialWrapper(), provideAccountRepository())
fun provideWeeksPresenter(): WeeksPresenter {
return WeeksPresenter(provideWeeksService(), weeksView, provideLogOutUseCase())
}
} | app/src/main/java/com/macoscope/ketchuplunch/di/WeekModule.kt | 3602138936 |
package com.habitrpg.android.habitica.ui.activities
import android.os.Bundle
import android.view.MenuItem
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.ui.helpers.setMarkdown
import kotlinx.android.synthetic.main.activity_prefs.*
import okhttp3.*
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
class GuidelinesActivity: BaseActivity() {
override fun getLayoutResId(): Int = R.layout.activity_guidelines
override fun injectActivity(component: UserComponent?) { /* no-on */ }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar(toolbar)
val client = OkHttpClient()
val request = Request.Builder().url("https://s3.amazonaws.com/habitica-assets/mobileApp/endpoint/community-guidelines.md").build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val `in` = response.body()?.byteStream()
val reader = BufferedReader(InputStreamReader(`in`))
val text = reader.readText()
response.body()?.close()
findViewById<TextView>(R.id.text_view).post {
findViewById<TextView>(R.id.text_view).setMarkdown(text)
}
}
})
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
} | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/GuidelinesActivity.kt | 2783240942 |
package v_builders
import org.junit.Assert.assertTrue
import org.junit.Test
class _39_Html_Builders {
@Test fun productTableIsFilled() {
val result = renderProductTable()
print(result)
assertTrue("Product table should contain corresponding data", result.contains("cactus"))
}
@Test fun productTableIsColored() {
val result = renderProductTable()
print(result)
assertTrue("Product table should be colored", result.contains("bgcolor"))
}
}
| test/v_builders/_39_Html_Builders.kt | 538270824 |
package cucumber.cukeulator.test
import androidx.test.espresso.Espresso
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.withId
import cucumber.cukeulator.R
import io.cucumber.java.en.Then
class KotlinSteps {
@Then("I should see {string} on the display")
fun I_should_see_s_on_the_display(s: String?) {
Espresso.onView(withId(R.id.txt_calc_display)).check(ViewAssertions.matches(ViewMatchers.withText(s)))
}
}
| test_projects/android/cucumber_sample_app/cukeulator/src/androidTest/java/cucumber/cukeulator/test/KotlinSteps.kt | 2134798258 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.observable.properties
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class PropertyView<R, S, T>(
private val instance: ReadWriteProperty<R, S>,
private val map: (S) -> T,
private val comap: (T) -> S
) : ReadWriteProperty<R, T> {
override fun getValue(thisRef: R, property: KProperty<*>): T {
return map(instance.getValue(thisRef, property))
}
override fun setValue(thisRef: R, property: KProperty<*>, value: T) {
instance.setValue(thisRef, property, comap(value))
}
companion object {
fun <R, T> ReadWriteProperty<R, T>.map(transform: (T) -> T) = PropertyView(this, transform, { it })
fun <R, T> ReadWriteProperty<R, T>.comap(transform: (T) -> T) = PropertyView(this, { it }, transform)
}
} | platform/platform-impl/src/com/intellij/openapi/observable/properties/PropertyView.kt | 3062040020 |
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.intellij.openapi.util.NlsSafe
import com.jetbrains.packagesearch.intellij.plugin.api.model.V2Repository
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
internal data class PackageSearchRepository(
@NlsSafe val id: String?,
@NlsSafe val name: String?,
@NlsSafe val url: String?,
val projectModule: ProjectModule?,
val remoteInfo: V2Repository?
)
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/PackageSearchRepository.kt | 4272216915 |
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.resolve
import org.jetbrains.kotlin.idea.completion.test.configureWithExtraFile
import org.jetbrains.kotlin.idea.invalidateCaches
import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.util.IgnoreTests
abstract class AbstractFirReferenceResolveTest : AbstractReferenceResolveTest() {
override fun isFirPlugin(): Boolean = true
override fun getProjectDescriptor(): KotlinLightProjectDescriptor =
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK
override fun tearDown() {
project.invalidateCaches(myFixture.file as? KtFile)
super.tearDown()
}
override fun doTest(path: String) {
assert(path.endsWith(".kt")) { path }
myFixture.configureWithExtraFile(path, ".Data")
IgnoreTests.runTestIfNotDisabledByFileDirective(testDataFile().toPath(), IgnoreTests.DIRECTIVES.IGNORE_FIR) {
performChecks()
}
}
} | plugins/kotlin/fir/test/org/jetbrains/kotlin/idea/resolve/AbstractFirReferenceResolveTest.kt | 4155681017 |
package module1
fun foo(): Int = 0 | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/multiModule/common/functionFromDifferentPackageChanged/module1_foo.kt | 2489408253 |
// WITH_RUNTIME
// SIBLING:
fun foo() {
val (a, b) = <selection>1 to 2</selection>
} | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/initializers/properties/multiDeclaration.kt | 657457701 |
/*
* Copyright (c) 2018 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.android.vmb.font
import android.graphics.Typeface
import android.widget.TextView
import net.mm2d.android.vmb.R
import net.mm2d.android.vmb.settings.Settings
import net.mm2d.android.vmb.util.Toaster
import net.mm2d.log.Logger
import java.io.File
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
object FontUtils {
fun isValidFontFile(file: File): Boolean =
try {
Typeface.createFromFile(file)
true
} catch (e: Exception) {
Logger.w(e)
false
}
fun setFont(textView: TextView, settings: Settings) {
if (settings.fontPathToUse.isEmpty()) {
textView.typeface = Typeface.DEFAULT
return
}
try {
val typeFace = Typeface.createFromFile(settings.fontPath)
if (typeFace != null) {
textView.setTypeface(typeFace, Typeface.NORMAL)
return
}
} catch (e: Exception) {
}
settings.useFont = false
settings.fontPath = ""
textView.typeface = Typeface.DEFAULT
Toaster.show(textView.context, R.string.toast_failed_to_load_font)
}
}
| app/src/main/java/net/mm2d/android/vmb/font/FontUtils.kt | 618935019 |
fun foo(f: (Int, <caret>Boolean) -> String) {
f(1, false)
bar(f)
}
fun bar(f: (Int, Boolean) -> String) {
}
fun lambda(): (Int, Boolean) -> String = { i, b -> "$i $b"}
fun baz(f: (Int, Boolean) -> String) {
fun g(i: Int, b: Boolean) = ""
foo(f)
foo(::g)
foo(lambda())
foo { i, b -> "${i + 1} $b" }
} | plugins/kotlin/idea/tests/testData/intentions/convertFunctionTypeParameterToReceiver/nonFirstParameter.kt | 3398720548 |
/*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* econsim-tr01 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01
/**
* @author Dmitri Pisarenko ([email protected])
* @version $Id$
* @since 1.0
*/
object Random : IRandom {
val random = createRandom()
override fun nextInt(bound: Int): Int = random.nextInt(bound)
override fun nextDouble(): Double = random.nextDouble()
}
| src/main/java/cc/altruix/econsimtr01/Random.kt | 748015604 |
// "Import" "false"
// WITH_RUNTIME
// LANGUAGE_VERSION: 1.2
// ACTION: Create local variable 'CoroutineImpl'
// ACTION: Create object 'CoroutineImpl'
// ACTION: Create parameter 'CoroutineImpl'
// ACTION: Create property 'CoroutineImpl'
// ACTION: Introduce local variable
// ACTION: Create annotation 'CoroutineImpl'
// ACTION: Create class 'CoroutineImpl'
// ACTION: Create enum 'CoroutineImpl'
// ACTION: Create interface 'CoroutineImpl'
// ACTION: Rename reference
// ERROR: Unresolved reference: CoroutineImpl
fun some() {
CoroutineImpl<caret>::class
}
| plugins/kotlin/idea/tests/testData/quickfix/autoImports/excludedCoroutineImpl.kt | 2718963896 |
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin
import org.jetbrains.kotlin.TestModule.Companion.default
import org.jetbrains.kotlin.TestModule.Companion.support
import java.nio.file.Path
import java.nio.file.Paths
import java.util.regex.Matcher
import java.util.regex.Pattern
private const val MODULE_DELIMITER = ",\\s*"
// These patterns are copies from
// kotlin/compiler/tests-common/tests/org/jetbrains/kotlin/test/TestFiles.java
// kotlin/compiler/tests-common/tests/org/jetbrains/kotlin/test/KotlinTestUtils.java
private val FILE_OR_MODULE_PATTERN: Pattern = Pattern.compile("(?://\\s*MODULE:\\s*([^()\\n]+)(?:\\(([^()]+(?:" +
"$MODULE_DELIMITER[^()]+)*)\\))?\\s*(?:\\(([^()]+(?:$MODULE_DELIMITER[^()]+)*)\\))?\\s*)?//\\s*FILE:\\s*(.*)$",
Pattern.MULTILINE)
private val DIRECTIVE_PATTERN = Pattern.compile("^//\\s*[!]?([A-Z_]+)(:[ \\t]*(.*))?$", Pattern.MULTILINE)
/**
* Creates test files from the given source file that may contain different test directives.
*
* @return list of test files [TestFile] to be compiled
*/
fun buildCompileList(source: Path, outputDirectory: String): List<TestFile> {
val result = mutableListOf<TestFile>()
val srcFile = source.toFile()
// Remove diagnostic parameters in external tests.
val srcText = srcFile.readText().replace(Regex("<!.*?!>(.*?)<!>")) { match -> match.groupValues[1] }
if (srcText.contains("// WITH_COROUTINES")) {
result.add(TestFile("helpers.kt", "$outputDirectory/helpers.kt",
createTextForHelpers(true), TestModule.support))
}
val matcher = FILE_OR_MODULE_PATTERN.matcher(srcText)
if (!matcher.find()) {
// There is only one file in the input
result.add(TestFile(srcFile.name, "$outputDirectory/${srcFile.name}", srcText))
} else {
// There are several files
var processedChars = 0
var module: TestModule = TestModule.default
var nextFileExists = true
while (nextFileExists) {
var moduleName = matcher.group(1)
val moduleDependencies = matcher.group(2)
val moduleFriends = matcher.group(3)
if (moduleName != null) {
moduleName = moduleName.trim { it <= ' ' }
module = TestModule("${srcFile.name}.$moduleName",
moduleDependencies.parseModuleList().map {
if (it != "support") "${srcFile.name}.$it" else it
},
moduleFriends.parseModuleList().map { "${srcFile.name}.$it" })
}
val fileName = matcher.group(4)
val filePath = "$outputDirectory/$fileName"
val start = processedChars
nextFileExists = matcher.find()
val end = if (nextFileExists) matcher.start() else srcText.length
val fileText = srcText.substring(start, end)
processedChars = end
if (fileName.endsWith(".kt")) {
result.add(TestFile(fileName, filePath, fileText, module))
}
}
}
return result
}
private fun String?.parseModuleList() = this
?.split(Pattern.compile(MODULE_DELIMITER), 0)
?: emptyList()
/**
* Test module from the test source declared by the [FILE_OR_MODULE_PATTERN].
* Module should have a [name] and could have [dependencies] on other modules and [friends].
*
* There are 2 predefined modules:
* - [default] that contains all sources that don't declare a module,
* - [support] for a helper sources like Coroutines support.
*/
data class TestModule(
val name: String,
val dependencies: List<String>,
val friends: List<String>
) {
val files = mutableListOf<TestFile>()
fun isDefaultModule() = this == default || name.endsWith(".main")
val hasVersions get() = this.files.any { it.version != null }
fun versionFiles(version: Int) = this.files.filter { it.version == null || it.version == version }
companion object {
val default = TestModule("default", emptyList(), emptyList())
val support = TestModule("support", emptyList(), emptyList())
}
}
/**
* Represent a single test file that belongs to the [module].
*/
data class TestFile(
val name: String,
val path: String,
var text: String = "",
val module: TestModule = TestModule.default
) {
init {
this.module.files.add(this)
}
val directives: Map<String, String> by lazy {
parseDirectives()
}
val version: Int? get() = this.directives["VERSION"]?.toInt()
fun parseDirectives(): Map<String, String> {
val newDirectives = mutableMapOf<String, String>()
val directiveMatcher: Matcher = DIRECTIVE_PATTERN.matcher(text)
while (directiveMatcher.find()) {
val name = directiveMatcher.group(1)
val value = directiveMatcher.group(3)
newDirectives.put(name, value)
}
return newDirectives
}
/**
* Writes [text] to the file created from the [path].
*/
fun writeTextToFile() {
Paths.get(path).takeUnless { text.isEmpty() }?.run {
parent.toFile()
.takeUnless { it.exists() }
?.mkdirs()
toFile().writeText(text)
}
}
}
| build-tools/src/main/kotlin/org/jetbrains/kotlin/TestDirectives.kt | 3684474668 |
package com.github.kerubistan.kerub.utils
import org.apache.shiro.SecurityUtils
/**
* Get current shiro user - throws exception if no user
*/
fun currentUser() = SecurityUtils.getSubject()?.principal?.toString()
| src/main/kotlin/com/github/kerubistan/kerub/utils/ShiroUtils.kt | 1862206552 |
package org.odfi.ooxoo.gradle.plugin
import com.idyria.osi.ooxoo.model.ModelProducer
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.workers.WorkParameters
interface XModelProducerParameters : WorkParameters {
fun getModelFile(): RegularFileProperty?
fun getBuildOutput(): RegularFileProperty?
} | gradle-ooxoo-plugin/src/main/kotlin/org/odfi/ooxoo/gradle/plugin/XModelProducerParameters.kt | 1508427343 |
/*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.data.model
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = false)
enum class TarotOudlerValue {
PETIT,
EXCUSE,
TWENTY_ONE
}
| data/src/main/kotlin/com/sbgapps/scoreit/data/model/TarotOudlerValue.kt | 2253727826 |
/*
* 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.ui.platform
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.test.InternalTestApi
import androidx.compose.ui.test.junit4.DesktopScreenshotTestRule
import androidx.compose.ui.unit.dp
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
@OptIn(InternalTestApi::class)
class GraphicsLayerTest {
@get:Rule
val screenshotRule = DesktopScreenshotTestRule("compose/ui/ui-desktop/platform")
@Test
fun scale() {
val window = TestComposeWindow(width = 40, height = 40)
window.setContent {
Box(
Modifier
.graphicsLayer(
scaleX = 2f,
scaleY = 0.5f,
transformOrigin = TransformOrigin(0f, 0f)
)
.requiredSize(10f.dp, 10f.dp).background(Color.Red)
)
Box(
Modifier
.graphicsLayer(
translationX = 10f,
translationY = 20f,
scaleX = 2f,
scaleY = 0.5f
)
.requiredSize(10f.dp, 10f.dp).background(Color.Blue)
)
}
screenshotRule.snap(window.surface)
}
@Test
fun rotationZ() {
val window = TestComposeWindow(width = 40, height = 40)
window.setContent {
Box(
Modifier
.graphicsLayer(
translationX = 10f,
rotationZ = 90f,
scaleX = 2f,
scaleY = 0.5f,
transformOrigin = TransformOrigin(0f, 0f)
)
.requiredSize(10f.dp, 10f.dp).background(Color.Red)
)
Box(
Modifier
.graphicsLayer(
translationX = 10f,
translationY = 20f,
rotationZ = 45f
)
.requiredSize(10f.dp, 10f.dp).background(Color.Blue)
)
}
screenshotRule.snap(window.surface)
}
@Test
fun rotationX() {
val window = TestComposeWindow(width = 40, height = 40)
window.setContent {
Box(
Modifier
.graphicsLayer(rotationX = 45f)
.requiredSize(10f.dp, 10f.dp).background(Color.Blue)
)
Box(
Modifier
.graphicsLayer(
translationX = 20f,
transformOrigin = TransformOrigin(0f, 0f),
rotationX = 45f
)
.requiredSize(10f.dp, 10f.dp).background(Color.Blue)
)
}
screenshotRule.snap(window.surface)
}
@Test
fun rotationY() {
val window = TestComposeWindow(width = 40, height = 40)
window.setContent {
Box(
Modifier
.graphicsLayer(rotationY = 45f)
.requiredSize(10f.dp, 10f.dp).background(Color.Blue)
)
Box(
Modifier
.graphicsLayer(
translationX = 20f,
transformOrigin = TransformOrigin(0f, 0f),
rotationY = 45f
)
.requiredSize(10f.dp, 10f.dp).background(Color.Blue)
)
}
screenshotRule.snap(window.surface)
}
@Test
fun `nested layer transformations`() {
val window = TestComposeWindow(width = 40, height = 40)
window.setContent {
Box(
Modifier
.graphicsLayer(rotationZ = 45f, translationX = 10f)
.requiredSize(20f.dp, 20f.dp).background(Color.Green)
) {
Box(
Modifier
.graphicsLayer(rotationZ = 45f)
.requiredSize(20f.dp, 20f.dp).background(Color.Blue)
)
}
}
screenshotRule.snap(window.surface)
}
@Test
fun clip() {
val window = TestComposeWindow(width = 40, height = 40)
window.setContent {
Box(
Modifier
.graphicsLayer(
translationX = 10f,
translationY = 10f,
transformOrigin = TransformOrigin(0f, 0f),
clip = false
)
.requiredSize(10f.dp, 10f.dp).background(Color.Red)
) {
Box(
Modifier
.graphicsLayer(
transformOrigin = TransformOrigin(0f, 0f),
clip = false
)
.requiredSize(20f.dp, 2f.dp)
.background(Color.Blue)
)
}
Box(
Modifier
.graphicsLayer(
translationX = 10f,
translationY = 30f,
transformOrigin = TransformOrigin(0f, 0f),
clip = true
)
.requiredSize(10f.dp, 10f.dp).background(Color.Red)
) {
Box(
Modifier
.graphicsLayer(
transformOrigin = TransformOrigin(0f, 0f),
clip = false
)
.requiredSize(20f.dp, 2f.dp)
.background(Color.Blue)
)
}
Box(
Modifier
.graphicsLayer(
translationX = 30f,
translationY = 10f,
transformOrigin = TransformOrigin(0f, 0f),
clip = true,
shape = RoundedCornerShape(5.dp)
)
.requiredSize(10f.dp, 10f.dp).background(Color.Red)
) {
Box(
Modifier
.graphicsLayer(
transformOrigin = TransformOrigin(0f, 0f),
clip = false
)
.requiredSize(20f.dp, 2f.dp)
.background(Color.Blue)
)
}
}
screenshotRule.snap(window.surface)
}
@Test
fun alpha() {
val window = TestComposeWindow(width = 40, height = 40)
window.setContent {
Box(
Modifier
.padding(start = 5.dp)
.graphicsLayer(
translationX = -5f,
translationY = 5f,
transformOrigin = TransformOrigin(0f, 0f),
alpha = 0.5f
)
.requiredSize(10f.dp, 10f.dp)
.background(Color.Green)
) {
// This box will be clipped (because if we use alpha, we draw into
// intermediate buffer)
Box(
Modifier
.requiredSize(30f.dp, 30f.dp)
.background(Color.Blue)
)
}
Box(
Modifier
.padding(start = 15.dp)
.graphicsLayer(alpha = 0.5f)
.requiredSize(15f.dp, 15f.dp)
.background(Color.Red)
) {
Box(
Modifier
.graphicsLayer(alpha = 0.5f)
.requiredSize(10f.dp, 10f.dp)
.background(Color.Blue)
)
}
Box(
Modifier
.graphicsLayer(
alpha = 0f
)
.requiredSize(10f.dp, 10f.dp)
.background(Color.Blue)
)
}
screenshotRule.snap(window.surface)
}
@Test
fun elevation() {
val window = TestComposeWindow(width = 40, height = 40)
window.setContent {
Box(
Modifier
.graphicsLayer(shadowElevation = 5f)
.requiredSize(20f.dp, 20f.dp)
)
Box(
Modifier
.graphicsLayer(translationX = 20f, shadowElevation = 5f)
.requiredSize(20f.dp, 20f.dp)
) {
Box(
Modifier
.requiredSize(20f.dp, 20f.dp)
.background(Color.Blue)
)
}
Box(
Modifier
.graphicsLayer(translationY = 20f, alpha = 0.8f, shadowElevation = 5f)
.requiredSize(20f.dp, 20f.dp)
) {
Box(
Modifier
.requiredSize(20f.dp, 20f.dp)
.background(Color.Red)
)
}
Box(
Modifier
.graphicsLayer(
translationX = 20f,
translationY = 20f,
shadowElevation = 5f,
alpha = 0.8f
)
.requiredSize(20f.dp, 20f.dp)
)
}
screenshotRule.snap(window.surface)
}
} | compose/ui/ui/src/desktopTest/kotlin/androidx/compose/ui/platform/GraphicsLayerTest.kt | 1002397669 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.graphics.vector
import androidx.compose.animation.core.AnimationVector
import androidx.compose.animation.core.AnimationVector1D
import androidx.compose.animation.core.AnimationVector2D
import androidx.compose.animation.core.AnimationVector3D
import androidx.compose.animation.core.AnimationVector4D
import androidx.compose.animation.core.FiniteAnimationSpec
import androidx.compose.animation.core.TwoWayConverter
import androidx.compose.animation.core.VectorizedFiniteAnimationSpec
private const val MillisToNanos = 1_000_000L
/**
* Returns this [FiniteAnimationSpec] reversed.
*/
internal fun <T> FiniteAnimationSpec<T>.reversed(durationMillis: Int): FiniteAnimationSpec<T> {
return ReversedSpec(this, durationMillis)
}
private class ReversedSpec<T>(
private val spec: FiniteAnimationSpec<T>,
private val durationMillis: Int
) : FiniteAnimationSpec<T> {
override fun <V : AnimationVector> vectorize(
converter: TwoWayConverter<T, V>
): VectorizedFiniteAnimationSpec<V> {
return VectorizedReversedSpec(spec.vectorize(converter), durationMillis * MillisToNanos)
}
}
private class VectorizedReversedSpec<V : AnimationVector>(
private val animation: VectorizedFiniteAnimationSpec<V>,
private val durationNanos: Long
) : VectorizedFiniteAnimationSpec<V> {
override fun getValueFromNanos(
playTimeNanos: Long,
initialValue: V,
targetValue: V,
initialVelocity: V
): V {
return animation.getValueFromNanos(
durationNanos - playTimeNanos,
targetValue,
initialValue,
initialVelocity
)
}
override fun getVelocityFromNanos(
playTimeNanos: Long,
initialValue: V,
targetValue: V,
initialVelocity: V
): V {
return animation.getVelocityFromNanos(
durationNanos - playTimeNanos,
targetValue,
initialValue,
initialVelocity
).reversed()
}
override fun getDurationNanos(initialValue: V, targetValue: V, initialVelocity: V): Long {
return durationNanos
}
}
/**
* Creates a [FiniteAnimationSpec] that combine and run multiple [specs] based on the start time
* (in milliseconds) specified as the first half of the pairs.
*/
internal fun <T> combined(
specs: List<Pair<Int, FiniteAnimationSpec<T>>>
): FiniteAnimationSpec<T> {
return CombinedSpec(specs)
}
private class CombinedSpec<T>(
private val specs: List<Pair<Int, FiniteAnimationSpec<T>>>
) : FiniteAnimationSpec<T> {
override fun <V : AnimationVector> vectorize(
converter: TwoWayConverter<T, V>
): VectorizedFiniteAnimationSpec<V> {
return VectorizedCombinedSpec(
specs.map { (timeMillis, spec) ->
timeMillis * MillisToNanos to spec.vectorize(converter)
}
)
}
}
private class VectorizedCombinedSpec<V : AnimationVector>(
private val animations: List<Pair<Long, VectorizedFiniteAnimationSpec<V>>>
) : VectorizedFiniteAnimationSpec<V> {
private fun chooseAnimation(playTimeNanos: Long): Pair<Long, VectorizedFiniteAnimationSpec<V>> {
return animations.lastOrNull { (timeNanos, _) ->
timeNanos <= playTimeNanos
} ?: animations.first()
}
override fun getValueFromNanos(
playTimeNanos: Long,
initialValue: V,
targetValue: V,
initialVelocity: V
): V {
val (timeNanos, animation) = chooseAnimation(playTimeNanos)
val internalPlayTimeNanos = playTimeNanos - timeNanos
return animation.getValueFromNanos(
internalPlayTimeNanos,
initialValue,
targetValue,
initialVelocity
)
}
override fun getVelocityFromNanos(
playTimeNanos: Long,
initialValue: V,
targetValue: V,
initialVelocity: V
): V {
val (timeNanos, animation) = chooseAnimation(playTimeNanos)
return animation.getVelocityFromNanos(
playTimeNanos - timeNanos,
initialValue,
targetValue,
initialVelocity
)
}
override fun getDurationNanos(initialValue: V, targetValue: V, initialVelocity: V): Long {
val (timeNanos, animation) = animations.last()
return timeNanos + animation.getDurationNanos(initialValue, targetValue, initialVelocity)
}
}
private fun <V : AnimationVector> V.reversed(): V {
@Suppress("UNCHECKED_CAST")
return when (this) {
is AnimationVector1D -> AnimationVector1D(value * -1) as V
is AnimationVector2D -> AnimationVector2D(v1 * -1, v2 * -1) as V
is AnimationVector3D -> AnimationVector3D(v1 * -1, v2 * -1, v3 * -1) as V
is AnimationVector4D -> AnimationVector4D(v1 * -1, v2 * -1, v3 * -1, v4 * -1) as V
else -> throw RuntimeException("Unknown AnimationVector: $this")
}
}
| compose/animation/animation-graphics/src/commonMain/kotlin/androidx/compose/animation/graphics/vector/AnimatorAnimationSpecs.kt | 3439642158 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.integration.demos.settings
import android.content.Context
import android.view.View
import android.view.Window
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat.setDecorFitsSystemWindows
import androidx.core.view.WindowInsetsCompat
import androidx.preference.CheckBoxPreference
/**
* Setting that determines whether [setDecorFitsSystemWindows] is called with true or false for the
* demo activity's window.
*/
internal object DecorFitsSystemWindowsSetting : DemoSetting<Boolean> {
private const val Key = "decorFitsSystemWindows"
private const val DefaultValue = true
override fun createPreference(context: Context) = CheckBoxPreference(context).apply {
title = "Decor fits system windows"
key = Key
summaryOff =
"The framework will not fit the content view to the insets and will just pass through" +
" the WindowInsetsCompat to the content view."
summaryOn = "The framework will fit the content view to the insets. WindowInsets APIs " +
"must be used to add necessary padding. Insets will be animated."
setDefaultValue(DefaultValue)
}
@Composable
fun asState() = preferenceAsState(Key) {
getBoolean(Key, DefaultValue)
}
}
/**
* Sets the window's [decorFitsSystemWindow][setDecorFitsSystemWindows] property to
* [decorFitsSystemWindows] as long as this function is composed.
*/
@Composable
internal fun DecorFitsSystemWindowsEffect(
decorFitsSystemWindows: Boolean,
view: View,
window: Window
) {
DisposableEffect(decorFitsSystemWindows, window) {
setDecorFitsSystemWindows(window, decorFitsSystemWindows)
ViewCompat.setOnApplyWindowInsetsListener(view) { _, insets ->
if (!decorFitsSystemWindows) WindowInsetsCompat.CONSUMED
else insets
}
onDispose {
setDecorFitsSystemWindows(window, true)
}
}
} | compose/integration-tests/demos/src/main/java/androidx/compose/integration/demos/settings/DecorFitsSystemWindowsSetting.kt | 2639891766 |
object J {
@JvmStatic
fun main(args: Array<String>) {
val code = """
String source = ${'"'}""
String message = "Hello, World!";
System.out.println(message);
""${'"'};
""".trimIndent()
}
}
| plugins/kotlin/j2k/new/tests/testData/newJ2k/newJavaFeatures/textBlocks/tripleQuote.kt | 2615933896 |
// FIR_COMPARISON
// WITH_MESSAGE: "Removed 1 import"
package ppp
import ppp.*
open class C
class D : C()
class E : ppp.ppp1.C1() | plugins/kotlin/idea/tests/testData/editor/optimizeImports/common/CurrentPackage.kt | 578383887 |
// "Import extension function 'ext'" "true"
package p
open class A {
fun <T> T.ext() {}
}
object AObject : A()
fun usage() {
val ten = 10
ten.<caret>ext()
}
| plugins/kotlin/idea/tests/testData/quickfix/autoImports/callablesDeclaredInClasses/genericExtensionFunctionVariable.kt | 1102968190 |
package entities.exception
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.ManagedEntity
import com.onyx.persistence.annotations.*
import com.onyx.persistence.annotations.values.RelationshipType
import entities.AllAttributeEntity
import entities.InheritedAttributeEntity
/**
* Created by timothy.osborn on 12/14/14.
*/
@Entity
class EntityToOneDoesNotMatch : ManagedEntity(), IManagedEntity {
@Identifier
@Attribute
var id = "234"
@Relationship(type = RelationshipType.ONE_TO_ONE, inverseClass = AllAttributeEntity::class)
var relationship: InheritedAttributeEntity? = null
}
| onyx-database-tests/src/main/kotlin/entities/exception/EntityToOneDoesNotMatch.kt | 489170254 |
// 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.liveTemplates.k1.macro
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.template.Expression
import com.intellij.codeInsight.template.ExpressionContext
import com.intellij.codeInsight.template.Result
import com.intellij.codeInsight.template.TextResult
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.codeInsight.ReferenceVariantsHelper
import org.jetbrains.kotlin.idea.completion.BasicLookupElementFactory
import org.jetbrains.kotlin.idea.completion.InsertHandlerProvider
import org.jetbrains.kotlin.idea.core.NotPropertiesService
import org.jetbrains.kotlin.idea.core.isVisible
import org.jetbrains.kotlin.idea.liveTemplates.macro.KotlinMacro
import org.jetbrains.kotlin.idea.util.CallType
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
abstract class Fe10AbstractKotlinVariableMacro<State> : KotlinMacro() {
private fun getVariables(params: Array<Expression>, context: ExpressionContext): Collection<VariableDescriptor> {
if (params.isNotEmpty()) {
return emptyList()
}
val project = context.project
val psiDocumentManager = PsiDocumentManager.getInstance(project)
psiDocumentManager.commitAllDocuments()
val document = context.editor?.document ?: return emptyList()
val psiFile = psiDocumentManager.getPsiFile(document) as? KtFile ?: return emptyList()
val contextElement = psiFile.findElementAt(context.startOffset)?.getNonStrictParentOfType<KtElement>() ?: return emptyList()
val resolutionFacade = psiFile.getResolutionFacade()
val bindingContext = resolutionFacade.analyze(contextElement, BodyResolveMode.PARTIAL_FOR_COMPLETION)
fun isVisible(descriptor: DeclarationDescriptor): Boolean {
return descriptor !is DeclarationDescriptorWithVisibility || descriptor.isVisible(
contextElement,
null,
bindingContext,
resolutionFacade
)
}
val state = initState(contextElement, bindingContext)
val helper = ReferenceVariantsHelper(
bindingContext,
resolutionFacade,
resolutionFacade.moduleDescriptor,
::isVisible,
NotPropertiesService.getNotProperties(contextElement)
)
return helper
.getReferenceVariants(contextElement, CallTypeAndReceiver.DEFAULT, DescriptorKindFilter.VARIABLES, { true })
.map { it as VariableDescriptor }
.filter { isSuitable(it, project, state) }
}
protected abstract fun initState(contextElement: KtElement, bindingContext: BindingContext): State
protected abstract fun isSuitable(
variableDescriptor: VariableDescriptor,
project: Project,
state: State
): Boolean
override fun calculateResult(params: Array<Expression>, context: ExpressionContext): Result? {
val vars = getVariables(params, context)
if (vars.isEmpty()) return null
return vars.firstOrNull()?.let { TextResult(it.name.render()) }
}
override fun calculateLookupItems(params: Array<Expression>, context: ExpressionContext): Array<LookupElement>? {
val vars = getVariables(params, context)
if (vars.size < 2) return null
val lookupElementFactory = BasicLookupElementFactory(context.project, InsertHandlerProvider(CallType.DEFAULT, editor = context.editor!!) { emptyList() })
return vars.map { lookupElementFactory.createLookupElement(it) }.toTypedArray()
}
}
| plugins/kotlin/code-insight/live-templates-k1/src/org/jetbrains/kotlin/idea/liveTemplates/k1/macro/Fe10AbstractKotlinVariableMacro.kt | 2130608407 |
package io.quartz.gen.jvm.asm
import io.quartz.gen.jvm.tree.JvmAnnotation
fun JvmAnnotation.generate(cg: ClassGenerator) = run {
val av = cg.cw.visitAnnotation("L${qualifiedName.locatableString};", true)!!
args.forEach {
av.visit(it.name.string, it.arg)
}
av.visitEnd()
av
}
| compiler/src/main/kotlin/io/quartz/gen/jvm/asm/JvmAnnotationGenerator.kt | 1229343103 |
// WITH_STDLIB
fun foo() {
Integer.<caret>toString(42 + 24, 16)
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/toString/toExtension.kt | 1032273869 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.target
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.NamedConfigurable
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.util.function.Supplier
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JPanel
internal class TargetEnvironmentDetailsConfigurable(
private val project: Project,
private val config: TargetEnvironmentConfiguration,
defaultLanguage: LanguageRuntimeType<*>?,
treeUpdate: Runnable
) : NamedConfigurable<TargetEnvironmentConfiguration>(true, treeUpdate) {
private val targetConfigurable: Configurable = config.getTargetType()
.createConfigurable(project, config, defaultLanguage, this)
private var languagesPanel: TargetEnvironmentLanguagesPanel? = null
override fun getBannerSlogan(): String = config.displayName
override fun getIcon(expanded: Boolean): Icon = config.getTargetType().icon
override fun isModified(): Boolean =
targetConfigurable.isModified || languagesPanel?.isModified == true
override fun getDisplayName(): String = config.displayName
override fun apply() {
targetConfigurable.apply()
languagesPanel?.applyAll()
}
override fun reset() {
targetConfigurable.reset()
languagesPanel?.reset()
}
override fun setDisplayName(name: String) {
config.displayName = name
}
override fun disposeUIResources() {
super.disposeUIResources()
targetConfigurable.disposeUIResources()
languagesPanel?.disposeUIResources()
}
override fun getEditableObject() = config
override fun createOptionsPanel(): JComponent {
val panel = JPanel(VerticalLayout(UIUtil.DEFAULT_VGAP))
panel.border = JBUI.Borders.empty(0, 10, 10, 10)
panel.add(targetConfigurable.createComponent() ?: throw IllegalStateException())
val targetSupplier: Supplier<TargetEnvironmentConfiguration>
if (targetConfigurable is BrowsableTargetEnvironmentType.ConfigurableCurrentConfigurationProvider)
targetSupplier = Supplier<TargetEnvironmentConfiguration>(targetConfigurable::getCurrentConfiguration)
else {
targetSupplier = Supplier<TargetEnvironmentConfiguration> { config }
}
languagesPanel = TargetEnvironmentLanguagesPanel(project, config.getTargetType(), targetSupplier, config.runtimes) {
forceRefreshUI()
}
panel.add(languagesPanel!!.component)
return JBScrollPane(panel).also {
it.border = JBUI.Borders.empty()
}
}
override fun resetOptionsPanel() {
languagesPanel?.disposeUIResources()
languagesPanel = null
super.resetOptionsPanel()
}
private fun forceRefreshUI() {
createComponent()?.let {
it.revalidate()
it.repaint()
}
}
} | platform/execution-impl/src/com/intellij/execution/target/TargetEnvironmentDetailsConfigurable.kt | 1113525474 |
class A : OverrideMe {
override fun <caret>overrideMe() {
}
}
//INFO: <div class='definition'><pre><span style="color:#000080;font-weight:bold;">public</span> <span style="color:#000080;font-weight:bold;">open</span> <span style="color:#000080;font-weight:bold;">fun</span> <span style="color:#000000;">overrideMe</span>()<span style="">: </span><span style="color:#000000;">Unit</span></pre></div></pre></div><table class='sections'><p><tr><td valign='top' class='section'><p>From interface:</td><td valign='top'><p><a href="psi_element://OverrideMe"><code><span style="color:#000000;">OverrideMe</span></code></a><br>
//INFO: Some comment
//INFO: </td><tr><td valign='top' class='section'><p>Specified by:</td><td valign='top'><p><a href="psi_element://OverrideMe#overrideMe()"><code><span style="color:#000000;">overrideMe</span></code></a> in interface <a href="psi_element://OverrideMe"><code><span style="color:#000000;">OverrideMe</span></code></a></td></table><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/classKotlin.svg"/> <a href="psi_element://A"><code><span style="color:#000000;">A</span></code></a><br/></div>
| plugins/kotlin/idea/tests/testData/editor/quickDoc/JavaDocFromOverridenInterface.kt | 1289713480 |
package com.mounacheikhna.nearby.ui
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v4.view.ViewCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
/**
* A divider for items in a {@link RecyclerView}.
*/
class DividerItemDecoration(context: Context, orientation: Int, paddingStart: Float,
private val rtl: Boolean) : RecyclerView.ItemDecoration() {
private val divider: Drawable
private var orientation: Int = 0
private var paddingStart: Float = 0.toFloat()
init {
val a = context.obtainStyledAttributes(ATTRS)
divider = a.getDrawable(0)
a.recycle()
setOrientation(orientation)
setPaddingStart(paddingStart)
}
fun setOrientation(orientation: Int) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw IllegalArgumentException("invalid orientation")
}
this.orientation = orientation
}
fun setPaddingStart(paddingStart: Float) {
if (paddingStart < 0) {
throw IllegalArgumentException("paddingStart < 0")
}
this.paddingStart = paddingStart
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) {
if (orientation == VERTICAL_LIST) {
drawVertical(c, parent)
} else {
drawHorizontal(c, parent)
}
}
fun drawVertical(c: Canvas, parent: RecyclerView) {
val left = (parent.paddingLeft + (if (rtl) 0 else paddingStart.toInt()))
val right = (parent.width - parent.paddingRight + (if (rtl) paddingStart.toInt() else 0)).toInt()
val childCount = parent.childCount
for (i in 0..childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin + Math.round(
ViewCompat.getTranslationY(child))
val bottom = top + divider.intrinsicHeight
divider.setBounds(left, top, right, bottom)
divider.draw(c)
}
}
fun drawHorizontal(c: Canvas, parent: RecyclerView) {
val top = parent.paddingTop
val bottom = parent.height - parent.paddingBottom
val childCount = parent.childCount
for (i in 0..childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val left = child.right + params.rightMargin + Math.round(
ViewCompat.getTranslationX(child))
val right = left + divider.intrinsicHeight
divider.setBounds(left, top, right, bottom)
divider.draw(c)
}
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView,
state: RecyclerView.State?) {
if (orientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, divider.intrinsicHeight)
} else {
outRect.set(0, 0, divider.intrinsicWidth, 0)
}
}
companion object {
private val ATTRS = intArrayOf(android.R.attr.listDivider)
val HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL
val VERTICAL_LIST = LinearLayoutManager.VERTICAL
}
}
| app/src/main/kotlin/com/mounacheikhna/nearby/ui/DividerItemDecoration.kt | 437995481 |
// 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.codeInspection.test.junit
import com.intellij.analysis.JvmAnalysisBundle
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.codeInspection.*
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.createModifierActions
import com.intellij.lang.jvm.actions.modifierRequest
import com.intellij.psi.PsiModifier.ModifierConstant
import com.intellij.psi.PsiType
import org.jetbrains.uast.UMethod
class JUnitBeforeAfterInspection : AbstractBaseUastLocalInspectionTool() {
override fun checkMethod(method: UMethod, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor> {
val javaMethod = method.javaPsi
val annotation = ANNOTATIONS.firstOrNull {
AnnotationUtil.isAnnotated(javaMethod, it, AnnotationUtil.CHECK_HIERARCHY)
} ?: return emptyArray()
val returnType = method.returnType ?: return emptyArray()
val parameterList = method.uastParameters
if ((parameterList.isNotEmpty() || returnType != PsiType.VOID || javaMethod.hasModifier(JvmModifier.STATIC))
|| (isJUnit4(annotation) && !javaMethod.hasModifier(JvmModifier.PUBLIC))
) return makeStaticVoidFix(method, manager, isOnTheFly, annotation, if (isJUnit4(annotation)) JvmModifier.PUBLIC else null)
if (isJUnit5(annotation) && javaMethod.hasModifier(JvmModifier.PRIVATE)) {
return removePrivateModifierFix(method, manager, isOnTheFly, annotation)
}
return emptyArray()
}
private fun makeStaticVoidFix(
method: UMethod,
manager: InspectionManager,
isOnTheFly: Boolean,
annotation: String,
@ModifierConstant modifier: JvmModifier? // null means unchanged
): Array<ProblemDescriptor> {
val message = JvmAnalysisBundle.message("jvm.inspections.before.after.descriptor", annotation)
val fixes = arrayOf(MakeNoArgVoidFix(method.name, false, modifier))
val place = method.uastAnchor?.sourcePsi ?: return emptyArray()
val problemDescriptor = manager.createProblemDescriptor(
place, message, isOnTheFly, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
return arrayOf(problemDescriptor)
}
private fun removePrivateModifierFix(
method: UMethod,
manager: InspectionManager,
isOnTheFly: Boolean,
annotation: String,
): Array<ProblemDescriptor> {
val message = JvmAnalysisBundle.message("jvm.inspections.before.after.descriptor", annotation)
val containingFile = method.sourcePsi?.containingFile ?: return emptyArray()
val fixes = IntentionWrapper.wrapToQuickFixes(
createModifierActions(method, modifierRequest(JvmModifier.PRIVATE, false)), containingFile
).toTypedArray()
val place = method.uastAnchor?.sourcePsi ?: return emptyArray()
val problemDescriptor = manager.createProblemDescriptor(
place, message, isOnTheFly, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
return arrayOf(problemDescriptor)
}
private fun isJUnit4(annotation: String) = annotation.endsWith(BEFORE) || annotation.endsWith(AFTER)
private fun isJUnit5(annotation: String) = annotation.endsWith(BEFORE_EACH) || annotation.endsWith(AFTER_EACH)
companion object {
// JUnit 4 classes
private const val BEFORE = "org.junit.Before"
private const val AFTER = "org.junit.After"
// JUnit 5 classes
private const val BEFORE_EACH = "org.junit.jupiter.api.BeforeEach"
private const val AFTER_EACH = "org.junit.jupiter.api.AfterEach"
private val ANNOTATIONS = arrayOf(BEFORE, AFTER, BEFORE_EACH, AFTER_EACH)
}
} | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnitBeforeAfterInspection.kt | 2906701034 |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package codegen.coroutines.degenerate2
import kotlin.test.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
companion object : EmptyContinuation()
override fun resumeWith(result: Result<Any?>) { result.getOrThrow() }
}
suspend fun s1(): Unit = suspendCoroutineUninterceptedOrReturn { x ->
println("s1")
x.resume(Unit)
COROUTINE_SUSPENDED
}
suspend fun s2() {
println("s2")
s1()
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
@Test fun runTest() {
builder {
s2()
}
} | backend.native/tests/codegen/coroutines/degenerate2.kt | 1395407887 |
// 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.caches.project
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
import org.jetbrains.kotlin.idea.configuration.BuildSystemType
import org.jetbrains.kotlin.idea.configuration.getBuildSystemType
import org.jetbrains.kotlin.idea.project.isHMPPEnabled
import org.jetbrains.kotlin.platform.TargetPlatform
fun Module.getSourceModuleDependencies(
forProduction: Boolean,
platform: TargetPlatform,
includeTransitiveDependencies: Boolean = true,
): List<IdeaModuleInfo> {
// Use StringBuilder so that all lines are written into the log atomically (otherwise
// logs of call to getIdeaModelDependencies for several different modules interleave, leading
// to unreadable mess)
val debugString: StringBuilder? = if (LOG.isDebugEnabled) StringBuilder() else null
debugString?.appendLine("Building idea model dependencies for module ${this}, platform=${platform}, forProduction=$forProduction")
val allIdeaModuleInfoDependencies = resolveDependenciesFromOrderEntries(debugString, forProduction, includeTransitiveDependencies)
val supportedModuleInfoDependencies = filterSourceModuleDependencies(debugString, platform, allIdeaModuleInfoDependencies)
LOG.debug(debugString?.toString())
return supportedModuleInfoDependencies.toList()
}
private fun Module.resolveDependenciesFromOrderEntries(
debugString: StringBuilder?,
forProduction: Boolean,
includeTransitiveDependencies: Boolean,
): Set<IdeaModuleInfo> {
//NOTE: lib dependencies can be processed several times during recursive traversal
val result = LinkedHashSet<IdeaModuleInfo>()
val dependencyEnumerator = ModuleRootManager.getInstance(this).orderEntries().compileOnly()
if (includeTransitiveDependencies) {
dependencyEnumerator.recursively().exportedOnly()
}
if (forProduction && getBuildSystemType() == BuildSystemType.JPS) {
dependencyEnumerator.productionOnly()
}
debugString?.append(" IDEA dependencies: [")
dependencyEnumerator.forEach { orderEntry ->
debugString?.append("${orderEntry.presentableName} ")
if (orderEntry.acceptAsDependency(forProduction)) {
result.addAll(orderEntryToModuleInfo(project, orderEntry, forProduction))
debugString?.append("OK; ")
} else {
debugString?.append("SKIP; ")
}
true
}
debugString?.appendLine("]")
return result.toSet()
}
private fun Module.filterSourceModuleDependencies(
debugString: StringBuilder?,
platform: TargetPlatform,
dependencies: Set<IdeaModuleInfo>
): Set<IdeaModuleInfo> {
val dependencyFilter = if (isHMPPEnabled) HmppSourceModuleDependencyFilter(platform) else NonHmppSourceModuleDependenciesFilter(platform)
val supportedDependencies = dependencies.filter { dependency -> dependencyFilter.isSupportedDependency(dependency) }.toSet()
debugString?.appendLine(
" Corrected result (Supported dependencies): ${
supportedDependencies.joinToString(
prefix = "[",
postfix = "]",
separator = ";"
) { it.displayedName }
}"
)
return supportedDependencies
}
private fun OrderEntry.acceptAsDependency(forProduction: Boolean): Boolean {
return this !is ExportableOrderEntry
|| !forProduction
// this is needed for Maven/Gradle projects with "production-on-test" dependency
|| this is ModuleOrderEntry && isProductionOnTestDependency
|| scope.isForProductionCompile
}
private fun orderEntryToModuleInfo(project: Project, orderEntry: OrderEntry, forProduction: Boolean): List<IdeaModuleInfo> {
fun Module.toInfos() = correspondingModuleInfos().filter { !forProduction || it is ModuleProductionSourceInfo }
if (!orderEntry.isValid) return emptyList()
return when (orderEntry) {
is ModuleSourceOrderEntry -> {
orderEntry.getOwnerModule().toInfos()
}
is ModuleOrderEntry -> {
val module = orderEntry.module ?: return emptyList()
if (forProduction && orderEntry.isProductionOnTestDependency) {
listOfNotNull(module.testSourceInfo())
} else {
module.toInfos()
}
}
is LibraryOrderEntry -> {
val library = orderEntry.library ?: return listOf()
createLibraryInfo(project, library)
}
is JdkOrderEntry -> {
val sdk = orderEntry.jdk ?: return listOf()
listOfNotNull(SdkInfo(project, sdk))
}
else -> {
throw IllegalStateException("Unexpected order entry $orderEntry")
}
}
}
| plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/getSourceModuleDependencies.kt | 2819206208 |
// WITH_STDLIB
fun foo() {
val a = intArrayOf(1, 2, 3)
a.size<caret> > 0
}
| plugins/kotlin/idea/tests/testData/intentions/replaceSizeCheckWithIsNotEmpty/primitiveArray.kt | 1036806430 |
class KotlinSynthetic : Main() {
fun t() {
smth = ""
}
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/javaMethodSyntheticSet/KotlinSynthetic.kt | 2630417615 |
// 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.codeWithMe
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.AccessToken
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.trace
import com.intellij.openapi.util.Disposer
import com.intellij.util.Processor
import kotlinx.coroutines.ThreadContextElement
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.Callable
import java.util.function.BiConsumer
import java.util.function.Function
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
/**
* ClientId is a global context class that is used to distinguish the originator of an action in multi-client systems
* In such systems, each client has their own ClientId. Current process also can have its own ClientId, with this class providing methods to distinguish local actions from remote ones.
*
* It's up to the application to preserve and propagate the current value across background threads and asynchronous activities.
*/
data class ClientId(val value: String) {
enum class AbsenceBehavior {
/**
* Return localId if ClientId is not set
*/
RETURN_LOCAL,
/**
* Throw an exception if ClientId is not set
*/
THROW
}
companion object {
private val LOG = Logger.getInstance(ClientId::class.java)
fun getClientIdLogger() = LOG
/**
* Default client id for local application
*/
val defaultLocalId: ClientId = ClientId("Host")
/**
* Specifies behavior for [ClientId.current]
*/
var AbsenceBehaviorValue: AbsenceBehavior = AbsenceBehavior.RETURN_LOCAL
/**
* Controls propagation behavior. When false, decorateRunnable does nothing.
*/
@JvmStatic
var propagateAcrossThreads: Boolean = false
/**
* The ID considered local to this process. All other IDs (except for null) are considered remote
*/
@JvmStatic
var localId: ClientId = defaultLocalId
private set
/**
* True if and only if the current [ClientId] is local to this process
*/
@JvmStatic
val isCurrentlyUnderLocalId: Boolean
get() {
val clientIdValue = getCachedService()?.clientIdValue
return clientIdValue == null || clientIdValue == localId.value
}
/**
* Gets the current [ClientId]. Subject to [AbsenceBehaviorValue]
*/
@JvmStatic
val current: ClientId
get() = when (AbsenceBehaviorValue) {
AbsenceBehavior.RETURN_LOCAL -> currentOrNull ?: localId
AbsenceBehavior.THROW -> currentOrNull ?: throw NullPointerException("ClientId not set")
}
@JvmStatic
@ApiStatus.Internal
// optimization method for avoiding allocating ClientId in the hot path
fun getCurrentValue(): String {
val service = getCachedService()
return if (service == null) localId.value else service.clientIdValue ?: localId.value
}
/**
* Gets the current [ClientId]. Can be null if none was set.
*/
@JvmStatic
val currentOrNull: ClientId?
get() = getCachedService()?.clientIdValue?.let(::ClientId)
/**
* Overrides the ID that is considered to be local to this process. Can be only invoked once.
*/
@JvmStatic
fun overrideLocalId(newId: ClientId) {
require(localId == defaultLocalId)
localId = newId
}
/**
* Returns true if and only if the given ID is considered to be local to this process
*/
@JvmStatic
@Deprecated("Use ClientId.isLocal", ReplaceWith("clientId.isLocal", "com.intellij.codeWithMe.ClientId.Companion.isLocal"))
fun isLocalId(clientId: ClientId?): Boolean {
return clientId.isLocal
}
/**
* Is true if and only if the given ID is considered to be local to this process
*/
@JvmStatic
val ClientId?.isLocal: Boolean
get() = this == null || this == localId
/**
* Returns true if the given ID is local or a client is still in the session.
* Consider subscribing to a proper lifetime instead of this check.
*/
@JvmStatic
@Deprecated("Use ClientId.isValid", ReplaceWith("clientId.isValid", "com.intellij.codeWithMe.ClientId.Companion.isValid"))
fun isValidId(clientId: ClientId?): Boolean {
return clientId.isValid
}
/**
* Is true if the given ID is local or a client is still in the session.
* Consider subscribing to a proper lifetime instead of this check
*/
@JvmStatic
val ClientId?.isValid: Boolean
get() = getCachedService()?.isValid(this) ?: true
/**
* Returns a disposable object associated with the given ID.
* Consider using a lifetime that is usually passed along with the ID
*/
@JvmStatic
fun ClientId?.toDisposable(): Disposable {
return getCachedService()?.toDisposable(this) ?: Disposer.newDisposable()
}
/**
* Invokes a runnable under the given [ClientId]
*/
@JvmStatic
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Consider using an overload that returns a AccessToken to follow java try-with-resources pattern")
fun withClientId(clientId: ClientId?, action: Runnable): Unit = withClientId(clientId) { action.run() }
/**
* Computes a value under given [ClientId]
*/
@JvmStatic
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Consider using an overload that returns an AccessToken to follow java try-with-resources pattern")
fun <T> withClientId(clientId: ClientId?, action: Callable<T>): T = withClientId(clientId) { action.call() }
/**
* Computes a value under given [ClientId]
*/
@JvmStatic
inline fun <T> withClientId(clientId: ClientId?, action: () -> T): T {
val service = ClientIdService.tryGetInstance() ?: return action()
val newClientIdValue = if (!service.isValid(clientId)) {
getClientIdLogger().trace { "Invalid ClientId $clientId replaced with null at ${Throwable().fillInStackTrace()}" }
null
}
else {
clientId?.value
}
val oldClientIdValue = service.clientIdValue
try {
service.clientIdValue = newClientIdValue
return action()
}
finally {
service.clientIdValue = oldClientIdValue
}
}
class ClientIdAccessToken(val oldClientIdValue: String?) : AccessToken() {
override fun finish() {
getCachedService()?.clientIdValue = oldClientIdValue
}
}
@JvmStatic
fun withClientId(clientId: ClientId?): AccessToken {
if (clientId == null) return AccessToken.EMPTY_ACCESS_TOKEN
return withClientId(clientId.value)
}
@JvmStatic
fun withClientId(clientIdValue: String): AccessToken {
val service = getCachedService()
val oldClientIdValue: String?
oldClientIdValue = service?.clientIdValue
if (service == null || clientIdValue == oldClientIdValue) return AccessToken.EMPTY_ACCESS_TOKEN
val newClientIdValue = if (service.isValid(ClientId(clientIdValue))) clientIdValue
else {
LOG.trace { "Invalid ClientId $clientIdValue replaced with null at ${Throwable().fillInStackTrace()}" }
null
}
service.clientIdValue = newClientIdValue
return ClientIdAccessToken(oldClientIdValue)
}
private var service:ClientIdService? = null
private fun getCachedService(): ClientIdService? {
var cached = service
if (cached != null) return cached
cached = ClientIdService.tryGetInstance()
if (cached != null) {
service = cached
}
return cached
}
@JvmStatic
fun <T> decorateFunction(action: () -> T): () -> T {
if (propagateAcrossThreads) return action
val currentId = currentOrNull
return {
withClientId(currentId) {
return@withClientId action()
}
}
}
@JvmStatic
fun decorateRunnable(runnable: Runnable): Runnable {
if (!propagateAcrossThreads) {
return runnable
}
val currentId = currentOrNull
return Runnable {
withClientId(currentId) { runnable.run() }
}
}
@JvmStatic
fun <T> decorateCallable(callable: Callable<T>): Callable<T> {
if (!propagateAcrossThreads) return callable
val currentId = currentOrNull
return Callable { withClientId(currentId, callable) }
}
@JvmStatic
fun <T, R> decorateFunction(function: Function<T, R>): Function<T, R> {
if (!propagateAcrossThreads) return function
val currentId = currentOrNull
return Function { withClientId(currentId) { function.apply(it) } }
}
@JvmStatic
fun <T, U> decorateBiConsumer(biConsumer: BiConsumer<T, U>): BiConsumer<T, U> {
if (!propagateAcrossThreads) return biConsumer
val currentId = currentOrNull
return BiConsumer { t, u -> withClientId(currentId) { biConsumer.accept(t, u) } }
}
@JvmStatic
fun <T> decorateProcessor(processor: Processor<T>): Processor<T> {
if (!propagateAcrossThreads) return processor
val currentId = currentOrNull
return Processor { withClientId(currentId) { processor.process(it) } }
}
fun coroutineContext(): CoroutineContext = currentOrNull?.asContextElement() ?: EmptyCoroutineContext
}
}
fun isForeignClientOnServer(): Boolean {
return !ClientId.isCurrentlyUnderLocalId && ClientId.localId == ClientId.defaultLocalId
}
fun isOnGuest(): Boolean {
return ClientId.localId != ClientId.defaultLocalId
}
fun ClientId.asContextElement(): CoroutineContext.Element = ClientIdElement(this)
private object ClientIdElementKey : CoroutineContext.Key<ClientIdElement>
private class ClientIdElement(private val clientId: ClientId) : ThreadContextElement<AccessToken> {
override val key: CoroutineContext.Key<*> get() = ClientIdElementKey
override fun updateThreadContext(context: CoroutineContext): AccessToken {
return ClientId.withClientId(clientId)
}
override fun restoreThreadContext(context: CoroutineContext, oldState: AccessToken): Unit {
oldState.finish()
}
}
| platform/core-api/src/com/intellij/codeWithMe/ClientId.kt | 508728639 |
package testing
interface I {
val <caret>p: Int
get() = 0
}
class A : I
class B : I {
override val p = 5
}
class C : I
interface II: I
interface III : I {
override val p: Int get() = 1
}
// REF: (in testing.B).p
// REF: (in testing.III).p
| plugins/kotlin/idea/tests/testData/navigation/implementations/DefaultImplProperty.kt | 2321146714 |
// AFTER-WARNING: Parameter 'a' is never used
fun <T> doSomething(a: T) {}
fun foo() {
for (i in 1..4)
<caret>doSomething("test")
}
| plugins/kotlin/idea/tests/testData/intentions/addBraces/addBracesForFor.kt | 3089442766 |
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetnews.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Shapes
import androidx.compose.ui.unit.dp
val JetnewsShapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(8.dp)
)
| JetNews/app/src/main/java/com/example/jetnews/ui/theme/Shape.kt | 1410918762 |
package foo
fun parenB(p: () -> Unit) = p()
fun parenP() {}
fun parenBP(p: () -> () -> Unit): () -> Unit = p()
fun parenPP(): () -> Unit = {}
fun parenPB(p: (() -> Unit) -> Unit): (() -> Unit) -> Unit = p
fun some(p1: () -> Unit, p2: (() -> Unit) -> Unit) {
parenB { p1() }
parenP()
parenBP { p1 }()
parenPP()()
(parenPB(p2)) {}
} | plugins/kotlin/idea/tests/testData/refactoring/copy/copyFunCallQualificationWithParentheses/after/foo/test.kt | 2809749376 |
// PROBLEM: none
class Test {
override fun equals(other: Any?): Boolean {
val another = Test()
if (<caret>another == other) return true
return false
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/recursiveEqualsCall/recursiveFake.kt | 3268896830 |
package com.stustirling.ribotviewer.data.local.dao
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Insert
import android.arch.persistence.room.OnConflictStrategy
import android.arch.persistence.room.Query
import com.stustirling.ribotviewer.data.local.model.LocalRibot
import io.reactivex.Flowable
/**
* Created by Stu Stirling on 23/09/2017.
*/
@Dao
interface RibotDao {
@Query("SELECT * FROM ribots")
fun getRibots() : Flowable<List<LocalRibot>>
@Query("SELECT * FROM ribots WHERE id = :id")
fun getRibot(id:String) : LocalRibot
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(ribots: List<LocalRibot>)
} | data/src/main/java/com/stustirling/ribotviewer/data/local/dao/RibotDao.kt | 1501011175 |
/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
package net.mediaarea.mediainfo
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.android.billingclient.api.SkuDetails
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingFlowParams
import android.app.Activity
import android.os.Bundle
import android.view.Gravity
import android.view.MenuItem
import android.view.View
import kotlinx.android.synthetic.main.activity_subscribe.*
class SubscribeActivity : AppCompatActivity() {
private lateinit var subscriptionManager: SubscriptionManager
private lateinit var subscriptionDetails: SkuDetails
private lateinit var lifetimeSubscriptionDetails: SkuDetails
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_subscribe)
subscriptionManager = SubscriptionManager.getInstance(application)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
subscriptionManager.details.observe (this, Observer {
subscriptionDetails = it
subscribe_button.isEnabled = true
subscribe_button.text = subscribe_button.text.toString()
.replace("%PRICE%", subscriptionDetails.price)
subscription_detail_text.visibility= View.VISIBLE
subscription_detail_text.gravity=Gravity.CENTER_HORIZONTAL
})
subscriptionManager.lifetimeDetails.observe (this, Observer {
lifetimeSubscriptionDetails = it
lifetime_subscribe_button.isEnabled = true
lifetime_subscribe_button.text = lifetime_subscribe_button.text.toString()
.replace("%PRICE%", lifetimeSubscriptionDetails.price)
})
subscribe_button.setOnClickListener {
if (::subscriptionDetails.isInitialized) {
val request = BillingFlowParams.newBuilder()
.setSkuDetails(subscriptionDetails)
.build()
if (subscriptionManager.launchBillingFlow(this, request) == BillingClient.BillingResponseCode.OK) {
finish()
}
}
}
lifetime_subscribe_button.setOnClickListener {
if (::lifetimeSubscriptionDetails.isInitialized) {
val request = BillingFlowParams.newBuilder()
.setSkuDetails(lifetimeSubscriptionDetails)
.build()
if (subscriptionManager.launchBillingFlow(this, request) == BillingClient.BillingResponseCode.OK) {
setResult(Activity.RESULT_OK)
finish()
}
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
setResult(Activity.RESULT_CANCELED)
finish()
}
return super.onOptionsItemSelected(item)
}
}
| Source/GUI/Android/app/src/main/java/net/mediaarea/mediainfo/SubscribeActivity.kt | 1104633549 |
package ch.rmy.android.http_shortcuts.variables.types
import android.content.Context
import android.graphics.Color
import ch.rmy.android.framework.extensions.showOrElse
import ch.rmy.android.framework.extensions.toLocalizable
import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableRepository
import ch.rmy.android.http_shortcuts.data.models.VariableModel
import ch.rmy.android.http_shortcuts.utils.ActivityProvider
import ch.rmy.android.http_shortcuts.utils.ColorPickerFactory
import ch.rmy.android.http_shortcuts.utils.ColorUtil.colorIntToHexString
import ch.rmy.android.http_shortcuts.utils.ColorUtil.hexStringToColorInt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import javax.inject.Inject
import kotlin.coroutines.resume
class ColorType : BaseVariableType() {
@Inject
lateinit var variablesRepository: VariableRepository
@Inject
lateinit var activityProvider: ActivityProvider
@Inject
lateinit var colorPickerFactory: ColorPickerFactory
override fun inject(applicationComponent: ApplicationComponent) {
applicationComponent.inject(this)
}
override suspend fun resolveValue(context: Context, variable: VariableModel): String {
val value = withContext(Dispatchers.Main) {
suspendCancellableCoroutine<String> { continuation ->
colorPickerFactory.createColorPicker(
onColorPicked = { color ->
continuation.resume(color.colorIntToHexString())
},
onDismissed = {
continuation.cancel()
},
title = variable.title.toLocalizable(),
initialColor = getInitialColor(variable),
)
.showOrElse {
continuation.cancel()
}
}
}
if (variable.rememberValue) {
variablesRepository.setVariableValue(variable.id, value)
}
return value
}
private fun getInitialColor(variable: VariableModel): Int =
variable.takeIf { it.rememberValue }?.value?.hexStringToColorInt()
?: Color.BLACK
}
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/variables/types/ColorType.kt | 515630401 |
package hu.juzraai.ted.xml.model.tedexport.coded
import hu.juzraai.ted.xml.model.tedexport.coded.refojs.NoOj
import org.simpleframework.xml.Element
import org.simpleframework.xml.Root
/**
* Model of REF_OJS element.
*
* @author Zsolt Jurányi
*/
@Root(name = "REF_OJS")
data class RefOjs(
@field:Element(name = "COLL_OJ")
var collOj: String = "",
@field:Element(name = "NO_OJ")
var noOj: NoOj = NoOj(),
@field:Element(name = "DATE_PUB")
var datePub: String = ""
) | src/main/kotlin/hu/juzraai/ted/xml/model/tedexport/coded/RefOjs.kt | 1430583608 |
package io.kotest.matchers.date
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNot
import io.kotest.matchers.shouldNotBe
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.Month
import java.time.OffsetDateTime
import java.time.Period
import java.time.ZonedDateTime
import java.time.temporal.TemporalAmount
/**
* Asserts that this year is the same as [date]'s year
*
* Verifies that this year is the same as [date]'s year, ignoring any other fields.
* For example, 09/02/1998 has the same year as 10/03/1998, and this assertion should pass for this comparison
*
* Opposite of [LocalDate.shouldNotHaveSameYearAs]
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 3, 10)
*
* firstDate shouldHaveSameYearAs secondDate // Assertion passes
*
*
* val firstDate = LocalDate.of(2018, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 9)
*
* firstDate shouldHaveSameYearAs secondDate // Assertion fails, 2018 != 1998
```
*/
infix fun LocalDate.shouldHaveSameYearAs(date: LocalDate) = this should haveSameYear(date)
/**
* Asserts that this year is NOT the same as [date]'s year
*
* Verifies that this year isn't the same as [date]'s year, ignoring any other fields.
* For example, 09/02/1998 doesn't have the same year as 09/02/2018, and this assertion should pass for this comparison
*
* Opposite of [LocalDate.shouldHaveSameYearAs]
*
* ```
* val firstDate = LocalDate.of(2018, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 9)
*
* firstDate shouldNotHaveSameYearAs secondDate // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 3, 10)
*
* firstDate shouldNotHaveSameYearAs secondDate // Assertion fails, 1998 == 1998, and we expected a difference
* ```
*/
infix fun LocalDate.shouldNotHaveSameYearAs(date: LocalDate) = this shouldNot haveSameYear(date)
/**
* Matcher that compares years of LocalDates
*
* Verifies that two dates have exactly the same year, ignoring any other fields.
* For example, 09/02/1998 has the same year as 10/03/1998, and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 3, 10)
*
* firstDate should haveSameYear(secondDate) // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(2018, 2, 9)
*
* firstDate shouldNot haveSameYear(secondDate) // Assertion passes
* ```
*
* @see [LocalDate.shouldHaveSameYearAs]
* @see [LocalDate.shouldNotHaveSameYearAs]
*/
fun haveSameYear(date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> {
override fun test(value: LocalDate): MatcherResult =
MatcherResult(value.year == date.year, "$value should have year ${date.year}", "$value should not have year ${date.year}")
}
/**
* Asserts that this year is the same as [date]'s year
*
* Verifies that this year is the same as [date]'s year, ignoring any other fields.
* For example, 09/02/1998 10:00:00 has the same year as 10/03/1998 11:30:30, and this assertion should pass for this comparison
*
* Opposite of [LocalDateTime.shouldNotHaveSameYearAs]
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 3, 10, 11, 30, 30)
*
* firstDate shouldHaveSameYearAs secondDate // Assertion passes
*
*
* val firstDate = LocalDateTime.of(2018, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
*
* firstDate shouldHaveSameYearAs secondDate // Assertion fails, 2018 != 1998
* ```
*/
infix fun LocalDateTime.shouldHaveSameYearAs(date: LocalDateTime) = this should haveSameYear(date)
/**
* Asserts that this year is NOT the same as [date]'s year
*
* Verifies that this year isn't the same as [date]'s year, ignoring any other fields.
* For example, 09/02/1998 10:00:00 doesn't have the same year as 09/02/2018 10:00:00, and this assertion should pass for this comparison
*
* Opposite of [LocalDateTime.shouldHaveSameYearAs]
*
* ```
* val firstDate = LocalDateTime.of(2018, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 3, 10, 11, 30, 30)
*
* firstDate shouldNotHaveSameYearAs secondDate // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 3, 10, 1, 30, 30)
*
* firstDate shouldNotHaveSameYearAs secondDate // Assertion fails, 1998 == 1998, and we expected a difference
* ```
*/
infix fun LocalDateTime.shouldNotHaveSameYearAs(date: LocalDateTime) = this shouldNot haveSameYear(date)
/**
* Matcher that compares years of LocalDateTimes
*
* Verifies that two DateTimes have exactly the same year, ignoring any other fields.
* For example, 09/02/1998 10:00:00 has the same year as 10/03/1998 11:30:30, and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 3, 10, 11, 30, 30)
*
* firstDate should haveSameYear(secondDate) // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(2018, 2, 9, 10, 0, 0)
*
* firstDate shouldNot haveSameYear(secondDate) // Assertion passes
* ```
*
* @see [LocalDateTime.shouldHaveSameYearAs]
* @see [LocalDateTime.shouldNotHaveSameYearAs]
*/
fun haveSameYear(date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> {
override fun test(value: LocalDateTime): MatcherResult =
MatcherResult(value.year == date.year, "$value should have year ${date.year}", "$value should not have year ${date.year}")
}
/**
* Asserts that this year is the same as [date]'s year
*
* Verifies that this year is the same as [date]'s year, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same year as 10/03/1998 11:30:30 -05:00 America/Chicago,
* and this assertion should pass for this comparison
*
* Opposite of [ZonedDateTime.shouldNotHaveSameYearAs]
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 3, 10, 11, 30, 30, 30, ZoneId.of("America/Chicago"))
*
* firstDate shouldHaveSameYearAs secondDate // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(2018, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldHaveSameYearAs secondDate // Assertion fails, 2018 != 1998
* ```
*/
infix fun ZonedDateTime.shouldHaveSameYearAs(date: ZonedDateTime) = this should haveSameYear(date)
/**
* Asserts that this year is NOT the same as [date]'s year
*
* Verifies that this year isn't the same as [date]'s year, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo doesn't have the same year as 09/02/2018 10:00:00 -03:00 America/Sao_Paulo,
* and this assertion should pass for this comparison
*
* Opposite of [ZonedDateTime.shouldHaveSameYearAs]
*
* ```
* val firstDate = ZonedDateTime.of(2018, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 9, 19, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNotHaveSameYearAs secondDate // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 3, 10, 1, 30, 30, 30, ZoneId.of("America/Chicago"))
*
* firstDate shouldNotHaveSameYearAs secondDate // Assertion fails, 1998 == 1998, and we expected a difference
* ```
*/
infix fun ZonedDateTime.shouldNotHaveSameYearAs(date: ZonedDateTime) = this shouldNot haveSameYear(date)
/**
* Matcher that compares years of ZonedDateTimes
*
* Verifies that two ZonedDateTimes have exactly the same year, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same year as 10/03/1998 11:30:30 -05:00 America/Chicago,
* and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 3, 10, 11, 30, 30, 30, ZoneId.of("America/Chicago"))
*
* firstDate should haveSameYear(secondDate) // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2018, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNot haveSameYear(secondDate) // Assertion passes
* ```
*
* @see [ZonedDateTime.shouldHaveSameYearAs]
* @see [ZonedDateTime.shouldNotHaveSameYearAs]
*/
fun haveSameYear(date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> {
override fun test(value: ZonedDateTime): MatcherResult =
MatcherResult(value.year == date.year, "$value should have year ${date.year}", "$value should not have year ${date.year}")
}
/**
* Asserts that this year is the same as [date]'s year
*
* Verifies that this year is the same as [date]'s year, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 has the same year as 10/03/1998 11:30:30 -05:00,
* and this assertion should pass for this comparison
*
* Opposite of [OffsetDateTime.shouldNotHaveSameYearAs]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 3, 10, 11, 30, 30, 30, ZoneOffset.ofHours(-5))
*
* firstDate shouldHaveSameYearAs secondDate // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(2018, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldHaveSameYearAs secondDate // Assertion fails, 2018 != 1998
* ```
*/
infix fun OffsetDateTime.shouldHaveSameYearAs(date: OffsetDateTime) = this should haveSameYear(date)
/**
* Asserts that this year is NOT the same as [date]'s year
*
* Verifies that this year isn't the same as [date]'s year, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 doesn't have the same year as 09/02/2018 10:00:00 -03:00,
* and this assertion should pass for this comparison
*
* Opposite of [OffsetDateTime.shouldHaveSameYearAs]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1999, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* firstDate shouldNotHaveSameYearAs secondDate // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 3, 10, 11, 30, 30, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNotHaveSameYearAs secondDate // Assertion fails, 1998 == 1998 and we expected a difference
*
* ```
*/
infix fun OffsetDateTime.shouldNotHaveSameYearAs(date: OffsetDateTime) = this shouldNot haveSameYear(date)
/**
* Matcher that compares years of OffsetDateTimes
*
* Verifies that two ZonedDateTimes have exactly the same year, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 has the same year as 10/03/1998 11:30:30 -05:00,
* and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = OffsetDateTime.of(2018, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 9, 19, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNotHaveSameYearAs secondDate // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 3, 10, 1, 30, 30, 30, ZoneOffset.ofHours(-5))
*
* firstDate shouldNotHaveSameYearAs secondDate // Assertion fails, 1998 == 1998, and we expected a difference
* ```
*
* @see [OffsetDateTime.shouldHaveSameYearAs]
* @see [OffsetDateTime.shouldNotHaveSameYearAs]
*/
fun haveSameYear(date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> {
override fun test(value: OffsetDateTime): MatcherResult =
MatcherResult(value.year == date.year, "$value should have year ${date.year}", "$value should not have year ${date.year}")
}
/**
* Asserts that this month is the same as [date]'s month
*
* Verifies that month year is the same as [date]'s month, ignoring any other fields.
* For example, 09/02/1998 has the same month as 10/02/2018, and this assertion should pass for this comparison
*
* Opposite of [LocalDate.shouldNotHaveSameMonthAs]
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 3, 10)
*
* firstDate should haveSameYear(secondDate) // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(2018, 2, 9)
*
* firstDate shouldNot haveSameYear(secondDate) // Assertion passes
* ```
*/
infix fun LocalDate.shouldHaveSameMonthAs(date: LocalDate) = this should haveSameMonth(date)
/**
* Asserts that this month is NOT the same as [date]'s month
*
* Verifies that this month isn't the same as [date]'s month, ignoring any other fields.
* For example, 09/02/1998 doesn't have the same month as 09/03/1998, and this assertion should pass for this comparison
*
* Opposite of [LocalDate.shouldHaveSameMonthAs]
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(2018, 2, 10)
*
* firstDate shouldHaveSameMonthAs secondDate // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 3, 9)
*
* firstDate shouldHaveSameMonthAs secondDate // Assertion fails, 2 != 3
* ```
*/
infix fun LocalDate.shouldNotHaveSameMonthAs(date: LocalDate) = this shouldNot haveSameMonth(date)
/**
* Matcher that compares months of LocalDates
*
* Verifies that two dates have exactly the same month, ignoring any other fields.
* For example, 09/02/1998 has the same month as 10/02/2018, and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 3, 9)
*
* firstDate shouldNotHaveSameMonthAs secondDate // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(2018, 2, 10)
*
* firstDate shouldNotHaveSameMonthAs secondDate // Assertion fails, 2 == 2, and we expected a difference
* ```
*
* @see [LocalDate.shouldHaveSameMonthAs]
* @see [LocalDate.shouldNotHaveSameMonthAs]
*/
fun haveSameMonth(date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> {
override fun test(value: LocalDate): MatcherResult =
MatcherResult(value.month == date.month, "$value should have month ${date.month}", "$value should not have month ${date.month}")
}
/**
* Asserts that this month is the same as [date]'s month
*
* Verifies that this month is the same as [date]'s month, ignoring any other fields.
* For example, 09/02/1998 10:00:00 has the same month as 10/02/2018 11:30:30, and this assertion should pass for this comparison
*
* Opposite of [LocalDateTime.shouldNotHaveSameMonthAs]
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(2018, 2, 10, 10, 0, 0)
*
* firstDate should haveSameMonth(secondDate) // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 3, 9, 10, 0, 0)
*
* firstDate shouldNot haveSameMonth(secondDate) // Assertion passes
* ```
*/
infix fun LocalDateTime.shouldHaveSameMonthAs(date: LocalDateTime) = this should haveSameMonth(date)
/**
* Asserts that this month is NOT the same as [date]'s month
*
* Verifies that this month isn't the same as [date]'s month, ignoring any other fields.
* For example, 09/02/1998 10:00:00 doesn't have the same month as 09/03/1998 10:00:00, and this assertion should pass for this comparison
*
* Opposite of [LocalDateTime.shouldHaveSameMonthAs]
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(2018, 2, 10, 11, 30, 30)
*
* firstDate shouldHaveSameMonthAs secondDate // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 3, 9, 10, 0, 0)
*
* firstDate shouldHaveSameMonthAs secondDate // Assertion fails, 2 != 3
* ```
*/
infix fun LocalDateTime.shouldNotHaveSameMonthAs(date: LocalDateTime) = this shouldNot haveSameMonth(date)
/**
* Matcher that compares months of LocalDateTimes
*
* Verifies that two DateTimes have exactly the same month, ignoring any other fields.
* For example, 09/02/1998 10:00:00 has the same month as 10/02/2018 11:30:30, and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 3, 10, 11, 30, 30)
*
* firstDate shouldNotHaveSameMonthAs secondDate // Assertion passes
*
*
* val firstDate = LocalDateTime.of(2018, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 10, 1, 30, 30)
*
* firstDate shouldNotHaveSameMonthAs secondDate // Assertion fails, 2 == 2, and we expected a difference
* ```
*
* @see [LocalDateTime.shouldHaveSameMonthAs]
* @see [LocalDateTime.shouldNotHaveSameMonthAs]
*/
fun haveSameMonth(date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> {
override fun test(value: LocalDateTime): MatcherResult =
MatcherResult(value.month == date.month, "$value should have month ${date.month}", "$value should not have month ${date.month}")
}
/**
* Asserts that this month is the same as [date]'s month
*
* Verifies that this month is the same as [date]'s month, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same month as 10/02/2018 11:30:30 -05:00 America/Chicago,
* and this assertion should pass for this comparison
*
* Opposite of [ZonedDateTime.shouldNotHaveSameMonthAs]
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2018, 2, 10, 11, 30, 30, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate should haveSameMonth(secondDate) // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 3, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNot haveSameMonth(secondDate) // Assertion passes
* ```
*/
infix fun ZonedDateTime.shouldHaveSameMonthAs(date: ZonedDateTime) = this should haveSameMonth(date)
/**
* Asserts that this month is NOT the same as [date]'s month
*
* Verifies that this month isn't the same as [date]'s month, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo doesn't have the same month as 09/03/1998 10:00:00 -03:00 America/Sao_Paulo,
* and this assertion should pass for this comparison
*
* Opposite of [ZonedDateTime.shouldHaveSameMonthAs]
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2018, 2, 10, 11, 30, 30, 30, ZoneId.of("America/Chicago"))
*
* firstDate shouldHaveSameMonthAs secondDate // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 3, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldHaveSameMonthAs secondDate // Assertion fails, 2 != 3
* ```
*/
infix fun ZonedDateTime.shouldNotHaveSameMonthAs(date: ZonedDateTime) = this shouldNot haveSameMonth(date)
/**
* Matcher that compares months of ZonedDateTimes
*
* Verifies that two ZonedDateTimes have exactly the same month, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same month as 10/02/2018 11:30:30 -05:00 America/Chicago,
* and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 3, 9, 19, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNotHaveSameMonthAs secondDate // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2018, 2, 10, 1, 30, 30, 30, ZoneId.of("America/Chicago"))
*
* firstDate shouldNotHaveSameMonthAs secondDate // Assertion fails, 2 == 2, and we expected a difference
* ```
*
* @see [ZonedDateTime.shouldHaveSameMonthAs]
* @see [ZonedDateTime.shouldNotHaveSameMonthAs]
*/
fun haveSameMonth(date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> {
override fun test(value: ZonedDateTime): MatcherResult =
MatcherResult(value.month == date.month, "$value should have month ${date.month}", "$value should not have month ${date.month}")
}
/**
* Asserts that this month is the same as [date]'s month
*
* Verifies that this month is the same as [date]'s month, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 has the same month as 10/02/2018 11:30:30 -05:00,
* and this assertion should pass for this comparison
*
* Opposite of [OffsetDateTime.shouldNotHaveSameMonthAs]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2018, 2, 10, 11, 30, 30, 30, ZoneOffset.ofHours(-5))
*
* firstDate shouldHaveSameMonthAs secondDate // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 3, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldHaveSameMonthAs secondDate // Assertion fails, 2 != 3
* ```
*/
infix fun OffsetDateTime.shouldHaveSameMonthAs(date: OffsetDateTime) = this should haveSameMonth(date)
/**
* Asserts that this month is NOT the same as [date]'s month
*
* Verifies that this month isn't the same as [date]'s month, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 doesn't have the same month as 09/03/1998 10:00:00 -03:00,
* and this assertion should pass for this comparison
*
* Opposite of [OffsetDateTime.shouldHaveSameMonthAs]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 3, 9, 19, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNotHaveSameMonthAs secondDate // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2018, 2, 10, 1, 30, 30, 30, ZoneOffset.ofHours(-5))
*
* firstDate shouldNotHaveSameMonthAs secondDate // Assertion fails, 2 == 2, and we expected a difference
* ```
*/
infix fun OffsetDateTime.shouldNotHaveSameMonthAs(date: OffsetDateTime) = this shouldNot haveSameMonth(date)
/**
* Matcher that compares months of OffsetDateTimes
*
* Verifies that two ZonedDateTimes have exactly the same month, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 has the same month as 10/02/1998 11:30:30 -05:00,
* and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2018, 2, 10, 11, 30, 30, 30, ZoneOffset.ofHours(-5))
*
* firstDate should haveSameMonth(secondDate) // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 3, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNot haveSameMonth(secondDate) // Assertion passes
* ```
*
* @see [OffsetDateTime.shouldHaveSameMonthAs]
* @see [OffsetDateTime.shouldNotHaveSameMonthAs]
*/
fun haveSameMonth(date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> {
override fun test(value: OffsetDateTime): MatcherResult =
MatcherResult(value.month == date.month, "$value should have month ${date.month}", "$value should not have month ${date.month}")
}
/**
* Asserts that this day is the same as [date]'s day
*
* Verifies that this day is the same as [date]'s day, ignoring any other fields.
* For example, 09/02/1998 has the same day as 09/03/2018, and this assertion should pass for this comparison
*
* Opposite of [LocalDate.shouldNotHaveSameDayAs]
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(2018, 3, 9)
*
* firstDate shouldHaveSameDayAs secondDate // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate shouldHaveSameDayAs secondDate // Assertion fails, 9 != 10
* ```
*/
infix fun LocalDate.shouldHaveSameDayAs(date: LocalDate) = this should haveSameDay(date)
/**
* Asserts that this day is NOT the same as [date]'s day
*
* Verifies that this day isn't the same as [date]'s day, ignoring any other fields.
* For example, 09/02/1998 doesn't have the same day as 10/02/1998, and this assertion should pass for this comparison
*
* Opposite of [LocalDate.shouldHaveSameDayAs]
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate shouldNotHaveSameDayAs secondDate // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(2018, 3, 9)
*
* firstDate shouldNotHaveSameDayAs secondDate // Assertion fails, 9 == 9, and we expected a difference
* ```
*/
infix fun LocalDate.shouldNotHaveSameDayAs(date: LocalDate) = this shouldNot haveSameDay(date)
/**
* Matcher that compares days of LocalDates
*
* Verifies that two dates have exactly the same day, ignoring any other fields.
* For example, 09/02/1998 has the same day as 09/03/2018, and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(2018, 3, 9)
*
* firstDate should haveSameDay(secondDate) // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate shouldNot haveSameDay(secondDate) // Assertion passes
* ```
*
* @see [LocalDate.shouldHaveSameDayAs]
* @see [LocalDate.shouldNotHaveSameDayAs]
*/
fun haveSameDay(date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> {
override fun test(value: LocalDate): MatcherResult =
MatcherResult(value.dayOfMonth == date.dayOfMonth, "$value should have day ${date.dayOfMonth} but had ${value.dayOfMonth}", "$value should not have day ${date.dayOfMonth}")
}
/**
* Asserts that this day is the same as [date]'s day
*
* Verifies that this day is the same as [date]'s day, ignoring any other fields.
* For example, 09/02/1998 10:00:00 has the same day as 09/03/2018 11:30:30, and this assertion should pass for this comparison
*
* Opposite of [LocalDateTime.shouldNotHaveSameDayAs]
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 3, 9, 11, 30, 30)
*
* firstDate shouldHaveSameDayAs secondDate // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0)
*
* firstDate shouldHaveSameDayAs secondDate // Assertion fails, 9 != 10
* ```
*/
infix fun LocalDateTime.shouldHaveSameDayAs(date: LocalDateTime) = this should haveSameDay(date)
/**
* Asserts that this day is NOT the same as [date]'s day
*
* Verifies that this year isn't the same as [date]'s day, ignoring any other fields.
* For example, 09/02/1998 10:00:00 doesn't have the same day as 10/02/1998 10:00:00, and this assertion should pass for this comparison
*
* Opposite of [LocalDateTime.shouldHaveSameDayAs]
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0)
*
* firstDate shouldNotHaveSameDayAs secondDate // Assertion passes
*
*
* val firstDate = LocalDateTime.of(2018, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 3, 9, 11, 30, 30)
*
* firstDate shouldNotHaveSameDayAs secondDate // Assertion fails, 9 == 9, and we expected a difference
* ```
*/
infix fun LocalDateTime.shouldNotHaveSameDayAs(date: LocalDateTime) = this shouldNot haveSameDay(date)
/**
* Matcher that compares days of LocalDateTimes
*
* Verifies that two DateTimes have exactly the same day, ignoring any other fields.
* For example, 09/02/1998 10:00:00 has the same day as 09/03/2018 11:30:30, and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(2018, 3, 9, 11, 30, 30)
*
* firstDate should haveSameDay(secondDate) // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0)
*
* firstDate shouldNot haveSameDay(secondDate) // Assertion passes
* ```
*
* @see [LocalDateTime.shouldHaveSameDayAs]
* @see [LocalDateTime.shouldNotHaveSameDayAs]
*/
fun haveSameDay(date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> {
override fun test(value: LocalDateTime): MatcherResult =
MatcherResult(value.dayOfMonth == date.dayOfMonth, "$value should have day ${date.dayOfMonth} but had ${value.dayOfMonth}", "$value should not have day ${date.dayOfMonth}")
}
/**
* Asserts that this day is the same as [date]'s day
*
* Verifies that this day is the same as [date]'s day, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same day as 09/03/2018 11:30:30 -05:00 America/Chicago,
* and this assertion should pass for this comparison
*
* Opposite of [ZonedDateTime.shouldNotHaveSameDayAs]
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2018, 3, 9, 11, 30, 30, 30, ZoneId.of("America/Chicago"))
*
* firstDate shouldHaveSameDayAs secondDate // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldHaveSameDayAs secondDate // Assertion fails, 9 != 10
* ```
*/
infix fun ZonedDateTime.shouldHaveSameDayAs(date: ZonedDateTime) = this should haveSameDay(date)
/**
* Asserts that this day is NOT the same as [date]'s day
*
* Verifies that this day isn't the same as [date]'s day, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo doesn't have the same day as 10/02/1998 10:00:00 -03:00 America/Sao_Paulo,
* and this assertion should pass for this comparison
*
* Opposite of [ZonedDateTime.shouldHaveSameDayAs]
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNotHaveSameDayAs secondDate // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2018, 3, 9, 11, 30, 30, 30, ZoneId.of("America/Chicago"))
*
* firstDate shouldNotHaveSameDayAs secondDate // Assertion fails, 9 == 9, and we expected a difference
* ```
*/
infix fun ZonedDateTime.shouldNotHaveSameDayAs(date: ZonedDateTime) = this shouldNot haveSameDay(date)
/**
* Matcher that compares days of ZonedDateTimes
*
* Verifies that two ZonedDateTimes have exactly the same day, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same day as 09/03/2018 11:30:30 -05:00 America/Chicago,
* and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2018, 3, 9, 11, 30, 30, 30, ZoneId.of("America/Chicago"))
*
* firstDate should haveSameDay(secondDate) // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNot haveSameDay(secondDate) // Assertion passes
* ```
*
* @see [ZonedDateTime.shouldHaveSameDayAs]
* @see [ZonedDateTime.shouldNotHaveSameDayAs]
*/
fun haveSameDay(date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> {
override fun test(value: ZonedDateTime): MatcherResult =
MatcherResult(value.dayOfMonth == date.dayOfMonth, "$value should have day ${date.dayOfMonth} but had ${value.dayOfMonth}", "$value should not have day ${date.dayOfMonth}")
}
/**
* Asserts that this day is the same as [date]'s day
*
* Verifies that this day is the same as [date]'s day, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 has the day year as 09/02/1998 11:30:30 -05:00,
* and this assertion should pass for this comparison
*
* Opposite of [OffsetDateTime.shouldNotHaveSameDayAs]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2018, 3, 9, 11, 30, 30, 30, ZoneOffset.ofHours(-5))
*
* firstDate shouldHaveSameDayAs secondDate // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldHaveSameDayAs secondDate // Assertion fails, 9 != 12
* ```
*/
infix fun OffsetDateTime.shouldHaveSameDayAs(date: OffsetDateTime) = this should haveSameDay(date)
/**
* Asserts that this day is NOT the same as [date]'s day
*
* Verifies that this day isn't the same as [date]'s day, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 doesn't have the same day as 10/02/1998 10:00:00 -03:00,
* and this assertion should pass for this comparison
*
* Opposite of [OffsetDateTime.shouldHaveSameDayAs]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 10, 19, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNotHaveSameDayAs secondDate // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2018, 3, 9, 1, 30, 30, 30, ZoneOffset.ofHours(-5))
*
* firstDate shouldNotHaveSameDayAs secondDate // Assertion fails, 9 == 9, and we expected a difference
* ```
*/
infix fun OffsetDateTime.shouldNotHaveSameDayAs(date: OffsetDateTime) = this shouldNot haveSameDay(date)
/**
* Matcher that compares days of OffsetDateTimes
*
* Verifies that two ZonedDateTimes have exactly the same day, ignoring any other fields.
* For example, 09/02/1998 10:00:00 -03:00 has the same day as 09/03/2018 11:30:30 -05:00,
* and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2018, 3, 9, 11, 30, 30, 30, ZoneOffset.ofHours(-5))
*
* firstDate should haveSameDay(secondDate) // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNot haveSameDay(secondDate) // Assertion passes
* ```
*
* @see [OffsetDateTime.shouldHaveSameDayAs]
* @see [OffsetDateTime.shouldNotHaveSameDayAs]
*/
fun haveSameDay(date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> {
override fun test(value: OffsetDateTime): MatcherResult =
MatcherResult(value.dayOfMonth == date.dayOfMonth, "$value should have day ${date.dayOfMonth} but had ${value.dayOfMonth}", "$value should not have day ${date.dayOfMonth}")
}
/**
* Asserts that this is before [date]
*
* Verifies that this is before [date], comparing year, month and day.
* For example, 09/02/1998 is before 10/02/1998, and this assertion should pass for this comparison.
*
* Opposite of [LocalDate.shouldNotBeBefore]
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate shouldBeBefore secondDate // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 10)
* val secondDate = LocalDate.of(1998, 2, 9)
*
* firstDate shouldBeBefore secondDate // Assertion fails, 10/02/1998 is not before 09/02/1998 as expected.
* ```
*
* @see LocalDate.shouldNotBeAfter
*/
infix fun LocalDate.shouldBeBefore(date: LocalDate) = this should before(date)
/**
* Asserts that this is NOT before [date]
*
* Verifies that this is not before [date], comparing year, month and day.
* For example, 10/02/1998 is not before 09/02/1998, and this assertion should pass for this comparison.
*
* Opposite of [LocalDate.shouldBeBefore]
*
* ```
* val firstDate = LocalDate.of(1998, 2, 10)
* val secondDate = LocalDate.of(1998, 2, 9)
*
* firstDate shouldNotBeBefore secondDate // Assertion passes
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate shouldNotBeBefore secondDate // Assertion fails, 09/02/1998 is before 10/02/1998, and we expected the opposite.
* ```
*
* @see LocalDate.shouldBeAfter
*/
infix fun LocalDate.shouldNotBeBefore(date: LocalDate) = this shouldNot before(date)
/**
* Matcher that compares two LocalDates and checks whether one is before the other
*
* Verifies that two LocalDates occurs in a certain order, checking that one happened before the other.
* For example, 09/02/1998 is before 10/02/1998, and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate shouldBe before(secondDate) // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 10)
* val secondDate = LocalDate.of(1998, 2, 9)
*
* firstDate shouldNotBe before(secondDate) // Assertion passes
* ```
*
* @see LocalDate.shouldBeBefore
* @see LocalDate.shouldNotBeBefore
*/
fun before(date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> {
override fun test(value: LocalDate): MatcherResult =
MatcherResult(value.isBefore(date), "$value should be before $date", "$value should not be before $date")
}
/**
* Asserts that this is before [date]
*
* Verifies that this is before [date], comparing every field in the LocalDateTime.
* For example, 09/02/1998 00:00:00 is before 09/02/1998 00:00:01, and this assertion should pass for this comparison.
*
* Opposite of [LocalDateTime.shouldNotBeBefore]
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1)
*
* firstDate shouldBeBefore secondDate // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1)
* val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0)
*
* firstDate shouldBeBefore secondDate // Assertion fails, firstDate is one second after secondDate
* ```
*
* @see LocalDateTime.shouldNotBeAfter
*/
infix fun LocalDateTime.shouldBeBefore(date: LocalDateTime) = this should before(date)
/**
* Asserts that this is NOT before [date]
*
* Verifies that this is not before [date], comparing every field in the LocalDateTime.
* For example, 09/02/1998 00:00:01 is not before 09/02/1998 00:00:00, and this assertion should pass for this comparison.
*
* Opposite of [LocalDateTime.shouldBeBefore]
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1)
* val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0)
*
* firstDate shouldNotBeBefore secondDate // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1)
*
* firstDate shouldNotBeBefore secondDate // Assertion fails, firstDate is one second before secondDate and we didn't expect it
* ```
*
* @see LocalDateTime.shouldBeAfter
*/
infix fun LocalDateTime.shouldNotBeBefore(date: LocalDateTime) = this shouldNot before(date)
/**
* Matcher that compares two LocalDateTimes and checks whether one is before the other
*
* Verifies that two LocalDateTimes occurs in a certain order, checking that one happened before the other.
* For example, 09/02/1998 00:00:00 is before 09/02/1998 00:00:01, and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1)
*
* firstDate shouldBe before(secondDate) // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1)
* val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0)
*
* firstDate shouldNotBe before(secondDate) // Assertion passes
* ```
*
* @see LocalDateTime.shouldBeBefore
* @see LocalDateTime.shouldNotBeBefore
*/
fun before(date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> {
override fun test(value: LocalDateTime): MatcherResult =
MatcherResult(value.isBefore(date), "$value should be before $date", "$value should not be before $date")
}
/**
* Asserts that this is before [date]
*
* Verifies that this is before [date], comparing every field in the ZonedDateTime.
* For example, 09/02/1998 00:00:00 -03:00 America/Sao_Paulo is before 09/02/1998 00:00:01 -03:00 America/Sao_Paulo,
* and this assertion should pass for this comparison.
*
* Opposite of [ZonedDateTime.shouldNotBeBefore]
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldBeBefore secondDate // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldBeBefore secondDate // Assertion fails, firstDate is one second after secondDate
* ```
*
* @see ZonedDateTime.shouldNotBeAfter
*/
infix fun ZonedDateTime.shouldBeBefore(date: ZonedDateTime) = this should before(date)
/**
* Asserts that this is NOT before [date]
*
* Verifies that this is not before [date], comparing every field in the ZonedDateTime.
* For example, 09/02/1998 00:00:01 -03:00 America/Sao_Paulo is not before 09/02/1998 00:00:00 -03:00 America/Sao_Paulo,
* and this assertion should pass for this comparison.
*
* Opposite of [ZonedDateTime.shouldBeBefore]
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNotBeBefore secondDate // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNotBeBefore secondDate // Assertion fails, firstDate is one second before secondDate and we didn't expect it
* ```
*
* @see ZonedDateTime.shouldBeAfter
*/
infix fun ZonedDateTime.shouldNotBeBefore(date: ZonedDateTime) = this shouldNot before(date)
/**
* Matcher that compares two ZonedDateTimes and checks whether one is before the other
*
* Verifies that two ZonedDateTimes occurs in a certain order, checking that one happened before the other.
* For example, 09/02/1998 00:00:00 -03:00 America/Sao_Paulo is before 09/02/1998 00:00:01 -03:00 America/Sao_Paulo,
* and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldBe before(secondDate) // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNotBe before(secondDate) // Assertion passes
* ```
*
* @see ZonedDateTime.shouldBeBefore
* @see ZonedDateTime.shouldNotBeBefore
*/
fun before(date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> {
override fun test(value: ZonedDateTime): MatcherResult =
MatcherResult(value.isBefore(date), "$value should be before $date", "$value should not be before $date")
}
/**
* Asserts that this is before [date]
*
* Verifies that this is before [date], comparing every field in the OffsetDateTime.
* For example, 09/02/1998 00:00:00 -03:00 is before 09/02/1998 00:00:01 -03:00,
* and this assertion should pass for this comparison.
*
* Opposite of [OffsetDateTime.shouldNotBeBefore]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldBeBefore secondDate // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldBeBefore secondDate // Assertion fails, firstDate is one second after secondDate
* ```
*
* @see OffsetDateTime.shouldNotBeAfter
*/
infix fun OffsetDateTime.shouldBeBefore(date: OffsetDateTime) = this should before(date)
/**
* Asserts that this is NOT before [date]
*
* Verifies that this is not before [date], comparing every field in the OffsetDateTime.
* For example, 09/02/1998 00:00:01 -03:00 is not before 09/02/1998 00:00:00 -03:00,
* and this assertion should pass for this comparison.
*
* Opposite of [OffsetDateTime.shouldBeBefore]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNotBeBefore secondDate // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNotBeBefore secondDate // Assertion fails, firstDate is one second before secondDate and we didn't expect it
* ```
*
* @see OffsetDateTime.shouldBeAfter
*/
infix fun OffsetDateTime.shouldNotBeBefore(date: OffsetDateTime) = this shouldNot before(date)
/**
* Matcher that compares two OffsetDateTimes and checks whether one is before the other
*
* Verifies that two OffsetDateTimes occurs in a certain order, checking that one happened before the other.
* For example, 09/02/1998 00:00:00 -03:00 is before 09/02/1998 00:00:01 -03:00,
* and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldBe before(secondDate) // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNotBe before(secondDate) // Assertion passes
* ```
*
* @see OffsetDateTime.shouldBeBefore
* @see OffsetDateTime.shouldNotBeBefore
*/
fun before(date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> {
override fun test(value: OffsetDateTime): MatcherResult =
MatcherResult(value.isBefore(date), "$value should be before $date", "$value should not be before $date")
}
/**
* Asserts that this is after [date]
*
* Verifies that this is after [date], comparing year, month and day.
* For example, 09/02/1998 is after 08/02/1998, and this assertion should pass for this comparison.
*
* Opposite of [LocalDate.shouldNotBeAfter]
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 8)
*
* firstDate shouldBeAfter secondDate // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate shouldBeAfter secondDate // Assertion fails, firstDate is NOT after secondDate
* ```
*
* @see LocalDate.shouldNotBeBefore
*/
infix fun LocalDate.shouldBeAfter(date: LocalDate) = this should after(date)
/**
* Asserts that this is NOT after [date]
*
* Verifies that this is not after [date], comparing year, month and day.
* For example, 09/02/1998 is not after 10/02/1998, and this assertion should pass for this comparison.
*
* Opposite of [LocalDate.shouldBeAfter]
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate shouldNotBeAfter secondDate // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 10)
* val secondDate = LocalDate.of(1998, 2, 9)
*
* firstDate shouldNotBeAfter secondDate // Assertion fails, first date IS after secondDate
* ```
*
* @see LocalDate.shouldBeBefore
*/
infix fun LocalDate.shouldNotBeAfter(date: LocalDate) = this shouldNot after(date)
/**
* Matcher that compares two LocalDates and checks whether one is after the other
*
* Verifies that two LocalDates occurs in a certain order, checking that one happened after the other.
* For example, 10/02/1998 is after 09/02/1998, and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 8)
*
* firstDate shouldBe after(secondDate ) // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate shouldNotBe after(secondDate) // Assertion passes
* ```
*
* @see LocalDate.shouldBeAfter
* @see LocalDate.shouldNotBeAfter
*/
fun after(date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> {
override fun test(value: LocalDate): MatcherResult =
MatcherResult(value.isAfter(date), "$value should be after $date", "$value should not be after $date")
}
/**
* Asserts that this is after [date]
*
* Verifies that this is after [date], comparing all fields in LocalDateTime.
* For example, 09/02/1998 10:00:00 is after 09/02/1998 09:00:00, and this assertion should pass for this comparison.
*
* Opposite of [LocalDateTime.shouldNotBeAfter]
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 8, 10, 0, 0)
*
* firstDate shouldBeAfter secondDate // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0)
*
* firstDate shouldBeAfter secondDate // Assertion fails, firstDate is NOT after secondDate
* ```
*
* @see LocalDateTime.shouldNotBeBefore
*/
infix fun LocalDateTime.shouldBeAfter(date: LocalDateTime) = this should after(date)
/**
* Asserts that this is NOT after [date]
*
* Verifies that this is not after [date], comparing all fields in LocalDateTime.
* For example, 09/02/1998 09:00:00 is not after 09/02/1998 10:00:00, and this assertion should pass for this comparison.
*
* Opposite of [LocalDateTime.shouldBeAfter]
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0)
*
* firstDate shouldNotBeAfter secondDate // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
*
* firstDate shouldNotBeAfter secondDate // Assertion fails, first date IS after secondDate
* ```
*
* @see LocalDateTime.shouldBeBefore
*/
infix fun LocalDateTime.shouldNotBeAfter(date: LocalDateTime) = this shouldNot after(date)
/**
* Matcher that compares two LocalDateTimes and checks whether one is after the other
*
* Verifies that two LocalDateTimes occurs in a certain order, checking that one happened after the other.
* For example, 09/02/1998 10:00:00 is after 09/02/1998 09:00:00, and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 8, 10, 0, 0)
*
* firstDate shouldBe after(secondDate ) // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0)
*
* firstDate shouldNotBe after(secondDate) // Assertion passes
* ```
*
* @see LocalDateTime.shouldBeAfter
* @see LocalDateTime.shouldNotBeAfter
*/
fun after(date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> {
override fun test(value: LocalDateTime): MatcherResult =
MatcherResult(value.isAfter(date), "$value should be after $date", "$value should not be after $date")
}
/**
* Asserts that this is after [date]
*
* Verifies that this is after [date], comparing all fields in ZonedDateTime.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo is after 09/02/1998 09:00:00 -03:00 America/Sao_Paulo,
* and this assertion should pass for this comparison.
*
* Opposite of [ZonedDateTime.shouldNotBeAfter]
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 8, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldBeAfter secondDate // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldBeAfter secondDate // Assertion fails, firstDate is NOT after secondDate
* ```
*
* @see ZonedDateTime.shouldNotBeBefore
*/
infix fun ZonedDateTime.shouldBeAfter(date: ZonedDateTime) = this should after(date)
/**
* Asserts that this is NOT after [date]
*
* Verifies that this is not after [date], comparing all fields in ZonedDateTime.
* For example, 09/02/1998 09:00:00 -03:00 America/Sao_Paulo is not after 09/02/1998 10:00:00 -03:00 America/Sao_Paulo,
* and this assertion should pass for this comparison.
*
* Opposite of [ZonedDateTime.shouldBeAfter]
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNotBeAfter secondDate // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNotBeAfter secondDate // Assertion fails, first date IS after secondDate
* ```
*
* @see ZonedDateTime.shouldBeBefore
*/
infix fun ZonedDateTime.shouldNotBeAfter(date: ZonedDateTime) = this shouldNot after(date)
/**
* Matcher that compares two ZonedDateTimes and checks whether one is after the other
*
* Verifies that two ZonedDateTimes occurs in a certain order, checking that one happened after the other.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo is after 09/02/1998 09:00:00 -03:00 America/Sao_Paulo,
* and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 8, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldBe after(secondDate ) // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* firstDate shouldNotBe after(secondDate) // Assertion passes
* ```
*
* @see ZonedDateTime.shouldBeAfter
* @see ZonedDateTime.shouldNotBeAfter
*/
fun after(date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> {
override fun test(value: ZonedDateTime): MatcherResult =
MatcherResult(value.isAfter(date), "$value should be after $date", "$value should not be after $date")
}
/**
* Asserts that this is after [date]
*
* Verifies that this is after [date], comparing all fields in OffsetDateTime.
* For example, 09/02/1998 10:00:00 -03:00 is after 09/02/1998 09:00:00 -03:00,
* and this assertion should pass for this comparison.
*
* Opposite of [OffsetDateTime.shouldNotBeAfter]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 8, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldBeAfter secondDate // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldBeAfter secondDate // Assertion fails, firstDate is NOT after secondDate
* ```
*
* @see OffsetDateTime.shouldNotBeBefore
*/
infix fun OffsetDateTime.shouldBeAfter(date: OffsetDateTime) = this should after(date)
/**
* Asserts that this is NOT after [date]
*
* Verifies that this is not after [date], comparing all fields in OffsetDateTime.
* For example, 09/02/1998 09:00:00 -03:00 is not after 09/02/1998 10:00:00 -03:00,
* and this assertion should pass for this comparison.
*
* Opposite of [OffsetDateTime.shouldBeAfter]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNotBeAfter secondDate // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNotBeAfter secondDate // Assertion fails, first date IS after secondDate
* ```
*
* @see OffsetDateTime.shouldBeBefore
*/
infix fun OffsetDateTime.shouldNotBeAfter(date: OffsetDateTime) = this shouldNot after(date)
/**
* Matcher that compares two OffsetDateTimes and checks whether one is after the other
*
* Verifies that two OffsetDateTimes occurs in a certain order, checking that one happened after the other.
* For example, 09/02/1998 10:00:00 -03:00 is after 09/02/1998 09:00:00 -03:00,
* and the matcher will have a positive result for this comparison
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 8, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldBe after(secondDate ) // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldNotBe after(secondDate) // Assertion passes
* ```
*
* @see OffsetDateTime.shouldBeAfter
* @see OffsetDateTime.shouldNotBeAfter
*/
fun after(date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> {
override fun test(value: OffsetDateTime): MatcherResult =
MatcherResult(value.isAfter(date), "$value should be after $date", "$value should not be after $date")
}
/**
* Asserts that this is within [period] of [date]
*
* Verifies that this is within [period] of [date].
* For example, 09/02/1998 is within 3 days of 10/02/1998, and this assertion should pass for this comparison.
*
* Opposite of [LocalDate.shouldNotBeWithin]
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 25)
*
* firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is not within 3 days of secondDate
* ```
*/
fun LocalDate.shouldBeWithin(period: Period, date: LocalDate) = this should within(period, date)
/**
* Asserts that this is NOT within [period] of [date]
*
* Verifies that this is not within [period] of [date].
* For example, 09/02/1998 is not within 3 days of 25/02/1998, and this assertion should pass for this comparison.
*
* Opposite of [LocalDate.shouldBeWithin]
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 25)
*
* firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is within 3 days of secondDate, and we expected not to
* ```
*/
fun LocalDate.shouldNotBeWithin(period: Period, date: LocalDate) = this shouldNot within(period, date)
/**
* Matcher that compares two LocalDates and checks whether one is within [period] of the other
*
* Verifies that two LocalDates are within a certain period.
* For example, 09/02/1998 is within 3 days of 10/02/1998, and the matcher will have a positive result for this comparison.
*
*
* ```
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 10)
*
* firstDate shouldBe within(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = LocalDate.of(1998, 2, 9)
* val secondDate = LocalDate.of(1998, 2, 25)
* firstDate shouldNotBe within(Period.ofDays(3), secondDate) // Assertion passes
* ```
*
* @see [LocalDate.shouldBeWithin]
* @see [LocalDate.shouldNotBeWithin]
*/
fun within(period: Period, date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> {
override fun test(value: LocalDate): MatcherResult {
val start = date.minus(period)
val end = date.plus(period)
val passed = start == value || end == value || start.isBefore(value) && end.isAfter(value)
return MatcherResult(passed, "$value should be within $period of $date", "$value should not be within $period of $date")
}
}
/**
* Asserts that this is within [temporalAmount] of [date]
*
* Verifies that this is within [temporalAmount] of [date].
* For example, 09/02/1998 10:00:00 is within 3 days of 10/02/1998 10:00:00, and this assertion should pass for this comparison.
*
* Opposite of [LocalDateTime.shouldNotBeWithin]
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0)
*
* firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 25, 10, 0, 0)
*
* firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is not within 3 days of secondDate
* ```
*/
fun LocalDateTime.shouldBeWithin(temporalAmount: TemporalAmount, date: LocalDateTime) = this should within(temporalAmount, date)
/**
* Asserts that this is NOT within [temporalAmount] of [date]
*
* Verifies that this is not within [temporalAmount] of [date].
* For example, 09/02/1998 10:00:00 is not within 3 days of 25/02/1998 10:00:00, and this assertion should pass for this comparison.
*
* Opposite of [LocalDateTime.shouldBeWithin]
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 25, 10, 0, 0)
*
* firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0)
*
* firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is within 3 days of secondDate, and we expected not to
* ```
*/
fun LocalDateTime.shouldNotBeWithin(temporalAmount: TemporalAmount, date: LocalDateTime) = this shouldNot within(temporalAmount, date)
/**
* Matcher that compares two LocalDateTimes and checks whether one is within [temporalAmount] of the other
*
* Verifies that two LocalDateTimes are within a certain period.
* For example, 09/02/1998 10:00:00 is within 3 days of 10/02/1998 10:00:00,
* and the matcher will have a positive result for this comparison.
*
*
* ```
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0)
*
* firstDate shouldBe within(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0)
* val secondDate = LocalDateTime.of(1998, 2, 25, 10, 0, 0)
* firstDate shouldNotBe within(Period.ofDays(3), secondDate) // Assertion passes
* ```
*
* @see [LocalDateTime.shouldBeWithin]
* @see [LocalDateTime.shouldNotBeWithin]
*/
fun within(temporalAmount: TemporalAmount, date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> {
override fun test(value: LocalDateTime): MatcherResult {
val start = date.minus(temporalAmount)
val end = date.plus(temporalAmount)
val passed = start == value || end == value || start.isBefore(value) && end.isAfter(value)
return MatcherResult(passed, "$value should be within $temporalAmount of $date", "$value should not be within $temporalAmount of $date")
}
}
/**
* Asserts that this is within [temporalAmount] of [date]
*
* Verifies that this is within [temporalAmount] of [date].
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo is within 3 days of 10/02/1998 10:00:00 -03:00 America/Sao_Paulo,
* and this assertion should pass for this comparison.
*
* Opposite of [ZonedDateTime.shouldNotBeWithin]
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
* val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
*
* firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
* val secondDate = ZonedDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
*
* firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is not within 3 days of secondDate
* ```
*/
fun ZonedDateTime.shouldBeWithin(temporalAmount: TemporalAmount, date: ZonedDateTime) = this should within(temporalAmount, date)
/**
* Asserts that this is NOT within [temporalAmount] of [date]
*
* Verifies that this is not within [temporalAmount] of [date].
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo is not within 3 days of 25/02/1998 10:00:00 -03:00 America/Sao_Paulo,
* and this assertion should pass for this comparison.
*
* Opposite of [ZonedDateTime.shouldBeWithin]
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
* val secondDate = ZonedDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
*
* firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
* val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
*
* firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is within 3 days of secondDate, and we expected not to
* ```
*/
fun ZonedDateTime.shouldNotBeWithin(temporalAmount: TemporalAmount, date: ZonedDateTime) = this shouldNot within(temporalAmount, date)
/**
* Matcher that compares two ZonedDateTimes and checks whether one is within [temporalAmount] of the other
*
* Verifies that two ZonedDateTimes are within a certain period.
* For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo is within 3 days of 10/02/1998 10:00:00 -03:00 America/Sao_Paulo,
* and the matcher will have a positive result for this comparison.
*
*
* ```
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
* val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
*
* firstDate shouldBe within(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
* val secondDate = ZonedDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo))
* firstDate shouldNotBe within(Period.ofDays(3), secondDate) // Assertion passes
* ```
*
* @see [ZonedDateTime.shouldBeWithin]
* @see [ZonedDateTime.shouldNotBeWithin]
*/
fun within(temporalAmount: TemporalAmount, date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> {
override fun test(value: ZonedDateTime): MatcherResult {
val start = date.minus(temporalAmount)
val end = date.plus(temporalAmount)
val passed = start == value || end == value || start.isBefore(value) && end.isAfter(value)
return MatcherResult(passed, "$value should be within $temporalAmount of $date", "$value should not be within $temporalAmount of $date")
}
}
/**
* Asserts that this is within [temporalAmount] of [date]
*
* Verifies that this is within [temporalAmount] of [date].
* For example, 09/02/1998 10:00:00 -03:00 is within 3 days of 10/02/1998 10:00:00 -03:00,
* and this assertion should pass for this comparison.
*
* Opposite of [OffsetDateTime.shouldNotBeWithin]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)
* val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is not within 3 days of secondDate
* ```
*/
fun OffsetDateTime.shouldBeWithin(temporalAmount: TemporalAmount, date: OffsetDateTime) = this should within(temporalAmount, date)
/**
* Asserts that this is NOT within [temporalAmount] of [date]
*
* Verifies that this is not within [temporalAmount] of [date].
* For example, 09/02/1998 10:00:00 -03:00 is not within 3 days of 25/02/1998 10:00:00 -03:00,
* and this assertion should pass for this comparison.
*
* Opposite of [OffsetDateTime.shouldBeWithin]
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is within 3 days of secondDate, and we expected not to
* ```
*/
fun OffsetDateTime.shouldNotBeWithin(temporalAmount: TemporalAmount, date: OffsetDateTime) = this shouldNot within(temporalAmount, date)
/**
* Matcher that compares two OffsetDateTimes and checks whether one is within [temporalAmount] of the other
*
* Verifies that two OffsetDateTimes are within a certain period.
* For example, 09/02/1998 10:00:00 -03:00 is within 3 days of 10/02/1998 10:00:00 -03:00,
* and the matcher will have a positive result for this comparison.
*
*
* ```
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* firstDate shouldBe within(Period.ofDays(3), secondDate) // Assertion passes
*
*
* val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneOffset.ofHours(-3))
* firstDate shouldNotBe within(Period.ofDays(3), secondDate) // Assertion passes
* ```
*
* @see [OffsetDateTime.shouldBeWithin]
* @see [OffsetDateTime.shouldNotBeWithin]
*/
fun within(temporalAmount: TemporalAmount, date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> {
override fun test(value: OffsetDateTime): MatcherResult {
val start = date.minus(temporalAmount)
val end = date.plus(temporalAmount)
val passed = start == value || end == value || start.isBefore(value) && end.isAfter(value)
return MatcherResult(passed, "$value should be within $temporalAmount of $date", "$value should not be within $temporalAmount of $date")
}
}
/**
* Asserts that this is between [a] and [b]
*
* Verifies that this is after [a] and before [b], comparing year, month and day.
*
* Opposite of [LocalDate.shouldNotBeBetween]
*
* ```
* val date = LocalDate.of(2019, 2, 16)
* val firstDate = LocalDate.of(2019, 2, 15)
* val secondDate = LocalDate.of(2019, 2, 17)
*
* date.shouldBeBetween(firstDate, secondDate) // Assertion passes
*
*
* val date = LocalDate.of(2019, 2, 15)
* val firstDate = LocalDate.of(2019, 2, 16)
* val secondDate = LocalDate.of(2019, 2, 17)
*
* date.shouldBeBetween(firstDate, secondDate) // Assertion fails, date is NOT between firstDate and secondDate
* ```
*
* @see LocalDate.shouldNotBeBetween
*/
fun LocalDate.shouldBeBetween(a: LocalDate, b: LocalDate) = this shouldBe between(a, b)
/**
* Asserts that this is NOT between [a] and [b]
*
* Verifies that this is not after [a] and before [b], comparing year, month and day.
*
* Opposite of [LocalDate.shouldBeBetween]
*
* ```
* val date = LocalDate.of(2019, 2, 15)
* val firstDate = LocalDate.of(2019, 2, 16)
* val secondDate = LocalDate.of(2019, 2, 17)
*
* date.shouldNotBeBetween(firstDate, secondDate) // Assertion passes
*
*
* val date = LocalDate.of(2019, 2, 16)
* val firstDate = LocalDate.of(2019, 2, 15)
* val secondDate = LocalDate.of(2019, 2, 17)
*
* date.shouldNotBeBetween(firstDate, secondDate) // Assertion fails, date IS between firstDate and secondDate
* ```
*
* @see LocalDate.shouldBeBetween
*/
fun LocalDate.shouldNotBeBetween(a: LocalDate, b: LocalDate) = this shouldNotBe between(a, b)
/**
* Matcher that checks if LocalDate is between two other LocalDates
*
* Verifies that LocalDate is after the first LocalDate and before the second LocalDate
* For example, 20/03/2019 is between 19/03/2019 and 21/03/2019, and the matcher will have a positive result for this comparison
*
* ```
* val date = LocalDate.of(2019, 2, 16)
* val firstDate = LocalDate.of(2019, 2, 15)
* val secondDate = LocalDate.of(2019, 2, 17)
*
* date shouldBe after(firstDate, secondDate) // Assertion passes
*
*
* val date = LocalDate.of(2019, 2, 15)
* val firstDate = LocalDate.of(2019, 2, 16)
* val secondDate = LocalDate.of(2019, 2, 17)
*
* date shouldNotBe between(firstDate, secondDate) // Assertion passes
* ```
*
* @see LocalDate.shouldBeBetween
* @see LocalDate.shouldNotBeBetween
*/
fun between(a: LocalDate, b: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> {
override fun test(value: LocalDate): MatcherResult {
val passed = value.isAfter(a) && value.isBefore(b)
return MatcherResult(passed, "$value should be after $a and before $b", "$value should not be be after $a and before $b")
}
}
/**
* Asserts that this is between [a] and [b]
*
* Verifies that this is after [a] and before [b], comparing all fields in LocalDateTime.
*
* Opposite of [LocalDateTime.shouldNotBeBetween]
*
* ```
* val date = LocalDateTime.of(2019, 2, 16, 12, 0, 0)
* val firstDate = LocalDateTime.of(2019, 2, 15, 12, 0, 0)
* val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0)
*
* date.shouldBeBetween(firstDate, secondDate) // Assertion passes
*
*
* val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0)
* val firstDate = LocalDateTime.of(2019, 2, 16, 12, 0, 0)
* val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0)
*
* date.shouldBeBetween(firstDate, secondDate) // Assertion fails, date is NOT between firstDate and secondDate
* ```
*
* @see LocalDateTime.shouldNotBeBetween
*/
fun LocalDateTime.shouldBeBetween(a: LocalDateTime, b: LocalDateTime) = this shouldBe between(a, b)
/**
* Asserts that this is NOT between [a] and [b]
*
* Verifies that this is not after [a] and before [b], comparing all fields in LocalDateTime.
*
* Opposite of [LocalDateTime.shouldBeBetween]
*
* ```
* val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0)
* val firstDate = LocalDateTime.of(2019, 2, 16, 12, 0, 0)
* val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0)
*
* date.shouldNotBeBetween(firstDate, secondDate) // Assertion passes
*
*
* val date = LocalDateTime.of(2019, 2, 16, 12, 0, 0)
* val firstDate = LocalDateTime.of(2019, 2, 15, 12, 0, 0)
* val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0)
*
* date.shouldNotBeBetween(firstDate, secondDate) // Assertion fails, date IS between firstDate and secondDate
* ```
*
* @see LocalDateTime.shouldBeBetween
*/
fun LocalDateTime.shouldNotBeBetween(a: LocalDateTime, b: LocalDateTime) = this shouldNotBe between(a, b)
/**
* Matcher that checks if LocalDateTime is between two other LocalDateTimes
*
* Verifies that LocalDateTime is after the first LocalDateTime and before the second LocalDateTime
* For example, 20/03/2019 10:00:00 is between 19/03/2019 10:00:00 and 21/03/2019 10:00:00, and the matcher will have a positive result for this comparison
*
* ```
* val date = LocalDateTime.of(2019, 2, 16, 12, 0, 0)
* val firstDate = LocalDateTime.of(2019, 2, 15, 12, 0, 0)
* val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0)
*
* date shouldBe after(firstDate, secondDate) // Assertion passes
*
*
* val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0)
* val firstDate = LocalDateTime.of(2019, 2, 16, 12, 0, 0)
* val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0)
*
* date shouldNotBe between(firstDate, secondDate) // Assertion passes
* ```
*
* @see LocalDateTime.shouldBeBetween
* @see LocalDateTime.shouldNotBeBetween
*/
fun between(a: LocalDateTime, b: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> {
override fun test(value: LocalDateTime): MatcherResult {
val passed = value.isAfter(a) && value.isBefore(b)
return MatcherResult(passed, "$value should be after $a and before $b", "$value should not be be after $a and before $b")
}
}
/**
* Asserts that this is between [a] and [b]
*
* Verifies that this is after [a] and before [b], comparing all fields in ZonedDateTime.
*
* Opposite of [ZonedDateTime.shouldNotBeBetween]
*
* ```
* val date = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val firstDate = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* date.shouldBeBetween(firstDate, secondDate) // Assertion passes
*
*
* val date = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val firstDate = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* date.shouldBeBetween(firstDate, secondDate) // Assertion fails, date is NOT between firstDate and secondDate
* ```
*
* @see ZonedDateTime.shouldNotBeBetween
*/
fun ZonedDateTime.shouldBeBetween(a: ZonedDateTime, b: ZonedDateTime) = this shouldBe between(a, b)
/**
* Asserts that this is NOT between [a] and [b]
*
* Verifies that this is not after [a] and before [b], comparing all fields in ZonedDateTime.
*
* Opposite of [ZonedDateTime.shouldBeBetween]
*
* ```
* val date = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val firstDate = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* date.shouldNotBeBetween(firstDate, secondDate) // Assertion passes
*
*
* val date = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val firstDate = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* date.shouldNotBeBetween(firstDate, secondDate) // Assertion fails, date IS between firstDate and secondDate
* ```
*
* @see ZonedDateTime.shouldBeBetween
*/
fun ZonedDateTime.shouldNotBeBetween(a: ZonedDateTime, b: ZonedDateTime) = this shouldNotBe between(a, b)
/**
* Matcher that checks if ZonedDateTime is between two other ZonedDateTimes
*
* Verifies that ZonedDateTime is after the first ZonedDateTime and before the second ZonedDateTime
* For example, 20/03/2019 10:00:00 -03:00 America/Sao_Paulo is between 19/03/2019 10:00:00 -03:00 America/Sao_Paulo
* and 21/03/2019 10:00:00 -03:00 America/Sao_Paulo, and the matcher will have a positive result for this comparison
*
* ```
* val date = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val firstDate = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* date shouldBe after(firstDate, secondDate) // Assertion passes
*
*
* val date = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val firstDate = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
* val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo"))
*
* date shouldNotBe between(firstDate, secondDate) // Assertion passes
* ```
*
* @see ZonedDateTime.shouldBeBetween
* @see ZonedDateTime.shouldNotBeBetween
*/
fun between(a: ZonedDateTime, b: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> {
override fun test(value: ZonedDateTime): MatcherResult {
val passed = value.isAfter(a) && value.isBefore(b)
return MatcherResult(passed, "$value should be after $a and before $b", "$value should not be be after $a and before $b")
}
}
/**
* Asserts that this is between [a] and [b]
*
* Verifies that this is after [a] and before [b], comparing all fields in ZonedDateTime.
*
* Opposite of [OffsetDateTime.shouldNotBeBetween]
*
* ```
* val date = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val firstDate = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date.shouldBeBetween(firstDate, secondDate) // Assertion passes
*
*
* val date = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val firstDate = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date.shouldBeBetween(firstDate, secondDate) // Assertion fails, date is NOT between firstDate and secondDate
* ```
*
* @see OffsetDateTime.shouldNotBeBetween
*/
fun OffsetDateTime.shouldBeBetween(a: OffsetDateTime, b: OffsetDateTime) = this shouldBe between(a, b)
/**
* Asserts that this is NOT between [a] and [b]
*
* Verifies that this is not after [a] and before [b], comparing all fields in ZonedDateTime.
*
* Opposite of [OffsetDateTime.shouldBeBetween]
*
* ```
* val date = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val firstDate = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date.shouldNotBeBetween(firstDate, secondDate) // Assertion passes
*
*
* val date = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val firstDate = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date.shouldNotBeBetween(firstDate, secondDate) // Assertion fails, date IS between firstDate and secondDate
* ```
*
* @see OffsetDateTime.shouldBeBetween
*/
fun OffsetDateTime.shouldNotBeBetween(a: OffsetDateTime, b: OffsetDateTime) = this shouldNotBe between(a, b)
/**
* Matcher that checks if OffsetDateTime is between two other OffsetDateTimes
*
* Verifies that OffsetDateTime is after the first OffsetDateTime and before the second OffsetDateTime
* For example, 20/03/2019 10:00:00 -03:00 is between 19/03/2019 10:00:00 -03:00 and 21/03/2019 10:00:00 -03:00,
* and the matcher will have a positive result for this comparison
*
* ```
* val date = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val firstDate = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date shouldBe after(firstDate, secondDate) // Assertion passes
*
*
* val date = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val firstDate = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
* val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date shouldNotBe between(firstDate, secondDate) // Assertion passes
* ```
*
* @see OffsetDateTime.shouldBeBetween
* @see OffsetDateTime.shouldNotBeBetween
*/
fun between(a: OffsetDateTime, b: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> {
override fun test(value: OffsetDateTime): MatcherResult {
val passed = value.isAfter(a) && value.isBefore(b)
return MatcherResult(passed, "$value should be after $a and before $b", "$value should not be be after $a and before $b")
}
}
/**
* Asserts that the day of month inputted is equaled the date day
*
* ```
* val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0, 0)
*
* date.shouldHaveDayOfMonth(15) // Assertion passes
* ```
*/
infix fun LocalDateTime.shouldHaveDayOfMonth(day: Int) = this.dayOfMonth shouldBe day
/**
* Asserts that the day of year inputted is equaled the date day
*
* ```
* val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0, 0)
*
* date.shouldHaveDayOfYear(46) // Assertion passes
* ```
*/
infix fun LocalDateTime.shouldHaveDayOfYear(day: Int) = this.dayOfYear shouldBe day
/**
* Asserts that the day of year inputted is equaled the date day
*
* ```
* val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0, 0)
*
* date.shouldHaveDayOfWeek(FRIDAY) // Assertion passes
* date.shouldHaveDayOfWeek(5) // Assertion passes
* ```
*/
infix fun LocalDateTime.shouldHaveDayOfWeek(day: Int) = this.dayOfWeek.value shouldBe day
infix fun LocalDateTime.shouldHaveDayOfWeek(day: DayOfWeek) = this.dayOfWeek shouldBe day
/**
* Asserts that the month inputted is equaled the date month
*
* ```
* val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0, 0)
*
* date.shouldHaveMonth(2) // Assertion passes
* date.shouldHaveMonth(FEBRUARY) // Assertion passes
* ```
*/
infix fun LocalDateTime.shouldHaveMonth(month: Int) = this.month.value shouldBe month
infix fun LocalDateTime.shouldHaveMonth(month: Month) = this.month shouldBe month
/**
* Asserts that the hour inputted is equaled the date time hour
*
* ```
* val date = LocalDateTime.of(2019, 2, 15, 12, 10, 0, 0)
*
* date.shouldHaveHour(12) // Assertion passes
* ```
*/
infix fun LocalDateTime.shouldHaveHour(hour: Int) = this.hour shouldBe hour
/**
* Asserts that the minute inputted is equaled the date time minute
*
* ```
* val date = LocalDateTime.of(2019, 2, 15, 12, 10, 0, 0)
*
* date.shouldHaveMinute(10) // Assertion passes
* ```
*/
infix fun LocalDateTime.shouldHaveMinute(minute: Int) = this.minute shouldBe minute
/**
* Asserts that the second inputted is equaled the date time second
*
* ```
* val date = LocalDateTime.of(2019, 2, 15, 12, 10, 11, 0)
*
* date.shouldHaveSecond(11) // Assertion passes
* ```
*/
infix fun LocalDateTime.shouldHaveSecond(second: Int) = this.second shouldBe second
/**
* Asserts that the nano inputted is equaled the date time nano
*
* ```
* val date = LocalDateTime.of(2019, 2, 15, 12, 10, 0, 12)
*
* date.shouldHaveNano(10) // Assertion passes
* ```
*/
infix fun LocalDateTime.shouldHaveNano(nano: Int) = this.nano shouldBe nano
/**
* Asserts that this is equal to [other] using the [ChronoZonedDateTime.isEqual]
*
* Opposite of [ZonedDateTime.shouldNotHaveSameInstantAs]
*
* ```
* val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1))
* val other = ZonedDateTime.of(2019, 2, 16, 9, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date.shouldHaveSameInstantAs(other) // Assertion passes
*
*
* val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1))
* val other = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date.shouldHaveSameInstantAs(other) // Assertion fails, date is NOT equal to the other date
* ```
*
* @see ZonedDateTime.shouldNotHaveSameInstant
*/
infix fun ZonedDateTime.shouldHaveSameInstantAs(other: ZonedDateTime) = this should haveSameInstantAs(other)
/**
* Asserts that this is NOT equal to [other] using the [ChronoZonedDateTime.isEqual]
*
* Opposite of [ZonedDateTime.shouldHaveSameInstantAs]
*
* ```
* val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1))
* val other = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date.shouldNotHaveSameInstantAs(other) // Assertion passes
*
*
* val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1))
* val other = ZonedDateTime.of(2019, 2, 16, 9, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date.shouldNotHaveSameInstantAs(other) // Assertion fails, date is equal to the other date
* ```
*
* @see ZonedDateTime.shouldHaveSameInstantAs
*/
infix fun ZonedDateTime.shouldNotHaveSameInstantAs(other: ZonedDateTime) = this shouldNot haveSameInstantAs(other)
/**
* Matcher that checks if ZonedDateTime is equal to another ZonedDateTime using the
* [ChronoZonedDateTime.isEqual]
*
*
* ```
* val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1))
* val other = ZonedDateTime.of(2019, 2, 16, 9, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date.haveSameInstantAs(other) // Assertion passes
*
*
* val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1))
* val other = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-3))
*
* date.haveSameInstantAs(other) // Assertion fails, date is NOT equal to the other date
* ```
*
* @see ZonedDateTime.shouldHaveSameInstantAs
* @see ZonedDateTime.shouldNotHaveSameInstantAs
*/
fun haveSameInstantAs(other: ZonedDateTime) = object : Matcher<ZonedDateTime> {
override fun test(value: ZonedDateTime): MatcherResult =
MatcherResult(
passed = value.isEqual(other),
failureMessage = "$value should be equal to $other",
negatedFailureMessage = "$value should not be equal to $other"
)
}
| kotest-assertions/kotest-assertions-core/src/jvmMain/kotlin/io/kotest/matchers/date/matchers.kt | 2966126585 |
package com.mapzen.erasermap.view
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import com.mapzen.erasermap.R
/**
* Formats time for display. Examples: <1 min, 45 mins, 2 hrs 1 min, 5 hrs 27 mins.
*/
public class TimeView(context: Context, attrs: AttributeSet) : TextView(context, attrs) {
public var timeInMinutes: Int = 0
set (value) {
if (value < 1) {
text = context.getString(R.string.less_than_one_minute)
} else {
formatTime(value)
}
}
private fun formatTime(value: Int) {
val hours = value / 60
val minutes = value % 60
val hourText = context.resources.getQuantityString(R.plurals.hours, hours, hours)
val minuteText = context.resources.getQuantityString(R.plurals.minutes, minutes, minutes)
if (hours == 0) {
text = minuteText
} else if (minutes == 0) {
text = hourText
} else {
text = hourText + " " + minuteText
}
}
}
| app/src/main/kotlin/com/mapzen/erasermap/view/TimeView.kt | 310345 |
package com.sksamuel.kotest.engine
import io.kotest.core.spec.DisplayName
import io.kotest.core.spec.style.FunSpec
import io.kotest.core.spec.toDescription
import io.kotest.matchers.shouldBe
@DisplayName("ZZZZZ")
class DisplayNameTest : FunSpec() {
init {
test("@DisplayName should be used for spec name") {
DisplayNameTest::class.toDescription().name.displayName shouldBe "ZZZZZ"
}
}
}
| kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/DisplayNameTest.kt | 418387911 |
package ch.softappeal.yass
import java.lang.reflect.*
import kotlin.test.*
val Method: Method = Any::class.java.getMethod("toString")
val Arguments = listOf(0)
private interface Calculator {
fun one(): Int
fun minus(a: Int): Int
fun divide(a: Int, b: Int): Int
fun echo(a: String?): String?
}
private class CalculatorImpl : Calculator {
override fun one() = 1
override fun minus(a: Int) = -a
override fun divide(a: Int, b: Int) = a / b
override fun echo(a: String?) = a
}
val JavaCalculatorImpl = object : JavaCalculator {
override fun one() = 1
override fun minus(a: Int) = -a
override fun divide(a: Int, b: Int) = a / b
override fun echo(a: String?) = a
}
private val Printer: Interceptor = { method, arguments, invocation ->
print("$method$arguments")
try {
val result = invocation()
println(" = $result")
result
} catch (e: Exception) {
println(" threw $e")
throw e
}
}
class InterceptorTest {
@Test
fun objectMethods() {
val calculator: Calculator = proxy<Calculator>(CalculatorImpl(), Printer)
println(calculator.divide(12, 4))
assertTrue(calculator.equals(calculator))
assertFalse(calculator.equals(""))
assertFalse(calculator.equals(null))
assertEquals(Calculator::class.java.hashCode(), calculator.hashCode())
assertEquals("<yass proxy for 'ch.softappeal.yass.Calculator'>", calculator.toString())
}
@Test
fun direct() {
val result = Any()
assertSame(
DirectInterceptor(Method, Arguments) { result },
result
)
}
@Test
fun composite2() {
val interceptor: Interceptor = { _, _, invocation -> invocation() }
assertSame(interceptor, compositeInterceptor(interceptor, DirectInterceptor))
assertSame(interceptor, compositeInterceptor(DirectInterceptor, interceptor))
}
@Test
fun compositeN() {
val offset = 100
var step = 0
fun stepInterceptor(begin: Int, end: Int): Interceptor = { method, arguments, invocation ->
println("enter $begin")
assertSame(Method, method)
assertSame(Arguments, arguments)
assertEquals(begin, step)
step++
val result = invocation()
println("exit $end $result")
assertEquals(end, step)
assertEquals(result, step + offset)
step++
step + offset
}
val interceptors = arrayOf(
stepInterceptor(0, 6),
stepInterceptor(1, 5),
stepInterceptor(2, 4)
)
val interceptor = compositeInterceptor(*interceptors)
val invocation = {
assertEquals(step, interceptors.size)
step++
step + offset
}
assertEquals((2 * interceptors.size) + offset + 1, interceptor(Method, Arguments, invocation))
assertEquals((2 * interceptors.size) + 1, step)
}
@Test
fun proxyTest() {
val c = CalculatorImpl()
assertSame(c, proxy(c))
val calculator: Calculator = proxy<Calculator>(CalculatorImpl(), Printer)
assertEquals(2, calculator.divide(6, 3))
assertFailsWith<ArithmeticException> { calculator.divide(6, 0) }
assertEquals(1, calculator.one())
assertEquals(-2, calculator.minus(2))
assertEquals("echo", calculator.echo("echo"))
assertNull(calculator.echo(null))
}
@Test
fun javaProxyTest() {
assertSame(JavaCalculatorImpl, proxy(JavaCalculatorImpl))
val calculator = proxy(JavaCalculatorImpl, Printer)
assertEquals(2, calculator.divide(6, 3))
assertFailsWith<ArithmeticException> { calculator.divide(6, 0) }
assertEquals(1, calculator.one())
assertEquals(-2, calculator.minus(2))
assertEquals("echo", calculator.echo("echo"))
assertNull(calculator.echo(null))
}
@Test
fun threadLocal() {
val threadLocal = ThreadLocal<String>()
assertNull(threadLocal.get())
val result = Any()
val value = "value"
assertSame(
result,
threadLocalInterceptor(threadLocal, value)(Method, Arguments) {
assertSame(value, threadLocal.get())
result
}
)
assertNull(threadLocal.get())
val oldValue = "oldValue"
threadLocal.set(oldValue)
assertSame(
result,
threadLocalInterceptor(threadLocal, value)(Method, Arguments) {
assertSame(value, threadLocal.get())
result
}
)
assertSame(oldValue, threadLocal.get())
threadLocalInterceptor(ThreadLocal<String?>(), null)(Method, Arguments) {}
}
}
| kotlin/yass/test/ch/softappeal/yass/InterceptorTest.kt | 2759938485 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.build.jetifier.processor.archive
import java.io.OutputStream
import java.nio.file.Path
/**
* Abstraction to represent archive and its files as a one thing before and after transformation
* together with information if any changes happened during the transformation.
*/
interface ArchiveItem {
/**
* Relative path of the item according to its location in the archive.
*
* Files in a nested archive have a path relative to that archive not to the parent of
* the archive. The root archive has the file system path set as its relative path.
*/
val relativePath: Path
/**
* Name of the file.
*/
val fileName: String
/**
* Whether the item's content or its children were changed by Jetifier. This determines
* whether the parent archive is going to be marked as changed thus having a dependency on
* support.
*/
val wasChanged: Boolean
/**
* Accepts visitor.
*/
fun accept(visitor: ArchiveItemVisitor)
/**
* Writes its internal data (or other nested files) into the given output stream.
*/
fun writeSelfTo(outputStream: OutputStream)
fun isPomFile() = fileName.equals("pom.xml", ignoreCase = true)
|| fileName.endsWith(".pom", ignoreCase = true)
fun isClassFile() = fileName.endsWith(".class", ignoreCase = true)
fun isXmlFile() = fileName.endsWith(".xml", ignoreCase = true)
fun isProGuardFile () = fileName.equals("proguard.txt", ignoreCase = true)
} | jetifier/jetifier/processor/src/main/kotlin/com/android/tools/build/jetifier/processor/archive/ArchiveItem.kt | 2893054337 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.