code
stringlengths 6
1.04M
| language
stringclasses 1
value | AST_depth
int64 -1
40
| alphanumeric_fraction
float64 0
0.97
| max_line_length
int64 0
1k
| avg_line_length
float64 0
171
| num_lines
int64 0
4.25k
| source
stringclasses 1
value |
---|---|---|---|---|---|---|---|
package com.lhwdev.ktui.plugin.compiler
object ConsoleColors {
// Reset
const val RESET = "\u001b[0m" // Text Reset
const val BOLD = "\u001b[1m"
const val UNDERLINE = "\u001b[4m"
const val FRAMED = "\u001b[51m"
const val ENCIRCLED = "\u001b[52m"
const val OVERLINED = "\u001b[53m"
// Regular Colors
const val BLACK = "\u001b[0;30m" // BLACK
const val RED = "\u001b[0;31m" // RED
const val GREEN = "\u001b[0;32m" // GREEN
const val YELLOW = "\u001b[0;33m" // YELLOW
const val BLUE = "\u001b[0;34m" // BLUE
const val PURPLE = "\u001b[0;35m" // PURPLE
const val CYAN = "\u001b[0;36m" // CYAN
const val WHITE = "\u001b[0;37m" // WHITE
// Bold
const val BLACK_BOLD = "\u001b[1;30m" // BLACK
const val RED_BOLD = "\u001b[1;31m" // RED
const val GREEN_BOLD = "\u001b[1;32m" // GREEN
const val YELLOW_BOLD = "\u001b[1;33m" // YELLOW
const val BLUE_BOLD = "\u001b[1;34m" // BLUE
const val PURPLE_BOLD = "\u001b[1;35m" // PURPLE
const val CYAN_BOLD = "\u001b[1;36m" // CYAN
const val WHITE_BOLD = "\u001b[1;37m" // WHITE
// Underline
const val BLACK_UNDERLINED = "\u001b[4;30m" // BLACK
const val RED_UNDERLINED = "\u001b[4;31m" // RED
const val GREEN_UNDERLINED = "\u001b[4;32m" // GREEN
const val YELLOW_UNDERLINED = "\u001b[4;33m" // YELLOW
const val BLUE_UNDERLINED = "\u001b[4;34m" // BLUE
const val PURPLE_UNDERLINED = "\u001b[4;35m" // PURPLE
const val CYAN_UNDERLINED = "\u001b[4;36m" // CYAN
const val WHITE_UNDERLINED = "\u001b[4;37m" // WHITE
const val WHITE_BOLD_UNDERLINED = "\u001b[1;4;37m" // WHITE
// Background
const val BLACK_BACKGROUND = "\u001b[40m" // BLACK
const val RED_BACKGROUND = "\u001b[41m" // RED
const val GREEN_BACKGROUND = "\u001b[42m" // GREEN
const val YELLOW_BACKGROUND = "\u001b[43m" // YELLOW
const val BLUE_BACKGROUND = "\u001b[44m" // BLUE
const val PURPLE_BACKGROUND = "\u001b[45m" // PURPLE
const val CYAN_BACKGROUND = "\u001b[46m" // CYAN
const val WHITE_BACKGROUND = "\u001b[47m" // WHITE
// High Intensity
const val BLACK_BRIGHT = "\u001b[0;90m" // BLACK
const val RED_BRIGHT = "\u001b[0;91m" // RED
const val GREEN_BRIGHT = "\u001b[0;92m" // GREEN
const val YELLOW_BRIGHT = "\u001b[0;93m" // YELLOW
const val BLUE_BRIGHT = "\u001b[0;94m" // BLUE
const val PURPLE_BRIGHT = "\u001b[0;95m" // PURPLE
const val CYAN_BRIGHT = "\u001b[0;96m" // CYAN
const val WHITE_BRIGHT = "\u001b[0;97m" // WHITE
const val WHITE_BRIGHT_UNDERLINED = "\u001b[0;4;97m" // WHITE
// Bold High Intensity
const val BLACK_BOLD_BRIGHT = "\u001b[1;90m" // BLACK
const val RED_BOLD_BRIGHT = "\u001b[1;91m" // RED
const val GREEN_BOLD_BRIGHT = "\u001b[1;92m" // GREEN
const val YELLOW_BOLD_BRIGHT = "\u001b[1;93m" // YELLOW
const val BLUE_BOLD_BRIGHT = "\u001b[1;94m" // BLUE
const val PURPLE_BOLD_BRIGHT = "\u001b[1;95m" // PURPLE
const val CYAN_BOLD_BRIGHT = "\u001b[1;96m" // CYAN
const val WHITE_BOLD_BRIGHT = "\u001b[1;97m" // WHITE
const val WHITE_BOLD_BRIGHT_UNDERLINED = "\u001b[1;4;97m" // WHITE
// High Intensity backgrounds
const val BLACK_BACKGROUND_BRIGHT = "\u001b[0;100m" // BLACK
const val RED_BACKGROUND_BRIGHT = "\u001b[0;101m" // RED
const val GREEN_BACKGROUND_BRIGHT = "\u001b[0;102m" // GREEN
const val YELLOW_BACKGROUND_BRIGHT = "\u001b[0;103m" // YELLOW
const val BLUE_BACKGROUND_BRIGHT = "\u001b[0;104m" // BLUE
const val PURPLE_BACKGROUND_BRIGHT = "\u001b[0;105m" // PURPLE
const val CYAN_BACKGROUND_BRIGHT = "\u001b[0;106m" // CYAN
const val WHITE_BACKGROUND_BRIGHT = "\u001b[0;107m" // WHITE
}
| kotlin | 5 | 0.671221 | 67 | 40.329412 | 85 | starcoderdata |
<filename>app/src/main/java/es/voghdev/playbattlegrounds/common/BaseActivity.kt
/*
* Copyright (C) 2017 <NAME>.
*
* 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 es.voghdev.playbattlegrounds.common
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
abstract class BaseActivity : AppCompatActivity() {
val NONE = -1
val coroutineScope = BaseScope()
class BaseScope : CoroutineScope by MainScope()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(getLayoutId())
}
abstract fun getLayoutId(): Int
open fun getToolbarTitle(): String {
return ""
}
open fun getToolbarBackgroundColor(): Int {
return NONE
}
open fun getToolbarTitleColor(): Int {
return NONE
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == android.R.id.home) {
onToolbarButtonClicked()
return true
}
return super.onOptionsItemSelected(item)
}
open fun onToolbarButtonClicked() {
finish() // Default behaviour. Override it if you want
}
}
| kotlin | 13 | 0.704319 | 79 | 27.666667 | 63 | starcoderdata |
package jdenticon
class SvgWriter(size: Int) {
val size = size
var _s = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"" +
size + "\" height=\"" + size + "\" viewBox=\"0 0 " +
size + ' ' + size + "\" preserveAspectRatio=\"xMidYMid meet\">";
fun setBackground(fillColor: String, opacity: Float?) {
opacity?.let {
this._s += "<rect width=\"100%\" height=\"100%\" fill=\"" +
fillColor + "\" opacity=\"" + opacity.format(2) + "\"/>"
}
}
fun append(color: String, dataString: String) {
this._s += "<path fill=\"" + color + "\" d=\"" + dataString + "\"/>"
}
override fun toString(): String {
return this._s + "</svg>"
}
}
expect fun Float.format(digits: Int): String | kotlin | 18 | 0.503797 | 76 | 29.423077 | 26 | starcoderdata |
<filename>src/main/kotlin/eu/long1/flutter/i18n/inspections/CreateStringInspector.kt
package eu.long1.flutter.i18n.inspections
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ex.BaseLocalInspectionTool
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.lang.dart.DartFileType
import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService
import com.jetbrains.lang.dart.psi.DartReferenceExpression
import eu.long1.flutter.i18n.inspections.quickfix.CreateStringResourceQuickFix
class CreateStringInspector : BaseLocalInspectionTool() {
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
if (file.fileType == DartFileType.INSTANCE) {
val analysisService = DartAnalysisServerService.getInstance(file.project).getErrors(file.virtualFile)
val errors = analysisService.filter {
it.code == "undefined_getter" && it.message.contains("defined for the class 'S'.")
}
if (errors.isNotEmpty()) {
val problems = ArrayList<ProblemDescriptor>(errors.size)
errors.forEach {
PsiTreeUtil.findElementOfClassAtOffset(
file,
it.offset,
DartReferenceExpression::class.java,
false
)?.let { string ->
val element = string.parent
val quickFix = CreateStringResourceQuickFix(element, string.text)
problems.add(manager.createProblemDescriptor(
element,
quickFix.text,
isOnTheFly,
arrayOf(quickFix),
ProblemHighlightType.GENERIC_ERROR
))
}
}
if (problems.isNotEmpty()) {
return problems.toTypedArray()
}
}
}
return null
}
override fun getDisplayName(): String = "Create string resource from S class reference"
override fun getGroupDisplayName(): String = "Flutter i18n"
} | kotlin | 34 | 0.614876 | 119 | 40.741379 | 58 | starcoderdata |
/*
* MIT License
*
* Copyright (c) 2019 <NAME>
*
* 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.tunjid.rcswitchcontrol.control
import android.os.Bundle
import android.view.View
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.android.flexbox.AlignItems
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.rcswitchcontrol.protocols.CommsProtocol
import com.tunjid.androidx.core.delegates.fragmentArgs
import com.tunjid.androidx.recyclerview.listAdapterOf
import com.tunjid.androidx.recyclerview.verticalLayoutManager
import com.tunjid.androidx.recyclerview.viewbinding.typed
import com.tunjid.globalui.liveUiState
import com.tunjid.globalui.uiState
import com.tunjid.globalui.updatePartial
import com.tunjid.rcswitchcontrol.R
import com.tunjid.rcswitchcontrol.client.ClientState
import com.tunjid.rcswitchcontrol.client.ProtocolKey
import com.tunjid.rcswitchcontrol.common.asSuspend
import com.tunjid.rcswitchcontrol.common.mapDistinct
import com.tunjid.rcswitchcontrol.databinding.FragmentListBinding
import com.tunjid.rcswitchcontrol.databinding.ViewholderCommandBinding
import com.tunjid.rcswitchcontrol.databinding.ViewholderHistoryBinding
import com.tunjid.rcswitchcontrol.di.viewModelFactory
import com.tunjid.rcswitchcontrol.viewholders.bind
import com.tunjid.rcswitchcontrol.viewholders.bindCommand
import com.tunjid.rcswitchcontrol.viewholders.commandViewHolder
import com.tunjid.rcswitchcontrol.viewholders.historyViewHolder
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
sealed class RecordFragment : Fragment(R.layout.fragment_list) {
class HistoryFragment : RecordFragment()
class CommandsFragment : RecordFragment()
internal var key: CommsProtocol.Key? by fragmentArgs()
private val viewModel by viewModelFactory<ControlViewModel>(::rootController)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
liveUiState.mapDistinct { it.systemUI.dynamic.bottomInset }.observe(viewLifecycleOwner) {
view.updatePadding(bottom = it)
}
val binding = FragmentListBinding.bind(view)
binding.list.apply {
val listAdapter = listAdapterOf(
initialItems = initialItems(),
viewHolderCreator = { parent, viewType ->
when (viewType) {
0 -> parent.historyViewHolder()
1 -> parent.commandViewHolder(::onRecordClicked)
else -> throw IllegalArgumentException("Invalid view type")
}
},
viewHolderBinder = { holder, record, _ ->
when (holder.binding) {
is ViewholderHistoryBinding -> holder.typed<ViewholderHistoryBinding>()
.bind(record)
is ViewholderCommandBinding -> holder.typed<ViewholderCommandBinding>()
.bindCommand(record)
}
},
viewTypeFunction = { if (key == null) 0 else 1 }
)
layoutManager = when (key) {
null -> verticalLayoutManager()
else -> FlexboxLayoutManager(context).apply {
alignItems = AlignItems.CENTER
flexDirection = FlexDirection.ROW
justifyContent = JustifyContent.CENTER
}
}
adapter = listAdapter
val clientState = viewModel.state.mapDistinct(ControlState::clientState.asSuspend)
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
if (key == null) clientState.mapDistinct(ClientState::history.asSuspend).collect { history ->
listAdapter.submitList(history)
if (history.isNotEmpty()) smoothScrollToPosition(history.lastIndex)
}
else clientState.mapDistinct { it.commands[key] }.collect {
it?.let(listAdapter::submitList)
}
}
}
}
}
private fun initialItems(): List<Record> = viewModel.state.value.clientState.let {
if (key == null) it.history else it.commands[key]
} ?: listOf()
override fun onResume() {
super.onResume()
uiState
::uiState.updatePartial { copy(altToolbarShows = false) }
}
private fun onRecordClicked(record: Record) = when (record) {
is Record.Command -> viewModel.accept(Input.Async.ServerCommand(record.payload))
is Record.Response -> Unit
}
companion object {
fun historyInstance(): HistoryFragment = HistoryFragment()
fun commandInstance(key: ProtocolKey): CommandsFragment =
CommandsFragment().apply { this.key = key.key }
}
}
| kotlin | 36 | 0.688535 | 113 | 42.013699 | 146 | starcoderdata |
package io.github.kongpf8848.rxhttp.sample.http.exception
class NullResponseException(val code: Int, val msg: String?) : RuntimeException(msg) | kotlin | 6 | 0.818182 | 84 | 47 | 3 | starcoderdata |
<filename>auth/src/androidMain/kotlin/com/github/lamba92/firebasemultiplatform/auth/OAuthProvider.kt
@file:Suppress("unused")
package com.github.lamba92.firebasemultiplatform.auth
actual class OAuthProvider(
override val delegate: PlatformSpecificOAuthProvider
) : FederatedAuthProvider(delegate) {
actual val providerId: String?
get() = delegate.providerId
actual companion object {
@Suppress("DEPRECATION")
@Deprecated(
"Please use newCredentialBuilder(String) instead",
ReplaceWith("newCredentialBuilder(providerId).setIdToken(idToken).setAccessToken(accessToken)")
)
actual fun getCredential(
providerId: String,
idToken: String,
accessToken: String
) = PlatformSpecificOAuthProvider
.getCredential(providerId, idToken, accessToken)
.toMpp()
fun newBuilder(providerId: String, firebaseAuth: FirebaseAuth) =
PlatformSpecificOAuthProvider.newBuilder(providerId, firebaseAuth.delegate).toMpp()
actual fun newBuilder(providerId: String) =
PlatformSpecificOAuthProvider
.newBuilder(providerId)
.toMpp()
actual fun newCredentialBuilder(providerId: String) =
PlatformSpecificOAuthProvider
.newCredentialBuilder(providerId)
.toMpp()
}
actual class Builder(
val delegate: PlatformSpecificOAuthProviderBuilder
) {
actual companion object;
actual fun build() =
delegate.build().toMpp()
actual fun setCustomParameters(customParameters: Map<String, String>): Builder {
delegate.addCustomParameters(customParameters)
return this
}
actual fun setScopes(scopes: List<String>): Builder {
delegate.setScopes(scopes)
return this
}
}
actual class CredentialsBuilder(
val delegate: PlatformSpecificOAuthProviderCredentialsBuilder
) {
actual companion object;
actual fun build() =
delegate.build().toMpp()
actual fun setAccessToken(accessToken: String): CredentialsBuilder {
delegate.setAccessToken(accessToken)
return this
}
actual fun setIdToken(idToken: String): CredentialsBuilder {
delegate.setIdToken(idToken)
return this
}
fun setIdTokenWithRawNonce(idToken: String, rawNonce: String?): CredentialsBuilder {
delegate.setIdTokenWithRawNonce(idToken, rawNonce)
return this
}
}
}
fun main() {
} | kotlin | 15 | 0.640853 | 107 | 27.446809 | 94 | starcoderdata |
package com.frogobox.nutritionframework.admob
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.frogobox.nutritionframework.R
import com.frogobox.nutritionframework.admob.NutriAdmobConstant.RECYCLER_VIEW_TYPE_BANNER_AD
import com.frogobox.nutritionframework.admob.NutriAdmobConstant.RECYCLER_VIEW_TYPE_MENU_ITEM
import com.frogobox.nutritionframework.recycler.core.NutriHolder
import com.frogobox.nutritionframework.recycler.core.NutriRecyclerNotifyListener
import com.frogobox.nutritionframework.recycler.core.NutriRecyclerViewListener
/**
* Created by <NAME>
* FrogoBox Inc License
* =========================================
* SpeechBooster
* Copyright (C) 10/09/2019.
* All rights reserved
* -----------------------------------------
* Name : <NAME>
* E-mail : <EMAIL>
* Github : github.com/amirisback
* LinkedIn : linkedin.com/in/faisalamircs
* -----------------------------------------
* FrogoBox Software Industries
* com.frogobox.speechbooster.base
*
*/
abstract class NutriAdmobViewAdapter<T> : RecyclerView.Adapter<NutriAdmobViewHolder<T>>() {
protected var viewCallback: INutriAdmobViewAdapter<T>? = null
protected var viewListener: NutriRecyclerViewListener<T>? = null
protected var listenerNotify = object : NutriRecyclerNotifyListener<T> {
override fun nutriNotifyData(): MutableList<T> {
return listData
}
override fun nutriNotifyDataSetChanged() {
notifyDataSetChanged()
}
override fun nutriNotifyItemChanged(data: T, position: Int, payload: Any) {
listData[position] = data
notifyItemChanged(position, payload)
}
override fun nutriNotifyItemChanged(data: T, position: Int) {
listData[position] = data
notifyItemChanged(position)
}
override fun nutriNotifyItemInserted(data: T, position: Int) {
listData.add(position, data)
notifyItemInserted(position)
}
override fun nutriNotifyItemMoved(data: T, fromPosition: Int, toPosition: Int) {
listData.removeAt(fromPosition)
listData.add(toPosition, data)
notifyItemMoved(fromPosition, toPosition)
}
override fun nutriNotifyItemRangeChanged(data: List<T>, positionStart: Int, payload: Any) {
listData.addAll(positionStart, data)
notifyItemRangeChanged(positionStart, data.size, payload)
}
override fun nutriNotifyItemRangeChanged(data: List<T>, positionStart: Int) {
listData.addAll(positionStart, data)
notifyItemRangeChanged(positionStart, data.size)
}
override fun nutriNotifyItemRangeInserted(data: List<T>, positionStart: Int) {
listData.addAll(positionStart, data)
notifyItemRangeChanged(positionStart, data.size)
}
override fun nutriNotifyItemRangeRemoved(positionStart: Int, itemCount: Int) {
listData.subList(positionStart, (positionStart + itemCount)).clear()
notifyItemRangeRemoved(positionStart, itemCount)
}
override fun nutriNotifyItemRemoved(position: Int) {
listData.removeAt(position)
notifyItemRemoved(position)
}
}
protected val frogoHolder = mutableListOf<NutriHolder<T>>()
protected val listData = mutableListOf<T>()
protected var listCount = 0
protected var hasEmptyView = false
protected var layoutRv: Int = 0
protected var customLayoutRestId: Int = 0
protected var emptyLayoutResId: Int = R.layout.nutri_container_empty_view
override fun getItemCount(): Int {
return if (hasEmptyView) {
listCount = if (listData.size == 0) {
1
} else {
listData.size
}
listCount
} else {
listData.size
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NutriAdmobViewHolder<T> {
return when (viewType) {
RECYCLER_VIEW_TYPE_MENU_ITEM -> {
viewCallback!!.onViewTypeMenuItem(parent)
}
RECYCLER_VIEW_TYPE_BANNER_AD -> {
viewCallback!!.onViewTypeBannerAds(parent)
}
else -> {
viewCallback!!.onViewTypeBannerAds(parent)
}
}
}
override fun onBindViewHolder(holder: NutriAdmobViewHolder<T>, position: Int) {
when (getItemViewType(position)) {
RECYCLER_VIEW_TYPE_MENU_ITEM -> {
holder.bindItem(listData[position], position, viewListener, listenerNotify)
}
RECYCLER_VIEW_TYPE_BANNER_AD -> {
holder.bindItemAdView(listData[position])
}
else -> {
holder.bindItemAdView(listData[position])
}
}
}
override fun getItemViewType(position: Int): Int {
return if (position % NutriAdmobConstant.RECYCLER_VIEW_ITEMS_PER_AD == 0) RECYCLER_VIEW_TYPE_BANNER_AD else RECYCLER_VIEW_TYPE_MENU_ITEM
}
protected fun viewLayout(parent: ViewGroup, layout: Int): View {
return LayoutInflater.from(parent.context).inflate(layout, parent, false)
}
private fun verifyViewInt() {
if (listData.isNotEmpty()) {
layoutRv = customLayoutRestId
} else {
layoutRv = emptyLayoutResId
}
}
private fun layoutHandle() {
if (customLayoutRestId != 0) {
verifyViewInt()
}
}
private fun emptyViewHandle() {
layoutHandle()
}
fun setupEmptyView(emptyView: Int?) {
hasEmptyView = true
if (emptyView != null) {
emptyLayoutResId = emptyView
}
emptyViewHandle()
}
fun setupRequirement(
customViewInt: Int,
listData: List<T>?,
listener: NutriRecyclerViewListener<T>?
) {
if (listener != null) {
viewListener = listener
}
this.listData.clear()
if (listData != null) {
this.listData.addAll(listData)
}
customLayoutRestId = customViewInt
emptyViewHandle()
}
fun viewLayout(parent: ViewGroup): View {
return LayoutInflater.from(parent.context).inflate(layoutRv, parent, false)
}
} | kotlin | 17 | 0.622857 | 144 | 30.285024 | 207 | starcoderdata |
<filename>samples/android-app/src/androidMain/kotlin/com/example/splitties/preview/sound/MediaPlayer.kt
/*
* Copyright 2019 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
package com.example.splitties.preview.sound
import android.media.MediaPlayer
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
suspend fun MediaPlayer.awaitPreparation(): Unit = try {
suspendCancellableCoroutine { continuation ->
setOnPreparedListener { continuation.resume(Unit) }
prepareAsync()
}
} finally {
setOnPreparedListener(null)
}
suspend fun MediaPlayer.playAndComplete(): Unit = try {
suspendCancellableCoroutine { continuation ->
setOnCompletionListener { continuation.resume(Unit) }
start()
}
} finally {
setOnCompletionListener(null)
}
| kotlin | 19 | 0.750885 | 103 | 29.25 | 28 | starcoderdata |
<filename>component/buildSrc/src/main/kotlin/commonMavenConfiguration.kt
import org.gradle.api.publish.maven.MavenPom
fun MavenPom.addCommonPom() {
url.set("https://github.com/n34t0/compose-code-editor")
licenses {
license {
name.set("The Apache License, Version 2.0")
url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")
}
}
developers {
developer {
id.set("n34t0")
name.set("<NAME>")
email.set("<EMAIL>")
}
}
scm {
connection.set("scm:git:git://github.com/n34t0/compose-code-editor.git")
developerConnection.set("scm:git:ssh://github.com:n34t0/compose-code-editor.git")
url.set("https://github.com/n34t0/compose-code-editor/tree/master")
}
} | kotlin | 18 | 0.611602 | 89 | 32.083333 | 24 | starcoderdata |
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.profilers.memory.chart
import com.android.tools.adtui.model.FakeTimer
import com.android.tools.idea.transport.faketransport.FakeGrpcChannel
import com.android.tools.idea.transport.faketransport.FakeTransportService
import com.android.tools.profilers.FakeIdeProfilerServices
import com.android.tools.profilers.FakeProfilerService
import com.android.tools.profilers.ProfilerClient
import com.android.tools.profilers.StudioProfilers
import com.android.tools.profilers.memory.FakeCaptureObjectLoader
import com.android.tools.profilers.memory.FakeMemoryService
import com.android.tools.profilers.memory.MemoryCaptureObjectTestUtils
import com.android.tools.profilers.memory.MemoryProfilerStage
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class ClassifierSetHNodeTest {
private val myTimer = FakeTimer()
@get:Rule
var myGrpcChannel = FakeGrpcChannel("MEMORY_TEST_CHANNEL",
FakeTransportService(myTimer),
FakeProfilerService(myTimer),
FakeMemoryService())
private lateinit var myStage: MemoryProfilerStage
@Before
fun before() {
val loader = FakeCaptureObjectLoader()
loader.setReturnImmediateFuture(true)
val fakeIdeProfilerServices = FakeIdeProfilerServices()
myStage = MemoryProfilerStage(
StudioProfilers(ProfilerClient(myGrpcChannel.channel), fakeIdeProfilerServices, FakeTimer()),
loader)
}
@Test
fun childrenOrderedBySize() {
val heapSet = MemoryCaptureObjectTestUtils.createAndSelectHeapSet(myStage)
val model = MemoryVisualizationModel()
model.axisFilter = MemoryVisualizationModel.XAxisFilter.TOTAL_COUNT
val node = ClassifierSetHNode(model, heapSet, 0)
assertThat(node.childCount).isEqualTo(3)
assertThat(node.firstChild).isEqualTo(node.getChildAt(0))
assertThat(node.lastChild).isEqualTo(node.getChildAt(2))
var previousDuration = node.getChildAt(0).duration
for (i in 0 until node.childCount) {
val child = node.getChildAt(i)
assertThat(child.duration).isAtMost(previousDuration)
previousDuration = child.duration
}
}
@Test
fun updateChildOffsetsOrdersChildByStartTime() {
val heapSet = MemoryCaptureObjectTestUtils.createAndSelectHeapSet(myStage)
val model = MemoryVisualizationModel()
model.axisFilter = MemoryVisualizationModel.XAxisFilter.TOTAL_SIZE
val node = ClassifierSetHNode(model, heapSet, 0)
node.updateChildrenOffsets()
var expectedStart = 0L
for (i in 0 until node.childCount) {
val child = node.getChildAt(i)
assertThat(child.start).isEqualTo(expectedStart)
expectedStart = child.end
}
}
@Test
fun durationRespectsFilter() {
val heapSet = MemoryCaptureObjectTestUtils.createAndSelectHeapSet(myStage)
val model = MemoryVisualizationModel()
model.axisFilter = MemoryVisualizationModel.XAxisFilter.TOTAL_COUNT
val root = ClassifierSetHNode(model, heapSet, 0)
assertThat(heapSet.totalObjectCount).isEqualTo(root.duration)
model.axisFilter = MemoryVisualizationModel.XAxisFilter.TOTAL_SIZE
assertThat(heapSet.totalShallowSize / 1024).isEqualTo(root.duration)
model.axisFilter = MemoryVisualizationModel.XAxisFilter.ALLOC_COUNT
assertThat(heapSet.deltaAllocationCount).isEqualTo(root.duration)
model.axisFilter = MemoryVisualizationModel.XAxisFilter.ALLOC_SIZE
assertThat(heapSet.totalRemainingSize / 1024).isEqualTo(root.duration)
}
} | kotlin | 21 | 0.763095 | 99 | 41.01 | 100 | starcoderdata |
package module555packageKt0;
annotation class Foo50Fancy
@Foo50Fancy
class Foo50 {
fun foo0(){
module555packageKt0.Foo49().foo2()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
} | kotlin | 11 | 0.630542 | 38 | 10.333333 | 18 | starcoderdata |
package app.futured.arkitekt.dagger.inject
import android.app.Activity
import androidx.fragment.app.Fragment
import dagger.android.AndroidInjection
import dagger.android.support.AndroidSupportInjection
/**
* AndroidInjection wrapper that allows customizing dependency injection of Activity or Fragment.
*
* Important: Methods and properties of this object should be used only for testing purposes.
*/
object TestableAndroidInjection {
/**
* Callback invoked when [Activity] class is being injected.
* It should be used in tests for manual dependency injection of [Activity] class.
*
* The most common use case is to replace [ViewModelCreator.viewModelFactory] with the factory
* that provides a view model with mocked use cases
*/
var onActivityInject: ((Activity) -> Unit)? = null
/**
* Callback invoked when [Fragment] class is being injected.
* It should be used in tests for manual dependency injection of [Fragment] class.
*
* The most common use case is to replace [ViewModelCreator.viewModelFactory] with the factory
* that provides a view model with mocked use cases
*/
var onFragmentInject: ((Fragment) -> Unit)? = null
/**
* Wrap [AndroidInjection.inject] method with helpful utilities for better testability of [Activity] class.
*
* Use] [onActivityInject] to customize behavior of this method in tests.
*/
fun inject(activity: Activity) {
AndroidInjection.inject(activity)
onActivityInject?.invoke(activity)
onActivityInject = null // Remove reference to the previous test since this will be executed only once
}
/**
* Wrap [AndroidInjection.inject] method with helpful utilities for better testability of [Fragment] class.
*
* Use [onFragmentInject] to customize behavior of this method in tests.
*/
fun inject(fragment: Fragment) {
AndroidSupportInjection.inject(fragment)
onFragmentInject?.invoke(fragment)
onFragmentInject = null // Remove reference to the previous test since this will be executed only once
}
}
| kotlin | 10 | 0.716032 | 111 | 38.388889 | 54 | starcoderdata |
<filename>nj2k/testData/newJ2k/constructors/fieldsInitializedFromParams7.kt
internal class C(x: Any?, b: Boolean) {
var x: Any? = null
init {
if (b) {
this.x = x
}
}
} | kotlin | 11 | 0.567308 | 75 | 19.9 | 10 | starcoderdata |
package org.arend.toolWindow.errors.tree
import com.intellij.codeInsight.hints.presentation.MouseButton
import com.intellij.codeInsight.hints.presentation.mouseButton
import com.intellij.psi.PsiElement
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.ui.tree.TreeUtil
import org.arend.ext.error.GeneralError
import org.arend.ext.prettyprinting.PrettyPrinterConfig
import org.arend.ext.prettyprinting.doc.DocStringBuilder
import org.arend.highlight.BasePass
import org.arend.naming.reference.Referable
import org.arend.psi.ArendFile
import org.arend.psi.ext.PsiConcreteReferable
import org.arend.psi.navigate
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JScrollPane
import javax.swing.JViewport
import javax.swing.tree.*
import kotlin.math.max
import kotlin.math.min
class ArendErrorTree(treeModel: DefaultTreeModel, private val listener: ArendErrorTreeListener? = null) : Tree(treeModel) {
init {
isRootVisible = false
emptyText.text = "No errors"
selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
when (e.mouseButton) {
MouseButton.Left -> if (e.clickCount >= 2) {
navigate(true)
}
MouseButton.Right -> {}
else -> {}
}
}
})
}
fun navigate(focus: Boolean) =
((selectionPath?.lastPathComponent as? DefaultMutableTreeNode)?.userObject as? ArendErrorTreeElement)?.let { BasePass.getImprovedCause(it.sampleError.error) }?.navigate(focus)
fun select(error: GeneralError) = selectNode(error)
fun selectFirst() = selectNode(null)
private fun selectNode(error: GeneralError?): Boolean {
val root = model.root as? DefaultMutableTreeNode ?: return false
var node: DefaultMutableTreeNode? = null
for (any in root.depthFirstEnumeration()) {
if (any is DefaultMutableTreeNode && (error != null && (any.userObject as? ArendErrorTreeElement)?.errors?.any { it.error == error } == true || error == null && any.userObject is ArendErrorTreeElement)) {
node = any
break
}
}
val path = node?.path?.let { TreePath(it) } ?: return false
selectionModel.selectionPath = path
scrollPathToVisibleVertical(path)
return true
}
fun scrollPathToVisibleVertical(path: TreePath) {
makeVisible(path)
val bounds = getPathBounds(path) ?: return
val parent = parent
if (parent is JViewport) {
bounds.width = min(bounds.width, max(parent.width - bounds.x - ((parent.parent as? JScrollPane)?.verticalScrollBar?.width ?: 0), 0))
} else {
bounds.x = 0
}
scrollRectToVisible(bounds)
(accessibleContext as? AccessibleJTree)?.fireVisibleDataPropertyChange()
}
fun getExistingPrefix(path: TreePath?): TreePath? {
var lastCorrect = path
var currentPath = path
while (currentPath != null) {
val parent = currentPath.parentPath
if (parent != null && (currentPath.lastPathComponent as? TreeNode)?.parent == null) {
lastCorrect = parent
}
currentPath = parent
}
return lastCorrect
}
override fun convertValueToText(value: Any?, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): String =
when (val obj = ((value as? DefaultMutableTreeNode)?.userObject)) {
is ArendFile -> obj.moduleLocation?.toString() ?: obj.name
is ArendErrorTreeElement -> {
val messages = LinkedHashSet<String>()
for (arendError in obj.errors) {
messages.add(DocStringBuilder.build(arendError.error.getShortHeaderDoc(PrettyPrinterConfig.DEFAULT)))
}
messages.joinToString("; ")
}
is Referable -> if ((obj as? PsiElement)?.isValid == false) "" else obj.textRepresentation()
else -> obj?.toString() ?: ""
}
fun containsNode(definition: PsiConcreteReferable): Boolean {
val file = definition.containingFile as? ArendFile ?: return false
val root = treeModel.root as? DefaultMutableTreeNode ?: return false
for (child in root.children()) {
if ((child as? DefaultMutableTreeNode)?.userObject == file) {
for (defChild in child.children()) {
if ((defChild as? DefaultMutableTreeNode)?.userObject == definition) {
return true
}
}
return false
}
}
return false
}
private fun <T : MutableTreeNode> insertNode(child: T, parent: T, comparator: Comparator<T>): T {
val treeElement = (child as? DefaultMutableTreeNode)?.userObject as? ArendErrorTreeElement
return if (treeElement != null) {
var i = parent.childCount - 1
while (i >= 0) {
val anotherError = (parent.getChildAt(i) as? DefaultMutableTreeNode)?.userObject as? ArendErrorTreeElement
if (anotherError == null || treeElement.highestError.error.level <= anotherError.highestError.error.level) {
break
}
i--
}
(treeModel as DefaultTreeModel).insertNodeInto(child, parent, i + 1)
listener?.let {
for (error in treeElement.errors) {
it.errorAdded(error)
}
}
child
} else {
val index = TreeUtil.indexedBinarySearch(parent, child, comparator)
if (index < 0) {
(treeModel as DefaultTreeModel).insertNodeInto(child, parent, -(index + 1))
child
} else {
@Suppress("UNCHECKED_CAST")
parent.getChildAt(index) as T
}
}
}
private fun notifyRemoval(node: TreeNode) {
((node as? DefaultMutableTreeNode)?.userObject as? ArendErrorTreeElement)?.let { treeElement ->
listener?.let {
for (error in treeElement.errors) {
it.errorRemoved(error)
}
}
}
for (child in node.children()) {
if (child is TreeNode) {
notifyRemoval(child)
}
}
}
fun update(node: DefaultMutableTreeNode, childrenFunc: (DefaultMutableTreeNode) -> Collection<Any?>) {
val children = childrenFunc(node).let { it as? HashSet ?: LinkedHashSet(it) }
var i = node.childCount - 1
while (i >= 0) {
val child = node.getChildAt(i)
if (child is DefaultMutableTreeNode && children.remove(child.userObject)) {
update(child, childrenFunc)
} else {
node.remove(i)
notifyRemoval(child)
}
i--
}
for (child in children) {
update(insertNode(DefaultMutableTreeNode(child), node, TreeNodeComparator), childrenFunc)
}
}
private object TreeNodeComparator : Comparator<DefaultMutableTreeNode> {
override fun compare(d1: DefaultMutableTreeNode, d2: DefaultMutableTreeNode): Int {
val obj1 = d1.userObject
val obj2 = d2.userObject
return when {
obj1 == obj2 -> 0
obj1 is ArendFile && obj2 is ArendFile -> fix((obj1.moduleLocation?.toString() ?: obj1.name).compareTo(obj2.moduleLocation?.toString() ?: obj2.name))
obj1 is PsiConcreteReferable && obj2 is PsiConcreteReferable -> fix(obj1.textOffset.compareTo(obj2.textOffset))
obj1 is ArendErrorTreeElement && obj2 is ArendErrorTreeElement -> fix(obj1.highestError.error.level.compareTo(obj2.highestError.error.level) * -1)
obj1 is ArendErrorTreeElement -> 1
obj2 is ArendErrorTreeElement -> -1
obj1 is ArendFile -> 1
obj2 is ArendFile -> -1
else -> -1
}
}
private fun fix(cmp: Int) = if (cmp == 0) -1 else cmp
}
} | kotlin | 27 | 0.596197 | 216 | 39.657005 | 207 | starcoderdata |
<filename>feature-flag/src/test/kotlin/com/linecorp/android/featureflag/loader/FeatureFlagSelectorParserTest.kt
//
// Copyright 2019 LINE Corporation
//
// 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.linecorp.android.featureflag.loader
import com.linecorp.android.featureflag.model.FeatureFlagElement.Link
import com.linecorp.android.featureflag.model.FeatureFlagElement.Phase
import com.linecorp.android.featureflag.model.FeatureFlagElement.User
import com.linecorp.android.featureflag.model.FeatureFlagElement.Version
import com.linecorp.android.featureflag.model.FlagLink
import com.linecorp.android.featureflag.utils.assertDisjunction
import com.linecorp.android.featureflag.utils.assertFailureMessage
import com.linecorp.android.featureflag.utils.conjunctionOf
import com.linecorp.android.featureflag.utils.disjunctionOf
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.io.File
/**
* Tests for [FeatureFlagSelectorParser].
* All the text resources are in "tests/FeatureFlagSelectorParser/" directory.
*/
object FeatureFlagSelectorParserTest : Spek({
fun loadLinesFromFile(name: String): List<String> {
val url = checkNotNull(
javaClass.classLoader.getResource("tests/FeatureFlagSelectorParserTest/$name")
)
return File(url.toURI()).bufferedReader().lineSequence().toList()
}
describe("Parsed result is correct") {
context("on each element type") {
val expectedResults = listOf(
disjunctionOf(conjunctionOf(Phase("PHASE"))),
disjunctionOf(conjunctionOf(User("USER"))),
disjunctionOf(conjunctionOf(Link(FlagLink("", "SELF_LINK")))),
disjunctionOf(conjunctionOf(Link(FlagLink("MODULE", "LINK")))),
disjunctionOf(conjunctionOf(Version("1.2.3"))),
disjunctionOf(conjunctionOf(Phase("PHASE1"), Phase("PHASE2")))
)
val testCases = loadLinesFromFile("VALUE_VALID_ELEMENT_TYPES")
testCases.forEachIndexed { index, testValue ->
it(testValue) {
assertDisjunction(
expectedResults[index],
FeatureFlagSelectorParser.parse(testValue)
)
}
}
}
context("with link to nested module") {
val expected = disjunctionOf(conjunctionOf(Link(FlagLink("NESTED:MODULE", "LINK"))))
val testCases = loadLinesFromFile("VALUE_VALID_NESTED_MODULE_LINK")
testCases.forEach { testValue ->
it(testValue) {
assertDisjunction(expected, FeatureFlagSelectorParser.parse(testValue))
}
}
}
context("with disjunction and space") {
val expected =
disjunctionOf(conjunctionOf(Phase("PHASE1")), conjunctionOf(Phase("PHASE2")))
val testCases = loadLinesFromFile("VALUE_VALID_DISJUNCTION_WITH_SPACE")
testCases.forEach { testValue ->
it(testValue) {
assertDisjunction(expected, FeatureFlagSelectorParser.parse(testValue))
}
}
}
context("with conjunction and space") {
val expected = disjunctionOf(conjunctionOf(Phase("PHASE1"), Phase("PHASE2")))
val testCases = loadLinesFromFile("VALUE_VALID_CONJUNCTION_WITH_SPACE")
testCases.forEach { testValue ->
it(testValue) {
assertDisjunction(expected, FeatureFlagSelectorParser.parse(testValue))
}
}
}
context("on combination of disjunction and conjunction") {
val expectedResults = listOf(
disjunctionOf(
conjunctionOf(Phase("PHASE1")),
conjunctionOf(Phase("PHASE2"), Phase("PHASE3"))
),
disjunctionOf(
conjunctionOf(Phase("PHASE1"), Phase("PHASE2")),
conjunctionOf(Phase("PHASE3"))
),
disjunctionOf(
conjunctionOf(Phase("PHASE1"), Phase("PHASE2")),
conjunctionOf(Phase("PHASE3"), Phase("PHASE4"))
)
)
val testCases = loadLinesFromFile("VALUE_VALID_DISJUNCTION_AND_CONJUNCTION")
testCases.forEachIndexed { index, testValue ->
it(testValue) {
assertDisjunction(
expectedResults[index],
FeatureFlagSelectorParser.parse(testValue)
)
}
}
}
}
describe("Parsing is failed") {
context("on each element type") {
it("User element with no value") {
assertFailureMessage<IllegalArgumentException>(
"Missing user name in user element."
) {
FeatureFlagSelectorParser.parse(
loadLinesFromFile("VALUE_INVALID_ELEMENT_USER")[0]
)
}
}
it("Link element with no value") {
assertFailureMessage<IllegalArgumentException>(
"Missing link value in link element."
) {
FeatureFlagSelectorParser.parse(
loadLinesFromFile("VALUE_INVALID_ELEMENT_LINK_SELF")[0]
)
}
}
it("Link element with no value") {
assertFailureMessage<IllegalArgumentException>(
"Missing link value in link element."
) {
FeatureFlagSelectorParser.parse(
loadLinesFromFile("VALUE_INVALID_ELEMENT_LINK_ANOTHER")[0]
)
}
}
it("Version element with no value") {
assertFailureMessage<IllegalArgumentException>(
"Missing version value in version element."
) {
FeatureFlagSelectorParser.parse(
loadLinesFromFile("VALUE_INVALID_ELEMENT_VERSION")[0]
)
}
}
}
context("on conjunction") {
it("with no value") {
assertFailureMessage<IllegalArgumentException>(
"An invalid blank element exists."
) {
FeatureFlagSelectorParser.parse(
loadLinesFromFile("VALUE_INVALID_CONJUNCTION_EMPTY")[0]
)
}
}
it("with only one sides value") {
assertFailureMessage<IllegalArgumentException>(
"An invalid blank element exists."
) {
FeatureFlagSelectorParser.parse(
loadLinesFromFile("VALUE_INVALID_CONJUNCTION_ONE_SIDE")[0]
)
}
}
}
context("on disjunction") {
it("with no value") {
assertFailureMessage<IllegalArgumentException>(
"An invalid blank element exists."
) {
FeatureFlagSelectorParser.parse(
loadLinesFromFile("VALUE_INVALID_DISJUNCTION_EMPTY")[0]
)
}
}
it("with only one sides value") {
assertFailureMessage<IllegalArgumentException>(
"An invalid blank element exists."
) {
FeatureFlagSelectorParser.parse(
loadLinesFromFile("VALUE_INVALID_DISJUNCTION_ONE_SIDE")[0]
)
}
}
}
}
})
| kotlin | 39 | 0.558813 | 111 | 38.553991 | 213 | starcoderdata |
/*
* Copyright 2015-2019 The twitlatte authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.moko256.twitlatte.mediaview
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.app.DownloadManager
import android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
import android.content.Context.DOWNLOAD_SERVICE
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.net.Uri
import android.os.Bundle
import android.os.Environment.DIRECTORY_DOWNLOADS
import android.view.*
import android.view.View.*
import android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import androidx.annotation.LayoutRes
import androidx.annotation.MenuRes
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.github.chuross.flinglayout.FlingLayout
import com.github.moko256.latte.client.base.CLIENT_TYPE_NOTHING
import com.github.moko256.latte.client.base.entity.Media
import com.github.moko256.twitlatte.R
import com.github.moko256.twitlatte.text.TwitterStringUtils
/**
* Created by moko256 on 2018/10/07.
*
* @author moko256
*/
private const val FRAG_MEDIA_ENTITY = "media_entity"
private const val FRAG_CLIENT_TYPE = "client_type"
private const val REQUEST_CODE_PERMISSION_STORAGE = 1
abstract class AbstractMediaFragment : Fragment() {
protected lateinit var media: Media
protected var clientType: Int = CLIENT_TYPE_NOTHING
fun setMediaToArg(media: Media, clientType: Int) {
val bundle = Bundle()
bundle.putSerializable(FRAG_MEDIA_ENTITY, media)
bundle.putInt(FRAG_CLIENT_TYPE, clientType)
arguments = bundle
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
showSystemUI()
arguments?.let { arguments ->
media = arguments.getSerializable(FRAG_MEDIA_ENTITY) as Media
clientType = arguments.getInt(FRAG_CLIENT_TYPE)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(returnLayoutId(), container, false) as FlingLayout
view.dismissListener = {
activity?.finish()
}
view.positionChangeListener = { _, _, _ ->
if (!isShowingSystemUI()) {
showSystemUI()
}
}
return view
}
protected fun showActionbar() {
activity?.actionBar?.show()
}
protected fun setSystemUIVisibilityListener(l: (Int) -> Unit) {
activity?.window?.decorView?.setOnSystemUiVisibilityChangeListener(l)
}
protected fun hideSystemUI() {
activity?.window?.let {
it.addFlags(FLAG_FULLSCREEN)
it.decorView.systemUiVisibility = (SYSTEM_UI_FLAG_LAYOUT_STABLE
or SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or SYSTEM_UI_FLAG_HIDE_NAVIGATION
or SYSTEM_UI_FLAG_FULLSCREEN
or SYSTEM_UI_FLAG_IMMERSIVE)
}
}
protected fun showSystemUI() {
activity?.window?.let {
it.decorView.systemUiVisibility = (SYSTEM_UI_FLAG_LAYOUT_STABLE
or SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
it.clearFlags(FLAG_FULLSCREEN)
}
}
protected fun isShowingSystemUI(): Boolean {
return activity?.window?.decorView?.systemUiVisibility?.and(SYSTEM_UI_FLAG_FULLSCREEN) == 0
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode == REQUEST_CODE_PERMISSION_STORAGE) {
if (grantResults.firstOrNull() == PERMISSION_GRANTED) {
startDownload()
} else {
Toast.makeText(context, R.string.permission_denied, LENGTH_LONG).show()
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(returnMenuId(), menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if (item.itemId == R.id.action_download) {
context?.let {
if (ContextCompat.checkSelfPermission(it, WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
requestPermissions(arrayOf(WRITE_EXTERNAL_STORAGE), REQUEST_CODE_PERMISSION_STORAGE)
} else {
startDownload()
}
}
true
} else {
false
}
}
private fun startDownload() {
val path = media.downloadVideoUrl
?: TwitterStringUtils.convertOriginalImageUrl(clientType, media.originalUrl)
val manager: DownloadManager = activity?.getSystemService(DOWNLOAD_SERVICE) as DownloadManager
val uri = Uri.parse(path)
val request = DownloadManager.Request(uri)
val lastPathSegment = uri.lastPathSegment?.split(":")?.first()
request.setDestinationInExternalPublicDir(
DIRECTORY_DOWNLOADS,
"/" + getString(R.string.app_name) + "/" + lastPathSegment
)
request.setTitle(lastPathSegment)
request.setNotificationVisibility(VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
manager.enqueue(request)
}
@LayoutRes
protected abstract fun returnLayoutId(): Int
@MenuRes
protected abstract fun returnMenuId(): Int
} | kotlin | 26 | 0.670598 | 116 | 33.20442 | 181 | starcoderdata |
package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.test.diffFileFormat
import com.pinterest.ktlint.test.diffFileLint
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class SpacingAroundRangeOperatorRuleTest {
@Test
fun testLint() {
assertThat(SpacingAroundRangeOperatorRule().diffFileLint("spec/range-spacing/lint.kt.spec")).isEmpty()
}
@Test
fun testFormat() {
assertThat(
SpacingAroundRangeOperatorRule().diffFileFormat(
"spec/range-spacing/format.kt.spec",
"spec/range-spacing/format-expected.kt.spec"
)
).isEmpty()
}
}
| kotlin | 17 | 0.685377 | 110 | 27.208333 | 24 | starcoderdata |
package nl.hannahsten.texifyidea.reference
import com.intellij.psi.*
import nl.hannahsten.texifyidea.psi.BibtexDefinedString
import nl.hannahsten.texifyidea.psi.BibtexEntry
import nl.hannahsten.texifyidea.util.childrenOfType
import nl.hannahsten.texifyidea.util.tags
import nl.hannahsten.texifyidea.util.toTextRange
import nl.hannahsten.texifyidea.util.tokenName
import java.util.*
/**
* @author <NAME>
*/
open class BibtexStringReference(
val string: BibtexDefinedString
) : PsiReferenceBase<BibtexDefinedString>(string), PsiPolyVariantReference {
init {
rangeInElement = (0..string.textLength).toTextRange()
}
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
return string.containingFile.childrenOfType(BibtexEntry::class).asSequence()
.filter { it.tokenName()?.toLowerCase() == "string" }
.map { it.tags() }
.filter { !it.isEmpty() }
.map { it.first().key }
.filter { it.text == string.text }
.map { PsiElementResolveResult(it) }
.toList()
.toTypedArray()
}
override fun resolve(): PsiElement? {
val results = multiResolve(false)
return if (results.size == 1) results[0].element else null
}
override fun getVariants() = emptyArray<Any>()
} | kotlin | 32 | 0.679641 | 84 | 31.609756 | 41 | starcoderdata |
package xyz.nulldev.ts.syncdeploy
import com.github.salomonbrys.kodein.conf.KodeinGlobalAware
import com.github.salomonbrys.kodein.instance
import com.kizitonwose.time.hours
import com.kizitonwose.time.milliseconds
import com.kizitonwose.time.minutes
import com.kizitonwose.time.schedule
import mu.KotlinLogging
import xyz.nulldev.ts.config.ConfigManager
import java.io.File
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import kotlin.concurrent.withLock
class AccountManager: KodeinGlobalAware {
private val accounts = ConcurrentHashMap<String, Account>()
private val syncConfig = instance<ConfigManager>().module<SyncConfigModule>()
private val logger = KotlinLogging.logger {}
val VALID_USERNAME_CHARS = "abcdefghijklmnopqrstuvwxyz".let {
it + it.toUpperCase() + "_-@" + "0123456789"
}.toCharArray()
val MAX_USERNAME_LENGTH = 100
fun confAccount(account: String, password: String) {
lockAcc(account) {
//Write config
it.folder.mkdirs()
it.configFolder.mkdirs()
val configFile = File(it.configFolder, "server.config")
configFile.writeText("""
|ts.server.rootDir = ${it.syncDataFolder.absolutePath}
""".trimMargin())
//Copy sandbox template config
if(syncConfig.sandboxedConfig.isFile)
syncConfig.sandboxedConfig.copyTo(File(it.configFolder, "sandbox_template.config"))
//Conf password
confAccountPw(account, password)
}
}
fun confAccountPw(account: String, password: String) {
lockAcc(account) {
//Write password
it.pwFile.writeText(if (password.isNotEmpty())
PasswordHasher.getSaltedHash(password)
else "")
}
}
fun authAccount(account: String, password: String?): Boolean {
return lockAcc(account) {
val hash = it.pwFile.readText().trim()
if(password == null || password.isEmpty())
hash.isEmpty()
else
hash.isNotEmpty() && PasswordHasher.check(password, hash)
}
}
fun authToken(account: String, token: String?): Boolean {
return lockAcc(account) {
if(token != null && token.isNotEmpty())
it.token.toString() == token.trim()
else {
val hash = it.pwFile.readText().trim()
return hash.isEmpty()
}
}
}
@Synchronized
fun getAccount(account: String)
= synchronized(accounts) {
accounts.getOrPut(account, {
Account(account)
})
}
inline fun <T> lockAcc(account: String, block: (Account) -> T): T
= getAccount(account).let {
val res = it.lock.withLock {
block(it)
}
it.lastUsedTime = System.currentTimeMillis()
res
}
fun forceUnloadAccount(account: String) {
lockAcc(account) {
synchronized(accounts) {
accounts.remove(account)
}
}
}
private val ACCOUNT_REMOVAL_TIMEOUT = 1.hours
init {
val timer = Timer()
timer.schedule(1.minutes, 1.minutes) {
logger.debug { "Reaping accounts..." }
synchronized(accounts) {
val toRemove = mutableListOf<Account>()
accounts.forEach { _: String, u: Account ->
if(u.lock.tryLock()) {
val diff = System.currentTimeMillis() - u.lastUsedTime
if (diff.milliseconds > ACCOUNT_REMOVAL_TIMEOUT)
toRemove.add(u) //Keep account locked
else u.lock.unlock()
}
}
toRemove.forEach {
accounts.remove(it.name)
it.lock.unlock()
}
}
}
}
} | kotlin | 29 | 0.572403 | 99 | 30.165354 | 127 | starcoderdata |
package metrik.project.rest.vo.request
import metrik.project.domain.model.PipelineConfiguration
import metrik.project.domain.model.PipelineType
import javax.validation.constraints.NotBlank
class BambooDeploymentPipelineRequest(
@field:NotBlank(message = "Name cannot be empty") val name: String,
@field:NotBlank(message = "Credential cannot be empty") val credential: String,
url: String
) : PipelineRequest(url, PipelineType.BAMBOO_DEPLOYMENT.toString()) {
override fun toPipeline(projectId: String, pipelineId: String): PipelineConfiguration {
return with(this) {
PipelineConfiguration(
id = pipelineId,
projectId = projectId,
name = name,
username = null,
credential = credential,
url = url,
type = PipelineType.valueOf(type)
)
}
}
}
class BambooDeploymentVerificationRequest(
@field:NotBlank(message = "Credential cannot be null or empty") val credential: String,
url: String
) : PipelineVerificationRequest(url, PipelineType.BAMBOO_DEPLOYMENT.toString()) {
override fun toPipeline() = with(this) {
PipelineConfiguration(
username = null,
credential = credential,
url = url,
type = PipelineType.valueOf(type)
)
}
}
| kotlin | 20 | 0.644833 | 91 | 34.230769 | 39 | starcoderdata |
package codes.side.andcolorpicker.converter
import codes.side.andcolorpicker.model.Color
import codes.side.andcolorpicker.model.IntegerCMYKColor
class IntegerCMYKColorConverter : ColorConverter {
override fun convertToOpaqueColorInt(color: Color): Int {
TODO("Not yet implemented")
}
override fun convertToColorInt(color: Color): Int {
require(color is IntegerCMYKColor) { "Unsupported color type supplied" }
val r = 255f * (1f - color.floatC) * (1f - color.floatK)
val g = 255f * (1f - color.floatM) * (1f - color.floatK)
val b = 255f * (1f - color.floatY) * (1f - color.floatK)
return android.graphics.Color.rgb(
r.toInt(),
g.toInt(),
b.toInt()
)
}
override fun convertToPureHueColorInt(color: Color): Int {
TODO("Not yet implemented")
}
override fun setFromColorInt(color: Color, value: Int) {
require(color is IntegerCMYKColor) { "Unsupported color type supplied" }
val r = android.graphics.Color.red(value) / 255f
val g = android.graphics.Color.green(value) / 255f
val b = android.graphics.Color.blue(value) / 255f
val k = 1f - requireNotNull(
arrayOf(
r,
g,
b
).maxOrNull()
)
val c = (1f - r - k) / (1f - k)
val m = (1f - g - k) / (1f - k)
val y = (1f - b - k) / (1f - k)
color.copyValuesFrom(
intArrayOf(
(c * 100f).toInt(),
(m * 100f).toInt(),
(y * 100f).toInt(),
(k * 100f).toInt()
)
)
}
}
| kotlin | 18 | 0.607333 | 76 | 25.315789 | 57 | starcoderdata |
<reponame>Shouheng88/Android-VMLib
package me.shouheng.vmlib.task
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.shouheng.vmlib.bean.Resources
import me.shouheng.vmlib.bean.Status
/** Suspend task builder. */
@TaskDSLMaker
class SuspendTaskBuilder<R> : AbsTaskBuilder<R>() {
private var realTask: (suspend () -> Resources<R>)? = null
/**
* The task to execute. Specify your suspend task here.
* By default, the task start and end in [launchContext] and is executed
* in [executeContext]. You can use [launchOn] and [executeOn] to specify
* launch context and execute context.
*/
fun doTask(task: suspend () -> Resources<R>) {
realTask = task
}
override fun launch() {
GlobalScope.launch(launchContext) {
val result = withContext(executeContext) {
try {
realTask?.invoke()
} catch (e: Throwable) {
Resources.failed<R>("-1", e.message).apply {
throwable = e
}
}
}
when(result?.status) {
Status.SUCCESS -> { onSucceed?.invoke(result) }
Status.LOADING -> { onLoading?.invoke(result) }
Status.FAILED -> { onFailed?.invoke(result) }
}
}
}
}
| kotlin | 28 | 0.578092 | 77 | 31.159091 | 44 | starcoderdata |
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! ALL CHANGES TO IT WILL BE OVERWRITTEN ON EACH BUILD
package godot
import godot.icalls._icall_Texture
import godot.icalls._icall_Unit_Object
import godot.internal.utils.getMethodBind
import godot.internal.utils.invokeConstructor
import kotlinx.cinterop.COpaquePointer
open class PanoramaSky : Sky() {
open var panorama: Texture
get() {
val mb = getMethodBind("PanoramaSky","get_panorama")
return _icall_Texture(mb, this.ptr)
}
set(value) {
val mb = getMethodBind("PanoramaSky","set_panorama")
_icall_Unit_Object(mb, this.ptr, value)
}
override fun __new(): COpaquePointer = invokeConstructor("PanoramaSky", "PanoramaSky")
open fun getPanorama(): Texture {
val mb = getMethodBind("PanoramaSky","get_panorama")
return _icall_Texture( mb, this.ptr)
}
open fun setPanorama(texture: Texture) {
val mb = getMethodBind("PanoramaSky","set_panorama")
_icall_Unit_Object( mb, this.ptr, texture)
}
}
| kotlin | 13 | 0.71076 | 103 | 30.65625 | 32 | starcoderdata |
<filename>reposilite-backend/src/test/kotlin/com/reposilite/auth/AuthenticationFacadeTest.kt<gh_stars>100-1000
/*
* Copyright (c) 2021 dzikoysk
*
* 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.reposilite.auth
import com.reposilite.auth.specification.AuthenticationSpecification
import com.reposilite.web.http.ErrorResponse
import io.javalin.http.HttpCode.UNAUTHORIZED
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test
import panda.std.ResultAssertions.assertError
import panda.std.ResultAssertions.assertOk
internal class AuthenticationFacadeTest : AuthenticationSpecification() {
@Test
fun `should reject authentication request with invalid credentials`() = runBlocking {
// given: an existing token with unknown secret
val name = "name"
createToken(name)
// when: an authentication is requested with invalid credentials
val response = authenticationFacade.authenticateByCredentials(name, "invalid-secret")
// then: the request has been rejected
assertError(ErrorResponse(UNAUTHORIZED, "Invalid authorization credentials"), response)
}
@Test
fun `should authenticate by valid credentials`() = runBlocking {
// given: a credentials to the existing token
val name = "name"
val secret = "secret"
val accessToken = createToken(name, secret)
// when: an authentication is requested with valid credentials
val response = authenticationFacade.authenticateByCredentials(name, secret)
// then: the request has been authorized
assertOk(accessToken, response)
}
} | kotlin | 18 | 0.739675 | 110 | 36.824561 | 57 | starcoderdata |
// FIR_IDENTICAL
// FILE: a/x.java
package a;
public class x {
public b getB() { return null; }
public static class b {
public b getB() { return null; }
public static class b {
public b getB() { return null; }
public static class b {
public b getB() { return null; }
}
}
}
}
// FILE: b/x.java
package b;
import a.x.b.b.b;
public class x {
public b getB() { return null; }
}
// FILE: b/y.java
package b;
import a.x.b.b.*;
public class y {
public b getB() { return null; }
}
// FILE: b/test.kt
package b
fun test() = x().getB()
fun test2() = y().getB() | kotlin | 8 | 0.52259 | 48 | 12.571429 | 49 | starcoderdata |
// WITH_RUNTIME
annotation class AllOpen
annotation class Plain(val name: String, val index: Int) {
companion object {
@JvmStatic val staticProperty = 42
@JvmStatic fun staticFun() {}
}
}
@AllOpen
annotation class MyComponent(val name: String, val index: Int) {
companion object {
@JvmStatic val staticProperty = 42
@JvmStatic fun staticFun() {}
}
}
| kotlin | 9 | 0.653367 | 64 | 21.277778 | 18 | starcoderdata |
<filename>compiler/testData/diagnostics/tests/inline/nonPublicMember/inNonPublicInnerClass.kt<gh_stars>1000+
// FIR_IDENTICAL
// !DIAGNOSTICS: -UNUSED_EXPRESSION -UNUSED_PARAMETER -UNUSED_VARIABLE -NOTHING_TO_INLINE
internal class Z2 {
private val privateProperty = 11;
public val publicProperty:Int = 12
private fun privateFun() {}
public fun publicFun() {}
internal inner class ZInner {
public inline fun test() {
privateProperty
privateFun()
publicFun()
publicProperty
Z2().publicProperty
Z2().publicFun()
Z2().privateProperty
Z2().privateFun()
}
internal inline fun testInternal() {
privateProperty
privateFun()
publicFun()
publicProperty
Z2().publicProperty
Z2().publicFun()
Z2().privateProperty
Z2().privateFun()
}
}
} | kotlin | 18 | 0.578141 | 108 | 24.789474 | 38 | starcoderdata |
fun test(i: Int): Char {
val c: Char
when (i) {
1 -> c = '1'
2 -> c = '2'
3 -> c = '3'
4 -> c = '4'
5 -> c = '5'
6 -> c = '6'
7 -> c = '7'
8 -> c = '8'
9 -> c = '9'
0 -> c = '0'
else -> c = ' '
}
return c
}
// 12 ISTORE 1
// 1 LOCALVARIABLE c C
| kotlin | 9 | 0.271429 | 24 | 16.5 | 20 | starcoderdata |
// TARGET_BACKEND: JVM
// FILE: Generic.java
class Generic<T> {
T id(T x) { return x; }
}
// FILE: Specialized.java
class Specialized extends Generic<Runnable> {}
// FILE: use.kt
fun box(): String {
var result = "fail"
Specialized().id { result = "OK" }.run()
return result
}
| kotlin | 13 | 0.622449 | 46 | 18.6 | 15 | starcoderdata |
<filename>compiler/testData/codegen/box/inlineClasses/unboxGenericParameter/lambda/string.kt
// WITH_RUNTIME
fun <T> underlying(a: IC): T = bar(a) {
it.value as T
}
fun <T> extension(a: IC): T = bar(a) {
it.extensionValue()
}
fun <T> dispatch(a: IC): T = bar(a) {
it.dispatchValue()
}
fun <T> normal(a: IC): T = bar(a) {
normalValue(it)
}
fun <T, R> bar(value: T, f: (T) -> R): R {
return f(value)
}
fun <T> IC.extensionValue(): T = value as T
fun <T> normalValue(ic: IC): T = ic.value as T
@Suppress("OPTIONAL_DECLARATION_USAGE_IN_NON_COMMON_SOURCE")
@kotlin.jvm.JvmInline
value class IC(val value: String) {
fun <T> dispatchValue(): T = value as T
}
fun box(): String {
var res = underlying<String>(IC("O")) + "K"
if (res != "OK") return "FAIL 1: $res"
res = extension<String>(IC("O")) + "K"
if (res != "OK") return "FAIL 2: $res"
res = dispatch<String>(IC("O")) + "K"
if (res != "OK") return "FAIL 3: $res"
res = normal<String>(IC("O")) + "K"
if (res != "OK") return "FAIL 3: $res"
return "OK"
}
| kotlin | 14 | 0.585821 | 92 | 21.333333 | 48 | starcoderdata |
import com.diffplug.spotless.extra.wtp.EclipseWtpFormatterStep
import com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id("com.github.ben-manes.versions") version "0.27.0"
id("com.diffplug.gradle.spotless") version "3.26.1"
}
buildscript {
repositories {
jcenter()
}
dependencies {
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
spotless {
java {
target(fileTree(".") {
include("**/*.java")
exclude("**/build", "**/out")
})
removeUnusedImports()
trimTrailingWhitespace()
indentWithTabs()
replaceRegex("class-level javadoc indentation fix", "^\\*", " *")
replaceRegex("method-level javadoc indentation fix", "\t\\*", "\t *")
}
kotlinGradle {
target(fileTree(".") {
include("**/*.gradle.kts")
exclude("**/build", "**/out")
})
ktlint()
}
format("xml") {
target(fileTree(".") {
include("config/**/*.xml", "sshlib/**/*.xml")
exclude("**/build", "**/out")
})
eclipseWtp(EclipseWtpFormatterStep.XML).configFile("spotless.xml.prefs")
}
format("misc") {
target("**/.gitignore")
indentWithTabs()
trimTrailingWhitespace()
endWithNewline()
}
}
tasks.named<DependencyUpdatesTask>("dependencyUpdates") {
resolutionStrategy {
componentSelection {
all {
val rejected = listOf("alpha", "beta", "rc", "cr", "m", "preview", "b", "ea")
.map { qualifier -> Regex("(?i).*[.-]$qualifier[.\\d-+]*") }
.any { it.matches(candidate.version) }
if (rejected) {
reject("Release candidate")
}
}
}
}
// optional parameters
checkForGradleUpdate = true
outputFormatter = "json"
outputDir = "build/dependencyUpdates"
reportfileName = "report"
}
| kotlin | 34 | 0.550111 | 99 | 25.72619 | 84 | starcoderdata |
<reponame>vcaen/iosched
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.adssched.ui.agenda
import android.graphics.drawable.GradientDrawable
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.databinding.BindingAdapter
import com.google.samples.apps.adssched.R
import com.google.samples.apps.adssched.shared.util.TimeUtils
import org.threeten.bp.ZoneId
import org.threeten.bp.ZonedDateTime
import org.threeten.bp.format.DateTimeFormatter
private val agendaTimePattern = DateTimeFormatter.ofPattern("h:mm a")
@BindingAdapter(
value = ["agendaColor", "agendaStrokeColor", "agendaStrokeWidth"], requireAll = true
)
fun agendaColor(view: View, fillColor: Int, strokeColor: Int, strokeWidth: Float) {
view.background = (view.background as? GradientDrawable ?: GradientDrawable()).apply {
setColor(fillColor)
setStroke(strokeWidth.toInt(), strokeColor)
}
}
@BindingAdapter("agendaIcon")
fun agendaIcon(imageView: ImageView, type: String) {
val iconId = when (type) {
"after_hours" -> R.drawable.ic_agenda_after_hours
"badge" -> R.drawable.ic_agenda_badge
"codelab" -> R.drawable.ic_agenda_codelab
"concert" -> R.drawable.ic_agenda_concert
"keynote" -> R.drawable.ic_agenda_keynote
"meal" -> R.drawable.ic_agenda_meal
"office_hours" -> R.drawable.ic_agenda_office_hours
"sandbox" -> R.drawable.ic_agenda_sandbox
"store" -> R.drawable.ic_agenda_store
else -> R.drawable.ic_agenda_session
}
imageView.setImageDrawable(AppCompatResources.getDrawable(imageView.context, iconId))
}
@BindingAdapter(value = ["startTime", "endTime", "timeZoneId"], requireAll = true)
fun agendaDuration(
textView: TextView,
startTime: ZonedDateTime,
endTime: ZonedDateTime,
timeZoneId: ZoneId
) {
textView.text = textView.context.getString(
R.string.agenda_duration,
agendaTimePattern.format(TimeUtils.zonedTime(startTime, timeZoneId)),
agendaTimePattern.format(TimeUtils.zonedTime(endTime, timeZoneId))
)
}
| kotlin | 17 | 0.733212 | 90 | 36.534247 | 73 | starcoderdata |
<gh_stars>0
package org.jetbrains.research.kex.annotations
internal class PackageTreeNode(val name: String,
private val parentPrivate: PackageTreeNode?) {
val isRoot get() = parentPrivate == null
val parent get() = parentPrivate!!
val root: PackageTreeNode
get() = run {
var current = this
while (!current.isRoot)
current = current.parent
current
}
val fullName: String = if (parentPrivate?.parentPrivate != null) "${parentPrivate.fullName}/$name" else name
val nodes = mutableListOf<PackageTreeNode>()
val entities = mutableListOf<MutableAnnotatedCall>()
private fun buildString(builder: StringBuilder, offset: String) {
builder.append(offset).append(name).append(":\n")
val newOffset = "$offset "
for (entity in entities)
builder.append(newOffset).append(entity.toString()).append('\n')
for (node in nodes)
node.buildString(builder, newOffset)
}
override fun toString(): String {
val builder = StringBuilder()
buildString(builder, "")
return builder.toString()
}
}
| kotlin | 15 | 0.617573 | 112 | 32.194444 | 36 | starcoderdata |
// !LANGUAGE: +NewInference
// !DIAGNOSTICS: -UNUSED_EXPRESSION -UNUSED_VARIABLE -UNUSED_VALUE
// SKIP_TXT
/*
* KOTLIN DIAGNOSTICS NOT LINKED SPEC TEST (NEGATIVE)
*
* SECTIONS: dfa
* NUMBER: 19
* DESCRIPTION: Raw data flow analysis test
* HELPERS: classes, objects, typealiases, functions, enumClasses, interfaces, sealedClasses
*/
/*
* TESTCASE NUMBER: 1
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28489
*/
fun case_1(x: Boolean?) {
l1@ while (true) {
l2@ while (true || x!!) {
break@l1
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
/*
* TESTCASE NUMBER: 2
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28489
*/
fun case_2(x: Boolean?) {
l1@ while (true) {
l2@ do {
break@l1
} while (true || x!!)
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
/*
* TESTCASE NUMBER: 3
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28489
*/
fun case_3(x: Boolean?) {
l1@ do {
l2@ do {
break@l1
} while (true || x!!)
} while (true)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
/*
* TESTCASE NUMBER: 4
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28489
*/
fun case_4(x: Boolean?) {
l1@ do {
l2@ do {
break@l1
} while (x!!)
} while (true)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>.not()
}
// TESTCASE NUMBER: 5
fun case_5(x: Boolean?) {
l1@ do {
l2@ do {
break@l2
} while (x!!)
} while (true)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>.not()
}
// TESTCASE NUMBER: 6
fun case_6(x: Boolean?) {
l1@ do {
l2@ do {
break@l1
} while (true)
} while (x!!)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>.not()
}
// TESTCASE NUMBER: 7
fun case_7(x: Boolean?) {
l1@ while (true) {
l2@ while (true || x!!) {
break@l2
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
/*
* TESTCASE NUMBER: 8
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28489
*/
fun case_8(x: Boolean?) {
l1@ while (true || x!!) {
l2@ while (true) {
break@l2
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 9
fun case_9(x: Boolean?) {
l1@ while (true) {
break@l1
l2@ while (x!!) {
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>.not()
}
/*
* TESTCASE NUMBER: 10
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28489
*/
fun case_10(x: Boolean?) {
l1@ while (true) {
l2@ while (break@l1 || x!!) {
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 11
fun case_11(x: Boolean?) {
l1@ while (true) {
l2@ while (break@l1 && x!!) {
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 12
fun case_12(x: Boolean?) {
while (true) {
break || x!!
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 13
fun case_13(x: Boolean?) {
while (true) {
break && x!!
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 14
fun case_14(x: Boolean?) {
do {
break || x!!
} while (true)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 15
fun case_15(x: Boolean?) {
do {
break && x!!
} while (true)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 16
fun case_16(x: Boolean?) {
do {
break
} while (x!!)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>.not()
}
/*
* TESTCASE NUMBER: 17
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28489
*/
fun case_17(x: Boolean?) {
l1@ while (true) {
l2@ while (true) {
l3@ while (break@l2 || x!!) {
}
}
break
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
/*
* TESTCASE NUMBER: 18
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28489
*/
fun case_18(x: Boolean?) {
l1@ while (true) {
l2@ while (true) {
l3@ while (break@l1 || x!!) {
}
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 19
fun case_19(x: Boolean?) {
l1@ while (true) {
l2@ while (true) {
l3@ while (break@l1 && x!!) {
}
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 20
fun case_20(x: Boolean?) {
l1@ while (true) {
l2@ while (true) {
l3@ while (break@l2 && x!!) {
}
}
break
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 21
fun case_21(x: Boolean?) {
for (i in listOf(1, 2, 3)) {
break || x!!
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 22
fun case_22(x: Boolean?) {
for (i in listOf(1, 2, 3)) {
break && x!!
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 23
fun case_23(x: Boolean?) {
l1@ for (i in listOf(1, 2, 3)) {
l2@ for (j in listOf(1, 2, 3)) {
break@l1 || x!!
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 24
fun case_24(x: Boolean?) {
l1@ for (i in listOf(1, 2, 3)) {
l2@ for (j in listOf(1, 2, 3)) {
true || x!!
break@l1
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
// TESTCASE NUMBER: 25
fun case_25(x: Boolean?) {
l1@ for (i in listOf(1, 2, 3)) {
l2@ for (j in listOf(true || x!!, break@l1 || x!!, x!!)) {
break@l1
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>not<!>()
}
/*
* TESTCASE NUMBER: 26
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-30867
*/
fun case_26(x: Boolean?) {
while (true) {
for (i in listOf(break, x!!, x!!)) {
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean & kotlin.Boolean?")!>x<!>.not()
}
/*
* TESTCASE NUMBER: 27
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-30868
*/
fun case_27(x: Int?, y: Class) {
while (true) {
y[break, x!!]
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.inv()
}
/*
* TESTCASE NUMBER: 28
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-30868
*/
fun case_28(x: Int?, y: List<List<Int>>) {
while (true) {
y[break][x!!]
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.inv()
}
| kotlin | 19 | 0.557449 | 92 | 22.562176 | 386 | starcoderdata |
<reponame>Alex-----/lwjgl3
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package bullet.templates
import bullet.*
import org.lwjgl.generator.*
val btDefaultSoftBodySolver = "BTDefaultSoftBodySolver".nativeClass(Module.BULLET, prefixMethod = "bt", binding = BULLET_BINDING_DELEGATE) {
opaque_p(
"DefaultSoftBodySolver_new",
"",
void()
)
void(
"DefaultSoftBodySolver_copySoftBodyToVertexBuffer",
"",
opaque_p("obj", ""),
opaque_p("softBody", ""),
opaque_p("vertexBuffer", "")
)
} | kotlin | 19 | 0.628059 | 140 | 20.928571 | 28 | starcoderdata |
package uk.tvidal.kraft.server
import java.lang.Runtime.getRuntime
import kotlin.concurrent.thread
internal const val KRAFT_THREAD_NAME = "KRaftMainThread"
private const val SHUTDOWN_HOOK_THREAD_NAME = "KRaftShutdownHook"
fun registerStopServerShutdownHook(server: KRaftServer) = getRuntime().addShutdownHook(
thread(name = SHUTDOWN_HOOK_THREAD_NAME, start = false) {
server.close()
}
)
| kotlin | 15 | 0.769042 | 87 | 28.071429 | 14 | starcoderdata |
<reponame>VanyaKrylov/kotlin<filename>compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrConverter.kt<gh_stars>0
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.backend
import org.jetbrains.kotlin.config.AnalysisFlags
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.backend.evaluate.evaluateConstants
import org.jetbrains.kotlin.fir.backend.generators.*
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.utils.isLocal
import org.jetbrains.kotlin.fir.declarations.utils.isSynthetic
import org.jetbrains.kotlin.fir.declarations.utils.primaryConstructor
import org.jetbrains.kotlin.fir.descriptors.FirModuleDescriptor
import org.jetbrains.kotlin.fir.packageFqName
import org.jetbrains.kotlin.fir.psi
import org.jetbrains.kotlin.fir.resolve.ScopeSession
import org.jetbrains.kotlin.fir.signaturer.FirBasedSignatureComposer
import org.jetbrains.kotlin.fir.signaturer.FirMangler
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.PsiIrFileEntry
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFileImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrModuleFragmentImpl
import org.jetbrains.kotlin.ir.util.DeclarationStubGenerator
import org.jetbrains.kotlin.ir.util.ExternalDependenciesGenerator
import org.jetbrains.kotlin.ir.util.IdSignatureComposer
import org.jetbrains.kotlin.ir.util.SymbolTable
import org.jetbrains.kotlin.ir.visitors.acceptVoid
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi2ir.generators.GeneratorExtensions
import org.jetbrains.kotlin.psi2ir.generators.generateTypicalIrProviderList
class Fir2IrConverter(
private val moduleDescriptor: FirModuleDescriptor,
private val components: Fir2IrComponents
) : Fir2IrComponents by components {
fun processLocalClassAndNestedClasses(regularClass: FirRegularClass, parent: IrDeclarationParent) {
val irClass = registerClassAndNestedClasses(regularClass, parent)
processClassAndNestedClassHeaders(regularClass)
processClassMembers(regularClass, irClass)
}
fun processRegisteredLocalClassAndNestedClasses(regularClass: FirRegularClass, irClass: IrClass) {
regularClass.declarations.forEach {
if (it is FirRegularClass) {
registerClassAndNestedClasses(it, irClass)
}
}
processClassAndNestedClassHeaders(regularClass)
processClassMembers(regularClass, irClass)
}
fun registerFileAndClasses(file: FirFile, moduleFragment: IrModuleFragment) {
val irFile = IrFileImpl(
PsiIrFileEntry(file.psi as KtFile),
moduleDescriptor.getPackage(file.packageFqName).fragments.first(),
moduleFragment
)
declarationStorage.registerFile(file, irFile)
file.declarations.forEach {
if (it is FirRegularClass) {
registerClassAndNestedClasses(it, irFile)
}
}
moduleFragment.files += irFile
}
fun processClassHeaders(file: FirFile) {
file.declarations.forEach {
when (it) {
is FirRegularClass -> processClassAndNestedClassHeaders(it)
is FirTypeAlias -> classifierStorage.registerTypeAlias(it, declarationStorage.getIrFile(file))
}
}
}
fun processFileAndClassMembers(file: FirFile) {
val irFile = declarationStorage.getIrFile(file)
for (declaration in file.declarations) {
val irDeclaration = processMemberDeclaration(declaration, null, irFile) ?: continue
irFile.declarations += irDeclaration
}
}
fun processAnonymousObjectMembers(
anonymousObject: FirAnonymousObject,
irClass: IrClass = classifierStorage.getCachedIrClass(anonymousObject)!!
): IrClass {
anonymousObject.primaryConstructor?.let {
irClass.declarations += declarationStorage.createIrConstructor(
it, irClass, isLocal = true
)
}
val processedCallableNames = mutableSetOf<Name>()
val classes = mutableListOf<FirRegularClass>()
for (declaration in syntheticPropertiesLast(anonymousObject.declarations)) {
val irDeclaration = if (declaration is FirRegularClass) {
classes += declaration
registerClassAndNestedClasses(declaration, irClass)
} else {
when (declaration) {
is FirSimpleFunction -> processedCallableNames += declaration.name
is FirProperty -> processedCallableNames += declaration.name
}
processMemberDeclaration(declaration, anonymousObject, irClass) ?: continue
}
irClass.declarations += irDeclaration
}
classes.forEach { processClassAndNestedClassHeaders(it) }
classes.forEach { processClassMembers(it) }
// Add delegated members *before* fake override generations.
// Otherwise, fake overrides for delegated members, which are redundant, will be added.
val realDeclarations = delegatedMembers(irClass) + anonymousObject.declarations
with(fakeOverrideGenerator) {
irClass.addFakeOverrides(anonymousObject, realDeclarations)
}
return irClass
}
private fun processClassMembers(
regularClass: FirRegularClass,
irClass: IrClass = classifierStorage.getCachedIrClass(regularClass)!!
): IrClass {
val irConstructor = regularClass.primaryConstructor?.let {
declarationStorage.getOrCreateIrConstructor(it, irClass, isLocal = regularClass.isLocal)
}
if (irConstructor != null) {
irClass.declarations += irConstructor
}
val allDeclarations = regularClass.declarations.toMutableList()
for (declaration in syntheticPropertiesLast(regularClass.declarations)) {
val irDeclaration = processMemberDeclaration(declaration, regularClass, irClass) ?: continue
irClass.declarations += irDeclaration
}
// Add delegated members *before* fake override generations.
// Otherwise, fake overrides for delegated members, which are redundant, will be added.
allDeclarations += delegatedMembers(irClass)
// Add synthetic members *before* fake override generations.
// Otherwise, redundant members, e.g., synthetic toString _and_ fake override toString, will be added.
if (irConstructor != null && (irClass.isInline || irClass.isData)) {
declarationStorage.enterScope(irConstructor)
val dataClassMembersGenerator = DataClassMembersGenerator(components)
if (irClass.isInline) {
allDeclarations += dataClassMembersGenerator.generateInlineClassMembers(regularClass, irClass)
}
if (irClass.isData) {
allDeclarations += dataClassMembersGenerator.generateDataClassMembers(regularClass, irClass)
}
declarationStorage.leaveScope(irConstructor)
}
with(fakeOverrideGenerator) {
irClass.addFakeOverrides(regularClass, allDeclarations)
}
return irClass
}
private fun delegatedMembers(irClass: IrClass): List<FirDeclaration> {
return irClass.declarations.filter {
it.origin == IrDeclarationOrigin.DELEGATED_MEMBER
}.mapNotNull {
components.declarationStorage.originalDeclarationForDelegated(it)
}
}
// Sort declarations so that all non-synthetic declarations are before synthetic ones.
// This is needed because converting synthetic fields for implementation delegation needs to know
// existing declarations in the class to avoid adding redundant delegated members.
private fun syntheticPropertiesLast(declarations: List<FirDeclaration>): Iterable<FirDeclaration> {
return declarations.sortedBy { it !is FirField && it.isSynthetic }
}
private fun registerClassAndNestedClasses(regularClass: FirRegularClass, parent: IrDeclarationParent): IrClass {
val irClass = classifierStorage.registerIrClass(regularClass, parent)
regularClass.declarations.forEach {
if (it is FirRegularClass) {
registerClassAndNestedClasses(it, irClass)
}
}
return irClass
}
private fun processClassAndNestedClassHeaders(regularClass: FirRegularClass) {
classifierStorage.processClassHeader(regularClass)
regularClass.declarations.forEach {
if (it is FirRegularClass) {
processClassAndNestedClassHeaders(it)
}
}
}
private fun processMemberDeclaration(
declaration: FirDeclaration,
containingClass: FirClass?,
parent: IrDeclarationParent
): IrDeclaration? {
val isLocal = containingClass != null &&
(containingClass !is FirRegularClass || containingClass.isLocal)
return when (declaration) {
is FirRegularClass -> {
processClassMembers(declaration)
}
is FirSimpleFunction -> {
declarationStorage.getOrCreateIrFunction(
declaration, parent, isLocal = isLocal
)
}
is FirProperty -> {
declarationStorage.getOrCreateIrProperty(
declaration, parent, isLocal = isLocal
)
}
is FirField -> {
if (declaration.isSynthetic) {
declarationStorage.createIrFieldAndDelegatedMembers(declaration, containingClass!!, parent as IrClass)
} else {
throw AssertionError("Unexpected non-synthetic field: ${declaration::class}")
}
}
is FirConstructor -> if (!declaration.isPrimary) {
declarationStorage.getOrCreateIrConstructor(
declaration, parent as IrClass, isLocal = isLocal
)
} else {
null
}
is FirEnumEntry -> {
classifierStorage.createIrEnumEntry(declaration, parent as IrClass)
}
is FirAnonymousInitializer -> {
declarationStorage.createIrAnonymousInitializer(declaration, parent as IrClass)
}
is FirTypeAlias -> {
// DO NOTHING
null
}
else -> {
error("Unexpected member: ${declaration::class}")
}
}
}
companion object {
@OptIn(ObsoleteDescriptorBasedAPI::class)
fun createModuleFragment(
session: FirSession,
scopeSession: ScopeSession,
firFiles: List<FirFile>,
languageVersionSettings: LanguageVersionSettings,
signaturer: IdSignatureComposer,
generatorExtensions: GeneratorExtensions,
mangler: FirMangler,
irFactory: IrFactory,
visibilityConverter: Fir2IrVisibilityConverter,
specialSymbolProvider: Fir2IrSpecialSymbolProvider?
): Fir2IrResult {
val moduleDescriptor = FirModuleDescriptor(session)
val symbolTable = SymbolTable(signaturer, irFactory)
val signatureComposer = FirBasedSignatureComposer(mangler)
val components = Fir2IrComponentsStorage(session, scopeSession, symbolTable, irFactory, signatureComposer)
val classifierStorage = Fir2IrClassifierStorage(components)
components.classifierStorage = classifierStorage
components.delegatedMemberGenerator = DelegatedMemberGenerator(components)
val declarationStorage = Fir2IrDeclarationStorage(components, moduleDescriptor)
components.declarationStorage = declarationStorage
components.visibilityConverter = visibilityConverter
val typeConverter = Fir2IrTypeConverter(components)
components.typeConverter = typeConverter
val irBuiltIns =
IrBuiltInsOverFir(
components, languageVersionSettings, moduleDescriptor,
languageVersionSettings.getFlag(AnalysisFlags.builtInsFromSources)
)
components.irBuiltIns = irBuiltIns
val converter = Fir2IrConverter(moduleDescriptor, components)
val conversionScope = Fir2IrConversionScope()
val fir2irVisitor = Fir2IrVisitor(converter, components, conversionScope)
val builtIns = Fir2IrBuiltIns(components, specialSymbolProvider)
val annotationGenerator = AnnotationGenerator(components)
components.builtIns = builtIns
components.annotationGenerator = annotationGenerator
val fakeOverrideGenerator = FakeOverrideGenerator(components, conversionScope)
components.fakeOverrideGenerator = fakeOverrideGenerator
val callGenerator = CallAndReferenceGenerator(components, fir2irVisitor, conversionScope)
components.callGenerator = callGenerator
val irModuleFragment = IrModuleFragmentImpl(moduleDescriptor, irBuiltIns)
for (firFile in firFiles) {
converter.registerFileAndClasses(firFile, irModuleFragment)
}
val irProviders =
generateTypicalIrProviderList(irModuleFragment.descriptor, irBuiltIns, symbolTable, extensions = generatorExtensions)
val externalDependenciesGenerator = ExternalDependenciesGenerator(
symbolTable,
irProviders
)
// Necessary call to generate built-in IR classes
externalDependenciesGenerator.generateUnboundSymbolsAsDependencies()
classifierStorage.preCacheBuiltinClasses()
for (firFile in firFiles) {
converter.processClassHeaders(firFile)
}
for (firFile in firFiles) {
converter.processFileAndClassMembers(firFile)
}
for (firFile in firFiles) {
firFile.accept(fir2irVisitor, null)
}
externalDependenciesGenerator.generateUnboundSymbolsAsDependencies()
val stubGenerator = irProviders.filterIsInstance<DeclarationStubGenerator>().first()
irModuleFragment.acceptVoid(ExternalPackageParentPatcher(stubGenerator))
evaluateConstants(irModuleFragment)
return Fir2IrResult(irModuleFragment, symbolTable, components)
}
}
}
| kotlin | 28 | 0.677516 | 133 | 44.804878 | 328 | starcoderdata |
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.recipes.kt
import java.io.IOException
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
class PostString {
private val client = OkHttpClient()
fun run() {
val postBody = """
|Releases
|--------
|
| * _1.0_ May 6, 2013
| * _1.1_ June 15, 2013
| * _1.2_ August 11, 2013
|""".trimMargin()
val request = Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(postBody.toRequestBody(MEDIA_TYPE_MARKDOWN))
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body!!.string())
}
}
companion object {
val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType()
}
}
fun main() {
PostString().run()
}
| kotlin | 20 | 0.658491 | 83 | 27.392857 | 56 | starcoderdata |
package gg.essential.elementa.components
import gg.essential.elementa.UIComponent
import gg.essential.elementa.constraints.CenterConstraint
import gg.essential.elementa.constraints.RelativeConstraint
import gg.essential.elementa.constraints.SiblingConstraint
import gg.essential.elementa.constraints.animation.Animations
import gg.essential.elementa.dsl.*
import gg.essential.elementa.effects.ScissorEffect
import gg.essential.elementa.svg.SVGParser
import gg.essential.elementa.utils.bindLast
import gg.essential.universal.UKeyboard
import gg.essential.universal.UMouse
import gg.essential.universal.UResolution
import java.awt.Color
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.math.abs
import kotlin.math.max
/**
* Basic scroll component that will only draw what is currently visible.
*
* Also prevents scrolling past what should be reasonable.
*/
class ScrollComponent @JvmOverloads constructor(
emptyString: String = "",
private val innerPadding: Float = 0f,
private val scrollIconColor: Color = Color.WHITE,
private val horizontalScrollEnabled: Boolean = false,
private val verticalScrollEnabled: Boolean = true,
private val horizontalScrollOpposite: Boolean = false,
private val verticalScrollOpposite: Boolean = false,
private val pixelsPerScroll: Float = 15f,
private val scrollAcceleration: Float = 1.0f,
customScissorBoundingBox: UIComponent? = null
) : UIContainer() {
private var animationFPS: Int? = null
private val actualHolder = UIContainer().constrain {
x = innerPadding.pixels()
y = innerPadding.pixels()
width = RelativeConstraint(1f) - innerPadding.pixels()
height = RelativeConstraint(1f)
}
//Exposed so its position and value can be adjusted by user
val emptyText = UIWrappedText(emptyString, centered = true).constrain {
x = CenterConstraint()
y = SiblingConstraint() + 4.pixels()
}
private val scrollSVGComponent = getScrollImage().constrain {
width = 24.pixels()
height = 24.pixels()
color = scrollIconColor.toConstraint()
}
var horizontalOffset = innerPadding
private set
var verticalOffset = innerPadding
private set
private var horizontalScrollBarGrip: UIComponent? = null
private var horizontalHideScrollWhenUseless = false
private var verticalScrollBarGrip: UIComponent? = null
private var verticalHideScrollWhenUseless = false
private var horizontalDragBeginPos = -1f
private var verticalDragBeginPos = -1f
private val horizontalScrollAdjustEvents: MutableList<(Float, Float) -> Unit> =
mutableListOf(::updateScrollBar.bindLast(true))
private val verticalScrollAdjustEvents: MutableList<(Float, Float) -> Unit> =
mutableListOf(::updateScrollBar.bindLast(false))
private var needsUpdate = true
private var isAutoScrolling = false
private var autoScrollBegin: Pair<Float, Float> = -1f to -1f
private var currentScrollAcceleration: Float = 1.0f
val allChildren = CopyOnWriteArrayList<UIComponent>()
/**
* Difference between the ScrollComponent's width and its contents' width.
* Will not be less than zero, even if the contents' width is less than the
* component's width.
*/
val horizontalOverhang: Float
get() = max(0f, calculateActualWidth() - getWidth())
/**
* Difference between the ScrollComponent's height and its contents' height.
* Will not be less than zero, even if the contents' height is less than the
* component's height.
*/
val verticalOverhang: Float
get() = max(0f, calculateActualHeight() - getHeight())
init {
if (!horizontalScrollEnabled && !verticalScrollEnabled)
throw IllegalArgumentException("ScrollComponent must have at least one direction of scrolling enabled")
super.addChild(actualHolder)
actualHolder.addChild(emptyText)
this.enableEffects(ScissorEffect(customScissorBoundingBox))
emptyText.setFontProvider(getFontProvider())
super.addChild(scrollSVGComponent)
scrollSVGComponent.hide(instantly = true)
onMouseScroll {
if (UKeyboard.isShiftKeyDown() && horizontalScrollEnabled) {
onScroll(it.delta.toFloat(), isHorizontal = true)
} else if (!UKeyboard.isShiftKeyDown() && verticalScrollEnabled) {
onScroll(it.delta.toFloat(), isHorizontal = false)
}
it.stopPropagation()
}
onMouseClick { event ->
onClick(event.relativeX, event.relativeY, event.mouseButton)
}
}
override fun draw() {
if (needsUpdate) {
needsUpdate = false
val horizontalRange = calculateOffsetRange(isHorizontal = true)
val verticalRange = calculateOffsetRange(isHorizontal = false)
// Recalculate our scroll box and move the content inside if needed.
actualHolder.animate {
horizontalOffset =
if (horizontalRange.isEmpty()) innerPadding else horizontalOffset.coerceIn(horizontalRange)
verticalOffset = if (verticalRange.isEmpty()) innerPadding else verticalOffset.coerceIn(verticalRange)
setXAnimation(Animations.IN_SIN, 0.1f, horizontalOffset.pixels())
setYAnimation(Animations.IN_SIN, 0.1f, verticalOffset.pixels())
}
// Run our scroll adjust event, normally updating [scrollBarGrip]
var percent = abs(horizontalOffset) / horizontalRange.width()
var percentageOfParent = this.getWidth() / calculateActualWidth()
horizontalScrollAdjustEvents.forEach { it(percent, percentageOfParent) }
percent = abs(verticalOffset) / verticalRange.width()
percentageOfParent = this.getHeight() / calculateActualHeight()
verticalScrollAdjustEvents.forEach { it(percent, percentageOfParent) }
}
super.draw()
}
override fun afterInitialization() {
super.afterInitialization()
animationFPS = Window.of(this).animationFPS
}
/**
* Sets the text that appears when no items are shown
*/
fun setEmptyText(text: String) {
emptyText.setText(text)
}
fun addScrollAdjustEvent(
isHorizontal: Boolean,
event: (scrollPercentage: Float, percentageOfParent: Float) -> Unit
) {
if (isHorizontal) horizontalScrollAdjustEvents.add(event) else verticalScrollAdjustEvents.add(event)
}
@JvmOverloads
fun setHorizontalScrollBarComponent(component: UIComponent, hideWhenUseless: Boolean = false) {
setScrollBarComponent(component, hideWhenUseless, isHorizontal = true)
}
@JvmOverloads
fun setVerticalScrollBarComponent(component: UIComponent, hideWhenUseless: Boolean = false) {
setScrollBarComponent(component, hideWhenUseless, isHorizontal = false)
}
/**
* A scroll bar component is an optional component that can visually display the scroll status
* of this scroll component (just like any scroll bar).
*
* The utility here is that it is automatically updated by this component with no extra work on the user-end.
*
* The hierarchy for this scrollbar grip component must be as follows:
* - Have a containing parent being the full height range of this scroll bar.
*
* [component]'s mouse events will all be overridden by this action.
*
* If [hideWhenUseless] is enabled, [component] will have [hide] called on it when the scrollbar is full height
* and dragging it would do nothing.
*/
fun setScrollBarComponent(component: UIComponent, hideWhenUseless: Boolean, isHorizontal: Boolean) {
if (isHorizontal) {
horizontalScrollBarGrip = component
horizontalHideScrollWhenUseless = hideWhenUseless
} else {
verticalScrollBarGrip = component
verticalHideScrollWhenUseless = hideWhenUseless
}
component.onMouseScroll {
if (isHorizontal && horizontalScrollEnabled && UKeyboard.isShiftKeyDown()) {
onScroll(it.delta.toFloat(), isHorizontal = true)
} else if (!isHorizontal && verticalScrollEnabled) {
onScroll(it.delta.toFloat(), isHorizontal = false)
}
it.stopPropagation()
}
component.onMouseClick { event ->
if (isHorizontal) {
horizontalDragBeginPos = event.relativeX
} else {
verticalDragBeginPos = event.relativeY
}
}
component.onMouseDrag { mouseX, mouseY, _ ->
if (isHorizontal) {
if (horizontalDragBeginPos == -1f)
return@onMouseDrag
updateGrip(component, mouseX, isHorizontal = true)
} else {
if (verticalDragBeginPos == -1f)
return@onMouseDrag
updateGrip(component, mouseY, isHorizontal = false)
}
}
component.onMouseRelease {
if (isHorizontal) {
horizontalDragBeginPos = -1f
} else {
verticalDragBeginPos = -1f
}
}
needsUpdate = true
}
fun scrollToLeft(smoothScroll: Boolean = true) {
// This gets clamped later
horizontalOffset = Float.POSITIVE_INFINITY
if (smoothScroll) {
needsUpdate = true
return
}
val horizontalRange = calculateOffsetRange(isHorizontal = true)
actualHolder.setX(horizontalRange.endInclusive.pixels())
horizontalScrollAdjustEvents.forEach { it(0f, this.getWidth() / calculateActualWidth()) }
}
fun scrollToRight(smoothScroll: Boolean = true) {
// This gets clamped later
horizontalOffset = Float.NEGATIVE_INFINITY
if (smoothScroll) {
needsUpdate = true
return
}
val horizontalRange = calculateOffsetRange(isHorizontal = true)
actualHolder.setX(horizontalRange.start.pixels())
horizontalScrollAdjustEvents.forEach { it(1f, this.getWidth() / calculateActualWidth()) }
}
fun scrollToTop(smoothScroll: Boolean = true) {
// This gets clamped later
verticalOffset = Float.POSITIVE_INFINITY
if (smoothScroll) {
needsUpdate = true
return
}
val verticalRange = calculateOffsetRange(isHorizontal = false)
actualHolder.setY(verticalRange.endInclusive.pixels())
verticalScrollAdjustEvents.forEach { it(0f, this.getHeight() / calculateActualHeight()) }
}
fun scrollToBottom(smoothScroll: Boolean = true) {
// This gets clamped later
verticalOffset = Float.NEGATIVE_INFINITY
if (smoothScroll) {
needsUpdate = true
return
}
val verticalRange = calculateOffsetRange(isHorizontal = false)
actualHolder.setY(verticalRange.start.pixels())
verticalScrollAdjustEvents.forEach { it(1f, this.getHeight() / calculateActualHeight()) }
}
fun filterChildren(filter: (component: UIComponent) -> Boolean) {
actualHolder.children.clear()
actualHolder.children.addAll(allChildren.filter(filter).ifEmpty { listOf(emptyText) })
actualHolder.children.forEach { it.parent = actualHolder }
needsUpdate = true
}
@JvmOverloads
fun <T : Comparable<T>> sortChildren(descending: Boolean = false, comparator: (UIComponent) -> T) {
if (descending) {
actualHolder.children.sortByDescending(comparator)
} else {
actualHolder.children.sortBy(comparator)
}
}
fun sortChildren(comparator: Comparator<UIComponent>) {
actualHolder.children.sortWith(comparator)
}
private fun updateGrip(component: UIComponent, mouseCoord: Float, isHorizontal: Boolean) {
if (isHorizontal) {
val minCoord = component.parent.getLeft()
val maxCoord = component.parent.getRight()
val dragDelta = mouseCoord - horizontalDragBeginPos
horizontalOffset = if (horizontalScrollOpposite) {
val newPos = maxCoord - component.getRight() - dragDelta
val percentage = newPos / (maxCoord - minCoord)
percentage * calculateActualWidth()
} else {
val newPos = component.getLeft() + dragDelta - minCoord
val percentage = newPos / (maxCoord - minCoord)
-(percentage * calculateActualWidth())
}
} else {
val minCoord = component.parent.getTop()
val maxCoord = component.parent.getBottom()
val dragDelta = mouseCoord - verticalDragBeginPos
verticalOffset = if (verticalScrollOpposite) {
val newPos = maxCoord - component.getBottom() - dragDelta
val percentage = newPos / (maxCoord - minCoord)
percentage * calculateActualHeight()
} else {
val newPos = component.getTop() + dragDelta - minCoord
val percentage = newPos / (maxCoord - minCoord)
-(percentage * calculateActualHeight())
}
}
needsUpdate = true
}
private fun onScroll(delta: Float, isHorizontal: Boolean) {
if (isHorizontal) {
horizontalOffset += delta * pixelsPerScroll * currentScrollAcceleration
} else {
verticalOffset += delta * pixelsPerScroll * currentScrollAcceleration
}
currentScrollAcceleration =
(currentScrollAcceleration + (scrollAcceleration - 1.0f) * 0.15f).coerceIn(0f, scrollAcceleration)
needsUpdate = true
}
private fun updateScrollBar(scrollPercentage: Float, percentageOfParent: Float, isHorizontal: Boolean) {
val component = if (isHorizontal) {
horizontalScrollBarGrip ?: return
} else {
verticalScrollBarGrip ?: return
}
val clampedPercentage = percentageOfParent.coerceAtMost(1f)
if ((isHorizontal && horizontalHideScrollWhenUseless) || (!isHorizontal && verticalHideScrollWhenUseless)) {
if (clampedPercentage == 1f) {
Window.enqueueRenderOperation(component::hide)
return
} else {
Window.enqueueRenderOperation(component::unhide)
}
}
if (isHorizontal) {
component.setWidth(RelativeConstraint(clampedPercentage))
} else {
component.setHeight(RelativeConstraint(clampedPercentage))
}
component.animate {
if (isHorizontal) {
setXAnimation(
Animations.IN_SIN, 0.1f, basicXConstraint { component ->
val offset = (component.parent.getWidth() - component.getWidth()) * scrollPercentage
if (horizontalScrollOpposite) component.parent.getRight() - component.getHeight() - offset
else component.parent.getLeft() + offset
}
)
} else {
setYAnimation(
Animations.IN_SIN, 0.1f, basicYConstraint { component ->
val offset = (component.parent.getHeight() - component.getHeight()) * scrollPercentage
if (verticalScrollOpposite) component.parent.getBottom() - component.getHeight() - offset
else component.parent.getTop() + offset
}
)
}
}
}
private fun calculateActualWidth(): Float {
if (actualHolder.children.isEmpty()) return 0f
return actualHolder.children.let { c ->
c.maxOf { it.getRight() } - c.minOf { it.getLeft() }
}
}
private fun calculateActualHeight(): Float {
if (actualHolder.children.isEmpty()) return 0f
return actualHolder.children.let { c ->
c.maxOf { it.getBottom() } - c.minOf { it.getTop() }
}
}
private fun calculateOffsetRange(isHorizontal: Boolean): ClosedFloatingPointRange<Float> {
return if (isHorizontal) {
val actualWidth = calculateActualWidth()
val maxNegative = this.getWidth() - actualWidth - innerPadding
if (horizontalScrollOpposite) (-innerPadding)..-maxNegative else maxNegative..(innerPadding)
} else {
val actualHeight = calculateActualHeight()
val maxNegative = this.getHeight() - actualHeight - innerPadding
if (verticalScrollOpposite) (-innerPadding)..-maxNegative else maxNegative..(innerPadding)
}
}
private fun onClick(mouseX: Float, mouseY: Float, mouseButton: Int) {
if (isAutoScrolling) {
isAutoScrolling = false
scrollSVGComponent.hide()
return
}
if (mouseButton == 2) {
// Middle click, begin the auto scroll
isAutoScrolling = true
autoScrollBegin = mouseX to mouseY
scrollSVGComponent.constrain {
x = (mouseX - 12).pixels()
y = (mouseY - 12).pixels()
}
scrollSVGComponent.unhide(useLastPosition = false)
}
}
override fun animationFrame() {
super.animationFrame()
currentScrollAcceleration =
(currentScrollAcceleration - ((scrollAcceleration - 1.0f) / (animationFPS ?: 244).toFloat()))
.coerceAtLeast(1.0f)
if (!isAutoScrolling) return
if (horizontalScrollEnabled) {
val xBegin = autoScrollBegin.first + getLeft()
val currentX = UMouse.getScaledX()
if (currentX in getLeft()..getRight()) {
val deltaX = currentX - xBegin
val percentX = deltaX / (-getWidth() / 2)
horizontalOffset += (percentX.toFloat() * 5f)
needsUpdate = true
}
}
if (verticalScrollEnabled) {
val yBegin = autoScrollBegin.second + getTop()
val currentY = UResolution.scaledHeight - UMouse.getScaledY() - 1
if (currentY in getTop()..getBottom()) {
val deltaY = currentY - yBegin
val percentY = deltaY / (-getHeight() / 2)
verticalOffset += (percentY.toFloat() * 5f)
needsUpdate = true
}
}
needsUpdate = true
}
override fun addChild(component: UIComponent) = apply {
actualHolder.removeChild(emptyText)
actualHolder.addChild(component)
allChildren.add(component)
needsUpdate = true
}
override fun insertChildAt(component: UIComponent, index: Int) = apply {
if (index < 0 || index > allChildren.size) {
println("Bad index given to insertChildAt (index: $index, children size: ${allChildren.size}")
return@apply
}
actualHolder.removeChild(emptyText)
component.parent = actualHolder
actualHolder.children.add(index, component)
allChildren.add(index, component)
needsUpdate = true
}
override fun insertChildBefore(newComponent: UIComponent, targetComponent: UIComponent) = apply {
val indexOfExisting = allChildren.indexOf(targetComponent)
if (indexOfExisting == -1) {
println("targetComponent given to insertChildBefore is not a child of this component")
return@apply
}
insertChildAt(newComponent, indexOfExisting)
}
override fun insertChildAfter(newComponent: UIComponent, targetComponent: UIComponent) = apply {
val indexOfExisting = allChildren.indexOf(targetComponent)
if (indexOfExisting == -1) {
println("targetComponent given to insertChildAfter is not a child of this component")
return@apply
}
insertChildAt(newComponent, indexOfExisting + 1)
}
override fun replaceChild(newComponent: UIComponent, componentToReplace: UIComponent) = apply {
val indexOfExisting = allChildren.indexOf(componentToReplace)
if (indexOfExisting == -1) {
println("componentToReplace given to replaceChild is not a child of this component")
return@apply
}
actualHolder.removeChild(emptyText)
actualHolder.children.removeAt(indexOfExisting)
allChildren.removeAt(indexOfExisting)
newComponent.parent = actualHolder
actualHolder.children.add(indexOfExisting, newComponent)
allChildren.add(indexOfExisting, newComponent)
needsUpdate = true
}
override fun removeChild(component: UIComponent) = apply {
if (component == scrollSVGComponent) {
super.removeChild(component)
return@apply
}
actualHolder.removeChild(component)
allChildren.remove(component)
if (allChildren.isEmpty())
actualHolder.addChild(emptyText)
needsUpdate = true
}
override fun clearChildren() = apply {
allChildren.clear()
actualHolder.clearChildren()
actualHolder.addChild(emptyText)
needsUpdate = true
}
override fun alwaysDrawChildren(): Boolean {
return true
}
override fun <T> childrenOfType(clazz: Class<T>): List<T> {
return actualHolder.childrenOfType(clazz)
}
override fun mouseClick(mouseX: Double, mouseY: Double, button: Int) {
actualHolder.mouseClick(mouseX, mouseY, button)
}
override fun hitTest(x: Float, y: Float): UIComponent {
return actualHolder.hitTest(x, y)
}
fun searchAndInsert(components: List<UIComponent>, comparison: (UIComponent) -> Int) {
if (components.isEmpty()) return
actualHolder.children.remove(emptyText)
val searchIndex = actualHolder.children.binarySearch(comparison = comparison)
components.forEach { it.parent = actualHolder }
allChildren.addAll(components)
actualHolder.children.addAll(
if (searchIndex >= 0) searchIndex else -(searchIndex + 1),
components
)
needsUpdate = true
}
fun setChildren(components: List<UIComponent>) = apply {
actualHolder.children.clear()
actualHolder.children.addAll(components.ifEmpty { listOf(emptyText) })
actualHolder.children.forEach { it.parent = actualHolder }
allChildren.clear()
allChildren.addAll(actualHolder.children)
needsUpdate = true
}
private fun ClosedFloatingPointRange<Double>.width() = abs(this.start - this.endInclusive)
private fun ClosedFloatingPointRange<Float>.width() = abs(this.start - this.endInclusive)
class DefaultScrollBar(isHorizontal: Boolean) : UIComponent() {
val grip: UIComponent
init {
if (isHorizontal) {
constrain {
y = 2.pixels(alignOpposite = true)
width = 100.percent()
height = 10.pixels()
}
val container = UIContainer().constrain {
x = 2.pixels()
y = CenterConstraint()
width = RelativeConstraint() - 4.pixels()
height = 4.pixels()
} childOf this
grip = UIBlock(Color(70, 70, 70)).constrain {
x = 0.pixels(alignOpposite = true)
y = CenterConstraint()
width = 30.pixels()
height = 3.pixels()
} childOf container
} else {
constrain {
x = 2.pixels(alignOpposite = true)
width = 10.pixels()
height = 100.percent()
}
val container = UIContainer().constrain {
x = CenterConstraint()
y = 2.pixels()
width = 4.pixels()
height = RelativeConstraint() - 4.pixels()
} childOf this
grip = UIBlock(Color(70, 70, 70)).constrain {
x = CenterConstraint()
y = 0.pixels(alignOpposite = true)
width = 3.pixels()
height = 30.pixels()
} childOf container
}
}
}
companion object {
fun getScrollImage(): UIImage {
return UIImage.ofResourceCached("/svg/scroll.png")
}
}
}
| kotlin | 31 | 0.619466 | 118 | 34.686331 | 695 | starcoderdata |
package dev.entao.kava.base
/**
* Created by <EMAIL> on 2016/12/20.
*/
val PROGRESS_DELAY = 100
interface Progress {
fun onStart(total: Int)
fun onProgress(current: Int, total: Int, percent: Int)
fun onFinish(success: Boolean)
}
| kotlin | 7 | 0.673387 | 58 | 15.533333 | 15 | starcoderdata |
package com.chebdowski.data.scheduler
import com.chebdowski.domain.scheduler.ComposedScheduler
import io.reactivex.SingleTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class AndroidComposedScheduler : ComposedScheduler {
override fun <T> applySingleScheduling(): SingleTransformer<T, T> {
return SingleTransformer { upstream ->
upstream
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
}
}
| kotlin | 21 | 0.729583 | 71 | 31.411765 | 17 | starcoderdata |
package io.github.config4k
import io.kotlintest.matchers.haveSize
import io.kotlintest.should
import io.kotlintest.shouldBe
import io.kotlintest.specs.WordSpec
import java.time.Duration
import java.util.*
class TestCollections : WordSpec({
val config = "key = [0m, 1m, 1m, 2m]".toConfig()
"Config.extract" should {
"return List" {
val list = config.extract<List<Duration>>("key")
list shouldBe listOf(Duration.ofMinutes(0),
Duration.ofMinutes(1),
Duration.ofMinutes(1),
Duration.ofMinutes(2))
}
"return List<List<Int>>" {
val intListConfig = "key = [[0, 0], [1, 1]]".toConfig()
val list = intListConfig.extract<List<List<Int>>>("key")
list shouldBe listOf(listOf(0, 0), listOf(1, 1))
}
"return Set" {
val set = config.extract<Set<Duration>>("key")
set should haveSize(3)
set shouldBe setOf(Duration.ofMinutes(0),
Duration.ofMinutes(1),
Duration.ofMinutes(1),
Duration.ofMinutes(2))
}
"return Array<T>" {
Arrays.deepEquals(
"""key = ["a", "b", "c", "d"]""".toConfig()
.extract<Array<String>>("key"),
arrayOf("a", "b", "c", "d")) shouldBe true
Arrays.deepEquals(
"""key = ["0m", "1m"]""".toConfig()
.extract<Array<Duration>>("key"),
arrayOf(Duration.ofMinutes(0),
Duration.ofMinutes(1))) shouldBe true
}
}
}) | kotlin | 29 | 0.502955 | 68 | 33.55102 | 49 | starcoderdata |
<filename>subprojects/gradle/ui-test-bytecode-analyzer/src/test/kotlin/com/avito/bytecode/metadata/MetadataFoundTest.kt<gh_stars>0
package com.avito.bytecode.metadata
import com.avito.bytecode.extractMetadata
import com.avito.bytecode.metadata.IdFieldExtractor.ScreenToId
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
class MetadataFoundTest {
@Test
fun `metadata found on target classes`() {
val metadata: Set<ScreenToId> = extractMetadata()
assertThat(metadata).containsAtLeast(
ScreenToId(
"com.example.dimorinny.example.screen.Page1",
"1"
),
ScreenToId(
"com.example.dimorinny.example.screen.Page2",
"2"
),
ScreenToId(
"com.example.dimorinny.example.screen.Page3FirstImplementation",
"31"
),
ScreenToId(
"com.example.dimorinny.example.screen.Page3SecondImplementation",
"32"
),
ScreenToId(
"com.example.dimorinny.example.screen.Page3SuperSpecialFirstImplementation",
"-1"
),
ScreenToId(
"com.example.dimorinny.example.screen.Page3SuperSpecialSecondImplementation",
"332"
)
)
}
@Test
fun `metadata found on target classes from abstract class`() {
val metadata: Set<ScreenToId> = extractMetadata()
assertThat(metadata).containsAtLeast(
ScreenToId("com.example.dimorinny.example.screen.Page4FirstImplementation", "4"),
ScreenToId("com.example.dimorinny.example.screen.Page4SecondImplementation", "4")
)
}
}
| kotlin | 14 | 0.609428 | 130 | 33.269231 | 52 | starcoderdata |
/*
* MIT License
*
* Copyright (C) 2020 The SimpleCloud authors
*
* 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 eu.thesimplecloud.api.sync.list.manager
import com.google.common.collect.Maps
import eu.thesimplecloud.api.CloudAPI
import eu.thesimplecloud.api.network.packets.sync.list.PacketIOGetAllCachedListProperties
import eu.thesimplecloud.api.sync.list.ISynchronizedObjectList
import eu.thesimplecloud.clientserverapi.client.INettyClient
import eu.thesimplecloud.clientserverapi.lib.promise.CommunicationPromise
import eu.thesimplecloud.clientserverapi.lib.promise.ICommunicationPromise
import eu.thesimplecloud.clientserverapi.lib.promise.combineAllPromises
class SynchronizedObjectListManager : ISynchronizedObjectListManager {
private val nameToSynchronizedObjectList = Maps.newConcurrentMap<String, ISynchronizedObjectList<out Any>>()
override fun registerSynchronizedObjectList(
synchronizedObjectList: ISynchronizedObjectList<out Any>,
syncContent: Boolean
): ICommunicationPromise<Unit> {
if (syncContent && CloudAPI.instance.isManager()) {
val oldObject = getSynchronizedObjectList(synchronizedObjectList.getIdentificationName())
oldObject?.let { oldList ->
oldList.getAllCachedObjects().map { oldList.remove(it) }.combineAllPromises().awaitUninterruptibly()
}
}
this.nameToSynchronizedObjectList[synchronizedObjectList.getIdentificationName()] = synchronizedObjectList
if (syncContent) {
if (!CloudAPI.instance.isManager()) {
val client = CloudAPI.instance.getThisSidesCommunicationBootstrap() as INettyClient
return client.getConnection()
.sendUnitQuery(
PacketIOGetAllCachedListProperties(synchronizedObjectList.getIdentificationName()),
4000
).syncUninterruptibly()
} else {
//manager
synchronizedObjectList as ISynchronizedObjectList<Any>
synchronizedObjectList.getAllCachedObjects().forEach { synchronizedObjectList.update(it) }
}
}
return CommunicationPromise.of(Unit)
}
override fun getSynchronizedObjectList(name: String): ISynchronizedObjectList<Any>? =
this.nameToSynchronizedObjectList[name] as ISynchronizedObjectList<Any>?
override fun unregisterSynchronizedObjectList(name: String) {
this.nameToSynchronizedObjectList.remove(name)
}
} | kotlin | 27 | 0.72934 | 116 | 47.743243 | 74 | starcoderdata |
/**
* Copyright 2006 - 2021 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 jetbrains.exodus.database.exceptions
import jetbrains.exodus.database.TransientEntity
open class ConstraintsValidationException(val causes: Set<DataIntegrityViolationException>) : DataIntegrityViolationException(buildMessage(causes)) {
override val entityFieldHandler get() = null
constructor(cause: DataIntegrityViolationException) : this(setOf(cause))
override fun relatesTo(entity: TransientEntity, fieldIdentity: Any?): Boolean {
return causes.any { it.relatesTo(entity, fieldIdentity) }
}
}
private fun buildMessage(causes: Set<DataIntegrityViolationException>) = buildString {
append("Constrains validation exception. Causes: \n")
causes.forEachIndexed { i, e ->
append(" ${i + 1}: ${e.message}\n")
}
}
| kotlin | 21 | 0.74344 | 149 | 37.111111 | 36 | starcoderdata |
<reponame>3DRing/PhotoHackServer
package com.ringov.data
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface UrlRepository : JpaRepository<Url, String>
| kotlin | 8 | 0.858974 | 60 | 28.25 | 8 | starcoderdata |
// Automatically generated - do not modify!
package react.dom
import org.w3c.dom.Element
external interface OptionHTMLAttributes<T : Element> : HTMLAttributes<T> {
var disabled: Boolean
var label: String
var selected: Boolean
var value: String
}
| kotlin | 7 | 0.732075 | 74 | 21.083333 | 12 | starcoderdata |
<reponame>quleuber/kafka-project
rootProject.name = "rbs-kafka"
| kotlin | 4 | 0.796875 | 32 | 31 | 2 | starcoderdata |
<gh_stars>0
package canon.parser.xml.strategy
import canon.api.IRenderable
import canon.extension.attrAsText
import canon.model.Text
import org.w3c.dom.Node
class OldTextStrategy : AbstractParseStrategy<Text>() {
override fun parse(node: Node, context: Map<String, Any?>, factory: (Node, Map<String, Any?>) -> List<IRenderable>): Text {
val id = node.attrAsText("id")
val `class` = node.attrAsText("class")
return Text(id, `class`, node.textContent)
}
} | kotlin | 13 | 0.697342 | 127 | 27.823529 | 17 | starcoderdata |
<gh_stars>0
package top.ntutn.simpleclock
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.customview.widget.ViewDragHelper
class FrameDraggableFrameLayout : FrameLayout {
private lateinit var mDragHelper: ViewDragHelper
var onDragEventListener: OnDragEventListener? = null
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
init()
}
private fun init() {
val callback: ViewDragHelper.Callback = object : ViewDragHelper.Callback() {
private val positionBeforeTryCapture = mutableMapOf<View, Pair<Int, Int>>()
private val positionBeforeCapture = mutableMapOf<View, Pair<Int, Int>>()
override fun tryCaptureView(child: View, pointerId: Int): Boolean {
positionBeforeTryCapture.getOrPut(child) { child.left to child.top }
return child is Draggable
}
override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int): Int =
if (child is HorizontalDraggable) left
else positionBeforeTryCapture[child]?.first ?: 0
override fun clampViewPositionVertical(child: View, top: Int, dy: Int): Int =
if (child is VerticalDraggable) top
else positionBeforeTryCapture[child]?.second ?: 0
override fun onViewCaptured(capturedChild: View, activePointerId: Int) {
super.onViewCaptured(capturedChild, activePointerId)
positionBeforeCapture.getOrPut(capturedChild) { capturedChild.left to capturedChild.top }
}
override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
super.onViewReleased(releasedChild, xvel, yvel)
mDragHelper.settleCapturedViewAt(
positionBeforeCapture[releasedChild]?.first ?: 0,
positionBeforeCapture[releasedChild]?.second ?: 0
)
invalidate()
onDragEventListener?.onDragReleases(releasedChild)
}
}
mDragHelper = ViewDragHelper.create(this, callback)
}
override fun computeScroll() {
super.computeScroll()
if (mDragHelper.continueSettling(true)) {
invalidate()
}
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
return mDragHelper.shouldInterceptTouchEvent(ev)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
mDragHelper.processTouchEvent(event)
return true
}
interface OnDragEventListener {
fun onDragReleases(view: View)
}
} | kotlin | 20 | 0.658797 | 105 | 34.965116 | 86 | starcoderdata |
<filename>android/app/src/main/java/com/algorand/android/MainViewModel.kt
/*
* Copyright 2019 Algorand, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.algorand.android
import android.content.SharedPreferences
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.algorand.android.core.AccountManager
import com.algorand.android.core.BaseViewModel
import com.algorand.android.database.NodeDao
import com.algorand.android.models.Account
import com.algorand.android.models.AssetInformation
import com.algorand.android.models.AssetStatus
import com.algorand.android.models.DeviceRegistrationRequest
import com.algorand.android.models.DeviceUpdateRequest
import com.algorand.android.models.Result
import com.algorand.android.network.AlgodInterceptor
import com.algorand.android.network.IndexerInterceptor
import com.algorand.android.network.MobileHeaderInterceptor
import com.algorand.android.repository.AccountRepository
import com.algorand.android.repository.AssetRepository
import com.algorand.android.repository.NotificationRepository
import com.algorand.android.repository.TransactionsRepository
import com.algorand.android.utils.AccountCacheManager
import com.algorand.android.utils.AutoLockManager
import com.algorand.android.utils.BlockPollingManager
import com.algorand.android.utils.Event
import com.algorand.android.utils.Resource
import com.algorand.android.utils.analytics.CreationType
import com.algorand.android.utils.analytics.logRegisterEvent
import com.algorand.android.utils.findAllNodes
import com.algorand.android.utils.preference.getNotificationUserId
import com.algorand.android.utils.preference.setNotificationUserId
import com.algorand.android.utils.preference.showGovernanceBanner
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.google.firebase.messaging.FirebaseMessaging
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
@Suppress("LongParameterList")
class MainViewModel @ViewModelInject constructor(
private val autoLockManager: AutoLockManager,
private val sharedPref: SharedPreferences,
private val nodeDao: NodeDao,
private val indexerInterceptor: IndexerInterceptor,
private val mobileHeaderInterceptor: MobileHeaderInterceptor,
private val algodInterceptor: AlgodInterceptor,
private val accountManager: AccountManager,
private val notificationRepository: NotificationRepository,
private val accountRepository: AccountRepository,
private val assetRepository: AssetRepository,
private val transactionRepository: TransactionsRepository,
private val accountCacheManager: AccountCacheManager,
private val firebaseAnalytics: FirebaseAnalytics
) : BaseViewModel() {
private val blockChainManager = BlockPollingManager(viewModelScope, transactionRepository)
val addAssetResultLiveData = MutableLiveData<Event<Resource<Unit>>>()
// TODO I'll change after checking usage of flow in activity.
val accountBalanceSyncStatus = accountCacheManager.getCacheStatusFlow().asLiveData()
val blockConnectionStableFlow = blockChainManager.blockConnectionStableFlow
val lastBlockNumberSharedFlow = blockChainManager.lastBlockNumberSharedFlow
val autoLockLiveData
get() = autoLockManager.autoLockLiveData
private var sendTransactionJob: Job? = null
var refreshBalanceJob: Job? = null
var verifiedAssetJob: Job? = null
var registerDeviceJob: Job? = null
init {
setAlgorandGovernanceBannerAsVisible()
initializeAccountBalanceRefresher()
initializeNodeInterceptor()
registerDevice()
getVerifiedAssets()
}
private fun setAlgorandGovernanceBannerAsVisible() {
sharedPref.showGovernanceBanner()
}
private fun initializeAccountBalanceRefresher() {
viewModelScope.launch {
blockChainManager.lastBlockNumberSharedFlow.collectLatest { lastBlockNumber ->
if (lastBlockNumber != null) {
refreshAccountBalances()
}
}
}
}
private fun initializeNodeInterceptor() {
viewModelScope.launch(Dispatchers.IO) {
if (indexerInterceptor.currentActiveNode == null) {
val lastActivatedNode = findAllNodes(sharedPref, nodeDao).find { it.isActive }
lastActivatedNode?.activate(indexerInterceptor, mobileHeaderInterceptor, algodInterceptor)
}
}
}
fun registerDevice() {
FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
accountManager.setFirebaseToken(token, false)
val accountsPublicKeys = accountManager.getAccounts().map { account -> account.address }
registerDeviceJob?.cancel()
registerDeviceJob = viewModelScope.launch(Dispatchers.IO) {
sendRegisterDevice(token, accountsPublicKeys)
}
}
}
private suspend fun sendRegisterDevice(firebaseMessagingToken: String, accountPublicKeys: List<String>) {
if (firebaseMessagingToken.isBlank()) {
val exception = Exception("firebase messaging token is empty\naccounts: $accountPublicKeys")
FirebaseCrashlytics.getInstance().recordException(exception)
}
with(sharedPref.getNotificationUserId()) {
if (!this.isNullOrEmpty()) {
updateDeviceRegistration(this, firebaseMessagingToken, accountPublicKeys)
} else {
registerDevice(firebaseMessagingToken, accountPublicKeys)
}
}
}
private suspend fun updateDeviceRegistration(
notificationUserId: String,
firebaseMessagingToken: String,
accountPublicKeys: List<String>
) {
notificationRepository.putRequestUpdateDevice(
notificationUserId, DeviceUpdateRequest(notificationUserId, firebaseMessagingToken, accountPublicKeys)
).use(
onSuccess = { deviceUpdateResponse ->
if (deviceUpdateResponse.userId != null) {
sharedPref.setNotificationUserId(deviceUpdateResponse.userId)
}
},
onFailed = {
delay(REGISTER_DEVICE_FAIL_DELAY)
updateDeviceRegistration(notificationUserId, firebaseMessagingToken, accountPublicKeys)
}
)
}
private suspend fun registerDevice(firebaseMessagingToken: String, accountPublicKeys: List<String>) {
notificationRepository.postRequestRegisterDevice(
DeviceRegistrationRequest(firebaseMessagingToken, accountPublicKeys)
).use(
onSuccess = { deviceRegistrationResponse ->
if (deviceRegistrationResponse.userId != null) {
sharedPref.setNotificationUserId(deviceRegistrationResponse.userId)
}
},
onFailed = {
delay(REGISTER_DEVICE_FAIL_DELAY)
registerDevice(firebaseMessagingToken, accountPublicKeys)
}
)
}
fun resetBlockPolling() {
refreshBalanceJob?.cancel()
blockChainManager.start()
}
fun activateBlockPolling() {
blockChainManager.start()
}
fun stopBlockPolling() {
blockChainManager.stop()
}
fun refreshAccountBalances() {
if (refreshBalanceJob?.isActive == true) {
return
}
refreshBalanceJob = viewModelScope.launch(Dispatchers.IO) {
verifiedAssetJob?.join()
accountManager.getAccounts().forEach {
accountRepository.getAuthAccountInformation(it)
}
}
}
fun getVerifiedAssets() {
verifiedAssetJob?.cancel()
verifiedAssetJob = viewModelScope.launch(Dispatchers.IO) {
when (val result = assetRepository.getVerifiedAssetList()) {
is Result.Success -> {
accountCacheManager.setVerifiedAssetList(result.data.results)
}
}
}
}
fun sendSignedTransaction(
signedTransactionData: ByteArray,
assetInformation: AssetInformation,
accountPublicKey: String
) {
if (sendTransactionJob?.isActive == true) {
return
}
sendTransactionJob = viewModelScope.launch(Dispatchers.IO) {
when (transactionRepository.sendSignedTransaction(signedTransactionData)) {
is Result.Success -> {
accountCacheManager.addAssetToAccount(accountPublicKey, assetInformation.apply {
assetStatus = AssetStatus.PENDING_FOR_ADDITION
})
addAssetResultLiveData.postValue(Event(Resource.Success(Unit)))
}
}
}
}
fun addAccount(tempAccount: Account?, creationType: CreationType?): Boolean {
if (tempAccount != null) {
if (tempAccount.isRegistrationCompleted()) {
firebaseAnalytics.logRegisterEvent(creationType)
accountManager.addNewAccount(tempAccount)
if (accountManager.getAccounts().size == 1) {
activateBlockPolling()
}
return true
}
}
return false
}
fun setupAutoLockManager(lifecycle: Lifecycle) {
autoLockManager.registerAppLifecycle(lifecycle)
}
companion object {
private const val REGISTER_DEVICE_FAIL_DELAY = 1500L
}
}
| kotlin | 28 | 0.703223 | 114 | 37.984906 | 265 | starcoderdata |
package eece513.client
import java.io.PrintStream
/**
* This class processes [GrepClient.Server.Response]'s and prints them
* to the given [out] and [err] PrintStream's. Instances of this class
* can be used to print results out to the console.
*/
class PrintStreamPresenter(
private val out: PrintStream, private val err: PrintStream
) : GrepClient.Presenter {
override fun displayResponse(response: GrepClient.Server.Response) {
when (response) {
is GrepClient.Server.Response.Result -> printStdOut(response)
is GrepClient.Server.Response.Error -> printStdErr(response)
}
}
override fun displayHelp(msg: String) = err.println(msg)
private fun printStdOut(response: GrepClient.Server.Response.Result) {
for (line in response.result) {
out.println("${response.name}:$line")
}
}
private fun printStdErr(response: GrepClient.Server.Response.Error) {
for (line in response.result) {
err.println("${response.name}:$line")
}
}
} | kotlin | 17 | 0.667293 | 74 | 31.272727 | 33 | starcoderdata |
package codegen.controlflow.for_loops_lowering.test6
import kotlin.test.*
@Test fun runTest() {
val rng = 'a' .. 'z'
for (c in rng) {
if (c in 'k' downTo 'e') {
println(c)
}
}
}
| kotlin | 14 | 0.537736 | 52 | 16.666667 | 12 | starcoderdata |
<reponame>windmaomao/adventofcode
package org.adventofcode
import org.junit.Assert.assertEquals
import org.junit.Test
class Day03Test {
private val d = Day03()
val line = parseFile("03").first()
@Test fun day03Part1Example() {
assertEquals(2, d.part1(">"))
assertEquals(4, d.part1("^>v<"))
assertEquals(2, d.part1("^v^v^v^v^v"))
}
@Test fun day03Part2Example() {
assertEquals(3, d.part2("^v"))
assertEquals(3, d.part2("^>v<"))
assertEquals(11, d.part2("^v^v^v^v^v"))
}
@Test fun day03Part1() {
assertEquals(2572, d.part1(line))
}
@Test fun day03Part2() {
assertEquals(2631, d.part2(line))
}
}
| kotlin | 14 | 0.640553 | 43 | 20.7 | 30 | starcoderdata |
package com.jetbrains.edu.learning.yaml.errorHandling
import com.intellij.CommonBundle
import com.intellij.notification.Notification
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.edu.learning.courseDir
import com.jetbrains.edu.learning.courseFormat.CourseMode
import com.jetbrains.edu.learning.document
import com.jetbrains.edu.learning.messages.EduCoreBundle
import com.jetbrains.edu.learning.yaml.YamlDeserializer
import com.jetbrains.edu.learning.yaml.YamlFormatSettings.COURSE_CONFIG
import javax.swing.event.HyperlinkEvent
class InvalidConfigNotification(project: Project, configFile: VirtualFile, cause: String) :
Notification("EduTools",
EduCoreBundle.message("yaml.invalid.config.notification.title"),
messageWithEditLink(project, configFile, cause),
NotificationType.ERROR) {
init {
setListener(GoToFileListener(project, configFile))
}
}
private fun messageWithEditLink(project: Project, configFile: VirtualFile, cause: String): String {
val courseConfig = if (configFile.name == COURSE_CONFIG) {
configFile
}
else {
project.courseDir.findChild(COURSE_CONFIG)
} ?: error(EduCoreBundle.message("yaml.editor.invalid.format.cannot.find.config"))
val mode = YamlDeserializer.getCourseMode(courseConfig.document.text)
val mainErrorMessage = "${
EduCoreBundle.message("yaml.invalid.config.notification.message", pathToConfig(project, configFile))
}: ${cause.decapitalize()}"
val editLink = if (mode == CourseMode.STUDENT) {
""
}
else {
"""<br>
<a href="">${
CommonBundle.message("button.edit")
}</a>"""
}
return mainErrorMessage + editLink
}
private fun pathToConfig(project: Project, configFile: VirtualFile): String =
FileUtil.getRelativePath(project.courseDir.path, configFile.path, VfsUtil.VFS_SEPARATOR_CHAR) ?: error(
EduCoreBundle.message("yaml.editor.invalid.format.path.not.found", configFile))
private class GoToFileListener(val project: Project, val file: VirtualFile) : NotificationListener {
override fun hyperlinkUpdate(notification: Notification, event: HyperlinkEvent) {
FileEditorManager.getInstance(project).openFile(file, true)
}
}
| kotlin | 15 | 0.76868 | 105 | 37.707692 | 65 | starcoderdata |
<filename>android/src/main/kotlin/com/builttoroam/devicecalendar/DeviceCalendarPlugin.kt
package com.builttoroam.devicecalendar
import android.app.Activity
import android.content.Context
import androidx.annotation.NonNull
import com.builttoroam.devicecalendar.common.Constants
import com.builttoroam.devicecalendar.common.DayOfWeek
import com.builttoroam.devicecalendar.common.RecurrenceFrequency
import com.builttoroam.devicecalendar.models.*
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
const val CHANNEL_NAME = "plugins.builttoroam.com/device_calendar"
class DeviceCalendarPlugin() : FlutterPlugin, MethodCallHandler, ActivityAware {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel: MethodChannel
private var context: Context? = null
private var activity: Activity? = null
// Methods
private val REQUEST_PERMISSIONS_METHOD = "requestPermissions"
private val HAS_PERMISSIONS_METHOD = "hasPermissions"
private val RETRIEVE_CALENDARS_METHOD = "retrieveCalendars"
private val RETRIEVE_EVENTS_METHOD = "retrieveEvents"
private val DELETE_EVENT_METHOD = "deleteEvent"
private val DELETE_EVENT_INSTANCE_METHOD = "deleteEventInstance"
private val CREATE_OR_UPDATE_EVENT_METHOD = "createOrUpdateEvent"
private val CREATE_CALENDAR_METHOD = "createCalendar"
private val DELETE_CALENDAR_METHOD = "deleteCalendar"
// Method arguments
private val CALENDAR_ID_ARGUMENT = "calendarId"
private val CALENDAR_NAME_ARGUMENT = "calendarName"
private val START_DATE_ARGUMENT = "startDate"
private val END_DATE_ARGUMENT = "endDate"
private val EVENT_IDS_ARGUMENT = "eventIds"
private val EVENT_ID_ARGUMENT = "eventId"
private val EVENT_TITLE_ARGUMENT = "eventTitle"
private val EVENT_LOCATION_ARGUMENT = "eventLocation"
private val EVENT_URL_ARGUMENT = "eventURL"
private val EVENT_DESCRIPTION_ARGUMENT = "eventDescription"
private val EVENT_ALL_DAY_ARGUMENT = "eventAllDay"
private val EVENT_START_DATE_ARGUMENT = "eventStartDate"
private val EVENT_END_DATE_ARGUMENT = "eventEndDate"
private val EVENT_START_TIMEZONE_ARGUMENT = "eventStartTimeZone"
private val EVENT_END_TIMEZONE_ARGUMENT = "eventEndTimeZone"
private val RECURRENCE_RULE_ARGUMENT = "recurrenceRule"
private val RECURRENCE_FREQUENCY_ARGUMENT = "recurrenceFrequency"
private val TOTAL_OCCURRENCES_ARGUMENT = "totalOccurrences"
private val INTERVAL_ARGUMENT = "interval"
private val DAYS_OF_WEEK_ARGUMENT = "daysOfWeek"
private val DAY_OF_MONTH_ARGUMENT = "dayOfMonth"
private val MONTH_OF_YEAR_ARGUMENT = "monthOfYear"
private val WEEK_OF_MONTH_ARGUMENT = "weekOfMonth"
private val ATTENDEES_ARGUMENT = "attendees"
private val EMAIL_ADDRESS_ARGUMENT = "emailAddress"
private val NAME_ARGUMENT = "name"
private val ROLE_ARGUMENT = "role"
private val REMINDERS_ARGUMENT = "reminders"
private val MINUTES_ARGUMENT = "minutes"
private val FOLLOWING_INSTANCES = "followingInstances"
private val CALENDAR_COLOR_ARGUMENT = "calendarColor"
private val LOCAL_ACCOUNT_NAME_ARGUMENT = "localAccountName"
private val EVENT_AVAILABILITY_ARGUMENT = "availability"
private lateinit var _calendarDelegate: CalendarDelegate
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
context = flutterPluginBinding.applicationContext
channel = MethodChannel(flutterPluginBinding.binaryMessenger, CHANNEL_NAME)
channel.setMethodCallHandler(this)
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
_calendarDelegate = CalendarDelegate(binding, context!!)
binding.addRequestPermissionsResultListener(_calendarDelegate)
}
override fun onDetachedFromActivityForConfigChanges() {
activity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
activity = binding.activity
_calendarDelegate = CalendarDelegate(binding, context!!)
binding.addRequestPermissionsResultListener(_calendarDelegate)
}
override fun onDetachedFromActivity() {
activity = null
}
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
REQUEST_PERMISSIONS_METHOD -> {
_calendarDelegate.requestPermissions(result)
}
HAS_PERMISSIONS_METHOD -> {
_calendarDelegate.hasPermissions(result)
}
RETRIEVE_CALENDARS_METHOD -> {
_calendarDelegate.retrieveCalendars(result)
}
RETRIEVE_EVENTS_METHOD -> {
val calendarId = call.argument<String>(CALENDAR_ID_ARGUMENT)
val startDate = call.argument<Long>(START_DATE_ARGUMENT)
val endDate = call.argument<Long>(END_DATE_ARGUMENT)
val eventIds = call.argument<List<String>>(EVENT_IDS_ARGUMENT) ?: listOf()
_calendarDelegate.retrieveEvents(calendarId!!, startDate, endDate, eventIds, result)
}
CREATE_OR_UPDATE_EVENT_METHOD -> {
val calendarId = call.argument<String>(CALENDAR_ID_ARGUMENT)
val event = parseEventArgs(call, calendarId)
_calendarDelegate.createOrUpdateEvent(calendarId!!, event, result)
}
DELETE_EVENT_METHOD -> {
val calendarId = call.argument<String>(CALENDAR_ID_ARGUMENT)
val eventId = call.argument<String>(EVENT_ID_ARGUMENT)
_calendarDelegate.deleteEvent(calendarId!!, eventId!!, result)
}
DELETE_EVENT_INSTANCE_METHOD -> {
val calendarId = call.argument<String>(CALENDAR_ID_ARGUMENT)
val eventId = call.argument<String>(EVENT_ID_ARGUMENT)
val startDate = call.argument<Long>(EVENT_START_DATE_ARGUMENT)
val endDate = call.argument<Long>(EVENT_END_DATE_ARGUMENT)
val followingInstances = call.argument<Boolean>(FOLLOWING_INSTANCES)
_calendarDelegate.deleteEvent(calendarId!!, eventId!!, result, startDate, endDate, followingInstances)
}
CREATE_CALENDAR_METHOD -> {
val calendarName = call.argument<String>(CALENDAR_NAME_ARGUMENT)
val calendarColor = call.argument<String>(CALENDAR_COLOR_ARGUMENT)
val localAccountName = call.argument<String>(LOCAL_ACCOUNT_NAME_ARGUMENT)
_calendarDelegate.createCalendar(calendarName!!, calendarColor, localAccountName!!, result)
}
DELETE_CALENDAR_METHOD -> {
val calendarId = call.argument<String>(CALENDAR_ID_ARGUMENT)
_calendarDelegate.deleteCalendar(calendarId!!,result)
}
else -> {
result.notImplemented()
}
}
}
private fun parseEventArgs(call: MethodCall, calendarId: String?): Event {
val event = Event()
event.title = call.argument<String>(EVENT_TITLE_ARGUMENT)
event.calendarId = calendarId
event.eventId = call.argument<String>(EVENT_ID_ARGUMENT)
event.description = call.argument<String>(EVENT_DESCRIPTION_ARGUMENT)
event.allDay = call.argument<Boolean>(EVENT_ALL_DAY_ARGUMENT) ?: false
event.start = call.argument<Long>(EVENT_START_DATE_ARGUMENT)!!
event.end = call.argument<Long>(EVENT_END_DATE_ARGUMENT)!!
event.startTimeZone = call.argument<String>(EVENT_START_TIMEZONE_ARGUMENT)
event.endTimeZone = call.argument<String>(EVENT_END_TIMEZONE_ARGUMENT)
event.location = call.argument<String>(EVENT_LOCATION_ARGUMENT)
event.url = call.argument<String>(EVENT_URL_ARGUMENT)
event.availability = parseAvailability(call.argument<String>(EVENT_AVAILABILITY_ARGUMENT))
if (call.hasArgument(RECURRENCE_RULE_ARGUMENT) && call.argument<Map<String, Any>>(RECURRENCE_RULE_ARGUMENT) != null) {
val recurrenceRule = parseRecurrenceRuleArgs(call)
event.recurrenceRule = recurrenceRule
}
if (call.hasArgument(ATTENDEES_ARGUMENT) && call.argument<List<Map<String, Any>>>(ATTENDEES_ARGUMENT) != null) {
event.attendees = mutableListOf()
val attendeesArgs = call.argument<List<Map<String, Any>>>(ATTENDEES_ARGUMENT)!!
for (attendeeArgs in attendeesArgs) {
event.attendees.add(Attendee(
attendeeArgs[EMAIL_ADDRESS_ARGUMENT] as String,
attendeeArgs[NAME_ARGUMENT] as String?,
attendeeArgs[ROLE_ARGUMENT] as Int,
null, null))
}
}
if (call.hasArgument(REMINDERS_ARGUMENT) && call.argument<List<Map<String, Any>>>(REMINDERS_ARGUMENT) != null) {
event.reminders = mutableListOf()
val remindersArgs = call.argument<List<Map<String, Any>>>(REMINDERS_ARGUMENT)!!
for (reminderArgs in remindersArgs) {
event.reminders.add(Reminder(reminderArgs[MINUTES_ARGUMENT] as Int))
}
}
return event
}
private fun parseRecurrenceRuleArgs(call: MethodCall): RecurrenceRule {
val recurrenceRuleArgs = call.argument<Map<String, Any>>(RECURRENCE_RULE_ARGUMENT)!!
val recurrenceFrequencyIndex = recurrenceRuleArgs[RECURRENCE_FREQUENCY_ARGUMENT] as Int
val recurrenceRule = RecurrenceRule(RecurrenceFrequency.values()[recurrenceFrequencyIndex])
if (recurrenceRuleArgs.containsKey(TOTAL_OCCURRENCES_ARGUMENT)) {
recurrenceRule.totalOccurrences = recurrenceRuleArgs[TOTAL_OCCURRENCES_ARGUMENT] as Int
}
if (recurrenceRuleArgs.containsKey(INTERVAL_ARGUMENT)) {
recurrenceRule.interval = recurrenceRuleArgs[INTERVAL_ARGUMENT] as Int
}
if (recurrenceRuleArgs.containsKey(END_DATE_ARGUMENT)) {
recurrenceRule.endDate = recurrenceRuleArgs[END_DATE_ARGUMENT] as Long
}
if (recurrenceRuleArgs.containsKey(DAYS_OF_WEEK_ARGUMENT)) {
recurrenceRule.daysOfWeek = recurrenceRuleArgs[DAYS_OF_WEEK_ARGUMENT].toListOf<Int>()?.map { DayOfWeek.values()[it] }?.toMutableList()
}
if (recurrenceRuleArgs.containsKey(DAY_OF_MONTH_ARGUMENT)) {
recurrenceRule.dayOfMonth = recurrenceRuleArgs[DAY_OF_MONTH_ARGUMENT] as Int
}
if (recurrenceRuleArgs.containsKey(MONTH_OF_YEAR_ARGUMENT)) {
recurrenceRule.monthOfYear = recurrenceRuleArgs[MONTH_OF_YEAR_ARGUMENT] as Int
}
if (recurrenceRuleArgs.containsKey(WEEK_OF_MONTH_ARGUMENT)) {
recurrenceRule.weekOfMonth = recurrenceRuleArgs[WEEK_OF_MONTH_ARGUMENT] as Int
}
return recurrenceRule
}
private inline fun <reified T : Any> Any?.toListOf(): List<T>? {
return (this as List<*>?)?.filterIsInstance<T>()?.toList()
}
private inline fun <reified T : Any> Any?.toMutableListOf(): MutableList<T>? {
return this?.toListOf<T>()?.toMutableList()
}
private fun parseAvailability(value: String?): Availability? =
if (value == null || value == Constants.AVAILABILITY_UNAVAILABLE) {
null
} else {
Availability.valueOf(value)
}
}
| kotlin | 23 | 0.684833 | 146 | 46.224806 | 258 | starcoderdata |
package com.expediagroup.graphql.generated.unionquerywithnamedfragments
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.annotation.JsonTypeInfo.As.PROPERTY
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id.NAME
import kotlin.Int
import kotlin.String
/**
* Very basic union of BasicObject and ComplexObject
*/
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "__typename"
)
@JsonSubTypes(value = [com.fasterxml.jackson.annotation.JsonSubTypes.Type(value =
BasicObject::class, name="BasicObject"),com.fasterxml.jackson.annotation.JsonSubTypes.Type(value
= ComplexObject::class, name="ComplexObject")])
interface BasicUnion
/**
* Some basic description
*/
data class BasicObject(
val id: Int,
/**
* Object name
*/
val name: String
) : BasicUnion
/**
* Multi line description of a complex type.
* This is a second line of the paragraph.
* This is final line of the description.
*/
data class ComplexObject(
/**
* Some unique identifier
*/
val id: Int,
/**
* Some object name
*/
val name: String,
/**
* Optional value
* Second line of the description
*/
val optional: String?
) : BasicUnion
| kotlin | 15 | 0.732765 | 100 | 23.358491 | 53 | starcoderdata |
package chat.sphinx.splash.ui
import androidx.constraintlayout.motion.widget.MotionLayout
import chat.sphinx.splash.R
import io.matthewnelson.android_concept_views.MotionLayoutViewState
import java.io.CharArrayWriter
@Suppress("ClassName")
internal sealed class SplashViewState: MotionLayoutViewState<SplashViewState>() {
object HideLoadingWheel: SplashViewState() {
override val startSetId: Int
get() = R.id.motion_scene_splash_set1
override val endSetId: Int
get() = R.id.motion_scene_splash_set2
}
object Start_ShowIcon: SplashViewState() {
override val startSetId: Int
get() = R.id.motion_scene_splash_set1
override val endSetId: Int
get() = R.id.motion_scene_splash_set2
override fun restoreMotionScene(motionLayout: MotionLayout) {}
override fun transitionToEndSet(motionLayout: MotionLayout) {}
}
object Transition_Set2_ShowWelcome: SplashViewState() {
override val startSetId: Int
get() = R.id.motion_scene_splash_set1
override val endSetId: Int
get() = R.id.motion_scene_splash_set2
}
object Set2_ShowWelcome: SplashViewState() {
override val startSetId: Int
get() = R.id.motion_scene_splash_set2
override val endSetId: Int?
get() = null
override fun restoreMotionScene(motionLayout: MotionLayout) {
motionLayout.setTransition(R.id.transition_splash_set1_to_set2)
motionLayout.setProgress(1F, 1F)
}
}
class Transition_Set3_DecryptKeys(val toDecrypt: ByteArray): SplashViewState() {
companion object {
val START_SET_ID: Int
get() = R.id.motion_scene_splash_set2
val END_SET_ID: Int
get() = R.id.motion_scene_splash_set3
}
override val startSetId: Int
get() = START_SET_ID
override val endSetId: Int
get() = END_SET_ID
}
class Set3_DecryptKeys(
val toDecrypt: ByteArray,
var inputLock: Boolean = false,
val pinWriter: CharArrayWriter = CharArrayWriter(6)
): SplashViewState() {
companion object {
val START_SET_ID: Int
get() = R.id.motion_scene_splash_set3
val END_SET_ID: Int
get() = R.id.motion_scene_splash_set2
}
override val startSetId: Int
get() = START_SET_ID
override val endSetId: Int
get() = END_SET_ID
override fun restoreMotionScene(motionLayout: MotionLayout) {
motionLayout.setTransition(R.id.transition_splash_set2_to_set3)
motionLayout.setProgress(1F, 1F)
}
}
} | kotlin | 15 | 0.621053 | 84 | 31.423529 | 85 | starcoderdata |
<reponame>AjiRespati/android-starter
package com.utek.android.utekapp.homeguest
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.utek.android.utekapp.databinding.AppmemberViewItemBinding
import com.utek.android.utekapp.network.AppMember
class MemberItemAdapter(val onClickListener: OnClickListener) :
ListAdapter<AppMember, MemberItemAdapter.AppMemberViewHolder>(DiffCallback) {
class AppMemberViewHolder(private var binding: AppmemberViewItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(appMember: AppMember) {
binding.appMember = appMember
// This is important, because it forces the data binding to execute immediately,
// which allows the RecyclerView to make the correct view size measurements
binding.executePendingBindings()
}
}
companion object DiffCallback : DiffUtil.ItemCallback<AppMember>() {
override fun areItemsTheSame(oldItem: AppMember, newItem: AppMember): Boolean {
return oldItem === newItem
}
override fun areContentsTheSame(oldItem: AppMember, newItem: AppMember): Boolean {
return oldItem.id == newItem.id
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppMemberViewHolder {
return AppMemberViewHolder(AppmemberViewItemBinding.inflate(LayoutInflater.from(parent.context)))
}
override fun onBindViewHolder(holder: AppMemberViewHolder, position: Int) {
val appMember = getItem(position)
holder.itemView.setOnClickListener {
onClickListener.onClick(appMember)
}
holder.bind(appMember)
}
class OnClickListener(val clickListener: (appMember: AppMember) -> Unit) {
fun onClick(appMember: AppMember) = clickListener(appMember)
}
} | kotlin | 21 | 0.730095 | 105 | 36.698113 | 53 | starcoderdata |
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
@file:OptIn(ExperimentalTime::class)
@file:Suppress("StringLiteralDuplication")
package com.kotlindiscord.kord.extensions.modules.extra.phishing
import com.kotlindiscord.kord.extensions.DISCORD_RED
import com.kotlindiscord.kord.extensions.checks.hasPermission
import com.kotlindiscord.kord.extensions.checks.isNotBot
import com.kotlindiscord.kord.extensions.commands.Arguments
import com.kotlindiscord.kord.extensions.commands.converters.impl.string
import com.kotlindiscord.kord.extensions.extensions.Extension
import com.kotlindiscord.kord.extensions.extensions.ephemeralMessageCommand
import com.kotlindiscord.kord.extensions.extensions.ephemeralSlashCommand
import com.kotlindiscord.kord.extensions.extensions.event
import com.kotlindiscord.kord.extensions.types.respond
import com.kotlindiscord.kord.extensions.utils.dm
import com.kotlindiscord.kord.extensions.utils.getJumpUrl
import dev.kord.core.behavior.ban
import dev.kord.core.behavior.channel.createMessage
import dev.kord.core.entity.Message
import dev.kord.core.entity.channel.GuildMessageChannel
import dev.kord.core.event.message.MessageCreateEvent
import dev.kord.core.event.message.MessageUpdateEvent
import dev.kord.rest.builder.message.create.embed
import io.ktor.client.*
import io.ktor.client.features.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.lastOrNull
import kotlinx.coroutines.launch
import mu.KotlinLogging
import org.jsoup.Jsoup
import org.jsoup.UnsupportedMimeTypeException
import kotlin.time.ExperimentalTime
/** The maximum number of redirects to attempt to follow for a URL. **/
const val MAX_REDIRECTS = 5
/** Phishing extension, responsible for checking for phishing domains in messages. **/
class PhishingExtension(private val settings: ExtPhishingBuilder) : Extension() {
override val name = "phishing"
private val api = PhishingApi(settings.appName)
private val domainCache: MutableSet<String> = mutableSetOf()
private val logger = KotlinLogging.logger { }
private var websocket: PhishingWebsocketWrapper = api.websocket(::handleChange)
private val httpClient = HttpClient {
followRedirects = false
}
override suspend fun setup() {
websocket.stop()
websocket.start()
domainCache.addAll(api.getAllDomains())
event<MessageCreateEvent> {
check { isNotBot() }
check { event.message.author != null }
check { event.guildId != null }
check {
settings.checks.forEach {
if (passed) it()
}
}
action {
handleMessage(event.message)
}
}
event<MessageUpdateEvent> {
check { isNotBot() }
check { event.new.author.value != null }
check { event.new.guildId.value != null }
check {
settings.checks.forEach {
if (passed) it()
}
}
action {
handleMessage(event.message.asMessage())
}
}
ephemeralMessageCommand {
name = "Phishing Check"
if (this@PhishingExtension.settings.requiredCommandPermission != null) {
check { hasPermission(this@PhishingExtension.settings.requiredCommandPermission!!) }
}
action {
for (message in targetMessages) {
val matches = parseDomains(message.content)
respond {
content = if (matches.isNotEmpty()) {
"⚠️ [Message ${message.id.value}](${message.getJumpUrl()}) " +
"**contains ${matches.size} phishing link/s**."
} else {
"✅ [Message ${message.id.value}](${message.getJumpUrl()}) " +
"**does not contain any phishing links**."
}
}
}
}
}
ephemeralSlashCommand(::DomainArgs) {
name = "phishing-check"
description = "Check whether a given domain is a known phishing domain."
if (<EMAIL> != null) {
check { hasPermission(this<EMAIL>.settings.requiredCommandPermission!!) }
}
action {
respond {
content = if (domainCache.contains(arguments.domain.lowercase())) {
"⚠️ `${arguments.domain}` is a known phishing domain."
} else {
"✅ `${arguments.domain}` is not a known phishing domain."
}
}
}
}
}
internal suspend fun handleMessage(message: Message) {
val matches = parseDomains(message.content)
if (matches.isNotEmpty()) {
logger.debug { "Found a message with ${matches.size} phishing domains." }
if (settings.notifyUser) {
message.kord.launch {
message.author!!.dm {
content = "We've detected that the following message contains a phishing domain. For this " +
"reason, **${settings.detectionAction.message}**."
embed {
title = "Phishing domain detected"
description = message.content
color = DISCORD_RED
field {
inline = true
name = "Channel"
value = message.channel.mention
}
field {
inline = true
name = "Message ID"
value = "`${message.id.value}`"
}
field {
inline = true
name = "Server"
value = message.getGuild().name
}
}
}
}
}
when (settings.detectionAction) {
DetectionAction.Ban -> {
message.getAuthorAsMember()!!.ban {
reason = "Message contained a phishing domain"
}
message.delete("Message contained a phishing domain")
}
DetectionAction.Delete -> message.delete("Message contained a phishing domain")
DetectionAction.Kick -> {
message.getAuthorAsMember()!!.kick("Message contained a phishing domain")
message.delete("Message contained a phishing domain")
}
DetectionAction.LogOnly -> {
// Do nothing, we always log
}
}
logDeletion(message, matches)
}
}
internal suspend fun logDeletion(message: Message, matches: Set<String>) {
val guild = message.getGuild()
val channel = message
.getGuild()
.channels
.filter { it.name == settings.logChannelName }
.lastOrNull()
?.asChannelOrNull() as? GuildMessageChannel
if (channel == null) {
logger.warn {
"Unable to find a channel named ${settings.logChannelName} on ${guild.name} (${guild.id.value})"
}
return
}
val matchList = "# Phishing Domain Matches\n\n" +
"**Total:** ${matches.size}\n\n" +
matches.joinToString("\n") { "* `$it`" }
channel.createMessage {
addFile("matches.md", matchList.byteInputStream())
embed {
title = "Phishing domain detected"
description = message.content
color = DISCORD_RED
field {
inline = true
name = "Author"
value = "${message.author!!.mention} (" +
"`${message.author!!.tag}` / " +
"`${message.author!!.id.value}`" +
")"
}
field {
inline = true
name = "Channel"
value = "${message.channel.mention} (`${message.channelId.value}`)"
}
field {
inline = true
name = "Message"
value = "[`${message.id.value}`](${message.getJumpUrl()})"
}
field {
inline = true
name = "Total Matches"
value = matches.size.toString()
}
}
}
}
internal suspend fun parseDomains(content: String): MutableSet<String> {
val domains: MutableSet<String> = mutableSetOf()
for (match in settings.urlRegex.findAll(content)) {
val found = match.groups[1]!!.value.trim('/')
var domain = found
if ("/" in domain) {
domain = domain
.split("/", limit = 2)
.first()
.lowercase()
}
domain = domain.filter { it.isLetterOrDigit() || it in "-+&@#%?=~_|!:,.;" }
if (domain in domainCache) {
domains.add(domain)
} else {
val result = followRedirects(match.value)
?.split("://")
?.lastOrNull()
?.split("/")
?.first()
?.lowercase()
if (result in domainCache) {
domains.add(result!!)
}
}
}
logger.debug { "Found ${domains.size} domains: ${domains.joinToString()}" }
return domains
}
@Suppress("MagicNumber") // HTTP status codes
internal suspend fun followRedirects(url: String, count: Int = 0): String? {
if (count >= MAX_REDIRECTS) {
logger.warn { "Maximum redirect count reached for URL: $url" }
return url
}
val response: HttpResponse = try {
httpClient.get(url)
} catch (e: RedirectResponseException) {
e.response
} catch (e: ClientRequestException) {
val status = e.response.status
if (status.value !in 200 until 499) {
logger.warn { "$url -> $status" }
}
return url
}
if (response.headers.contains("Location")) {
val newUrl = response.headers["Location"]!!
if (url.trim('/') == newUrl.trim('/')) {
return null // Results in the same URL
}
return followRedirects(newUrl, count + 1)
} else {
val soup = try {
Jsoup.connect(url).get()
} catch (e: UnsupportedMimeTypeException) {
logger.debug { "$url -> Unsupported MIME type; not parsing" }
return url
}
val element = soup.head()
.getElementsByAttributeValue("http-equiv", "refresh")
.first()
if (element != null) {
val content = element.attributes().get("content")
val newUrl = content
.split(";")
.firstOrNull { it.startsWith("URL=", true) }
?.split("=", limit = 2)
?.lastOrNull()
if (newUrl != null) {
if (url.trim('/') == newUrl.trim('/')) {
return null // Results in the same URL
}
return followRedirects(newUrl, count + 1)
}
}
}
return url
}
override suspend fun unload() {
websocket.stop()
}
internal fun handleChange(change: DomainChange) {
when (change.type) {
DomainChangeType.Add -> domainCache.addAll(change.domains)
DomainChangeType.Delete -> domainCache.removeAll(change.domains)
}
}
/** Arguments class for domain-relevant commands. **/
inner class DomainArgs : Arguments() {
/** Targeted domain string. **/
val domain by string {
name = "domain"
description = "Domain to check"
validate {
failIf("Please provide the domain name only, without the protocol or a path.") { "/" in value }
}
}
}
}
| kotlin | 38 | 0.506212 | 117 | 31.962312 | 398 | starcoderdata |
package com.example.hades.androidpo._1_render_op.startup.v2
import io.reactivex.ObservableTransformer
interface RxLifeCycleSchedulerBinder : RxLifeCycleBinder {
fun <T> bindWithScheduler(): ObservableTransformer<T, T>?
} | kotlin | 9 | 0.809735 | 61 | 31.428571 | 7 | starcoderdata |
<gh_stars>0
package io.github.pshegger.gamedevexperiments.scenes.menu
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import io.github.pshegger.gamedevexperiments.GameSurfaceView
import io.github.pshegger.gamedevexperiments.Scene
import io.github.pshegger.gamedevexperiments.hud.Button
/**
* @author <EMAIL>
*/
abstract class BaseMenuScene(val gameSurfaceView: GameSurfaceView) : Scene {
private var width: Int = 0
private var height: Int = 0
private val margin = 20f
private var buttons = listOf<Button>()
protected abstract val scenes: List<MenuItem>
protected abstract val title: String
private val titlePaint = Paint().apply {
textSize = 96f
isAntiAlias = true
textAlign = Paint.Align.CENTER
color = Color.DKGRAY
}
override fun sizeChanged(width: Int, height: Int) {
this.width = width
this.height = height
val textS = 80f
val textPaint = Paint().apply {
textSize = textS
textAlign = Paint.Align.CENTER
}
val textHeight = -(textPaint.descent() + textPaint.ascent())
val rectHeight = textHeight * 2.5f
val titleTextHeight = -(titlePaint.descent() + titlePaint.ascent())
val titleHeight = titleTextHeight * 1.5f
buttons = scenes.mapIndexed { i, (title, scene) ->
val top = (i + 4) * margin + i * rectHeight + titleHeight
Button(title, margin, top, width - margin, top + rectHeight, Color.GREEN, Color.RED, Color.BLACK, textS).apply {
setOnClickListener { gameSurfaceView.scene = scene }
}
}
}
override fun update(deltaTime: Long) {
buttons.forEach { it.update(deltaTime, gameSurfaceView.touch) }
}
override fun render(canvas: Canvas) {
canvas.drawColor(Color.rgb(154, 206, 235))
canvas.drawText(title, width / 2f, 96f, titlePaint)
buttons.forEach { it.render(canvas) }
}
protected data class MenuItem(val title: String, val scene: Scene)
}
| kotlin | 25 | 0.653423 | 124 | 30.179104 | 67 | starcoderdata |
package com.example.moviedatabase.domain.model
data class MovieVideos(
val id: Int? = 0,
val results: List<MovieVideoResult>? = listOf()
) : Model()
| kotlin | 9 | 0.702532 | 51 | 25.333333 | 6 | starcoderdata |
/*
* Copyright © 2019. <NAME>.
* 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 tech.sirwellington.alchemy.kotlin.extensions
import tech.sirwellington.alchemy.annotations.concurrency.ThreadUnsafe
import java.util.Collections
import java.util.LinkedList
/**
*
* @author SirWellington
*/
/**
* Checks whether [index] is a valid index in `this` [List].
*
* @return `true` if [index] is a valid index in `this`, `false` otherwise.
*/
fun <T> List<T>.isValidIndex(index: Int): Boolean
{
if (index < 0) return false
return index < size
}
/**
* Checks to make sure [index] is not a valid index in this [List].
*
* @return `true` if [index] is an invalid index in `this`, `false` if it a valid index.
*/
fun <T> List<T>.notValidIndex(index: Int) = !isValidIndex(index)
/**
* @return `true` if `this` [Int] is a valid index in [list], false if it is not.
*/
fun <T> Int.isValidIndexIn(list: List<T>): Boolean
{
if (this < 0) return false
return this < list.size
}
/**
* @return true if this [Number][Int] is a valid index in the given [List],
* false otherwise.
*/
fun <T> Int.notValidIndexIn(list: List<T>) = !isValidIndexIn(list)
/**
* @return A shuffled version of this [List].
*/
fun <T> List<T>.shuffled(): List<T>
{
val result = this.toMutableList()
Collections.shuffle(result)
return result
}
/**
* @return The first element of the list, or `null` if the list is empty.
*/
val <T> List<T>?.first: T? get() = this?.firstOrNull()
/**
* @return The second element of the list, or `null` if there isn't a second element.
*/
val <T> List<T>?.second: T? get() = this?.getOrNull(1)
/**
* @return The third element of the list, or `null` if there isn't one.
*/
val <T> List<T>?.third: T? get() = this?.getOrNull(2)
/**
* @return the last element of the list, or `null` if the list is empty.
*/
val <T> List<T>?.last: T? get() = this?.lastOrNull()
/**
*
* @return a random element from the list, null if the list is empty or null.
*/
val <T> List<T>?.anyElement: T?
get()
{
if (this == null) return null
val index = (0..size).random()
return if (index.isValidIndexIn(this)) this[index] else null
}
/**
* Removes all elements from the collection that match the given predicate.
*
* @return `true` if any elements were removed, `false` if none were found to match the predicate.
*/
inline fun <reified T> MutableCollection<T>.removeElementIf(predicate: (T) -> (Boolean)): Boolean
{
val elementsToRemove = this.filter(predicate).toList()
return this.removeAll(elementsToRemove)
}
/**
* Adds an element to be front of a [List].
*/
inline fun <reified T> MutableList<T>.addToFront(element: T)
{
add(0, element)
}
/**
* Simple alias for [addToFront].
*/
inline fun <reified T> MutableList<T>.prepend(element: T)
{
addToFront(element)
}
/**
* @return `true` if [element] is not present in this List, `false` otherwise.
*/
inline fun <reified T> List<T>.doesNotContain(element: T): Boolean = !contains(element)
/**
* An alias for [any] that returns true if any of the elements in this collection
* match the [predicate].
*
* @param predicate Ran on elements in the list to test whether the condition is met or not.
*
* @return `true` If this collection contains an element matching the [predicate], `false` otherwise.
*/
inline fun <reified T> Collection<T>.containsWhere(predicate: (T) -> Boolean): Boolean
{
return this.any(predicate)
}
/**
* A negated form of [containsWhere].
*
* @param predicate Ran on elements in the list to test whether the condition is met or not.
*
* @return `true` If this collection does not contain an element matching the [predicate], `false` if it doesn.
*/
inline fun <reified T> Collection<T>.doesNotContainWhere(predicate: (T) -> Boolean): Boolean
{
return !this.any(predicate)
}
/**
* @param elements The arguments to check for containment.
*
* @return `true` If this Collection contains any of the specified [elements], `false` otherwise.
*/
inline fun <reified T> List<T>.containsAnyOf(vararg elements: T): Boolean
{
return elements.any { this.contains(it) }
}
/**
* Simple alias for [removeElementIf].
*
* @see removeElementIf
*/
inline fun <reified T> MutableCollection<T>.removeWhere(predicate: (T) -> Boolean): Boolean
{
return this.removeElementIf(predicate)
}
/**
* Removes and returns the first element, and then adds it to the back of the list.
* Use this function to turn any list into a circular array.
*
* @return The element currently at the front.
*/
@ThreadUnsafe
inline fun <reified T> MutableList<T>.circulateNext(): T?
{
if (this.isEmpty()) return null
val first = removeAt(0)
add(first)
return first
}
/**
* Creates a list of size [size], using the specified [generator].
*/
fun <E> createListOf(size: Int = 10, generator: () -> E): List<E>
{
when
{
size < 0 -> throw IllegalArgumentException("size must be >= 0")
size == 0 -> return emptyList()
}
return (0 until size).map { generator() }
}
/**
* @return `true` if this collection is `null` or [empty][Collection.isEmpty].
*/
val <E> Collection<E>?.isNullOrEmpty
get() = this == null || this.isEmpty()
/**
* @return `true` if this collection is neither `null` nor [empty][Collection.isEmpty].
*/
val <E> Collection<E>?.notNullOrEmpty
get() = !isNullOrEmpty
/**
* Remove and returns the first element of this list.
*/
fun <E> MutableList<E>.popFirst(): E?
{
return if (this.isEmpty())
{
null
}
else
{
this.removeAt(0)
}
}
/**
* Removes and returns the last element of this list.
*/
fun <E> MutableList<E>.popLast(): E?
{
return if (this.isEmpty())
{
null
}
else
{
this.removeAt(lastIndex)
}
}
//===========================================
// LINKED LIST EXTENSIONS
//===========================================
/**
* Creates a [LinkedList] from [this].
*
* @author SirWellington
*/
fun <E> Collection<E>.toLinkedList(): LinkedList<E>
{
return LinkedList(this)
}
/**
* Removes and returns the first element in the LinkedList, or returns `null` if the list
* is empty.
*/
fun <E> LinkedList<E>.popSafe(): E?
{
return if (isEmpty()) null else pop()
}
/**
* @return `true` if the list is [List.isEmpty], `false` otherwise.
*/
val <E> List<E>.notEmpty get() = this.isNotEmpty()
/**
* Removes and returns the remaining elements in the LinkedList.
* This function essentially returns the list in reverse.
*/
fun <E> LinkedList<E>.popRemaining(collector: (E) -> (Unit))
{
while (notEmpty)
{
val value = popSafe()
if (value != null)
collector(value)
else
return
}
} | kotlin | 14 | 0.648019 | 111 | 23.072607 | 303 | starcoderdata |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
class GHRepositoryPath(val owner: String, val repository: String) {
fun toString(showOwner: Boolean) = if (showOwner) "$owner/$repository" else repository
@NlsSafe
override fun toString() = "$owner/$repository"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GHRepositoryPath) return false
if (!owner.equals(other.owner, true)) return false
if (!repository.equals(other.repository, true)) return false
return true
}
override fun hashCode(): Int {
var result = StringUtil.stringHashCodeInsensitive(owner)
result = 31 * result + StringUtil.stringHashCodeInsensitive(repository)
return result
}
} | kotlin | 14 | 0.737773 | 140 | 32.172414 | 29 | starcoderdata |
package ch.uzh.ifi.seal.smr.soa.analysis.numberofbenchmarks
import com.opencsv.bean.CsvBindByPosition
class ResNumberOfBenchmarks {
@CsvBindByPosition(position = 0)
lateinit var project: String
@CsvBindByPosition(position = 1)
var benchmarks: Int = 0
constructor()
constructor(project: String, benchmarks: Int) {
this.project = project
this.benchmarks = benchmarks
}
} | kotlin | 9 | 0.713942 | 59 | 23.529412 | 17 | starcoderdata |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui
import java.util.*
interface GHLoadingModel {
val loading: Boolean
val resultAvailable: Boolean
val error: Throwable?
fun addStateChangeListener(listener: StateChangeListener)
fun removeStateChangeListener(listener: StateChangeListener)
interface StateChangeListener : EventListener {
fun onLoadingStarted() {}
fun onLoadingCompleted() {}
fun onReset() {
onLoadingCompleted()
}
}
} | kotlin | 11 | 0.756098 | 140 | 27 | 22 | starcoderdata |
<reponame>reginaldosoares/vaadin-kt-template
package eu.regente.demo
import com.vaadin.flow.component.Key
import com.vaadin.flow.component.button.Button
import com.vaadin.flow.component.button.ButtonVariant
import com.vaadin.flow.component.dependency.CssImport
import com.vaadin.flow.component.notification.Notification
import com.vaadin.flow.component.orderedlayout.VerticalLayout
import com.vaadin.flow.component.textfield.TextField
import com.vaadin.flow.router.Route
/**
* The main view contains a button and a click listener.
*/
@Route("")
@CssImport("./styles/shared-styles.css")
@CssImport(value = "./styles/vaadin-text-field-styles.css", themeFor = "vaadin-text-field")
class MainView : VerticalLayout() {
init {
val greetService = GreetService()
val textField = TextField("<NAME>")
// Button click listeners can be defined as lambda expressions
val button =
Button("Say hello!") { Notification.show(greetService.greet(textField.value)) }.apply {
addThemeVariants(ButtonVariant.LUMO_PRIMARY)
addClickShortcut(Key.ENTER)
}
// Use custom CSS classes to apply styling. This is defined in shared-styles.css.
addClassName("centered-content")
add(textField, button)
}
}
| kotlin | 33 | 0.717692 | 99 | 34.135135 | 37 | starcoderdata |
package com.firsttimeinforever.intellij.pdf.viewer.settings
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager.getService
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.util.xmlb.XmlSerializerUtil.copyBean
import com.intellij.util.xmlb.annotations.Transient
@State(name = "PdfViewerSettings", storages = [(Storage("pdf_viewer.xml"))])
class PdfViewerSettings: PersistentStateComponent<PdfViewerSettings> {
var useCustomColors = false
var customBackgroundColor: Int = defaultBackgroundColor.rgb
var customForegroundColor: Int = defaultForegroundColor.rgb
var customIconColor: Int = defaultIconColor.rgb
var enableDocumentAutoReload = true
@Transient
private val changeListenersHolder = mutableListOf<(PdfViewerSettings) -> Unit>()
val changeListeners
get() = changeListenersHolder.toList()
fun addChangeListener(listener: (settings: PdfViewerSettings) -> Unit) {
changeListenersHolder.add(listener)
}
fun removeChangeListener(listener: (settings: PdfViewerSettings) -> Unit) {
changeListenersHolder.remove(listener)
}
override fun getState() = this
override fun loadState(state: PdfViewerSettings) {
copyBean(state, this)
}
companion object {
val instance: PdfViewerSettings
get() = getService(PdfViewerSettings::class.java)
val defaultBackgroundColor
get() = EditorColorsManager.getInstance().globalScheme.defaultBackground
val defaultForegroundColor
get() = EditorColorsManager.getInstance().globalScheme.defaultForeground
val defaultIconColor
get() = defaultForegroundColor
}
}
| kotlin | 13 | 0.749198 | 84 | 34.961538 | 52 | starcoderdata |
<filename>buy-oyc-concert-service/src/main/kotlin/org/jesperancinha/concert/buy/oyc/concert/service/ConcertService.kt
package org.jesperancinha.concert.buy.oyc.concert.service
import io.lettuce.core.RedisClient
import io.lettuce.core.pubsub.RedisPubSubAdapter
import io.lettuce.core.pubsub.api.async.RedisPubSubAsyncCommands
import io.micronaut.context.annotation.Factory
import jakarta.inject.Singleton
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import org.jesperancinha.concert.buy.oyc.commons.domain.BuyOycCodec
import org.jesperancinha.concert.buy.oyc.commons.domain.ConcertDayRepository
import org.jesperancinha.concert.buy.oyc.commons.domain.ConcertDayReservationRepository
import org.jesperancinha.concert.buy.oyc.commons.domain.readTypedObject
import org.jesperancinha.concert.buy.oyc.commons.dto.ConcertDayDto
import org.jesperancinha.concert.buy.oyc.commons.dto.toData
import org.jesperancinha.concert.buy.oyc.commons.dto.toDto
import org.jesperancinha.concert.buy.oyc.commons.pubsub.initPubSub
import java.io.ObjectInputStream
import javax.validation.Valid
/**
* Created by jofisaes on 20/04/2022
*/
private const val CONCERT_CHANNEL = "concertChannel"
@DelicateCoroutinesApi
@Singleton
class ConcertDayService(
private val concertDayRepository: ConcertDayRepository,
private val concertDayReservationRepository: ConcertDayReservationRepository,
redisClient: RedisClient,
private val pubSubCommands: RedisPubSubAsyncCommands<String, ConcertDayDto>,
) {
init {
redisClient.initPubSub(
channelName = CONCERT_CHANNEL,
redisCodec = ConcertDayCodec(),
redisPubSubAdapter = Listener(
concertDayRepository,
concertDayReservationRepository
)
)
}
suspend fun createConcertDayReservation(concertDayDto: @Valid ConcertDayDto?): Unit =
withContext(Dispatchers.Default) {
pubSubCommands.publish(CONCERT_CHANNEL, concertDayDto)
}
fun getAll(): Flow<ConcertDayDto> = concertDayReservationRepository.findAll().map { it.toDto }
}
@Factory
class RedisBeanFactory {
@Singleton
fun pubSubCommands(redisClient: RedisClient): RedisPubSubAsyncCommands<String, ConcertDayDto>? =
redisClient.connectPubSub(ConcertDayCodec()).async()
}
@DelicateCoroutinesApi
class Listener(
private val concertDayRepository: ConcertDayRepository,
private val concertDayReservationRepository: ConcertDayReservationRepository,
) : RedisPubSubAdapter<String, ConcertDayDto>() {
override fun message(key: String, concertDayDto: ConcertDayDto) {
CoroutineScope(Dispatchers.IO).launch {
val concertDayReservation =
concertDayDto.toData(
concertDayRepository.findById(
concertDayDto.concertId ?: throw RuntimeException("Concert not sent!")
) ?: throw RuntimeException("Concert Not found")
)
concertDayReservationRepository.save(concertDayReservation)
}
}
}
class ConcertDayCodec : BuyOycCodec<ConcertDayDto>() {
override fun readCodecObject(it: ObjectInputStream): ConcertDayDto = it.readTypedObject()
}
| kotlin | 27 | 0.755058 | 117 | 37.833333 | 84 | starcoderdata |
package io.sullivanproject.practice02
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mom_radioButton.setOnClickListener {
imageView.setImageResource(R.drawable.mom_image)
textView2.setText("엄마 사랑해요")
}
dad_radioButton.setOnClickListener {
imageView.setImageResource(R.drawable.dad_image)
textView2.setText("아빠 사랑해요")
}
}
}
| kotlin | 18 | 0.697504 | 60 | 29.954545 | 22 | starcoderdata |
<gh_stars>0
package com.wanztudio.kotlin.mvp.ui.splash.presenter
import com.wanztudio.kotlin.mvp.ui.base.presenter.MVPPresenter
import com.wanztudio.kotlin.mvp.ui.splash.interactor.SplashMVPInteractor
import com.wanztudio.kotlin.mvp.ui.splash.view.SplashMVPView
/**
* Created by <NAME> on 23 September 2018
* You can contact me at : <EMAIL>
*/
interface SplashMVPPresenter<V : SplashMVPView, I : SplashMVPInteractor> : MVPPresenter<V,I> | kotlin | 9 | 0.791855 | 92 | 33.076923 | 13 | starcoderdata |
<reponame>pr0-dev/Pr0
package com.pr0gramm.app.ui.views
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.text.style.ImageSpan
import android.util.AttributeSet
import android.widget.TextView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.graphics.toRectF
import androidx.core.text.inSpans
import com.pr0gramm.app.UserClassesService
import com.pr0gramm.app.services.ThemeHelper
import com.pr0gramm.app.ui.BaseDrawable
import com.pr0gramm.app.ui.paint
import com.pr0gramm.app.util.di.injector
import com.pr0gramm.app.util.dp
import com.pr0gramm.app.util.getColorCompat
import kotlinx.coroutines.flow.emptyFlow
/**
*/
class UsernameView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
AppCompatTextView(context, attrs, defStyleAttr) {
init {
maxLines = 1
if (isInEditMode) {
setUsername("Mopsalarm", 1)
}
}
@SuppressLint("SetTextI18n")
fun setUsername(name: String, mark: Int, op: Boolean = false) {
this.text = SpannableStringBuilder().apply {
appendUsernameAndMark(this@UsernameView, name, mark, op)
}
}
}
fun SpannableStringBuilder.appendUsernameAndMark(parent: TextView, name: String, mark: Int, op: Boolean = false) {
val userClassesService: UserClassesService = if (parent.isInEditMode) {
UserClassesService(emptyFlow())
} else {
parent.context.injector.instance()
}
val userClass = userClassesService.get(mark)
if (op) {
val badge = OpDrawable(parent.context, parent.textSize)
badge.setBounds(0, 0, badge.intrinsicWidth, badge.intrinsicHeight)
inSpans(ImageSpan(badge, ImageSpan.ALIGN_BASELINE)) {
append("OP")
}
append(" ")
}
append(name)
append("\u2009")
inSpans(ForegroundColorSpan(userClass.color)) {
append(userClass.symbol)
}
}
class OpDrawable(context: Context, textSize: Float) : BaseDrawable(PixelFormat.TRANSLUCENT) {
private val paint = paint { }
private val outerR = Rect().also {
paint.textSize = textSize
paint.getTextBounds("OP", 0, 2, it)
}.toRectF()
private val innerR = Rect().also {
paint.textSize = 0.8f * textSize
paint.typeface = Typeface.DEFAULT_BOLD
paint.getTextBounds("OP", 0, 2, it)
}
private val accentColor = context.getColorCompat(ThemeHelper.accentColor)
private val textColor = blendColors(0.2f, Color.WHITE, accentColor)
private val radius = context.dp(2f)
private val padding = context.dp(2f)
override fun getIntrinsicWidth(): Int {
return (outerR.width() + 2f * padding).toInt()
}
override fun getIntrinsicHeight(): Int {
return (outerR.height() + 2f * padding).toInt()
}
override fun draw(canvas: Canvas) {
val bounds = this.bounds.toRectF()
val top = bounds.bottom - padding - outerR.height()
val bottom = bounds.bottom + padding
paint.color = accentColor
canvas.drawRoundRect(bounds.left, top, bounds.right, bottom, radius, radius, paint)
val textX = (bounds.width() - innerR.width()) / 2f
val textY = bottom - padding - (outerR.height() - innerR.height()) / 2f
paint.color = textColor
canvas.drawText("OP", textX, textY, paint)
}
}
| kotlin | 18 | 0.682373 | 116 | 29.111111 | 117 | starcoderdata |
<reponame>akuleshov7/diKTat
package org.cqfn.diktat.ruleset.chapter4
import org.cqfn.diktat.ruleset.rules.NullChecksRule
import org.cqfn.diktat.util.FixTestBase
import generated.WarningNames
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
class NullChecksRuleFixTest : FixTestBase("test/paragraph4/null_checks", ::NullChecksRule) {
@Test
@Tag(WarningNames.AVOID_NULL_CHECKS)
fun `should fix if conditions`() {
fixAndCompare("IfConditionNullCheckExpected.kt", "IfConditionNullCheckTest.kt")
}
@Test
@Tag(WarningNames.AVOID_NULL_CHECKS)
fun `should fix require function`() {
fixAndCompare("RequireFunctionExpected.kt", "RequireFunctionTest.kt")
}
}
| kotlin | 11 | 0.754875 | 92 | 30.217391 | 23 | starcoderdata |
/*
* KOTLIN PSI SPEC TEST (NEGATIVE)
*
* SPEC VERSION: 0.1-draft
* PLACE: constant-literals, real-literals -> paragraph 3 -> sentence 1
* NUMBER: 2
* DESCRIPTION: Real literals with dots at the beginning and exponent mark/float suffix right after it.
*/
val value = .f
val value = ..F
val value = .e10
val value = .+e1
val value = ..-E10F
val value = ...+e000000F
val value = ..e1f1
val value = ...E0000000000
| kotlin | 4 | 0.675418 | 103 | 22.277778 | 18 | starcoderdata |
package org.geepawhill.dungeon
class Connector(private val map: Map, seed: Coords, private val direction: Direction) {
private val neighbor1 = direction.neighbors().first
private val neighbor2 = direction.neighbors().second
private val opposite = direction.opposite()
private val cells = mutableListOf<Coords>()
val end: Terminator = moveToTerminator(seed, direction, false)
val start: Terminator = moveToTerminator(end.coords[opposite], opposite, true)
val area = Area.normalized(start.coords, end.coords)
val isLegal = map[end.cause] != CellType.BORDER &&
map[start.cause] != CellType.BORDER &&
area.longest > 2
fun commit(type: CellType) {
area.fill(map, type)
}
private fun moveToTerminator(seed: Coords, direction: Direction, track: Boolean): Terminator {
var last = seed
while (true) {
if (map[last[neighbor1]] != CellType.GRANITE) return Terminator(last, last[neighbor1])
if (map[last[neighbor2]] != CellType.GRANITE) return Terminator(last, last[neighbor2])
if (map[last[direction]] != CellType.GRANITE) return Terminator(last, last[direction])
if (track) cells.add(last)
last = last[direction]
}
}
}
| kotlin | 18 | 0.65808 | 98 | 36.676471 | 34 | starcoderdata |
<reponame>vitekkor/bbfgradle<gh_stars>1-10
//File A.java
import java.util.Collection;
import java.util.Iterator;
import java.util.function.Predicate;
import kotlin.Metadata;
import kotlin.jvm.internal.CollectionToArray;
import kotlin.jvm.internal.Intrinsics;
import kotlin.jvm.internal.markers.KMappedMarker;
import org.jetbrains.annotations.NotNull;
public abstract class A implements Collection, KMappedMarker {
@NotNull
protected final Object[] foo(@NotNull Object[] x) {
return x;
}
public abstract int getSize();
public abstract boolean contains(String var1);
public Iterator iterator() {
throw new UnsupportedOperationException("Operation is not supported for read-only collection");
}
public boolean add(String var1) {
throw new UnsupportedOperationException("Operation is not supported for read-only collection");
}
public boolean addAll(Collection var1) {
throw new UnsupportedOperationException("Operation is not supported for read-only collection");
}
public void clear() {
throw new UnsupportedOperationException("Operation is not supported for read-only collection");
}
public boolean remove(Object var1) {
throw new UnsupportedOperationException("Operation is not supported for read-only collection");
}
public boolean removeAll(Collection var1) {
throw new UnsupportedOperationException("Operation is not supported for read-only collection");
}
public boolean removeIf(Predicate var1) {
throw new UnsupportedOperationException("Operation is not supported for read-only collection");
}
public boolean retainAll(Collection var1) {
throw new UnsupportedOperationException("Operation is not supported for read-only collection");
}
// $FF: synthetic method
public boolean add(Object var1) {
throw new UnsupportedOperationException("Operation is not supported for read-only collection");
}
public Object[] toArray() {
return CollectionToArray.toArray(this);
}
public Object[] toArray(Object[] var1) {
return CollectionToArray.toArray(this, var1);
}
}
//File Main.kt
// IGNORE_BACKEND_FIR: JVM_IR
// SKIP_JDK6
// TARGET_BACKEND: JVM
// FULL_JDK
// WITH_RUNTIME
import java.lang.reflect.Modifier
fun box(): String {
val method = A::class.java.declaredMethods.single { it.name == "foo" }
return if (Modifier.isProtected(method.modifiers)) "OK" else "Fail: $method"
}
| kotlin | 17 | 0.734528 | 101 | 28.95122 | 82 | starcoderdata |
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.resolve.dfa.cfg
import org.jetbrains.kotlin.contracts.description.EventOccurrencesRange
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.utils.isLocal
import org.jetbrains.kotlin.fir.expressions.*
import org.jetbrains.kotlin.fir.expressions.builder.buildAnonymousFunctionExpression
import org.jetbrains.kotlin.fir.references.FirControlFlowGraphReference
import org.jetbrains.kotlin.fir.render
import org.jetbrains.kotlin.fir.resolve.dfa.*
import org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.resultType
import org.jetbrains.kotlin.fir.symbols.FirBasedSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirFunctionSymbol
import org.jetbrains.kotlin.fir.types.isNothing
import org.jetbrains.kotlin.fir.util.ListMultimap
import org.jetbrains.kotlin.fir.util.listMultimapOf
import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitor
import org.jetbrains.kotlin.utils.addToStdlib.runIf
import kotlin.random.Random
@RequiresOptIn
private annotation class CfgBuilderInternals
class ControlFlowGraphBuilder {
@CfgBuilderInternals
private val graphs: Stack<ControlFlowGraph> = stackOf(ControlFlowGraph(null, "<TOP_LEVEL_GRAPH>", ControlFlowGraph.Kind.TopLevel))
@get:OptIn(CfgBuilderInternals::class)
val currentGraph: ControlFlowGraph
get() = graphs.top()
private val lastNodes: Stack<CFGNode<*>> = stackOf()
val lastNode: CFGNode<*>
get() = lastNodes.top()
var levelCounter: Int = 0
private set
private val modes: Stack<Mode> = stackOf(Mode.TopLevel)
private val mode: Mode get() = modes.top()
/*
* TODO: it's temporary hack for anonymous functions resolved twice in delegate expressions
* Example: val x: Boolean by lazy { true }
*
* Note that this hack breaks passing data flow from inplace lambdas inside lambdas of delegates:
* val x: Boolean by lazy {
* val b: Any = ...
* run {
* require(b is Boolean)
* }
* b // there will be no smartcast, but it should be
* }
*/
private val shouldPassFlowFromInplaceLambda: Stack<Boolean> = stackOf(true)
private enum class Mode {
Function, TopLevel, Body, ClassInitializer, PropertyInitializer, FieldInitializer
}
// ----------------------------------- Node caches -----------------------------------
private val exitTargetsForReturn: SymbolBasedNodeStorage<FirFunction, FunctionExitNode> = SymbolBasedNodeStorage()
private val exitTargetsForTry: Stack<CFGNode<*>> = stackOf()
private val exitsOfAnonymousFunctions: MutableMap<FirFunctionSymbol<*>, FunctionExitNode> = mutableMapOf()
private val enterToLocalClassesMembers: MutableMap<FirBasedSymbol<*>, CFGNode<*>?> = mutableMapOf()
//return jumps via finally blocks, target -> jumps
private val nonDirectJumps: ListMultimap<CFGNode<*>, CFGNode<*>> = listMultimapOf()
private val postponedLambdas: MutableSet<FirFunctionSymbol<*>> = mutableSetOf()
private val entersToPostponedAnonymousFunctions: MutableMap<FirFunctionSymbol<*>, PostponedLambdaEnterNode> = mutableMapOf()
private val exitsFromPostponedAnonymousFunctions: MutableMap<FirFunctionSymbol<*>, PostponedLambdaExitNode> = mutableMapOf()
private val parentGraphForAnonymousFunctions: MutableMap<FirFunctionSymbol<*>, ControlFlowGraph> = mutableMapOf()
private val loopEnterNodes: NodeStorage<FirElement, CFGNode<FirElement>> = NodeStorage()
private val loopExitNodes: NodeStorage<FirLoop, LoopExitNode> = NodeStorage()
private val exitsFromCompletedPostponedAnonymousFunctions: MutableList<PostponedLambdaExitNode> = mutableListOf()
private val whenExitNodes: NodeStorage<FirWhenExpression, WhenExitNode> = NodeStorage()
private val whenBranchIndices: Stack<Map<FirWhenBranch, Int>> = stackOf()
private val binaryAndExitNodes: Stack<BinaryAndExitNode> = stackOf()
private val binaryOrExitNodes: Stack<BinaryOrExitNode> = stackOf()
private val tryExitNodes: NodeStorage<FirTryExpression, TryExpressionExitNode> = NodeStorage()
private val tryMainExitNodes: NodeStorage<FirTryExpression, TryMainBlockExitNode> = NodeStorage()
private val catchNodeStorages: Stack<NodeStorage<FirCatch, CatchClauseEnterNode>> = stackOf()
private val catchNodeStorage: NodeStorage<FirCatch, CatchClauseEnterNode> get() = catchNodeStorages.top()
private val catchExitNodeStorages: Stack<NodeStorage<FirCatch, CatchClauseExitNode>> = stackOf()
private val finallyEnterNodes: Stack<FinallyBlockEnterNode> = stackOf()
private val finallyExitNodes: NodeStorage<FirTryExpression, FinallyBlockExitNode> = NodeStorage()
private val initBlockExitNodes: Stack<InitBlockExitNode> = stackOf()
private val exitSafeCallNodes: Stack<ExitSafeCallNode> = stackOf()
private val exitElvisExpressionNodes: Stack<ElvisExitNode> = stackOf()
private val elvisRhsEnterNodes: Stack<ElvisRhsEnterNode> = stackOf()
private val notCompletedFunctionCalls: Stack<MutableList<FunctionCallNode>> = stackOf()
/*
* ignoredFunctionCalls is needed for resolve of += operator:
* we have two different calls for resolve, but we left only one of them,
* so we twice call `enterCall` and twice increase `levelCounter`, but
* `exitFunctionCall` we call only once.
*
* So workflow looks like that:
* Calls:
* - a.plus(b) // (1)
* - a.plusAssign(b) // (2)
*
* enterCall(a.plus(b)), increase counter
* exitIgnoredCall(a.plus(b)) // decrease counter
* enterCall(a.plusAssign(b)) // increase counter
* exitIgnoredCall(a.plusAssign(b)) // decrease counter
* exitFunctionCall(a.plus(b) | a.plusAssign(b)) // don't touch counter
*/
private val ignoredFunctionCalls: MutableSet<FirFunctionCall> = mutableSetOf()
// ----------------------------------- API for node builders -----------------------------------
private var idCounter: Int = Random.nextInt()
fun createId(): Int = idCounter++
// ----------------------------------- Public API -----------------------------------
fun isThereControlFlowInfoForAnonymousFunction(function: FirAnonymousFunction): Boolean =
function.controlFlowGraphReference?.controlFlowGraph != null ||
exitsOfAnonymousFunctions.containsKey(function.symbol)
// This function might throw exception if !isThereControlFlowInfoForAnonymousFunction(function)
fun returnExpressionsOfAnonymousFunction(function: FirAnonymousFunction): Collection<FirStatement> {
fun FirElement.extractArgument(): FirElement = when {
this is FirReturnExpression && target.labeledElement.symbol == function.symbol -> result.extractArgument()
else -> this
}
fun CFGNode<*>.extractArgument(): FirElement? = when (this) {
is FunctionEnterNode, is TryMainBlockEnterNode, is FinallyBlockExitNode, is CatchClauseEnterNode -> null
is BlockExitNode -> if (function.isLambda || isDead) firstPreviousNode.extractArgument() else null
is StubNode -> firstPreviousNode.extractArgument()
else -> fir.extractArgument()
}
val exitNode = function.controlFlowGraphReference?.controlFlowGraph?.exitNode
?: exitsOfAnonymousFunctions.getValue(function.symbol)
val nonDirect = nonDirectJumps[exitNode]
return (nonDirect + exitNode.previousNodes).mapNotNullTo(mutableSetOf()) {
it.extractArgument() as FirStatement?
}
}
@OptIn(CfgBuilderInternals::class)
fun isTopLevel(): Boolean = graphs.size == 1
// ----------------------------------- Utils -----------------------------------
@OptIn(CfgBuilderInternals::class)
private fun pushGraph(graph: ControlFlowGraph, mode: Mode) {
graphs.push(graph)
modes.push(mode)
levelCounter++
}
@OptIn(CfgBuilderInternals::class)
private fun popGraph(): ControlFlowGraph {
levelCounter--
modes.pop()
return graphs.pop().also { it.complete() }
}
// ----------------------------------- Regular function -----------------------------------
fun enterFunction(function: FirFunction): Triple<FunctionEnterNode, LocalFunctionDeclarationNode?, CFGNode<*>?> {
require(function !is FirAnonymousFunction)
val name = when (function) {
is FirSimpleFunction -> function.name.asString()
is FirPropertyAccessor -> if (function.isGetter) "<getter>" else "<setter>"
is FirConstructor -> "<init>"
else -> throw IllegalArgumentException("Unknown function: ${function.render()}")
}
val graph = ControlFlowGraph(function, name, ControlFlowGraph.Kind.Function)
// function is local
val localFunctionNode = runIf(mode == Mode.Body) {
assert(currentGraph.kind.withBody)
currentGraph.addSubGraph(graph)
createLocalFunctionDeclarationNode(function).also {
addNewSimpleNode(it)
}
}
pushGraph(
graph = graph,
mode = Mode.Body
)
val previousNode = enterToLocalClassesMembers[function.symbol]
?: (function as? FirSimpleFunction)?.takeIf { it.isLocal }?.let { lastNode }
val enterNode = createFunctionEnterNode(function).also {
lastNodes.push(it)
}
if (previousNode != null) {
if (localFunctionNode == previousNode) {
addEdge(localFunctionNode, enterNode, preferredKind = EdgeKind.Forward)
} else {
addEdge(previousNode, enterNode, preferredKind = EdgeKind.DfgForward)
}
}
createFunctionExitNode(function).also {
exitTargetsForReturn.push(it)
exitTargetsForTry.push(it)
}
return Triple(enterNode, localFunctionNode, previousNode)
}
fun exitFunction(function: FirFunction): Pair<FunctionExitNode, ControlFlowGraph> {
require(function !is FirAnonymousFunction)
val exitNode = exitTargetsForReturn.pop()
popAndAddEdge(exitNode)
val graph = popGraph()
assert(exitNode == graph.exitNode)
exitTargetsForTry.pop().also {
assert(it == graph.exitNode)
}
graph.exitNode.updateDeadStatus()
return graph.exitNode as FunctionExitNode to graph
}
// ----------------------------------- Anonymous function -----------------------------------
fun visitPostponedAnonymousFunction(anonymousFunctionExpression: FirAnonymousFunctionExpression): Pair<PostponedLambdaEnterNode, PostponedLambdaExitNode> {
val anonymousFunction = anonymousFunctionExpression.anonymousFunction
val enterNode = createPostponedLambdaEnterNode(anonymousFunction)
val exitNode = createPostponedLambdaExitNode(anonymousFunctionExpression)
val symbol = anonymousFunction.symbol
postponedLambdas += symbol
entersToPostponedAnonymousFunctions[symbol] = enterNode
exitsFromPostponedAnonymousFunctions[symbol] = exitNode
parentGraphForAnonymousFunctions[symbol] = currentGraph
popAndAddEdge(enterNode, preferredKind = EdgeKind.Forward)
addEdge(enterNode, exitNode, preferredKind = EdgeKind.DfgForward)
lastNodes.push(exitNode)
return enterNode to exitNode
}
fun enterAnonymousFunction(anonymousFunction: FirAnonymousFunction): Pair<PostponedLambdaEnterNode?, FunctionEnterNode> {
val invocationKind = anonymousFunction.invocationKind
var previousNodeIsNew = false
val symbol = anonymousFunction.symbol
val previousNode = entersToPostponedAnonymousFunctions[symbol]
?: createPostponedLambdaEnterNode(anonymousFunction).also {
addNewSimpleNode(it)
entersToPostponedAnonymousFunctions[symbol] = it
previousNodeIsNew = true
}
if (previousNodeIsNew) {
assert(symbol !in exitsFromPostponedAnonymousFunctions)
val lambdaExpression = buildAnonymousFunctionExpression {
source = anonymousFunction.source
this.anonymousFunction = anonymousFunction
}
val exitFromLambda = createPostponedLambdaExitNode(lambdaExpression).also {
exitsFromPostponedAnonymousFunctions[symbol] = it
}
addEdge(previousNode, exitFromLambda)
}
pushGraph(ControlFlowGraph(anonymousFunction, "<anonymous>", ControlFlowGraph.Kind.AnonymousFunction), Mode.Function)
val enterNode = createFunctionEnterNode(anonymousFunction).also {
if (previousNodeIsNew) {
addNewSimpleNode(it)
} else {
addEdge(previousNode, it)
lastNodes.push(it)
}
}
val exitNode = createFunctionExitNode(anonymousFunction).also {
exitsOfAnonymousFunctions[symbol] = it
exitTargetsForReturn.push(it)
if (!invocationKind.isInPlace) {
exitTargetsForTry.push(it)
}
}
if (invocationKind.hasTowardEdge) {
addEdge(enterNode, exitNode)
}
if (invocationKind.hasBackEdge) {
addBackEdge(exitNode, enterNode)
}
return if (previousNodeIsNew) {
previousNode to enterNode
} else {
null to enterNode
}
}
private val EventOccurrencesRange?.hasTowardEdge: Boolean
get() = when (this) {
EventOccurrencesRange.AT_MOST_ONCE, EventOccurrencesRange.UNKNOWN -> true
else -> false
}
private val EventOccurrencesRange?.hasBackEdge: Boolean
get() = when (this) {
EventOccurrencesRange.AT_LEAST_ONCE, EventOccurrencesRange.UNKNOWN -> true
else -> false
}
fun exitAnonymousFunction(anonymousFunction: FirAnonymousFunction): Triple<FunctionExitNode, PostponedLambdaExitNode?, ControlFlowGraph> {
val symbol = anonymousFunction.symbol
val exitNode = exitsOfAnonymousFunctions.remove(symbol)!!.also {
require(it == exitTargetsForReturn.pop())
if (!anonymousFunction.invocationKind.isInPlace) {
require(it == exitTargetsForTry.pop())
}
}
popAndAddEdge(exitNode)
exitNode.updateDeadStatus()
val graph = popGraph().also { graph ->
assert(graph.declaration == anonymousFunction)
assert(graph.exitNode == exitNode)
exitsFromCompletedPostponedAnonymousFunctions.removeAll { it.owner == graph }
}
val postponedEnterNode = entersToPostponedAnonymousFunctions.remove(symbol)!!
val postponedExitNode = exitsFromPostponedAnonymousFunctions.remove(symbol)!!
val lambdaIsPostponedFromCall = postponedLambdas.remove(symbol)
if (!lambdaIsPostponedFromCall) {
lastNodes.push(postponedExitNode)
}
val invocationKind = anonymousFunction.invocationKind
if (invocationKind != null) {
addEdge(exitNode, postponedExitNode, preferredKind = EdgeKind.CfgForward)
} else {
val kind = if (postponedExitNode.isDead) EdgeKind.DeadForward else EdgeKind.CfgForward
CFGNode.addJustKindEdge(postponedEnterNode, postponedExitNode, kind, propagateDeadness = true)
}
if (invocationKind == EventOccurrencesRange.EXACTLY_ONCE && shouldPassFlowFromInplaceLambda.top()) {
exitsFromCompletedPostponedAnonymousFunctions += postponedExitNode
}
val containingGraph = parentGraphForAnonymousFunctions.remove(symbol) ?: currentGraph
containingGraph.addSubGraph(graph)
return if (lambdaIsPostponedFromCall) {
Triple(exitNode, null, graph)
} else {
Triple(exitNode, postponedExitNode, graph)
}
}
fun exitAnonymousFunctionExpression(anonymousFunctionExpression: FirAnonymousFunctionExpression): AnonymousFunctionExpressionExitNode {
return createAnonymousFunctionExpressionExitNode(anonymousFunctionExpression).also {
addNewSimpleNode(it)
}
}
// ----------------------------------- Classes -----------------------------------
fun enterClass() {
pushGraph(
ControlFlowGraph(null, "STUB_CLASS_GRAPH", ControlFlowGraph.Kind.Stub),
mode = Mode.ClassInitializer
)
}
fun exitClass() {
popGraph()
}
fun exitClass(klass: FirClass): ControlFlowGraph {
exitClass()
val name = when (klass) {
is FirAnonymousObject -> "<anonymous object>"
is FirRegularClass -> klass.name.asString()
else -> throw IllegalArgumentException("Unknown class kind: ${klass::class}")
}
val classGraph = ControlFlowGraph(klass, name, ControlFlowGraph.Kind.ClassInitializer)
pushGraph(classGraph, Mode.ClassInitializer)
val exitNode = createClassExitNode(klass)
var node: CFGNode<*> = createClassEnterNode(klass)
var prevInitPartNode: CFGNode<*>? = null
for (declaration in klass.declarations) {
val graph = when (declaration) {
is FirProperty -> declaration.controlFlowGraphReference?.controlFlowGraph
is FirAnonymousInitializer -> declaration.controlFlowGraphReference?.controlFlowGraph
else -> null
} ?: continue
createPartOfClassInitializationNode(declaration as FirControlFlowGraphOwner).also {
addEdge(node, it, preferredKind = EdgeKind.CfgForward)
addEdge(it, graph.enterNode, preferredKind = EdgeKind.CfgForward)
node = graph.exitNode
if (prevInitPartNode != null) addEdge(prevInitPartNode!!, it, preferredKind = EdgeKind.DeadForward)
it.updateDeadStatus()
prevInitPartNode = it
}
}
addEdge(node, exitNode, preferredKind = EdgeKind.CfgForward)
if (prevInitPartNode != null) addEdge(prevInitPartNode!!, exitNode, preferredKind = EdgeKind.DeadForward)
exitNode.updateDeadStatus()
return popGraph()
}
fun prepareForLocalClassMembers(members: Collection<FirDeclaration>) {
members.forEachMember {
enterToLocalClassesMembers[it.symbol] = lastNodes.topOrNull()
}
}
fun cleanAfterForLocalClassMembers(members: Collection<FirDeclaration>) {
members.forEachMember {
enterToLocalClassesMembers.remove(it.symbol)
}
}
fun exitLocalClass(klass: FirRegularClass): Pair<LocalClassExitNode, ControlFlowGraph> {
val graph = exitClass(klass).also {
currentGraph.addSubGraph(it)
}
val node = createLocalClassExitNode(klass).also {
addNewSimpleNodeIfPossible(it)
}
visitLocalClassFunctions(klass, node)
addEdge(node, graph.enterNode, preferredKind = EdgeKind.CfgForward)
return node to graph
}
fun exitAnonymousObject(anonymousObject: FirAnonymousObject): Pair<AnonymousObjectExitNode, ControlFlowGraph> {
val graph = exitClass(anonymousObject).also {
currentGraph.addSubGraph(it)
}
val node = createAnonymousObjectExitNode(anonymousObject).also {
// TODO: looks like there was some problem with enum initializers
if (lastNodes.isNotEmpty) {
addNewSimpleNode(it)
}
}
visitLocalClassFunctions(anonymousObject, node)
addEdge(node, graph.enterNode, preferredKind = EdgeKind.CfgForward)
return node to graph
}
fun exitAnonymousObjectExpression(anonymousObjectExpression: FirAnonymousObjectExpression): AnonymousObjectExpressionExitNode {
return createAnonymousObjectExpressionExitNode(anonymousObjectExpression).also {
addNewSimpleNodeIfPossible(it)
}
}
fun visitLocalClassFunctions(klass: FirClass, node: CFGNodeWithCfgOwner<*>) {
klass.declarations.filterIsInstance<FirFunction>().forEach { function ->
val functionGraph = function.controlFlowGraphReference?.controlFlowGraph
if (functionGraph != null && functionGraph.owner == null) {
addEdge(node, functionGraph.enterNode, preferredKind = EdgeKind.CfgForward)
node.addSubGraph(functionGraph)
}
}
}
// ----------------------------------- Value parameters (and it's defaults) -----------------------------------
fun enterValueParameter(valueParameter: FirValueParameter): EnterDefaultArgumentsNode? {
if (valueParameter.defaultValue == null) return null
val graph = ControlFlowGraph(valueParameter, "default value of ${valueParameter.name}", ControlFlowGraph.Kind.DefaultArgument)
currentGraph.addSubGraph(graph)
pushGraph(graph, Mode.Body)
createExitDefaultArgumentsNode(valueParameter).also {
exitTargetsForTry.push(it)
}
return createEnterDefaultArgumentsNode(valueParameter).also {
addEdge(lastNode, it)
lastNodes.push(it)
}
}
fun exitValueParameter(valueParameter: FirValueParameter): Pair<ExitDefaultArgumentsNode, ControlFlowGraph>? {
if (valueParameter.defaultValue == null) return null
val exitNode = exitTargetsForTry.pop() as ExitDefaultArgumentsNode
popAndAddEdge(exitNode)
val graph = popGraph()
require(exitNode == graph.exitNode)
return exitNode to graph
}
// ----------------------------------- Block -----------------------------------
fun enterBlock(block: FirBlock): BlockEnterNode {
return createBlockEnterNode(block).also {
addNewSimpleNode(it)
}
}
fun exitBlock(block: FirBlock): CFGNode<*> {
return createBlockExitNode(block).also {
addNewSimpleNode(it)
}
}
// ----------------------------------- Property -----------------------------------
fun enterProperty(property: FirProperty): PropertyInitializerEnterNode? {
if (property.initializer == null && property.delegate == null) return null
val graph = ControlFlowGraph(property, "val ${property.name}", ControlFlowGraph.Kind.PropertyInitializer)
pushGraph(graph, Mode.PropertyInitializer)
val enterNode = createPropertyInitializerEnterNode(property)
val exitNode = createPropertyInitializerExitNode(property)
exitTargetsForTry.push(exitNode)
enterToLocalClassesMembers[property.symbol]?.let {
addEdge(it, enterNode, preferredKind = EdgeKind.DfgForward)
}
lastNodes.push(enterNode)
return enterNode
}
fun exitProperty(property: FirProperty): Pair<PropertyInitializerExitNode, ControlFlowGraph>? {
if (property.initializer == null && property.delegate == null) return null
val exitNode = exitTargetsForTry.pop() as PropertyInitializerExitNode
popAndAddEdge(exitNode)
val graph = popGraph()
assert(exitNode == graph.exitNode)
return exitNode to graph
}
// ----------------------------------- Field -----------------------------------
fun enterField(field: FirField): FieldInitializerEnterNode? {
if (field.initializer == null) return null
val graph = ControlFlowGraph(field, "val ${field.name}", ControlFlowGraph.Kind.FieldInitializer)
pushGraph(graph, Mode.FieldInitializer)
val enterNode = createFieldInitializerEnterNode(field)
val exitNode = createFieldInitializerExitNode(field)
exitTargetsForTry.push(exitNode)
enterToLocalClassesMembers[field.symbol]?.let {
addEdge(it, enterNode, preferredKind = EdgeKind.DfgForward)
}
lastNodes.push(enterNode)
return enterNode
}
fun exitField(field: FirField): Pair<FieldInitializerExitNode, ControlFlowGraph>? {
if (field.initializer == null) return null
val exitNode = exitTargetsForTry.pop() as FieldInitializerExitNode
popAndAddEdge(exitNode)
val graph = popGraph()
assert(exitNode == graph.exitNode)
return exitNode to graph
}
// ----------------------------------- Delegate -----------------------------------
fun enterDelegateExpression() {
shouldPassFlowFromInplaceLambda.push(false)
}
fun exitDelegateExpression() {
shouldPassFlowFromInplaceLambda.pop()
}
// ----------------------------------- Operator call -----------------------------------
fun exitTypeOperatorCall(typeOperatorCall: FirTypeOperatorCall): TypeOperatorCallNode {
return createTypeOperatorCallNode(typeOperatorCall).also { addNewSimpleNode(it) }
}
fun exitComparisonExpression(comparisonExpression: FirComparisonExpression): ComparisonExpressionNode {
return createComparisonExpressionNode(comparisonExpression).also { addNewSimpleNode(it) }
}
fun exitEqualityOperatorCall(equalityOperatorCall: FirEqualityOperatorCall): EqualityOperatorCallNode {
return createEqualityOperatorCallNode(equalityOperatorCall).also { addNewSimpleNode(it) }
}
// ----------------------------------- Jump -----------------------------------
fun exitJump(jump: FirJump<*>): JumpNode {
val node = createJumpNode(jump)
val nextNode = when (jump) {
is FirReturnExpression -> exitTargetsForReturn[jump.target.labeledElement.symbol]
is FirContinueExpression -> loopEnterNodes[jump.target.labeledElement]
is FirBreakExpression -> loopExitNodes[jump.target.labeledElement]
else -> throw IllegalArgumentException("Unknown jump type: ${jump.render()}")
}
val labelForFinallyBLock = if (jump is FirReturnExpression) {
ReturnPath(jump.target.labeledElement.symbol)
} else {
NormalPath
}
addNodeWithJump(
node,
nextNode,
isBack = jump is FirContinueExpression,
trackJump = jump is FirReturnExpression,
label = NormalPath,
labelForFinallyBLock = labelForFinallyBLock
)
return node
}
// ----------------------------------- When -----------------------------------
fun enterWhenExpression(whenExpression: FirWhenExpression): WhenEnterNode {
val node = createWhenEnterNode(whenExpression)
addNewSimpleNode(node)
whenExitNodes.push(createWhenExitNode(whenExpression))
whenBranchIndices.push(whenExpression.branches.mapIndexed { index, branch -> branch to index }.toMap())
levelCounter++
return node
}
fun enterWhenBranchCondition(whenBranch: FirWhenBranch): WhenBranchConditionEnterNode {
levelCounter += whenBranchIndices.top().getValue(whenBranch)
return createWhenBranchConditionEnterNode(whenBranch).also { addNewSimpleNode(it) }.also { levelCounter++ }
}
fun exitWhenBranchCondition(whenBranch: FirWhenBranch): Pair<WhenBranchConditionExitNode, WhenBranchResultEnterNode> {
levelCounter--
val conditionExitNode = createWhenBranchConditionExitNode(whenBranch).also {
addNewSimpleNode(it)
}.also { levelCounter++ }
val branchEnterNode = createWhenBranchResultEnterNode(whenBranch).also {
lastNodes.push(it)
addEdge(conditionExitNode, it)
}
return conditionExitNode to branchEnterNode
}
fun exitWhenBranchResult(whenBranch: FirWhenBranch): WhenBranchResultExitNode {
levelCounter--
val node = createWhenBranchResultExitNode(whenBranch)
popAndAddEdge(node)
val whenExitNode = whenExitNodes.top()
addEdge(node, whenExitNode, propagateDeadness = false)
levelCounter -= whenBranchIndices.top().getValue(whenBranch)
return node
}
fun exitWhenExpression(whenExpression: FirWhenExpression): Pair<WhenExitNode, WhenSyntheticElseBranchNode?> {
val whenExitNode = whenExitNodes.pop()
// exit from last condition node still on stack
// we should remove it
val lastWhenConditionExit = lastNodes.pop()
val syntheticElseBranchNode = if (!whenExpression.isProperlyExhaustive) {
createWhenSyntheticElseBranchNode(whenExpression).apply {
addEdge(lastWhenConditionExit, this)
addEdge(this, whenExitNode)
}
} else null
whenExitNode.updateDeadStatus()
lastNodes.push(whenExitNode)
dropPostponedLambdasForNonDeterministicCalls()
levelCounter--
whenBranchIndices.pop()
return whenExitNode to syntheticElseBranchNode
}
// ----------------------------------- While Loop -----------------------------------
fun enterWhileLoop(loop: FirLoop): Pair<LoopEnterNode, LoopConditionEnterNode> {
val loopEnterNode = createLoopEnterNode(loop).also {
addNewSimpleNode(it)
loopEnterNodes.push(it)
}
loopExitNodes.push(createLoopExitNode(loop))
levelCounter++
val conditionEnterNode = createLoopConditionEnterNode(loop.condition, loop).also {
addNewSimpleNode(it)
// put conditional node twice so we can refer it after exit from loop block
lastNodes.push(it)
}
levelCounter++
return loopEnterNode to conditionEnterNode
}
fun exitWhileLoopCondition(loop: FirLoop): Pair<LoopConditionExitNode, LoopBlockEnterNode> {
levelCounter--
val conditionExitNode = createLoopConditionExitNode(loop.condition)
addNewSimpleNode(conditionExitNode)
val conditionConstBooleanValue = conditionExitNode.booleanConstValue
addEdge(conditionExitNode, loopExitNodes.top(), propagateDeadness = false, isDead = conditionConstBooleanValue == true)
val loopBlockEnterNode = createLoopBlockEnterNode(loop)
addNewSimpleNode(loopBlockEnterNode, conditionConstBooleanValue == false)
levelCounter++
return conditionExitNode to loopBlockEnterNode
}
fun exitWhileLoop(loop: FirLoop): Pair<LoopBlockExitNode, LoopExitNode> {
loopEnterNodes.pop()
levelCounter--
val loopBlockExitNode = createLoopBlockExitNode(loop)
popAndAddEdge(loopBlockExitNode)
if (lastNodes.isNotEmpty) {
val conditionEnterNode = lastNodes.pop()
require(conditionEnterNode is LoopConditionEnterNode) { loop.render() }
addBackEdge(loopBlockExitNode, conditionEnterNode, label = LoopBackPath)
}
val loopExitNode = loopExitNodes.pop()
loopExitNode.updateDeadStatus()
lastNodes.push(loopExitNode)
levelCounter--
return loopBlockExitNode to loopExitNode
}
// ----------------------------------- Do while Loop -----------------------------------
fun enterDoWhileLoop(loop: FirLoop): Pair<LoopEnterNode, LoopBlockEnterNode> {
val loopEnterNode = createLoopEnterNode(loop)
addNewSimpleNode(loopEnterNode)
loopExitNodes.push(createLoopExitNode(loop))
levelCounter++
val blockEnterNode = createLoopBlockEnterNode(loop)
addNewSimpleNode(blockEnterNode)
// put block enter node twice so we can refer it after exit from loop condition
lastNodes.push(blockEnterNode)
loopEnterNodes.push(blockEnterNode)
levelCounter++
return loopEnterNode to blockEnterNode
}
fun enterDoWhileLoopCondition(loop: FirLoop): Pair<LoopBlockExitNode, LoopConditionEnterNode> {
levelCounter--
val blockExitNode = createLoopBlockExitNode(loop).also { addNewSimpleNode(it) }
val conditionEnterNode = createLoopConditionEnterNode(loop.condition, loop).also { addNewSimpleNode(it) }
levelCounter++
return blockExitNode to conditionEnterNode
}
fun exitDoWhileLoop(loop: FirLoop): Pair<LoopConditionExitNode, LoopExitNode> {
loopEnterNodes.pop()
levelCounter--
val conditionExitNode = createLoopConditionExitNode(loop.condition)
val conditionBooleanValue = conditionExitNode.booleanConstValue
popAndAddEdge(conditionExitNode)
val blockEnterNode = lastNodes.pop()
require(blockEnterNode is LoopBlockEnterNode)
addBackEdge(conditionExitNode, blockEnterNode, isDead = conditionBooleanValue == false, label = LoopBackPath)
val loopExit = loopExitNodes.pop()
addEdge(conditionExitNode, loopExit, propagateDeadness = false, isDead = conditionBooleanValue == true)
loopExit.updateDeadStatus()
lastNodes.push(loopExit)
levelCounter--
return conditionExitNode to loopExit
}
// ----------------------------------- Boolean operators -----------------------------------
fun enterBinaryAnd(binaryLogicExpression: FirBinaryLogicExpression): BinaryAndEnterNode {
assert(binaryLogicExpression.kind == LogicOperationKind.AND)
binaryAndExitNodes.push(createBinaryAndExitNode(binaryLogicExpression))
return createBinaryAndEnterNode(binaryLogicExpression).also { addNewSimpleNode(it) }.also { levelCounter++ }
}
fun exitLeftBinaryAndArgument(binaryLogicExpression: FirBinaryLogicExpression): Pair<BinaryAndExitLeftOperandNode, BinaryAndEnterRightOperandNode> {
assert(binaryLogicExpression.kind == LogicOperationKind.AND)
val lastNode = lastNodes.pop()
val leftBooleanConstValue = lastNode.booleanConstValue
val leftExitNode = createBinaryAndExitLeftOperandNode(binaryLogicExpression).also {
addEdge(lastNode, it)
addEdge(it, binaryAndExitNodes.top(), propagateDeadness = false, isDead = leftBooleanConstValue == true)
}
val rightEnterNode = createBinaryAndEnterRightOperandNode(binaryLogicExpression).also {
addEdge(leftExitNode, it, isDead = leftBooleanConstValue == false)
lastNodes.push(it)
}
return leftExitNode to rightEnterNode
}
fun exitBinaryAnd(binaryLogicExpression: FirBinaryLogicExpression): BinaryAndExitNode {
levelCounter--
assert(binaryLogicExpression.kind == LogicOperationKind.AND)
return binaryAndExitNodes.pop().also {
val rightNode = lastNodes.pop()
addEdge(rightNode, it, propagateDeadness = false, isDead = it.leftOperandNode.booleanConstValue == false)
it.updateDeadStatus()
lastNodes.push(it)
}
}
fun enterBinaryOr(binaryLogicExpression: FirBinaryLogicExpression): BinaryOrEnterNode {
assert(binaryLogicExpression.kind == LogicOperationKind.OR)
binaryOrExitNodes.push(createBinaryOrExitNode(binaryLogicExpression))
return createBinaryOrEnterNode(binaryLogicExpression).also {
addNewSimpleNode(it)
}.also { levelCounter++ }
}
fun exitLeftBinaryOrArgument(binaryLogicExpression: FirBinaryLogicExpression): Pair<BinaryOrExitLeftOperandNode, BinaryOrEnterRightOperandNode> {
levelCounter--
assert(binaryLogicExpression.kind == LogicOperationKind.OR)
val previousNode = lastNodes.pop()
val leftBooleanValue = previousNode.booleanConstValue
val leftExitNode = createBinaryOrExitLeftOperandNode(binaryLogicExpression).also {
addEdge(previousNode, it)
addEdge(it, binaryOrExitNodes.top(), propagateDeadness = false, isDead = leftBooleanValue == false)
}
val rightExitNode = createBinaryOrEnterRightOperandNode(binaryLogicExpression).also {
addEdge(leftExitNode, it, propagateDeadness = true, isDead = leftBooleanValue == true)
lastNodes.push(it)
levelCounter++
}
return leftExitNode to rightExitNode
}
fun enterContract(qualifiedAccess: FirQualifiedAccess): EnterContractNode {
return createEnterContractNode(qualifiedAccess).also { addNewSimpleNode(it) }
}
fun exitContract(qualifiedAccess: FirQualifiedAccess): ExitContractNode {
return createExitContractNode(qualifiedAccess).also { addNewSimpleNode(it) }
}
fun exitBinaryOr(binaryLogicExpression: FirBinaryLogicExpression): BinaryOrExitNode {
assert(binaryLogicExpression.kind == LogicOperationKind.OR)
levelCounter--
return binaryOrExitNodes.pop().also {
val rightNode = lastNodes.pop()
addEdge(rightNode, it, propagateDeadness = false)
it.updateDeadStatus()
lastNodes.push(it)
}
}
private val CFGNode<*>.booleanConstValue: Boolean? get() = (fir as? FirConstExpression<*>)?.value as? Boolean?
// ----------------------------------- Try-catch-finally -----------------------------------
fun enterTryExpression(tryExpression: FirTryExpression): Pair<TryExpressionEnterNode, TryMainBlockEnterNode> {
catchNodeStorages.push(NodeStorage())
catchExitNodeStorages.push(NodeStorage())
val enterTryExpressionNode = createTryExpressionEnterNode(tryExpression)
addNewSimpleNode(enterTryExpressionNode)
val tryExitNode = createTryExpressionExitNode(tryExpression)
tryExitNodes.push(tryExitNode)
levelCounter++
val enterTryNodeBlock = createTryMainBlockEnterNode(tryExpression)
addNewSimpleNode(enterTryNodeBlock)
val exitTryNodeBlock = createTryMainBlockExitNode(tryExpression)
tryMainExitNodes.push(exitTryNodeBlock)
for (catch in tryExpression.catches) {
val catchNode = createCatchClauseEnterNode(catch)
catchNodeStorage.push(catchNode)
// a flow where an exception of interest is thrown and caught before executing any of try-main block.
addEdge(enterTryExpressionNode, catchNode)
}
levelCounter++
if (tryExpression.finallyBlock != null) {
val finallyEnterNode = createFinallyBlockEnterNode(tryExpression)
// a flow where an uncaught exception is thrown before executing any of try-main block.
addEdge(enterTryExpressionNode, finallyEnterNode, propagateDeadness = false, label = UncaughtExceptionPath)
finallyEnterNodes.push(finallyEnterNode)
finallyExitNodes.push(createFinallyBlockExitNode(tryExpression))
}
notCompletedFunctionCalls.push(mutableListOf())
return enterTryExpressionNode to enterTryNodeBlock
}
fun exitTryMainBlock(): TryMainBlockExitNode {
levelCounter--
val node = tryMainExitNodes.top()
popAndAddEdge(node)
node.updateDeadStatus()
val finallyEnterNode = finallyEnterNodes.topOrNull()
// NB: Check the level to avoid adding an edge to the finally block at an upper level.
if (finallyEnterNode != null && finallyEnterNode.level == levelCounter + 1) {
// TODO: in case of return/continue/break in try main block, we need a unique label.
addEdge(node, finallyEnterNode)
//in case try exit is dead, but there is other edges to finally (eg return)
// actually finallyEnterNode can't be dead, except for the case when the whole try is dead
finallyEnterNode.updateDeadStatus()
} else {
addEdge(node, tryExitNodes.top(), propagateDeadness = false)
}
return node
}
fun enterCatchClause(catch: FirCatch): CatchClauseEnterNode {
return catchNodeStorage[catch]!!.also {
val tryMainExitNode = tryMainExitNodes.top()
// a flow where an exception of interest is thrown and caught after executing all of try-main block.
addEdge(tryMainExitNode, it)
//tryMainExitNode might be dead (eg main block contains return), but it doesn't mean catch block is also dead
it.updateDeadStatus()
val finallyEnterNode = finallyEnterNodes.topOrNull()
// a flow where an uncaught exception is thrown before executing any of catch clause.
// NB: Check the level to avoid adding an edge to the finally block at an upper level.
if (finallyEnterNode != null && finallyEnterNode.level == levelCounter + 1) {
addEdge(it, finallyEnterNode, propagateDeadness = false, label = UncaughtExceptionPath)
} else {
addEdge(it, exitTargetsForTry.top(), label = UncaughtExceptionPath)
}
lastNodes.push(it)
levelCounter++
}
}
fun exitCatchClause(catch: FirCatch): CatchClauseExitNode {
levelCounter--
return createCatchClauseExitNode(catch).also {
popAndAddEdge(it)
val finallyEnterNode = finallyEnterNodes.topOrNull()
// NB: Check the level to avoid adding an edge to the finally block at an upper level.
if (finallyEnterNode != null && finallyEnterNode.level == levelCounter + 1) {
// TODO: in case of return/continue/break in catch clause, we need a unique label.
addEdge(it, finallyEnterNode, propagateDeadness = false)
} else {
addEdge(it, tryExitNodes.top(), propagateDeadness = false)
}
catchExitNodeStorages.top().push(it)
}
}
fun enterFinallyBlock(): FinallyBlockEnterNode {
val enterNode = finallyEnterNodes.pop()
lastNodes.push(enterNode)
return enterNode
}
fun exitFinallyBlock(): FinallyBlockExitNode {
return finallyExitNodes.pop().also { finallyExit ->
popAndAddEdge(finallyExit)
val tryExitNode = tryExitNodes.top()
// a flow where either there wasn't any exception or caught if any.
addEdge(finallyExit, tryExitNode)
if (finallyExit.isDead) {
//refresh forward links, which were created before finalizing try expression (eg created by `break`)
propagateDeadnessForward(finallyExit)
}
// a flow that exits to the exit target while there was an uncaught exception.
//todo this edge might exist already if try has jump outside, so we effectively lose labeled edge here
addEdgeIfNotExist(finallyExit, exitTargetsForTry.top(), propagateDeadness = false, label = UncaughtExceptionPath)
// TODO: differentiate flows that return/(re)throw in try main block and/or catch clauses
// To do so, we need mappings from such distinct label to original exit target (fun exit or loop)
// Also, CFG should support multiple edges towards the same destination node
}
}
fun exitTryExpression(
callCompleted: Boolean
): Pair<TryExpressionExitNode, UnionFunctionCallArgumentsNode?> {
levelCounter--
catchNodeStorages.pop()
val catchExitNodes = catchExitNodeStorages.pop()
val tryMainExitNode = tryMainExitNodes.pop()
notCompletedFunctionCalls.pop().forEach(::completeFunctionCall)
val node = tryExitNodes.pop()
node.updateDeadStatus()
lastNodes.push(node)
val (_, unionNode) = processUnionOfArguments(node, callCompleted)
val allCatchesAreDead = tryMainExitNode.fir.catches.all { catch -> catchExitNodes[catch]!!.isDead }
val tryMainBlockIsDead = tryMainExitNode.previousNodes.all { prev ->
prev.isDead || tryMainExitNode.incomingEdges.getValue(prev).label != NormalPath
}
if (tryMainBlockIsDead && allCatchesAreDead) {
//if try expression doesn't have any regular non-dead exits, we add stub to make everything after dead
val stub = createStubNode()
popAndAddEdge(stub)
lastNodes.push(stub)
}
return node to unionNode
}
//this is a workaround to make function call dead when call is completed _after_ building its node in the graph
//this happens when completing the last call in try/catch blocks
//todo this doesn't make fully 'right' Nothing node (doesn't support going to catch and pass through finally)
// because doing those afterwards is quite challenging
// it would be much easier if we could build calls after full completion only, at least for Nothing calls
private fun completeFunctionCall(node: FunctionCallNode) {
if (!node.fir.resultType.isNothing) return
val stub = withLevelOfNode(node) { createStubNode() }
val edges = node.followingNodes.map { it to node.outgoingEdges.getValue(it) }
CFGNode.removeAllOutgoingEdges(node)
addEdge(node, stub)
for ((to, edge) in edges) {
addEdge(
from = stub,
to = to,
isBack = edge.kind.isBack,
preferredKind = edge.kind,
label = edge.label
)
}
stub.followingNodes.forEach { propagateDeadnessForward(it, deep = true) }
}
// ----------------------------------- Resolvable call -----------------------------------
fun exitQualifiedAccessExpression(qualifiedAccessExpression: FirQualifiedAccessExpression): QualifiedAccessNode {
val returnsNothing = qualifiedAccessExpression.resultType.isNothing
val node = createQualifiedAccessNode(qualifiedAccessExpression)
if (returnsNothing) {
addNodeThatReturnsNothing(node)
} else {
addNewSimpleNode(node)
}
return node
}
fun exitResolvedQualifierNode(resolvedQualifier: FirResolvedQualifier): ResolvedQualifierNode {
return createResolvedQualifierNode(resolvedQualifier).also(this::addNewSimpleNode)
}
fun enterCall() {
levelCounter++
}
fun exitIgnoredCall(functionCall: FirFunctionCall) {
levelCounter--
ignoredFunctionCalls += functionCall
}
fun exitFunctionCall(functionCall: FirFunctionCall, callCompleted: Boolean): Pair<FunctionCallNode, UnionFunctionCallArgumentsNode?> {
val callWasIgnored = ignoredFunctionCalls.remove(functionCall)
if (!callWasIgnored) {
levelCounter--
} else {
ignoredFunctionCalls.clear()
}
val returnsNothing = functionCall.resultType.isNothing
val node = createFunctionCallNode(functionCall)
val (kind, unionNode) = processUnionOfArguments(node, callCompleted)
if (returnsNothing) {
addNodeThatReturnsNothing(node, preferredKind = kind)
} else {
addNewSimpleNode(node, preferredKind = kind)
}
if (!returnsNothing && !callCompleted) {
notCompletedFunctionCalls.topOrNull()?.add(node)
}
return node to unionNode
}
fun exitDelegatedConstructorCall(
call: FirDelegatedConstructorCall,
callCompleted: Boolean
): Pair<DelegatedConstructorCallNode, UnionFunctionCallArgumentsNode?> {
levelCounter--
val node = createDelegatedConstructorCallNode(call)
val (kind, unionNode) = processUnionOfArguments(node, callCompleted)
addNewSimpleNode(node, preferredKind = kind)
return node to unionNode
}
fun exitStringConcatenationCall(call: FirStringConcatenationCall): Pair<StringConcatenationCallNode, UnionFunctionCallArgumentsNode?> {
levelCounter--
val node = createStringConcatenationCallNode(call)
val (kind, unionNode) = processUnionOfArguments(node, true)
addNewSimpleNode(node, preferredKind = kind)
return node to unionNode
}
fun exitConstExpression(constExpression: FirConstExpression<*>): ConstExpressionNode {
return createConstExpressionNode(constExpression).also { addNewSimpleNode(it) }
}
fun exitVariableDeclaration(variable: FirProperty): VariableDeclarationNode {
return createVariableDeclarationNode(variable).also { addNewSimpleNode(it) }
}
fun exitVariableAssignment(assignment: FirVariableAssignment): VariableAssignmentNode {
return createVariableAssignmentNode(assignment).also { addNewSimpleNode(it) }
}
fun exitThrowExceptionNode(throwExpression: FirThrowExpression): ThrowExceptionNode {
return createThrowExceptionNode(throwExpression).also { addNodeThatReturnsNothing(it) }
}
fun exitCheckNotNullCall(
checkNotNullCall: FirCheckNotNullCall,
callCompleted: Boolean
): Pair<CheckNotNullCallNode, UnionFunctionCallArgumentsNode?> {
val node = createCheckNotNullCallNode(checkNotNullCall)
if (checkNotNullCall.resultType.isNothing) {
addNodeThatReturnsNothing(node)
} else {
addNewSimpleNode(node)
}
val unionNode = processUnionOfArguments(node, callCompleted).second
return node to unionNode
}
/*
* This is needed for some control flow constructions which are resolved as calls (when and elvis)
* For usual call we have invariant that all arguments will be called before function call, but for
* when and elvis only one of arguments will be actually called, so it's illegal to pass data flow info
* from lambda in one of branches
*/
private fun dropPostponedLambdasForNonDeterministicCalls() {
exitsFromCompletedPostponedAnonymousFunctions.clear()
}
private fun processUnionOfArguments(
node: CFGNode<*>,
callCompleted: Boolean
): Pair<EdgeKind, UnionFunctionCallArgumentsNode?> {
if (!shouldPassFlowFromInplaceLambda.top()) return EdgeKind.Forward to null
var kind = EdgeKind.Forward
if (!callCompleted || exitsFromCompletedPostponedAnonymousFunctions.isEmpty()) {
return EdgeKind.Forward to null
}
val unionNode by lazy { createUnionFunctionCallArgumentsNode(node.fir) }
var hasDirectPreviousNode = false
var hasPostponedLambdas = false
val iterator = exitsFromCompletedPostponedAnonymousFunctions.iterator()
val lastPostponedLambdaExitNode = lastNode
while (iterator.hasNext()) {
val exitNode = iterator.next()
if (node.level >= exitNode.level) continue
hasPostponedLambdas = true
if (exitNode == lastPostponedLambdaExitNode) {
popAndAddEdge(node, preferredKind = EdgeKind.CfgForward)
kind = EdgeKind.DfgForward
hasDirectPreviousNode = true
}
addEdge(exitNode.lastPreviousNode, unionNode, preferredKind = EdgeKind.DfgForward)
iterator.remove()
}
if (hasPostponedLambdas) {
if (hasDirectPreviousNode) {
lastNodes.push(unionNode)
} else {
addNewSimpleNode(unionNode)
}
} else {
return EdgeKind.Forward to null
}
return Pair(kind, unionNode)
}
// ----------------------------------- Annotations -----------------------------------
fun enterAnnotationCall(annotationCall: FirAnnotationCall): AnnotationEnterNode {
val graph = ControlFlowGraph(null, "STUB_GRAPH_FOR_ANNOTATION_CALL", ControlFlowGraph.Kind.AnnotationCall)
pushGraph(graph, Mode.Body)
return createAnnotationEnterNode(annotationCall).also {
lastNodes.push(it)
}
}
fun exitAnnotationCall(annotationCall: FirAnnotationCall): AnnotationExitNode {
val node = createAnnotationExitNode(annotationCall)
popAndAddEdge(node)
popGraph()
return node
}
// ----------------------------------- Callable references -----------------------------------
fun exitCallableReference(callableReferenceAccess: FirCallableReferenceAccess): CallableReferenceNode {
return createCallableReferenceNode(callableReferenceAccess).also { addNewSimpleNode(it) }
}
fun exitGetClassCall(getClassCall: FirGetClassCall): GetClassCallNode {
return createGetClassCallNode(getClassCall).also { addNewSimpleNode(it) }
}
// ----------------------------------- Block -----------------------------------
fun enterInitBlock(initBlock: FirAnonymousInitializer): Pair<InitBlockEnterNode, CFGNode<*>?> {
// TODO: questionable moment that we should pass data flow from init to init
val graph = ControlFlowGraph(initBlock, "init block", ControlFlowGraph.Kind.Function)
pushGraph(graph, Mode.Body)
val enterNode = createInitBlockEnterNode(initBlock).also {
lastNodes.push(it)
}
val lastNode = runIf(lastNode is InitBlockExitNode) { lastNodes.pop() } ?: enterToLocalClassesMembers[initBlock.symbol]
lastNode?.let { addEdge(it, enterNode, preferredKind = EdgeKind.DfgForward) }
createInitBlockExitNode(initBlock).also {
initBlockExitNodes.push(it)
exitTargetsForTry.push(it)
}
return enterNode to lastNode
}
fun exitInitBlock(initBlock: FirAnonymousInitializer): Pair<InitBlockExitNode, ControlFlowGraph> {
val exitNode = initBlockExitNodes.pop()
require(exitNode == exitTargetsForTry.pop())
popAndAddEdge(exitNode)
val graph = popGraph()
assert(graph.declaration == initBlock)
exitNode.updateDeadStatus()
return exitNode to graph
}
// ----------------------------------- Safe calls -----------------------------------
fun enterSafeCall(safeCall: FirSafeCallExpression): EnterSafeCallNode {
/*
* We create
* lastNode -> enterNode
* lastNode -> exitNode
* instead of
* lastNode -> enterNode -> exitNode
* because we need to fork flow before `enterNode`, so `exitNode`
* will have unchanged flow from `lastNode`
* which corresponds to a path with nullable receiver.
*/
val lastNode = lastNodes.pop()
val enterNode = createEnterSafeCallNode(safeCall)
lastNodes.push(enterNode)
val exitNode = createExitSafeCallNode(safeCall)
exitSafeCallNodes.push(exitNode)
addEdge(lastNode, enterNode)
if (elvisRhsEnterNodes.topOrNull()?.fir?.lhs === safeCall) {
//if this is safe call in lhs of elvis, we make two edges
// 1. Df-only edge to exit node, to get not null implications there
// 2. Cf-only edge to elvis rhs
addEdge(lastNode, exitNode, preferredKind = EdgeKind.DfgForward)
addEdge(lastNode, elvisRhsEnterNodes.top(), preferredKind = EdgeKind.CfgForward)
} else {
addEdge(lastNode, exitNode)
}
return enterNode
}
fun exitSafeCall(): ExitSafeCallNode {
// There will be two paths towards this exit safe call node:
// one from the node prior to the enclosing safe call, and
// the other from the selector part in the enclosing safe call.
// Note that *neither* points to the safe call directly.
// So, when it comes to the real exit of the enclosing block/function,
// the safe call bound to this exit safe call node should be retrieved.
return exitSafeCallNodes.pop().also {
addNewSimpleNode(it)
it.updateDeadStatus()
}
}
// ----------------------------------- Elvis -----------------------------------
fun enterElvis(elvisExpression: FirElvisExpression) {
elvisRhsEnterNodes.push(createElvisRhsEnterNode(elvisExpression))
}
fun exitElvisLhs(elvisExpression: FirElvisExpression): Triple<ElvisLhsExitNode, ElvisLhsIsNotNullNode, ElvisRhsEnterNode> {
val exitNode = createElvisExitNode(elvisExpression).also {
exitElvisExpressionNodes.push(it)
}
val lhsExitNode = createElvisLhsExitNode(elvisExpression).also {
popAndAddEdge(it)
}
val lhsIsNotNullNode = createElvisLhsIsNotNullNode(elvisExpression).also {
addEdge(lhsExitNode, it)
addEdge(it, exitNode)
}
val rhsEnterNode = elvisRhsEnterNodes.pop().also {
addEdge(lhsExitNode, it)
}
lastNodes.push(rhsEnterNode)
return Triple(lhsExitNode, lhsIsNotNullNode, rhsEnterNode)
}
fun exitElvis(): ElvisExitNode {
val exitNode = exitElvisExpressionNodes.pop()
addNewSimpleNode(exitNode)
exitNode.updateDeadStatus()
dropPostponedLambdasForNonDeterministicCalls()
return exitNode
}
// ----------------------------------- Contract description -----------------------------------
fun enterContractDescription(): CFGNode<*> {
pushGraph(ControlFlowGraph(null, "contract description", ControlFlowGraph.Kind.TopLevel), Mode.Body)
return createContractDescriptionEnterNode().also {
lastNodes.push(it)
exitTargetsForTry.push(it)
}
}
fun exitContractDescription() {
lastNodes.pop()
exitTargetsForTry.pop()
popGraph()
}
// -------------------------------------------------------------------------------------------------------------------------
fun reset() {
exitsOfAnonymousFunctions.clear()
exitsFromCompletedPostponedAnonymousFunctions.clear()
lastNodes.reset()
}
fun dropSubgraphFromCall(call: FirFunctionCall) {
val graphs = mutableListOf<ControlFlowGraph>()
call.acceptChildren(object : FirDefaultVisitor<Unit, Any?>() {
override fun visitElement(element: FirElement, data: Any?) {
element.acceptChildren(this, null)
}
override fun visitAnonymousFunction(anonymousFunction: FirAnonymousFunction, data: Any?) {
anonymousFunction.controlFlowGraphReference?.accept(this, null)
}
override fun visitAnonymousObject(anonymousObject: FirAnonymousObject, data: Any?) {
anonymousObject.controlFlowGraphReference?.accept(this, null)
}
override fun visitControlFlowGraphReference(controlFlowGraphReference: FirControlFlowGraphReference, data: Any?) {
val graph = controlFlowGraphReference.controlFlowGraph ?: return
if (graph.owner == null) return
graphs += graph
}
}, null)
for (graph in graphs) {
currentGraph.removeSubGraph(graph)
}
}
// ----------------------------------- Edge utils -----------------------------------
private fun addNewSimpleNode(
node: CFGNode<*>,
isDead: Boolean = false,
preferredKind: EdgeKind = EdgeKind.Forward
): CFGNode<*> {
val lastNode = lastNodes.pop()
addEdge(lastNode, node, isDead = isDead, preferredKind = preferredKind)
lastNodes.push(node)
return lastNode
}
private fun addNodeThatReturnsNothing(node: CFGNode<*>, preferredKind: EdgeKind = EdgeKind.Forward) {
// If an expression, which returns Nothing, ...(1)
val targetNode = when {
tryExitNodes.isEmpty -> {
// (1)... isn't inside a try expression, that is an uncaught exception path.
exitTargetsForTry.top()
}
// (1)... inside a try expression...(2)
finallyEnterNodes.topOrNull()?.level == levelCounter -> {
// (2)... with finally
// Either in try-main or catch. Route to `finally`
finallyEnterNodes.top()
}
// (2)... without finally or within finally ...(3)
tryExitNodes.top().fir.finallyBlock == null -> {
// (3)... without finally ...(4)
// Either in try-main or catch.
if (tryMainExitNodes.top().followingNodes.isNotEmpty()) {
// (4)... in catch, i.e., re-throw.
exitTargetsForTry.top()
} else {
// (4)... in try-main. Route to exit of try main block.
// We already have edges from the exit of try main block to each catch clause.
// This edge makes the remaining part of try main block, e.g., following `when` branches, marked as dead.
tryMainExitNodes.top()
}
}
// (3)... within finally.
else -> exitTargetsForTry.top()
}
if (targetNode is TryMainBlockExitNode) {
val catches = targetNode.fir.catches
if (catches.isEmpty()) {
addNodeWithJump(node, exitTargetsForTry.top(), preferredKind, label = UncaughtExceptionPath)
} else {
//edges to all the catches
addNodeWithJumpToCatches(node, catches.map { catchNodeStorage[it]!! }, preferredKind = preferredKind)
}
} else {
addNodeWithJump(node, targetNode, preferredKind, label = UncaughtExceptionPath)
}
}
private fun addNodeWithJump(
node: CFGNode<*>,
targetNode: CFGNode<*>?,
preferredKind: EdgeKind = EdgeKind.Forward,
isBack: Boolean = false,
label: EdgeLabel = NormalPath,
labelForFinallyBLock: EdgeLabel = label,
trackJump: Boolean = false
) {
popAndAddEdge(node, preferredKind)
if (targetNode != null) {
if (isBack) {
if (targetNode is LoopEnterNode) {
// `continue` to the loop header
addBackEdge(node, targetNode, label = LoopBackPath)
} else {
addBackEdge(node, targetNode, label = label)
}
} else {
// go through all final nodes between node and target
val finallyNodes = finallyBefore(targetNode)
val finalFrom = finallyNodes.fold(node) { from, (finallyEnter, tryExit) ->
addEdgeIfNotExist(from, finallyEnter, propagateDeadness = false, label = labelForFinallyBLock)
tryExit
}
addEdgeIfNotExist(
finalFrom,
targetNode,
propagateDeadness = false,
label = if (finallyNodes.isEmpty()) label else labelForFinallyBLock
)
if (trackJump && finallyNodes.isNotEmpty()) {
//actually we can store all returns like this, but not sure if it makes anything better
nonDirectJumps.put(targetNode, node)
}
}
}
val stub = createStubNode()
addEdge(node, stub)
lastNodes.push(stub)
}
private fun addNodeWithJumpToCatches(
node: CFGNode<*>,
targets: List<CatchClauseEnterNode>,
label: EdgeLabel = UncaughtExceptionPath,
preferredKind: EdgeKind = EdgeKind.Forward
) {
require(targets.isNotEmpty())
popAndAddEdge(node, preferredKind)
targets.forEach { target ->
addEdge(node, target, propagateDeadness = false, label = label)
}
val stub = createStubNode()
addEdge(node, stub)
lastNodes.push(stub)
}
private fun finallyBefore(target: CFGNode<*>): List<Pair<FinallyBlockEnterNode, FinallyBlockExitNode>> {
return finallyEnterNodes.all().takeWhile { it.level > target.level }.map { finallyEnter ->
val finallyExit = finallyExitNodes[finallyEnter.fir]!!
finallyEnter to finallyExit
}
}
private fun popAndAddEdge(to: CFGNode<*>, preferredKind: EdgeKind = EdgeKind.Forward) {
addEdge(lastNodes.pop(), to, preferredKind = preferredKind)
}
private fun addEdgeIfNotExist(
from: CFGNode<*>,
to: CFGNode<*>,
propagateDeadness: Boolean = true,
isDead: Boolean = false,
preferredKind: EdgeKind = EdgeKind.Forward,
label: EdgeLabel = NormalPath
) {
if (!from.followingNodes.contains(to)) {
addEdge(from, to, propagateDeadness, isDead, preferredKind = preferredKind, label = label)
}
}
private fun addEdge(
from: CFGNode<*>,
to: CFGNode<*>,
propagateDeadness: Boolean = true,
isDead: Boolean = false,
isBack: Boolean = false,
preferredKind: EdgeKind = EdgeKind.Forward,
label: EdgeLabel = NormalPath
) {
val kind = if (isDead || from.isDead || to.isDead) {
if (isBack) EdgeKind.DeadBackward else EdgeKind.DeadForward
} else preferredKind
CFGNode.addEdge(from, to, kind, propagateDeadness, label)
}
private fun addBackEdge(
from: CFGNode<*>,
to: CFGNode<*>,
isDead: Boolean = false,
label: EdgeLabel = NormalPath
) {
addEdge(from, to, propagateDeadness = false, isDead = isDead, isBack = true, preferredKind = EdgeKind.CfgBackward, label = label)
}
private fun propagateDeadnessForward(node: CFGNode<*>, deep: Boolean = false) {
if (!node.isDead) return
node.followingNodes
.filter { node.outgoingEdges.getValue(it).kind == EdgeKind.Forward }
.forEach { target ->
CFGNode.addJustKindEdge(node, target, EdgeKind.DeadForward, false)
target.updateDeadStatus()
if (deep) {
propagateDeadnessForward(target, true)
}
}
}
// ----------------------------------- Utils -----------------------------------
private inline fun Collection<FirDeclaration>.forEachMember(block: (FirDeclaration) -> Unit) {
for (member in this) {
for (callableDeclaration in member.unwrap()) {
block(callableDeclaration)
}
}
}
private fun FirDeclaration.unwrap(): List<FirDeclaration> =
when (this) {
is FirFunction, is FirAnonymousInitializer -> listOf(this)
is FirProperty -> listOfNotNull(this.getter, this.setter, this)
else -> emptyList()
}
private fun addNewSimpleNodeIfPossible(newNode: CFGNode<*>, isDead: Boolean = false): CFGNode<*>? {
if (lastNodes.isEmpty) return null
return addNewSimpleNode(newNode, isDead)
}
private fun <R> withLevelOfNode(node: CFGNode<*>, f: () -> R): R {
val last = levelCounter
levelCounter = node.level
try {
return f()
} finally {
levelCounter = last
}
}
}
fun FirDeclaration?.isLocalClassOrAnonymousObject() = ((this as? FirRegularClass)?.isLocal == true) || this is FirAnonymousObject
| kotlin | -1 | 0 | 0 | 0 | 0 | starcoderdata |
<gh_stars>1-10
package com.costular.atomtasks.ui.util
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.costular.atomtasks.R
import com.costular.atomtasks.ui.util.DateTimeFormatters.timeFormatter
import java.time.LocalDate
import java.time.LocalTime
object DateUtils {
fun datesBetween(start: LocalDate, end: LocalDate): List<LocalDate> {
var localStart = start
val dates = mutableListOf<LocalDate>()
while (!localStart.isAfter(end)) {
dates.add(localStart)
localStart = localStart.plusDays(1)
}
return dates
}
@Composable
fun dayAsText(day: LocalDate): String {
return when (day) {
LocalDate.now() -> stringResource(R.string.day_today)
LocalDate.now().minusDays(1) -> stringResource(R.string.day_yesterday)
LocalDate.now().plusDays(1) -> stringResource(R.string.day_tomorrow)
else -> DateTimeFormatters.dateFormatter.format(day)
}
}
@Composable
fun timeAsText(time: LocalTime): String =
timeFormatter.format(time)
}
| kotlin | 17 | 0.676056 | 82 | 30.555556 | 36 | starcoderdata |
<filename>src/main/kotlin/jp/nephy/vrchakt/models/Error.kt
package jp.nephy.vrchakt.models
import jp.nephy.jsonkt.JsonObject
import jp.nephy.jsonkt.delegation.int
import jp.nephy.jsonkt.delegation.model
import jp.nephy.jsonkt.delegation.string
data class Error(override val json: JsonObject): VRChaKtModel {
val message by string
val statusCode by int("status_code")
data class Result(override val json: JsonObject): VRChaKtModel {
val error by model<Error>()
}
}
| kotlin | 12 | 0.761711 | 68 | 29.6875 | 16 | starcoderdata |
<filename>stripe/src/main/java/com/stripe/android/paymentsheet/ui/PrimaryButtonAnimator.kt
package com.stripe.android.paymentsheet.ui
import android.animation.ObjectAnimator
import android.content.Context
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.core.animation.doOnEnd
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import com.stripe.android.R
internal class PrimaryButtonAnimator(
private val context: Context
) {
private val slideAnimationDuration = context.resources
.getInteger(android.R.integer.config_shortAnimTime)
.toLong()
internal fun fadeIn(
view: View,
parentWidth: Int,
onAnimationEnd: () -> Unit
) {
view.startAnimation(
AnimationUtils.loadAnimation(
context,
R.anim.stripe_paymentsheet_transition_fade_in
).also { animation ->
animation.setAnimationListener(
object : Animation.AnimationListener {
override fun onAnimationStart(p0: Animation?) {
view.isVisible = true
}
override fun onAnimationEnd(p0: Animation?) {
view.isVisible = true
slideToCenter(view, parentWidth, onAnimationEnd)
}
override fun onAnimationRepeat(p0: Animation?) {
}
}
)
}
)
}
// slide the view to the horizontal center of the parent view
private fun slideToCenter(
view: View,
parentWidth: Int,
onAnimationEnd: () -> Unit
) {
val iconCenter = view.left + (view.right - view.left) / 2f
val targetX = iconCenter - parentWidth / 2f
ObjectAnimator.ofFloat(
view,
"translationX",
0f,
-targetX
).also { animator ->
animator.duration = slideAnimationDuration
animator.doOnEnd {
onAnimationEnd()
}
}.start()
}
internal fun fadeOut(view: View) {
view.startAnimation(
AnimationUtils.loadAnimation(
context,
R.anim.stripe_paymentsheet_transition_fade_out
).also { animation ->
animation.setAnimationListener(
object : Animation.AnimationListener {
override fun onAnimationStart(p0: Animation?) {
view.isVisible = true
}
override fun onAnimationEnd(p0: Animation?) {
view.isInvisible = true
}
override fun onAnimationRepeat(p0: Animation?) {
}
}
)
}
)
}
}
| kotlin | 28 | 0.531209 | 90 | 30.708333 | 96 | starcoderdata |
package org.gradle.kotlin.dsl.support
import org.gradle.kotlin.dsl.fixtures.TestWithTempFiles
import org.gradle.kotlin.dsl.fixtures.classLoaderFor
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
class KotlinCompilerTest : TestWithTempFiles() {
@Test
fun `can compile Kotlin source file into jar`() {
val sourceFile =
newFile("DeepThought.kt", """
package hhgttg
class DeepThought {
fun compute(): Int = 42
}
""")
val outputJar = newFile("output.jar")
compileToJar(outputJar, listOf(sourceFile), loggerFor<KotlinCompilerTest>())
val answer =
classLoaderFor(outputJar).use { it
.loadClass("hhgttg.DeepThought")
.newInstance()
.run {
this::class.java.getMethod("compute").invoke(this)
}
}
assertThat(
answer,
equalTo<Any>(42))
assert(outputJar.delete())
}
}
| kotlin | 24 | 0.571557 | 84 | 24.25 | 44 | starcoderdata |
package pl.dawidfiruzek.dagger2android.util.injection
import dagger.Module
import dagger.Provides
import org.greenrobot.eventbus.EventBus
import pl.dawidfiruzek.dagger2android.feature.main.MainFragmentContract
import pl.dawidfiruzek.dagger2android.feature.main.navigation.MainFragmentRouter
import pl.dawidfiruzek.dagger2android.feature.main.presentation.MainFragmentPresenter
import pl.dawidfiruzek.dagger2android.feature.main.ui.MainFragment
@Module
class MainFragmentModule {
@Provides
fun view(fragment: MainFragment): MainFragmentContract.View = fragment
@Provides
fun router(eventBus: EventBus): MainFragmentContract.Router =
MainFragmentRouter(eventBus)
@Provides
fun presenter(view: MainFragmentContract.View, router: MainFragmentContract.Router): MainFragmentContract.Presenter =
MainFragmentPresenter(view, router)
}
| kotlin | 9 | 0.814773 | 121 | 35.666667 | 24 | starcoderdata |
<filename>domain-layer/src/main/kotlin/org/deafsapps/android/githubbrowser/domainlayer/domain/DomainBo.kt<gh_stars>1-10
package org.deafsapps.android.githubbrowser.domainlayer.domain
private const val DEFAULT_STRING_RESOURCE = -1
data class DataRepoBoWrapper(
val totalCount: Int,
val incompleteResults: Boolean,
val items: List<DataRepoBo>
)
data class DataRepoBo(
val id: Long,
val name: String,
val owner: OwnerBo,
val htmlUrl: String,
val description: String,
val stars: Int,
val forks: Int,
val language: String
)
data class OwnerBo(
val login: String,
val profilePic: String,
val type: String
)
sealed class FailureBo(var msgRes: Int = DEFAULT_STRING_RESOURCE) {
class NoConnection(msgRes: Int): FailureBo(msgRes = msgRes)
class InputParamsError(msgRes: Int) : FailureBo(msgRes = msgRes)
class RequestError(msgRes: Int) : FailureBo(msgRes = msgRes)
class NoCachedData(msgRes: Int) : FailureBo(msgRes = msgRes)
class ServerError(msgRes: Int) : FailureBo(msgRes = msgRes)
class NoData(msgRes: Int) : FailureBo(msgRes = msgRes)
class Unknown(msgRes: Int) : FailureBo(msgRes = msgRes)
} | kotlin | 15 | 0.723874 | 119 | 30.837838 | 37 | starcoderdata |
package demo.nitin.tumblr_android_demo.base
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.ncapdevi.fragnav.FragNavController
import com.ncapdevi.fragnav.FragNavTransactionOptions
import demo.nitin.tumblr_android_demo.R
import demo.nitin.tumblr_android_demo.features.dashboard.DashboardFragment
import demo.nitin.tumblr_android_demo.features.following.FollowingFragment
import demo.nitin.tumblr_android_demo.features.likes.LikesFragment
import kotlinx.android.synthetic.main.activity_main.*
/**
* Base activity defining the UI components and fragment navigation
* @author - <NAME>
* @since - 11/17/2019
*/
class MainActivity : AppCompatActivity(), FragNavController.RootFragmentListener {
companion object {
const val DASHBOARD = 0
const val FOLLOWING = 1
const val LIKES = 2
const val MAX_NUM_TABS = 3
}
private lateinit var fragNavController: FragNavController
override val numberOfRootFragments: Int =
MAX_NUM_TABS
override fun getRootFragment(index: Int): Fragment {
// return the root fragment for each tab
return when (index) {
DASHBOARD -> DashboardFragment.newInstance()
FOLLOWING -> FollowingFragment.newInstance()
LIKES -> LikesFragment.newInstance()
else -> DashboardFragment.newInstance()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fragNavController =
FragNavController(supportFragmentManager, R.id.content_container).apply {
rootFragmentListener = this@MainActivity
initialize(DASHBOARD, savedInstanceState)
}
initNavigationBar()
}
override fun onBackPressed() {
if (!fragNavController.isRootFragment) {
popFragment()
} else {
super.onBackPressed()
}
}
fun pushFragment(fragment: Fragment) {
val options = FragNavTransactionOptions
.newBuilder()
.customAnimations(
R.anim.enter_from_bottom_animation,
0,
R.anim.enter_from_bottom_animation,
0
)
.allowStateLoss(false)
.build()
fragNavController.pushFragment(fragment, options)
}
fun popFragment() {
val options = FragNavTransactionOptions
.newBuilder()
.customAnimations(
0,
R.anim.exit_to_bottom_animation,
0,
R.anim.exit_to_bottom_animation
)
.allowStateLoss(false)
.build()
fragNavController.popFragment(options)
}
private fun initNavigationBar() {
navigation_bar?.setOnNavigationItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.dashboard -> {
fragNavController.switchTab(DASHBOARD)
}
R.id.following -> {
fragNavController.switchTab(FOLLOWING)
}
R.id.likes -> {
fragNavController.switchTab(LIKES)
}
}
true
}
}
}
| kotlin | 19 | 0.610436 | 85 | 30.231481 | 108 | starcoderdata |
package com.okhttpinspector.spring.internal.support
import android.app.IntentService
import android.content.Intent
import com.okhttpinspector.spring.internal.data.SpringContentProvider
class ClearTransactionsService : IntentService("Spring-ClearTransactionsService") {
override fun onHandleIntent(intent: Intent?) {
contentResolver.delete(SpringContentProvider.TRANSACTION_URI, null, null)
NotificationHelper.clearBuffer()
val notificationHelper = NotificationHelper(this)
notificationHelper.dismiss()
}
} | kotlin | 12 | 0.791971 | 83 | 35.6 | 15 | starcoderdata |
package com.frogobox.recycler.core
import androidx.viewbinding.ViewBinding
/*
* Created by faisalamir on 11/12/21
* FrogoRecyclerView
* -----------------------------------------
* Name : <NAME>
* E-mail : <EMAIL>
* Github : github.com/amirisback
* -----------------------------------------
* Copyright (C) 2021 FrogoBox Inc.
* All rights reserved
*
*/
interface FrogoRecyclerBindingListener<T, VB : ViewBinding> {
// on itemview set on click listener
fun onItemClicked(
binding: VB,
data: T,
position: Int,
notifyListener: FrogoRecyclerNotifyListener<T>
)
// on itemview set on long click listener
fun onItemLongClicked(
binding: VB,
data: T,
position: Int,
notifyListener: FrogoRecyclerNotifyListener<T>
)
} | kotlin | 10 | 0.574186 | 61 | 20.842105 | 38 | starcoderdata |
<reponame>intellij-rainbow-brackets/intellij-rainbow-brackets
package com.github.izhangzhihao.rainbow.brackets.annotator
import com.github.izhangzhihao.rainbow.brackets.RainbowHighlighter
import com.github.izhangzhihao.rainbow.brackets.RainbowHighlighter.getTextAttributes
import com.github.izhangzhihao.rainbow.brackets.annotator.RainbowUtils.annotateUtil
import com.github.izhangzhihao.rainbow.brackets.annotator.RainbowUtils.settings
import com.github.izhangzhihao.rainbow.brackets.settings.RainbowSettings
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.source.tree.LeafPsiElement
class RainbowAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (settings.isRainbowEnabled && element is LeafPsiElement) {
if (settings.isEnableRainbowRoundBrackets) annotateUtil(element, holder, "(", ")", RainbowHighlighter.NAME_ROUND_BRACKETS)
if (settings.isEnableRainbowSquareBrackets) annotateUtil(element, holder, "[", "]", RainbowHighlighter.NAME_SQUARE_BRACKETS)
if (settings.isEnableRainbowSquigglyBrackets) annotateUtil(element, holder, "{", "}", RainbowHighlighter.NAME_SQUIGGLY_BRACKETS)
if (settings.isEnableRainbowAngleBrackets) annotateUtil(element, holder, "<", ">", RainbowHighlighter.NAME_ANGLE_BRACKETS)
}
}
}
object RainbowUtils {
val settings = RainbowSettings.instance
fun annotateUtil(element: LeafPsiElement, holder: AnnotationHolder,
LEFT: String, RIGHT: String, rainbowName: String) {
fun getBracketLevel(element: LeafPsiElement): Int {
//Using `element.elementType.toString()` if we didn't want add more dependencies.
var level = if (element.text == RIGHT) 1 else 0
tailrec fun iterateParents(currentNode: PsiElement) {
tailrec fun iterateChildren(currentChild: PsiElement) {
if (currentChild is LeafPsiElement) {
//Using `currentChild.elementType.toString()` if we didn't want add more dependencies.
when (currentChild.text) {
LEFT -> level++
RIGHT -> level--
}
}
if ((currentChild != currentNode) && (currentChild != currentNode.parent.lastChild)) {
iterateChildren(currentChild.nextSibling)
}
}
if (currentNode.parent !is PsiFile) {
iterateChildren(currentNode.parent.firstChild)
iterateParents(currentNode.parent)
}
}
iterateParents(element)
return level
}
//Using `element.elementType.toString()` if we didn't want add more dependencies.
val level = when (element.text) {
LEFT, RIGHT -> getBracketLevel(element)
else -> 0
}
val scheme = EditorColorsManager.getInstance().globalScheme
if (level > 0) {
holder.createInfoAnnotation(element.psi, null).enforcedTextAttributes = getTextAttributes(scheme, rainbowName, level)
}
}
} | kotlin | 24 | 0.66374 | 140 | 48.536232 | 69 | starcoderdata |
<filename>kotlinx-coroutines-core/jvm/src/internal/MainDispatchers.kt<gh_stars>1-10
package kotlinx.coroutines.internal
import kotlinx.coroutines.*
import java.util.*
import kotlin.coroutines.*
/**
* Name of the boolean property that enables using of [FastServiceLoader].
*/
private const val FAST_SERVICE_LOADER_PROPERTY_NAME = "kotlinx.coroutines.fast.service.loader"
// Lazy loader for the main dispatcher
internal object MainDispatcherLoader {
private val FAST_SERVICE_LOADER_ENABLED = systemProp(FAST_SERVICE_LOADER_PROPERTY_NAME, true)
@JvmField
val dispatcher: MainCoroutineDispatcher = loadMainDispatcher()
private fun loadMainDispatcher(): MainCoroutineDispatcher {
return try {
val factories = if (FAST_SERVICE_LOADER_ENABLED) {
MainDispatcherFactory::class.java.let { clz ->
FastServiceLoader.load(clz, clz.classLoader)
}
} else {
//We are explicitly using the
//`ServiceLoader.load(MyClass::class.java, MyClass::class.java.classLoader).iterator()`
//form of the ServiceLoader call to enable R8 optimization when compiled on Android.
ServiceLoader.load(
MainDispatcherFactory::class.java,
MainDispatcherFactory::class.java.classLoader
).iterator().asSequence().toList()
}
factories.maxBy { it.loadPriority }?.tryCreateDispatcher(factories)
?: MissingMainCoroutineDispatcher(null)
} catch (e: Throwable) {
// Service loader can throw an exception as well
MissingMainCoroutineDispatcher(e)
}
}
}
/**
* If anything goes wrong while trying to create main dispatcher (class not found,
* initialization failed, etc), then replace the main dispatcher with a special
* stub that throws an error message on any attempt to actually use it.
*
* @suppress internal API
*/
@InternalCoroutinesApi
public fun MainDispatcherFactory.tryCreateDispatcher(factories: List<MainDispatcherFactory>): MainCoroutineDispatcher =
try {
createDispatcher(factories)
} catch (cause: Throwable) {
MissingMainCoroutineDispatcher(cause, hintOnError())
}
/** @suppress */
@InternalCoroutinesApi
public fun MainCoroutineDispatcher.isMissing(): Boolean = this is MissingMainCoroutineDispatcher
private class MissingMainCoroutineDispatcher(
private val cause: Throwable?,
private val errorHint: String? = null
) : MainCoroutineDispatcher(), Delay {
override val immediate: MainCoroutineDispatcher get() = this
override fun isDispatchNeeded(context: CoroutineContext): Boolean {
missing()
}
override suspend fun delay(time: Long) {
missing()
}
override fun invokeOnTimeout(timeMillis: Long, block: Runnable): DisposableHandle {
missing()
}
override fun dispatch(context: CoroutineContext, block: Runnable) =
missing()
override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) =
missing()
private fun missing(): Nothing {
if (cause == null) {
throw IllegalStateException(
"Module with the Main dispatcher is missing. " +
"Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android'"
)
} else {
val message = "Module with the Main dispatcher had failed to initialize" + (errorHint?.let { ". $it" } ?: "")
throw IllegalStateException(message, cause)
}
}
override fun toString(): String = "Main[missing${if (cause != null) ", cause=$cause" else ""}]"
}
/**
* @suppress
*/
@InternalCoroutinesApi
public object MissingMainCoroutineDispatcherFactory : MainDispatcherFactory {
override val loadPriority: Int
get() = -1
override fun createDispatcher(allFactories: List<MainDispatcherFactory>): MainCoroutineDispatcher {
return MissingMainCoroutineDispatcher(null)
}
} | kotlin | 36 | 0.673584 | 121 | 34.626087 | 115 | starcoderdata |
package com.example.android.navigation
import androidx.databinding.DataBindingUtil
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.appcompat.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import com.example.android.navigation.databinding.FragmentQuestionsBinding
class QuestionsFragment : Fragment() {
data class Question(
val text: String,
val answers: List<String>)
private val questions: MutableList<Question> = mutableListOf(
Question(text = "Nuclear sizes are expressed in a unit named",
answers = listOf("Fermi", "Newton", "Tesla", "Angstrom")),
Question(text = "The speed of light will be minimum while passing through",
answers = listOf("Glass", "Water", "Air", "Vaccum")),
Question(text = "Which of the following is not a vector quantity?",
answers = listOf("Speed", "Velocity", "Torque", "Displacement")),
Question(text = "Which of the following is not the unit of time",
answers = listOf("Parallactic second ", "Micro Second", "Solar Day", "Leap Year")),
Question(text = "An air bubble in water will act like a",
answers = listOf("Concave Lens", "Convex Lens", "Concave Mirror", "Convex Mirror")),
Question(text = "A solid ball of metal has a spherical cavity inside it.When the ball is heated the volume of the cavity will",
answers = listOf("increase", "decrease", "remain unaffected", "have its shape changed")),
Question(text = "It is more difficult to walk on ice than on a concrete road because ",
answers = listOf("there is very little friction between the ice and feet pressing it", " ice is soft when compared to concrete", " there is more friction between the ice and feet", "None of these")),
Question(text = "Rain drops acquire spherical shape due to ",
answers = listOf("surface tension", "Viscosity", "Elasticity", "friction")),
Question(text = "If a sound travels from air to water, the quantity that remain unchanged is",
answers = listOf("frequency", "velocity", "amplitude", "wavelength")),
Question(text = "Air pressure is usually highest when the air is ",
answers = listOf("cool and moist", "warm and moist", "warm and dry", "cool and dry")),
Question(text = "Sound following a flash of lightning is called",
answers = listOf("Thunder", "Stoning", "Cloud Clash", "Bolting")),
Question(text = "When a bottle of perfume is opened in one corner of a room the smell spreads soon throughout the room.This is an example of ",
answers = listOf("diffusion", "viscosity", "capillarity", "surface tension")),
Question(text = "The rate of change of linear momentum of a body falling freely under gravity is equal to it's ____ ?",
answers = listOf("Weight", "Kinetic Energy", "Potential Energy", "Impulse")),
Question(text = "Which is best used as a sound absorbing material in partition walls ?",
answers = listOf("Glass - wool", "Glass pieces", "Steel", "Stone Chips")),
Question(text = "The minimum number of Non zero non collinear vectors required to produce a zero vector is",
answers = listOf("3", "4", "2", "1")),
Question(text = "Pieces of camphor placed on water move about rapidly. This is because of",
answers = listOf("surface tension","diffusion", "viscosity", "capillarity")),
Question(text = "Mirage is an example of",
answers = listOf("Total Internal Reflection", "reflection", "refraction", "dispersion")),
Question(text = "No current will flow between two charged bodies if they have the same ",
answers = listOf("potential", "resistance", "charge", "charge/potential ratio")),
Question(text = "A periscope works by the principle of",
answers = listOf("total internal reflection", "diffraction", "refraction", "reflection")),
Question(text = "The core of an electromagnet is made of soft iron because soft iron has",
answers = listOf("large susceptibility and small retentivity", "small density and large retentivity", "large density and large retentivity", " small susceptibility and small retentivity"))
)
lateinit var currentQuestion: Question
lateinit var answers: MutableList<String>
private var questionIndex = 0
private val numQuestions = 5
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding = DataBindingUtil.inflate<FragmentQuestionsBinding>(
inflater, R.layout.fragment_questions, container, false)
randomizeQuestions()
binding.game = this
binding.submitButton.setOnClickListener { view: View ->
val checkedId = binding.questionRadioGroup.checkedRadioButtonId
if (-1 != checkedId) {
var answerIndex = 0
when (checkedId) {
R.id.secondAnswerRadioButton -> answerIndex = 1
R.id.thirdAnswerRadioButton -> answerIndex = 2
R.id.fourthAnswerRadioButton -> answerIndex = 3
}
if (answers[answerIndex] == currentQuestion.answers[0]) {
questionIndex++
if (questionIndex < numQuestions) {
currentQuestion = questions[questionIndex]
setQuestion()
binding.invalidateAll()
} else {
view.findNavController().navigate(QuestionsFragmentDirections.actionGameFragmentToCongratulationFragment(numQuestions,questionIndex))
}
} else {
view.findNavController().navigate(QuestionsFragmentDirections.actionGameFragmentToLostFragment())
}
}
}
return binding.root
}
private fun randomizeQuestions() {
questions.shuffle()
questionIndex = 0
setQuestion()
}
private fun setQuestion() {
currentQuestion = questions[questionIndex]
answers = currentQuestion.answers.toMutableList()
answers.shuffle()
(activity as AppCompatActivity).supportActionBar?.title = getString(R.string.madScientistGameQuestions, questionIndex + 1, numQuestions)
}
}
| kotlin | 28 | 0.621917 | 220 | 51.312977 | 131 | starcoderdata |
<reponame>jenkinsci/git-automerger-plugin<gh_stars>1-10
package com.vinted.automerger.plugin
import org.slf4j.spi.LocationAwareLogger
enum class LogLevel {
TRACE, DEBUG, INFO, WARN, ERROR;
val levelInt: Int
get() = when (this) {
TRACE -> LocationAwareLogger.TRACE_INT
DEBUG -> LocationAwareLogger.DEBUG_INT
INFO -> LocationAwareLogger.INFO_INT
WARN -> LocationAwareLogger.WARN_INT
ERROR -> LocationAwareLogger.ERROR_INT
}
}
| kotlin | 10 | 0.655577 | 55 | 29.058824 | 17 | starcoderdata |
<reponame>jnthn/intellij-community
// 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.lang.java.actions
import com.intellij.codeInsight.daemon.QuickFixBundle.message
import com.intellij.codeInsight.generation.GenerateMembersUtil.generateSimpleGetterPrototype
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.lang.java.beans.PropertyKind
import com.intellij.lang.jvm.actions.CreateMethodRequest
import com.intellij.lang.jvm.actions.CreateReadOnlyPropertyActionGroup
import com.intellij.lang.jvm.actions.JvmActionGroup
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiFile
import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass
/**
* This action renders a read-only property (field + getter) in Java class when getter is requested.
*/
internal class CreateGetterWithFieldAction(target: PsiClass, request: CreateMethodRequest) : CreatePropertyActionBase(target, request) {
override fun getActionGroup(): JvmActionGroup = CreateReadOnlyPropertyActionGroup
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
return super.isAvailable(project, editor, file) && propertyInfo.second != PropertyKind.SETTER
}
override fun getText(): String {
return message("create.read.only.property.from.usage.full.text", getPropertyName(), getNameForClass(target, false))
}
override fun createRenderer(project: Project) = object : PropertyRenderer(project, target, request, propertyInfo) {
override fun fillTemplate(builder: TemplateBuilderImpl): RangeExpression? {
val prototypeField = generatePrototypeField()
val prototype = generateSimpleGetterPrototype(prototypeField)
val accessor = insertAccessor(prototype) ?: return null
val data = accessor.extractGetterTemplateData()
return builder.setupInput(data)
}
}
}
| kotlin | 16 | 0.802619 | 140 | 46.953488 | 43 | starcoderdata |
// !DIAGNOSTICS: -UNUSED_PARAMETER
class Example {
public fun plus(o: Example) = o
public operator fun minus(o: Example) = o
public fun get(i: Int) = ""
public operator fun get(s: String) = ""
public fun set(i: Int, v: String) {}
public operator fun set(s: String, v: String) {}
public fun not() = false
public fun rangeTo(o: Example) = o
public fun contains(o: Example) = false
public fun compareTo(o: Example) = 0
public fun inc() = this
public fun dec() = this
public fun invoke() {}
}
class Example2 {
public operator fun not() = true
public fun plusAssign(o: Example2) {}
public operator fun minusAssign(o: Example2) {}
public operator fun rangeTo(o: Example2) = o
public operator fun contains(o: Example2) = false
public operator fun compareTo(o: Example2) = 0
public operator fun inc() = this
public operator fun dec() = this
public operator fun invoke() {}
}
fun test() {
var a = Example()
var b = Example()
var c = Example2()
var d = Example2()
Example() == Example()
a == b
c != d
Example() + Example()
a + b
a - b
a[1]
a["str"]
a[1] = "A"
a["str"] = "str"
a.plus(b)
a.minus(b)
a.get(1)
a.get("str")
c += d
c -= d
a..b
c..d
Example()..Example()
Example2()..Example2()
a < b
a >= b
c > d
a in b
c in d
a++
a--
c++
c--
!a
!c
a()
c()
Example()()
Example2()()
}
abstract class Base {
abstract operator fun plus(o: Base): Base
abstract fun minus(o: Base): Base
}
open class Anc : Base() {
override fun plus(o: Base) = o
override fun minus(o: Base) = o
}
class Anc2 : Anc()
fun test2() {
Anc() + Anc()
Anc() - Anc()
Anc2() + Anc2()
}
fun Int.iterator(): MyIntIterator = null!!
operator fun Double.iterator(): MyDoubleIterator = null!!
operator fun Boolean.iterator(): MyBooleanIterator = null!!
interface MyIntIterator {
operator fun hasNext(): Boolean
operator fun next(): Int
}
interface MyDoubleIterator {
operator fun hasNext(): Boolean
fun next(): Double
}
interface MyBooleanIterator {
fun hasNext(): Boolean
operator fun next(): Boolean
}
fun test3(i: Int, d: Double, b: Boolean) {
for (element in <!OPERATOR_MODIFIER_REQUIRED!>i<!>) {}
for (element in <!OPERATOR_MODIFIER_REQUIRED!>d<!>) {}
for (element in <!OPERATOR_MODIFIER_REQUIRED!>b<!>) {}
}
| kotlin | 24 | 0.578779 | 59 | 16.780142 | 141 | starcoderdata |
<reponame>Vritra4/terra.proto<gh_stars>1-10
//Generated by the protocol buffer compiler. DO NOT EDIT!
// source: ibc/core/channel/v1/tx.proto
package ibc.core.channel.v1;
@kotlin.jvm.JvmSynthetic
inline fun msgChannelOpenConfirm(block: ibc.core.channel.v1.MsgChannelOpenConfirmKt.Dsl.() -> Unit): ibc.core.channel.v1.Tx.MsgChannelOpenConfirm =
ibc.core.channel.v1.MsgChannelOpenConfirmKt.Dsl._create(ibc.core.channel.v1.Tx.MsgChannelOpenConfirm.newBuilder()).apply { block() }._build()
object MsgChannelOpenConfirmKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker
class Dsl private constructor(
@kotlin.jvm.JvmField private val _builder: ibc.core.channel.v1.Tx.MsgChannelOpenConfirm.Builder
) {
companion object {
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _create(builder: ibc.core.channel.v1.Tx.MsgChannelOpenConfirm.Builder): Dsl = Dsl(builder)
}
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _build(): ibc.core.channel.v1.Tx.MsgChannelOpenConfirm = _builder.build()
/**
* <code>string port_id = 1 [(.gogoproto.moretags) = "yaml:\"port_id\""];</code>
*/
var portId: kotlin.String
@JvmName("getPortId")
get() = _builder.getPortId()
@JvmName("setPortId")
set(value) {
_builder.setPortId(value)
}
/**
* <code>string port_id = 1 [(.gogoproto.moretags) = "yaml:\"port_id\""];</code>
*/
fun clearPortId() {
_builder.clearPortId()
}
/**
* <code>string channel_id = 2 [(.gogoproto.moretags) = "yaml:\"channel_id\""];</code>
*/
var channelId: kotlin.String
@JvmName("getChannelId")
get() = _builder.getChannelId()
@JvmName("setChannelId")
set(value) {
_builder.setChannelId(value)
}
/**
* <code>string channel_id = 2 [(.gogoproto.moretags) = "yaml:\"channel_id\""];</code>
*/
fun clearChannelId() {
_builder.clearChannelId()
}
/**
* <code>bytes proof_ack = 3 [(.gogoproto.moretags) = "yaml:\"proof_ack\""];</code>
*/
var proofAck: com.google.protobuf.ByteString
@JvmName("getProofAck")
get() = _builder.getProofAck()
@JvmName("setProofAck")
set(value) {
_builder.setProofAck(value)
}
/**
* <code>bytes proof_ack = 3 [(.gogoproto.moretags) = "yaml:\"proof_ack\""];</code>
*/
fun clearProofAck() {
_builder.clearProofAck()
}
/**
* <code>.ibc.core.client.v1.Height proof_height = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"proof_height\""];</code>
*/
var proofHeight: ibc.core.client.v1.Client.Height
@JvmName("getProofHeight")
get() = _builder.getProofHeight()
@JvmName("setProofHeight")
set(value) {
_builder.setProofHeight(value)
}
/**
* <code>.ibc.core.client.v1.Height proof_height = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"proof_height\""];</code>
*/
fun clearProofHeight() {
_builder.clearProofHeight()
}
/**
* <code>.ibc.core.client.v1.Height proof_height = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"proof_height\""];</code>
* @return Whether the proofHeight field is set.
*/
fun hasProofHeight(): kotlin.Boolean {
return _builder.hasProofHeight()
}
/**
* <code>string signer = 5;</code>
*/
var signer: kotlin.String
@JvmName("getSigner")
get() = _builder.getSigner()
@JvmName("setSigner")
set(value) {
_builder.setSigner(value)
}
/**
* <code>string signer = 5;</code>
*/
fun clearSigner() {
_builder.clearSigner()
}
}
}
@kotlin.jvm.JvmSynthetic
inline fun ibc.core.channel.v1.Tx.MsgChannelOpenConfirm.copy(block: ibc.core.channel.v1.MsgChannelOpenConfirmKt.Dsl.() -> Unit): ibc.core.channel.v1.Tx.MsgChannelOpenConfirm =
ibc.core.channel.v1.MsgChannelOpenConfirmKt.Dsl._create(this.toBuilder()).apply { block() }._build()
| kotlin | 19 | 0.628967 | 175 | 33.636364 | 121 | starcoderdata |
<reponame>Vritra4/terra.proto<gh_stars>1-10
//Generated by the protocol buffer compiler. DO NOT EDIT!
// source: ibc/core/connection/v1/tx.proto
package ibc.core.connection.v1;
@kotlin.jvm.JvmSynthetic
inline fun msgConnectionOpenTry(block: ibc.core.connection.v1.MsgConnectionOpenTryKt.Dsl.() -> Unit): ibc.core.connection.v1.Tx.MsgConnectionOpenTry =
ibc.core.connection.v1.MsgConnectionOpenTryKt.Dsl._create(ibc.core.connection.v1.Tx.MsgConnectionOpenTry.newBuilder()).apply { block() }._build()
object MsgConnectionOpenTryKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker
class Dsl private constructor(
@kotlin.jvm.JvmField private val _builder: ibc.core.connection.v1.Tx.MsgConnectionOpenTry.Builder
) {
companion object {
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _create(builder: ibc.core.connection.v1.Tx.MsgConnectionOpenTry.Builder): Dsl = Dsl(builder)
}
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _build(): ibc.core.connection.v1.Tx.MsgConnectionOpenTry = _builder.build()
/**
* <code>string client_id = 1 [(.gogoproto.moretags) = "yaml:\"client_id\""];</code>
*/
var clientId: kotlin.String
@JvmName("getClientId")
get() = _builder.getClientId()
@JvmName("setClientId")
set(value) {
_builder.setClientId(value)
}
/**
* <code>string client_id = 1 [(.gogoproto.moretags) = "yaml:\"client_id\""];</code>
*/
fun clearClientId() {
_builder.clearClientId()
}
/**
* <pre>
* in the case of crossing hello's, when both chains call OpenInit, we need
* the connection identifier of the previous connection in state INIT
* </pre>
*
* <code>string previous_connection_id = 2 [(.gogoproto.moretags) = "yaml:\"previous_connection_id\""];</code>
*/
var previousConnectionId: kotlin.String
@JvmName("getPreviousConnectionId")
get() = _builder.getPreviousConnectionId()
@JvmName("setPreviousConnectionId")
set(value) {
_builder.setPreviousConnectionId(value)
}
/**
* <pre>
* in the case of crossing hello's, when both chains call OpenInit, we need
* the connection identifier of the previous connection in state INIT
* </pre>
*
* <code>string previous_connection_id = 2 [(.gogoproto.moretags) = "yaml:\"previous_connection_id\""];</code>
*/
fun clearPreviousConnectionId() {
_builder.clearPreviousConnectionId()
}
/**
* <code>.google.protobuf.Any client_state = 3 [(.gogoproto.moretags) = "yaml:\"client_state\""];</code>
*/
var clientState: com.google.protobuf.Any
@JvmName("getClientState")
get() = _builder.getClientState()
@JvmName("setClientState")
set(value) {
_builder.setClientState(value)
}
/**
* <code>.google.protobuf.Any client_state = 3 [(.gogoproto.moretags) = "yaml:\"client_state\""];</code>
*/
fun clearClientState() {
_builder.clearClientState()
}
/**
* <code>.google.protobuf.Any client_state = 3 [(.gogoproto.moretags) = "yaml:\"client_state\""];</code>
* @return Whether the clientState field is set.
*/
fun hasClientState(): kotlin.Boolean {
return _builder.hasClientState()
}
/**
* <code>.ibc.core.connection.v1.Counterparty counterparty = 4 [(.gogoproto.nullable) = false];</code>
*/
var counterparty: ibc.core.connection.v1.Connection.Counterparty
@JvmName("getCounterparty")
get() = _builder.getCounterparty()
@JvmName("setCounterparty")
set(value) {
_builder.setCounterparty(value)
}
/**
* <code>.ibc.core.connection.v1.Counterparty counterparty = 4 [(.gogoproto.nullable) = false];</code>
*/
fun clearCounterparty() {
_builder.clearCounterparty()
}
/**
* <code>.ibc.core.connection.v1.Counterparty counterparty = 4 [(.gogoproto.nullable) = false];</code>
* @return Whether the counterparty field is set.
*/
fun hasCounterparty(): kotlin.Boolean {
return _builder.hasCounterparty()
}
/**
* <code>uint64 delay_period = 5 [(.gogoproto.moretags) = "yaml:\"delay_period\""];</code>
*/
var delayPeriod: kotlin.Long
@JvmName("getDelayPeriod")
get() = _builder.getDelayPeriod()
@JvmName("setDelayPeriod")
set(value) {
_builder.setDelayPeriod(value)
}
/**
* <code>uint64 delay_period = 5 [(.gogoproto.moretags) = "yaml:\"delay_period\""];</code>
*/
fun clearDelayPeriod() {
_builder.clearDelayPeriod()
}
/**
* An uninstantiable, behaviorless type to represent the field in
* generics.
*/
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
class CounterpartyVersionsProxy private constructor() : com.google.protobuf.kotlin.DslProxy()
/**
* <code>repeated .ibc.core.connection.v1.Version counterparty_versions = 6 [(.gogoproto.moretags) = "yaml:\"counterparty_versions\""];</code>
*/
val counterpartyVersions: com.google.protobuf.kotlin.DslList<ibc.core.connection.v1.Connection.Version, CounterpartyVersionsProxy>
@kotlin.jvm.JvmSynthetic
get() = com.google.protobuf.kotlin.DslList(
_builder.getCounterpartyVersionsList()
)
/**
* <code>repeated .ibc.core.connection.v1.Version counterparty_versions = 6 [(.gogoproto.moretags) = "yaml:\"counterparty_versions\""];</code>
* @param value The counterpartyVersions to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addCounterpartyVersions")
fun com.google.protobuf.kotlin.DslList<ibc.core.connection.v1.Connection.Version, CounterpartyVersionsProxy>.add(value: ibc.core.connection.v1.Connection.Version) {
_builder.addCounterpartyVersions(value)
}/**
* <code>repeated .ibc.core.connection.v1.Version counterparty_versions = 6 [(.gogoproto.moretags) = "yaml:\"counterparty_versions\""];</code>
* @param value The counterpartyVersions to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignCounterpartyVersions")
inline operator fun com.google.protobuf.kotlin.DslList<ibc.core.connection.v1.Connection.Version, CounterpartyVersionsProxy>.plusAssign(value: ibc.core.connection.v1.Connection.Version) {
add(value)
}/**
* <code>repeated .ibc.core.connection.v1.Version counterparty_versions = 6 [(.gogoproto.moretags) = "yaml:\"counterparty_versions\""];</code>
* @param values The counterpartyVersions to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addAllCounterpartyVersions")
fun com.google.protobuf.kotlin.DslList<ibc.core.connection.v1.Connection.Version, CounterpartyVersionsProxy>.addAll(values: kotlin.collections.Iterable<ibc.core.connection.v1.Connection.Version>) {
_builder.addAllCounterpartyVersions(values)
}/**
* <code>repeated .ibc.core.connection.v1.Version counterparty_versions = 6 [(.gogoproto.moretags) = "yaml:\"counterparty_versions\""];</code>
* @param values The counterpartyVersions to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignAllCounterpartyVersions")
inline operator fun com.google.protobuf.kotlin.DslList<ibc.core.connection.v1.Connection.Version, CounterpartyVersionsProxy>.plusAssign(values: kotlin.collections.Iterable<ibc.core.connection.v1.Connection.Version>) {
addAll(values)
}/**
* <code>repeated .ibc.core.connection.v1.Version counterparty_versions = 6 [(.gogoproto.moretags) = "yaml:\"counterparty_versions\""];</code>
* @param index The index to set the value at.
* @param value The counterpartyVersions to set.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("setCounterpartyVersions")
operator fun com.google.protobuf.kotlin.DslList<ibc.core.connection.v1.Connection.Version, CounterpartyVersionsProxy>.set(index: kotlin.Int, value: ibc.core.connection.v1.Connection.Version) {
_builder.setCounterpartyVersions(index, value)
}/**
* <code>repeated .ibc.core.connection.v1.Version counterparty_versions = 6 [(.gogoproto.moretags) = "yaml:\"counterparty_versions\""];</code>
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("clearCounterpartyVersions")
fun com.google.protobuf.kotlin.DslList<ibc.core.connection.v1.Connection.Version, CounterpartyVersionsProxy>.clear() {
_builder.clearCounterpartyVersions()
}
/**
* <code>.ibc.core.client.v1.Height proof_height = 7 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"proof_height\""];</code>
*/
var proofHeight: ibc.core.client.v1.Client.Height
@JvmName("getProofHeight")
get() = _builder.getProofHeight()
@JvmName("setProofHeight")
set(value) {
_builder.setProofHeight(value)
}
/**
* <code>.ibc.core.client.v1.Height proof_height = 7 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"proof_height\""];</code>
*/
fun clearProofHeight() {
_builder.clearProofHeight()
}
/**
* <code>.ibc.core.client.v1.Height proof_height = 7 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"proof_height\""];</code>
* @return Whether the proofHeight field is set.
*/
fun hasProofHeight(): kotlin.Boolean {
return _builder.hasProofHeight()
}
/**
* <pre>
* proof of the initialization the connection on Chain A: `UNITIALIZED ->
* INIT`
* </pre>
*
* <code>bytes proof_init = 8 [(.gogoproto.moretags) = "yaml:\"proof_init\""];</code>
*/
var proofInit: com.google.protobuf.ByteString
@JvmName("getProofInit")
get() = _builder.getProofInit()
@JvmName("setProofInit")
set(value) {
_builder.setProofInit(value)
}
/**
* <pre>
* proof of the initialization the connection on Chain A: `UNITIALIZED ->
* INIT`
* </pre>
*
* <code>bytes proof_init = 8 [(.gogoproto.moretags) = "yaml:\"proof_init\""];</code>
*/
fun clearProofInit() {
_builder.clearProofInit()
}
/**
* <pre>
* proof of client state included in message
* </pre>
*
* <code>bytes proof_client = 9 [(.gogoproto.moretags) = "yaml:\"proof_client\""];</code>
*/
var proofClient: com.google.protobuf.ByteString
@JvmName("getProofClient")
get() = _builder.getProofClient()
@JvmName("setProofClient")
set(value) {
_builder.setProofClient(value)
}
/**
* <pre>
* proof of client state included in message
* </pre>
*
* <code>bytes proof_client = 9 [(.gogoproto.moretags) = "yaml:\"proof_client\""];</code>
*/
fun clearProofClient() {
_builder.clearProofClient()
}
/**
* <pre>
* proof of client consensus state
* </pre>
*
* <code>bytes proof_consensus = 10 [(.gogoproto.moretags) = "yaml:\"proof_consensus\""];</code>
*/
var proofConsensus: com.google.protobuf.ByteString
@JvmName("getProofConsensus")
get() = _builder.getProofConsensus()
@JvmName("setProofConsensus")
set(value) {
_builder.setProofConsensus(value)
}
/**
* <pre>
* proof of client consensus state
* </pre>
*
* <code>bytes proof_consensus = 10 [(.gogoproto.moretags) = "yaml:\"proof_consensus\""];</code>
*/
fun clearProofConsensus() {
_builder.clearProofConsensus()
}
/**
* <code>.ibc.core.client.v1.Height consensus_height = 11 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"consensus_height\""];</code>
*/
var consensusHeight: ibc.core.client.v1.Client.Height
@JvmName("getConsensusHeight")
get() = _builder.getConsensusHeight()
@JvmName("setConsensusHeight")
set(value) {
_builder.setConsensusHeight(value)
}
/**
* <code>.ibc.core.client.v1.Height consensus_height = 11 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"consensus_height\""];</code>
*/
fun clearConsensusHeight() {
_builder.clearConsensusHeight()
}
/**
* <code>.ibc.core.client.v1.Height consensus_height = 11 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"consensus_height\""];</code>
* @return Whether the consensusHeight field is set.
*/
fun hasConsensusHeight(): kotlin.Boolean {
return _builder.hasConsensusHeight()
}
/**
* <code>string signer = 12;</code>
*/
var signer: kotlin.String
@JvmName("getSigner")
get() = _builder.getSigner()
@JvmName("setSigner")
set(value) {
_builder.setSigner(value)
}
/**
* <code>string signer = 12;</code>
*/
fun clearSigner() {
_builder.clearSigner()
}
}
}
@kotlin.jvm.JvmSynthetic
inline fun ibc.core.connection.v1.Tx.MsgConnectionOpenTry.copy(block: ibc.core.connection.v1.MsgConnectionOpenTryKt.Dsl.() -> Unit): ibc.core.connection.v1.Tx.MsgConnectionOpenTry =
ibc.core.connection.v1.MsgConnectionOpenTryKt.Dsl._create(this.toBuilder()).apply { block() }._build()
| kotlin | 19 | 0.64926 | 221 | 38.41691 | 343 | starcoderdata |
<filename>data/repository/src/main/java/com/brunotiba/repository/datasource/LocationDataSource.kt
package com.brunotiba.repository.datasource
import com.brunotiba.repository.model.Location
/**
* Data source for geolocation conversions.
*/
interface LocationDataSource {
/**
* Retrieves the location corresponding to the given name.
*
* @param name the location name
* @return the location
*/
suspend fun getLocationFromName(name: String): Location
}
| kotlin | 12 | 0.741803 | 97 | 26.111111 | 18 | starcoderdata |
package com.lucasprojects.braziliancovid19.model.domain.symptoms
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.lucasprojects.braziliancovid19.databinding.ItemSymptomsRecyclerBinding
class SymptomsAdapter(private val _listSymptoms: List<Symptoms>) : RecyclerView.Adapter<SymptomsAdapter.SymptomsViewHolder>() {
inner class SymptomsViewHolder(private val itemBinding: ItemSymptomsRecyclerBinding) : RecyclerView.ViewHolder(itemBinding.root) {
fun bindData(symptoms: Symptoms) {
itemBinding.imageSymptoms.setImageResource(symptoms.image)
itemBinding.textNameSymptoms.text = symptoms.name
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) : SymptomsViewHolder {
val itemBinding = ItemSymptomsRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return SymptomsViewHolder(itemBinding)
}
override fun onBindViewHolder(holder: SymptomsViewHolder, position: Int) {
holder.bindData(_listSymptoms[position])
}
override fun getItemCount() = _listSymptoms.size
} | kotlin | 17 | 0.777114 | 134 | 40.857143 | 28 | starcoderdata |
<gh_stars>1-10
package com.rakuten.tech.mobile.testapp.analytics.rat_wrapper
import android.view.MenuItem
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import com.rakuten.tech.mobile.testapp.analytics.DemoAppAnalytics
import com.rakuten.tech.mobile.testapp.ui.settings.AppSettings
enum class MenuItemDefaults {
HOME,
BACK,
}
/**
* This is a custom Activity to handle rat analytics.
*/
abstract class RATActivity : AppCompatActivity(), RatComponent {
private var menuItemLabel = ""
override fun onResume() {
DemoAppAnalytics.init(AppSettings.instance.projectId).sendAnalytics(
RATEvent(
event = EventType.PAGE_LOAD,
pageName = pageName,
siteSection = siteSection
)
)
super.onResume()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
supportActionBar?.let {
menuItemLabel = if (it.displayOptions and ActionBar.DISPLAY_HOME_AS_UP !== 0) {
MenuItemDefaults.BACK.name
} else {
MenuItemDefaults.HOME.name
}
}
} else {
menuItemLabel = item.title.toString()
}
DemoAppAnalytics.init(AppSettings.instance.projectId).sendAnalytics(
RATEvent(
event = EventType.CLICK,
action = ActionType.OPEN,
pageName = pageName,
siteSection = siteSection,
componentName = menuItemLabel,
elementType = "ActionBar"
)
)
return super.onOptionsItemSelected(item)
}
}
| kotlin | 21 | 0.602506 | 95 | 30.357143 | 56 | starcoderdata |
<reponame>sanderploegsma/aoc<filename>2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/Resources.kt<gh_stars>1-10
package nl.sanderp.aoc.aoc2021
import java.io.IOException
internal object Resources
/**
* Reads a file from the resources.
* @param fileName the name of the file, relative to the resources root
* @return the contents of the resource
*/
fun readResource(fileName: String) = Resources.javaClass.getResource("/$fileName")?.readText()?.trim()
?: throw IOException("File does not exist: $fileName") | kotlin | 13 | 0.763462 | 115 | 36.214286 | 14 | starcoderdata |