content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.soywiz.korge.ext.spriter
import com.soywiz.korge.atlas.*
import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.*
import com.soywiz.korge.render.*
import com.soywiz.korge.view.*
import com.soywiz.korim.bitmap.*
import com.soywiz.korim.format.*
import com.soywiz.korio.file.*
import kotlin.collections.set
//e: java.lang.UnsupportedOperationException: Class literal annotation arguments are not yet supported: Factory
//@AsyncFactoryClass(SpriterLibrary.Loader::class)
class SpriterLibrary(val views: Views, val data: Data, val atlas: Map<String, TransformedTexture>) {
val entityNames = data.entities.map { it.name }
fun create(
entityName: String,
animationName1: String? = null,
animationName2: String? = animationName1
): SpriterView {
val entity = data.getEntity(entityName)
return SpriterView(
this,
entity!!,
animationName1 ?: entity.getAnimation(0).name,
animationName2 ?: entity.getAnimation(0).name
)
}
}
suspend fun VfsFile.readSpriterLibrary(views: Views): SpriterLibrary {
val file = this
val scmlContent = file.readString()
val reader = SCMLReader(scmlContent)
val data = reader.data
val textures = hashMapOf<String, TransformedTexture>()
for (atlasName in data.atlases) {
val atlas = file.parent[atlasName].readAtlas(views)
textures += atlas.textures
}
for (folder in data.folders) {
for (f in folder.files) {
if (f.name in textures) continue
val image = file.parent[f.name]
val bmpSlice = image.readBitmapSlice()
textures[f.name] = TransformedTexture(bmpSlice)
}
}
return SpriterLibrary(views, data, textures)
}
| @old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/SpriterLibrary.kt | 752949809 |
/*
* Copyright (C) 2017 Artem Hluhovskyi
*
* 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.dewarder.akommons.binding
import android.app.Activity
import android.app.Dialog
import android.app.Fragment
import android.content.Context
import android.support.annotation.RestrictTo
import android.support.annotation.StringRes
import android.view.View
import com.dewarder.akommons.binding.util.contextProvider
import com.dewarder.akommons.binding.util.safeString
import com.dewarder.akommons.util.Optional
import com.dewarder.akommons.util.Required
import kotlin.properties.ReadOnlyProperty
/**
* View
*/
fun View.string(@StringRes stringRes: Int): ReadOnlyProperty<View, String>
= requiredString(contextProvider, stringRes)
fun View.stringOptional(@StringRes stringRes: Int): ReadOnlyProperty<View, String?>
= optionalString(contextProvider, stringRes)
fun View.strings(@StringRes vararg stringRes: Int): ReadOnlyProperty<View, List<String>>
= requiredStrings(contextProvider, stringRes)
fun View.stringsOptional(@StringRes vararg stringRes: Int): ReadOnlyProperty<View, List<String?>>
= optionalStrings(contextProvider, stringRes)
/**
* Activity
*/
fun Activity.string(@StringRes stringRes: Int): ReadOnlyProperty<Activity, String>
= requiredString(contextProvider, stringRes)
fun Activity.stringOptional(@StringRes stringRes: Int): ReadOnlyProperty<Activity, String?>
= optionalString(contextProvider, stringRes)
fun Activity.strings(@StringRes vararg stringRes: Int): ReadOnlyProperty<Activity, List<String>>
= requiredStrings(contextProvider, stringRes)
fun Activity.stringsOptional(@StringRes vararg stringRes: Int): ReadOnlyProperty<Activity, List<String?>>
= optionalStrings(contextProvider, stringRes)
/**
* Fragment
*/
fun Fragment.string(@StringRes stringRes: Int): ReadOnlyProperty<Fragment, String>
= requiredString(contextProvider, stringRes)
fun Fragment.stringOptional(@StringRes stringRes: Int): ReadOnlyProperty<Fragment, String?>
= optionalString(contextProvider, stringRes)
fun Fragment.strings(@StringRes vararg stringRes: Int): ReadOnlyProperty<Fragment, List<String>>
= requiredStrings(contextProvider, stringRes)
fun Fragment.stringsOptional(@StringRes vararg stringRes: Int): ReadOnlyProperty<Fragment, List<String?>>
= optionalStrings(contextProvider, stringRes)
/**
* Dialog
*/
fun Dialog.string(@StringRes stringRes: Int): ReadOnlyProperty<Dialog, String>
= requiredString(contextProvider, stringRes)
fun Dialog.stringOptional(@StringRes stringRes: Int): ReadOnlyProperty<Dialog, String?>
= optionalString(contextProvider, stringRes)
fun Dialog.strings(@StringRes vararg stringRes: Int): ReadOnlyProperty<Dialog, List<String>>
= requiredStrings(contextProvider, stringRes)
fun Dialog.stringsOptional(@StringRes vararg stringRes: Int): ReadOnlyProperty<Dialog, List<String?>>
= optionalStrings(contextProvider, stringRes)
/**
* ContextProvider
*/
fun ContextProvider.string(@StringRes stringRes: Int): ReadOnlyProperty<ContextProvider, String>
= requiredString(this::provideContext, stringRes)
fun ContextProvider.stringOptional(@StringRes stringRes: Int): ReadOnlyProperty<ContextProvider, String?>
= optionalString(this::provideContext, stringRes)
fun ContextProvider.strings(@StringRes vararg stringRes: Int): ReadOnlyProperty<ContextProvider, List<String>>
= requiredStrings(this::provideContext, stringRes)
fun ContextProvider.stringsOptional(@StringRes vararg stringRes: Int): ReadOnlyProperty<ContextProvider, List<String?>>
= optionalStrings(this::provideContext, stringRes)
/**
* Getters
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> requiredString(crossinline contextProvider: () -> Context,
@StringRes stringRes: Int): ReadOnlyProperty<R, String> {
return Required { contextProvider().getString(stringRes) }
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> optionalString(crossinline contextProvider: () -> Context,
@StringRes stringRes: Int): ReadOnlyProperty<R, String?> {
return Optional { contextProvider().safeString(stringRes) }
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> requiredStrings(crossinline contextProvider: () -> Context,
@StringRes stringRes: IntArray): ReadOnlyProperty<R, List<String>> {
return Required {
val context = contextProvider()
stringRes.map(context::getString)
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> optionalStrings(crossinline contextProvider: () -> Context,
@StringRes stringRes: IntArray): ReadOnlyProperty<R, List<String?>> {
return Required {
val context = contextProvider()
stringRes.map(context::safeString)
}
}
| akommons-bindings/src/main/java/com/dewarder/akommons/binding/StringBindings.kt | 683838566 |
/*
* Copyright 2017 Mike Gouline
*
* 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 net.gouline.kapsule.demo
import net.gouline.kapsule.demo.di.MainDataModule
import net.gouline.kapsule.demo.di.MainLogicModule
import net.gouline.kapsule.demo.di.Module
import net.gouline.kapsule.transitive
/**
* Basic concept of application "context".
*/
open class Context {
@Suppress("LeakingThis")
open val module = Module(
data = MainDataModule(),
logic = MainLogicModule())
.transitive()
}
| samples/simple/src/main/kotlin/net/gouline/kapsule/demo/Context.kt | 116735997 |
package app.cash.sqldelight.intellij
import com.alecstrong.sql.psi.core.psi.SqlInsertStmt
import com.alecstrong.sql.psi.core.psi.SqlInsertStmtValues
import com.alecstrong.sql.psi.core.psi.SqlValuesExpression
import com.intellij.codeInsight.hints.InlayInfo
import com.intellij.codeInsight.hints.InlayParameterHintsProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import com.intellij.refactoring.suggested.startOffset
class SqlDelightInlayParameterHintsProvider : InlayParameterHintsProvider {
override fun getParameterHints(element: PsiElement): List<InlayInfo> {
if (element !is SqlValuesExpression || element.parent !is SqlInsertStmtValues) {
return emptyList()
}
return element.parentOfType<SqlInsertStmt>()?.columnNameList.orEmpty()
.zip(element.exprList) { col, expr ->
InlayInfo(col.name, expr.startOffset)
}
}
override fun getDefaultBlackList(): Set<String> {
return emptySet()
}
}
| sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/SqlDelightInlayParameterHintsProvider.kt | 1850184142 |
package tornadofx.testapps
import javafx.beans.property.SimpleIntegerProperty
import javafx.scene.Scene
import javafx.stage.Stage
import tornadofx.*
import java.util.concurrent.atomic.AtomicInteger
class ViewDockingApp : App(PrimaryDockingView::class)
open class PrimaryDockingView : View() {
companion object {
val instanceCounter = AtomicInteger()
}
val instanceId = instanceCounter.getAndIncrement()
val dockCounterProperty = SimpleIntegerProperty()
var dockCounter by dockCounterProperty
val undockCounterProperty = SimpleIntegerProperty()
var undockCounter by undockCounterProperty
init {
println("$tag.init()")
}
open val tag: String
get() = "PrimaryDockingView"
override val root = vbox {
form {
fieldset {
field("Instance ID") {
label(instanceId.toString())
}
field("Dock Counter") {
label(dockCounterProperty) {
style {
fontSize = 48.pt
}
}
}
field("Undock Counter") {
label(undockCounterProperty) {
style {
fontSize = 48.pt
}
}
}
}
}
}
override fun onDock() {
super.onDock()
dockCounter++
println("$tag.dockCounter: $dockCounter")
}
override fun onUndock() {
super.onUndock()
undockCounter++
println("$tag.undockCounter: $undockCounter")
}
}
class SecondaryDockingView : PrimaryDockingView() {
override val tag: String
get() = "SecondaryDockingView"
}
class NoPrimaryViewDockingApp : App() {
override fun start(stage: Stage) {
super.start(stage)
stage.scene = Scene(find<PrimaryDockingView>().root)
stage.show()
}
} | src/test/kotlin/tornadofx/testapps/ViewDockingApp.kt | 2825995726 |
package ffc.app.photo
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import com.sembozdemir.permissionskt.askPermissions
import com.sembozdemir.permissionskt.handlePermissionsResult
import ffc.android.load
import ffc.android.onClick
import ffc.android.sceneTransition
import ffc.app.FamilyFolderActivity
import ffc.app.R
import ffc.app.dev
import ffc.app.util.alert.handle
import ffc.app.util.alert.toast
import kotlinx.android.synthetic.main.photo_action_bar.choosePhoto
import kotlinx.android.synthetic.main.photo_action_bar.takePhoto
import kotlinx.android.synthetic.main.photo_avatar_activity.avatarView
import me.piruin.phototaker.PhotoSize
import me.piruin.phototaker.PhotoTaker
import me.piruin.phototaker.PhotoTakerListener
import org.jetbrains.anko.dip
import org.jetbrains.anko.indeterminateProgressDialog
import org.jetbrains.anko.intentFor
class AvatarPhotoActivity : FamilyFolderActivity() {
private val photoTaker by lazy {
PhotoTaker(this, PhotoSize(dip(1024), dip(1024))).apply {
setListener(object : PhotoTakerListener {
override fun onFinish(intent: Intent) {
photoUri = UriPhoto(intent.data!!)
avatarView.load(intent.data!!)
}
override fun onCancel(action: Int) {}
override fun onError(action: Int) {}
})
}
}
private var previousPhotoUrl: UrlPhoto? = null
var photoUri: Photo? = null
private val storage: PhotoStorage
get() = org!!.photoStorageFor(intent.photoType)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.photo_avatar_activity)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
intent.data?.let {
previousPhotoUrl = UrlPhoto(it.toString())
avatarView.load(it)
}
takePhoto.onClick {
askPermissions(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) {
onGranted {
photoTaker.captureImage()
}
}
}
choosePhoto.onClick {
askPermissions(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) {
onGranted {
photoTaker.pickImage()
}
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
handlePermissionsResult(requestCode, permissions, grantResults)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
photoTaker.onActivityResult(requestCode, resultCode, data)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> {
if (photoUri == null) finish()
photoUri?.let { photo -> upload(photo) }
}
}
return super.onOptionsItemSelected(item)
}
private fun upload(photo: Photo) {
val dialog = indeterminateProgressDialog("บันทึกภาพถ่าย").apply { show() }
storage.save(photo.uri) {
onComplete {
delete(previousPhotoUrl)
dialog.dismiss()
setResult(Activity.RESULT_OK, Intent().apply { data = it })
finish()
}
onFail {
handle(it)
}
}
}
private fun delete(photo: Photo?) {
photo?.let { photo ->
storage.delete(photo.uri) {
onComplete { dev { toast("Deleted ${photo.uri}") } }
onFail { handle(it) }
}
}
}
}
fun Activity.startAvatarPhotoActivity(
type: PhotoType,
url: String? = null,
avatarView: View? = null,
requestCode: Int = REQUEST_TAKE_PHOTO
) {
val intent = intentFor<AvatarPhotoActivity>()
intent.photoType = type
url?.let { intent.data = Uri.parse(it) }
val bundle = if (avatarView == null)
sceneTransition()
else
sceneTransition(avatarView to getString(R.string.transition_photo))
startActivityForResult(intent, requestCode, bundle)
}
| ffc/src/main/kotlin/ffc/app/photo/AvatarPhotoActivity.kt | 522210002 |
package br.com.edsilfer.android.starwarswiki.view.activities.contracts
import br.com.edsilfer.android.starwarswiki.model.Character
import br.com.tyllt.view.contracts.BaseView
/**
* Created by ferna on 2/18/2017.
*/
interface HomepageViewContract : BaseView {
fun showErrorMessage(message: Int)
/*
Load cached character list on recycler view
*/
fun loadCachedCharacters()
/*
Adds character on recycler view
*/
fun addCharacter(character: Character)
/*
Removes character from recycler view
*/
fun removeCharacter(character: Character)
/**
* Opens film details activity
*/
fun onCharacterClick(character: Character)
/*
Deletes character entry from database
*/
fun deleteCharacter(character: Character)
/*
Displays a pop up to gather character's url
*/
fun showGetUrlPopUp()
/*
Request permission for Camera and Access Coarse Location
*/
fun requestAppPermissions()
/**
* Forces soft keyboard to close
*/
fun dismissSoftKeyboard ()
} | app/src/main/java/br/com/edsilfer/android/starwarswiki/view/activities/contracts/HomepageViewContract.kt | 2449076109 |
/*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.samplepay.model
import android.os.Bundle
data class PaymentOptions(
val requestPayerName: Boolean,
val requestPayerPhone: Boolean,
val requestPayerEmail: Boolean,
val requestShipping: Boolean,
val shippingType: String
) {
companion object {
fun from(extras: Bundle?): PaymentOptions {
return PaymentOptions(
requestPayerName = extras?.getBoolean("requestPayerName", false) ?: false,
requestPayerPhone = extras?.getBoolean("requestPayerPhone", false) ?: false,
requestPayerEmail = extras?.getBoolean("requestPayerEmail", false) ?: false,
requestShipping = extras?.getBoolean("requestShipping", false) ?: false,
shippingType = extras?.getString("shippingType", "shipping") ?: "shipping"
)
}
}
val requireContact: Boolean
get() = requestPayerName || requestPayerPhone || requestPayerEmail
}
| SamplePay/app/src/main/java/com/example/android/samplepay/model/PaymentOptions.kt | 2025531942 |
package com.tamsiree.rxdemo.activity
import android.annotation.SuppressLint
import android.os.Bundle
import com.tamsiree.rxdemo.R
import com.tamsiree.rxkit.RxDataTool.Companion.cn2PY
import com.tamsiree.rxkit.RxDataTool.Companion.format2Decimals
import com.tamsiree.rxkit.RxDataTool.Companion.formatCard
import com.tamsiree.rxkit.RxDataTool.Companion.formatCardEnd4
import com.tamsiree.rxkit.RxDataTool.Companion.getAmountValue
import com.tamsiree.rxkit.RxDataTool.Companion.getAstro
import com.tamsiree.rxkit.RxDataTool.Companion.getPYAllFirstLetter
import com.tamsiree.rxkit.RxDataTool.Companion.getPYFirstLetter
import com.tamsiree.rxkit.RxDataTool.Companion.getRoundUp
import com.tamsiree.rxkit.RxDataTool.Companion.hideMobilePhone4
import com.tamsiree.rxkit.RxDataTool.Companion.isDouble
import com.tamsiree.rxkit.RxDataTool.Companion.isInteger
import com.tamsiree.rxkit.RxDataTool.Companion.isNullString
import com.tamsiree.rxkit.RxDataTool.Companion.isNumber
import com.tamsiree.rxkit.RxDataTool.Companion.lowerFirstLetter
import com.tamsiree.rxkit.RxDataTool.Companion.oneCn2ASCII
import com.tamsiree.rxkit.RxDataTool.Companion.oneCn2PY
import com.tamsiree.rxkit.RxDataTool.Companion.reverse
import com.tamsiree.rxkit.RxDataTool.Companion.stringToDouble
import com.tamsiree.rxkit.RxDataTool.Companion.stringToFloat
import com.tamsiree.rxkit.RxDataTool.Companion.stringToInt
import com.tamsiree.rxkit.RxDataTool.Companion.stringToLong
import com.tamsiree.rxkit.RxDataTool.Companion.toDBC
import com.tamsiree.rxkit.RxDataTool.Companion.toSBC
import com.tamsiree.rxkit.RxDataTool.Companion.upperFirstLetter
import com.tamsiree.rxkit.RxDeviceTool.setPortrait
import com.tamsiree.rxui.activity.ActivityBase
import kotlinx.android.synthetic.main.activity_rx_data_utils.*
/**
* @author tamsiree
*/
class ActivityRxDataTool : ActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rx_data_utils)
setPortrait(this)
}
@SuppressLint("SetTextI18n")
override fun initView() {
rx_title.setLeftFinish(mContext)
btn_null.setOnClickListener { tv_null.text = isNullString(editText.text.toString()).toString() }
btn_null_obj.setOnClickListener { tv_null_obj.text = isNullString(editText.text.toString()).toString() }
btn_is_integer.setOnClickListener { tv_is_integer.text = isInteger(editText.text.toString()).toString() }
btn_is_double.setOnClickListener { tv_is_double.text = isDouble(editText.text.toString()).toString() }
btn_is_number.setOnClickListener { tv_is_number.text = isNumber(editText.text.toString()).toString() }
btn_astro.setOnClickListener { tv_astro.text = getAstro(stringToInt(ed_month.text.toString()), stringToInt(ed_day.text.toString())) }
btn_hind_mobile.setOnClickListener { tv_hind_mobile.text = hideMobilePhone4(ed_mobile.text.toString()) }
btn_format_bank_card.setOnClickListener { tv_format_bank_card.text = formatCard(ed_bank_card.text.toString()) }
btn_format_bank_card_4.setOnClickListener { tv_format_bank_card_4.text = formatCardEnd4(ed_bank_card.text.toString()) }
btn_getAmountValue.setOnClickListener { tv_getAmountValue.text = getAmountValue(ed_money.text.toString()) }
btn_getRoundUp.setOnClickListener { tv_getRoundUp.text = getRoundUp(ed_money.text.toString(), 2) }
btn_string_to_int.setOnClickListener { tv_string_to_int.text = stringToInt(ed_text.text.toString()).toString() }
btn_string_to_long.setOnClickListener { tv_string_to_long.text = stringToLong(ed_text.text.toString()).toString() }
btn_string_to_double.setOnClickListener { tv_string_to_double.text = stringToDouble(ed_text.text.toString()).toString() }
btn_string_to_float.setOnClickListener { tv_string_to_float.text = stringToFloat(ed_text.text.toString()).toString() }
btn_string_to_two_number.setOnClickListener { tv_string_to_two_number.text = format2Decimals(ed_text.text.toString()) }
btn_upperFirstLetter.setOnClickListener { tv_upperFirstLetter.text = upperFirstLetter(ed_string.text.toString()) }
btn_lowerFirstLetter.setOnClickListener { tv_lowerFirstLetter.text = lowerFirstLetter(ed_string.text.toString()) }
btn_reverse.setOnClickListener { tv_reverse.text = reverse(ed_string.text.toString()) }
btn_toDBC.setOnClickListener { tv_toDBC.text = toDBC(ed_string.text.toString()) }
btn_toSBC.setOnClickListener { tv_toSBC.text = toSBC(ed_string.text.toString()) }
btn_oneCn2ASCII.setOnClickListener { tv_oneCn2ASCII.text = oneCn2ASCII(ed_string.text.toString()).toString() }
btn_oneCn2PY.setOnClickListener { tv_oneCn2PY.text = oneCn2PY(ed_string.text.toString()) }
btn_getPYFirstLetter.setOnClickListener { tv_getPYFirstLetter.text = getPYFirstLetter(ed_string.text.toString()) }
btn_getPYAllFirstLetter.setOnClickListener { tv_getPYAllFirstLetter.text = getPYAllFirstLetter(ed_string.text.toString()) }
btn_cn2PY.setOnClickListener { tv_cn2PY.text = cn2PY(ed_string.text.toString()) }
}
override fun initData() {
}
} | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityRxDataTool.kt | 1089249904 |
/*
* Copyright 2020 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pasterino.service.single
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class SinglePasteReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
SinglePasteService.enqueue(context)
}
}
| app/src/main/java/com/pyamsoft/pasterino/service/single/SinglePasteReceiver.kt | 496009500 |
package org.wikipedia.diff
import android.graphics.Canvas
import android.graphics.Paint
import android.text.style.LineBackgroundSpan
import androidx.annotation.ColorInt
import org.wikipedia.util.DimenUtil
class EmptyLineSpan(@ColorInt val fillColor: Int, @ColorInt val strokeColor: Int) : LineBackgroundSpan {
override fun drawBackground(canvas: Canvas, paint: Paint, left: Int, right: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence, start: Int, end: Int, lineNumber: Int) {
val prevColor = paint.color
val prevStyle = paint.style
val strokeAdjust = DimenUtil.dpToPx(0.5f)
val roundRadius = DimenUtil.dpToPx(8f)
paint.style = Paint.Style.FILL
paint.color = fillColor
canvas.drawRoundRect(left.toFloat() + strokeAdjust, top.toFloat() + strokeAdjust,
right.toFloat() - strokeAdjust, bottom.toFloat() + roundRadius / 2f, roundRadius, roundRadius, paint)
paint.style = Paint.Style.STROKE
paint.color = strokeColor
canvas.drawRoundRect(left.toFloat() + strokeAdjust, top.toFloat() + strokeAdjust,
right.toFloat() - strokeAdjust, bottom.toFloat() + roundRadius / 2f, roundRadius, roundRadius, paint)
paint.style = prevStyle
paint.color = prevColor
}
}
| app/src/main/java/org/wikipedia/diff/EmptyLineSpan.kt | 4270434617 |
package com.stripe.android.stripecardscan.framework.util
import android.util.Size
import com.stripe.android.stripecardscan.framework.api.dto.CardImageVerificationDetailsAcceptedImageConfigs
import com.stripe.android.stripecardscan.framework.api.dto.CardImageVerificationDetailsFormat
import com.stripe.android.stripecardscan.framework.api.dto.CardImageVerificationDetailsImageSettings
internal enum class ImageFormat(val string: String) {
HEIC("heic"),
JPEG("jpeg"),
WEBP("webp");
companion object {
fun fromValue(value: CardImageVerificationDetailsFormat): ImageFormat =
when (value) {
CardImageVerificationDetailsFormat.HEIC -> HEIC
CardImageVerificationDetailsFormat.JPEG -> JPEG
CardImageVerificationDetailsFormat.WEBP -> WEBP
}
}
}
internal data class OptionalImageSettings(
val compressionRatio: Double?,
val imageSize: Size?,
val imageCount: Int?
) {
constructor(settings: CardImageVerificationDetailsImageSettings?) : this(
compressionRatio = settings?.compressionRatio,
imageSize = settings?.imageSize?.takeIf { it.size > 1 }?.let {
Size(it.first().toInt(), it.last().toInt())
},
imageCount = settings?.imageCount
)
}
internal data class ImageSettings(
val compressionRatio: Double,
val imageSize: Size,
val imageCount: Int
) {
companion object {
// These default values are what Android was using before the addition of a server config.
val DEFAULT = ImageSettings(0.92, Size(1080, 1920), 3)
}
}
internal data class AcceptedImageConfigs(
private val defaultSettings: OptionalImageSettings?,
private val formatSettings: Map<ImageFormat, OptionalImageSettings?>? = null,
val preferredFormats: List<ImageFormat>? = listOf(ImageFormat.JPEG)
) {
companion object {
internal fun isFormatSupported(format: ImageFormat) =
format == ImageFormat.JPEG || format == ImageFormat.WEBP
}
constructor(configs: CardImageVerificationDetailsAcceptedImageConfigs? = null) : this(
defaultSettings = configs?.defaultSettings?.let { OptionalImageSettings(it) },
formatSettings = configs?.formatSettings?.takeIf { it.isNotEmpty() }?.map { entry ->
ImageFormat.fromValue(entry.key) to OptionalImageSettings(entry.value)
}
?.toMap(),
preferredFormats = configs?.preferredFormats?.map { ImageFormat.fromValue(it) }
?.filter { isFormatSupported(it) }
?.takeIf { it.isNotEmpty() }
)
fun getImageSettings(format: ImageFormat): ImageSettings = ImageSettings(
compressionRatio = formatSettings?.get(format)?.compressionRatio
?: defaultSettings?.compressionRatio ?: ImageSettings.DEFAULT.compressionRatio,
imageSize = formatSettings?.get(format)?.imageSize ?: defaultSettings?.imageSize
?: ImageSettings.DEFAULT.imageSize,
imageCount = formatSettings?.get(format)?.imageCount ?: defaultSettings?.imageCount
?: ImageSettings.DEFAULT.imageCount
)
fun getImageSettings(): Pair<ImageFormat, ImageSettings> {
val format = preferredFormats?.first() ?: ImageFormat.JPEG
return format to getImageSettings(format)
}
}
| stripecardscan/src/main/java/com/stripe/android/stripecardscan/framework/util/AcceptedImageConfigs.kt | 1839478101 |
package ru.softeg.slartus.forum.api
interface TopicAttachmentsRepository {
suspend fun fetchTopicAttachments(topicId: String): List<TopicAttachment>
} | topic/topic-api/src/main/java/ru/softeg/slartus/forum.api/TopicAttachmentsRepository.kt | 3618744497 |
package com.stripe.android.identity.networking
import android.util.Log
import androidx.annotation.VisibleForTesting
import com.stripe.android.camera.framework.time.Clock
import com.stripe.android.core.exception.APIConnectionException
import com.stripe.android.core.exception.APIException
import com.stripe.android.core.model.StripeFile
import com.stripe.android.core.model.StripeFileParams
import com.stripe.android.core.model.StripeFilePurpose
import com.stripe.android.core.model.StripeModel
import com.stripe.android.core.model.parsers.ModelJsonParser
import com.stripe.android.core.model.parsers.StripeErrorJsonParser
import com.stripe.android.core.model.parsers.StripeFileJsonParser
import com.stripe.android.core.networking.AnalyticsRequestV2
import com.stripe.android.core.networking.ApiRequest
import com.stripe.android.core.networking.StripeNetworkClient
import com.stripe.android.core.networking.StripeRequest
import com.stripe.android.core.networking.responseJson
import com.stripe.android.core.utils.urlEncode
import com.stripe.android.identity.networking.models.ClearDataParam
import com.stripe.android.identity.networking.models.ClearDataParam.Companion.createCollectedDataParamEntry
import com.stripe.android.identity.networking.models.CollectedDataParam
import com.stripe.android.identity.networking.models.CollectedDataParam.Companion.createCollectedDataParamEntry
import com.stripe.android.identity.networking.models.VerificationPage
import com.stripe.android.identity.networking.models.VerificationPageData
import com.stripe.android.identity.utils.IdentityIO
import kotlinx.serialization.KSerializer
import kotlinx.serialization.json.Json
import java.io.File
import javax.inject.Inject
internal class DefaultIdentityRepository @Inject constructor(
private val stripeNetworkClient: StripeNetworkClient,
private val identityIO: IdentityIO
) : IdentityRepository {
@VisibleForTesting
internal val json: Json = Json {
ignoreUnknownKeys = true
isLenient = true
encodeDefaults = true
}
private val stripeErrorJsonParser = StripeErrorJsonParser()
private val stripeFileJsonParser = StripeFileJsonParser()
private val apiRequestFactory = ApiRequest.Factory(
apiVersion = IDENTITY_STRIPE_API_VERSION_WITH_BETA_HEADER
)
override suspend fun retrieveVerificationPage(
id: String,
ephemeralKey: String
): VerificationPage = executeRequestWithKSerializer(
apiRequestFactory.createGet(
url = "$BASE_URL/$IDENTITY_VERIFICATION_PAGES/${urlEncode(id)}",
options = ApiRequest.Options(
apiKey = ephemeralKey
)
),
VerificationPage.serializer()
)
override suspend fun postVerificationPageData(
id: String,
ephemeralKey: String,
collectedDataParam: CollectedDataParam,
clearDataParam: ClearDataParam
): VerificationPageData = executeRequestWithKSerializer(
apiRequestFactory.createPost(
url = "$BASE_URL/$IDENTITY_VERIFICATION_PAGES/${urlEncode(id)}/$DATA",
options = ApiRequest.Options(
apiKey = ephemeralKey
),
params = mapOf(
collectedDataParam.createCollectedDataParamEntry(json),
clearDataParam.createCollectedDataParamEntry(json)
)
),
VerificationPageData.serializer()
)
override suspend fun postVerificationPageSubmit(
id: String,
ephemeralKey: String
): VerificationPageData = executeRequestWithKSerializer(
apiRequestFactory.createPost(
url = "$BASE_URL/$IDENTITY_VERIFICATION_PAGES/${urlEncode(id)}/$SUBMIT",
options = ApiRequest.Options(
apiKey = ephemeralKey
)
),
VerificationPageData.serializer()
)
override suspend fun uploadImage(
verificationId: String,
ephemeralKey: String,
imageFile: File,
filePurpose: StripeFilePurpose,
onSuccessExecutionTimeBlock: (Long) -> Unit
): StripeFile = executeRequestWithModelJsonParser(
request = IdentityFileUploadRequest(
fileParams = StripeFileParams(
file = imageFile,
purpose = filePurpose
),
options = ApiRequest.Options(
apiKey = ephemeralKey
),
verificationId = verificationId
),
responseJsonParser = stripeFileJsonParser,
onSuccessExecutionTimeBlock = onSuccessExecutionTimeBlock
)
override suspend fun downloadModel(modelUrl: String) = runCatching {
stripeNetworkClient.executeRequestForFile(
IdentityFileDownloadRequest(modelUrl),
identityIO.createTFLiteFile(modelUrl)
)
}.fold(
onSuccess = { response ->
if (response.isError) {
throw APIException(
requestId = response.requestId?.value,
statusCode = response.code,
message = "Downloading from $modelUrl returns error response"
)
} else {
response.body ?: run {
throw APIException(
message = "Downloading from $modelUrl returns a null body"
)
}
}
},
onFailure = {
throw APIConnectionException(
"Fail to download file at $modelUrl",
cause = it
)
}
)
override suspend fun downloadFile(fileUrl: String) = runCatching {
stripeNetworkClient.executeRequestForFile(
IdentityFileDownloadRequest(fileUrl),
identityIO.createCacheFile()
)
}.fold(
onSuccess = { response ->
if (response.isError) {
throw APIException(
requestId = response.requestId?.value,
statusCode = response.code,
message = "Downloading from $fileUrl returns error response"
)
} else {
response.body ?: run {
throw APIException(
message = "Downloading from $fileUrl returns a null body"
)
}
}
},
onFailure = {
throw APIConnectionException(
"Fail to download file at $fileUrl",
cause = it
)
}
)
override suspend fun sendAnalyticsRequest(analyticsRequestV2: AnalyticsRequestV2) {
runCatching {
stripeNetworkClient.executeRequest(analyticsRequestV2)
}.onFailure {
Log.e(TAG, "Exception while making analytics request")
}
}
private suspend fun <Response> executeRequestWithKSerializer(
request: StripeRequest,
responseSerializer: KSerializer<Response>
): Response = runCatching {
stripeNetworkClient.executeRequest(
request
)
}.fold(
onSuccess = { response ->
if (response.isError) {
// TODO(ccen) Parse the response code and throw different exceptions
throw APIException(
stripeError = stripeErrorJsonParser.parse(response.responseJson()),
requestId = response.requestId?.value,
statusCode = response.code
)
} else {
json.decodeFromString(
responseSerializer,
requireNotNull(response.body)
)
}
},
onFailure = {
throw APIConnectionException(
"Failed to execute $request",
cause = it
)
}
)
private suspend fun <Response : StripeModel> executeRequestWithModelJsonParser(
request: StripeRequest,
responseJsonParser: ModelJsonParser<Response>,
onSuccessExecutionTimeBlock: (Long) -> Unit = {}
): Response {
val started = Clock.markNow()
return runCatching {
stripeNetworkClient.executeRequest(
request
)
}.fold(
onSuccess = { response ->
if (response.isError) {
// TODO(ccen) Parse the response code and throw different exceptions
throw APIException(
stripeError = stripeErrorJsonParser.parse(response.responseJson()),
requestId = response.requestId?.value,
statusCode = response.code
)
} else {
responseJsonParser.parse(response.responseJson())?.let { response ->
onSuccessExecutionTimeBlock(started.elapsedSince().inMilliseconds.toLong())
response
} ?: run {
throw APIException(
message = "$responseJsonParser returns null for ${response.responseJson()}"
)
}
}
},
onFailure = {
throw APIConnectionException(
"Failed to execute $request",
cause = it
)
}
)
}
internal companion object {
const val SUBMIT = "submit"
const val DATA = "data"
val TAG: String = DefaultIdentityRepository::class.java.simpleName
}
}
| identity/src/main/java/com/stripe/android/identity/networking/DefaultIdentityRepository.kt | 3734344685 |
package de.sudoq.model.solverGenerator.solution
import de.sudoq.model.actionTree.Action
import de.sudoq.model.actionTree.NoteActionFactory
import de.sudoq.model.solvingAssistant.HintTypes
import de.sudoq.model.sudoku.Constraint
import de.sudoq.model.sudoku.Sudoku
import de.sudoq.model.sudoku.Utils
import de.sudoq.model.sudoku.getGroupShape
import java.util.*
/**
* Created by timo on 04.10.16.
*/
class LeftoverNoteDerivation(val constraint: Constraint, val note: Int) :
SolveDerivation(HintTypes.LeftoverNote) {
private val actionlist: MutableList<Action> = ArrayList()
val constraintShape: Utils.ConstraintShape
get() = getGroupShape(constraint)
override fun getActionList(sudoku: Sudoku): List<Action> {
val af = NoteActionFactory()
for (p in constraint) {
val f = sudoku.getCell(p)
if (f!!.isNoteSet(note) && f.isNotSolved) actionlist.add(af.createAction(note, f))
}
return actionlist
}
init {
hasActionListCapability = true
}
} | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/solverGenerator/solution/LeftoverNoteDerivation.kt | 3851693477 |
/*
* Copyright 2019 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.pyamsoft.padlock.model.list
data class LockInfoUpdatePayload(
val index: Int,
val entry: ActivityEntry
)
| padlock-model/src/main/java/com/pyamsoft/padlock/model/list/LockInfoUpdatePayload.kt | 1772059651 |
package com.iezview.view
import tornadofx.*
/**
* 主视图
*/
class MainView : View("Hello Flash Air") {
val toolBar :TopView by inject()
val cameraList : CameraListView by inject()
val console :ConsoleView by inject()
override val root =borderpane {
top=toolBar.root
center=cameraList.root
bottom =console.root
}
} | src/main/kotlin/com/iezview/view/MainView.kt | 832937017 |
package org.jetbrains.dokka
import org.jetbrains.dokka.DokkaConfiguration.SourceLinkDefinition
import org.jetbrains.dokka.DokkaConfiguration.SourceRoot
import java.io.File
data class SourceLinkDefinitionImpl(override val path: String,
override val url: String,
override val lineSuffix: String?) : SourceLinkDefinition {
companion object {
fun parseSourceLinkDefinition(srcLink: String): SourceLinkDefinition {
val (path, urlAndLine) = srcLink.split('=')
return SourceLinkDefinitionImpl(File(path).absolutePath,
urlAndLine.substringBefore("#"),
urlAndLine.substringAfter("#", "").let { if (it.isEmpty()) null else "#" + it })
}
}
}
class SourceRootImpl(path: String, override val platforms: List<String> = emptyList()) : SourceRoot {
override val path: String = File(path).absolutePath
companion object {
fun parseSourceRoot(sourceRoot: String): SourceRoot {
val components = sourceRoot.split("::", limit = 2)
return SourceRootImpl(components.last(), if (components.size == 1) listOf() else components[0].split(','))
}
}
}
data class PackageOptionsImpl(override val prefix: String,
override val includeNonPublic: Boolean = false,
override val reportUndocumented: Boolean = true,
override val skipDeprecated: Boolean = false,
override val suppress: Boolean = false) : DokkaConfiguration.PackageOptions
data class DokkaConfigurationImpl(
override val moduleName: String,
override val classpath: List<String>,
override val sourceRoots: List<SourceRootImpl>,
override val samples: List<String>,
override val includes: List<String>,
override val outputDir: String,
override val format: String,
override val includeNonPublic: Boolean,
override val includeRootPackage: Boolean,
override val reportUndocumented: Boolean,
override val skipEmptyPackages: Boolean,
override val skipDeprecated: Boolean,
override val jdkVersion: Int,
override val generateClassIndexPage: Boolean,
override val generatePackageIndexPage: Boolean,
override val sourceLinks: List<SourceLinkDefinitionImpl>,
override val impliedPlatforms: List<String>,
override val perPackageOptions: List<PackageOptionsImpl>,
override val externalDocumentationLinks: List<ExternalDocumentationLinkImpl>,
override val noStdlibLink: Boolean,
override val noJdkLink: Boolean,
override val cacheRoot: String?,
override val suppressedFiles: List<String>,
override val languageVersion: String?,
override val apiVersion: String?,
override val collectInheritedExtensionsFromLibraries: Boolean,
override val outlineRoot: String,
override val dacRoot: String
) : DokkaConfiguration | core/src/main/kotlin/Generation/configurationImpl.kt | 301730387 |
package me.keegan.snap
import android.app.AlertDialog
import android.app.ListActivity
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.NavUtils
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.Window
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
import com.parse.FindCallback
import com.parse.ParseException
import com.parse.ParseFile
import com.parse.ParseObject
import com.parse.ParseQuery
import com.parse.ParseRelation
import com.parse.ParseUser
import com.parse.SaveCallback
import java.util.ArrayList
class RecipientsActivity : ListActivity() {
protected lateinit var mFriendsRelation: ParseRelation<ParseUser>
protected lateinit var mCurrentUser: ParseUser
protected lateinit var mFriends: List<ParseUser>
protected lateinit var mSendMenuItem: MenuItem
protected var mMediaUri: Uri? = null
protected var mFileType: String? = null
protected val recipientIds: ArrayList<String>
get() {
val recipientIds = ArrayList<String>()
for (i in 0 until listView.count) {
if (listView.isItemChecked(i)) {
recipientIds.add(mFriends[i].objectId)
}
}
return recipientIds
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS)
setContentView(R.layout.activity_recipients)
// Show the Up button in the action bar.
setupActionBar()
listView.choiceMode = ListView.CHOICE_MODE_MULTIPLE
mMediaUri = intent.data
mFileType = intent.extras!!.getString(ParseConstants.KEY_FILE_TYPE)
}
public override fun onResume() {
super.onResume()
mCurrentUser = ParseUser.getCurrentUser()
mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION)
setProgressBarIndeterminateVisibility(true)
val query = mFriendsRelation.query
query.addAscendingOrder(ParseConstants.KEY_USERNAME)
query.findInBackground { friends, e ->
setProgressBarIndeterminateVisibility(false)
if (e == null) {
mFriends = friends
val usernames = arrayOfNulls<String>(mFriends.size)
var i = 0
for (user in mFriends) {
usernames[i] = user.username
i++
}
val adapter = ArrayAdapter<String>(
listView.context,
android.R.layout.simple_list_item_checked,
usernames)
listAdapter = adapter
} else {
Log.e(TAG, e.message)
val builder = AlertDialog.Builder(this@RecipientsActivity)
builder.setMessage(e.message)
.setTitle(R.string.error_title)
.setPositiveButton(android.R.string.ok, null)
val dialog = builder.create()
dialog.show()
}
}
}
/**
* Set up the [android.app.ActionBar].
*/
private fun setupActionBar() {
actionBar!!.setDisplayHomeAsUpEnabled(true)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.recipients, menu)
mSendMenuItem = menu.getItem(0)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this)
return true
}
R.id.action_send -> {
val message = createMessage()
if (message == null) {
// error
val builder = AlertDialog.Builder(this)
builder.setMessage(R.string.error_selecting_file)
.setTitle(R.string.error_selecting_file_title)
.setPositiveButton(android.R.string.ok, null)
val dialog = builder.create()
dialog.show()
} else {
send(message)
finish()
}
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {
super.onListItemClick(l, v, position, id)
if (l.checkedItemCount > 0) {
mSendMenuItem.isVisible = true
} else {
mSendMenuItem.isVisible = false
}
}
protected fun createMessage(): ParseObject? {
val message = ParseObject(ParseConstants.CLASS_MESSAGES)
message.put(ParseConstants.KEY_SENDER_ID, ParseUser.getCurrentUser().objectId)
message.put(ParseConstants.KEY_SENDER_NAME, ParseUser.getCurrentUser().username)
message.put(ParseConstants.KEY_RECIPIENT_IDS, recipientIds)
message.put(ParseConstants.KEY_FILE_TYPE, mFileType!!)
var fileBytes = FileHelper.getByteArrayFromFile(this, mMediaUri!!)
if (fileBytes == null) {
return null
} else {
if (mFileType == ParseConstants.TYPE_IMAGE) {
fileBytes = FileHelper.reduceImageForUpload(fileBytes)
}
val fileName = FileHelper.getFileName(this, mMediaUri!!, mFileType!!)
val file = ParseFile(fileName, fileBytes)
message.put(ParseConstants.KEY_FILE, file)
return message
}
}
protected fun send(message: ParseObject?) {
message!!.saveInBackground { e ->
if (e == null) {
// success!
Toast.makeText(this@RecipientsActivity, R.string.success_message, Toast.LENGTH_LONG).show()
} else {
val builder = AlertDialog.Builder(this@RecipientsActivity)
builder.setMessage(R.string.error_sending_message)
.setTitle(R.string.error_selecting_file_title)
.setPositiveButton(android.R.string.ok, null)
val dialog = builder.create()
dialog.show()
}
}
}
companion object {
val TAG = RecipientsActivity::class.java.simpleName
}
}
| app/src/main/java/me/keegan/snap/RecipientsActivity.kt | 4093715811 |
/*
Copyright 2017-2020 Charles Korn.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.docker.pull
import batect.testutils.equalTo
import batect.testutils.given
import batect.testutils.on
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.startsWith
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object DockerImageProgressSpec : Spek({
describe("Docker image progress information") {
given("the image is downloading") {
val progress = DockerImageProgress("Downloading", 10, 100)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("formats the progress in the expected style") {
assertThat(display, equalTo("Downloading: 10 B of 100 B (10%)"))
}
}
}
given("the total size is not known and the download has not started") {
val progress = DockerImageProgress("Downloading", 0, 0)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("does not display the size and just shows the percentage") {
assertThat(display, equalTo("Downloading"))
}
}
}
given("the total size is not known and the download has started") {
val progress = DockerImageProgress("Downloading", 100, 0)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("does not display the size and just shows the percentage") {
assertThat(display, equalTo("Downloading: 100 B"))
}
}
}
given("the pull has not started") {
val progress = DockerImageProgress("Downloading", 0, 100)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("formats the progress in the expected style") {
assertThat(display, equalTo("Downloading: 0 B of 100 B (0%)"))
}
}
}
given("the pull has completed") {
val progress = DockerImageProgress("Downloading", 100, 100)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("formats the progress in the expected style") {
assertThat(display, equalTo("Downloading: 100 B of 100 B (100%)"))
}
}
}
mapOf(
10L to "10 B",
100L to "100 B",
999L to "999 B",
1000L to "1.0 KB",
1100L to "1.1 KB",
(1000L * 1000) - 1 to "1000.0 KB",
1000L * 1000 to "1.0 MB",
10L * 1000 * 1000 to "10.0 MB",
1000L * 1000 * 1000 to "1.0 GB",
2L * 1000 * 1000 * 1000 to "2.0 GB",
1000L * 1000 * 1000 * 1000 to "1.0 TB",
2L * 1000 * 1000 * 1000 * 1000 to "2.0 TB"
).forEach { (bytes, expectedBytesDisplay) ->
given("$bytes have been downloaded so far") {
val progress = DockerImageProgress("Downloading", bytes, 100)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("formats the progress in the expected style") {
assertThat(display, startsWith("Downloading: $expectedBytesDisplay of 100 B ("))
}
}
}
given("$bytes need to be downloaded in total") {
val progress = DockerImageProgress("Downloading", 100, bytes)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("formats the progress in the expected style") {
assertThat(display, startsWith("Downloading: 100 B of $expectedBytesDisplay ("))
}
}
}
}
}
})
| app/src/unitTest/kotlin/batect/docker/pull/DockerImageProgressSpec.kt | 1620098864 |
package data.tinder.recommendation
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 android.arch.persistence.room.Transaction
@Dao
internal interface RecommendationUserPhotoDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertPhoto(photo: RecommendationUserPhotoEntity)
@Query("SELECT * from RecommendationUserPhotoEntity WHERE id=:id")
@Transaction
fun selectPhotoById(id: String): List<RecommendationUserPhotoWithRelatives>
}
| data/src/main/kotlin/data/tinder/recommendation/RecommendationUserPhotoDao.kt | 3124876834 |
package com.blok
import com.blok.Common.Infrastructure.HTTP.ErrorPayload
import com.blok.Common.Infrastructure.toJson
import com.blok.common.Bus.CommandBus
import com.blok.common.Bus.QueryBus
import com.blok.handlers.RequestPayload.NoPayload
import com.blok.model.AbstractRepository
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import org.apache.http.HttpStatus
import spark.Request
import spark.Response
import spark.Route
import java.util.logging.Logger
abstract class BusRequestHandler<V : Any, B: Any>(private val valueClass: Class<V>, open protected val bus: B) : RequestHandler<V>, Route {
private val logger = Logger.getLogger(this.javaClass.canonicalName)
override fun process(value: V, urlParams: Map<String, String>, shouldReturnHtml: Boolean): Answer {
return try {
processImpl(value, urlParams, shouldReturnHtml)
} catch (e: IllegalArgumentException) {
Answer.badRequest(ErrorPayload("Exception: ${e.javaClass.canonicalName}: ${e.message}").toJson())
} catch (e: AbstractRepository.NotFound) {
Answer.notFound(ErrorPayload("Exception: ${e.javaClass.canonicalName}: ${e.message}").toJson())
}
}
protected abstract fun processImpl(value: V, urlParams: Map<String, String>, shouldReturnHtml: Boolean): Answer
@Throws(Exception::class)
override fun handle(request: Request, response: Response): String? {
try {
var value: V = castPayload(request)
val urlParams = request.params()
val answer = process(value, urlParams, shouldReturnHtml(request))
response.status(answer.code)
response.type(getRequestType(request))
response.body(answer.body)
return answer.body?: ""
} catch (e: JsonSyntaxException) {
val payload = ErrorPayload( "Bad request: [${request.url()}]" +
"[${request.body()}]" +
"[Message: ${e.message}]" +
"[${e.printStackTrace()}]")
logger.finer(payload.message)
response.status(HttpStatus.SC_BAD_REQUEST)
response.body(payload.toJson())
return payload.toJson()
} catch (e: Throwable) {
val payload = ErrorPayload("Internal server error: [${request.url()}]" +
"[${request.body()}]" +
"[Message: ${e.message}]" +
"[${e.printStackTrace()}]")
logger.severe(payload.message)
response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
response.body(payload.toJson())
return payload.toJson()
}
}
private fun getRequestType(request: Request): String {
return if (shouldReturnHtml(request)) {
"text/html"
} else {
"application/json"
}
}
private fun castPayload(request: Request): V {
return if (valueClass != NoPayload::class.java) {
Gson().fromJson(request.body(), valueClass)
} else NoPayload() as V
}
companion object {
private fun shouldReturnHtml(request: Request): Boolean {
val accept = request.headers("Accept")
return accept != null && accept.contains("text/html")
}
}
}
abstract class CommandRequestHandler<V : Any>(valueClass: Class<V>, override val bus: CommandBus): BusRequestHandler<V, CommandBus>(valueClass, bus)
abstract class QueryRequestHandler<V : Any>(valueClass: Class<V>, override val bus: QueryBus): BusRequestHandler<V, QueryBus>(valueClass, bus) | apps/Api/src/main/kotlin/com/blok/Common/Infrastructure/HTTP/BusRequestHandler.kt | 3641089806 |
package pl.gumyns.java_code_generator.model
import com.google.gson.annotations.SerializedName
data class ClassDef(
@SerializedName("class") val name: String,
@SerializedName("vars") val variables: List<VariableDef>
) | src/main/kotlin/pl/gumyns/java_code_generator/model/ClassDef.kt | 2851807850 |
package com.antyzero.cardcheck
import android.app.Application
import android.test.ApplicationTestCase
import junit.framework.Assert
import org.junit.Test
class ApplicationTest : ApplicationTestCase<Application>(Application::class.java) {
@Test
fun testDumb() {
Assert.assertTrue(true)
}
} | app/src/androidTest/kotlin/com/antyzero/cardcheck/ApplicationTest.kt | 4224400261 |
package nerd.tuxmobil.fahrplan.congress.schedule
import com.google.common.truth.Truth.assertThat
import info.metadude.android.eventfahrplan.commons.temporal.Moment
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.threeten.bp.OffsetDateTime
import java.util.TimeZone
@RunWith(Parameterized::class)
class TimeSegmentFormattedTextTest(
private val minutesOfTheDay: Int,
private val expectedFormattedText: String
) {
companion object {
val DEFAULT_TIME_ZONE: TimeZone = TimeZone.getTimeZone("GMT+1")
private fun scenarioOf(minutesOfTheDay: Int, expectedFormattedText: String) =
arrayOf(minutesOfTheDay, expectedFormattedText)
@JvmStatic
@Parameterized.Parameters(name = "{index}: minutes = {0} -> formattedText = {1}")
fun data() = listOf(
scenarioOf(minutesOfTheDay = 0, expectedFormattedText = "01:00"),
scenarioOf(minutesOfTheDay = 1, expectedFormattedText = "01:00"),
scenarioOf(minutesOfTheDay = 2, expectedFormattedText = "01:00"),
scenarioOf(minutesOfTheDay = 3, expectedFormattedText = "01:00"),
scenarioOf(minutesOfTheDay = 4, expectedFormattedText = "01:00"),
scenarioOf(minutesOfTheDay = 5, expectedFormattedText = "01:05"),
scenarioOf(minutesOfTheDay = 6, expectedFormattedText = "01:05"),
scenarioOf(minutesOfTheDay = 7, expectedFormattedText = "01:05"),
scenarioOf(minutesOfTheDay = 8, expectedFormattedText = "01:05"),
scenarioOf(minutesOfTheDay = 9, expectedFormattedText = "01:05"),
scenarioOf(minutesOfTheDay = 10, expectedFormattedText = "01:10"),
scenarioOf(minutesOfTheDay = 120, expectedFormattedText = "03:00"),
scenarioOf(minutesOfTheDay = 660, expectedFormattedText = "12:00"),
scenarioOf(minutesOfTheDay = 1425, expectedFormattedText = "00:45")
)
}
@Test
fun formattedText() {
TimeZone.setDefault(DEFAULT_TIME_ZONE)
val zoneOffsetNow = OffsetDateTime.now().offset
val moment = Moment.now().startOfDay().plusMinutes(minutesOfTheDay.toLong())
val segment = TimeSegment.ofMoment(moment)
assertThat(segment.getFormattedText(zoneOffsetNow, useDeviceTimeZone = false)).isEqualTo(expectedFormattedText)
}
}
| app/src/test/java/nerd/tuxmobil/fahrplan/congress/schedule/TimeSegmentFormattedTextTest.kt | 774564913 |
package org.jonnyzzz.kotlin.xml.bind.jdom.impl
import kotlin.reflect.full.declaredMemberProperties
internal fun <T : Any> Class<T>.declaredPropertyNames(): Set<String> {
return this.kotlin.declaredMemberProperties.map { x -> x.name }.toSortedSet()
}
internal fun <T : Any, Y : Any> T.delegatedProperties(propertyDelegate: Class<Y>): List<Y> = scan(propertyDelegate, this)
private fun <T : Any, Y : Any> scan(propertyDelegate: Class<Y>, obj: T, clazz: Class<T> = obj.javaClass): List<Y> {
val names = clazz.declaredPropertyNames()
val declaredFields = arrayListOf<Y>()
for (it in clazz.declaredFields) {
val name = it.name ?: continue
if (!name.endsWith("\$delegate")) continue
if (!names.contains(name.split('$').first())) continue
it.type ?: continue
it.isAccessible = true
val value = it.get(obj)
if (!propertyDelegate.isInstance(value)) continue
declaredFields.add(propertyDelegate.cast(value)!!)
}
val sup = clazz.getSuperclass()
if (sup != null && sup != Any::class.java) {
return declaredFields + scan<Any, Y>(propertyDelegate, obj, sup as Class<Any>)
} else {
return declaredFields
}
}
| jdom/src/main/kotlin/org/jonnyzzz/kotlin/xml/bind/jdom/impl/XProperties.kt | 1322889239 |
/*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.codeInsight.template.context
import com.intellij.codeInsight.template.TemplateContextType
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiUtilCore
import com.tang.intellij.lua.comment.LuaCommentUtil
import com.tang.intellij.lua.lang.LuaFileType
import com.tang.intellij.lua.lang.LuaLanguage
import com.tang.intellij.lua.psi.LuaTypes
/**
* Created by tangzx on 2017/2/11.
*/
class LuaCodeContextType : TemplateContextType("LUA_CODE", "Lua") {
override fun isInContext(file: PsiFile, offset: Int): Boolean {
if (PsiUtilCore.getLanguageAtOffset(file, offset).isKindOf(LuaLanguage.INSTANCE)) {
val element = file.findElementAt(offset)
if (element == null || element is PsiWhiteSpace || LuaCommentUtil.isComment(element)) {
return false
}
if (element.node.elementType in arrayOf(LuaTypes.STRING, LuaTypes.NUMBER)) {
return false
}
}
return file.fileType === LuaFileType.INSTANCE
}
}
| src/main/java/com/tang/intellij/lua/codeInsight/template/context/LuaCodeContextType.kt | 3381651179 |
package org.wordpress.aztec.spans
import android.content.Context
import android.graphics.drawable.Drawable
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.AztecText
import java.lang.ref.WeakReference
class AztecHorizontalRuleSpan(context: Context, drawable: Drawable, override var nestingLevel: Int,
override var attributes: AztecAttributes = AztecAttributes(), editor: AztecText? = null) :
AztecDynamicImageSpan(context, drawable), IAztecFullWidthImageSpan, IAztecSpan {
init {
textView = WeakReference(editor)
}
override val TAG: String = "hr"
}
| aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecHorizontalRuleSpan.kt | 4181523273 |
/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.vk.api.sdk.utils
import androidx.annotation.WorkerThread
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.min
/**
* @property minDelayMs
* @property maxDelayMs
* @property factor [onError] will multiply delay by this factor
* @property criticalFactor [onCriticalError] will multiply delay by this factor
* @property jitter
*/
open class ExponentialBackoff(
private val minDelayMs: Long = TimeUnit.MILLISECONDS.toMillis(100),
private val maxDelayMs: Long = TimeUnit.MINUTES.toMillis(5),
private val factor: Float = 2f,
private val criticalFactor: Float = 5f,
private val jitter: Float = 0.1f
) {
private val random = Random(System.currentTimeMillis())
@Volatile
var delayMs = minDelayMs
private set
@Volatile
var errorsCount = 0
private set
fun shouldWait() = errorsCount > 0
@WorkerThread
fun waitIfNeeded() {
if (shouldWait()) {
Thread.sleep(delayMs)
}
}
fun reset() {
delayMs = minDelayMs
errorsCount = 0
}
fun onError() = increase(factor)
fun onCriticalError() = increase(criticalFactor)
private fun increase(factor: Float) {
delayMs = min(delayMs * factor, maxDelayMs.toFloat()).toLong()
delayMs += variance(delayMs * jitter)
errorsCount++
}
private fun variance(std: Float) = (random.nextGaussian() * std).toLong()
companion object {
@JvmStatic
fun forNetworkWait() = ExponentialBackoff(minDelayMs = 500, maxDelayMs = 60000, factor = 1.5f)
}
} | core/src/main/java/com/vk/api/sdk/utils/ExponentialBackoff.kt | 3116116831 |
package org.jetbrains.bio
import com.google.common.base.Stopwatch
import com.google.common.collect.Iterators
import com.google.common.collect.UnmodifiableIterator
import com.google.common.math.IntMath
import com.google.common.math.LongMath
import org.slf4j.Logger
import java.io.BufferedReader
import java.math.RoundingMode
import java.nio.file.Files
import java.nio.file.OpenOption
import java.nio.file.Path
import java.util.zip.GZIPInputStream
import java.util.zip.ZipInputStream
import kotlin.reflect.KProperty
/**
* Various internal helpers.
*
* You shouldn't be using them outside of `big`.
*/
internal infix fun Int.divCeiling(other: Int): Int {
return IntMath.divide(this, other, RoundingMode.CEILING)
}
internal infix fun Long.divCeiling(other: Long): Long {
return LongMath.divide(this, other, RoundingMode.CEILING)
}
/**
* Computes the value n such that base^n <= this.
*/
internal infix fun Int.logCeiling(base: Int): Int {
require(this > 0) { "non-positive number" }
require(base > 1) { "base must be >1" }
var rem = this
var acc = 1
while (rem > base) {
rem = rem divCeiling base
acc++
}
return acc
}
internal inline fun <T> Logger.time(message: String, block: () -> T): T {
debug(message)
val stopwatch = Stopwatch.createStarted()
val res = block()
stopwatch.stop()
debug("Done in $stopwatch")
return res
}
/** A function which simply ignores a given [_value]. */
@Suppress("UNUSED_PARAMETER")
internal fun ignore(_value: Any?) {}
internal operator fun <T> ThreadLocal<T>.getValue(thisRef: Any?, property: KProperty<*>) = get()
internal operator fun <T> ThreadLocal<T>.setValue(thisRef: Any?, property: KProperty<*>, value: T) = set(value)
// XXX calling the 'Iterable<T>#map' leads to boxing.
internal inline fun <R> IntProgression.mapUnboxed(
crossinline transform: (Int) -> R): Sequence<R> {
val it = iterator()
return object : Iterator<R> {
override fun next() = transform(it.nextInt())
override fun hasNext() = it.hasNext()
}.asSequence()
}
internal abstract class CachingIterator<T>(reader: BufferedReader) : UnmodifiableIterator<T>() {
protected var lines = Iterators.peekingIterator(reader.lines().iterator())!!
private var cached: T? = null
override fun hasNext(): Boolean {
if (cached == null) {
cached = cache() // Got some?
}
return cached != null
}
override fun next(): T? {
check(hasNext())
val next = cached
cached = null
return next
}
protected abstract fun cache(): T?
}
/**
* Lazily groups elements of the sequence into sub-sequences based
* on the values produced by the key function [f].
*
* The user is responsible for consuming the resulting sub-sequences
* *in order*. Otherwise the implementation might yield unexpected
* results.
*
* No assumptions are made about the monotonicity of [f].
*/
internal fun <T : Any, K> Sequence<T>.groupingBy(f: (T) -> K): Sequence<Pair<K, Sequence<T>>> {
return Sequence {
object : Iterator<Pair<K, Sequence<T>>> {
private var cached: K? = null
private val it = Iterators.peekingIterator([email protected]())
override fun hasNext() = it.hasNext()
override fun next(): Pair<K, Sequence<T>> {
val target = f(it.peek())
assert(cached == null || cached != target) {
"group (key: $target) was not consumed fully"
}
cached = target
return target to generateSequence {
if (it.hasNext() && f(it.peek()) == cached) {
it.next()
} else {
null
}
}
}
}
}
}
internal fun Path.bufferedReader(vararg options: OpenOption): BufferedReader {
val inputStream = Files.newInputStream(this, *options).buffered()
return when (toFile().extension) {
"gz" -> GZIPInputStream(inputStream)
"zip" ->
// This only works for single-entry ZIP files.
ZipInputStream(inputStream).apply { nextEntry }
else -> inputStream
}.bufferedReader()
}
| src/main/kotlin/org/jetbrains/bio/Support.kt | 3281449085 |
package eu.kanade.tachiyomi.extension.en.mangareadorg
import eu.kanade.tachiyomi.multisrc.madara.Madara
import java.text.SimpleDateFormat
import java.util.Locale
class MangaReadOrg : Madara("MangaRead.org", "https://www.mangaread.org", "en", SimpleDateFormat("dd.MM.yyy", Locale.US))
| multisrc/overrides/madara/mangareadorg/src/MangaReadOrg.kt | 2832427883 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.friends.dto
import com.google.gson.annotations.SerializedName
import kotlin.String
enum class FriendsGetSuggestionsNameCase(
val value: String
) {
@SerializedName("nom")
NOMINATIVE("nom"),
@SerializedName("gen")
GENITIVE("gen"),
@SerializedName("dat")
DATIVE("dat"),
@SerializedName("acc")
ACCUSATIVE("acc"),
@SerializedName("ins")
INSTRUMENTAL("ins"),
@SerializedName("abl")
PREPOSITIONAL("abl");
}
| api/src/main/java/com/vk/sdk/api/friends/dto/FriendsGetSuggestionsNameCase.kt | 1151685888 |
package com.jtransc.examples.tictactoe
import jtransc.game.JTranscGame
object TicTacToeGdx {
@JvmStatic fun main(args: Array<String>) {
JTranscLibgdx.init()
TicTacToe.main(args)
}
}
object TicTacToeTransc {
@JvmStatic fun main(args: Array<String>) {
JTranscLime.init()
TicTacToe.main(args)
}
}
object TicTacToe {
@JvmStatic fun main(args: Array<String>) {
JTranscGame.init(512, 512) { game ->
val ingameScene = IngameController(Views.Ingame(GameAssets(game)))
ingameScene.start()
game.root.addChild(ingameScene.ingameView)
}
}
} | JTranscDemo/src/com/jtransc/examples/tictactoe/main.kt | 2799364172 |
package org.xdty.callerinfo.settings.dialog
import android.content.Context
import android.content.SharedPreferences
import android.text.InputType
import android.view.View
import android.widget.EditText
import org.xdty.callerinfo.R
class EditDialog(context: Context, sharedPreferences: SharedPreferences) : SettingsDialog(context, sharedPreferences) {
private lateinit var editText: EditText
override fun bindViews() {
val layout = View.inflate(context, R.layout.dialog_edit, null)
builder.setView(layout)
editText = layout.findViewById(R.id.text)
if (defaultText > 0) {
editText.setText(sharedPrefs.getString(key, context.getString(defaultText)))
} else {
editText.setText(sharedPrefs.getString(key, ""))
}
editText.setInputType(InputType.TYPE_CLASS_TEXT)
if (hint > 0) {
editText.setHint(hint)
}
}
override fun onConfirm() {
var value = editText.text.toString()
if (value.isEmpty() && defaultText != 0) {
value = context.getString(defaultText)
}
val editor = sharedPrefs.edit()
editor.putString(key, value)
editor.apply()
super.onConfirm(value)
}
} | app/src/main/java/org/xdty/callerinfo/settings/dialog/EditDialog.kt | 2824996990 |
/*
* Copyright (C) 2016-2017, 2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xquery.psi.impl.plugin
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement
import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginBooleanConstructor
class PluginBooleanConstructorPsiImpl(node: ASTNode) :
ASTWrapperPsiElement(node), PluginBooleanConstructor, XpmSyntaxValidationElement {
override val expressionElement: PsiElement
get() = this
override val conformanceElement: PsiElement
get() = firstChild
}
| src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/plugin/PluginBooleanConstructorPsiImpl.kt | 3934216506 |
package com.themovielist.injector.components
import com.themovielist.PopularMovieApplication
import com.themovielist.injector.modules.ApplicationModule
import javax.inject.Singleton
import dagger.Component
import retrofit2.Retrofit
@Singleton
@Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent {
fun retrofit(): Retrofit
fun popularMovieApplicationContext(): PopularMovieApplication
}
| app/src/main/java/com/themovielist/injector/components/ApplicationComponent.kt | 3708161363 |
package org.stepik.android.view.injection.course_list.visited
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class CourseListVisitedScope | app/src/main/java/org/stepik/android/view/injection/course_list/visited/CourseListVisitedScope.kt | 2652673256 |
fun foo() = println("foo")
fun bar() = println("bar")
inline fun baz(x: Unit = foo(), y: Unit) {}
fun main(args: Array<String>) {
baz(y = bar())
}
| backend.native/tests/codegen/inline/inline24.kt | 1122533612 |
package me.mkweb.releasr.model.mapper
interface Mapper<Entity, Dto> {
fun toDto(entity: Entity): Dto
fun fromDto(dto: Dto): Entity
} | backend/src/main/kotlin/me/mkweb/releasr/model/mapper/Mapper.kt | 2313666094 |
package me.liuqingwen.android.projectandroidtest.data
import android.support.annotation.VisibleForTesting
/**
* Created by Qingwen on 2018-5-31, project: ProjectAndroidTest.
*
* @Author: Qingwen
* @DateTime: 2018-5-31
* @Package: me.liuqingwen.android.projectandroidtest.data in project: ProjectAndroidTest
*
* Notice: If you are using this class or file, check it and do some modification.
*/
class InMemoryNotesRepository(private val serviceApi: INotesServiceApi) : INotesRepository
{
@VisibleForTesting
private val cachedNotes by lazy(LazyThreadSafetyMode.NONE) { mutableListOf<Note>() }
override fun getNotes(callback: (List<Note>) -> Unit)
{
if (this.cachedNotes.isEmpty())
{
this.serviceApi.getAllNotes{
this.cachedNotes.addAll(it)
callback(this.cachedNotes)
}
}
else
{
callback(this.cachedNotes)
}
}
override fun getNote(noteId: Int, callback: (Note?) -> Unit)
{
this.serviceApi.getNote(noteId, callback)
}
override fun saveNote(note: Note, callback: (Boolean) -> Unit)
{
this.serviceApi.saveNote(note, callback)
this.refreshData()
}
override fun refreshData()
{
this.cachedNotes.clear()
}
} | ProjectAndroidTest/app/src/main/java/me/liuqingwen/android/projectandroidtest/data/InMemoryNotesRepository.kt | 4050951940 |
package net.zdendukmonarezio.takuzu.domain.game.models.game
/**
* Created by samuelkodytek on 06/03/2017.
*/
enum class Field{
BLUE, RED, ANON
} | app/src/main/java/net/zdendukmonarezio/takuzu/domain/game/models/board/Field.kt | 1942874714 |
// Copyright 2015-07-03 PlanBase Inc. & Glen Peterson
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.organicdesign.testUtils
/**
* Tests Reflexive, Symmetric, Transitive, Consistent, and non-nullity properties of the equals()
* contract. If you think this is confusing, realize that there is no way to implement a
* one-sided equals() correctly with inheritance - it's a broken concept, but it's still used so
* often that you have to do your best with it.
*
* I got the idea of contract-based testing from watching Bill Venners:
* https://www.youtube.com/watch?v=bCTZQi2dpl8
*/
object EqualsContract {
/**
* Apply the given function against all unique pairings of items in the list. Does this belong on Function2 instead
* of List?
*/
@JvmStatic
fun <T> permutations(
items: List<T>,
f: (T, T) -> Any?) {
for (i in items.indices) {
for (j in i + 1 until items.size) {
f.invoke(items[i], items[j])
}
}
}
/**
* Tests Reflexive, Symmetric, Transitive, Consistent, and non-nullity properties of the equals()
* contract. See note in class documentation.
*
* @param equiv1 First equivalent (but unique) object
* @param equiv2 Second equivalent (but unique) object (could be a different class)
* @param equiv3 Third equivalent (but unique) object (could be a different class)
* @param different Non-equivalent object with a (maybe) different hashCode (should be an otherwise compatible class)
* @param requireDistinctHashes if true, require that the fourth object have a different hashCode. Otherwise,
* require that it have the same hashCode.
* @param <S> The super-class of all these objects - an interface or super-class within which they should be equal.
</S> */
@JvmStatic
fun equalsHashCode(
equiv1: Any,
equiv2: Any,
equiv3: Any,
different: Any,
requireDistinctHashes: Boolean
) {
require(!(equiv1 === equiv2 ||
equiv1 === equiv3 ||
equiv1 === different ||
equiv2 === equiv3 ||
equiv2 === different ||
equiv3 === different)) { "You must provide four different (having different memory locations) but 3 equivalent objects" }
val equivs: List<Any> = listOf(equiv1, equiv2, equiv3)
if (different.equals(null)) {
throw AssertionError("The different param should not allow itself to equal null")
}
if (different.hashCode() != different.hashCode()) {
throw AssertionError("The different param must have the same hashCode as itself")
}
if (!different.equals(different)) {
throw AssertionError("The different param must equal itself")
}
var i = 0
// Reflexive
for (equiv in equivs) {
i++
if (equiv.hashCode() != equiv.hashCode()) {
throw AssertionError("Param $i must have the same hashCode as itself")
}
if (requireDistinctHashes) {
if (equiv.hashCode() == different.hashCode()) {
throw AssertionError("The hashCode of param " + i + " must not equal the" +
" hashCode of the different param. If you meant to do that, use equalsSameHashCode()" +
" instead.")
}
} else {
if (equiv.hashCode() != different.hashCode()) {
throw AssertionError("The hashCode of param " + i + " must equal the" +
" hashCode of the different param If you meant to do that, use equalsDistinctHashCode()" +
" instead.")
}
}
if (!equiv.equals(equiv)) {
throw AssertionError("Param $i must be equal to itself")
}
if (equiv.equals(different)) {
throw AssertionError("Param $i cannot be equal to the different param")
}
if (different.equals(equiv)) {
throw AssertionError("The different param cannot be equal to param $i")
}
// Check null
if (equiv.equals(null)) {
throw AssertionError("Param $i cannot allow itself to equal null")
}
}
// Symmetric (effectively covers Transitive as well)
permutations(equivs) { a: Any, b: Any ->
if (a.hashCode() != b.hashCode()) {
throw AssertionError("Found an unequal hashCode while inspecting permutations: a=$a b=$b")
}
if (!a.equals(b)) {
throw AssertionError("Failed equals while inspecting permutations: a=$a b=$b")
}
if (!b.equals(a)) {
throw AssertionError("Failed reflexive equals while inspecting permutations: a=$a b=$b")
}
}
}
/**
* Tests Reflexive, Symmetric, Transitive, Consistent, and non-nullity properties of the equals()
* contract. See note in class documentation.
*
* @param equiv1 First equivalent (but unique) object
* @param equiv2 Second equivalent (but unique) object (could be a different class)
* @param equiv3 Third equivalent (but unique) object (could be a different class)
* @param different Non-equivalent object with the same hashCode as the previous three
* @param <S> The super-class of all these objects - an interface or super-class within which they should be equal.
</S> */
@JvmStatic
fun equalsSameHashCode(
equiv1: Any,
equiv2: Any,
equiv3: Any,
different: Any
) {
equalsHashCode(equiv1, equiv2, equiv3, different, false)
}
/**
* Tests Reflexive, Symmetric, Transitive, Consistent, and non-nullity properties of the equals()
* contract. See note in class documentation.
*
* @param equiv1 First equivalent (but unique) object
* @param equiv2 Second equivalent (but unique) object (could be a different class)
* @param equiv3 Third equivalent (but unique) object (could be a different class)
* @param different Non-equivalent object with a different hashCode (should be an otherwise compatible class)
* @param <S> The super-class of all these objects - an interface or super-class within which they should be equal.
</S> */
@JvmStatic
fun equalsDistinctHashCode(
equiv1: Any,
equiv2: Any,
equiv3: Any,
different: Any
) {
equalsHashCode(equiv1, equiv2, equiv3, different, true)
}
} | src/main/java/org/organicdesign/testUtils/EqualsContract.kt | 3139886396 |
package promitech.colonization.screen.debug
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.ui.TextField
import com.badlogic.gdx.utils.Align
import net.sf.freecol.common.model.Tile
import promitech.colonization.screen.map.hud.GUIGameController
import promitech.colonization.screen.map.hud.GUIGameModel
import promitech.colonization.GameResources
import promitech.colonization.ui.ClosableDialog
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.badlogic.gdx.Input.Keys
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.InputEvent
import net.sf.freecol.common.model.map.generator.MapGenerator
import net.sf.freecol.common.model.UnitIterator
import net.sf.freecol.common.model.Unit
import promitech.colonization.DI
class DebugConsole(val commands : Commands)
: ClosableDialog<DebugConsole>(), ConsoleOutput
{
private val dialogLayout = Table()
private val textField = TextField("", GameResources.instance.getUiSkin())
private val label = Label("", GameResources.instance.getUiSkin())
private val scrollPane = ScrollPane(label)
var keepOpenConsoleAfterExecute : Boolean = false
init {
label.setAlignment(Align.top or Align.left);
//label.setFillParent(true)
scrollPane.setForceScroll(false, false)
scrollPane.setFadeScrollBars(false)
scrollPane.setOverscroll(true, true)
scrollPane.setScrollBarPositions(false, true)
dialogLayout.add(scrollPane).expand().fill().row()
dialogLayout.add(textField).fillX().expandX()
getContentTable().add(dialogLayout)
dialog.addListener(object : InputListener() {
override fun keyDown(event: InputEvent, keycode: Int) : Boolean {
if (keycode == Keys.ENTER) {
executeCommand()
return true
}
if (keycode == Keys.TAB) {
hintCommand()
return true
}
return false
}
})
withHidingOnEsc();
}
fun executeCommand() {
var cmd = textField.getText()
textField.setText("")
out(cmd)
val executedCmd = commands.execute(cmd)
if (executedCmd != null && !keepOpenConsoleAfterExecute) {
hideWithFade()
}
keepOpenConsoleAfterExecute = false
}
fun hintCommand() {
var enteredCmd = textField.getText();
out(" hints: ")
val filteredCommands = commands.filterCommandsByPrefix(enteredCmd)
filteredCommands.forEach { cmdName ->
out(cmdName)
}
var enlargedCommand = commands.enlargeHintCommandToBetterMatch(enteredCmd)
textField.setText(enlargedCommand)
if (filteredCommands.size == 1) {
textField.setText(textField.getText() + " ")
}
textField.setCursorPosition(textField.getText().length)
}
override fun out(line: String) : ConsoleOutput {
if (label.getText().toString().equals("")) {
label.setText(line)
} else {
label.setText(label.getText().toString() + "\n" + line)
}
scrollPane.setScrollPercentY(100f)
scrollPane.layout()
return this
}
override fun keepOpen() : ConsoleOutput {
keepOpenConsoleAfterExecute = true
return this
}
override fun show(stage: Stage) {
getContentTable().getCell(dialogLayout)
.width(stage.getWidth() * 0.75f)
.height(stage.getHeight() * 0.75f)
super.show(stage)
stage.setKeyboardFocus(textField)
}
}
| core/src/promitech/colonization/screen/debug/DebugConsole.kt | 3590202288 |
package info.nightscout.androidaps.plugin.general.openhumans.ui
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.view.ContextThemeWrapper
import androidx.lifecycle.LiveData
import com.google.android.material.button.MaterialButton
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.plugin.general.openhumans.R
import info.nightscout.androidaps.plugin.general.openhumans.OpenHumansState
import info.nightscout.androidaps.plugin.general.openhumans.OpenHumansUploader
import javax.inject.Inject
class OHFragment : DaggerFragment() {
@Inject
internal lateinit var stateLiveData: LiveData<OpenHumansState?>
@Inject
internal lateinit var plugin: OpenHumansUploader
private lateinit var setup: MaterialButton
private lateinit var logout: MaterialButton
private lateinit var uploadNow: MaterialButton
private lateinit var info: TextView
private lateinit var memberId: TextView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val contextWrapper = ContextThemeWrapper(requireActivity(), R.style.OpenHumans)
val wrappedInflater = inflater.cloneInContext(contextWrapper)
val view = wrappedInflater.inflate(R.layout.fragment_open_humans_new, container, false)
setup = view.findViewById(R.id.setup)
setup.setOnClickListener { startActivity(Intent(context, OHLoginActivity::class.java)) }
logout = view.findViewById(R.id.logout)
logout.setOnClickListener { plugin.logout() }
info = view.findViewById(R.id.info)
memberId = view.findViewById(R.id.member_id)
uploadNow = view.findViewById(R.id.upload_now)
uploadNow.setOnClickListener { plugin.uploadNow() }
return view
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
stateLiveData.observe(this) { state ->
if (state == null) {
setup.visibility = View.VISIBLE
logout.visibility = View.GONE
memberId.visibility = View.GONE
uploadNow.visibility = View.GONE
info.setText(R.string.not_setup_info)
} else {
setup.visibility = View.GONE
logout.visibility = View.VISIBLE
memberId.visibility = View.VISIBLE
uploadNow.visibility = View.VISIBLE
memberId.text = getString(R.string.project_member_id, state.projectMemberId)
info.setText(R.string.setup_completed_info)
}
}
}
} | openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/ui/OHFragment.kt | 2471139526 |
package br.com.maiconhellmann.pomodoro.data.local
import android.content.ContentValues
import br.com.maiconhellmann.pomodoro.data.model.Pomodoro
import br.com.maiconhellmann.pomodoro.data.model.PomodoroStatus
import com.squareup.sqlbrite.BriteDatabase
import rx.Emitter
import rx.Observable
import timber.log.Timber
import java.sql.SQLException
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DatabaseHelper
@Inject constructor(val db: BriteDatabase) {
fun findAllPomodoro(): Observable<List<Pomodoro>>{
return db.createQuery(Db.PomodoroTable.TABLE_NAME,
"SELECT * FROM ${Db.PomodoroTable.TABLE_NAME}")
.mapToList<Pomodoro> {
Db.PomodoroTable.parseCursor(it)
}
}
fun savePomodoro(pomodoro: Pomodoro): Observable<Pomodoro> {
return Observable.create<Pomodoro>({emitter ->
val transaction = db.newTransaction()
try{
if(pomodoro.id != 0L){
db.update(Db.PomodoroTable.TABLE_NAME,
Db.PomodoroTable.toContentValues(pomodoro),
Db.PomodoroTable.COLUMN_ID+ " = ?",
pomodoro.id.toString())
}else{
val id = db.insert(Db.PomodoroTable.TABLE_NAME, Db.PomodoroTable.toContentValues(pomodoro))
pomodoro.id = id
}
transaction.markSuccessful()
emitter.onNext(pomodoro)
} catch (exception: SQLException) {
Timber.e(exception)
emitter.onError(exception)
}
transaction.end()
}, Emitter.BackpressureMode.BUFFER )
}
fun findRunningPomodoro(): Observable<Pomodoro>{
val sql = "SELECT * FROM ${Db.PomodoroTable.TABLE_NAME} " +
"where ${Db.PomodoroTable.COLUMN_STATUS} = ? " +
"order by ${Db.PomodoroTable.COLUMN_ID} desc " +
"limit 1 "
var cursor = db.createQuery(Db.PomodoroTable.TABLE_NAME, sql, PomodoroStatus.RUNNING.id.toString())
return cursor.mapToOne{Db.PomodoroTable.parseCursor(it)}
}
fun stopRunningPomodoro(pomodoro: Pomodoro): Observable<Unit>{
return Observable.create<Unit>({emitter ->
val transaction = db.newTransaction()
try{
val cv = ContentValues()
cv.put(Db.PomodoroTable.COLUMN_STATUS, PomodoroStatus.STOPPED.id)
cv.put(Db.PomodoroTable.COLUMN_END_TIME, System.currentTimeMillis())
db.update(Db.PomodoroTable.TABLE_NAME, cv,
"${Db.PomodoroTable.COLUMN_ID} =? ",
pomodoro.id.toString())
transaction.markSuccessful()
emitter.onCompleted()
} catch (exception: SQLException) {
Timber.e(exception)
emitter.onError(exception)
}
transaction.end()
}, Emitter.BackpressureMode.BUFFER )
}
}
| app/src/main/kotlin/br/com/maiconhellmann/pomodoro/data/local/DatabaseHelper.kt | 4015764339 |
package br.com.maiconhellmann.pomodoro.util
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import rx.Scheduler
import rx.android.plugins.RxAndroidPlugins
import rx.android.plugins.RxAndroidSchedulersHook
import rx.functions.Func1
import rx.plugins.RxJavaHooks
import rx.schedulers.Schedulers
/**
* This rule registers SchedulerHooks for RxJava and RxAndroid to ensure that subscriptions
* always subscribeOn and observeOn Schedulers.immediate().
* Warning, this rule will reset RxAndroidPlugins and RxJavaPlugins before and after each test so
* if the application code uses RxJava plugins this may affect the behaviour of the testing method.
*/
class RxSchedulersOverrideRule : TestRule {
private val mRxAndroidSchedulersHook = object : RxAndroidSchedulersHook() {
override fun getMainThreadScheduler(): Scheduler {
return Schedulers.immediate()
}
}
private val mRxJavaImmediateScheduler = Func1<Scheduler, Scheduler> { Schedulers.immediate() }
override fun apply(base: Statement, description: Description): Statement {
return object : Statement() {
override fun evaluate() {
RxAndroidPlugins.getInstance().reset()
RxAndroidPlugins.getInstance().registerSchedulersHook(mRxAndroidSchedulersHook)
RxJavaHooks.reset()
RxJavaHooks.setOnIOScheduler(mRxJavaImmediateScheduler)
RxJavaHooks.setOnNewThreadScheduler(mRxJavaImmediateScheduler)
base.evaluate()
RxAndroidPlugins.getInstance().reset()
RxJavaHooks.reset()
}
}
}
}
| app/src/test/java/br/com/maiconhellmann/pomodoro/util/RxSchedulersOverrideRule.kt | 1494939331 |
package pl.droidsonroids.gradle.ci
import com.android.ddmlib.IDevice
class DeviceSetupReverter : DeviceWorker() {
override fun doWork(device: IDevice) {
if (device.version.isGreaterOrEqualThan(17)) {
device.executeRemoteCommand("settings put global window_animation_scale 1")
device.executeRemoteCommand("settings put global transition_animation_scale 1")
device.executeRemoteCommand("settings put global animator_duration_scale 1")
}
device.executeRemoteCommand("su 0 pm enable com.android.browser")
device.executeRemoteCommand("su 0 pm unhide org.chromium.webview_shell")
device.executeRemoteCommand("su 0 pm unhide com.android.chrome")
}
}
| plugin/src/main/kotlin/pl/droidsonroids/gradle/ci/DeviceSetupReverter.kt | 2423418679 |
package info.nightscout.androidaps.plugins.aps.events
import info.nightscout.androidaps.events.EventUpdateGui
class EventOpenAPSUpdateResultGui(val text: String) : EventUpdateGui()
| app/src/main/java/info/nightscout/androidaps/plugins/aps/events/EventOpenAPSUpdateResultGui.kt | 1907764847 |
package com.squareup.wire.kotlin.grpcserver
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.TypeName
import com.squareup.wire.schema.ProtoType
internal class ClassNameGenerator(private val typeToKotlinName: Map<ProtoType, TypeName>) {
fun classNameFor(type: ProtoType, suffix: String = ""): ClassName {
val originalClassName = typeToKotlinName[type]!! as ClassName
return ClassName(
originalClassName.packageName,
"${originalClassName.simpleName}$suffix"
)
}
}
| wire-library/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ClassNameGenerator.kt | 2875229833 |
//
// Copyright (c) 2008-2020 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
package com.github.urho3d.launcher
import com.github.urho3d.UrhoActivity
class MainActivity : UrhoActivity() {
companion object {
const val argument = "argument"
}
private lateinit var arguments: List<String>
override fun getArguments() = arguments.toTypedArray()
override fun onLoadLibrary(libraryNames: MutableList<String>) {
// All runtime shared libraries must always be loaded if available
val regex = Regex("^(?:Urho3D|.+_shared)\$")
libraryNames.retainAll { regex.matches(it) }
// Parse the argument string
val argumentString = intent.getStringExtra(argument)
if (argumentString != null) arguments = argumentString.split(':')
else throw IllegalArgumentException("The MainActivity requires an argument to start")
// Must add the chosen sample library to the last of the list
libraryNames.add(arguments[0])
super.onLoadLibrary(libraryNames)
}
}
| android/launcher-app/src/main/java/com/github/urho3d/launcher/MainActivity.kt | 2881417442 |
package just4fun.holomorph
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.shouldEqual
class TestTemplate: Spek() { init {
given("A") {
on("b") {
it("c") { shouldEqual(0, 0) }
}
}
}
}
| src/test/kotlin/just4fun/holomorph/TestTemplate.kt | 2596557787 |
/*******************************************************************************
* This file is part of Improbable Bot.
*
* Improbable Bot 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.
*
* Improbable Bot 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 Improbable Bot. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package com.joedanpar.improbabot.components.dialog
import com.jagrosh.jdautilities.commons.waiter.EventWaiter
import com.jagrosh.jdautilities.menu.Menu
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.MessageChannel
import net.dv8tion.jda.api.entities.Role
import net.dv8tion.jda.api.entities.User
import java.util.*
import java.util.Arrays.asList
import java.util.concurrent.TimeUnit
open class WizardDialog protected constructor(waiter: EventWaiter, users: Set<User>, roles: Set<Role>, timeout: Long,
unit: TimeUnit) : Menu(waiter, users, roles, timeout, unit) {
protected val dialogs: MutableList<Menu> = LinkedList()
protected var currentMenu = dialogs.listIterator()
protected fun reset() {
currentMenu = dialogs.listIterator()
}
private fun safeReset() {
if (!(currentMenu.hasPrevious() || currentMenu.hasNext())) {
reset()
}
}
override fun display(channel: MessageChannel) {
safeReset()
dialogs[currentMenu.nextIndex()].display(channel)
currentMenu.next()
}
override fun display(message: Message) {
safeReset()
dialogs[currentMenu.nextIndex()].display(message)
currentMenu.next()
}
abstract class Builder<B : Builder<B, D>, D : WizardDialog> : Menu.Builder<B, D>() {
protected val dialogs: MutableList<Menu> = LinkedList()
fun addDialog(dialog: Menu): B {
this.dialogs.add(dialog)
return this as B
}
fun setDialogs(vararg dialogs: Menu): B {
this.dialogs.clear()
this.dialogs.addAll(asList(*dialogs))
return this as B
}
}
}
| src/main/kotlin/com/joedanpar/improbabot/components/dialog/WizardDialog.kt | 27057224 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.mark
data class Jump(var line: Int, val col: Int, var filepath: String)
| vim-engine/src/main/kotlin/com/maddyhome/idea/vim/mark/Jump.kt | 2481340373 |
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package promotion
import jetbrains.buildServer.configs.kotlin.v2019_2.RelativeId
import vcsroots.gradlePromotionMaster
abstract class BasePublishGradleDistribution(
// The branch to be promoted
val promotedBranch: String,
val triggerName: String,
val gitUserName: String = "bot-teamcity",
val gitUserEmail: String = "[email protected]",
val extraParameters: String = "",
vcsRootId: String = gradlePromotionMaster,
cleanCheckout: Boolean = true
) : BasePromotionBuildType(vcsRootId, cleanCheckout) {
init {
artifactRules = """
**/build/git-checkout/subprojects/base-services/build/generated-resources/build-receipt/org/gradle/build-receipt.properties
**/build/distributions/*.zip => promote-build-distributions
**/build/website-checkout/data/releases.xml
**/build/git-checkout/build/reports/integTest/** => distribution-tests
**/smoke-tests/build/reports/tests/** => post-smoke-tests
**/build/version-info.properties => version-info.properties
""".trimIndent()
dependencies {
snapshot(RelativeId("Check_Stage_${[email protected]}_Trigger")) {
synchronizeRevisions = false
}
}
}
}
| .teamcity/src/main/kotlin/promotion/BasePublishGradleDistribution.kt | 2066680069 |
/*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32"
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot.commands.uncategorized
import me.duncte123.botcommons.messaging.MessageConfig
import me.duncte123.botcommons.messaging.MessageUtils
import ml.duncte123.skybot.objects.command.Command
import ml.duncte123.skybot.objects.command.CommandContext
import ml.duncte123.skybot.utils.ModerationUtils
import net.dv8tion.jda.api.Permission
import java.util.concurrent.TimeUnit
class KickMeCommand : Command() {
init {
this.name = "kickme"
this.help = "Kicks you off the server"
}
override fun execute(ctx: CommandContext) {
val prefix = ctx.prefix
val event = ctx.event
val args = ctx.args
val warningMsg = """**WARNING** this command will kick you from this server
|If you are sure that you want to kick yourself off this server use `$prefix$name YESIMSURE`
|By running `$prefix$name YESIMSURE` you agree that you are responsible for the consequences of this command.
|DuncteBot and any of it's developers are not responsible for your own kick by running this command
""".trimMargin()
if (args.isEmpty() || args[0] != "YESIMSURE") {
MessageUtils.sendMsg(ctx, warningMsg)
} else if (args.isNotEmpty() && args[0] == "YESIMSURE") {
// Check for perms
if (event.guild.selfMember.canInteract(ctx.member) && event.guild.selfMember.hasPermission(Permission.KICK_MEMBERS)) {
MessageUtils.sendSuccess(event.message)
// Kick the user
MessageUtils.sendMsg(
MessageConfig.Builder.fromCtx(ctx)
.setMessage("Your kick will commence in 20 seconds")
.setSuccessAction {
it.guild.kick(ctx.member)
.reason("${event.author.asTag} ran the kickme command and got kicked")
.queueAfter(20L, TimeUnit.SECONDS) {
ModerationUtils.modLog(
event.jda.selfUser,
event.author,
"kicked",
"Used the kickme command",
null,
ctx.guild
)
}
}
.build()
)
} else {
MessageUtils.sendMsg(
ctx,
"""I'm missing the permission to kick you.
|You got lucky this time ${ctx.member.asMention}.
""".trimMargin()
)
}
} else {
MessageUtils.sendMsg(ctx, warningMsg)
}
}
}
| src/main/kotlin/ml/duncte123/skybot/commands/uncategorized/KickMeCommand.kt | 2927200874 |
package au.com.dius.pact.core.matchers
import au.com.dius.pact.core.model.matchingrules.MatchingRules
import au.com.dius.pact.core.model.matchingrules.MatchingRulesImpl
import mu.KLogging
import org.atteo.evo.inflector.English
object QueryMatcher : KLogging() {
private fun compare(
parameter: String,
path: List<String>,
expected: String,
actual: String,
matchers: MatchingRules
): List<QueryMismatch> {
return if (Matchers.matcherDefined("query", listOf(parameter), matchers)) {
logger.debug { "compareQueryParameterValues: Matcher defined for query parameter '$parameter'" }
Matchers.domatch(matchers, "query", listOf(parameter), expected, actual, QueryMismatchFactory)
} else {
logger.debug { "compareQueryParameterValues: No matcher defined for query parameter '$parameter', using equality" }
if (expected == actual) {
emptyList()
} else {
listOf(QueryMismatch(parameter, expected, actual, "Expected '$expected' but received '$actual' " +
"for query parameter '$parameter'", parameter))
}
}
}
private fun compareQueryParameterValues(
parameter: String,
expected: List<String>,
actual: List<String>,
path: List<String>,
matchers: MatchingRules
): List<QueryMismatch> {
return expected.mapIndexed { index, value -> index to value }
.flatMap { (index, value) ->
when {
index < actual.size -> compare(parameter, path + index.toString(), value, actual[index], matchers)
!Matchers.matcherDefined("query", path, matchers) ->
listOf(QueryMismatch(parameter, expected.toString(), actual.toString(),
"Expected query parameter '$parameter' with value '$value' but was missing",
path.joinToString(".")))
else -> emptyList()
}
}
}
@JvmStatic
fun compareQuery(
parameter: String,
expected: List<String>,
actual: List<String>,
matchingRules: MatchingRules?
): List<QueryMismatch> {
val path = listOf(parameter)
val matchers = matchingRules ?: MatchingRulesImpl()
return if (Matchers.matcherDefined("query", path, matchers)) {
logger.debug { "compareQuery: Matcher defined for query parameter '$parameter'" }
Matchers.domatch(matchers, "query", path, expected, actual, QueryMismatchFactory) +
compareQueryParameterValues(parameter, expected, actual, path, matchers)
} else {
if (expected.isEmpty() && actual.isNotEmpty()) {
listOf(QueryMismatch(parameter, expected.toString(), actual.toString(),
"Expected an empty parameter List for '$parameter' but received $actual",
path.joinToString(".")))
} else {
val mismatches = mutableListOf<QueryMismatch>()
if (expected.size != actual.size) {
mismatches.add(QueryMismatch(parameter, expected.toString(), actual.toString(),
"Expected query parameter '$parameter' with ${expected.size} " +
"${English.plural("value", expected.size)} but received ${actual.size} " +
English.plural("value", actual.size),
path.joinToString(".")))
}
mismatches + compareQueryParameterValues(parameter, expected, actual, path, matchers)
}
}
}
}
| core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/QueryMatcher.kt | 2942458100 |
package org.wordpress.android.ui.posts.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import androidx.annotation.CallSuper
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.graphics.ColorUtils
import com.google.android.material.elevation.ElevationOverlayProvider
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.ui.posts.AuthorFilterListItemUIState
import org.wordpress.android.ui.posts.AuthorFilterSelection
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.GravatarUtils
import org.wordpress.android.util.extensions.getColorFromAttribute
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.util.image.ImageType.NO_PLACEHOLDER
import javax.inject.Inject
class AuthorSelectionAdapter(context: Context) : BaseAdapter() {
@Inject lateinit var imageManager: ImageManager
@Inject lateinit var uiHelpers: UiHelpers
private val items = mutableListOf<AuthorFilterListItemUIState>()
init {
(context.applicationContext as WordPress).component().inject(this)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
var view: View? = convertView
val holder: DropdownViewHolder
if (view == null) {
val inflater = LayoutInflater.from(parent.context)
view = inflater.inflate(R.layout.author_selection_dropdown, parent, false)
holder = DropdownViewHolder(view)
view.tag = holder
} else {
holder = view.tag as DropdownViewHolder
}
holder.bind(items[position], imageManager, uiHelpers)
return view!!
}
override fun getItemId(position: Int): Long = items[position].id
fun getIndexOfSelection(selection: AuthorFilterSelection): Int? {
for ((index, item) in items.withIndex()) {
if (item.id == selection.id) {
return index
}
}
return null
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var view: View? = convertView
val holder: NormalViewHolder
if (view == null) {
val inflater = LayoutInflater.from(parent.context)
view = inflater.inflate(R.layout.author_selection, parent, false)
holder = NormalViewHolder(view)
view.tag = holder
} else {
holder = view.tag as NormalViewHolder
}
holder.bind(items[position], imageManager, uiHelpers)
return view!!
}
override fun hasStableIds(): Boolean = true
override fun getItem(position: Int): Any = items[position]
override fun getCount(): Int = items.count()
fun updateItems(newItems: List<AuthorFilterListItemUIState>) {
items.clear()
items.addAll(newItems)
notifyDataSetChanged()
}
private open class NormalViewHolder(protected val itemView: View) {
protected val image: AppCompatImageView = itemView.findViewById(R.id.author_selection_image)
@CallSuper
open fun bind(
state: AuthorFilterListItemUIState,
imageManager: ImageManager,
uiHelpers: UiHelpers
) {
/**
* We can't use error/placeholder drawables as it causes an issue described here
* https://github.com/wordpress-mobile/WordPress-Android/issues/9745.
* It seems getView method always returns convertView == null when used with Spinner. When we invoke
* imageManager.load..(url..) in the view holder and the 'url' is empty or the requests fails
* an error/placeholder drawable is used. However, this results in another layout/measure phase
* -> getView(..) is called again. However, since the convertView == null we inflate a new view and
* imageManager.load..(..) is invoked again - this goes on forever.
* In order to prevent this issue we don't use placeholder/error drawables in this case.
* The cost of this solution is that an empty circle is shown if we don't have the avatar in the cache
* and the request fails.
*/
when (state) {
is AuthorFilterListItemUIState.Everyone -> {
imageManager.load(image, state.imageRes)
}
is AuthorFilterListItemUIState.Me -> {
val avatarSize = image.resources.getDimensionPixelSize(R.dimen.avatar_sz_small)
val url = GravatarUtils.fixGravatarUrl(state.avatarUrl, avatarSize)
imageManager.loadIntoCircle(image, NO_PLACEHOLDER, url)
}
}
}
}
private class DropdownViewHolder(itemView: View) : NormalViewHolder(itemView) {
private val text: AppCompatTextView = itemView.findViewById(R.id.author_selection_text)
override fun bind(
state: AuthorFilterListItemUIState,
imageManager: ImageManager,
uiHelpers: UiHelpers
) {
super.bind(state, imageManager, uiHelpers)
val context = itemView.context
// Because it's a custom popup list we need to manage colors of list items manually
val elevationOverlayProvider = ElevationOverlayProvider(context)
val appbarElevation = context.resources.getDimension(R.dimen.appbar_elevation)
val elevatedSurfaceColor = elevationOverlayProvider.compositeOverlayWithThemeSurfaceColorIfNeeded(
appbarElevation
)
val selectedColor = ColorUtils
.setAlphaComponent(
context.getColorFromAttribute(R.attr.colorOnSurface),
context.resources.getInteger(R.integer.custom_popup_selected_list_item_opacity_dec)
)
text.text = uiHelpers.getTextOfUiString(context, state.text)
if (state.isSelected) {
itemView.setBackgroundColor(selectedColor)
} else {
itemView.setBackgroundColor(elevatedSurfaceColor)
}
}
}
}
| WordPress/src/main/java/org/wordpress/android/ui/posts/adapters/AuthorSelectionAdapter.kt | 1643564513 |
package org.wordpress.android.ui.mysite
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.ui.jetpack.JetpackCapabilitiesUseCase
import org.wordpress.android.ui.mysite.MySiteSource.MySiteRefreshSource
import org.wordpress.android.ui.mysite.MySiteUiState.PartialState.JetpackCapabilities
import org.wordpress.android.util.SiteUtils
import javax.inject.Inject
import javax.inject.Named
class ScanAndBackupSource @Inject constructor(
@param:Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher,
private val selectedSiteRepository: SelectedSiteRepository,
private val jetpackCapabilitiesUseCase: JetpackCapabilitiesUseCase
) : MySiteRefreshSource<JetpackCapabilities> {
override val refresh = MutableLiveData(false)
fun clear() {
jetpackCapabilitiesUseCase.clear()
}
override fun build(coroutineScope: CoroutineScope, siteLocalId: Int): LiveData<JetpackCapabilities> {
val result = MediatorLiveData<JetpackCapabilities>()
result.addSource(refresh) { result.refreshData(coroutineScope, siteLocalId, refresh.value) }
refresh()
return result
}
private fun MediatorLiveData<JetpackCapabilities>.refreshData(
coroutineScope: CoroutineScope,
siteLocalId: Int,
isRefresh: Boolean? = null
) {
when (isRefresh) {
null, true -> refreshData(coroutineScope, siteLocalId)
false -> Unit // Do nothing
}
}
private fun MediatorLiveData<JetpackCapabilities>.refreshData(
coroutineScope: CoroutineScope,
siteLocalId: Int
) {
val selectedSite = selectedSiteRepository.getSelectedSite()
if (selectedSite != null && selectedSite.id == siteLocalId) {
coroutineScope.launch(bgDispatcher) {
jetpackCapabilitiesUseCase.getJetpackPurchasedProducts(selectedSite.siteId).collect {
postState(
JetpackCapabilities(
scanAvailable = SiteUtils.isScanEnabled(it.scan, selectedSite),
backupAvailable = it.backup
)
)
}
}
} else {
postState(JetpackCapabilities(scanAvailable = false, backupAvailable = false))
}
}
}
| WordPress/src/main/java/org/wordpress/android/ui/mysite/ScanAndBackupSource.kt | 2614288847 |
package org.wordpress.android.bloggingreminders
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.bloggingreminders.BloggingRemindersSyncAnalyticsTracker.ErrorType
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
class BloggingRemindersSyncAnalyticsTrackerTest {
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper = mock()
private val classToTest = BloggingRemindersSyncAnalyticsTracker(analyticsTrackerWrapper)
@Test
fun `Should track get blogging reminders start correctly`() {
classToTest.trackStart()
verify(analyticsTrackerWrapper).track(Stat.BLOGGING_REMINDERS_SYNC_START)
}
@Test
fun `Should track get blogging reminders success correctly`() {
val remindersSyncedCount = 3
classToTest.trackSuccess(remindersSyncedCount)
verify(analyticsTrackerWrapper).track(
Stat.BLOGGING_REMINDERS_SYNC_SUCCESS, mapOf(REMINDERS_SYNCED_COUNT to remindersSyncedCount)
)
}
@Test
fun `Should track failed with QueryBloggingRemindersError correctly`() {
classToTest.trackFailed(ErrorType.QueryBloggingRemindersError)
verify(analyticsTrackerWrapper).track(
Stat.BLOGGING_REMINDERS_SYNC_FAILED,
mapOf("error_type" to "query_blogging_reminders_error")
)
}
@Test
fun `Should track failed with UpdateBloggingRemindersError correctly`() {
classToTest.trackFailed(ErrorType.UpdateBloggingRemindersError)
verify(analyticsTrackerWrapper).track(
Stat.BLOGGING_REMINDERS_SYNC_FAILED,
mapOf("error_type" to "update_blogging_reminders_error")
)
}
}
| WordPress/src/test/java/org/wordpress/android/bloggingreminders/BloggingRemindersSyncAnalyticsTrackerTest.kt | 50649189 |
class A {
internal fun foo(min: Int) {
for (i in 10 downTo min + 1) {
println(i)
}
}
}
| plugins/kotlin/j2k/old/tests/testData/fileOrElement/for/downTo4.kt | 4279793562 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.script
import com.intellij.ProjectTopics
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.FileTypeIndex
import com.intellij.util.indexing.DumbModeAccessType
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.allScope
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionSourceAsContributor
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.core.script.loadDefinitionsFromTemplatesByPaths
import org.jetbrains.kotlin.scripting.definitions.SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.getEnvironment
import java.io.File
import java.nio.file.Path
import java.util.concurrent.Callable
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.script.experimental.host.ScriptingHostConfiguration
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
class ScriptTemplatesFromDependenciesProvider(private val project: Project) : ScriptDefinitionSourceAsContributor {
private val logger = Logger.getInstance(ScriptTemplatesFromDependenciesProvider::class.java)
override val id = "ScriptTemplatesFromDependenciesProvider"
override fun isReady(): Boolean = _definitions != null
override val definitions: Sequence<ScriptDefinition>
get() {
definitionsLock.withLock {
_definitions?.let { return it.asSequence() }
}
forceStartUpdate = false
asyncRunUpdateScriptTemplates()
return emptySequence()
}
init {
val connection = project.messageBus.connect()
connection.subscribe(
ProjectTopics.PROJECT_ROOTS,
object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
if (project.isInitialized) {
forceStartUpdate = true
asyncRunUpdateScriptTemplates()
}
}
},
)
}
private fun asyncRunUpdateScriptTemplates() {
definitionsLock.withLock {
if (!forceStartUpdate && _definitions != null) return
}
if (inProgress.compareAndSet(false, true)) {
loadScriptDefinitions()
}
}
@Volatile
private var _definitions: List<ScriptDefinition>? = null
private val definitionsLock = ReentrantLock()
private var oldTemplates: TemplatesWithCp? = null
private data class TemplatesWithCp(
val templates: List<String>,
val classpath: List<Path>,
)
private val inProgress = AtomicBoolean(false)
@Volatile
private var forceStartUpdate = false
private fun loadScriptDefinitions() {
if (project.isDefault) {
return onEarlyEnd()
}
if (logger.isDebugEnabled) {
logger.debug("async script definitions update started")
}
val task = object : Task.Backgroundable(
project, KotlinBundle.message("kotlin.script.lookup.definitions"), false
) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val pluginDisposable = KotlinPluginDisposable.getInstance(project)
val (templates, classpath) =
ReadAction.nonBlocking(Callable {
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode(ThrowableComputable {
val files = mutableSetOf<VirtualFile>()
FileTypeIndex.processFiles(ScriptDefinitionMarkerFileType, {
indicator.checkCanceled()
files.add(it)
true
}, project.allScope())
getTemplateClassPath(files, indicator)
})
})
.expireWith(pluginDisposable)
.wrapProgress(indicator)
.executeSynchronously() ?: return onEarlyEnd()
try {
indicator.checkCanceled()
if (pluginDisposable.disposed || !inProgress.get() || templates.isEmpty()) return onEarlyEnd()
val newTemplates = TemplatesWithCp(templates.toList(), classpath.toList())
if (!inProgress.get() || newTemplates == oldTemplates) return onEarlyEnd()
if (logger.isDebugEnabled) {
logger.debug("script templates found: $newTemplates")
}
oldTemplates = newTemplates
val hostConfiguration = ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration) {
getEnvironment {
mapOf(
"projectRoot" to (project.basePath ?: project.baseDir.canonicalPath)?.let(::File),
)
}
}
val newDefinitions = loadDefinitionsFromTemplatesByPaths(
templateClassNames = newTemplates.templates,
templateClasspath = newTemplates.classpath,
baseHostConfiguration = hostConfiguration,
)
indicator.checkCanceled()
if (logger.isDebugEnabled) {
logger.debug("script definitions found: ${newDefinitions.joinToString()}")
}
val needReload = definitionsLock.withLock {
if (newDefinitions != _definitions) {
_definitions = newDefinitions
return@withLock true
}
return@withLock false
}
if (needReload) {
ScriptDefinitionsManager.getInstance(project).reloadDefinitionsBy(this@ScriptTemplatesFromDependenciesProvider)
}
} finally {
inProgress.set(false)
}
}
}
ProgressManager.getInstance().runProcessWithProgressAsynchronously(
task,
BackgroundableProcessIndicator(task)
)
}
private fun onEarlyEnd() {
definitionsLock.withLock {
_definitions = emptyList()
}
inProgress.set(false)
}
// public for tests
fun getTemplateClassPath(files: Collection<VirtualFile>, indicator: ProgressIndicator): Pair<Collection<String>, Collection<Path>> {
val rootDirToTemplates: MutableMap<VirtualFile, MutableList<VirtualFile>> = hashMapOf()
for (file in files) {
val dir = file.parent?.parent?.parent?.parent?.parent ?: continue
rootDirToTemplates.getOrPut(dir) { arrayListOf() }.add(file)
}
val templates = linkedSetOf<String>()
val classpath = linkedSetOf<Path>()
rootDirToTemplates.forEach { (root, templateFiles) ->
if (logger.isDebugEnabled) {
logger.debug("root matching SCRIPT_DEFINITION_MARKERS_PATH found: ${root.path}")
}
val orderEntriesForFile = ProjectFileIndex.getInstance(project).getOrderEntriesForFile(root)
.filter {
indicator.checkCanceled()
if (it is ModuleSourceOrderEntry) {
if (ModuleRootManager.getInstance(it.ownerModule).fileIndex.isInTestSourceContent(root)) {
return@filter false
}
it.getFiles(OrderRootType.SOURCES).contains(root)
} else {
it is LibraryOrSdkOrderEntry && it.getFiles(OrderRootType.CLASSES).contains(root)
}
}
.takeIf { it.isNotEmpty() } ?: return@forEach
for (virtualFile in templateFiles) {
templates.add(virtualFile.name.removeSuffix(SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT))
}
// assuming that all libraries are placed into classes roots
// TODO: extract exact library dependencies instead of putting all module dependencies into classpath
// minimizing the classpath needed to use the template by taking cp only from modules with new templates found
// on the other hand the approach may fail if some module contains a template without proper classpath, while
// the other has properly configured classpath, so assuming that the dependencies are set correctly everywhere
for (orderEntry in orderEntriesForFile) {
for (virtualFile in OrderEnumerator.orderEntries(orderEntry.ownerModule).withoutSdk().classesRoots) {
indicator.checkCanceled()
val localVirtualFile = VfsUtil.getLocalFile(virtualFile)
localVirtualFile.fileSystem.getNioPath(localVirtualFile)?.let(classpath::add)
}
}
}
return templates to classpath
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/ScriptTemplatesFromDependenciesProvider.kt | 993411917 |
/*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.ui.modules.dialogs
import com.kotcrab.vis.ui.util.async.AsyncTaskListener
import com.kotcrab.vis.ui.widget.VisDialog
import com.kotcrab.vis.ui.widget.VisLabel
import com.kotcrab.vis.ui.widget.VisProgressBar
import com.mbrlabs.mundus.editor.Mundus
import com.mbrlabs.mundus.editor.core.kryo.KryoManager
import com.mbrlabs.mundus.editor.core.project.ProjectManager
import com.mbrlabs.mundus.editor.exporter.Exporter
import com.mbrlabs.mundus.editor.ui.UI
import com.mbrlabs.mundus.editor.utils.Log
import com.mbrlabs.mundus.editor.utils.Toaster
/**
* @author Marcus Brummer
* @version 26-12-2015
*/
class ExportDialog : VisDialog("Exporting") {
private var lastExport: Long = 0
private val label = VisLabel()
private val progressBar = VisProgressBar(0f, 100f, 1f, false)
private val projectManager: ProjectManager = Mundus.inject()
private val kryoManager: KryoManager = Mundus.inject()
init {
isModal = true
isMovable = false
contentTable.add(label).padBottom(UI.PAD_BOTTOM).padTop(UI.PAD_BOTTOM_X2).left().growX().row()
contentTable.add(progressBar).width(300f).left().growX().row()
}
fun export() {
// validate
val export = projectManager.current().settings?.export
if(export == null || export.outputFolder == null
|| export.outputFolder.path().isEmpty() || !export.outputFolder.exists()) {
UI.toaster.error("Export Error\nYou have to supply a output folder in the export settings." +
"\nWindow -> Settings -> Export Settings")
return
}
// prevent from exporting to fast which sometimes results in the export dialog not closing correctly
if(System.currentTimeMillis() - lastExport < 1000f) {
UI.toaster.error("Export pending")
return
}
show(UI)
Exporter(kryoManager, projectManager.current()).exportAsync(export.outputFolder, object: AsyncTaskListener {
private var error = false
override fun progressChanged(newProgressPercent: Int) {
progressBar.value = newProgressPercent.toFloat()
}
override fun finished() {
if(!error) {
UI.toaster.success("Project exported")
}
resetValues()
close()
lastExport = System.currentTimeMillis()
}
override fun messageChanged(message: String?) {
label.setText(message)
}
override fun failed(message: String?, exception: Exception?) {
Log.exception("Exporter", exception)
UI.toaster.sticky(Toaster.ToastType.ERROR, "Export failed: " + exception.toString())
error = true
resetValues()
close()
}
})
}
private fun resetValues() {
progressBar.value = 0f
label.setText("")
}
override fun close() {
super.close()
}
}
| editor/src/main/com/mbrlabs/mundus/editor/ui/modules/dialogs/ExportDialog.kt | 1631670776 |
@file:JsModule("emoji-mart")
package vendor
import org.w3c.dom.events.Event
import react.RProps
import react.RState
import react.React
@JsName("Picker")
external class EmojiPicker: React.Component<EmojiPickerProps, RState> {
override fun render()
}
external interface EmojiPickerProps : RProps {
var autoFocus: Boolean // false Auto focus the search input when mounted
var color: String // #ae65c5 The top bar anchors select and hover color
var emoji: String // department_store The emoji shown when no emojis are hovered, set to an empty string to show nothing
var include: Array<String> // [] Only load included categories. Accepts I18n categories keys. Order will be respected, except for the recent category which will always be the first.
var exclude: Array<String> // [] Don't load excluded categories. Accepts I18n categories keys.
var recent: Array<String> // [] Pass your own frequently used emojis as array of string IDs
var emojiSize: Int // 24 The emoji width and height
var perLine: Int // 9 Number of emojis per line. While there’s no minimum or maximum, this will affect the picker’s width. This will set Frequently Used length as well (perLine * 4)
var native: Boolean // false Renders the native unicode emoji
var set: String // apple The emoji set: 'apple', 'google', 'twitter', 'emojione', 'messenger', 'facebook'
var sheetSize: Int // 64 The emoji sheet size: 16, 20, 32, 64
var showPreview: Boolean // true Display preview section
var emojiTooltip: Boolean // false Show emojis short name when hovering (title)
var skin: Int // 1 Default skin color: 1, 2, 3, 4, 5, 6
var style: String // Inline styles applied to the root element. Useful for positioning
var title: String // Emoji Mart™ The title shown when no emojis are hovered
var onClick: (Emoji, Event) -> Unit
/**
* A Fn to choose whether an emoji should be displayed or not
*/
var emojisToShowFilter: (Emoji) -> Boolean
/*
custom [] Custom emojis
i18n {…} An object containing localized strings
backgroundImageFn ((set, sheetSize) => …) A Fn that returns that image sheet to use for emojis. Useful for avoiding a request if you have the sheet locally.
*/
}
external interface Emoji {
var id: String
var name: String
var colons: String
var text : String
var emoticons: Array<String>
var skin: Int?
var native: String?
}
| webui/src/main/kotlin/vendor/emojimart.kt | 1376021631 |
// !RENDER_DIAGNOSTICS_MESSAGES
package foo
expect class <!AMBIGUOUS_ACTUALS("Class 'ActualInMiddleCompatibleInBottom'; bottom, middle"), LINE_MARKER("descr='Has actuals in middle module'")!>ActualInMiddleCompatibleInBottom<!>
expect class <!AMBIGUOUS_ACTUALS("Class 'CompatibleInMiddleActualInBottom'; bottom, middle"), LINE_MARKER("descr='Has actuals in bottom module'")!>CompatibleInMiddleActualInBottom<!>
expect class <!AMBIGUOUS_ACTUALS("Class 'CompatibleInMiddleAndBottom'; bottom, middle")!>CompatibleInMiddleAndBottom<!>
| plugins/kotlin/idea/tests/testData/multiplatform/duplicateActualsImplicit/top/top.kt | 1827173539 |
package net.squanchy.about.licenses
internal object Libraries {
val LIBRARIES = listOf(
Library("Squanchy", "the Squanchy Authors", License.APACHE_2),
Library("Android", "Google Inc. and the Open Handset Alliance", License.APACHE_2),
Library("Android Support Library", "Google Inc. and the Open Handset Alliance", License.APACHE_2),
Library("Λrrow", "The Arrow Authors", License.APACHE_2),
Library("Dagger", "the Dagger Authors", License.APACHE_2),
Library("Detekt", "the Detekt Authors", License.APACHE_2),
Library("Firebase-UI", "Google Inc.", License.APACHE_2),
Library("Flexbox-layout", "Google Inc.", License.APACHE_2),
Library("Glide", "Google Inc.", License.GLIDE),
Library("Gradle Build Properties plugin", "Novoda, Ltd.", License.APACHE_2),
Library("Gradle Play Publisher plugin", "Christian Becker and Björn Hurling", License.MIT),
Library("Gradle Static Analysis plugin", "Novoda, Ltd.", License.APACHE_2),
Library("Joda-Time", "the Joda-Time Authors", License.APACHE_2),
Library("Joda-Time Android", "Daniel Lew", License.APACHE_2),
Library("JUnit 4", "JUnit.org", License.ECLIPSE_PUBLIC_LICENSE),
Library("Kotlin", "JetBrains s.r.o. and the Kotlin Authors", License.APACHE_2),
Library("KtLint", "the KtLint Authors", License.MIT),
Library("Mockito", "the Mockito Authors", License.MIT),
Library("Moshi", "Square, Inc.", License.APACHE_2),
Library("RxAndroid", "the RxAndroid Authors", License.APACHE_2),
Library("RxJava", "the RxJava Authors", License.APACHE_2),
Library("RxLint", "Little Robot", License.APACHE_2),
Library("Timber", "Jake Wharton", License.APACHE_2),
Library("Truth", "the Truth Authors", License.APACHE_2),
Library("ViewPagerAdapter", "Novoda Ltd.", License.APACHE_2),
Library("League Spartan", "Micah Rich, Caroline Hadilaksono, and Tyler Finck", License.OPEN_FONT_LICENSE),
Library("Quicksand", "the Quicksand Project Authors", License.OPEN_FONT_LICENSE),
Library("VT323", "the VT323 Project Authors", License.OPEN_FONT_LICENSE)
)
}
| app/src/main/java/net/squanchy/about/licenses/Libraries.kt | 3746902075 |
package com.emberjs.lookup
import com.emberjs.icons.EmberIconProvider
import com.emberjs.icons.EmberIcons
import com.emberjs.resolver.EmberName
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
object EmberLookupElementBuilder {
fun create(it: EmberName, dots: Boolean = true): LookupElement = LookupElementBuilder
.create(if (dots) it.name.replace("/", ".") else it.name)
.withTypeText(it.type)
.withIcon(EmberIconProvider.getIcon(it.type) ?: EmberIcons.EMPTY_16)
.withCaseSensitivity(true)
}
| src/main/kotlin/com/emberjs/lookup/EmberLookupElementBuilder.kt | 3130118119 |
package com.intellij.grazie.text
import com.intellij.grazie.GrazieConfig
class SuppressionPattern(errorText: CharSequence, sentenceText: String?) {
internal val errorText : String = normalize(errorText)
internal val sentenceText : String? = sentenceText?.let(::normalize)
internal val full : String = this.errorText + (if (sentenceText == null) "" else "|" + this.sentenceText)
private fun normalize(text: CharSequence) = text.replace(Regex("\\s+"), " ").trim()
fun isSuppressed(): Boolean = full in GrazieConfig.get().suppressingContext.suppressed
}
| plugins/grazie/src/main/kotlin/com/intellij/grazie/text/SuppressionPattern.kt | 4085631156 |
package demo
object SwitchDemo {
fun print(o: Any?) {
println(o)
}
fun test(i: Int) {
var monthString = "<empty>"
when (i) {
1 -> {
print(1)
print(2)
print(3)
print(4)
print(5)
}
2 -> {
print(2)
print(3)
print(4)
print(5)
}
3 -> {
print(3)
print(4)
print(5)
}
4 -> {
print(4)
print(5)
}
5 -> print(5)
6 -> {
print(6)
print(7)
print(8)
print(9)
print(10)
print(11)
monthString = "December"
}
7 -> {
print(7)
print(8)
print(9)
print(10)
print(11)
monthString = "December"
}
8 -> {
print(8)
print(9)
print(10)
print(11)
monthString = "December"
}
9 -> {
print(9)
print(10)
print(11)
monthString = "December"
}
10 -> {
print(10)
print(11)
monthString = "December"
}
11 -> {
print(11)
monthString = "December"
}
12 -> monthString = "December"
else -> monthString = "Invalid month"
}
println(monthString)
}
@JvmStatic
fun main(args: Array<String>) {
for (i in 1..12) test(i)
}
}
| plugins/kotlin/j2k/new/tests/testData/newJ2k/switch/comlicatedFallDown.kt | 138311411 |
package com.intellij.settingsSync
import com.intellij.openapi.util.NlsSafe
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
sealed class SettingsSyncPushResult {
class Success(val serverVersionId: String?) : SettingsSyncPushResult() {
override fun toString(): String = "SUCCESS"
}
object Rejected: SettingsSyncPushResult() {
override fun toString(): String = "REJECTED"
}
class Error(@NlsSafe val message: String): SettingsSyncPushResult() {
override fun toString(): String = "ERROR[$message]"
}
}
| plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncPushResult.kt | 1376245388 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.layout
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.components.dialog
import com.intellij.ui.tabs.TabInfo
import com.intellij.ui.tabs.impl.JBEditorTabs
// not easy to replicate the same LaF outside of IDEA app, so, to be sure, showcase available as an IDE action
internal class ShowcaseUiDslAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val disposable = Disposer.newDisposable()
val tabs = object : JBEditorTabs(e.project, ActionManager.getInstance(), IdeFocusManager.getInstance(e.project), disposable) {
override fun isAlphabeticalMode(): Boolean {
return false
}
}
tabs.addTab(TabInfo(secondColumnSmallerPanel()).setText("Second Column Smaller"))
val dialog = dialog("UI DSL Showcase", tabs)
Disposer.register(dialog.disposable, disposable)
dialog.showAndGet()
}
}
| platform/platform-impl/src/com/intellij/ui/layout/ShowcaseUiDslAction.kt | 634556308 |
package io.farallons.puffin.stack
abstract class AbstractStack<Item> : Stack<Item> {
protected abstract fun top() : Item?
protected abstract fun size() : Int
protected abstract fun empty() : Boolean
override val top: Item?
get() = top()
override val size: Int
get() = size()
override val empty: Boolean
get() = empty()
} | src/main/kotlin/io/farallons/puffin/stack/AbstractStack.kt | 4007336449 |
package lt.markmerkk.utils
import com.nhaarman.mockitokotlin2.mock
import lt.markmerkk.ConfigPathProvider
import org.junit.Assert.*
import org.junit.Test
class ConfigSetSettingsImplCurrentConfigOrDefaultTest {
val pathProvider: ConfigPathProvider = mock()
val settings = ConfigSetSettingsImpl(pathProvider)
@Test
fun valid() {
// Arrange
// Act
settings.changeActiveConfig("valid_config")
val result = settings.currentConfigOrDefault()
// Assert
assertEquals("valid_config", result)
}
@Test
fun emptyConfig() {
// Arrange
// Act
settings.changeActiveConfig("")
val result = settings.currentConfigOrDefault()
// Assert
assertEquals(ConfigSetSettingsImpl.DEFAULT_ROOT_CONFIG_NAME, result)
}
@Test
fun defaultConfig() {
// Arrange
// Act
settings.changeActiveConfig(ConfigSetSettingsImpl.DEFAULT_ROOT_CONFIG_NAME)
val result = settings.currentConfigOrDefault()
// Assert
assertEquals(ConfigSetSettingsImpl.DEFAULT_ROOT_CONFIG_NAME, result)
}
} | components/src/test/java/lt/markmerkk/utils/ConfigSetSettingsImplCurrentConfigOrDefaultTest.kt | 2880280749 |
package eu.kanade.tachiyomi.widget.listener
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
class IgnoreFirstSpinnerListener(private val block: (Int) -> Unit) : OnItemSelectedListener {
private var firstEvent = true
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (!firstEvent) {
block(position)
} else {
firstEvent = false
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
| app/src/main/java/eu/kanade/tachiyomi/widget/listener/IgnoreFirstSpinnerListener.kt | 1134738386 |
package imgui.internal.api
import imgui.classes.Context
import imgui.classes.ContextHook
import imgui.classes.ContextHookType
// Generic context hooks
interface `generic context hooks` {
/** No specific ordering/dependency support, will see as needed */
fun addContextHook(ctx: Context, hook: ContextHook) {
val g = ctx
// assert(hook.callback != null)
g.hooks += hook
}
/** Call context hooks (used by e.g. test engine)
* We assume a small number of hooks so all stored in same array */
fun callContextHooks(ctx: Context, hookType: ContextHookType) {
val g = ctx
for (hook in g.hooks)
if (hook.type == hookType)
hook.callback!!(g, hook)
}
} | core/src/main/kotlin/imgui/internal/api/generic context hooks.kt | 636830896 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.datacapture.fhirpath
import com.google.android.fhir.datacapture.EXTENSION_CALCULATED_EXPRESSION_URL
import com.google.android.fhir.datacapture.EXTENSION_VARIABLE_URL
import com.google.android.fhir.datacapture.common.datatype.asStringValue
import com.google.android.fhir.datacapture.fhirpath.ExpressionEvaluator.detectExpressionCyclicDependency
import com.google.android.fhir.datacapture.fhirpath.ExpressionEvaluator.evaluateCalculatedExpressions
import com.google.android.fhir.datacapture.variableExpressions
import com.google.common.truth.Truth.assertThat
import java.util.Calendar
import java.util.Date
import kotlinx.coroutines.runBlocking
import org.hl7.fhir.r4.model.DateType
import org.hl7.fhir.r4.model.Expression
import org.hl7.fhir.r4.model.IntegerType
import org.hl7.fhir.r4.model.Quantity
import org.hl7.fhir.r4.model.Questionnaire
import org.hl7.fhir.r4.model.QuestionnaireResponse
import org.hl7.fhir.r4.model.Type
import org.junit.Assert.assertThrows
import org.junit.Test
class ExpressionEvaluatorTest {
@Test
fun `should return not null value with simple variable expression for questionnaire root level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "1"
}
)
}
}
val result =
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.first(),
questionnaire,
QuestionnaireResponse()
)
assertThat((result as Type).asStringValue()).isEqualTo("1")
}
@Test
fun `should return not null value with variables dependent on other variables for questionnaire root level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "1"
}
)
}
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "B"
language = "text/fhirpath"
expression = "%A + 1"
}
)
}
}
val result =
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.last(),
questionnaire,
QuestionnaireResponse()
)
assertThat((result as Type).asStringValue()).isEqualTo("2")
}
@Test
fun `should return not null value with variables dependent on other variables in parent for questionnaire item level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-group-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.GROUP
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "1"
}
)
}
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "an-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.TEXT
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "B"
language = "text/fhirpath"
expression = "%A + 1"
}
)
}
}
)
}
)
}
val result =
ExpressionEvaluator.evaluateQuestionnaireItemVariableExpression(
questionnaire.item[0].item[0].variableExpressions.last(),
questionnaire,
QuestionnaireResponse(),
mapOf(questionnaire.item[0].item[0] to questionnaire.item[0]),
questionnaire.item[0].item[0]
)
assertThat((result as Type).asStringValue()).isEqualTo("2")
}
@Test
fun `should return not null value with variables dependent on multiple variables for questionnaire root level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "1"
}
)
}
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "B"
language = "text/fhirpath"
expression = "2"
}
)
}
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "C"
language = "text/fhirpath"
expression = "%A + %B"
}
)
}
}
val result =
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.last(),
questionnaire,
QuestionnaireResponse()
)
assertThat((result as Type).asStringValue()).isEqualTo("3")
}
@Test
fun `should return null with variables dependent on missing variables for questionnaire root level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "%B + 1"
}
)
}
}
val result =
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.last(),
questionnaire,
QuestionnaireResponse()
)
assertThat(result).isEqualTo(null)
}
@Test
fun `should return not null value with variables dependent on other variables at origin for questionnaire item level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "an-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.TEXT
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "B"
language = "text/fhirpath"
expression = "1"
}
)
}
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "%B + 1"
}
)
}
}
)
}
val result =
ExpressionEvaluator.evaluateQuestionnaireItemVariableExpression(
questionnaire.item[0].variableExpressions.last(),
questionnaire,
QuestionnaireResponse(),
mapOf(),
questionnaire.item[0]
)
assertThat((result as Type).asStringValue()).isEqualTo("2")
}
@Test
fun `should return null with variables dependent on missing variables at origin for questionnaire item level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "an-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.TEXT
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "%B + 1"
}
)
}
}
)
}
val result =
ExpressionEvaluator.evaluateQuestionnaireItemVariableExpression(
questionnaire.item[0].variableExpressions.last(),
questionnaire,
QuestionnaireResponse(),
mapOf(),
questionnaire.item[0]
)
assertThat(result).isEqualTo(null)
}
@Test
fun `should throw illegal argument exception with missing expression name for questionnaire variables`() {
assertThrows(IllegalArgumentException::class.java) {
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
language = "text/fhirpath"
expression = "%resource.repeat(item).where(linkId='an-item').answer.first().value"
}
)
}
}
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.first(),
questionnaire,
QuestionnaireResponse()
)
}
}
}
@Test
fun `should throw illegal argument exception with missing exception language for questionnaire variables`() {
assertThrows(IllegalArgumentException::class.java) {
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "X"
expression = "1"
}
)
}
}
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.first(),
questionnaire,
QuestionnaireResponse()
)
}
}
}
@Test
fun `should throw illegal argument exception with unsupported expression language for questionnaire variables`() {
assertThrows(IllegalArgumentException::class.java) {
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "X"
expression = "1"
language = "application/x-fhir-query"
}
)
}
}
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.first(),
questionnaire,
QuestionnaireResponse()
)
}
}
}
@Test
fun `should throw null pointer exception with missing expression for questionnaire variables`() {
assertThrows(NullPointerException::class.java) {
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "X"
language = "text/fhirpath"
}
)
}
}
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.first(),
questionnaire,
QuestionnaireResponse()
)
}
}
}
@Test
fun `should return not null value with expression dependent on answers of items for questionnaire item level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-group-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.GROUP
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "M"
language = "text/fhirpath"
expression =
"%resource.repeat(item).where(linkId='an-item').answer.first().value"
}
)
}
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "an-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.TEXT
}
)
}
)
}
val questionnaireResponse =
QuestionnaireResponse().apply {
id = "a-questionnaire-response"
addItem(
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
linkId = "an-item"
addAnswer(
QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply {
value = IntegerType(2)
}
)
}
)
}
val result =
ExpressionEvaluator.evaluateQuestionnaireItemVariableExpression(
questionnaire.item[0].variableExpressions.last(),
questionnaire,
questionnaireResponse,
mapOf(),
questionnaire.item[0]
)
assertThat((result as Type).asStringValue()).isEqualTo("2")
}
@Test
fun `evaluateCalculatedExpressions should return list of calculated values`() = runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-birthdate"
type = Questionnaire.QuestionnaireItemType.DATE
addExtension().apply {
url = EXTENSION_CALCULATED_EXPRESSION_URL
setValue(
Expression().apply {
this.language = "text/fhirpath"
this.expression =
"%resource.repeat(item).where(linkId='a-age-years' and answer.empty().not()).select(today() - answer.value)"
}
)
}
}
)
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-age-years"
type = Questionnaire.QuestionnaireItemType.QUANTITY
}
)
}
val questionnaireResponse =
QuestionnaireResponse().apply {
addItem(
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
linkId = "a-birthdate"
}
)
addItem(
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
linkId = "a-age-years"
answer =
listOf(
QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply {
this.value = Quantity(1).apply { unit = "year" }
}
)
}
)
}
val result =
evaluateCalculatedExpressions(
questionnaire.item.elementAt(1),
questionnaire,
questionnaireResponse,
emptyMap()
)
assertThat(result.first().second.first().asStringValue())
.isEqualTo(DateType(Date()).apply { add(Calendar.YEAR, -1) }.asStringValue())
}
@Test
fun `evaluateCalculatedExpressions should return list of calculated values with variables`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "AGE-YEARS"
language = "text/fhirpath"
expression =
"%resource.repeat(item).where(linkId='a-age-years' and answer.empty().not()).select(today() - answer.value)"
}
)
}
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-birthdate"
type = Questionnaire.QuestionnaireItemType.DATE
addExtension().apply {
url = EXTENSION_CALCULATED_EXPRESSION_URL
setValue(
Expression().apply {
this.language = "text/fhirpath"
this.expression = "%AGE-YEARS"
}
)
}
}
)
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-age-years"
type = Questionnaire.QuestionnaireItemType.QUANTITY
}
)
}
val questionnaireResponse =
QuestionnaireResponse().apply {
addItem(
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
linkId = "a-birthdate"
}
)
addItem(
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
linkId = "a-age-years"
answer =
listOf(
QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply {
this.value = Quantity(1).apply { unit = "year" }
}
)
}
)
}
val result =
evaluateCalculatedExpressions(
questionnaire.item.elementAt(1),
questionnaire,
questionnaireResponse,
emptyMap()
)
assertThat(result.first().second.first().asStringValue())
.isEqualTo(DateType(Date()).apply { add(Calendar.YEAR, -1) }.asStringValue())
}
@Test
fun `detectExpressionCyclicDependency() should throw illegal argument exception when item with calculated expression have cyclic dependency`() {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-birthdate"
type = Questionnaire.QuestionnaireItemType.DATE
addInitial(
Questionnaire.QuestionnaireItemInitialComponent(
DateType(Date()).apply { add(Calendar.YEAR, -2) }
)
)
addExtension().apply {
url = EXTENSION_CALCULATED_EXPRESSION_URL
setValue(
Expression().apply {
this.language = "text/fhirpath"
this.expression =
"%resource.repeat(item).where(linkId='a-age-years' and answer.empty().not()).select(today() - answer.value)"
}
)
}
}
)
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-age-years"
type = Questionnaire.QuestionnaireItemType.INTEGER
addExtension().apply {
url = EXTENSION_CALCULATED_EXPRESSION_URL
setValue(
Expression().apply {
this.language = "text/fhirpath"
this.expression =
"today().toString().substring(0, 4).toInteger() - %resource.repeat(item).where(linkId='a-birthdate').answer.value.toString().substring(0, 4).toInteger()"
}
)
}
}
)
}
val exception =
assertThrows(null, IllegalStateException::class.java) {
detectExpressionCyclicDependency(questionnaire.item)
}
assertThat(exception.message)
.isEqualTo("a-birthdate and a-age-years have cyclic dependency in expression based extension")
}
}
| datacapture/src/test/java/com/google/android/fhir/datacapture/fhirpath/ExpressionEvaluatorTest.kt | 2577166104 |
package com.scavi.brainsqueeze.adventofcode
import com.scavi.brainsqueeze.adventofcode.util.FileHelper
import kotlin.test.Test
import kotlin.test.assertEquals
class Day1Test {
@Test
fun test1A() {
val input = setOf(1721, 979, 366, 299, 675, 1456)
val day1 = Day1ReportRepair()
val result = day1.solveA(input, 2020)
assertEquals(514579, result)
}
@Test
fun test1B() {
val filePath = FileHelper.fileForUnitTest("input/adventofcode/y2020/Day1.txt")
val input = FileHelper.readAsIntSet(filePath)
val day1 = Day1ReportRepair()
val result = day1.solveA(input, 2020)
assertEquals(197451, result)
}
@Test
fun test2A() {
val input = setOf(1721, 979, 366, 299, 675, 1456)
val day1 = Day1ReportRepair()
val result = day1.solveB(input, 2020)
assertEquals(241861950, result)
}
@Test
fun test2B() {
val filePath = FileHelper.fileForUnitTest("input/adventofcode/y2020/Day1.txt")
val input = FileHelper.readAsIntSet(filePath)
val day1 = Day1ReportRepair()
val result = day1.solveB(input, 2020)
assertEquals(138233720, result)
}
}
| src/test/kotlin/com/scavi/brainsqueeze/adventofcode/TestDay1ReportRepair.kt | 29539240 |
/*
* Copyright 2000-2015 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.
*/
/*
* Copyright 2000-2015 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.openapi.util
/**
* Put here extension functions and variables for classes from util/util.rt modules
*/
operator fun <A, B> Pair<A, B>.component1(): A = this.first
operator fun <A, B> Pair<A, B>.component2(): B = this.second
| platform/platform-impl/src/com/intellij/openapi/util/extensions.kt | 163976898 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.importing
import com.intellij.codeInsight.ExternalAnnotationsArtifactsResolver
import com.intellij.jarRepository.RemoteRepositoriesConfiguration
import com.intellij.jarRepository.RemoteRepositoryDescription
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.util.registry.Registry
import org.jetbrains.idea.maven.model.MavenArtifact
import org.jetbrains.idea.maven.project.*
class ExternalAnnotationsImporter : MavenImporter("org.apache.maven.plugins", "maven-compiler-plugin") {
private val myProcessedLibraries = hashSetOf<MavenArtifact>()
override fun isApplicable(mavenProject: MavenProject?): Boolean {
return super.isApplicable(mavenProject) && Registry.`is`("external.system.import.resolve.annotations")
}
override fun processChangedModulesOnly(): Boolean = false
override fun process(modifiableModelsProvider: IdeModifiableModelsProvider?,
module: Module?,
rootModel: MavenRootModelAdapter?,
mavenModel: MavenProjectsTree?,
mavenProject: MavenProject?,
changes: MavenProjectChanges?,
mavenProjectToModuleName: MutableMap<MavenProject, String>?,
postTasks: MutableList<MavenProjectsProcessorTask>?) {
// do nothing
}
override fun preProcess(module: Module?,
mavenProject: MavenProject?,
changes: MavenProjectChanges?,
modifiableModelsProvider: IdeModifiableModelsProvider?) {
if (module == null
|| mavenProject == null
|| !MavenProjectsManager.getInstance(module.project).importingSettings.isDownloadAnnotationsAutomatically) {
return
}
val repoConfig = RemoteRepositoriesConfiguration.getInstance(module.project)
val repositories: MutableCollection<RemoteRepositoryDescription> =
hashSetOf<RemoteRepositoryDescription>().apply { addAll(repoConfig.repositories) }
mavenProject.remoteRepositories.mapTo(repositories) { RemoteRepositoryDescription(it.id, it.name ?: it.id, it.url) }
repoConfig.repositories = repositories.toMutableList()
}
override fun postProcess(module: Module,
mavenProject: MavenProject,
changes: MavenProjectChanges,
modifiableModelsProvider: IdeModifiableModelsProvider) {
val resolver = ExternalAnnotationsArtifactsResolver.EP_NAME.extensionList.firstOrNull() ?: return
val project = module.project
val librariesMap = mutableMapOf<MavenArtifact, Library>()
if (!MavenProjectsManager.getInstance(project).importingSettings.isDownloadAnnotationsAutomatically) {
return
}
mavenProject.dependencies.forEach {
val library = modifiableModelsProvider.getLibraryByName(it.libraryName)
if (library != null) {
librariesMap[it] = library
}
}
val toProcess = librariesMap.filterKeys { myProcessedLibraries.add(it) }
val totalSize = toProcess.size
var count = 0
runBackgroundableTask("Resolving external annotations", project) { indicator ->
indicator.isIndeterminate = false
toProcess.forEach { mavenArtifact, library ->
if (indicator.isCanceled) {
return@forEach
}
count++
indicator.fraction = (count.toDouble() + 1) / totalSize
indicator.text = "Looking for annotations for '${mavenArtifact.libraryName}'"
val mavenId = "${mavenArtifact.groupId}:${mavenArtifact.artifactId}:${mavenArtifact.version}"
resolver.resolve(project, library, mavenId)
}
}
}
companion object {
val LOG = Logger.getInstance(ExternalAnnotationsImporter::class.java)
}
}
| plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/ExternalAnnotationsImporter.kt | 1816187935 |
package org.wikipedia.commons
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.dataclient.Service
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.wikidata.Claims
import org.wikipedia.dataclient.wikidata.Entities
import kotlin.collections.ArrayList
object ImageTagsProvider {
@JvmStatic
fun getImageTagsObservable(pageId: Int, langCode: String): Observable<Map<String, List<String>>> {
return ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getClaims("M$pageId", "P180")
.subscribeOn(Schedulers.io())
.onErrorReturnItem(Claims())
.flatMap { claims ->
val ids = claims.claims()["P180"]?.map { it.mainSnak?.dataValue?.value }
if (ids.isNullOrEmpty()) {
Observable.just(Entities())
} else {
ServiceFactory.get(WikiSite(Service.WIKIDATA_URL)).getWikidataLabels(ids.joinToString(separator = "|"), langCode)
}
}
.subscribeOn(Schedulers.io())
.map { entities ->
val tags = HashMap<String, MutableList<String>>()
entities.entities().flatMap { it.value.labels().values }
.forEach { label ->
tags.getOrPut(label.language(), { ArrayList() }).add(label.value())
}
tags
}
}
}
| app/src/main/java/org/wikipedia/commons/ImageTagsProvider.kt | 3572324922 |
/*
* 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.codeInsight.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.icons.AllIcons
import com.intellij.openapi.project.DumbAware
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ProcessingContext
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.*
import com.jetbrains.python.extensions.afterDefInMethod
import com.jetbrains.python.extensions.inParameterList
import com.jetbrains.python.psi.PyParameter
import com.jetbrains.python.psi.PyParameterList
import com.jetbrains.python.psi.PySubscriptionExpression
import com.jetbrains.python.psi.PyTargetExpression
import com.jetbrains.python.psi.types.PyClassType
class PyDataclassCompletionContributor : CompletionContributor(), DumbAware {
override fun handleAutoCompletionPossibility(context: AutoCompletionContext): AutoCompletionDecision = autoInsertSingleItem(context)
init {
extend(CompletionType.BASIC, PlatformPatterns.psiElement().afterDefInMethod(), PostInitProvider)
extend(CompletionType.BASIC, PlatformPatterns.psiElement().inParameterList(), AttrsValidatorParameterProvider)
}
private object PostInitProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val cls = parameters.getPyClass() ?: return
val typeEvalContext = parameters.getTypeEvalContext()
val dataclassParameters = parseDataclassParameters(cls, typeEvalContext)
if (dataclassParameters == null || !dataclassParameters.init) return
if (dataclassParameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.STD) {
val postInitParameters = mutableListOf(PyNames.CANONICAL_SELF)
cls.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression && element.annotationValue != null) {
val name = element.name
val annotationValue = element.annotation?.value as? PySubscriptionExpression
if (name != null && annotationValue != null) {
val type = typeEvalContext.getType(element)
if (type is PyClassType && type.classQName == DATACLASSES_INITVAR_TYPE) {
val typeHint = annotationValue.indexExpression.let { if (it == null) "" else ": ${it.text}" }
postInitParameters.add(name + typeHint)
}
}
}
true
}
addMethodToResult(result, cls, typeEvalContext, DUNDER_POST_INIT, postInitParameters.joinToString(prefix = "(", postfix = ")"))
}
else if (dataclassParameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) {
addMethodToResult(result, cls, typeEvalContext, DUNDER_ATTRS_POST_INIT)
}
}
}
private object AttrsValidatorParameterProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val cls = parameters.getPyClass() ?: return
val parameterList = PsiTreeUtil.getParentOfType(parameters.position, PyParameterList::class.java) ?: return
val parameter = PsiTreeUtil.getParentOfType(parameters.position, PyParameter::class.java) ?: return
val index = parameterList.parameters.indexOf(parameter)
if (index != 1 && index != 2) return
val decorators = parameterList.containingFunction?.decoratorList ?: return
if (decorators.decorators.none { it.qualifiedName?.endsWith("validator") == true }) return
val typeEvalContext = parameters.getTypeEvalContext()
if (parseDataclassParameters(cls, typeEvalContext)?.type?.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) {
result.addElement(LookupElementBuilder.create(if (index == 1) "attribute" else "value").withIcon(AllIcons.Nodes.Parameter))
}
}
}
}
| python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyDataclassCompletionContributor.kt | 2422080866 |
// FIX: Replace with '..'
fun test() {
class Test {
operator fun rangeTo(a: Int): Test = Test()
}
val test = Test()
test.range<caret>To(1)
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/conventionNameCalls/replaceCallWithBinaryOperator/rangeToSanityTest.kt | 26967264 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.projectPropertyBased
import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction
import com.intellij.find.FindBundle
import com.intellij.find.FindManager
import com.intellij.find.findUsages.FindUsagesHandlerFactory
import com.intellij.find.findUsages.FindUsagesManager
import com.intellij.find.impl.FindManagerImpl
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task.Backgroundable
import com.intellij.openapi.progress.impl.ProgressManagerImpl
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.testFramework.propertyBased.ActionOnFile
import com.intellij.testFramework.propertyBased.MadTestingUtil
import com.intellij.usages.Usage
import com.intellij.util.Processors
import org.jetbrains.jetCheck.Generator
import org.jetbrains.jetCheck.ImperativeCommand
import org.jetbrains.kotlin.idea.findUsages.KotlinClassFindUsagesOptions
import org.jetbrains.kotlin.idea.findUsages.KotlinFunctionFindUsagesOptions
import org.jetbrains.kotlin.idea.findUsages.KotlinPropertyFindUsagesOptions
import org.jetbrains.kotlin.idea.util.isUnderKotlinSourceRootTypes
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.utils.addToStdlib.cast
import java.util.*
class InvokeFindUsages(file: PsiFile): ActionOnFile(file) {
override fun performCommand(env: ImperativeCommand.Environment) {
// ignore test data, and other resources
file.takeIf { it.isUnderKotlinSourceRootTypes() } ?: return
val project = project
val editor =
FileEditorManager.getInstance(project).openTextEditor(OpenFileDescriptor(project, virtualFile, 0), true)
?: error("Unable to open file $virtualFile")
// todo: it's suboptimal search
val (offset: Int, element: PsiElement) = run {
val attempts = env.generateValue(Generator.integers(10, 30), null)
for (attempt in 0 until attempts) {
val offset = generateDocOffset(env, null)
val element = when (GotoDeclarationAction.findElementToShowUsagesOf(editor, offset)) {
null -> GotoDeclarationAction.findTargetElement(project, editor, offset)
else -> GotoDeclarationAction.findElementToShowUsagesOf(editor, offset)
} ?: continue
if (element is KtElement) {
return@run (offset to element)
}
}
env.logMessage("Unable to look up element for find usage in $attempts attempts")
return
}
env.logMessage("Go to ${MadTestingUtil.getPositionDescription(offset, document)}")
env.logMessage("Command find usages is called on element '$element' of ${element.javaClass.name}")
val findUsagesManager = FindManager.getInstance(project).cast<FindManagerImpl>().findUsagesManager
val handler = findUsagesManager.getFindUsagesHandler(
element, FindUsagesHandlerFactory.OperationMode.USAGES_WITH_DEFAULT_OPTIONS
) ?: run {
env.logMessage("No find usage handler found for the element: '${element.text}'")
return
}
val findUsagesOptions = when (element) {
is KtFunction -> KotlinFunctionFindUsagesOptions(project).apply {
// TODO: randomize isOverridingMethods etc
isOverridingMethods = false
isImplementingMethods = false
isCheckDeepInheritance = true
isIncludeInherited = false
isIncludeOverloadUsages = false
isImplicitToString = true
isSearchForBaseMethod = true
isSkipImportStatements = false
isSearchForTextOccurrences = false
isUsages = true
searchExpected = true
}
is KtClassOrObject -> KotlinClassFindUsagesOptions(project).apply {
searchExpected = true
searchConstructorUsages = true
isMethodsUsages = false
isFieldsUsages = false
isDerivedClasses = false
isImplementingClasses = false
isDerivedInterfaces = false
isCheckDeepInheritance = true
isIncludeInherited = false
isSkipImportStatements = false
isSearchForTextOccurrences = true
isUsages = true
}
else -> KotlinPropertyFindUsagesOptions(project).apply {
searchExpected = true
isReadWriteAccess = true
searchOverrides = false
isReadAccess = true
isWriteAccess = true
isSearchForAccessors = false
isSearchInOverridingMethods = false
isSearchForBaseAccessors = false
isSkipImportStatements = false
isSearchForTextOccurrences = false
isUsages = true
}
}
val usages = mutableListOf<Usage>()
val processor = Processors.cancelableCollectProcessor(Collections.synchronizedList(usages))
val usageSearcher =
FindUsagesManager.createUsageSearcher(handler, handler.primaryElements, handler.secondaryElements, findUsagesOptions)
val task = object : Backgroundable(project, FindBundle.message("progress.title.finding.usages")) {
override fun run(indicator: ProgressIndicator) {
usageSearcher.generate(processor)
}
}
ProgressManager.getInstance().cast<ProgressManagerImpl>()
.runProcessWithProgressInCurrentThread(task, EmptyProgressIndicator(), ModalityState.defaultModalityState())
env.logMessage("Found ${usages.size} usages for element $element")
}
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/projectPropertyBased/InvokeFindUsages.kt | 3961831266 |
val foo: (Int) -> Int = <warning descr="SSR">{ it -> it }</warning>
val foo2: (Int) -> Int = <warning descr="SSR">{ 1 }</warning>
var bar1: (Int) -> Unit = {}
val bar2: () -> Int = { 1 }
val bar3: (Int) -> Int = { it -> 1 }
| plugins/kotlin/idea/tests/testData/structuralsearch/lambdaExpression/identity.kt | 2593762831 |
// "Create class 'A'" "true"
// ERROR: Unresolved reference: A
fun foo(): J.A = throw Throwable("") | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/typeReference/classJavaTypeReceiver.after.kt | 2834526305 |
package test
class ClassWithNamedClassObject {
companion object Named {
fun a() {
}
}
}
| plugins/kotlin/idea/tests/testData/decompiler/decompiledText/ClassWithNamedClassObject/ClassWithNamedClassObject.kt | 237488762 |
package testing
object Testing {
companion object {
@<caret>va
}
}
/// Should not fall on temp references in invalid code
// REF_EMPTY | plugins/kotlin/idea/tests/testData/resolve/references/PropertyPlaceInClassObjectInObject.kt | 2099331806 |
package klay.jvm
import euklid.f.Point
import klay.core.*
import java.util.concurrent.ConcurrentLinkedDeque
open class JavaInput(plat: JavaPlatform) : Input(plat) {
@Suppress("CanBePrimaryConstructorProperty")
override val plat: JavaPlatform = plat
// used for injecting keyboard evnets
private val kevQueue = ConcurrentLinkedDeque<Keyboard.Event>()
// these are used for touch emulation
private var mouseDown: Boolean = false
private var pivot: Point? = null
private var x: Float = 0.toFloat()
private var y: Float = 0.toFloat()
private var currentId: Int = 0
init {
// if touch emulation is configured, wire it up
if (plat.config.emulateTouch) emulateTouch()
}
/** Posts a key event received from elsewhere (i.e. a native UI component). This is useful for
* applications that are using GL in Canvas mode and sharing keyboard focus with other (non-GL)
* components. The event will be queued and dispatched on the next frame, after GL keyboard
* events.
* @param time the time (in millis since epoch) at which the event was generated, or 0 if N/A.
* *
* @param key the key that was pressed or released, or null for a char typed event
* *
* @param pressed whether the key was pressed or released, ignored if key is null
* *
* @param typedCh the character that was typed, ignored if key is not null
* *
* @param modFlags modifier key state flags (generated by [.modifierFlags])
*/
fun postKey(time: Long, key: Key?, pressed: Boolean, typedCh: Char, modFlags: Int) {
val event = if (key == null)
Keyboard.TypedEvent(0, time.toDouble(), typedCh)
else
Keyboard.KeyEvent(0, time.toDouble(), key, pressed)
event.setFlag(modFlags)
kevQueue.add(event)
}
protected fun emulateTouch() {
val pivotKey = plat.config.pivotKey
keyboardEvents.connect { event: Keyboard.Event ->
if (event is Keyboard.KeyEvent) {
val kevent = event
if (kevent.key === pivotKey && kevent.down) {
pivot = Point(x, y)
}
}
}
mouseEvents.connect { event: Mouse.Event ->
if (event is Mouse.ButtonEvent) {
val bevent = event
if (bevent.button === Mouse.ButtonEvent.Id.LEFT) {
mouseDown = bevent.down
if (mouseDown) {
currentId += 2 // skip an id in case of pivot
dispatchTouch(event, Touch.Event.Kind.START)
} else {
pivot = null
dispatchTouch(event, Touch.Event.Kind.END)
}
}
} else if (event is Mouse.MotionEvent) {
if (mouseDown) dispatchTouch(event, Touch.Event.Kind.MOVE)
// keep track of the current mouse position for pivot
x = event.x
y = event.y
}
}
// TODO: it's pesky that both mouse and touch events are dispatched when touch is emulated, it
// would be nice to throw away the mouse events and only have touch, but we rely on something
// generating the mouse events so we can't throw them away just yet... plus it could be useful
// to keep wheel events... blah
}
override val hasMouse = true
override val hasHardwareKeyboard = true
override val hasTouch: Boolean
get() = plat.config.emulateTouch
internal open fun update() {
// dispatch any queued keyboard events
while (true) {
val kev: Keyboard.Event = kevQueue.poll() ?: break
plat.dispatchEvent(keyboardEvents, kev)
}
}
private fun dispatchTouch(event: Mouse.Event, kind: Touch.Event.Kind) {
val ex = event.x
val ey = event.y
val main = toTouch(event.time, ex, ey, kind, 0)
val evs: Array<Touch.Event> = if (pivot == null)
arrayOf(main)
else
arrayOf(main, toTouch(event.time, 2 * pivot!!.x - ex, 2 * pivot!!.y - ey, kind, 1))
plat.dispatchEvent(touchEvents, evs)
}
private fun toTouch(time: Double, x: Float, y: Float, kind: Touch.Event.Kind, idoff: Int): Touch.Event {
return Touch.Event(0, time, x, y, kind, currentId + idoff)
}
}
| klay-jvm/src/main/kotlin/klay/jvm/JavaInput.kt | 1099969859 |
private fun completeBackquotedFunction() {
fu
}
private fun `fun that needs backquotes`() {
} | server/src/test/resources/completions/BackquotedFunction.kt | 2965753074 |
package com.github.codeql
import com.github.codeql.KotlinUsesExtractor.LocallyVisibleFunctionLabels
import java.io.BufferedWriter
import java.io.File
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.path
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.IrVariable
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.util.SYNTHETIC_OFFSET
import com.semmle.extractor.java.PopulateFile
import com.semmle.util.unicode.UTF8Util
import org.jetbrains.kotlin.ir.expressions.IrCall
/**
* Each `.trap` file has a `TrapLabelManager` while we are writing it.
* It provides fresh TRAP label names, and maintains a mapping from keys
* (`@"..."`) to labels.
*/
class TrapLabelManager {
/** The next integer to use as a label name. */
private var nextInt: Int = 100
/** Returns a fresh label. */
fun <T: AnyDbType> getFreshLabel(): Label<T> {
return IntLabel(nextInt++)
}
/**
* A mapping from a key (`@"..."`) to the label defined to be that
* key, if any.
*/
val labelMapping: MutableMap<String, Label<*>> = mutableMapOf<String, Label<*>>()
val anonymousTypeMapping: MutableMap<IrClass, TypeResults> = mutableMapOf()
val locallyVisibleFunctionLabelMapping: MutableMap<IrFunction, LocallyVisibleFunctionLabels> = mutableMapOf()
/**
* The set of labels of generic specialisations that we have extracted
* in this TRAP file.
* We can't easily avoid duplication between TRAP files, as the labels
* contain references to other labels, so we just accept this
* duplication.
*/
val genericSpecialisationsExtracted = HashSet<String>()
}
/**
* A `TrapWriter` is used to write TRAP to a particular TRAP file.
* There may be multiple `TrapWriter`s for the same file, as different
* instances will have different additional state, but they must all
* share the same `TrapLabelManager` and `BufferedWriter`.
*/
// TODO lm was `protected` before anonymousTypeMapping and locallyVisibleFunctionLabelMapping moved into it. Should we re-protect it and provide accessors?
open class TrapWriter (protected val loggerBase: LoggerBase, val lm: TrapLabelManager, private val bw: BufferedWriter, val diagnosticTrapWriter: TrapWriter?) {
/**
* Returns the label that is defined to be the given key, if such
* a label exists, and `null` otherwise. Most users will want to use
* `getLabelFor` instead, which allows non-existent labels to be
* initialised.
*/
fun <T: AnyDbType> getExistingLabelFor(key: String): Label<T>? {
return lm.labelMapping.get(key)?.cast<T>()
}
/**
* Returns the label for the given key, if one exists.
* Otherwise, a fresh label is bound to that key, `initialise`
* is run on it, and it is returned.
*/
@JvmOverloads // Needed so Java can call a method with an optional argument
fun <T: AnyDbType> getLabelFor(key: String, initialise: (Label<T>) -> Unit = {}): Label<T> {
val maybeLabel: Label<T>? = getExistingLabelFor(key)
if(maybeLabel == null) {
val label: Label<T> = lm.getFreshLabel()
lm.labelMapping.put(key, label)
writeTrap("$label = $key\n")
initialise(label)
return label
} else {
return maybeLabel
}
}
/**
* Returns a label for a fresh ID (i.e. a new label bound to `*`).
*/
fun <T: AnyDbType> getFreshIdLabel(): Label<T> {
val label: Label<T> = lm.getFreshLabel()
writeTrap("$label = *\n")
return label
}
/**
* It is not easy to assign keys to local variables, so they get
* given `*` IDs. However, the same variable may be referred to
* from distant places in the IR, so we need a way to find out
* which label is used for a given local variable. This information
* is stored in this mapping.
*/
private val variableLabelMapping: MutableMap<IrVariable, Label<out DbLocalvar>> = mutableMapOf<IrVariable, Label<out DbLocalvar>>()
/**
* This returns the label used for a local variable, creating one
* if none currently exists.
*/
fun <T> getVariableLabelFor(v: IrVariable): Label<out DbLocalvar> {
val maybeLabel = variableLabelMapping.get(v)
if(maybeLabel == null) {
val label = getFreshIdLabel<DbLocalvar>()
variableLabelMapping.put(v, label)
return label
} else {
return maybeLabel
}
}
fun getExistingVariableLabelFor(v: IrVariable): Label<out DbLocalvar>? {
return variableLabelMapping.get(v)
}
/**
* This returns a label for the location described by its arguments.
* Typically users will not want to call this directly, but instead
* use `unknownLocation`, or overloads of this defined by subclasses.
*/
fun getLocation(fileId: Label<DbFile>, startLine: Int, startColumn: Int, endLine: Int, endColumn: Int): Label<DbLocation> {
return getLabelFor("@\"loc,{$fileId},$startLine,$startColumn,$endLine,$endColumn\"") {
writeLocations_default(it, fileId, startLine, startColumn, endLine, endColumn)
}
}
/**
* The label for the 'unknown' file ID.
* Users will want to use `unknownLocation` instead.
* This is lazy, as we don't want to define it in a TRAP file unless
* the TRAP file actually contains something in the 'unknown' file.
*/
protected val unknownFileId: Label<DbFile> by lazy {
val unknownFileLabel = "@\";sourcefile\""
getLabelFor(unknownFileLabel, {
writeFiles(it, "")
})
}
/**
* The label for the 'unknown' location.
* This is lazy, as we don't want to define it in a TRAP file unless
* the TRAP file actually contains something with an 'unknown'
* location.
*/
val unknownLocation: Label<DbLocation> by lazy {
getWholeFileLocation(unknownFileId)
}
/**
* Returns the label for the file `filePath`.
* If `populateFileTables` is true, then this also adds rows to the
* `files` and `folders` tables for this file.
*/
fun mkFileId(filePath: String, populateFileTables: Boolean): Label<DbFile> {
// If a file is in a jar, then the Kotlin compiler gives
// `<jar file>!/<path within jar>` as its path. We need to split
// it as appropriate, to make the right file ID.
val populateFile = PopulateFile(this)
val splitFilePath = filePath.split("!/")
if(splitFilePath.size == 1) {
return populateFile.getFileLabel(File(filePath), populateFileTables)
} else {
return populateFile.getFileInJarLabel(File(splitFilePath.get(0)), splitFilePath.get(1), populateFileTables)
}
}
/**
* If you have an ID for a file, then this gets a label for the
* location representing the whole of that file.
*/
fun getWholeFileLocation(fileId: Label<DbFile>): Label<DbLocation> {
return getLocation(fileId, 0, 0, 0, 0)
}
/**
* Write a raw string into the TRAP file. Users should call one of
* the wrapper functions instead.
*/
fun writeTrap(trap: String) {
bw.write(trap)
}
/**
* Write a comment into the TRAP file.
*/
fun writeComment(comment: String) {
writeTrap("// ${comment.replace("\n", "\n// ")}\n")
}
/**
* Flush the TRAP file.
*/
fun flush() {
bw.flush()
}
/**
* Escape a string so that it can be used in a TRAP string literal,
* i.e. with `"` escaped as `""`.
*/
fun escapeTrapString(str: String) = str.replace("\"", "\"\"")
/**
* TRAP string literals are limited to 1 megabyte.
*/
private val MAX_STRLEN = 1.shl(20)
/**
* Truncate a string, if necessary, so that it can be used as a TRAP
* string literal. TRAP string literals are limited to 1 megabyte.
*/
fun truncateString(str: String): String {
val len = str.length
val newLen = UTF8Util.encodablePrefixLength(str, MAX_STRLEN)
if (newLen < len) {
loggerBase.warn(diagnosticTrapWriter ?: this,
"Truncated string of length $len",
"Truncated string of length $len, starting '${str.take(100)}', ending '${str.takeLast(100)}'")
return str.take(newLen)
} else {
return str
}
}
/**
* Gets a FileTrapWriter like this one (using the same label manager,
* writer etc), but using the given `filePath` for locations.
*/
fun makeFileTrapWriter(filePath: String, populateFileTables: Boolean) =
FileTrapWriter(loggerBase, lm, bw, diagnosticTrapWriter, filePath, populateFileTables)
/**
* Gets a FileTrapWriter like this one (using the same label manager,
* writer etc), but using the given `IrFile` for locations.
*/
fun makeSourceFileTrapWriter(file: IrFile, populateFileTables: Boolean) =
SourceFileTrapWriter(loggerBase, lm, bw, diagnosticTrapWriter, file, populateFileTables)
}
/**
* A `FileTrapWriter` is used when we know which file we are extracting
* entities from, so we can at least give the right file as a location.
*
* An ID for the file will be created, and if `populateFileTables` is
* true then we will also add rows to the `files` and `folders` tables
* for it.
*/
open class FileTrapWriter (
loggerBase: LoggerBase,
lm: TrapLabelManager,
bw: BufferedWriter,
diagnosticTrapWriter: TrapWriter?,
val filePath: String,
populateFileTables: Boolean
): TrapWriter (loggerBase, lm, bw, diagnosticTrapWriter) {
/**
* The ID for the file that we are extracting from.
*/
val fileId = mkFileId(filePath, populateFileTables)
private fun offsetMinOf(default: Int, vararg options: Int?): Int {
if (default == UNDEFINED_OFFSET || default == SYNTHETIC_OFFSET) {
return default
}
var currentMin = default
for (option in options) {
if (option != null && option != UNDEFINED_OFFSET && option != SYNTHETIC_OFFSET && option < currentMin) {
currentMin = option
}
}
return currentMin
}
private fun getStartOffset(e: IrElement): Int {
return when (e) {
is IrCall -> {
// Calls have incorrect startOffset, so we adjust them:
val dr = e.dispatchReceiver?.let { getStartOffset(it) }
val er = e.extensionReceiver?.let { getStartOffset(it) }
offsetMinOf(e.startOffset, dr, er)
}
else -> e.startOffset
}
}
private fun getEndOffset(e: IrElement): Int {
return e.endOffset
}
/**
* Gets a label for the location of `e`.
*/
fun getLocation(e: IrElement): Label<DbLocation> {
return getLocation(getStartOffset(e), getEndOffset(e))
}
/**
* Gets a label for the location corresponding to `startOffset` and
* `endOffset` within this file.
*/
open fun getLocation(startOffset: Int, endOffset: Int): Label<DbLocation> {
// We don't have a FileEntry to look up the offsets in, so all
// we can do is return a whole-file location.
return getWholeFileLocation()
}
/**
* Gets the location of `e` as a human-readable string. Only used in
* log messages and exception messages.
*/
open fun getLocationString(e: IrElement): String {
// We don't have a FileEntry to look up the offsets in, so all
// we can do is return a whole-file location. We omit the
// `:0:0:0:0` so that it is easy to distinguish from a location
// where we have actually determined the start/end lines/columns
// to be 0.
return "file://$filePath"
}
/**
* Gets a label for the location representing the whole of this file.
*/
fun getWholeFileLocation(): Label<DbLocation> {
return getWholeFileLocation(fileId)
}
}
/**
* A `SourceFileTrapWriter` is used when not only do we know which file
* we are extracting entities from, but we also have an `IrFileEntry`
* (from an `IrFile`) which allows us to map byte offsets to line
* and column numbers.
*
* An ID for the file will be created, and if `populateFileTables` is
* true then we will also add rows to the `files` and `folders` tables
* for it.
*/
class SourceFileTrapWriter (
loggerBase: LoggerBase,
lm: TrapLabelManager,
bw: BufferedWriter,
diagnosticTrapWriter: TrapWriter?,
val irFile: IrFile,
populateFileTables: Boolean) :
FileTrapWriter(loggerBase, lm, bw, diagnosticTrapWriter, irFile.path, populateFileTables) {
/**
* The file entry for the file that we are extracting from.
* Used to map offsets to line/column numbers.
*/
private val fileEntry = irFile.fileEntry
override fun getLocation(startOffset: Int, endOffset: Int): Label<DbLocation> {
if (startOffset == UNDEFINED_OFFSET || endOffset == UNDEFINED_OFFSET) {
if (startOffset != endOffset) {
loggerBase.warn(this, "Location with inconsistent offsets (start $startOffset, end $endOffset)", null)
}
return getWholeFileLocation()
}
if (startOffset == SYNTHETIC_OFFSET || endOffset == SYNTHETIC_OFFSET) {
if (startOffset != endOffset) {
loggerBase.warn(this, "Location with inconsistent offsets (start $startOffset, end $endOffset)", null)
}
return getWholeFileLocation()
}
// If this is the location for a compiler-generated element, then it will
// be a zero-width location. QL doesn't support these, so we translate it
// into a one-width location.
val endColumnOffset = if (startOffset == endOffset) 1 else 0
return getLocation(
fileId,
fileEntry.getLineNumber(startOffset) + 1,
fileEntry.getColumnNumber(startOffset) + 1,
fileEntry.getLineNumber(endOffset) + 1,
fileEntry.getColumnNumber(endOffset) + endColumnOffset)
}
override fun getLocationString(e: IrElement): String {
if (e.startOffset == UNDEFINED_OFFSET || e.endOffset == UNDEFINED_OFFSET) {
if (e.startOffset != e.endOffset) {
loggerBase.warn(this, "Location with inconsistent offsets (start ${e.startOffset}, end ${e.endOffset})", null)
}
return "<unknown location while processing $filePath>"
}
if (e.startOffset == SYNTHETIC_OFFSET || e.endOffset == SYNTHETIC_OFFSET) {
if (e.startOffset != e.endOffset) {
loggerBase.warn(this, "Location with inconsistent offsets (start ${e.startOffset}, end ${e.endOffset})", null)
}
return "<synthetic location while processing $filePath>"
}
val startLine = fileEntry.getLineNumber(e.startOffset) + 1
val startColumn = fileEntry.getColumnNumber(e.startOffset) + 1
val endLine = fileEntry.getLineNumber(e.endOffset) + 1
val endColumn = fileEntry.getColumnNumber(e.endOffset)
return "file://$filePath:$startLine:$startColumn:$endLine:$endColumn"
}
}
| java/kotlin-extractor/src/main/kotlin/TrapWriter.kt | 252028630 |
/*
* Copyright 2022, Leanplum, Inc. All rights reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.leanplum.migration.push
import android.content.Context
import android.os.Bundle
import com.clevertap.android.sdk.Utils
import com.clevertap.android.sdk.pushnotification.PushConstants.PushType
import com.clevertap.android.sdk.pushnotification.PushNotificationHandler
class MiPushMigrationHandler internal constructor() {
fun createNotification(context: Context?, messageContent: String?): Boolean {
val messageBundle: Bundle = Utils.stringToBundle(messageContent)
val isSuccess = try {
PushNotificationHandler.getPushNotificationHandler().onMessageReceived(
context,
messageBundle,
PushType.XPS.toString())
} catch (t: Throwable) {
t.printStackTrace()
false
}
return isSuccess
}
fun onNewToken(context: Context?, token: String?): Boolean {
var isSuccess = false
try {
PushNotificationHandler.getPushNotificationHandler().onNewToken(
context,
token,
PushType.XPS.type
)
isSuccess = true
} catch (t: Throwable) {
t.printStackTrace()
}
return isSuccess
}
}
| AndroidSDKCore/src/main/java/com/leanplum/migration/push/MiPushMigrationHandler.kt | 2298333131 |
package jp.juggler.subwaytooter.mfm
import android.graphics.Color
import android.graphics.Typeface
import android.text.style.ForegroundColorSpan
import android.util.SparseBooleanArray
import jp.juggler.util.asciiPattern
import jp.juggler.util.firstNonNull
import jp.juggler.util.fontSpan
import jp.juggler.util.groupEx
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern
// ```code``` マークダウン内部ではプログラムっぽい何かの文法強調表示が行われる
object MisskeySyntaxHighlighter {
private val keywords = HashSet<String>().apply {
val _keywords = arrayOf(
"true",
"false",
"null",
"nil",
"undefined",
"void",
"var",
"const",
"let",
"mut",
"dim",
"if",
"then",
"else",
"switch",
"match",
"case",
"default",
"for",
"each",
"in",
"while",
"loop",
"continue",
"break",
"do",
"goto",
"next",
"end",
"sub",
"throw",
"try",
"catch",
"finally",
"enum",
"delegate",
"function",
"func",
"fun",
"fn",
"return",
"yield",
"async",
"await",
"require",
"include",
"import",
"imports",
"export",
"exports",
"from",
"as",
"using",
"use",
"internal",
"module",
"namespace",
"where",
"select",
"struct",
"union",
"new",
"delete",
"this",
"super",
"base",
"class",
"interface",
"abstract",
"static",
"public",
"private",
"protected",
"virtual",
"partial",
"override",
"extends",
"implements",
"constructor"
)
// lower
addAll(_keywords)
// UPPER
addAll(_keywords.map { it.uppercase() })
// Snake
addAll(_keywords.map { k -> k[0].uppercase() + k.substring(1) })
add("NaN")
// 識別子に対して既存の名前と一致するか調べるようになったので、もはやソートの必要はない
}
private val symbolMap = SparseBooleanArray().apply {
"=+-*/%~^&|><!?".forEach { put(it.code, true) }
}
// 文字列リテラルの開始文字のマップ
private val stringStart = SparseBooleanArray().apply {
"\"'`".forEach { put(it.code, true) }
}
private class Token(
val length: Int,
val color: Int = 0,
val italic: Boolean = false,
val comment: Boolean = false,
)
private class Env(
val source: String,
val start: Int,
val end: Int,
) {
// 出力先2
val spanList = SpanList()
fun push(start: Int, token: Token) {
val end = start + token.length
if (token.comment) {
spanList.addLast(start, end, ForegroundColorSpan(Color.BLACK or 0x808000))
} else {
var c = token.color
if (c != 0) {
if (c < 0x1000000) {
c = c or Color.BLACK
}
spanList.addLast(start, end, ForegroundColorSpan(c))
}
if (token.italic) {
spanList.addLast(
start,
end,
fontSpan(Typeface.defaultFromStyle(Typeface.ITALIC))
)
}
}
}
// スキャン位置
var pos: Int = start
fun remainMatcher(pattern: Pattern): Matcher =
MatcherCache.matcher(pattern, source, pos, end)
fun parse(): SpanList {
var i = start
var lastEnd = start
fun closeTextToken(textEnd: Int) {
val length = textEnd - lastEnd
if (length > 0) {
push(lastEnd, Token(length = length))
lastEnd = textEnd
}
}
while (i < end) {
pos = i
val token = elements.firstNonNull {
val t = this.it()
when {
t == null -> null // not match
i + t.length > end -> null // overrun detected
else -> t
}
}
if (token == null) {
++i
continue
}
closeTextToken(i)
push(i, token)
i += token.length
lastEnd = i
}
closeTextToken(end)
return spanList
}
}
private val reLineComment = """\A//.*"""
.asciiPattern()
private val reBlockComment = """\A/\*.*?\*/"""
.asciiPattern(Pattern.DOTALL)
private val reNumber = """\A[\-+]?[\d.]+"""
.asciiPattern()
private val reLabel = """\A@([A-Z_-][A-Z0-9_-]*)"""
.asciiPattern(Pattern.CASE_INSENSITIVE)
private val reKeyword = """\A([A-Z_-][A-Z0-9_-]*)([ \t]*\()?"""
.asciiPattern(Pattern.CASE_INSENSITIVE)
private val reContainsAlpha = """[A-Za-z_]"""
.asciiPattern()
private const val charH80 = 0x80.toChar()
private val elements = arrayOf<Env.() -> Token?>(
// マルチバイト文字をまとめて読み飛ばす
{
var s = pos
while (s < end && source[s] >= charH80) {
++s
}
when {
s > pos -> Token(length = s - pos)
else -> null
}
},
// 空白と改行をまとめて読み飛ばす
{
var s = pos
while (s < end && source[s] <= ' ') {
++s
}
when {
s > pos -> Token(length = s - pos)
else -> null
}
},
// comment
{
val match = remainMatcher(reLineComment)
when {
!match.find() -> null
else -> Token(length = match.end() - match.start(), comment = true)
}
},
// block comment
{
val match = remainMatcher(reBlockComment)
when {
!match.find() -> null
else -> Token(length = match.end() - match.start(), comment = true)
}
},
// string
{
val beginChar = source[pos]
if (!stringStart[beginChar.code]) return@arrayOf null
var i = pos + 1
while (i < end) {
val char = source[i++]
if (char == beginChar) {
break // end
} else if (char == '\n' || i >= end) {
i = 0 // not string literal
break
} else if (char == '\\' && i < end) {
++i // \" では閉じないようにする
}
}
when {
i <= pos -> null
else -> Token(length = i - pos, color = 0xe96900)
}
},
// regexp
{
if (source[pos] != '/') return@arrayOf null
val regexp = StringBuilder()
var i = pos + 1
while (i < end) {
val char = source[i++]
if (char == '/') {
break
} else if (char == '\n' || i >= end) {
i = 0 // not closed
break
} else {
regexp.append(char)
if (char == '\\' && i < end) {
regexp.append(source[i++])
}
}
}
when {
i == 0 -> null
regexp.isEmpty() -> null
regexp.first() == ' ' && regexp.last() == ' ' -> null
else -> Token(length = regexp.length + 2, color = 0xe9003f)
}
},
// label
{
// 直前に識別子があればNG
val prev = if (pos <= 0) null else source[pos - 1]
if (prev?.isLetterOrDigit() == true) return@arrayOf null
val match = remainMatcher(reLabel)
if (!match.find()) return@arrayOf null
val matchEnd = match.end()
when {
// @user@host のように直後に@が続くのはNG
matchEnd < end && source[matchEnd] == '@' -> null
else -> Token(length = match.end() - pos, color = 0xe9003f)
}
},
// number
{
val prev = if (pos <= 0) null else source[pos - 1]
if (prev?.isLetterOrDigit() == true) return@arrayOf null
val match = remainMatcher(reNumber)
when {
!match.find() -> null
else -> Token(length = match.end() - pos, color = 0xae81ff)
}
},
// method, property, keyword
{
// 直前の文字が識別子に使えるなら識別子の開始とはみなさない
val prev = if (pos <= 0) null else source[pos - 1]
if (prev?.isLetterOrDigit() == true || prev == '_') return@arrayOf null
val match = remainMatcher(reKeyword)
if (!match.find()) return@arrayOf null
val kw = match.groupEx(1)!!
val bracket = match.groupEx(2) // may null
when {
// 英数字や_を含まないキーワードは無視する
// -moz-foo- や __ はキーワードだが、 - や -- はキーワードではない
!reContainsAlpha.matcher(kw).find() -> null
// メソッド呼び出しは対象が変数かプロパティかに関わらずメソッドの色になる
bracket?.isNotEmpty() == true ->
Token(length = kw.length, color = 0x8964c1, italic = true)
// 変数や定数ではなくプロパティならプロパティの色になる
prev == '.' -> Token(length = kw.length, color = 0xa71d5d)
// 予約語ではない
// 強調表示しないが、識別子単位で読み飛ばす
!keywords.contains(kw) -> Token(length = kw.length)
else -> when (kw) {
// 定数
"true", "false", "null", "nil", "undefined", "NaN" ->
Token(length = kw.length, color = 0xae81ff)
// その他の予約語
else -> Token(length = kw.length, color = 0x2973b7)
}
}
},
// symbol
{
val c = source[pos]
when {
symbolMap.get(c.code, false) ->
Token(length = 1, color = 0x42b983)
c == '-' ->
Token(length = 1, color = 0x42b983)
else -> null
}
}
)
fun parse(source: String) = Env(source, 0, source.length).parse()
}
| app/src/main/java/jp/juggler/subwaytooter/mfm/MisskeySyntaxHighlighter.kt | 1451869500 |
// snippet-sourcedescription:[PublishTextSMS.kt demonstrates how to send an Amazon Simple Notification Service (Amazon SNS) text message.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-keyword:[Amazon Simple Notification Service]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.sns
// snippet-start:[sns.kotlin.PublishTextSMS.import]
import aws.sdk.kotlin.services.sns.SnsClient
import aws.sdk.kotlin.services.sns.model.PublishRequest
import kotlin.system.exitProcess
// snippet-end:[sns.kotlin.PublishTextSMS.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<message> <phoneNumber>
Where:
message - The message text to send.
phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).
"""
if (args.size != 2) {
println(usage)
exitProcess(0)
}
val message = args[0]
val phoneNumber = args[1]
pubTextSMS(message, phoneNumber)
}
// snippet-start:[sns.kotlin.PublishTextSMS.main]
suspend fun pubTextSMS(messageVal: String?, phoneNumberVal: String?) {
val request = PublishRequest {
message = messageVal
phoneNumber = phoneNumberVal
}
SnsClient { region = "us-east-1" }.use { snsClient ->
val result = snsClient.publish(request)
println("${result.messageId} message sent.")
}
}
// snippet-end:[sns.kotlin.PublishTextSMS.main]
| kotlin/services/sns/src/main/kotlin/com/kotlin/sns/PublishTextSMS.kt | 1416435585 |
package com.github.codeql
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.config.KotlinCompilerVersion
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.IrElement
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.lang.management.*
import java.nio.file.Files
import java.nio.file.Paths
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import com.semmle.util.files.FileUtil
import kotlin.system.exitProcess
/*
* KotlinExtractorExtension is the main entry point of the CodeQL Kotlin
* extractor. When the jar is used as a kotlinc plugin, kotlinc will
* call the `generate` method.
*/
class KotlinExtractorExtension(
// The filepath for the invocation TRAP file.
// This TRAP file is for this invocation of the extractor as a
// whole, not tied to a particular source file. It contains
// information about which files this invocation compiled, and
// any warnings or errors encountered during the invocation.
private val invocationTrapFile: String,
// By default, if a TRAP file we want to generate for a source
// file already exists, then we will do nothing. If this is set,
// then we will instead generate the TRAP file, and give a
// warning if we would generate different TRAP to that which
// already exists.
private val checkTrapIdentical: Boolean,
// If non-null, then this is the number of milliseconds since
// midnight, January 1, 1970 UTC (as returned by Java's
// `System.currentTimeMillis()`. If this is given, then it is used
// to record the time taken to compile the source code, which is
// presumed to be the difference between this time and the time
// that this plugin is invoked.
private val compilationStartTime: Long?,
// Under normal conditions, the extractor runs during a build of
// the project, and kotlinc continues after the plugin has finished.
// If the plugin is being used independently of a build, then this
// can be set to true to make the plugin terminate the kotlinc
// invocation when it has finished. This means that kotlinc will not
// write any `.class` files etc.
private val exitAfterExtraction: Boolean)
: IrGenerationExtension {
// This is the main entry point to the extractor.
// It will be called by kotlinc with the IR for the files being
// compiled in `moduleFragment`, and `pluginContext` providing
// various utility functions.
override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
try {
runExtractor(moduleFragment, pluginContext)
// We catch Throwable rather than Exception, as we want to
// continue trying to extract everything else even if we get a
// stack overflow or an assertion failure in one file.
} catch(e: Throwable) {
// If we get an exception at the top level, then something's
// gone very wrong. Don't try to be too fancy, but try to
// log a simple message.
val msg = "[ERROR] CodeQL Kotlin extractor: Top-level exception."
// First, if we can find our log directory, then let's try
// making a log file there:
val extractorLogDir = System.getenv("CODEQL_EXTRACTOR_JAVA_LOG_DIR")
if (extractorLogDir != null && extractorLogDir != "") {
// We use a slightly different filename pattern compared
// to normal logs. Just the existence of a `-top` log is
// a sign that something's gone very wrong.
val logFile = File.createTempFile("kotlin-extractor-top.", ".log", File(extractorLogDir))
logFile.writeText(msg)
// Now we've got that out, let's see if we can append a stack trace too
logFile.appendText(e.stackTraceToString())
} else {
// We don't have much choice here except to print to
// stderr and hope for the best.
System.err.println(msg)
e.printStackTrace(System.err)
}
}
if (exitAfterExtraction) {
exitProcess(0)
}
}
private fun runExtractor(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
val startTimeMs = System.currentTimeMillis()
// This default should be kept in sync with com.semmle.extractor.java.interceptors.KotlinInterceptor.initializeExtractionContext
val trapDir = File(System.getenv("CODEQL_EXTRACTOR_JAVA_TRAP_DIR").takeUnless { it.isNullOrEmpty() } ?: "kotlin-extractor/trap")
val compression_env_var = "CODEQL_EXTRACTOR_JAVA_OPTION_TRAP_COMPRESSION"
val compression_option = System.getenv(compression_env_var)
val defaultCompression = Compression.GZIP
val (compression, compressionWarning) =
if (compression_option == null) {
Pair(defaultCompression, null)
} else {
try {
@OptIn(kotlin.ExperimentalStdlibApi::class) // Annotation required by kotlin versions < 1.5
val requested_compression = Compression.valueOf(compression_option.uppercase())
if (requested_compression == Compression.BROTLI) {
Pair(Compression.GZIP, "Kotlin extractor doesn't support Brotli compression. Using GZip instead.")
} else {
Pair(requested_compression, null)
}
} catch (e: IllegalArgumentException) {
Pair(defaultCompression,
"Unsupported compression type (\$$compression_env_var) \"$compression_option\". Supported values are ${Compression.values().joinToString()}")
}
}
// The invocation TRAP file will already have been started
// before the plugin is run, so we always use no compression
// and we open it in append mode.
FileOutputStream(File(invocationTrapFile), true).bufferedWriter().use { invocationTrapFileBW ->
val invocationExtractionProblems = ExtractionProblems()
val lm = TrapLabelManager()
val logCounter = LogCounter()
val loggerBase = LoggerBase(logCounter)
val tw = TrapWriter(loggerBase, lm, invocationTrapFileBW, null)
// The interceptor has already defined #compilation = *
val compilation: Label<DbCompilation> = StringLabel("compilation")
tw.writeCompilation_started(compilation)
tw.writeCompilation_info(compilation, "Kotlin Compiler Version", KotlinCompilerVersion.getVersion() ?: "<unknown>")
val extractor_name = this::class.java.getResource("extractor.name")?.readText() ?: "<unknown>"
tw.writeCompilation_info(compilation, "Kotlin Extractor Name", extractor_name)
if (compilationStartTime != null) {
tw.writeCompilation_compiler_times(compilation, -1.0, (System.currentTimeMillis()-compilationStartTime)/1000.0)
}
tw.flush()
val logger = Logger(loggerBase, tw)
logger.info("Extraction started")
logger.flush()
logger.info("Extraction for invocation TRAP file $invocationTrapFile")
logger.flush()
logger.info("Kotlin version ${KotlinCompilerVersion.getVersion()}")
logger.flush()
logPeakMemoryUsage(logger, "before extractor")
if (System.getenv("CODEQL_EXTRACTOR_JAVA_KOTLIN_DUMP") == "true") {
logger.info("moduleFragment:\n" + moduleFragment.dump())
}
if (compressionWarning != null) {
logger.warn(compressionWarning)
}
val primitiveTypeMapping = PrimitiveTypeMapping(logger, pluginContext)
// FIXME: FileUtil expects a static global logger
// which should be provided by SLF4J's factory facility. For now we set it here.
FileUtil.logger = logger
val srcDir = File(System.getenv("CODEQL_EXTRACTOR_JAVA_SOURCE_ARCHIVE_DIR").takeUnless { it.isNullOrEmpty() } ?: "kotlin-extractor/src")
srcDir.mkdirs()
val globalExtensionState = KotlinExtractorGlobalState()
moduleFragment.files.mapIndexed { index: Int, file: IrFile ->
val fileExtractionProblems = FileExtractionProblems(invocationExtractionProblems)
val fileTrapWriter = tw.makeSourceFileTrapWriter(file, true)
loggerBase.setFileNumber(index)
fileTrapWriter.writeCompilation_compiling_files(compilation, index, fileTrapWriter.fileId)
doFile(compression, fileExtractionProblems, invocationTrapFile, fileTrapWriter, checkTrapIdentical, loggerBase, trapDir, srcDir, file, primitiveTypeMapping, pluginContext, globalExtensionState)
fileTrapWriter.writeCompilation_compiling_files_completed(compilation, index, fileExtractionProblems.extractionResult())
}
loggerBase.printLimitedDiagnosticCounts(tw)
logPeakMemoryUsage(logger, "after extractor")
logger.info("Extraction completed")
logger.flush()
val compilationTimeMs = System.currentTimeMillis() - startTimeMs
tw.writeCompilation_finished(compilation, -1.0, compilationTimeMs.toDouble() / 1000, invocationExtractionProblems.extractionResult())
tw.flush()
loggerBase.close()
}
}
private fun logPeakMemoryUsage(logger: Logger, time: String) {
logger.info("Peak memory: Usage $time")
val beans = ManagementFactory.getMemoryPoolMXBeans()
var heap: Long = 0
var nonheap: Long = 0
for (bean in beans) {
val peak = bean.getPeakUsage().getUsed()
val kind = when (bean.getType()) {
MemoryType.HEAP -> { heap += peak; "heap" }
MemoryType.NON_HEAP -> { nonheap += peak; "non-heap" }
else -> "unknown"
}
logger.info("Peak memory: * Peak for $kind bean ${bean.getName()} is $peak")
}
logger.info("Peak memory: * Total heap peak: $heap")
logger.info("Peak memory: * Total non-heap peak: $nonheap")
}
}
class KotlinExtractorGlobalState {
// These three record mappings of classes, functions and fields that should be replaced wherever they are found.
// As of now these are only used to fix IR generated by the Gradle Android Extensions plugin, hence e.g. IrProperty
// doesn't have a map as that plugin doesn't generate them. If and when these are used more widely additional maps
// should be added here.
val syntheticToRealClassMap = HashMap<IrClass, IrClass?>()
val syntheticToRealFunctionMap = HashMap<IrFunction, IrFunction?>()
val syntheticToRealFieldMap = HashMap<IrField, IrField?>()
}
/*
The `ExtractionProblems` class is used to record whether this invocation
had any problems. It distinguish 2 kinds of problem:
* Recoverable problems: e.g. if we check something that we expect to be
non-null and find that it is null.
* Non-recoverable problems: if we catch an exception.
*/
open class ExtractionProblems {
private var recoverableProblem = false
private var nonRecoverableProblem = false
open fun setRecoverableProblem() {
recoverableProblem = true
}
open fun setNonRecoverableProblem() {
nonRecoverableProblem = true
}
fun extractionResult(): Int {
if(nonRecoverableProblem) {
return 2
} else if(recoverableProblem) {
return 1
} else {
return 0
}
}
}
/*
The `FileExtractionProblems` is analogous to `ExtractionProblems`,
except it records whether there were any problems while extracting a
particular source file.
*/
class FileExtractionProblems(val invocationExtractionProblems: ExtractionProblems): ExtractionProblems() {
override fun setRecoverableProblem() {
super.setRecoverableProblem()
invocationExtractionProblems.setRecoverableProblem()
}
override fun setNonRecoverableProblem() {
super.setNonRecoverableProblem()
invocationExtractionProblems.setNonRecoverableProblem()
}
}
/*
This function determines whether 2 TRAP files should be considered to be
equivalent. It returns `true` iff all of their non-comment lines are
identical.
*/
private fun equivalentTrap(r1: BufferedReader, r2: BufferedReader): Boolean {
r1.use { br1 ->
r2.use { br2 ->
while(true) {
val l1 = br1.readLine()
val l2 = br2.readLine()
if (l1 == null && l2 == null) {
return true
} else if (l1 == null || l2 == null) {
return false
} else if (l1 != l2) {
if (!l1.startsWith("//") || !l2.startsWith("//")) {
return false
}
}
}
}
}
}
private fun doFile(
compression: Compression,
fileExtractionProblems: FileExtractionProblems,
invocationTrapFile: String,
fileTrapWriter: FileTrapWriter,
checkTrapIdentical: Boolean,
loggerBase: LoggerBase,
dbTrapDir: File,
dbSrcDir: File,
srcFile: IrFile,
primitiveTypeMapping: PrimitiveTypeMapping,
pluginContext: IrPluginContext,
globalExtensionState: KotlinExtractorGlobalState) {
val srcFilePath = srcFile.path
val logger = FileLogger(loggerBase, fileTrapWriter)
logger.info("Extracting file $srcFilePath")
logger.flush()
val context = logger.loggerBase.extractorContextStack
if (!context.empty()) {
logger.warn("Extractor context was not empty. It thought:")
context.clear()
}
val srcFileRelativePath = srcFilePath.replace(':', '_')
val dbSrcFilePath = Paths.get("$dbSrcDir/$srcFileRelativePath")
val dbSrcDirPath = dbSrcFilePath.parent
Files.createDirectories(dbSrcDirPath)
val srcTmpFile = File.createTempFile(dbSrcFilePath.fileName.toString() + ".", ".src.tmp", dbSrcDirPath.toFile())
srcTmpFile.outputStream().use {
Files.copy(Paths.get(srcFilePath), it)
}
srcTmpFile.renameTo(dbSrcFilePath.toFile())
val trapFileName = "$dbTrapDir/$srcFileRelativePath.trap"
val trapFileWriter = getTrapFileWriter(compression, logger, trapFileName)
if (checkTrapIdentical || !trapFileWriter.exists()) {
trapFileWriter.makeParentDirectory()
try {
trapFileWriter.getTempWriter().use { trapFileBW ->
// We want our comments to be the first thing in the file,
// so start off with a mere TrapWriter
val tw = TrapWriter(loggerBase, TrapLabelManager(), trapFileBW, fileTrapWriter)
tw.writeComment("Generated by the CodeQL Kotlin extractor for kotlin source code")
tw.writeComment("Part of invocation $invocationTrapFile")
// Now elevate to a SourceFileTrapWriter, and populate the
// file information
val sftw = tw.makeSourceFileTrapWriter(srcFile, true)
val externalDeclExtractor = ExternalDeclExtractor(logger, invocationTrapFile, srcFilePath, primitiveTypeMapping, pluginContext, globalExtensionState, fileTrapWriter)
val linesOfCode = LinesOfCode(logger, sftw, srcFile)
val fileExtractor = KotlinFileExtractor(logger, sftw, linesOfCode, srcFilePath, null, externalDeclExtractor, primitiveTypeMapping, pluginContext, KotlinFileExtractor.DeclarationStack(), globalExtensionState)
fileExtractor.extractFileContents(srcFile, sftw.fileId)
externalDeclExtractor.extractExternalClasses()
}
if (checkTrapIdentical && trapFileWriter.exists()) {
if (equivalentTrap(trapFileWriter.getTempReader(), trapFileWriter.getRealReader())) {
trapFileWriter.deleteTemp()
} else {
trapFileWriter.renameTempToDifferent()
}
} else {
trapFileWriter.renameTempToReal()
}
// We catch Throwable rather than Exception, as we want to
// continue trying to extract everything else even if we get a
// stack overflow or an assertion failure in one file.
} catch (e: Throwable) {
logger.error("Failed to extract '$srcFilePath'. " + trapFileWriter.debugInfo(), e)
context.clear()
fileExtractionProblems.setNonRecoverableProblem()
}
}
}
enum class Compression { NONE, GZIP, BROTLI }
private fun getTrapFileWriter(compression: Compression, logger: FileLogger, trapFileName: String): TrapFileWriter {
return when (compression) {
Compression.NONE -> NonCompressedTrapFileWriter(logger, trapFileName)
Compression.GZIP -> GZipCompressedTrapFileWriter(logger, trapFileName)
Compression.BROTLI -> {
// Brotli should have been replaced with gzip earlier, but
// if we somehow manage to get here then keep going
logger.error("Impossible Brotli compression requested. Using Gzip instead.")
getTrapFileWriter(Compression.GZIP, logger, trapFileName)
}
}
}
private abstract class TrapFileWriter(val logger: FileLogger, trapName: String, val extension: String) {
private val realFile = File(trapName + extension)
private val parentDir = realFile.parentFile
lateinit private var tempFile: File
fun debugInfo(): String {
if (this::tempFile.isInitialized) {
return "Partial TRAP file location is $tempFile"
} else {
return "Temporary file not yet created."
}
}
fun makeParentDirectory() {
parentDir.mkdirs()
}
fun exists(): Boolean {
return realFile.exists()
}
abstract protected fun getReader(file: File): BufferedReader
abstract protected fun getWriter(file: File): BufferedWriter
fun getRealReader(): BufferedReader {
return getReader(realFile)
}
fun getTempReader(): BufferedReader {
return getReader(tempFile)
}
fun getTempWriter(): BufferedWriter {
if (this::tempFile.isInitialized) {
logger.error("Temp writer reinitialized for $realFile")
}
tempFile = File.createTempFile(realFile.getName() + ".", ".trap.tmp" + extension, parentDir)
return getWriter(tempFile)
}
fun deleteTemp() {
if (!tempFile.delete()) {
logger.warn("Failed to delete $tempFile")
}
}
fun renameTempToDifferent() {
val trapDifferentFile = File.createTempFile(realFile.getName() + ".", ".trap.different" + extension, parentDir)
if (tempFile.renameTo(trapDifferentFile)) {
logger.warn("TRAP difference: $realFile vs $trapDifferentFile")
} else {
logger.warn("Failed to rename $tempFile to $realFile")
}
}
fun renameTempToReal() {
if (!tempFile.renameTo(realFile)) {
logger.warn("Failed to rename $tempFile to $realFile")
}
}
}
private class NonCompressedTrapFileWriter(logger: FileLogger, trapName: String): TrapFileWriter(logger, trapName, "") {
override protected fun getReader(file: File): BufferedReader {
return file.bufferedReader()
}
override protected fun getWriter(file: File): BufferedWriter {
return file.bufferedWriter()
}
}
private class GZipCompressedTrapFileWriter(logger: FileLogger, trapName: String): TrapFileWriter(logger, trapName, ".gz") {
override protected fun getReader(file: File): BufferedReader {
return BufferedReader(InputStreamReader(GZIPInputStream(BufferedInputStream(FileInputStream(file)))))
}
override protected fun getWriter(file: File): BufferedWriter {
return BufferedWriter(OutputStreamWriter(GZIPOutputStream(BufferedOutputStream(FileOutputStream(file)))))
}
}
| java/kotlin-extractor/src/main/kotlin/KotlinExtractorExtension.kt | 2494507562 |
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.features.settings
import androidx.preference.Preference
class ProfileSettingsFragment : SettingsFragmentBase() {
public override fun updateItemSummaries() {
setSummary(SettingsManager.KEY_PROFILE_FIRST_NAME, SettingsManager.profileFirstName)
setSummary(SettingsManager.KEY_PROFILE_LAST_NAME, SettingsManager.profileLastName)
setSummary(
SettingsManager.KEY_PROFILE_BIRTHDAY,
SettingsManager.profileBirthDayFormatted ?: ""
)
setSummary(SettingsManager.KEY_PROFILE_CLUB, SettingsManager.profileClub)
setSummary(SettingsManager.KEY_PROFILE_LICENCE_NUMBER, SettingsManager.profileLicenceNumber)
}
override fun onDisplayPreferenceDialog(preference: Preference) {
if (preference !is DatePreference) {
super.onDisplayPreferenceDialog(preference)
return
}
val f = DatePreferenceDialogFragmentCompat.newInstance(preference.getKey())
f.setTargetFragment(this, 0)
f.show(fragmentManager!!, DIALOG_FRAGMENT_TAG)
}
companion object {
private const val DIALOG_FRAGMENT_TAG =
"androidx.preference.PreferenceFragment.DIALOG"
}
}
| app/src/main/java/de/dreier/mytargets/features/settings/ProfileSettingsFragment.kt | 2675965007 |
package me.ranmocy.rcaltrain.models
import java.util.*
/** Represents the time since midnight. */
class DayTime : Comparable<DayTime> {
private val minutesSinceMidnight: Long
constructor(secondsSinceMidnight: Long) {
this.minutesSinceMidnight = secondsSinceMidnight / 60
}
private constructor(hours: Int, minutes: Int) {
this.minutesSinceMidnight = (hours * 60 + minutes).toLong()
}
override fun compareTo(other: DayTime): Int {
return (this.minutesSinceMidnight - other.minutesSinceMidnight).toInt()
}
override fun toString(): String {
return String.format(Locale.getDefault(), "%02d:%02d",
minutesSinceMidnight / 60 % 24, minutesSinceMidnight % 60)
}
fun toSecondsSinceMidnight(): Long {
return minutesSinceMidnight * 60
}
/**
* Returns the interval time in minutes from this [DayTime] to the given [DayTime].
*/
fun toInMinutes(another: DayTime): Long {
return another.minutesSinceMidnight - this.minutesSinceMidnight
}
companion object {
fun now(): DayTime {
val calendar = Calendar.getInstance()
return DayTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE))
}
}
}
| android/app/src/main/java/me/ranmocy/rcaltrain/models/DayTime.kt | 3237278458 |
package pl.dawidfiruzek.sharelog.util.screenshot
internal typealias Callback = () -> Unit
internal interface ScreenshotUtils {
fun takeScreenshot(filename: String, success: Callback, failure: Callback)
}
| sharelog/src/main/java/pl/dawidfiruzek/sharelog/util/screenshot/ScreenshotUtils.kt | 2732389723 |
package me.angrybyte.activitytasks.activities
import android.Manifest
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_layout.*
import me.angrybyte.activitytasks.R
import me.angrybyte.activitytasks.utils.*
/**
* Superclass of all app's activities. Displays everything that's needed on the UI,
* overriding activities only need to override stuff to provide detailed info about themselves.
*/
abstract class GenericTaskActivity : AppCompatActivity() {
private val PERMISSION_REQUEST_TASKS = 1
private val KEY_ORIGIN_NAME = "KEY_ORIGIN_NAME"
private val KEY_ORIGIN_ID = "KEY_ORIGIN_ID"
private val KEY_ORIGIN_TASK_ID = "KEY_ORIGIN_TASK_ID"
private var reInit: Boolean = false
/* Activity stuff */
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_layout)
@Suppress("DEPRECATION") // not true, this is a valid KitKat permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.GET_TASKS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.GET_TASKS), PERMISSION_REQUEST_TASKS)
} else {
setupActivity()
}
}
override fun onStart() {
super.onStart()
if (reInit) setupActivity()
}
override fun onStop() {
super.onStop()
reInit = true
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
PERMISSION_REQUEST_TASKS -> {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
finish()
} else {
setupActivity()
}
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
intent?.let {
outState.putString(KEY_ORIGIN_NAME, intent.getStringExtra(KEY_ORIGIN_NAME))
outState.putString(KEY_ORIGIN_ID, intent.getStringExtra(KEY_ORIGIN_ID))
outState.putString(KEY_ORIGIN_TASK_ID, intent.getStringExtra(KEY_ORIGIN_TASK_ID))
}
super.onSaveInstanceState(outState)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
setupActivity()
}
/**
* Initializes all views.
*/
private fun setupActivity() {
// update stack details from the current intent and task info
stackInfo.setHtml(getTaskStackHtml())
// update current activity info
val thisActTitle = getActivityTitle() // template already has 'Activity'
val thisActHash = "#${getId()}"
val thisTaskHash = "#${Utils.toHex(taskId)}"
val originActName = getOriginActivity().replace("Activity", "")
val originActHash = "#${getOriginActivityId()}"
val originTaskHash = "#${getOriginTaskId()}"
descriptionText.text = getString(R.string.description_template,
thisActTitle, thisActHash, thisTaskHash, originActName, originActHash, originTaskHash
)
// calculate colors and replace plain IDs with colored IDs
val launcherHash = "#${getString(R.string.activity_name_launcher)[0]}"
val originActColor = if (launcherHash == originActHash) 0xCCCCCC else Utils.parseHex(originActHash)
val originTaskColor = if (launcherHash == originTaskHash) 0xCCCCCC else Utils.parseHex(originTaskHash)
val replacements = arrayOf(thisActHash, thisTaskHash, originActHash, originTaskHash)
val colors = intArrayOf(hashCode(), taskId, originActColor, originTaskColor)
descriptionText.markText(replacements, colors)
// assign click listeners for buttons so that they open the correct activities
val classes = listOf(DefaultActivity::class.java, SingleTaskActivity::class.java, SingleTopActivity::class.java, SingleInstanceActivity::class.java)
listOf(start_default, start_single_task, start_single_top, start_single_instance).forEachIndexed {
i, iView ->
iView.setOnClickListener {
val intent = Intent(GenericTaskActivity@ this, classes[i])
intent.putExtra(KEY_ORIGIN_NAME, GenericTaskActivity@ this.javaClass.simpleName!!)
intent.putExtra(KEY_ORIGIN_ID, getId())
intent.putExtra(KEY_ORIGIN_TASK_ID, Utils.toHex(taskId))
startActivity(intent)
}
}
}
/* Important operations */
/**
* Searches through the current Intent to find the origin Activity name, if supplied.
*/
private fun getOriginActivity() = findInIntent(KEY_ORIGIN_NAME, getString(R.string.activity_name_launcher))
/**
* Searches through the current Intent to find the origin Activity ID, if supplied.
*/
private fun getOriginActivityId() = findInIntent(KEY_ORIGIN_ID, getString(R.string.activity_name_launcher)[0].toString())
/**
* Searches through the current Intent to find the origin Task ID, if supplied.
*/
private fun getOriginTaskId() = findInIntent(KEY_ORIGIN_TASK_ID, getString(R.string.activity_name_launcher)[0].toString())
/**
* Tries to find the current task stack, if possible. Outputs plain HTML text.
*/
private fun getTaskStackHtml(): String {
val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
@Suppress("DEPRECATION") // valid call, even with Lollipop limitations
val taskList = manager.getRunningTasks(10) // this may not work on Lollipop...
if (taskList.isEmpty()) {
return getString(R.string.stack_unknown)
}
val builder = StringBuilder(taskList.size)
for ((i, task) in taskList.withIndex()) {
val colorHash = Utils.toHex(task.id)
val taskId = "<font color=\"#$colorHash\"><b>#$colorHash</b></font>"
val baseName = task.baseActivity.shortClassName
val topName = task.topActivity.shortClassName
val taskDescription = getString(R.string.stack_item_template, taskId, baseName, topName, task.numActivities, task.numRunning)
builder.append("-")
builder.append(taskDescription.replace("\n", "<br>"))
// add new lines only on middle tasks
if (i < taskList.size - 1) {
builder.append("<br><br>")
}
}
return builder.toString()
}
/* Override these in sub-activities */
/**
* Gets the unique activity title from the implementation class.
*/
protected abstract fun getActivityTitle(): String
} | app/src/main/kotlin/me/angrybyte/activitytasks/activities/GenericTaskActivity.kt | 1491675755 |
package org.firezenk.kartographer.extensions
import android.annotation.SuppressLint
import android.support.design.internal.BottomNavigationItemView
import android.support.design.internal.BottomNavigationMenuView
import android.support.design.widget.BottomNavigationView
@SuppressLint("RestrictedApi")
fun BottomNavigationView.disableShiftMode() {
val menuView = this.getChildAt(0) as BottomNavigationMenuView
try {
val shiftingMode = menuView.javaClass.getDeclaredField("mShiftingMode")
shiftingMode.isAccessible = true
shiftingMode.setBoolean(menuView, false)
shiftingMode.isAccessible = false
for (i in 0 until menuView.childCount) {
val item = menuView.getChildAt(i) as BottomNavigationItemView
item.setShiftingMode(false)
// set once again checked value, so view will be updated
item.setChecked(item.itemData.isChecked)
}
} catch (ignored: NoSuchFieldException) {
} catch (ignored: IllegalAccessException) {
}
} | sample/src/main/java/org/firezenk/kartographer/extensions/BottomNavigationViewExt.kt | 2589532267 |
package com.outbrain.ob1k.crud
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.outbrain.ob1k.crud.model.EntityField
internal fun JsonObject.with(name: String, value: Number?): JsonObject {
addProperty(name, value)
return this
}
internal fun JsonObject.with(name: String, value: String?): JsonObject {
addProperty(name, value)
return this
}
internal fun JsonObject.with(name: String, value: Boolean?): JsonObject {
addProperty(name, value)
return this
}
internal fun JsonObject.with(name: String, value: JsonArray?): JsonObject {
add(name, value)
return this
}
internal fun JsonObject.with(name: String, value: List<JsonObject>?): JsonObject {
value?.let {
val arr = JsonArray()
it.forEach { arr.add(it) }
add(name, arr)
}
return this
}
internal fun JsonObject.with(field: EntityField, value: Number?) = with(field.name, value)
internal fun JsonObject.with(field: EntityField, value: String?) = with(field.name, value)
internal fun JsonObject.with(field: EntityField, value: Boolean?) = with(field.name, value)
internal fun JsonObject.with(field: EntityField, value: JsonArray?) = with(field.name, value)
internal fun JsonObject.with(field: EntityField, value: List<JsonObject>?) = with(field.name, value)
internal fun JsonObject.getInt(field: EntityField) = getInt(field.name)
internal fun JsonObject.getLong(field: EntityField) = getLong(field.name)
internal fun JsonObject.getString(field: EntityField) = getString(field.name)
internal fun JsonObject.getBoolean(field: EntityField) = getBoolean(field.name)
internal fun JsonObject.getList(field: EntityField) = getList(field.name)
internal fun JsonObject.id() = getLong("id")
internal fun JsonObject.getInt(name: String) = get(name)?.asInt
internal fun JsonObject.getLong(name: String) = get(name)?.asLong
internal fun JsonObject.getString(name: String) = get(name)?.toString()
internal fun JsonObject.getBoolean(name: String) = get(name)?.asBoolean
internal fun JsonObject.getList(name: String): List<JsonObject>? {
val jsonArray = getAsJsonArray(name) ?: return null
return jsonArray.map { it.asJsonObject }
} | ob1k-crud/src/main/java/com/outbrain/ob1k/crud/JsonUtils.kt | 3975616389 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.personalization
/**
* @author Vitaliy.Bibaev
*/
abstract class UserFactorBase<in R : FactorReader>(override val id: String, private val descriptor: UserFactorDescription<*, R>) : UserFactor {
final override fun compute(storage: UserFactorStorage): String? {
return compute(storage.getFactorReader(descriptor))
}
abstract fun compute(reader: R): String?
} | plugins/stats-collector/src/com/intellij/stats/personalization/UserFactorBase.kt | 3212432290 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.