path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/raion/furnitale/ui/categories/outdoor/OutdoorFragment.kt
|
KylixEza
| 349,910,754
| false
| null |
package com.raion.furnitale.ui.categories.outdoor
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.viewbinding.library.fragment.viewBinding
import androidx.recyclerview.widget.GridLayoutManager
import com.raion.furnitale.R
import com.raion.furnitale.core.data.Resource
import com.raion.furnitale.core.ui.CategoryAdapter
import com.raion.furnitale.databinding.OutdoorFragmentBinding
import com.raion.furnitale.utils.ShowState
import org.koin.android.viewmodel.ext.android.viewModel
class OutdoorFragment : Fragment(), ShowState<OutdoorFragmentBinding> {
private val outdoorViewModel: OutdoorViewModel by viewModel()
private val outdoorBinding by viewBinding<OutdoorFragmentBinding>()
private lateinit var outdoorAdapter: CategoryAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.outdoor_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
outdoorAdapter = activity?.let { CategoryAdapter(it) }!!
outdoorBinding.rvOutdoor.apply {
layoutManager = GridLayoutManager(context, 2)
adapter = outdoorAdapter
}
outdoorViewModel.outdoor.observe(viewLifecycleOwner, {
when(it) {
is Resource.Error -> onResourceFailed(outdoorBinding, it.message)
is Resource.Loading -> onResourceLoading(outdoorBinding)
is Resource.Success -> {
it.data?.let { it1 -> outdoorAdapter.setAll(it1) }
onResourceSuccess(outdoorBinding)
}
}
})
}
override fun onResourceSuccess(binding: OutdoorFragmentBinding?) {
binding?.apply {
loadingOutdoor.stop()
includeDefaultError.apply {
ivError.visibility = gone
tvErrorMessage.visibility = gone
}
rvOutdoor.visibility = visible
}
}
override fun onResourceFailed(binding: OutdoorFragmentBinding?, message: String?) {
binding?.apply {
loadingOutdoor.stop()
rvOutdoor.visibility = gone
includeDefaultError.apply {
ivError.visibility = visible
tvErrorMessage.text = message?: resources.getText(R.string.message_if_null)
tvErrorMessage.visibility = visible
}
}
}
override fun onResourceLoading(binding: OutdoorFragmentBinding?) {
binding?.apply {
loadingOutdoor.start()
rvOutdoor.visibility = gone
includeDefaultError.apply {
ivError.visibility = gone
tvErrorMessage.visibility = gone
}
}
}
}
| 0
|
Kotlin
|
1
| 1
|
014d82d8764c7c1002d166f435b7243508794fd3
| 3,009
|
FurniTale
|
MIT License
|
android/app/src/main/java/com/algorand/android/modules/inapppin/deletealldata/ui/DeleteAllDataConfirmationBottomSheet.kt
|
perawallet
| 364,359,642
| false
|
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
|
/*
* Copyright 2022 Pera Wallet, LDA
* 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.modules.inapppin.deletealldata.ui
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.algorand.android.R
import com.algorand.android.utils.BaseDoubleButtonBottomSheet
import com.algorand.android.utils.setFragmentNavigationResult
import com.google.android.material.button.MaterialButton
class DeleteAllDataConfirmationBottomSheet : BaseDoubleButtonBottomSheet() {
override fun setTitleText(textView: TextView) {
textView.setText(R.string.delete_all_data)
}
override fun setDescriptionText(textView: TextView) {
textView.setText(R.string.you_are_about_to_delete)
}
override fun setAcceptButton(materialButton: MaterialButton) {
materialButton.apply {
setText(R.string.yes_remove_all_accounts)
setOnClickListener {
setFragmentNavigationResult(DELETE_ALL_DATA_CONFIRMATION_KEY, true)
navBack()
}
}
}
override fun setCancelButton(materialButton: MaterialButton) {
materialButton.apply {
setText(R.string.keep_it)
setOnClickListener { navBack() }
}
}
override fun setIconImageView(imageView: ImageView) {
imageView.apply {
setImageResource(R.drawable.ic_trash)
imageTintList = ContextCompat.getColorStateList(context, R.color.negative)
}
}
companion object {
const val DELETE_ALL_DATA_CONFIRMATION_KEY = "deleteAllDataConfirmationKey"
}
}
| 22
|
Swift
|
62
| 181
|
92fc77f73fa4105de82d5e87b03c1e67600a57c0
| 2,154
|
pera-wallet
|
Apache License 2.0
|
app/src/main/java/us/egek/proteinbar/sample/MainActivity.kt
|
jitheeshsk
| 169,946,809
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 4, "XML": 26, "Java": 2}
|
package com.wildbook.wildbookmobile
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
}
}
| 3
| null |
1
| 1
|
eeb895b068800cb0a83fbacdaa088280094cb1c0
| 451
|
Wildbook-Android
|
MIT License
|
compiler/src/main/kotlin/edu/cornell/cs/apl/viaduct/errors/NoMainError.kt
|
byzhang
| 374,496,728
| true
|
{"Kotlin": 878748, "Java": 43761, "C++": 13898, "Python": 11991, "Lex": 6620, "Dockerfile": 1963, "Makefile": 1785, "SWIG": 1212, "Shell": 698}
|
package edu.cornell.cs.apl.viaduct.errors
import edu.cornell.cs.apl.prettyprinting.Document
import edu.cornell.cs.apl.prettyprinting.plus
import edu.cornell.cs.apl.prettyprinting.times
import edu.cornell.cs.apl.viaduct.parsing.parse
import edu.cornell.cs.apl.viaduct.protocols.MainProtocol
import edu.cornell.cs.apl.viaduct.syntax.Name
import edu.cornell.cs.apl.viaduct.syntax.surface.ProgramNode
/** Thrown when trying to compile a program with no main. */
class NoMainError(override val source: String) : CompilationError() {
override val category: String
get() = "No Main"
override val description: Document
get() =
Document("This program has no") * mainPhrase + "." + Document.lineBreak
override val hint: Document
get() = (Document("Add a") * mainPhrase * "like so:")
.withData(exampleMain)
private companion object {
val exampleMain: ProgramNode
get() = """
process main {}
""".trimIndent().parse()
private val mainPhrase: Document
get() {
val main: Name = MainProtocol
return main * main.nameCategory
}
}
}
| 0
| null |
0
| 0
|
7aae916a0b9b1e5f880611c7ff69007fc946346b
| 1,200
|
viaduct
|
MIT License
|
app/src/main/java/tipz/viola/webview/HitTestAlertDialog.kt
|
rcky844
| 287,279,448
| false
|
{"Kotlin": 239665, "HTML": 2441, "CSS": 1242}
|
// Copyright (c) 2023-2024 Tipz Team
// SPDX-License-Identifier: Apache-2.0
package tipz.viola.webview
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.webkit.WebView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import tipz.viola.R
import tipz.viola.webview.activity.BrowserActivity
import tipz.viola.databinding.DialogHitTestTitleBinding
import tipz.viola.download.DownloadObject
import tipz.viola.download.MiniDownloadHelper
import tipz.viola.utils.CommonUtils
import tipz.viola.widget.StringResAdapter
open class HitTestAlertDialog(context: Context) : MaterialAlertDialogBuilder(context) {
private var arrayAdapter = StringResAdapter(context)
open fun setupDialogForShowing(view: VWebView, bundle: Bundle): Boolean {
val hr = view.hitTestResult
val type = hr.type
var url = bundle.getString("url") ?: return false
val title = bundle.getString("title")
val src = bundle.getString("src")
// Perform checks on the type of content we are dealing with
if (type == WebView.HitTestResult.UNKNOWN_TYPE
|| type == WebView.HitTestResult.EDIT_TEXT_TYPE) return false
if (title.isNullOrBlank()) {
// Truncate url string to make things load faster
setTitle(if (url.length > 100) url.substring(0, 99) + "…" else url)
} else {
val binding: DialogHitTestTitleBinding =
DialogHitTestTitleBinding.inflate(LayoutInflater.from(context))
val mView = binding.root
binding.title.text = title.trim()
binding.url.text = url
val icon = binding.icon
if (src.isNullOrBlank()) icon.visibility = View.GONE
else {
CoroutineScope(Dispatchers.IO).launch {
val data = MiniDownloadHelper.startDownload(src)!!
val bitmap = BitmapFactory.decodeByteArray(data, 0, data.size)
if (bitmap != null)
CoroutineScope(Dispatchers.Main).launch {
icon.setImageBitmap(bitmap)
}
}
}
this.setCustomTitle(mView)
}
// Add items to array adapter
arrayAdapter.addAll(R.string.open_in_new_tab, R.string.copy_url, R.string.download_url)
if (title.isNullOrBlank()) arrayAdapter.add(R.string.copy_text_url)
if (!src.isNullOrBlank()) arrayAdapter.addAll(
R.string.download_image,
R.string.copy_src_url,
R.string.search_image
)
arrayAdapter.add(R.string.share_url)
setAdapter(arrayAdapter) { _: DialogInterface?, which: Int ->
when (arrayAdapter.getItemResId(which)) {
R.string.copy_url -> CommonUtils.copyClipboard(context, url)
R.string.copy_text_url -> CommonUtils.copyClipboard(context, title)
R.string.download_url -> {
view.downloadClient.addToQueue(DownloadObject().apply {
uriString = url
})
}
R.string.copy_src_url -> CommonUtils.copyClipboard(context, src)
R.string.download_image -> {
view.downloadClient.addToQueue(DownloadObject().apply {
uriString = src ?: url
})
}
R.string.search_image -> {
val fileSearch = src ?: url
view.loadUrl("http://images.google.com/searchbyimage?image_url=$fileSearch")
}
R.string.open_in_new_tab -> {
val intent = Intent(context, BrowserActivity::class.java)
intent.data = Uri.parse(url)
context.startActivity(intent)
}
R.string.share_url -> CommonUtils.shareUrl(context, url)
}
}
return true
}
}
| 0
|
Kotlin
|
3
| 14
|
ec39c7d858bebab80578892ac46d65a45795b4d9
| 4,319
|
viola
|
Apache License 2.0
|
src/main/kotlin/io/kvision/types/Date.kt
|
rjaros
| 120,835,750
| false
| null |
/*
* Copyright (c) 2017-present <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 pl.treksoft.kvision.types
import kotlinx.serialization.Decoder
import kotlinx.serialization.Encoder
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialDescriptor
import kotlinx.serialization.internal.SerialClassDescImpl
import pl.treksoft.kvision.KVManager
import kotlin.js.Date
const val KV_DEFAULT_DATE_FORMAT = "YYYY-MM-DD HH:mm:ss"
actual typealias Date = Date
/**
* Extension function to convert String to Date with a given date format.
* @param format date/time format
* @return Date object
*/
@Suppress("UnsafeCastFromDynamic")
fun String.toDateF(format: String = KV_DEFAULT_DATE_FORMAT): Date {
val result = KVManager.fecha.parse(this, format)
return if (result) result else Date()
}
/**
* Extension function to convert Date to String with a given date format.
* @param format date/time format
* @return String object
*/
@Suppress("UnsafeCastFromDynamic")
fun Date.toStringF(format: String = KV_DEFAULT_DATE_FORMAT): String {
return KVManager.fecha.format(this, format)
}
object DateSerializer : KSerializer<Date> {
override val descriptor: SerialDescriptor = SerialClassDescImpl("kotlin.js.Date")
override fun deserialize(decoder: Decoder): Date {
return decoder.decodeString().toDateF()
}
override fun serialize(encoder: Encoder, obj: Date) {
encoder.encodeString(obj.toStringF())
}
}
| 3
| null |
65
| 882
|
bde30bbfd3c1a837eeff58a0a81bf7a5d677c72f
| 2,511
|
kvision
|
MIT License
|
src/main/kotlin/com/nekofar/milad/intellij/slim/SlimIcons.kt
|
KartanHQ
| 461,389,713
| false
| null |
package com.nekofar.milad.intellij.slim
import com.intellij.openapi.util.IconLoader
object SlimIcons {
@JvmField
val ProjectGenerator = IconLoader.getIcon("/icons/logoIcon.svg", javaClass)
}
| 0
|
Kotlin
|
0
| 2
|
f2567006afa4fdcbe5b994c953057c17b19dc5df
| 201
|
intellij-slim
|
Apache License 2.0
|
data/src/main/java/com/kwsilence/topmoviescompose/data/api/ImageSize.kt
|
KWSilence
| 592,816,509
| false
| null |
package com.kwsilence.topmoviescompose.data.api
sealed class ImageSize(val path: String) {
object Original : ImageSize("original/")
data class Custom(val width: Int) : ImageSize("w$width/")
companion object {
fun getSize(width: Int?): ImageSize = width?.let { Custom(it) } ?: Original
}
}
| 0
|
Kotlin
|
0
| 2
|
ee2e5a52a3e632adde4dde4593321f8773058620
| 315
|
TopMoviesCompose
|
Apache License 2.0
|
project/Application/src/main/kotlin/cga/exercise/components/Color.kt
|
DennisGoss99
| 397,846,380
| true
|
{"Kotlin": 147862, "GLSL": 9453}
|
package cga.exercise.components
import org.joml.*
class Color : Vector4f {
constructor(red : Int, green : Int, blue : Int){
x = red / 255f
y = green / 255f
z = blue / 255f
}
constructor(red : Int, green : Int, blue : Int, alpha : Int) : this(red , green , blue){
w = alpha / 255f
}
constructor(red : Float, green : Float, blue : Float){
x = red
y = green
z = blue
}
constructor(red : Float, green : Float, blue : Float, alpha : Float) : this(red , green , blue){
w = alpha
}
fun toVector3f() : Vector3f = Vector3f(x, y, z)
}
| 0
|
Kotlin
|
0
| 0
|
eb988c98528bf26a3362e74bae2b2b250d6255dd
| 632
|
CGA_Project
|
MIT License
|
sdk/src/main/java/com/qonversion/android/sdk/internal/dto/ActionPoints.kt
|
qonversion
| 224,974,105
| false
|
{"Kotlin": 604976, "Java": 9442, "Ruby": 2698}
|
package com.qonversion.android.sdk.internal.dto
import com.qonversion.android.sdk.internal.dto.automations.ActionPointScreen
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
internal data class ActionPoints(
@Json(name = "items") val items: List<Data<ActionPointScreen>>
)
| 2
|
Kotlin
|
21
| 122
|
619465b65dbf2612486ec3adad9b0a8750d76c7b
| 332
|
android-sdk
|
MIT License
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/WeierstrassInvariantG3.kt
|
Danilo-Araujo-Silva
| 271,904,885
| false
| null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: WeierstrassInvariantG3
*
* Full name: System`WeierstrassInvariantG3
*
* ′ ′
* WeierstrassInvariantG3[{ω, ω ] gives the invariant g for the Weierstrass elliptic functions corresponding to the half‐periods {ω, ω }.
* Usage: 3
*
* Options: None
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/WeierstrassInvariantG3
* Documentation: web: http://reference.wolfram.com/language/ref/WeierstrassInvariantG3.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun weierstrassInvariantG3(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("WeierstrassInvariantG3", arguments.toMutableList(), options)
}
| 2
|
Kotlin
|
0
| 3
|
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 1,355
|
mathemagika
|
Apache License 2.0
|
stocka-mobile/src/commonMain/kotlin/dev/wellingtoncosta/stocka/data/db/DriverFactory.kt
|
wellingtoncosta
| 223,506,533
| false
| null |
package dev.wellingtoncosta.stocka.data.db
import com.squareup.sqldelight.db.SqlDriver
expect class DriverFactory {
fun create(): SqlDriver
}
| 0
|
Kotlin
|
1
| 16
|
093cc7e6b0c8c4abcbc8d5c968f81770d1b5a352
| 147
|
stocka
|
MIT License
|
mcumgr-core/src/main/java/io/runtime/mcumgr/transfer/Uploader.kt
|
oleg-krv
| 324,370,889
| false
|
{"INI": 3, "Shell": 2, "Markdown": 1, "Batchfile": 1, "Proguard": 3, "Kotlin": 18, "Java": 129, "Java Properties": 1}
|
package io.runtime.mcumgr.transfer
import io.runtime.mcumgr.McuMgrScheme
import kotlinx.coroutines.channels.ReceiveChannel
import java.lang.IllegalArgumentException
import kotlin.math.min
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import org.slf4j.LoggerFactory
import java.lang.IllegalStateException
private const val RETRIES = 5
data class UploadProgress(val offset: Int, val size: Int)
abstract class Uploader(
private val data: ByteArray,
private val windowCapacity: Int,
internal var mtu: Int,
private val protocol: McuMgrScheme
) {
private val log = LoggerFactory.getLogger("Uploader")
private val _progress: MutableStateFlow<UploadProgress> =
MutableStateFlow(UploadProgress(0, data.size))
val progress: Flow<UploadProgress> = _progress
@Throws
internal abstract fun writeAsync(
data: ByteArray,
offset: Int,
length: Int?
): ReceiveChannel<UploadResult>
@Throws
suspend fun upload() = coroutineScope {
val window = WindowSemaphore(windowCapacity)
var offset = 0
while (offset < data.size) {
val transmitOffset = offset
val chunkSize = getChunkSize(data, offset)
window.acquire()
log.trace("uploader write: offset=$transmitOffset")
// Write the chunk asynchronously and launch a coroutine which
// suspends until the response is received on the result channel.
val resultChannel = writeChunkAsync(data, transmitOffset, chunkSize)
launch {
resultChannel.receive()
.mapResponse { response ->
// An unexpected offset means that the device did not
// accept the chunk. We need to resend the chunk.
// Map the response to a failure to be handled by the
// onErrorOrFailure block.
val responseOffset = response.body.off
if (responseOffset != transmitOffset + chunkSize) {
val e = IllegalStateException(
"Unexpected offset: expected=${transmitOffset + chunkSize}, " +
"actual=${responseOffset}"
)
UploadResult.Failure(e)
} else {
response
}
}
.onSuccess {
window.success()
val current = transmitOffset + chunkSize
_progress.value = UploadProgress(current, data.size)
}
.onErrorOrFailure {
log.info("uploader write failure: offset=$transmitOffset")
window.fail()
// Retry sending the request. Recover the window on success or throw
// on failure.
retryWriteChunk(data, transmitOffset, chunkSize, RETRIES)
.onSuccess {
log.info("uploader write recovered: offset=$transmitOffset")
window.recover()
}
.onErrorOrFailure {
log.info("uploader write failed: offset=$transmitOffset")
throw it
}
}
log.trace("uploader write complete: offset=$transmitOffset")
}
// Update the offset with the size of the last chunk
offset += chunkSize
}
}
/**
* Copy a chunk of data from the offset and send the write request.
*/
private fun writeChunkAsync(
data: ByteArray,
offset: Int,
chunkSize: Int
): ReceiveChannel<UploadResult> {
val chunk = data.copyOfRange(offset, offset + chunkSize)
val length = if (offset == 0) {
data.size
} else {
null
}
return writeAsync(chunk, offset, length)
}
/**
* Retry sending an upload write request.
*
* Returns the last received error if all attempts fail.
*/
private suspend fun retryWriteChunk(
data: ByteArray,
offset: Int,
chunkSize: Int,
times: Int
): UploadResult {
var error: UploadResult? = null
repeat(times) {
val result = writeChunkAsync(data, offset, chunkSize).receive()
when {
result.isSuccess -> return result
result.isError || result.isFailure -> error = result
}
}
return checkNotNull(error)
}
/**
* Returns the maximum amount of upload data which can fit into an upload request with the given
* data and offset.
*
* This calculation is optimal, and takes into account the transport scheme and size of data and
* offset since CBOR will make the integers as efficient as possible. In order to avoid an index
* out of bounds on the last chunk, if the calculated chunk size is greater than data.size -
* offset, then the latter value is returned.
*/
private fun getChunkSize(data: ByteArray, offset: Int): Int {
// The size of the header is based on the scheme. CoAP scheme is larger because there are
// 4 additional bytes of CBOR.
val headerSize = when (protocol) {
McuMgrScheme.BLE -> 8
else -> 8 + 4
}
// Size of the indefinite length map tokens (bf, ff)
val mapSize = 2
// Size of the string "off" plus the length of the offset integer
val offsetSize = cborStringLength("off") + cborUIntLength(offset)
val lengthSize = if (offset == 0) {
// Size of the string "len" plus the length of the data size integer
cborStringLength("len") + cborUIntLength(data.size)
} else {
0
}
// Size of the field name "data" utf8 string
val dataStringSize = cborStringLength("data")
val combinedSize = headerSize + mapSize + offsetSize + lengthSize + dataStringSize
// Now we calculate the max amount of data that we can fit given the MTU.
val maxDataLength = mtu - combinedSize
// We have to take into account the few bytes of CBOR which describe the length of the data.
// Even though we don't know the actual length at this point, the maxDataLength is guaranteed
// to be larger than what we will eventually send, making this calculation always correct.
val maxDataUIntTokenSize = cborUIntLength(maxDataLength)
// Final data chunk size
val maxChunkSize = mtu - combinedSize - maxDataUIntTokenSize
return min(maxChunkSize, data.size - offset)
}
}
/**
* Calculates the size in bytes of a CBOR encoded string.
*/
internal fun cborStringLength(s: String): Int {
val headerLength = cborUIntLength(s.length)
return headerLength + s.length
}
/**
* Calculates the size in bytes of a CBOR encoded unsigned integer.
*/
internal fun cborUIntLength(n: Int): Int =
when {
n < 0 -> throw IllegalArgumentException("n must be >= 0")
n < 24 -> 1
n < 256 -> 2 // 2^8
n < 65536 -> 3 // 2^16
n < 4294967296 -> 5 // 2^32
else -> 9
}
| 1
| null |
1
| 1
|
f9489c8a6e79442174eebab2644c0fc6cbdbe4fa
| 7,630
|
mcumgr-android
|
Apache License 2.0
|
kenet-gen-typescript/src/jvmMain/kotlin/org/kotlin/everywhere/net/gen/typescript/typescript.kt
|
kotlin-everywhere
| 368,894,676
| false
| null |
package org.kotlin.everywhere.net.gen.typescript
import org.kotlin.everywhere.net.Call
import org.kotlin.everywhere.net.Fire
import org.kotlin.everywhere.net.Kenet
import java.io.File
import java.nio.file.Path
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.KTypeProjection
import kotlin.reflect.full.createType
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.memberProperties
data class KenetDefinition(val name: String, val definitions: List<EndpointDefinition>)
sealed class EndpointDefinition {
abstract val name: String
}
data class CallDefinition(override val name: String, val parameterType: KType, val responseType: KType) :
EndpointDefinition()
data class FireDefinition(override val name: String, val parameterType: KType) : EndpointDefinition()
data class SubDefinition(override val name: String, val kenetDefinition: KenetDefinition) : EndpointDefinition()
internal fun define(kenet: Kenet, name: String? = null): KenetDefinition {
val className =
kenet::class.simpleName
?: name
?: throw IllegalArgumentException("Cannot find class simple name : kenet = $kenet")
val definitions = kenet::class
.members
// TODO :: reflection 제거
.map {
when {
it.returnType.isSubtypeOf(
Call::class.createType(
listOf(
KTypeProjection.STAR,
KTypeProjection.STAR
)
)
) -> {
require(it.returnType.arguments.size == 2) {
"invalid endpoint parameter length, it must be 2(Parameter, Response) types : parameters = ${it.returnType.arguments}"
}
val (parameterType, responseType) = it.returnType.arguments
CallDefinition(
it.name,
parameterType.type
?: throw IllegalArgumentException("call endpoint parameter type missing : parameterType = $parameterType"),
responseType.type
?: throw IllegalArgumentException("call endpoint response type missing : responseType = $responseType")
)
}
it.returnType.isSubtypeOf(Fire::class.createType(listOf(KTypeProjection.STAR))) -> {
require(it.returnType.arguments.size == 1) {
"invalid endpoint parameter length, it must be 1(Parameter) types : parameters = ${it.returnType.arguments}"
}
val (parameterType) = it.returnType.arguments
FireDefinition(
it.name,
parameterType.type
?: throw IllegalArgumentException("call endpoint parameter type missing : parameterType = $parameterType"),
)
}
it.returnType.isSubtypeOf(Kenet::class.createType()) -> {
SubDefinition(it.name, define(it.call(kenet) as Kenet, it.name))
}
else -> {
null
}
}
}
.filterNotNull()
// 리플렉션은 필드의 순서를 보장하지 않는다. 항상 동일한 결과값을 보장하기 위해서 이름 순으로 정렬한다.
.sortedBy { it.name }
return KenetDefinition(className, definitions)
}
internal fun render(def: KenetDefinition, subName: String? = null): List<String> {
return if (subName == null) {
listOf("export class ${def.name} extends KenetClient {") +
def.definitions.flatMap { render(it) } +
listOf("}")
} else {
listOf("readonly $subName = this.s('${subName}', new (class ${def.name} extends KenetClient {") +
def.definitions.flatMap { render(it) } +
listOf("}));")
}
}
internal fun render(def: EndpointDefinition): List<String> {
return when (def) {
is CallDefinition -> render(def)
is FireDefinition -> render(def)
is SubDefinition -> render(def.kenetDefinition, def.name)
}
}
internal fun render(def: CallDefinition): List<String> {
return listOf("readonly ${def.name} = this.c<${renderType(def.parameterType)}, ${renderType(def.responseType)}>('${def.name}');")
}
internal fun render(def: FireDefinition): List<String> {
return listOf("readonly ${def.name} = this.f<${renderType(def.parameterType)}>('${def.name}');")
}
internal fun renderType(createType: KType): String {
val rendered = when (createType) {
Int::class.createType(), Int::class.createType(nullable = true) -> "number"
String::class.createType(), String::class.createType(nullable = true) -> "string"
Array<String>::class.createType(listOf(KTypeProjection.invariant(String::class.createType()))) -> "string[]"
else -> {
if (createType.toString().startsWith("kotlin.collections.List<")) {
val listTypeArgument = createType.arguments.first().type
?: throw IllegalArgumentException("List type argument missing")
return renderType(listTypeArgument) + "[]"
}
val kClass: KClass<*> = createType.classifier as KClass<*>
kClass.memberProperties
.asSequence()
.map { it.name to renderType(it.returnType) }
.sortedBy { it.first }
.map { "${it.first}: ${it.second}" }
.joinToString(", ", prefix = "{", postfix = "}")
}
}
return rendered + (if (createType.isMarkedNullable) " | null" else "")
}
sealed class Variant
object TypeScript : Variant()
object Deno : Variant()
fun generate(kenet: Kenet, variant: Variant): String {
return (listOf(
when (variant) {
Deno ->
"import { KenetClient } from './kenet.ts';"
TypeScript ->
"import { KenetClient } from './kenet';"
},
""
) + render(define(kenet)))
.joinToString("\n")
}
fun generate(kenet: Kenet, path: Path, name: String, variant: Variant) {
val directory = path.toFile()
if (!directory.exists()) {
assert(directory.mkdirs()) { "cannot create target path : path=${path}" }
}
File(directory, "kenet.ts").writeBytes(
object {}.javaClass.getResourceAsStream("/kenet.ts").use { it!!.readAllBytes() }
)
File(directory, "$name.ts").writeText(generate(kenet, variant))
}
| 4
|
Kotlin
|
9
| 13
|
087fed6fead77d7ec2fc087608ae3095efd3d852
| 6,580
|
kenet
|
MIT License
|
packages/graalvm/src/test/kotlin/elide/runtime/gvm/internals/vfs/HostVFSConfigTest.kt
|
elide-dev
| 506,113,888
| false
| null |
/*
* Copyright (c) 2024 Elide Technologies, Inc.
*
* Licensed under the MIT license (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://opensource.org/license/mit/
*
* 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 elide.runtime.gvm.internals.vfs
import io.micronaut.test.support.TestPropertyProvider
import org.junit.jupiter.api.TestInstance
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import elide.annotations.Inject
import elide.runtime.vfs.GuestVFS
import elide.testing.annotations.Test
import elide.testing.annotations.TestCase
/** Test injection of a file-system implementation when `vfs.mode=GUEST`. */
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestCase internal class EmbeddedVFSConfigTest: TestPropertyProvider {
override fun getProperties(): MutableMap<String, String> = mutableMapOf(
"elide.gvm.vfs.enabled" to "true",
"elide.gvm.vfs.mode" to "GUEST",
)
@Inject lateinit var vfs: GuestVFS
@Test fun testInjectable() {
assertNotNull(vfs, "should be able to inject a VFS implementation when `mode=GUEST`")
}
@Test fun testExpectedImpl() {
assertTrue(
vfs is EmbeddedGuestVFSImpl,
"expected embedded VFS implementation when `mode=GUEST`, instead got '${vfs::class.java.simpleName}'",
)
}
}
| 75
| null |
16
| 97
|
652036fb4e8394e8ad1aced2f4bbfaa9e00a5181
| 1,646
|
elide
|
MIT License
|
QuaBionicApp/app/src/main/java/com/bionichamza/quabionicapp/data/RemoteDataSource.kt
|
biyonikhamza
| 760,676,497
| false
|
{"Kotlin": 52722}
|
package com.bionichamza.quabionicapp.data
import android.util.JsonToken
import com.bionichamza.quabionicapp.data.network.ProstheticsAPI
import com.bionichamza.quabionicapp.models.InspirationWord
import com.bionichamza.quabionicapp.models.Prosthetics
import com.bionichamza.quabionicapp.models.ProstheticsInfo
import retrofit2.Response
import javax.inject.Inject
class RemoteDataSource @Inject constructor(
private val prostheticsAPI: ProstheticsAPI
) {
suspend fun getProstheticsInfo(queries: Map<String, String>) : Response<ProstheticsInfo> {
return prostheticsAPI.getProstheticsInfo(queries)
}
suspend fun getProsthetics(queries : Map<String , String>) : Response<Prosthetics> {
return prostheticsAPI.getProsthetics(queries)
}
suspend fun searchProstheticsInfo(searchQuery: Map<String, String>) : Response<ProstheticsInfo> {
return prostheticsAPI.searchProstheticsInfo(searchQuery)
}
suspend fun searchProsthetics(searchQuery : Map<String , String>) : Response<Prosthetics> {
return prostheticsAPI.searchProsthetics(searchQuery)
}
suspend fun getInspiration(queries: Map<String, String>) : Response<InspirationWord> {
return prostheticsAPI.getInspiration(queries)
}
}
| 0
|
Kotlin
|
0
| 0
|
e29a7da035e9fbc63f9fa5d2e6c142d1fcc66039
| 1,260
|
QuaBionicApp
|
Apache License 2.0
|
kotlinx-coroutines-jdk8/src/test/kotlin/examples/simple-example-2.kt
|
pljp
| 88,139,141
| true
| null |
/*
* Copyright 2016-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.future.future
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
// this function returns a CompletableFuture using Kotlin coroutines
fun supplyTheAnswerAsync(): CompletableFuture<Int> = future {
println("We might be doing some asynchronous IO here or something else...")
delay(1, TimeUnit.SECONDS) // just do a non-blocking delay
42 // The answer!
}
fun main(args: Array<String>) {
// We can use `supplyTheAnswerAsync` just like any other future-supplier function
val future = supplyTheAnswerAsync()
println("The answer is ${future.get()}")
}
| 0
|
Kotlin
|
5
| 39
|
52e15006d31e779aaeadba053dcda1afd0198240
| 1,305
|
kotlinx.coroutines
|
Apache License 2.0
|
app/src/main/java/com/ezpnix/writeon/presentation/screens/edit/components/CustomTextField.kt
|
3zpnix
| 850,596,389
| false
|
{"Kotlin": 256758}
|
package com.ezpnix.writeon.presentation.screens.edit.components
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
@Composable
fun CustomTextField(
value: TextFieldValue,
onValueChange: (TextFieldValue) -> Unit,
placeholder: String,
shape: RoundedCornerShape = RoundedCornerShape(0.dp),
interactionSource: MutableInteractionSource = MutableInteractionSource(),
singleLine: Boolean = false,
modifier: Modifier = Modifier,
enabled: Boolean = true,
hideContent: Boolean = false
) {
val visualTransformation = if (hideContent) {
PasswordVisualTransformation()
} else {
VisualTransformation.None
}
TextField(
value = value,
visualTransformation = visualTransformation,
onValueChange = onValueChange,
interactionSource = interactionSource,
enabled = enabled,
modifier = modifier
.fillMaxWidth()
.clip(shape),
singleLine = singleLine,
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
),
placeholder = {
Text(placeholder)
}
)
}
class UndoRedoState {
var input by mutableStateOf(TextFieldValue(""))
private val undoHistory = ArrayDeque<TextFieldValue>()
private val redoHistory = ArrayDeque<TextFieldValue>()
init {
undoHistory.add(input)
}
fun onInput(value: TextFieldValue) {
val updatedValue = value.copy(value.text, selection = TextRange(value.text.length))
undoHistory.add(updatedValue)
redoHistory.clear()
input = updatedValue
}
fun undo() {
if (undoHistory.size > 1) {
val lastState = undoHistory.removeLastOrNull()
lastState?.let {
redoHistory.add(it)
}
val previousState = undoHistory.lastOrNull()
previousState?.let {
input = it
}
}
}
fun redo() {
val redoState = redoHistory.removeLastOrNull()
redoState?.let {
undoHistory.add(it)
input = it
}
}
}
| 7
|
Kotlin
|
0
| 6
|
2b59993da41c2ebdf325d9d60f0c42e00ef5ad5c
| 3,131
|
WriteOn
|
Apache License 2.0
|
app/src/main/java/com/hxs/opengles3demo/AssimpHelper.kt
|
Mightted
| 272,359,232
| false
| null |
package com.hxs.opengles3demo
import assimp.*
import com.hxs.opengles3demo.obj.FLOAT_BYTE_COUNT
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
object AssimpHelper {
private val importer = Importer()
fun loadModel(path: String) {
val scene = importer.readFile(
path,
AiPostProcessStep.Triangulate.i or AiPostProcessStep.FlipUVs.i
)
if (scene?.rootNode == null || scene.flags or AI_SCENE_FLAGS_INCOMPLETE != 0) {
println("hxs:${importer.errorString}")
return
}
scene.let {
it.meshes[0]
}
}
private fun processNode(node: AiNode, scene: AiScene) {
// 处理节点所有的网格(如果有的话)
// for(index in 0 until node.numMeshes)
// {
// val mesh = scene.meshes[index]
//
// aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
// meshes.push_back(processMesh(mesh, scene));
// }
// // 接下来对它的子节点重复这一过程
// for(unsigned int i = 0; i < node->mNumChildren; i++)
// {
// processNode(node->mChildren[i], scene);
// }
}
private fun processMesh(mesh: AiMesh, scene: AiScene): Mesh {
val vMesh = Mesh()
vMesh.vertices = ByteBuffer.allocateDirect(mesh.numVertices * 8 * FLOAT_BYTE_COUNT)
.order(ByteOrder.nativeOrder()).asFloatBuffer()
vMesh.vertices.position(0)
// 处理顶点
for (i in 0 until mesh.numVertices) {
mesh.vertices[i] to vMesh.vertices
mesh.normals[i] to vMesh.vertices
if (!mesh.textureCoords[0].isNullOrEmpty()) {
mesh.textureCoords[0][i] to vMesh.vertices
} else {
AiVector2D(0f, 0f) to vMesh.vertices
}
}
for (face in mesh.faces) {
// for(index in face)
}
return vMesh
}
}
data class Vertex(
val position: ArrayList<Float>,
val normal: ArrayList<Float>,
val texCoords: ArrayList<Float>
)
data class Texture(val id: Int, val type: Int)
class Mesh {
lateinit var vertices: FloatBuffer
val indices: ArrayList<Int> = arrayListOf()
val textures: ArrayList<Texture> = arrayListOf()
}
| 0
|
Kotlin
|
0
| 0
|
4416184b635e8571c0d3633f88673f275bf95c9e
| 2,249
|
OpenGLES3Demo
|
Apache License 2.0
|
app/src/main/java/com/example/spygamers/services/group/GetAccountGroupsBody.kt
|
Juicy-Lemonberry
| 748,985,682
| false
|
{"Kotlin": 123050}
|
package com.example.spygamers.services.group
data class GetAccountGroupsBody (
val auth_token: String,
val filter: String?
)
| 0
|
Kotlin
|
2
| 0
|
78deb69c4b017042b3a6779a0d6d48bdd131ea43
| 133
|
SpyGamers-App
|
MIT License
|
src/test/kotlin/no/nav/tilleggsstonader/sak/vedtak/totrinnskontroll/SendTilBeslutterStegTest.kt
|
navikt
| 685,490,225
| false
|
{"Kotlin": 1513596, "Gherkin": 39138, "HTML": 33935, "Shell": 924, "Dockerfile": 164}
|
package no.nav.tilleggsstonader.sak.vedtak.totrinnskontroll
import com.fasterxml.jackson.module.kotlin.readValue
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import no.nav.familie.prosessering.domene.Task
import no.nav.familie.prosessering.internal.TaskService
import no.nav.tilleggsstonader.kontrakter.felles.ObjectMapperProvider.objectMapper
import no.nav.tilleggsstonader.kontrakter.felles.Stønadstype
import no.nav.tilleggsstonader.kontrakter.oppgave.Oppgave
import no.nav.tilleggsstonader.kontrakter.oppgave.Oppgavetype
import no.nav.tilleggsstonader.libs.test.assertions.catchThrowableOfType
import no.nav.tilleggsstonader.sak.behandling.BehandlingService
import no.nav.tilleggsstonader.sak.behandling.domain.BehandlingResultat
import no.nav.tilleggsstonader.sak.behandling.domain.BehandlingResultat.INNVILGET
import no.nav.tilleggsstonader.sak.behandling.domain.BehandlingStatus
import no.nav.tilleggsstonader.sak.behandling.domain.BehandlingType
import no.nav.tilleggsstonader.sak.behandling.domain.BehandlingÅrsak
import no.nav.tilleggsstonader.sak.brev.Vedtaksbrev
import no.nav.tilleggsstonader.sak.brev.VedtaksbrevRepository
import no.nav.tilleggsstonader.sak.fagsak.domain.PersonIdent
import no.nav.tilleggsstonader.sak.infrastruktur.database.repository.findByIdOrThrow
import no.nav.tilleggsstonader.sak.infrastruktur.exception.ApiFeil
import no.nav.tilleggsstonader.sak.opplysninger.oppgave.OppgaveService
import no.nav.tilleggsstonader.sak.opplysninger.oppgave.tasks.FerdigstillOppgaveTask
import no.nav.tilleggsstonader.sak.opplysninger.oppgave.tasks.OpprettOppgaveTask
import no.nav.tilleggsstonader.sak.util.BrukerContextUtil.clearBrukerContext
import no.nav.tilleggsstonader.sak.util.BrukerContextUtil.mockBrukerContext
import no.nav.tilleggsstonader.sak.util.behandling
import no.nav.tilleggsstonader.sak.util.fagsak
import no.nav.tilleggsstonader.sak.util.oppgave
import no.nav.tilleggsstonader.sak.util.saksbehandling
import no.nav.tilleggsstonader.sak.vedtak.TypeVedtak
import no.nav.tilleggsstonader.sak.vedtak.VedtaksresultatService
import no.nav.tilleggsstonader.sak.vedtak.totrinnskontroll.domain.TotrinnInternStatus
import no.nav.tilleggsstonader.sak.vedtak.totrinnskontroll.domain.TotrinnskontrollUtil.totrinnskontroll
import no.nav.tilleggsstonader.sak.vilkår.stønadsvilkår.VilkårService
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.data.repository.findByIdOrNull
import java.util.Properties
import java.util.UUID
class SendTilBeslutterStegTest {
private val taskService = mockk<TaskService>()
private val behandlingService = mockk<BehandlingService>(relaxed = true)
private val vedtaksbrevRepository = mockk<VedtaksbrevRepository>()
private val vedtaksresultatService = mockk<VedtaksresultatService>()
private val vilkårService = mockk<VilkårService>()
private val oppgaveService = mockk<OppgaveService>()
private val totrinnskontrollService = mockk<TotrinnskontrollService>(relaxed = true)
private val beslutteVedtakSteg =
SendTilBeslutterSteg(
taskService,
behandlingService,
vedtaksbrevRepository,
vedtaksresultatService,
vilkårService,
oppgaveService,
totrinnskontrollService,
)
private val fagsak = fagsak(
stønadstype = Stønadstype.BARNETILSYN,
identer = setOf(PersonIdent(ident = "12345678901")),
)
private val saksbehandlerNavn = "saksbehandlernavn"
private val vedtaksbrev = Vedtaksbrev(
behandlingId = UUID.randomUUID(),
saksbehandlersignatur = saksbehandlerNavn,
beslutterPdf = null,
saksbehandlerIdent = saksbehandlerNavn,
saksbehandlerHtml = "",
)
private val behandling = saksbehandling(
fagsak,
behandling(
fagsak = fagsak,
type = BehandlingType.FØRSTEGANGSBEHANDLING,
status = BehandlingStatus.UTREDES,
steg = beslutteVedtakSteg.stegType(),
resultat = BehandlingResultat.IKKE_SATT,
årsak = BehandlingÅrsak.SØKNAD,
),
)
private val revurdering =
behandling.copy(type = BehandlingType.REVURDERING, resultat = INNVILGET)
private lateinit var taskSlot: MutableList<Task>
@BeforeEach
internal fun setUp() {
taskSlot = mutableListOf()
every {
taskService.save(capture(taskSlot))
} returns Task("", "", Properties())
every { vedtaksbrevRepository.findByIdOrThrow(any()) } returns vedtaksbrev
every { vilkårService.erAlleVilkårOppfylt(any()) } returns true
every { vedtaksbrevRepository.existsById(any()) } returns true
every { oppgaveService.hentBehandleSakOppgaveSomIkkeErFerdigstilt(any()) } returns oppgave(behandling.id)
every { oppgaveService.hentOppgaveSomIkkeErFerdigstilt(any(), any()) } returns null
every { oppgaveService.hentOppgave(any()) } returns Oppgave(id = 123, versjon = 0)
// TODO tilbakekreving
// every { simuleringService.hentLagretSimuleringsoppsummering(any()) } returns simuleringsoppsummering
// every { tilbakekrevingService.harSaksbehandlerTattStillingTilTilbakekreving(any()) } returns true
// every { tilbakekrevingService.finnesÅpenTilbakekrevingsBehandling(any()) } returns true
every { vedtaksresultatService.hentVedtaksresultat(any()) } returns TypeVedtak.INNVILGET
mockBrukerContext(saksbehandlerNavn)
}
@AfterEach
internal fun tearDown() {
clearBrukerContext()
}
@Test
internal fun `Innvilget behandling - alt ok`() {
val innvilgetBehandling = behandling.copy(resultat = INNVILGET)
beslutteVedtakSteg.validerSteg(innvilgetBehandling)
}
@Test
internal fun `Innvilget behandling - IKKE ok hvis erAlleVilkårOppfylt false`() {
every { vilkårService.erAlleVilkårOppfylt(any()) } returns false
val innvilgetBehandling = behandling.copy(resultat = INNVILGET)
val forvetetFeilmelding =
"Kan ikke innvilge hvis ikke alle vilkår er oppfylt for behandlingId: ${innvilgetBehandling.id}"
assertThat(catchThrowableOfType<ApiFeil> { beslutteVedtakSteg.validerSteg(innvilgetBehandling) }.feil)
.isEqualTo(forvetetFeilmelding)
}
@Test
internal fun `Skal avslutte oppgave BehandleSak hvis den finnes`() {
utførOgVerifiserKall(Oppgavetype.BehandleSak)
verifiserVedtattBehandlingsstatistikkTask()
}
@Test
internal fun `Skal avslutte oppgave BehandleUnderkjentVedtak hvis den finnes`() {
every { totrinnskontrollService.hentTotrinnskontroll(any()) } returns totrinnskontroll(status = TotrinnInternStatus.UNDERKJENT)
utførOgVerifiserKall(Oppgavetype.BehandleUnderkjentVedtak)
verifiserVedtattBehandlingsstatistikkTask()
}
@Test
internal fun `Skal kaste feil hvis oppgave med type BehandleUnderkjentVedtak eller BehandleSak ikke finnes`() {
every { oppgaveService.hentBehandleSakOppgaveSomIkkeErFerdigstilt(any()) } returns null
val feil = catchThrowableOfType<ApiFeil> { beslutteVedtakSteg.validerSteg(behandling) }
assertThat(feil.feil)
.contains("Oppgaven for behandlingen er ikke tilgjengelig.")
}
@Test
internal fun `Skal kaste feil hvis BehandleSak-oppgaven er tilordnet en annen saksbehandler`() {
val oppgaveId = 10099L
val oppgaveDomain = oppgave(behandling.id, gsakOppgaveId = oppgaveId)
val oppgave = Oppgave(id = oppgaveId, versjon = 0, tilordnetRessurs = "annenSaksbehandler")
every { oppgaveService.hentBehandleSakOppgaveSomIkkeErFerdigstilt(any()) } returns oppgaveDomain
every { oppgaveService.hentOppgave(oppgaveDomain.gsakOppgaveId) } returns oppgave
val feil = catchThrowableOfType<ApiFeil> { beslutteVedtakSteg.validerSteg(behandling) }
assertThat(feil.feil)
.contains("Kan ikke sende til beslutter. Oppgaven for behandlingen er plukket av annenSaksbehandler")
}
@Test
internal fun `Skal kaste feil hvis godkjenne vedtak-oppgaven ikke er ferdigstilt`() {
every {
oppgaveService.hentOppgaveSomIkkeErFerdigstilt(behandling.id, Oppgavetype.GodkjenneVedtak)
} returns oppgave(behandling.id)
val feil = catchThrowableOfType<ApiFeil> { beslutteVedtakSteg.validerSteg(behandling) }
assertThat(feil.feil)
.contains("Det finnes en Godkjenne Vedtak oppgave systemet må ferdigstille før behandlingen kan sendes til beslutter.")
}
@Test
internal fun `Skal feile hvis saksbehandlersignatur i vedtaksbrev er ulik saksbehandleren som sendte til beslutter`() {
every { vedtaksbrevRepository.findByIdOrThrow(any()) } returns vedtaksbrev.copy(saksbehandlersignatur = "Saksbehandler A")
mockBrukerContext("Saksbehandler B")
assertThat(catchThrowableOfType<ApiFeil> { beslutteVedtakSteg.validerSteg(behandling) })
.hasMessageContaining("En annen saksbehandler har signert vedtaksbrevet")
}
@Test
internal fun `skal ikke hente brev når man håndterer behandling med årsak korrigering uten brev`() {
every { vedtaksresultatService.hentVedtaksresultat(any()) } returns TypeVedtak.INNVILGET
val behandling = behandling.copy(årsak = BehandlingÅrsak.KORRIGERING_UTEN_BREV)
beslutteVedtakSteg.validerSteg(behandling)
verify(exactly = 0) {
vedtaksbrevRepository.findByIdOrNull(any())
}
}
// TODO DVH
private fun verifiserVedtattBehandlingsstatistikkTask() {
// assertThat(taskSlot[2].type).isEqualTo(BehandlingsstatistikkTask.TYPE)
// assertThat(objectMapper.readValue<BehandlingsstatistikkTaskPayload>(taskSlot[2].payload).hendelse)
// .isEqualTo(Hendelse.VEDTATT)
}
private fun utførOgVerifiserKall(ferdigstillOppgaveType: Oppgavetype) {
mockBrukerContext("saksbehandlernavn")
utførSteg()
clearBrukerContext()
verify { behandlingService.oppdaterStatusPåBehandling(behandling.id, BehandlingStatus.FATTER_VEDTAK) }
with(taskSlot[1]) {
assertThat(type).isEqualTo(OpprettOppgaveTask.TYPE)
val taskData = objectMapper.readValue<OpprettOppgaveTask.OpprettOppgaveTaskData>(payload)
assertThat(taskData.oppgave.oppgavetype).isEqualTo(Oppgavetype.GodkjenneVedtak)
}
with(taskSlot[0]) {
assertThat(type).isEqualTo(FerdigstillOppgaveTask.TYPE)
assertThat(objectMapper.readValue<FerdigstillOppgaveTask.FerdigstillOppgaveTaskData>(payload).oppgavetype)
.isEqualTo(ferdigstillOppgaveType)
}
}
private fun utførSteg() {
beslutteVedtakSteg.utførSteg(behandling, null)
}
}
| 5
|
Kotlin
|
1
| 0
|
c9124fe9a92bffd2d450278dc08344b62903f9a8
| 10,971
|
tilleggsstonader-sak
|
MIT License
|
src/test/kotlin/hello/hellospring/HelloSpringApplicationTests.kt
|
suites
| 283,834,530
| false
| null |
package hello.hellospring
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class HelloSpringApplicationTests {
@Test
fun contextLoads() {
}
}
| 0
|
Kotlin
|
0
| 7
|
094826f7ab078da4479edf84d18d856d837c1d5b
| 210
|
hello-spring
|
MIT License
|
src/test/kotlin/com/example/useraccount/services/UserAccountClient.kt
|
LuismiBarcos
| 600,857,845
| false
|
{"Kotlin": 43161, "Java": 3869}
|
package com.example.useraccount.services
import org.sdi.domain.annotations.Component
import org.sdi.domain.annotations.Inject
/**
*@author <NAME>
*/
@Component(classes = [UserAccountClient::class])
class UserAccountClient {
@Inject
private lateinit var userService: UserService
@Inject("com.example.useraccount.services.impl.AccountServiceImpl")
private lateinit var accountService: AccountService
fun displayUserAccount() {
val userName = userService.getUserName()
val accountNumber = accountService.getAccountNumber(userName)
println("Username: $userName\nAccountNumber: $accountNumber")
}
}
| 0
|
Kotlin
|
0
| 0
|
7b74b015949c753784efbf289fdba90e6efbc35f
| 647
|
SDI
|
Apache License 2.0
|
kotlin-csstype/src/main/generated/csstype/ScrollbarWidth.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package csstype
// language=JavaScript
@JsName("""(/*union*/{thin: 'thin'}/*union*/)""")
sealed external interface ScrollbarWidth {
companion object {
val thin: ScrollbarWidth
}
}
| 12
|
Kotlin
|
6
| 983
|
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
| 338
|
kotlin-wrappers
|
Apache License 2.0
|
payments-core/src/test/java/com/stripe/android/ApiVersionTest.kt
|
stripe
| 6,926,049
| false
| null |
package com.stripe.android
import com.google.common.truth.Truth.assertThat
import com.stripe.android.ApiVersion.Companion.API_VERSION_CODE
import org.junit.Test
class ApiVersionTest {
@Test
fun `instance should instantiate correctly`() {
assertThat(ApiVersion.get().code).isEqualTo(API_VERSION_CODE)
}
@Test
fun `single beta header should have correct code`() {
assertThat(ApiVersion(setOf(StripeApiBeta.WeChatPayV1)).code)
.isEqualTo("$API_VERSION_CODE;${StripeApiBeta.WeChatPayV1.code}")
}
}
| 55
| null |
516
| 914
|
3c2b2ad9c60d1d13c8770888ef38c24286d96f0e
| 549
|
stripe-android
|
MIT License
|
src/main/kotlin/io/github/leandroborgesferreira/dagcommand/domain/Edge.kt
|
leandroBorgesFerreira
| 268,720,218
| false
|
{"Kotlin": 45712}
|
package io.github.leandroborgesferreira.dagcommand.domain
data class Edge(
val source: String,
val target: String,
val weight: Int
)
| 6
|
Kotlin
|
11
| 39
|
ef7c97e4b2691c9d16953b35dfdd0bdb8691d841
| 146
|
dag-command
|
Apache License 2.0
|
src/main/kotlin/org/example/detekt/test/BeforeAnnotationInTest.kt
|
Keslerdk
| 863,145,840
| false
|
{"Kotlin": 47765, "Shell": 738}
|
package org.example.detekt.rules.test
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.hasAnnotation
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
class BeforeAnnotationInTestRule(config: Config) : Rule(config) {
private companion object {
const val RULE_DESCRIPTION =
"Проверяет, что в каждом тесте присутствует аннотация @Before или @BeforeEach."
const val REPORT_MESSAGE =
"Используйте setup метод для инициализации переменных перед тестом."
}
override val issue: Issue
get() = Issue(javaClass.simpleName, Severity.CodeSmell, RULE_DESCRIPTION, Debt.FIVE_MINS)
override fun visitClass(klass: KtClass) {
super.visitClass(klass)
val isTestClass = klass.name?.contains("Test", ignoreCase = true) ?: return
if (isTestClass && !isContainsSetUpMethod(klass)) {
report(CodeSmell(issue, Entity.Companion.from(klass), REPORT_MESSAGE))
}
}
private fun isContainsSetUpMethod(klass: KtClass): Boolean {
var haveBeforeAnnotation = false
klass.forEachDescendantOfType<KtNamedFunction> { func ->
haveBeforeAnnotation =
haveBeforeAnnotation || func.hasAnnotation("Before")
|| func.hasAnnotation("BeforeEach")
}
return haveBeforeAnnotation
}
}
| 2
|
Kotlin
|
0
| 0
|
614c19c88d61c41f6a9af7e6d49d677945965509
| 1,759
|
fluffy-octo-meme
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/example/movieskmm/data/local/db/DbHelper.kt
|
pushpalroy
| 735,486,564
| false
|
{"Kotlin": 196812, "Swift": 14743, "Ruby": 2451, "Shell": 442}
|
package com.example.movieskmm.data.local.db
import com.example.movieskmm.data.local.db.util.PlatformSQLiteState
abstract class DbHelper {
abstract val databaseState: PlatformSQLiteState
abstract val appDatabaseDAO: AppDatabaseDAO
var relaunchListFlowCallback: (() -> Unit)? = null
abstract fun buildDbIfNeed(passphrase: CharSequence = ""): DatabaseHolder
abstract fun decrypt(oldPass: CharSequence)
abstract fun reKey(oldPass: CharSequence, newPass: CharSequence)
abstract fun encrypt(newPass: CharSequence)
abstract fun closeDatabase()
companion object {
const val DB_NAME = "mkmm.db"
}
}
| 12
|
Kotlin
|
1
| 21
|
df5e3f4e1f0ad24b28a75f281ca936d88c2e398a
| 647
|
movieskmm
|
MIT License
|
TeamCode/src/main/kotlin/org/firstinspires/ftc/teamcode/config/components/DriveMotors.kt
|
ftc8580
| 683,384,905
| false
|
{"Kotlin": 257621, "Java": 45100}
|
package org.firstinspires.ftc.teamcode.config.components
data class DriveMotors(
val leftFront: String = "leftFront",
val rightFront: String = "rightFront",
val leftRear: String = "leftRear",
val rightRear: String = "rightRear"
)
| 0
|
Kotlin
|
0
| 0
|
a56c7c0b33d5d769ba643adb7324787a7455e887
| 246
|
centerstage
|
BSD 3-Clause Clear License
|
TeamCode/src/main/kotlin/org/firstinspires/ftc/teamcode/config/components/DriveMotors.kt
|
ftc8580
| 683,384,905
| false
|
{"Kotlin": 257621, "Java": 45100}
|
package org.firstinspires.ftc.teamcode.config.components
data class DriveMotors(
val leftFront: String = "leftFront",
val rightFront: String = "rightFront",
val leftRear: String = "leftRear",
val rightRear: String = "rightRear"
)
| 0
|
Kotlin
|
0
| 0
|
a56c7c0b33d5d769ba643adb7324787a7455e887
| 246
|
centerstage
|
BSD 3-Clause Clear License
|
intellij-plugin-structure/tests/src/test/kotlin/com/jetbrains/plugin/structure/fleet/mock/FleetTestData.kt
|
JetBrains
| 3,686,654
| false
|
{"Kotlin": 2524497, "Java": 253600, "CSS": 1454, "JavaScript": 692}
|
package com.jetbrains.plugin.structure.fleet.mock
fun getMockPluginJsonContent(fileName: String): String {
return object {}.javaClass.getResource("/fleet/$fileName.json").readText()
}
| 6
|
Kotlin
|
38
| 178
|
4deec2e4e08c9ee4ce087697ef80b8b327703548
| 187
|
intellij-plugin-verifier
|
Apache License 2.0
|
mvvm-coroutines-clean-architecture/app/src/main/java/br/com/mobiplus/gitclient/presentation/di/PresentationModule.kt
|
mariofelesdossantosjunior
| 249,457,538
| true
|
{"Kotlin": 145177}
|
package br.com.mobiplus.gitclient.presentation.di
val presentationModule = listOf(
viewModelModule
)
| 0
|
Kotlin
|
0
| 1
|
f1d96c8f45814b883fab3987b8e365310e2de2dc
| 105
|
android-architecture-examples
|
MIT License
|
CV_App/app/src/main/java/com/app/cv/ReferencesActivity.kt
|
katlaang
| 461,564,362
| false
| null |
package com.app.cv
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_contact.*
import kotlinx.android.synthetic.main.activity_references.*
class ReferencesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_references)
setSupportActionBar(toolbar_ref)
toolbar_ref.title
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
}
| 0
|
Kotlin
|
0
| 0
|
8efb8e9f4170189656d47dc5ffeedb1cd59eb30e
| 547
|
Mobile_Device_Programing
|
MIT License
|
feature-onboarding-impl/src/main/java/jp/co/soramitsu/onboarding/impl/OnboardingRouter.kt
|
soramitsu
| 278,060,397
| false
| null |
package jp.co.soramitsu.onboarding.impl
import jp.co.soramitsu.account.api.domain.model.ImportMode
import jp.co.soramitsu.account.api.presentation.account.create.ChainAccountCreatePayload
import jp.co.soramitsu.account.api.presentation.create_backup_password.CreateBackupPasswordPayload
import kotlinx.coroutines.flow.Flow
interface OnboardingRouter {
fun openCreateAccountFromOnboarding()
fun openCreateAccountSkipWelcome(payload: ChainAccountCreatePayload)
fun backToWelcomeScreen()
fun openImportAccountScreen(blockChainType: Int, importMode: ImportMode)
fun openImportAccountSkipWelcome(payload: ChainAccountCreatePayload)
fun openCreateWalletDialog(isFromGoogleBackup: Boolean)
fun openImportRemoteWalletDialog()
fun openCreateBackupPasswordDialog(payload: CreateBackupPasswordPayload)
fun openMnemonicAgreementsDialog(
isFromGoogleBackup: Boolean,
accountName: String
)
fun back()
fun backWithResult(vararg results: Pair<String, Any?>)
fun openSelectImportModeForResult(): Flow<ImportMode>
fun openCreatePincode()
fun openInitialCheckPincode()
}
| 9
| null |
30
| 89
|
1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2
| 1,144
|
fearless-Android
|
Apache License 2.0
|
story/src/main/java/com/yavuzmobile/story/CombinedAnimation.kt
|
mstfyvz
| 754,741,341
| false
|
{"Kotlin": 31553}
|
package com.yavuzmobile.story
import android.animation.PropertyValuesHolder
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.SweepGradient
import android.util.AttributeSet
import android.view.View
import androidx.annotation.CheckResult
import androidx.core.content.ContextCompat
import kotlin.math.cos
import kotlin.math.sin
class CombinedAnimation(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val dottedPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val numberOfPoints = 20
private val pointRadius = 5f
private var startAngle = -90f
private val sweepAngle = 360f / numberOfPoints
private var currentPointIndex = 0
private val desiredSize = 100.dpToPx()
private var width: Int = 0
private var height: Int = 0
private var currentPercentage = 0
var isOpened: Boolean = false
@CheckResult
get
set(value) {
field = value
invalidate()
}
private val ovalSpace = RectF()
private var colors: IntArray
private val fillArcPaint = Paint()
private val backgroundPaint = Paint()
init {
val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.StoryView, 0, 0)
isOpened = typedArray.getBoolean(R.styleable.StoryView_isOpened, false)
colors = intArrayOf(
ContextCompat.getColor(context, R.color.instagramRoyalBlue),
ContextCompat.getColor(context, R.color.instagramBlue),
ContextCompat.getColor(context, R.color.instagramPurple),
ContextCompat.getColor(context, R.color.instagramDarkPink),
ContextCompat.getColor(context, R.color.instagramPurpleRed),
ContextCompat.getColor(context, R.color.instagramRed),
ContextCompat.getColor(context, R.color.instagramDarkOrange),
ContextCompat.getColor(context, R.color.instagramOrange),
ContextCompat.getColor(context, R.color.instagramYellow),
ContextCompat.getColor(context, R.color.instagramLightYellow),
)
backgroundPaint.apply {
style = Paint.Style.STROKE
isAntiAlias = true
strokeWidth = 10f
strokeCap = Paint.Cap.ROUND
}
fillArcPaint.apply {
style = Paint.Style.STROKE
isAntiAlias = true
strokeWidth = 10f
strokeCap = Paint.Cap.ROUND
}
}
fun startAnimations() {
startDottedAnimation()
startArcAnimation()
}
private fun startDottedAnimation() {
val animator = ValueAnimator.ofInt(0, numberOfPoints)
animator.repeatCount = 0
animator.duration = 3000
animator.addUpdateListener { valueAnimator ->
currentPointIndex = valueAnimator.animatedValue as Int
startAngle = -90f + currentPointIndex * sweepAngle
invalidate()
}
animator.start()
}
private fun startArcAnimation() {
val valuesHolder = PropertyValuesHolder.ofFloat("percentage", 0f, 100f)
val animator = ValueAnimator().apply {
setValues(valuesHolder)
duration = 3000
addUpdateListener {
val percentage = it.getAnimatedValue("percentage") as Float
currentPercentage = percentage.toInt()
invalidate()
}
}
animator.start()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
width = resolveSize(desiredSize, widthMeasureSpec)
height = resolveSize(desiredSize, heightMeasureSpec)
setMeasuredDimension(width, height)
}
override fun onDraw(canvas: Canvas) {
if (isOpened) {
drawBackground(canvas)
} else {
drawDotted(canvas)
drawInnerArc(canvas)
}
}
private fun drawDotted(canvas: Canvas) {
val centerX = width / 2f
val centerY = height / 2f
for (i in 0 until numberOfPoints) {
val angle = startAngle + i * sweepAngle
val x = centerX + ((width - 10) / 2) * cos(Math.toRadians(angle.toDouble())).toFloat()
val y = centerY + ((height - 10) / 2) * sin(Math.toRadians(angle.toDouble())).toFloat()
dottedPaint.color = colors[i % colors.size]
canvas.drawCircle(x, y, pointRadius, dottedPaint)
}
}
private fun drawInnerArc(canvas: Canvas) {
setSpace()
val percentageToFill = (360 * (currentPercentage / 100.0)).toFloat()
// create gradient color
val gradientColors = IntArray(colors.size)
colors.indices.forEach {
gradientColors[it] = colors[it]
}
val gradient = SweepGradient(ovalSpace.centerX(), ovalSpace.centerY(), gradientColors, null)
fillArcPaint.shader = gradient
canvas.drawArc(ovalSpace, -90f, percentageToFill, false, fillArcPaint)
}
private fun drawBackground(canvas: Canvas) {
setSpace()
backgroundPaint.color = ContextCompat.getColor(context, R.color.gray)
canvas.drawCircle(width / 2.0f, height / 2.0f, (width - 10) / 2.0f, backgroundPaint)
}
private fun setSpace() {
val horizontalCenter = (width / 2).toFloat()
val verticalCenter = (height / 2).toFloat()
val ovalSize = (width - 10) / 2
ovalSpace.set(
horizontalCenter - ovalSize,
verticalCenter - ovalSize,
horizontalCenter + ovalSize,
verticalCenter + ovalSize
)
}
private fun Int.dpToPx(): Int {
val density = resources.displayMetrics.density
return (this * density).toInt()
}
}
| 0
|
Kotlin
|
0
| 0
|
d4eb8ff1b3d845f001320372a60b50af4244bb7c
| 5,874
|
story-view
|
MIT License
|
client/app/src/main/java/com/unina/natourkt/core/domain/use_case/auth/GetAuthStateUseCase.kt
|
archer-65
| 433,413,556
| false
| null |
package com.unina.natourkt.core.domain.use_case.auth
import com.unina.natourkt.core.domain.repository.AuthRepository
import javax.inject.Inject
/**
* This UseCase provides a fast way to check if an user is authenticated or not
* @see [AuthRepository]
*/
class GetAuthStateUseCase @Inject constructor(
private val authRepository: AuthRepository,
) {
suspend operator fun invoke(): Boolean {
return authRepository.fetchCurrentSession()
}
}
| 0
|
Kotlin
|
0
| 1
|
d0c4881e6b8432aff5cf1751d58350da2d5a4461
| 463
|
natour-2122
|
Apache License 2.0
|
src/main/kotlin/io/sc3/peripherals/client/block/PrintBakedModel.kt
|
SwitchCraftCC
| 526,790,497
| false
|
{"Kotlin": 177221, "Lua": 13313, "TypeScript": 11642, "Java": 9882, "JavaScript": 6018, "HTML": 638, "Dockerfile": 181, "CSS": 59}
|
package io.sc3.peripherals.client.block
import io.sc3.library.ext.faces
import io.sc3.library.ext.rotateTowards
import io.sc3.peripherals.Registration.ModBlockEntities
import io.sc3.peripherals.ScPeripherals.ModId
import io.sc3.peripherals.prints.*
import net.fabricmc.fabric.api.renderer.v1.RendererAccess
import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh
import net.fabricmc.fabric.api.renderer.v1.mesh.MeshBuilder
import net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView.BAKE_LOCK_UV
import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter
import net.fabricmc.fabric.api.renderer.v1.model.FabricBakedModel
import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
import net.fabricmc.fabric.api.resource.ResourceManagerHelper
import net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener
import net.minecraft.block.BlockState
import net.minecraft.client.MinecraftClient
import net.minecraft.client.render.model.BakedModel
import net.minecraft.client.render.model.BakedQuad
import net.minecraft.client.render.model.json.ModelOverrideList
import net.minecraft.client.render.model.json.ModelTransformation
import net.minecraft.client.texture.Sprite
import net.minecraft.client.util.SpriteIdentifier
import net.minecraft.item.ItemStack
import net.minecraft.resource.ResourceManager
import net.minecraft.resource.ResourceType
import net.minecraft.screen.PlayerScreenHandler.BLOCK_ATLAS_TEXTURE
import net.minecraft.text.Text.literal
import net.minecraft.util.Formatting.BOLD
import net.minecraft.util.Formatting.YELLOW
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
import net.minecraft.util.math.random.Random
import net.minecraft.world.BlockRenderView
import org.cache2k.Cache2kBuilder
import java.util.function.Supplier
class PrintBakedModel(
private val sprite: Sprite
) : BakedModel, FabricBakedModel {
private val mc by lazy { MinecraftClient.getInstance() }
private val missingModel by lazy { mc.bakedModelManager.missingModel }
private val meshBuilder = ThreadLocal.withInitial { RendererAccess.INSTANCE.renderer?.meshBuilder() }
override fun isVanillaAdapter() = false
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos,
randomSupplier: Supplier<Random>, ctx: RenderContext) {
// If the renderer or block entity are null, return missingModel before trying to do anything else
val builder = meshBuilder.get()
val be = blockView.getBlockEntity(pos, ModBlockEntities.print).orElse(null)
if (builder == null || be == null) {
// 2024-03-13: if the print is too far away, the BE/data will be null, so returning missingModel results in the
// world looking like you forgot to install Counter Strike: Source. so DON'T return missingModel here
// missingModel.emitBlockQuads(blockView, state, pos, randomSupplier, ctx)
return
}
val shapes = be.shapes // Get the shapes for the current state (on/off)
val shapesFacing = ShapesFacing(shapes, be.facing)
meshCache.computeIfAbsent(shapesFacing) {
buildPrintMesh(builder, shapes, be.facing)
}.outputTo(ctx.emitter)
}
override fun emitItemQuads(stack: ItemStack, randomSupplier: Supplier<Random>, ctx: RenderContext) {
// If the renderer is null, return missingModel before trying to do anything else
// Quick-fail for completely empty item stacks (REI, JEI, etc)
val builder = meshBuilder.get()
if (builder == null || !stack.hasNbt()) {
missingModel.emitItemQuads(stack, randomSupplier, ctx)
return
}
try {
// Allow this to throw when there are no shapes for the item stack
val printData = itemCache.computeIfAbsent(stack) {
PrintItem.printData(stack)
}
val shapes = printData.shapesOff
itemMeshCache.computeIfAbsent(shapes) {
buildPrintMesh(builder, shapes)
}.outputTo(ctx.emitter)
} catch (e: Exception) {
when(e) {
is NoPrintDataException -> { /* no-op */ }
else -> throw e // Let this bubble up to the consumer
}
// Show the invalid model
missingModel.emitItemQuads(stack, randomSupplier, ctx)
return
}
}
private fun buildPrintMesh(
builder: MeshBuilder,
shapes: Shapes,
facing: Direction = Direction.SOUTH
): Mesh? {
val emitter = builder.emitter
shapes.filter { it.texture != null }.forEach {
buildShape(emitter, it, facing)
}
return builder.build()
}
private fun buildShape(emitter: QuadEmitter, shape: Shape, facing: Direction) {
val bounds = shape.bounds.rotateTowards(facing)
val texture = shape.texture
// Discard original alpha component, then set it back to full alpha
val tint = ((shape.tint ?: 0xFFFFFF) and 0xFFFFFF) or 0xFF000000.toInt()
val spriteIdentifier = SpriteIdentifier(BLOCK_ATLAS_TEXTURE, texture)
val sprite = spriteIdentifier.sprite
// Generate the 6 faces for this Box, as a list of four vertices
val faces = bounds.faces
// Render each quad of the cube
for (dir in Direction.entries) {
// TODO: Since we are not using QuadEmitter.square(), we need to do the cullFace check ourselves
val face = faces[dir.ordinal]
emitter.cullFace(null)
emitter.nominalFace(dir)
emitter
.pos(0, face[0])
.pos(1, face[1])
.pos(2, face[2])
.pos(3, face[3])
.spriteBake(sprite, BAKE_LOCK_UV)
.color(0, tint)
.color(1, tint)
.color(2, tint)
.color(3, tint)
.emit()
}
}
override fun getQuads(state: BlockState?, face: Direction?, random: Random): MutableList<BakedQuad> =
mutableListOf() // Leave empty, as we are using FabricBakedModel instead
override fun useAmbientOcclusion() = true
override fun hasDepth() = false
override fun isSideLit() = false
override fun isBuiltin() = false
override fun getTransformation(): ModelTransformation = ModelHelper.MODEL_TRANSFORM_BLOCK
override fun getOverrides(): ModelOverrideList = ModelOverrideList.EMPTY
override fun getParticleSprite() = sprite
class NoPrintDataException : IllegalArgumentException("No print data found")
companion object {
private val reloadId = ModId("print_baked_model_cache_reloader")
// TODO: Tune these caches
private val meshCache = object : Cache2kBuilder<ShapesFacing, Mesh>() {}
.entryCapacity(10000)
.build()
private val itemMeshCache = object : Cache2kBuilder<Shapes, Mesh>() {}
.entryCapacity(1000)
.build()
private val itemCache = object : Cache2kBuilder<ItemStack, PrintData>() {}
.entryCapacity(10000)
.build()
private fun clearCaches() {
val count = meshCache.keys().size + itemMeshCache.keys().size + itemCache.keys().size
meshCache.clear()
itemMeshCache.clear()
itemCache.clear()
MinecraftClient.getInstance().player?.sendMessage(literal("")
.append(literal("[sc-peripherals] ").formatted(YELLOW, BOLD))
.append(literal("Cleared $count cached 3d print models")), false)
}
fun init() {
ResourceManagerHelper.get(ResourceType.CLIENT_RESOURCES).registerReloadListener(object : SimpleSynchronousResourceReloadListener {
override fun reload(manager: ResourceManager) {
clearCaches()
}
override fun getFabricId() = reloadId
})
}
}
}
| 6
|
Kotlin
|
7
| 10
|
65e643e5418af04412a35a8260271ece5e4f76e0
| 7,516
|
sc-peripherals
|
MIT License
|
regions/src/commonMain/kotlin/com/privateinternetaccess/regions/internals/PingPerformer.kt
|
pia-foss
| 272,978,863
| false
|
{"Kotlin": 94635}
|
package com.privateinternetaccess.regions.internals
internal expect class PingPerformer() {
/**
* @param endpoints Map<String, String>. Key: Region. String: Endpoint to ping in the region.
* @param callback Map<String, Long>. Key: Region. Value: Latency.
*/
fun pingEndpoints(
endpoints: Map<String, String>,
callback: (result: Map<String, Long>) -> Unit
)
}
| 0
|
Kotlin
|
1
| 0
|
592fc4f403df3006e98396fc5b063ad624d470b6
| 404
|
mobile-shared-regions
|
MIT License
|
app/src/main/java/com/nanchen/rxjava2examples/module/rxjava2/anmis/item/RxAnmiatorActivity.kt
|
tyty119
| 188,666,669
| false
|
{"Java": 188849, "Kotlin": 1428}
|
package com.nanchen.rxjava2examples.module.rxjava2.anmis.item
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.nanchen.rxjava2examples.R
/**
* Description:
* Author: PC306
* Date: 2019/5/26
*/
class RxAnmiatorActivity:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rx_anmi)
}
}
| 1
| null |
1
| 1
|
cc60112ff7d52dfdb138dc75964c5f0f02ed0820
| 440
|
BannerAnmiatorView
|
Apache License 2.0
|
android/src/main/java/com/rnvideoplayer/ui/controls/BottomControls.kt
|
MichelGutner
| 714,850,144
| false
|
{"Kotlin": 84600, "Swift": 72280, "TypeScript": 10099, "Ruby": 3216, "JavaScript": 2135, "Objective-C": 2040, "Objective-C++": 812, "C": 103}
|
package com.rnvideoplayer.ui.controls
import android.annotation.SuppressLint
import android.content.Context
import android.util.TypedValue
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.LinearLayout
import androidx.annotation.OptIn
import androidx.media3.common.util.UnstableApi
import com.rnvideoplayer.R
import com.rnvideoplayer.ui.components.CustomTimeBar
import com.rnvideoplayer.ui.components.Thumbnails
import com.rnvideoplayer.utilities.layoutParamsCenter
@OptIn(UnstableApi::class)
class BottomControls(context: Context) : FrameLayout(context) {
private val mainLayout = createMainLayout(context).apply {
layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply {
gravity = Gravity.BOTTOM
}
}
private val buttonsLayout = createButtonsLayout(context)
val menuControlLayout = createMenuControlLayout(context)
val fullscreenControlLayout = fullscreenControlLayout(context)
val fullscreenButton = createFullscreenButtonAnimated(context)
val timeBar = CustomTimeBar(context)
val thumbnails by lazy { Thumbnails(context) }
init {
fullscreenControlLayout.addView(fullscreenButton)
buttonsLayout.addView(menuControlLayout)
buttonsLayout.addView(fullscreenControlLayout)
mainLayout.addView(thumbnails)
mainLayout.addView(timeBar)
mainLayout.addView(buttonsLayout)
addView(mainLayout)
}
private fun createButtonsLayout(context: Context): LinearLayout {
return LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.END
}
}
private fun createMainLayout(context: Context): LinearLayout {
return LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
gravity = Gravity.BOTTOM
}
}
@SuppressLint("ResourceType")
private fun createMenuControlLayout(context: Context): LinearLayout {
val menuControlLayout = LinearLayout(context).apply {
layoutParams = LinearLayout.LayoutParams(dpToPx(40), dpToPx(40)).apply {
setMargins(dpToPx(4),dpToPx(4),dpToPx(4),dpToPx(8))
}
setBackgroundResource(R.drawable.rounded_background)
isClickable = true
isFocusable = true
visibility = INVISIBLE
}
val menuIcon = ImageButton(context).apply {
layoutParams = LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
val typedValue = TypedValue()
context.theme.resolveAttribute(
android.R.attr.selectableItemBackgroundBorderless,
typedValue,
true
)
setBackgroundResource(typedValue.resourceId)
setImageResource(R.drawable.baseline_more_horiz_24)
isClickable = false
isFocusable = false
}
menuControlLayout.addView(menuIcon)
return menuControlLayout
}
@SuppressLint("ResourceType")
private fun fullscreenControlLayout(context: Context): LinearLayout {
return LinearLayout(context).apply {
layoutParams = LinearLayout.LayoutParams(dpToPx(40), dpToPx(40)).apply {
setMargins(dpToPx(4), dpToPx(4), dpToPx(4), dpToPx(8))
}
setBackgroundResource(R.drawable.rounded_background)
visibility = INVISIBLE
}
}
@SuppressLint("ResourceType")
fun createFullscreenButtonAnimated(context: Context): ImageButton {
return ImageButton(context).apply {
layoutParams =
layoutParamsCenter(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
val typedValue = TypedValue()
context.theme.resolveAttribute(
android.R.attr.selectableItemBackgroundBorderless,
typedValue,
true
)
setBackgroundResource(typedValue.resourceId)
setImageResource(R.drawable.animated_full_to_exit)
}
}
private fun dpToPx(dp: Int): Int {
return (dp * context.resources.displayMetrics.density).toInt()
}
}
| 0
|
Kotlin
|
0
| 4
|
3ae08f4b017de93e389a2ee1d5dd6a6a4976d926
| 3,943
|
rn-media-player
|
MIT License
|
manager/src/main/java/com/markoid/manager/managers/MapsManager.kt
|
knockmark10
| 263,102,379
| false
| null |
package com.markoid.manager.managers
import android.content.Context
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.PorterDuff
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.*
import com.markoid.manager.R
import com.markoid.manager.entities.MarkerItem
import com.markoid.manager.enums.MapStyles
import java.util.*
class MapsManager(
private val mContext: Context,
private val mGoogleMap: GoogleMap
) {
private val mMarkersList = mutableListOf<MarkerItem>()
private val inflater: LayoutInflater
get() = this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
/**
* Turns drawable into bitmap to use as a marker
*/
fun getIconFromDrawable(@DrawableRes drawable: Int): BitmapDescriptor? {
val icon = getMarkerBitmapFromView(drawable)
return BitmapDescriptorFactory.fromBitmap(icon)
}
/**
* Adds marker into the map, while saving an internal list for every marker.
*/
fun addMarker(id: String, markerOptions: MarkerOptions) {
val marker = this.mGoogleMap.addMarker(markerOptions)
this.saveMarker(MarkerItem(id, marker))
}
/**
* Get the list of markers added to the map
*/
fun getAllMarkers(): List<Marker> =
this.mMarkersList.map { it.marker }
/**
* Get a marker with a condition set
*/
fun getMarkerBy(condition: (item: MarkerItem) -> Boolean): Marker? =
this.mMarkersList.firstOrNull(condition)?.marker
/**
* Clear markers from map
*/
fun clearMakers() {
this.mMarkersList.clear()
this.mGoogleMap.clear()
}
/**
* Choose between Aubergine, Dark, Night,
* Retro, Silver or default style for
* your map
*/
fun setMapStyle(style: MapStyles) {
this.mGoogleMap.setMapStyle(style)
}
/**
* Sets the map style according to the daylight
*/
fun setDaylightStyle() {
this.mGoogleMap.setDaylightStyle()
}
/**
* Set the camera to desire position with custom zoom
*/
fun setCurrentPosition(position: LatLng, zoom: Float) {
this.mGoogleMap.setCurrentPosition(position, zoom)
}
/**
* Centers the camera with a marker list given
*/
fun centerCamera(markerList: List<Marker>, zoom: Float) {
this.mGoogleMap.centerCamera(markerList, zoom)
}
/**
* Centers the camera with a positions list given
*/
fun centerMarkers(positionList: List<LatLng>) {
this.mGoogleMap.centerMarkers(positionList)
}
/**
* Draws a circle within the map with the given parameters.
* You can define the color of the stroke, the color of the circle
* itself and the width of the stroke.
*/
fun drawCircle(
location: LatLng,
radius: Double,
@ColorInt strokeColor: Int = Color.BLACK,
@ColorInt fillColor: Int = 0x30ff0000,
strokeWidth: Float = 2f
) {
this.mGoogleMap.drawCircle(location, radius, strokeColor, fillColor, strokeWidth)
}
private fun getMarkerBitmapFromView(@DrawableRes resourceId: Int): Bitmap {
val customMarkerView = this.inflater.inflate(R.layout.custom_marker, null)
val markerImageView = customMarkerView.findViewById(R.id.custom_marker_icon) as ImageView
markerImageView.setImageResource(resourceId)
customMarkerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
customMarkerView.layout(
0,
0,
customMarkerView.measuredWidth,
customMarkerView.measuredHeight
)
customMarkerView.buildDrawingCache()
val returnedBitmap = Bitmap.createBitmap(
customMarkerView.measuredWidth, customMarkerView.measuredHeight,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(returnedBitmap)
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN)
customMarkerView.background?.draw(canvas)
customMarkerView.draw(canvas)
return returnedBitmap
}
private fun saveMarker(marker: MarkerItem) {
this.mMarkersList.add(marker)
}
private fun GoogleMap.setMapStyle(style: MapStyles) {
val rawStyle: Int =
when (style) {
MapStyles.Aubergine -> R.raw.map_auberine
MapStyles.Dark -> R.raw.map_dark
MapStyles.Night -> R.raw.map_night
MapStyles.Retro -> R.raw.map_retro
MapStyles.Silver -> R.raw.map_silver
MapStyles.Default -> R.raw.map_default
is MapStyles.Custom -> style.rawMap
}
try {
val selectedStyle = MapStyleOptions.loadRawResourceStyle(mContext, rawStyle)
val success = this.setMapStyle(selectedStyle)
if (!success) Log.e("Error", "Style parsing failed")
} catch (e: Resources.NotFoundException) {
Log.e("Error", "Can't find style")
}
}
private fun GoogleMap.setDaylightStyle() {
val style: MapStyles =
when (Calendar.getInstance().get(Calendar.HOUR_OF_DAY)) {
in 8..11 -> MapStyles.Default
in 12..18 -> MapStyles.Retro
in 19..21 -> MapStyles.Aubergine
in 22..23 -> MapStyles.Night
else -> MapStyles.Dark
}
this.setMapStyle(style)
}
private fun GoogleMap.setCurrentPosition(position: LatLng, zoom: Float) {
val cameraPosition = CameraPosition.Builder().target(position).zoom(zoom).build()
this.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
private fun GoogleMap.centerCamera(listMarker: List<Marker>, zoom: Float) {
var latitude = 0.0
var longitude = 0.0
for (marker in listMarker) {
latitude += marker.position.latitude
longitude += marker.position.longitude
}
if (listMarker.isNotEmpty()) {
latitude /= listMarker.size
longitude /= listMarker.size
}
val cameraPosition =
CameraPosition.Builder().target(LatLng(latitude, longitude)).zoom(zoom).build()
this.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
private fun GoogleMap.centerMarkers(latLngList: List<LatLng>) {
val latLngBounds = LatLngBounds.Builder()
latLngList.forEach { latLngBounds.include(it) }
val bounds = latLngBounds.build()
val width = mContext.resources.displayMetrics.widthPixels
val height = mContext.resources.displayMetrics.heightPixels
val padding = (width * 0.10).toInt()
val cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding)
this.animateCamera(cameraUpdate)
}
private fun GoogleMap.drawCircle(
location: LatLng,
radius: Double,
@ColorInt strokeColor: Int = Color.BLACK,
@ColorInt fillColor: Int = 0x30ff0000,
strokeWidth: Float = 2f
): Circle {
val circleOptions = CircleOptions().apply {
center(location)
radius(radius)
strokeColor(strokeColor)
fillColor(fillColor)
strokeWidth(strokeWidth)
}
return this.addCircle(circleOptions)
}
}
| 0
|
Kotlin
|
0
| 0
|
3eb2d8d1fa668af7b62fdb7bfcc46e811e432d92
| 7,784
|
GoogleMapsManager
|
MIT License
|
app/src/main/java/nerd/tuxmobil/fahrplan/congress/models/Alarm.kt
|
grote
| 114,628,676
| true
|
{"Java": 333159, "Kotlin": 125801, "Prolog": 647}
|
package nerd.tuxmobil.fahrplan.congress.models
import info.metadude.android.eventfahrplan.database.contract.FahrplanContract
data class Alarm(
val id: Int,
val alarmTimeInMin: Int,
val day: Int,
val displayTime: Long,
val eventId: String,
val eventTitle: String,
val startTime: Long,
val timeText: String
) {
constructor(
alarmTimeInMin: Int,
day: Int,
displayTime: Long,
eventId: String,
eventTitle: String,
startTime: Long,
timeText: String
) : this(
DEFAULT_VALUE_ID,
alarmTimeInMin,
day,
displayTime,
eventId,
eventTitle,
startTime,
timeText
)
companion object {
const val DEFAULT_VALUE_ID = FahrplanContract.AlarmsTable.Defaults.DEFAULT_VALUE_ID
}
}
| 0
|
Java
|
1
| 3
|
761d339bf804698760db17ba00990e164f90cff2
| 934
|
EventFahrplan
|
Apache License 2.0
|
agent/src/main/kotlin/org/nessus/didcomm/service/CamelEndpointService.kt
|
tdiesler
| 578,916,709
| false
| null |
/*-
* #%L
* Nessus DIDComm :: Agent
* %%
* Copyright (C) 2022 - 2023 Nessus
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.nessus.didcomm.service
import mu.KotlinLogging
import org.apache.camel.CamelContext
import org.apache.camel.Exchange
import org.apache.camel.builder.RouteBuilder
import org.apache.camel.impl.DefaultCamelContext
import org.nessus.didcomm.model.EndpointMessage
import org.nessus.didcomm.util.encodeJson
import java.io.PrintWriter
import java.io.StringWriter
import java.net.HttpURLConnection.HTTP_INTERNAL_ERROR
import java.net.HttpURLConnection.HTTP_OK
class CamelEndpointService: EndpointService<CamelContext>() {
private val log = KotlinLogging.logger {}
private val dashboard get() = DashboardService.getService()
private val receiverService get() = MessageReceiverService.getService()
override fun startEndpoint(endpointUrl: String, dispatcher: MessageReceiver?): CamelContext {
log.info("Starting Camel endpoint on: $endpointUrl")
val camelctx: CamelContext = DefaultCamelContext()
camelctx.addRoutes(object: RouteBuilder(camelctx) {
override fun configure() {
from("undertow:$endpointUrl?matchOnUriPrefix=true")
.process { exchange ->
val headers = exchange.message.headers
when(val httpMethod = headers["CamelHttpMethod"]) {
"GET" -> dashboard.processHttpGet(exchange)
"POST" -> processDidCommMessage(exchange, dispatcher)
else -> throw IllegalStateException("Unsupported HTTP method: $httpMethod")
}
}
}
})
camelctx.start()
return camelctx
}
// Private ---------------------------------------------------------------------------------------------------------
private fun processDidCommMessage(exchange: Exchange, messageReceiver: MessageReceiver?) {
val headers = exchange.message.headers
val body = exchange.message.getBody(String::class.java)
checkNotNull(body) { "No message body" }
runCatching {
val epm = EndpointMessage.Builder(body, headers)
.inbound()
.build()
(messageReceiver ?: receiverService).invoke(epm)
headers[Exchange.HTTP_RESPONSE_CODE] = HTTP_OK
headers[Exchange.CONTENT_TYPE] = "application/json"
exchange.message.body = "{}"
}.onFailure { th ->
headers[Exchange.HTTP_RESPONSE_CODE] = HTTP_INTERNAL_ERROR // Internal Server Error
headers[Exchange.CONTENT_TYPE] = "application/json"
val sw = StringWriter()
th.printStackTrace(PrintWriter(sw))
val traceLines = "$sw".lines().map { it.trim() }.find { it.isNotEmpty() }
exchange.message.body = mapOf(
"msg" to th.message,
"trace" to traceLines,
).encodeJson()
log.error(th) { th.message }
}
}
}
| 28
|
Kotlin
|
1
| 8
|
c199c1289544c706797e755e18f6fba2cbf2832b
| 3,625
|
nessus-didcomm
|
Apache License 2.0
|
src/main/kotlin/com/github/optimisticgeek/editor/httpClient/SpringApiHttpTestExt.kt
|
OptimisticGeek
| 734,509,440
| false
|
{"Kotlin": 107151, "Java": 6491}
|
// Copyright 2023-2024 OptimisticGeek. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.github.optimisticgeek.editor.httpClient
import com.github.optimisticgeek.analyze.model.AnalyzeHttpMethod
import com.github.optimisticgeek.editor.listener.toJson
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import java.io.File
@JvmName("createHttpTestFile")
fun AnalyzeHttpMethod.createHttpTestFile(isShow: Boolean = true, flushed: Boolean = false) {
val keyword = "### $position"
project.getHttpTestFile(position!!)
.let { LocalFileSystem.getInstance().refreshAndFindFileByIoFile(it) }
?.run {
FileDocumentManager.getInstance().getDocument(this)?.apply {
runWriteAction {
// 创建多环境变量文件
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(project.createHttpTestEvnFile())
if (text.indexOf(keyword) == -1) {
setText(text + createHttpTestStr())
} else if (flushed) {
setText(text.replace(Regex("(### $position[\\s\\S]*?$END_FIX)"), createHttpTestStr()))
} else return@runWriteAction
FileDocumentManager.getInstance().saveDocument(this)
}
}?.text?.indexOf(keyword).let {
OpenFileDescriptor(project, this, it ?: -1).navigate(isShow)
}
}
}
@JvmName("hasHttpTestFile")
fun AnalyzeHttpMethod.hasHttpTestMethod(): Boolean {
return project.getHttpTestFile(position!!, false)
.also { if (!it.exists()) return false }
.readText().contains("### $position")
}
private const val END_FIX = "### END\n\n\n\n"
@JvmName("createHttpTestStr")
private fun AnalyzeHttpMethod.createHttpTestStr(): String {
val sb = StringBuilder("### $position\n")
sb.appendLine("# @name ${if (remark.isNullOrBlank()) name else remark} $author").appendLine()
sb.appendLine("$httpMethod {{host}}${getUrl(true, hasRootUrl = true)}")
requestBody?.let { sb.appendLine("Content-Type: application/json") }
response?.let { sb.appendLine("Accept: application/json") }
sb.appendLine("Authorization: {{token}}").appendLine("Cookie: {{cookie}}")
sb.appendLine()
requestBody?.let { sb.appendLine(requestBody.toJson(false)).appendLine() }
sb.append(END_FIX)
return sb.toString()
}
/**
* 获取测试文件目录
*
* @param qName 方法的position
*/
@JvmName("getHttpTestPath")
private fun Project.getHttpTestFile(qName: String, isCreate: Boolean = true): File {
return buildString {
append("$basePath${File.separator}.http${File.separator}")
append(qName.replaceFirst(Regex("#\\w+"), "").replace('.', File.separatorChar))
append(".http")
}.let { File(it) }.apply {
if (!exists() && isCreate) {
parentFile.mkdirs()
createNewFile()
}
}
}
@JvmName("createHttpTestEvnFile")
private fun Project.createHttpTestEvnFile(): File {
return File("$basePath${File.separator}.http${File.separator}http-client.env.json")
.apply { if (exists()) return@apply }
.apply { parentFile.mkdirs();createNewFile() }
.apply { appendText(http_client_evn) }
}
private const val http_client_evn = """
{
"dev": {
"host": "http://localhost",
"cookie": "",
"token": ""
},
"release": {
"host": "https://www.baidu.com",
"cookie": "",
"token": ""
}
}
"""
| 0
|
Kotlin
|
1
| 2
|
b4182ed171738d6c00cc9e590b9226ddba54f91c
| 3,716
|
spring-doc-helper
|
Apache License 2.0
|
app/src/main/java/com/breezefieldsalesmaxpaints/features/member/CustomerOnClick.kt
|
DebashisINT
| 798,102,822
| false
|
{"Kotlin": 14782094, "Java": 1023489}
|
package com.breezefieldsalesmaxpaints.features.member
import com.breezefieldsalesmaxpaints.features.member.model.CustomerDataModel
interface CustomerOnClick {
fun OnClick(obj: CustomerDataModel)
}
| 0
|
Kotlin
|
0
| 0
|
b850214769e3579daf79ca8476e65c92bff845f5
| 202
|
MaxPaints
|
Apache License 2.0
|
pushreceiver/src/main/java/pro/devonics/push/PushCache.kt
|
PushDevonics
| 479,396,096
| false
|
{"Kotlin": 39459}
|
package pro.devonics.push
import android.content.Context
private const val TAG = "PushCache"
class PushCache {
private val PUSH_CACHE = "push_cache"
private val REGISTRATION_ID = "registration_id"
private val SUBSCRIBE_STATUS = "subscribe_status"
private val INTERNAL_ID = "internal_id"
private val TAG_KEY = "tag_key"
private val TAG_VALUE = "tag_value"
private val appContext = AppContextKeeper.getContext()
private val ed = appContext
.getSharedPreferences(PUSH_CACHE, Context.MODE_PRIVATE)
?.edit()
fun saveTagKey(key: String) {
ed?.putString(TAG_KEY, key)
ed?.apply()
}
fun getTagKey(): String? {
return appContext
.getSharedPreferences(PUSH_CACHE, Context.MODE_PRIVATE)
?.getString(TAG_KEY, null)
}
fun saveTagValue(value: String) {
ed?.putString(TAG_VALUE, value)
ed?.apply()
}
fun getTagValue(): String? {
return appContext
.getSharedPreferences(PUSH_CACHE, Context.MODE_PRIVATE)
?.getString(TAG_VALUE, null)
}
fun saveInternalId(internalId: String) {
ed?.putString(INTERNAL_ID, internalId)
ed?.apply()
}
fun getInternalId(): String? {
return appContext
.getSharedPreferences(PUSH_CACHE, Context.MODE_PRIVATE)
?.getString(INTERNAL_ID, null)
}
fun saveRegistrationId(regId: String) {
ed?.putString(REGISTRATION_ID, regId)
ed?.apply()
}
fun getRegistrationId(): String? {
return appContext
.getSharedPreferences(PUSH_CACHE, Context.MODE_PRIVATE)
?.getString(REGISTRATION_ID, null)
}
fun saveSubscribeStatus(status: Boolean) {
ed?.putBoolean(SUBSCRIBE_STATUS, status)
ed?.apply()
}
fun getSubscribeStatus(): Boolean? {
return appContext
.getSharedPreferences(PUSH_CACHE, Context.MODE_PRIVATE)
?.getBoolean(SUBSCRIBE_STATUS, false)
}
}
| 0
|
Kotlin
|
2
| 0
|
2634621d0ea70ed0910a55b260c30224c71b584f
| 2,022
|
push-devonics-unity
|
MIT License
|
designer/src/com/android/tools/idea/annotations/TestDumbService.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.annotations
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.AccessToken
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.DumbModeBlockedFunctionality
import com.intellij.openapi.project.DumbModeTask
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import javax.swing.JComponent
import javax.swing.JPanel
/**
* [DumbService] implementation to be used in tests.
*
* TODO(b/228294269): Move this to the dedicated testutil module.
*/
class TestDumbService(
override val project: Project,
) : DumbService() {
private val smartRunnables = mutableListOf<Runnable>()
private var modifications = 0L
var dumbMode = true
set(value) {
field = value
modifications++
if (!value) {
smartRunnables.forEach { it.run() }
smartRunnables.clear()
}
}
override val modificationTracker: ModificationTracker = ModificationTracker { modifications }
override val isDumb: Boolean = dumbMode
override var isAlternativeResolveEnabled: Boolean =false
override fun runWhenSmart(runnable: Runnable) {
if (isDumb) {
smartRunnables.add(runnable)
} else {
runnable.run()
}
}
override fun waitForSmartMode() {}
override fun smartInvokeLater(runnable: Runnable) {}
override fun smartInvokeLater(runnable: Runnable, modalityState: ModalityState) {}
override fun queueTask(task: DumbModeTask) {}
override fun cancelTask(task: DumbModeTask) {}
override fun cancelAllTasksAndWait() {}
override fun completeJustSubmittedTasks() {}
override fun wrapGently(
dumbUnawareContent: JComponent,
parentDisposable: Disposable
): JComponent = JPanel()
override fun wrapWithSpoiler(
dumbAwareContent: JComponent,
updateRunnable: Runnable,
parentDisposable: Disposable
): JComponent = JPanel()
override fun showDumbModeNotification(message: String) {}
override fun showDumbModeNotificationForFunctionality(message: String, functionality: DumbModeBlockedFunctionality) {}
override fun showDumbModeNotificationForAction(message: String, actionId: String?) {}
override fun showDumbModeActionBalloon(balloonText: String, runWhenSmartAndBalloonStillShowing: Runnable, actionIds: List<String>) {}
override fun suspendIndexingAndRun(activityName: String, activity: Runnable) {}
override suspend fun suspendIndexingAndRun(activityName: String, activity: suspend () -> Unit) {}
override fun runWithWaitForSmartModeDisabled(): AccessToken = error("Not implemented")
override fun unsafeRunWhenSmart(runnable: Runnable) {}
}
| 3
| null |
228
| 912
|
d88742a5542b0852e7cb2dd6571e01576cb52841
| 3,354
|
android
|
Apache License 2.0
|
timber-lint/src/test/java/timber/lint/WrongTimberUsageDetectorTest.kt
|
JakeWharton
| 11,495,787
| false
| null |
package timber.lint
import com.android.tools.lint.checks.infrastructure.TestFiles.java
import com.android.tools.lint.checks.infrastructure.TestFiles.kotlin
import com.android.tools.lint.checks.infrastructure.TestFiles.manifest
import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
import org.junit.Test
import timber.lint.WrongTimberUsageDetector.Companion.issues
class WrongTimberUsageDetectorTest {
private val TIMBER_STUB = kotlin("""
|package timber.log
|class Timber private constructor() {
| private companion object {
| @JvmStatic fun d(message: String?, vararg args: Any?) {}
| @JvmStatic fun d(t: Throwable?, message: String, vararg args: Any?) {}
| @JvmStatic fun tag(tag: String) = Tree()
| }
| open class Tree {
| open fun d(message: String?, vararg args: Any?) {}
| open fun d(t: Throwable?, message: String?, vararg args: Any?) {}
| }
|}""".trimMargin().toString())
@Test fun usingAndroidLogWithTwoArguments() {
lint()
.files(
java("""
|package foo;
|import android.util.Log;
|public class Example {
| public void log() {
| Log.d("TAG", "msg");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import android.util.Log
|class Example {
| fun log() {
| Log.d("TAG", "msg")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| Log.d("TAG", "msg");
| ~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| Log.d("TAG", "msg")
| ~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Replace with Timber.tag("TAG").d("msg"):
|@@ -5 +5
|- Log.d("TAG", "msg");
|+ Timber.tag("TAG").d("msg");
|Fix for src/foo/Example.java line 5: Replace with Timber.d("msg"):
|@@ -5 +5
|- Log.d("TAG", "msg");
|+ Timber.d("msg");
|Fix for src/foo/Example.kt line 5: Replace with Timber.tag("TAG").d("msg"):
|@@ -5 +5
|- Log.d("TAG", "msg")
|+ Timber.tag("TAG").d("msg")
|Fix for src/foo/Example.kt line 5: Replace with Timber.d("msg"):
|@@ -5 +5
|- Log.d("TAG", "msg")
|+ Timber.d("msg")
|""".trimMargin().toString())
}
@Test fun usingAndroidLogWithThreeArguments() {
lint()
.files(
java("""
|package foo;
|import android.util.Log;
|public class Example {
| public void log() {
| Log.d("TAG", "msg", new Exception());
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import android.util.Log
|class Example {
| fun log() {
| Log.d("TAG", "msg", Exception())
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| Log.d("TAG", "msg", new Exception());
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| Log.d("TAG", "msg", Exception())
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Replace with Timber.tag("TAG").d(new Exception(), "msg"):
|@@ -5 +5
|- Log.d("TAG", "msg", new Exception());
|+ Timber.tag("TAG").d(new Exception(), "msg");
|Fix for src/foo/Example.java line 5: Replace with Timber.d(new Exception(), "msg"):
|@@ -5 +5
|- Log.d("TAG", "msg", new Exception());
|+ Timber.d(new Exception(), "msg");
|Fix for src/foo/Example.kt line 5: Replace with Timber.tag("TAG").d(Exception(), "msg"):
|@@ -5 +5
|- Log.d("TAG", "msg", Exception())
|+ Timber.tag("TAG").d(Exception(), "msg")
|Fix for src/foo/Example.kt line 5: Replace with Timber.d(Exception(), "msg"):
|@@ -5 +5
|- Log.d("TAG", "msg", Exception())
|+ Timber.d(Exception(), "msg")
|""".trimMargin().toString())
}
@Test fun usingFullyQualifiedAndroidLogWithTwoArguments() {
lint()
.files(
java("""
|package foo;
|public class Example {
| public void log() {
| android.util.Log.d("TAG", "msg");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|class Example {
| fun log() {
| android.util.Log.d("TAG", "msg")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:4: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| android.util.Log.d("TAG", "msg");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:4: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| android.util.Log.d("TAG", "msg")
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 4: Replace with Timber.tag("TAG").d("msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg");
|+ Timber.tag("TAG").d("msg");
|Fix for src/foo/Example.java line 4: Replace with Timber.d("msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg");
|+ Timber.d("msg");
|Fix for src/foo/Example.kt line 4: Replace with Timber.tag("TAG").d("msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg")
|+ Timber.tag("TAG").d("msg")
|Fix for src/foo/Example.kt line 4: Replace with Timber.d("msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg")
|+ Timber.d("msg")
|""".trimMargin().toString())
}
@Test fun usingFullyQualifiedAndroidLogWithThreeArguments() {
lint()
.files(
java("""
|package foo;
|public class Example {
| public void log() {
| android.util.Log.d("TAG", "msg", new Exception());
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|class Example {
| fun log() {
| android.util.Log.d("TAG", "msg", Exception())
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:4: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| android.util.Log.d("TAG", "msg", new Exception());
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:4: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| android.util.Log.d("TAG", "msg", Exception())
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 4: Replace with Timber.tag("TAG").d(new Exception(), "msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg", new Exception());
|+ Timber.tag("TAG").d(new Exception(), "msg");
|Fix for src/foo/Example.java line 4: Replace with Timber.d(new Exception(), "msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg", new Exception());
|+ Timber.d(new Exception(), "msg");
|Fix for src/foo/Example.kt line 4: Replace with Timber.tag("TAG").d(Exception(), "msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg", Exception())
|+ Timber.tag("TAG").d(Exception(), "msg")
|Fix for src/foo/Example.kt line 4: Replace with Timber.d(Exception(), "msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg", Exception())
|+ Timber.d(Exception(), "msg")
|""".trimMargin().toString())
}
@Test fun innerStringFormat() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d(String.format("%s", "arg1"));
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d(String.format("%s", "arg1"))
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(String.format("%s", "arg1"));
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(String.format("%s", "arg1"))
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Remove String.format(...):
|@@ -5 +5
|- Timber.d(String.format("%s", "arg1"));
|+ Timber.d("%s", "arg1");
|Fix for src/foo/Example.kt line 5: Remove String.format(...):
|@@ -5 +5
|- Timber.d(String.format("%s", "arg1"))
|+ Timber.d("%s", "arg1")
|""".trimMargin().toString())
}
@Test fun innerStringFormatWithStaticImport() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|import static java.lang.String.format;
|public class Example {
| public void log() {
| Timber.d(format("%s", "arg1"));
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|import java.lang.String.format
|class Example {
| fun log() {
| Timber.d(format("%s", "arg1"))
| }
|}""".trimMargin().toString())
)
// Remove when AGP 7.1.0-alpha07 is out
// https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.allowCompilationErrors()
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(format("%s", "arg1"));
| ~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(format("%s", "arg1"))
| ~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Remove String.format(...):
|@@ -6 +6
|- Timber.d(format("%s", "arg1"));
|+ Timber.d("%s", "arg1");
|Fix for src/foo/Example.kt line 6: Remove String.format(...):
|@@ -6 +6
|- Timber.d(format("%s", "arg1"))
|+ Timber.d("%s", "arg1")
|""".trimMargin().toString())
}
@Test fun innerStringFormatInNestedMethods() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d(id(String.format("%s", "arg1")));
| }
| private String id(String s) { return s; }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d(id(String.format("%s", "arg1")))
| }
| private fun id(s: String): String { return s }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(id(String.format("%s", "arg1")));
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(id(String.format("%s", "arg1")))
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
}
@Test fun innerStringFormatInNestedAssignment() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String msg = null;
| Timber.d(msg = String.format("msg"));
| }
|}""".trimMargin().toString())
// no kotlin equivalent, since nested assignments do not exist
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(msg = String.format("msg"));
| ~~~~~~~~~~~~~~~~~~~~
|0 errors, 1 warnings""".trimMargin().toString())
}
@Test fun validStringFormatInCodeBlock() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|public class Example {
| public void log() {
| for(;;) {
| String name = String.format("msg");
| }
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|class Example {
| fun log() {
| while(true) {
| val name = String.format("msg")
| }
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun validStringFormatInConstructorCall() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|public class Example {
| public void log() {
| new Exception(String.format("msg"));
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|class Example {
| fun log() {
| Exception(String.format("msg"))
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun validStringFormatInStaticArray() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|public class Example {
| static String[] X = { String.format("%s", 100) };
|}""".trimMargin().toString()),
kotlin("""
|package foo
|class Example {
| companion object {
| val X = arrayOf(String.format("%s", 100))
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun validStringFormatExtracted() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String message = String.format("%s", "foo");
| Timber.d(message);
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val message = String.format("%s", "foo")
| Timber.d(message)
| }
|}""".trimMargin().toString()),
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun throwableNotAtBeginning() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d("%s", e);
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d("%s", e)
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Throwable should be first argument [ThrowableNotAtBeginning]
| Timber.d("%s", e);
| ~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Throwable should be first argument [ThrowableNotAtBeginning]
| Timber.d("%s", e)
| ~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Replace with e, "%s":
|@@ -6 +6
|- Timber.d("%s", e);
|+ Timber.d(e, "%s");
|Fix for src/foo/Example.kt line 6: Replace with e, "%s":
|@@ -6 +6
|- Timber.d("%s", e)
|+ Timber.d(e, "%s")
|""".trimMargin().toString())
}
@Test fun stringConcatenationBothLiterals() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("foo" + "bar");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("foo" + "bar")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun stringConcatenationLeftLiteral() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String foo = "foo";
| Timber.d(foo + "bar");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val foo = "foo"
| Timber.d("${"$"}{foo}bar")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Replace String concatenation with Timber's string formatting [BinaryOperationInTimber]
| Timber.d(foo + "bar");
| ~~~~~~~~~~~
|0 errors, 1 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Replace with "%sbar", foo:
|@@ -6 +6
|- Timber.d(foo + "bar");
|+ Timber.d("%sbar", foo);
|""".trimMargin().toString())
}
@Test fun stringConcatenationRightLiteral() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String bar = "bar";
| Timber.d("foo" + bar);
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val bar = "bar"
| Timber.d("foo${"$"}bar")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Replace String concatenation with Timber's string formatting [BinaryOperationInTimber]
| Timber.d("foo" + bar);
| ~~~~~~~~~~~
|0 errors, 1 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Replace with "foo%s", bar:
|@@ -6 +6
|- Timber.d("foo" + bar);
|+ Timber.d("foo%s", bar);
|""".trimMargin().toString())
}
@Test fun stringConcatenationBothVariables() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String foo = "foo";
| String bar = "bar";
| Timber.d(foo + bar);
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val foo = "foo"
| val bar = "bar"
| Timber.d("${"$"}foo${"$"}bar")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:7: Warning: Replace String concatenation with Timber's string formatting [BinaryOperationInTimber]
| Timber.d(foo + bar);
| ~~~~~~~~~
|0 errors, 1 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Replace with "%s%s", foo, bar:
|@@ -7 +7
|- Timber.d(foo + bar);
|+ Timber.d("%s%s", foo, bar);
|""".trimMargin().toString())
}
@Test fun stringConcatenationInsideTernary() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String s = "world!";
| Timber.d(true ? "Hello, " + s : "Bye");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val s = "world!"
| Timber.d(if(true) "Hello, ${"$"}s" else "Bye")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Replace String concatenation with Timber's string formatting [BinaryOperationInTimber]
| Timber.d(true ? "Hello, " + s : "Bye");
| ~~~~~~~~~~~~~
|0 errors, 1 warnings""".trimMargin().toString())
}
@Test fun tooManyFormatArgs() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%s %s", "arg1");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("%s %s", "arg1")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument count, format string %s %s requires 2 but format call supplies 1 [TimberArgCount]
| Timber.d("%s %s", "arg1");
| ~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument count, format string %s %s requires 2 but format call supplies 1 [TimberArgCount]
| Timber.d("%s %s", "arg1")
| ~~~~~~~~~~~~~~~~~~~~~~~~~
|2 errors, 0 warnings""".trimMargin().toString())
}
@Test fun tooManyArgs() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%s", "arg1", "arg2");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("%s", "arg1", "arg2")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument count, format string %s requires 1 but format call supplies 2 [TimberArgCount]
| Timber.d("%s", "arg1", "arg2");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument count, format string %s requires 1 but format call supplies 2 [TimberArgCount]
| Timber.d("%s", "arg1", "arg2")
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|2 errors, 0 warnings""".trimMargin().toString())
}
@Test fun wrongArgTypes() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%d", "arg1");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("%d", "arg1")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument type for formatting argument '#1' in %d: conversion is 'd', received String (argument #2 in method call) [TimberArgTypes]
| Timber.d("%d", "arg1");
| ~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument type for formatting argument '#1' in %d: conversion is 'd', received String (argument #2 in method call) [TimberArgTypes]
| Timber.d("%d", "arg1")
| ~~~~
|2 errors, 0 warnings""".trimMargin().toString())
}
@Test fun tagTooLongLiteralOnly() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.tag("abcdefghijklmnopqrstuvwx");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.tag("abcdefghijklmnopqrstuvwx")
| }
|}""".trimMargin().toString()),
manifest().minSdk(25)
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: The logging tag can be at most 23 characters, was 24 (abcdefghijklmnopqrstuvwx) [TimberTagLength]
| Timber.tag("abcdefghijklmnopqrstuvwx");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin().toString())
}
@Test fun tagTooLongLiteralOnlyBeforeApi26() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.tag("abcdefghijklmnopqrstuvwx");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.tag("abcdefghijklmnopqrstuvwx")
| }
|}""".trimMargin().toString()),
manifest().minSdk(26)
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun tooManyFormatArgsInTag() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.tag("tag").d("%s %s", "arg1");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.tag("tag").d("%s %s", "arg1")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument count, format string %s %s requires 2 but format call supplies 1 [TimberArgCount]
| Timber.tag("tag").d("%s %s", "arg1");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument count, format string %s %s requires 2 but format call supplies 1 [TimberArgCount]
| Timber.tag("tag").d("%s %s", "arg1")
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|2 errors, 0 warnings""".trimMargin().toString())
}
@Test fun tooManyArgsInTag() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.tag("tag").d("%s", "arg1", "arg2");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.tag("tag").d("%s", "arg1", "arg2")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument count, format string %s requires 1 but format call supplies 2 [TimberArgCount]
| Timber.tag("tag").d("%s", "arg1", "arg2");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument count, format string %s requires 1 but format call supplies 2 [TimberArgCount]
| Timber.tag("tag").d("%s", "arg1", "arg2")
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|2 errors, 0 warnings""".trimMargin().toString())
}
@Test fun wrongArgTypesInTag() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.tag("tag").d("%d", "arg1");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.tag("tag").d("%d", "arg1")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument type for formatting argument '#1' in %d: conversion is 'd', received String (argument #2 in method call) [TimberArgTypes]
| Timber.tag("tag").d("%d", "arg1");
| ~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument type for formatting argument '#1' in %d: conversion is 'd', received String (argument #2 in method call) [TimberArgTypes]
| Timber.tag("tag").d("%d", "arg1")
| ~~~~
|2 errors, 0 warnings""".trimMargin().toString())
}
@Test fun exceptionLoggingUsingExceptionMessage() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d(e.getMessage());
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d(e.message)
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Explicitly logging exception message is redundant [TimberExceptionLogging]
| Timber.d(e.getMessage());
| ~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Explicitly logging exception message is redundant [TimberExceptionLogging]
| Timber.d(e.message)
| ~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Replace message with throwable:
|@@ -6 +6
|- Timber.d(e.getMessage());
|+ Timber.d(e);
|Fix for src/foo/Example.kt line 6: Replace message with throwable:
|@@ -6 +6
|- Timber.d(e.message)
|+ Timber.d(e)
|""".trimMargin().toString())
}
@Test fun exceptionLoggingUsingExceptionMessageArgument() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d(e, e.getMessage());
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d(e, e.message)
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Explicitly logging exception message is redundant [TimberExceptionLogging]
| Timber.d(e, e.getMessage());
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Explicitly logging exception message is redundant [TimberExceptionLogging]
| Timber.d(e, e.message)
| ~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, e.getMessage());
|+ Timber.d(e);
|Fix for src/foo/Example.kt line 5: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, e.message)
|+ Timber.d(e)
|""".trimMargin().toString())
}
@Test fun exceptionLoggingUsingVariable() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String msg = "Hello";
| Exception e = new Exception();
| Timber.d(e, msg);
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val msg = "Hello"
| val e = Exception()
| Timber.d(e, msg)
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun exceptionLoggingUsingParameter() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log(Exception e, String message) {
| Timber.d(e, message);
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log(e: Exception, message: String) {
| Timber.d(e, message)
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun exceptionLoggingUsingMethod() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log(Exception e) {
| Timber.d(e, method());
| }
| private String method() {
| return "foo";
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log(e: Exception) {
| Timber.d(e, method())
| }
| private fun method(): String {
| return "foo"
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun exceptionLoggingUsingNonFinalField() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| private String message;
| public void log() {
| Exception e = new Exception();
| Timber.d(e, message);
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| private var message = ""
| fun log() {
| val e = Exception()
| Timber.d(e, message)
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun exceptionLoggingUsingFinalField() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| private final String message = "foo";
| public void log() {
| Exception e = new Exception();
| Timber.d(e, message);
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| private val message = ""
| fun log() {
| val e = Exception()
| Timber.d(e, message)
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun exceptionLoggingUsingEmptyStringMessage() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d(e, "");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d(e, "")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Use single-argument log method instead of null/empty message [TimberExceptionLogging]
| Timber.d(e, "");
| ~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Use single-argument log method instead of null/empty message [TimberExceptionLogging]
| Timber.d(e, "")
| ~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, "");
|+ Timber.d(e);
|Fix for src/foo/Example.kt line 6: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, "")
|+ Timber.d(e)
|""".trimMargin().toString())
}
@Test fun exceptionLoggingUsingNullMessage() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d(e, null);
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d(e, null)
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Use single-argument log method instead of null/empty message [TimberExceptionLogging]
| Timber.d(e, null);
| ~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Use single-argument log method instead of null/empty message [TimberExceptionLogging]
| Timber.d(e, null)
| ~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin().toString())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, null);
|+ Timber.d(e);
|Fix for src/foo/Example.kt line 6: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, null)
|+ Timber.d(e)
|""".trimMargin().toString())
}
@Test fun exceptionLoggingUsingValidMessage() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d(e, "Valid message");
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d(e, "Valid message")
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun dateFormatNotDisplayingWarning() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%tc", new java.util.Date());
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("%tc", java.util.Date())
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun systemTimeMillisValidMessage() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%tc", System.currentTimeMillis());
| }
|}""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("%tc", System.currentTimeMillis())
| }
|}""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun wrappedBooleanType() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%b", Boolean.valueOf(true));
| }
|}""".trimMargin().toString()),
// no kotlin equivalent, since primitive wrappers do not exist
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun memberVariable() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public static class Bar {
| public static String baz = "timber";
| }
| public void log() {
| Bar bar = new Bar();
| Timber.d(bar.baz);
| }
|}
""".trimMargin().toString()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| class Bar {
| val baz = "timber"
| }
| fun log() {
| val bar = Bar()
| Timber.d(bar.baz)
| }
|}
""".trimMargin().toString())
)
.issues(*issues)
.run()
.expectClean()
}
}
| 9
| null |
954
| 9,951
|
9954d94abbaea9d003243be5b69f8ae0ffc0c99d
| 50,398
|
timber
|
Apache License 2.0
|
app/src/main/java/com/certified/audionote/ui/NotesViewModel.kt
|
certified84
| 435,328,596
| false
|
{"Kotlin": 87491}
|
/*
* Copyright (c) 2023 <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 com.certified.audionote.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.certified.audionote.model.Note
import com.certified.audionote.repository.Repository
import com.certified.audionote.utils.ReminderAvailableState
import com.certified.audionote.utils.ReminderCompletionState
import com.certified.audionote.utils.UIState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class NotesViewModel @Inject constructor(private val repository: Repository) : ViewModel() {
val _reminderAvailableState = MutableStateFlow(ReminderAvailableState.NO_REMINDER)
val reminderAvailableState = _reminderAvailableState.asStateFlow()
val _reminderCompletionState = MutableStateFlow(ReminderCompletionState.ONGOING)
val reminderCompletionState = _reminderCompletionState.asStateFlow()
private val _uiState = MutableStateFlow(UIState.LOADING)
val uiState = _uiState.asStateFlow()
private val _notes = MutableStateFlow<List<Note>?>(null)
val notes = _notes.asStateFlow()
private val _note = MutableStateFlow<Note?>(null)
val note = _note.asStateFlow()
init {
getNotes()
}
private fun getNotes() {
viewModelScope.launch {
repository.allNotes.collect {
_notes.value = it
if (it.isNullOrEmpty())
_uiState.value = UIState.EMPTY
else
_uiState.value = UIState.HAS_DATA
}
}
}
fun insertNote(note: Note) {
viewModelScope.launch(Dispatchers.IO) {
repository.insertNote(note)
}
}
fun updateNote(note: Note) {
viewModelScope.launch(Dispatchers.IO) {
repository.updateNote(note)
}
}
fun deleteNote(note: Note) {
viewModelScope.launch(Dispatchers.IO) {
repository.deleteNote(note)
}
}
fun getNote(noteId: Int) {
viewModelScope.launch(Dispatchers.IO) {
repository.getNote(noteId).collect {
_note.value = it
}
}
}
}
| 8
|
Kotlin
|
5
| 72
|
3436c26516927dc7d9691f354b69ea24c951a5a7
| 2,906
|
AudioNote
|
Apache License 2.0
|
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KSAnnotatedExt.kt
|
RikkaW
| 389,105,112
| false
| null |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.ksp
import com.google.devtools.ksp.symbol.KSAnnotated
private fun KSAnnotated.hasAnnotationWithQName(qName: String) = annotations.any {
try {
it.annotationType.resolve().declaration.qualifiedName?.asString() == qName
} catch (illegal: IllegalStateException) {
// see: https://github.com/google/ksp/issues/173
false
}
}
internal fun KSAnnotated.hasJvmStaticAnnotation() = hasAnnotationWithQName("kotlin.jvm.JvmStatic")
internal fun KSAnnotated.hasJvmTransientAnnotation() =
hasAnnotationWithQName("kotlin.jvm.Transient")
internal fun KSAnnotated.hasJvmFieldAnnotation() = hasAnnotationWithQName("kotlin.jvm.JvmField")
internal fun KSAnnotated.hasJvmDefaultAnnotation() = hasAnnotationWithQName("kotlin.jvm.JvmDefault")
| 1
| null |
1
| 7
|
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
| 1,423
|
androidx
|
Apache License 2.0
|
app/src/main/java/com/muzzley/app/workers/DevicePickerMashData.kt
|
habitio
| 191,952,436
| false
| null |
package com.muzzley.app.workers
import com.muzzley.app.tiles.Models
import com.muzzley.model.channels.ChannelData
import com.muzzley.model.tiles.TileGroupsData
import com.muzzley.model.tiles.TilesData
import com.muzzley.services.GroupsInteractor
import com.muzzley.util.retrofit.UserService
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function3
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class DevicePickerMashData
@Inject constructor(
val userService: UserService,
val groupsInteractor: GroupsInteractor
){
fun getItemsWithTypeAndExclude(typeId: String , excludeValue: String ): Observable<Models> =
Observable.zip(
// userService.getUserTileGroupData(mapOf("include" to "unsorted,context")),
groupsInteractor.getUserTileGroupData(mapOf("include" to "unsorted,context")),
userService.getUserTileDataWithType(mapOf("include" to "specs,context,capabilities", "type" to typeId, "exclude" to excludeValue)),
userService.getUserChannelsWithType(mapOf("include" to "channelProperties,context,capabilities", "type" to typeId)),
Function3{ tileGroupsData: TileGroupsData , tilesData: TilesData , channelData: ChannelData ->
Models(tileGroupsData, tilesData, channelData)
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
| 1
| null |
1
| 1
|
57174e1ca5e0d72ebc01d0750e278fc493b44e42
| 1,547
|
habit-whitelabel-app-android
|
MIT License
|
android-gradle-plugin-aspectj/src/main/kotlin/com/archinamon/api/AspectJMergeJars.kt
|
thunderheadone
| 152,609,582
| true
|
{"Kotlin": 68338}
|
/*
* Copyright 2018 the original author or authors.
* Copyright 2018 Thunderhead
*
* 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.archinamon.api
import com.android.build.api.transform.Format
import com.android.build.api.transform.TransformException
import com.android.build.api.transform.TransformInvocation
import com.android.builder.packaging.JarMerger
import com.android.builder.packaging.ZipEntryFilter
import com.android.utils.FileUtils
import com.archinamon.api.transform.AspectJTransform
import java.io.File
/**
* Merging all jars and aars in project with dependencies
* This runs when AspectJ augments jar's/aar's bytecode
*
* @author archinamon on 13/03/17.
*/
internal class AspectJMergeJars {
private val target = com.archinamon.api.transform.TRANSFORM_NAME
internal fun doMerge(transform: AspectJTransform, context: TransformInvocation, resultDir: File) {
if (resultDir.listFiles().isNotEmpty()) {
val jarFile = context.outputProvider.getContentLocation(target, transform.outputTypes, transform.scopes, Format.JAR)
FileUtils.mkdirs(jarFile.parentFile)
FileUtils.deleteIfExists(jarFile)
val jarMerger = JarMerger(jarFile.toPath(), ZipEntryFilter.CLASSES_ONLY)
try {
jarMerger.addDirectory(resultDir.toPath())
} catch (e: Exception) {
throw TransformException(e)
} finally {
jarMerger.close()
}
}
FileUtils.deletePath(resultDir)
}
}
| 0
|
Kotlin
|
0
| 5
|
929ea8b656dcf2b5b235f0f7a246f9deee09c9b5
| 2,094
|
one-android-gradle-aspectj
|
Apache License 2.0
|
libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/milestone/Milestone.kt
|
luugiathuy
| 227,537,256
| true
|
{"Java": 1439669, "Kotlin": 697036, "Python": 4645, "Makefile": 3713, "JavaScript": 3107, "Shell": 1903}
|
package com.mapbox.services.android.navigation.v5.milestone
import com.mapbox.services.android.navigation.v5.instruction.Instruction
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgress
/**
* Base Milestone statement. Subclassed to provide concrete statements.
*
* @since 0.4.0
*/
// Public exposed for creation of milestone classes outside SDK
abstract class Milestone(private val builder: Builder) {
/**
* Milestone specific identifier as an `int` value, useful for deciphering which milestone
* invoked [MilestoneEventListener.onMilestoneEvent].
*
* @return `int` representing the identifier
* @since 0.4.0
*/
open val identifier: Int
get() = builder.getIdentifier()
/**
* Milestone specific [Instruction], which can be used to build a [String]
* instruction specified by the superclass.
*
* @return [Instruction] to be used to build the [String] passed to
* [MilestoneEventListener.onMilestoneEvent]
* @since 0.4.0
*/
open val instruction: Instruction?
get() = builder.getInstruction()
/**
* A milestone can either be passed in to the
* [com.mapbox.services.android.navigation.v5.navigation.MapboxNavigation] object
* (recommended) or validated directly inside your activity.
*
* @param previousRouteProgress last locations generated [RouteProgress] object used to
* determine certain [TriggerProperty]s
* @param routeProgress used to determine certain [TriggerProperty]s
* @return true if the milestone trigger's valid, else false
* @since 0.4.0
*/
abstract fun isOccurring(
previousRouteProgress: RouteProgress,
routeProgress: RouteProgress
): Boolean
/**
* Build a new [Milestone]
*
* @since 0.4.0
*/
abstract class Builder {
private var identifier: Int = 0
private var instruction: Instruction? = null
/**
* Milestone specific identifier as an `int` value, useful for deciphering which milestone
* invoked [MilestoneEventListener.onMilestoneEvent].
*
* @return `int` representing the identifier
* @since 0.4.0
*/
fun getIdentifier(): Int = identifier
/**
* Milestone specific identifier as an `int` value, useful for deciphering which milestone
* invoked [MilestoneEventListener.onMilestoneEvent].
*
* @param identifier an `int` used to identify this milestone instance
* @return this builder
* @since 0.4.0
*/
fun setIdentifier(identifier: Int): Builder {
this.identifier = identifier
return this
}
/**
* Milestone specific [Instruction], which can be used to build a [String]
* instruction specified by the superclass
*
* @return this builder
* @since 0.4.0
*/
fun getInstruction(): Instruction? = instruction
fun setInstruction(instruction: Instruction): Builder {
this.instruction = instruction
return this
}
/**
* The list of triggers that are used to determine whether this milestone should invoke
* [MilestoneEventListener.onMilestoneEvent]
*
* @param trigger a single simple statement or compound statement found in [Trigger]
* @return this builder
* @since 0.4.0
*/
abstract fun setTrigger(trigger: Trigger.Statement?): Builder
internal abstract fun getTrigger(): Trigger.Statement?
/**
* Build a new milestone
*
* @return A new [Milestone] object
* @since 0.4.0
*/
abstract fun build(): Milestone
}
}
| 0
| null |
0
| 1
|
f1e5d047665617c4ef32a3b4b5c9ab29d0ecaa93
| 3,823
|
mapbox-navigation-android
|
Apache License 2.0
|
src/main/kotlin/silentorb/imp/intellij/highlighting/ImpColorSettingsPage.kt
|
silentorb
| 239,162,536
| false
| null |
package silentorb.imp.intellij.highlighting
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighter
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import silentorb.imp.intellij.misc.ImpIcons
import javax.swing.Icon
class ImpColorSettingsPage : ColorSettingsPage {
override fun getIcon(): Icon? {
return ImpIcons.FILE
}
override fun getHighlighter(): SyntaxHighlighter {
return ImpSyntaxHighlighter()
}
override fun getDemoText(): String {
return "# You are reading the \".properties\" entry."
}
override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey>? {
return null
}
override fun getAttributeDescriptors(): Array<AttributesDescriptor> {
return DESCRIPTORS
}
override fun getColorDescriptors(): Array<ColorDescriptor> {
return ColorDescriptor.EMPTY_ARRAY
}
override fun getDisplayName(): String {
return "Imp"
}
companion object {
private val DESCRIPTORS = arrayOf(
AttributesDescriptor("Key", ImpSyntaxColors.KEYWORD),
AttributesDescriptor("Separator", ImpSyntaxColors.SEPARATOR),
AttributesDescriptor("Value", ImpSyntaxColors.VALUE))
}
}
| 0
|
Kotlin
|
0
| 0
|
24c4f4b4e712256ee7686a947021072a6e9a2549
| 1,369
|
imp-intellij
|
MIT License
|
Frontend/src/test/kotlin/com/jetbrains/fortea/highlighting/T4IncludedExecutableTemplateInSubfolderHighlightingTest.kt
|
JetBrains
| 202,559,189
| false
|
{"C#": 870119, "Kotlin": 102802, "Lex": 8199, "PowerShell": 2960, "Shell": 2282, "Batchfile": 207}
|
package com.jetbrains.fortea.highlighting
import org.testng.annotations.Test
class T4IncludedExecutableTemplateInSubfolderHighlightingTest : T4HighlightingTestBase() {
override val testSolution = "ProjectWith4AndIncluderInSubfolder"
override val testFilePath get() = "Project/Folder/$fileName"
@Test fun testDefaultClassesResolution() = doTestErrors()
}
| 20
|
C#
|
10
| 56
|
9569d79cb9ad732b084155f14219c184f0051ef2
| 361
|
ForTea
|
Apache License 2.0
|
nlp/model/opennlp/src/main/kotlin/OpenNlpEngineProvider.kt
|
theopenconversationkit
| 84,538,053
| false
| null |
/*
* Copyright (C) 2017 VSCT
*
* 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 ai.tock.nlp.opennlp
import ai.tock.nlp.core.NlpEngineType
import ai.tock.nlp.model.service.engine.EntityClassifier
import ai.tock.nlp.model.service.engine.EntityModelHolder
import ai.tock.nlp.model.service.engine.IntentClassifier
import ai.tock.nlp.model.service.engine.IntentModelHolder
import ai.tock.nlp.model.service.engine.NlpEngineModelBuilder
import ai.tock.nlp.model.service.engine.NlpEngineModelIo
import ai.tock.nlp.model.service.engine.NlpEngineProvider
import ai.tock.nlp.model.service.engine.Tokenizer
import ai.tock.nlp.model.service.engine.TokenizerModelHolder
/**
*
*/
class OpenNlpEngineProvider : NlpEngineProvider {
override val type: NlpEngineType = NlpEngineType.opennlp
override fun getIntentClassifier(model: IntentModelHolder): IntentClassifier {
return OpenNlpIntentClassifier(model)
}
override fun getEntityClassifier(model: EntityModelHolder): EntityClassifier {
return OpenNlpEntityClassifier(model)
}
override fun getTokenizer(model: TokenizerModelHolder): Tokenizer {
return OpenNlpTokenizer(model)
}
override val modelBuilder: NlpEngineModelBuilder = OpenNlpModelBuilder
override val modelIo: NlpEngineModelIo = OpenNlpModelIo
}
| 163
| null |
127
| 475
|
890f69960997ae9146747d082d808d92ee407fcb
| 1,828
|
tock
|
Apache License 2.0
|
android/src/main/kotlin/com/cjx/x5_webview/JavascriptChannel.kt
|
VenusCao
| 186,570,806
| false
| null |
package com.cjx.x5_webview
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.webkit.JavascriptInterface
import io.flutter.plugin.common.MethodChannel
class JavascriptChannel(val name: String, val channel: MethodChannel, val context: Context) {
@JavascriptInterface
fun postMessage(msg: String) {
val postRunnable = Runnable {
val arg = hashMapOf<String, Any>()
arg["name"] = name
arg["msg"] = msg
channel.invokeMethod("onJavascriptChannelCallBack", arg)
}
val handler = Handler(context.mainLooper)
if (handler.looper == Looper.myLooper()) {
postRunnable.run()
} else {
handler.post(postRunnable)
}
}
}
| 7
|
Dart
|
32
| 90
|
249a7b812c4de2f7444622a356865619846783ee
| 784
|
x5_webview_flutter
|
Apache License 2.0
|
src/main/kotlin/com/insyncwithfoo/pyright/runner/Command.kt
|
InSyncWithFoo
| 762,967,939
| false
|
{"Kotlin": 78609, "Python": 1796, "HTML": 471}
|
package com.insyncwithfoo.pyright.runner
import com.insyncwithfoo.pyright.PyrightDiagnosticSeverity
import com.insyncwithfoo.pyright.configuration.AllConfigurations
import com.insyncwithfoo.pyright.path
import com.insyncwithfoo.pyright.pyrightConfigurations
import com.insyncwithfoo.pyright.sdkPath
import com.intellij.execution.RunCanceledByUserException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.ProcessOutput
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiFile
import com.jetbrains.python.packaging.IndicatedProcessOutputListener
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import java.nio.file.Path
import kotlin.io.path.exists
private fun String.toPathIfItExists(base: String = "") =
this.toPathIfItExists(Path.of(base))
private fun String.toPathIfItExists(base: Path) =
Path.of(this)
.let { base.resolve(it).normalize() }
.takeIf { it.exists() }
private object PathSerializer : KSerializer<Path> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("Path", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Path) {
encoder.encodeString(value.toString())
}
override fun deserialize(decoder: Decoder): Path {
throw NotImplementedError("The deserializer should not be used")
}
}
@Serializable
internal data class PyrightCommand(
@Serializable(with = PathSerializer::class)
val executable: Path,
@Serializable(with = PathSerializer::class)
val target: Path,
val projectPath: String,
val extraArguments: List<String>
) {
private val fragments: List<String>
get() = listOf(
executable.toString(),
*extraArguments.toTypedArray(),
target.toString()
)
private val handler: CapturingProcessHandler
get() = CapturingProcessHandler(getCommandLine())
internal val extraArgumentsMap: Map<String, String?>
get() {
val map = mutableMapOf<String, String?>()
var index = 0
while (index < extraArguments.size) {
val element = extraArguments[index]
val nextElement = extraArguments.getOrNull(index + 1)
if (nextElement?.startsWith("--") == true) {
map[element] = null
} else {
map[element] = nextElement
index++
}
index++
}
return map
}
private fun getCommandLine() =
GeneralCommandLine(fragments).apply {
withWorkDirectory(projectPath)
withCharset(Charsets.UTF_8)
}
private fun runWithIndicator(): ProcessOutput {
val indicator = ProgressManager.getInstance().progressIndicator
return with(handler) {
if (indicator != null) {
addProcessListener(IndicatedProcessOutputListener(indicator))
runProcessWithProgressIndicator(indicator)
} else {
runProcess()
}
}
}
fun run(): String {
val processOutput = runWithIndicator()
return processOutput.run {
if (isCancelled) {
throw RunCanceledByUserException()
}
when (PyrightExitCode.fromInt(exitCode)) {
PyrightExitCode.FATAL -> throw FatalException(stdout, stderr)
PyrightExitCode.INVALID_CONFIG -> throw InvalidConfigurationsException(stdout, stderr)
PyrightExitCode.INVALID_PARAMETERS -> throw InvalidParametersException(stdout, stderr)
else -> stdout
}
}
}
companion object {
internal fun create(
configurations: AllConfigurations,
executable: Path,
target: Path,
projectPath: Path,
interpreterPath: Path
): PyrightCommand {
val configurationFile = configurations.configurationFile
val argumentForProject = configurationFile ?: projectPath
val extraArguments: MutableList<String> = mutableListOf(
"--outputjson",
"--project", argumentForProject.toString(),
"--pythonpath", interpreterPath.toString()
)
if (configurations.minimumSeverityLevel != PyrightDiagnosticSeverity.INFORMATION) {
extraArguments.add("--level")
extraArguments.add(configurations.minimumSeverityLevel.name)
}
return PyrightCommand(executable, target, projectPath.toString(), extraArguments)
}
fun create(file: PsiFile): PyrightCommand? {
val project = file.project
val configurations = project.pyrightConfigurations
val filePath = file.virtualFile.path.toPathIfItExists() ?: return null
val projectPath = project.path ?: return null
val executable = configurations.executable?.toPathIfItExists(base = projectPath) ?: return null
val interpreterPath = project.sdkPath ?: return null
return create(configurations, executable, filePath, projectPath, interpreterPath)
}
}
}
| 5
|
Kotlin
|
0
| 33
|
7d02d73bcbf364c66f6bdd9e4b01f713f1c2e6d6
| 5,895
|
pyright-for-pycharm
|
MIT License
|
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/medialive/CfnMultiplex.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 142794926}
|
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.medialive
import io.cloudshiftdev.awscdk.CfnResource
import io.cloudshiftdev.awscdk.CfnTag
import io.cloudshiftdev.awscdk.IInspectable
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.ITaggableV2
import io.cloudshiftdev.awscdk.TagManager
import io.cloudshiftdev.awscdk.TreeInspector
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.Number
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmName
import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct
import software.constructs.Construct as SoftwareConstructsConstruct
/**
* The multiplex object.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.medialive.*;
* CfnMultiplex cfnMultiplex = CfnMultiplex.Builder.create(this, "MyCfnMultiplex")
* .availabilityZones(List.of("availabilityZones"))
* .multiplexSettings(MultiplexSettingsProperty.builder()
* .transportStreamBitrate(123)
* .transportStreamId(123)
* // the properties below are optional
* .maximumVideoBufferDelayMilliseconds(123)
* .transportStreamReservedBitrate(123)
* .build())
* .name("name")
* // the properties below are optional
* .destinations(List.of(MultiplexOutputDestinationProperty.builder()
* .multiplexMediaConnectOutputDestinationSettings(MultiplexMediaConnectOutputDestinationSettingsProperty.builder()
* .entitlementArn("entitlementArn")
* .build())
* .build()))
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html)
*/
public open class CfnMultiplex(
cdkObject: software.amazon.awscdk.services.medialive.CfnMultiplex,
) : CfnResource(cdkObject), IInspectable, ITaggableV2 {
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnMultiplexProps,
) :
this(software.amazon.awscdk.services.medialive.CfnMultiplex(scope.let(CloudshiftdevConstructsConstruct::unwrap),
id, props.let(CfnMultiplexProps::unwrap))
)
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnMultiplexProps.Builder.() -> Unit,
) : this(scope, id, CfnMultiplexProps(props)
)
/**
* The unique arn of the multiplex.
*/
public open fun attrArn(): String = unwrap(this).getAttrArn()
/**
* The unique id of the multiplex.
*/
public open fun attrId(): String = unwrap(this).getAttrId()
/**
* The number of currently healthy pipelines.
*/
public open fun attrPipelinesRunningCount(): Number = unwrap(this).getAttrPipelinesRunningCount()
/**
* The number of programs in the multiplex.
*/
public open fun attrProgramCount(): Number = unwrap(this).getAttrProgramCount()
/**
* The current state of the multiplex.
*/
public open fun attrState(): String = unwrap(this).getAttrState()
/**
* A list of availability zones for the multiplex.
*/
public open fun availabilityZones(): List<String> = unwrap(this).getAvailabilityZones()
/**
* A list of availability zones for the multiplex.
*/
public open fun availabilityZones(`value`: List<String>) {
unwrap(this).setAvailabilityZones(`value`)
}
/**
* A list of availability zones for the multiplex.
*/
public open fun availabilityZones(vararg `value`: String): Unit =
availabilityZones(`value`.toList())
/**
* Tag Manager which manages the tags for this resource.
*/
public override fun cdkTagManager(): TagManager =
unwrap(this).getCdkTagManager().let(TagManager::wrap)
/**
* A list of the multiplex output destinations.
*/
public open fun destinations(): Any? = unwrap(this).getDestinations()
/**
* A list of the multiplex output destinations.
*/
public open fun destinations(`value`: IResolvable) {
unwrap(this).setDestinations(`value`.let(IResolvable::unwrap))
}
/**
* A list of the multiplex output destinations.
*/
public open fun destinations(`value`: List<Any>) {
unwrap(this).setDestinations(`value`)
}
/**
* A list of the multiplex output destinations.
*/
public open fun destinations(vararg `value`: Any): Unit = destinations(`value`.toList())
/**
* Examines the CloudFormation resource and discloses attributes.
*
* @param inspector tree inspector to collect and process attributes.
*/
public override fun inspect(inspector: TreeInspector) {
unwrap(this).inspect(inspector.let(TreeInspector::unwrap))
}
/**
* Configuration for a multiplex event.
*/
public open fun multiplexSettings(): Any = unwrap(this).getMultiplexSettings()
/**
* Configuration for a multiplex event.
*/
public open fun multiplexSettings(`value`: IResolvable) {
unwrap(this).setMultiplexSettings(`value`.let(IResolvable::unwrap))
}
/**
* Configuration for a multiplex event.
*/
public open fun multiplexSettings(`value`: MultiplexSettingsProperty) {
unwrap(this).setMultiplexSettings(`value`.let(MultiplexSettingsProperty::unwrap))
}
/**
* Configuration for a multiplex event.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("d77642a3d1aff7c1c2b69132c9bec5fe92ded4de3ec1940e2e187944f6361c1d")
public open fun multiplexSettings(`value`: MultiplexSettingsProperty.Builder.() -> Unit): Unit =
multiplexSettings(MultiplexSettingsProperty(`value`))
/**
* The name of the multiplex.
*/
public open fun name(): String = unwrap(this).getName()
/**
* The name of the multiplex.
*/
public open fun name(`value`: String) {
unwrap(this).setName(`value`)
}
/**
* A collection of key-value pairs.
*/
public open fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* A collection of key-value pairs.
*/
public open fun tags(`value`: List<CfnTag>) {
unwrap(this).setTags(`value`.map(CfnTag::unwrap))
}
/**
* A collection of key-value pairs.
*/
public open fun tags(vararg `value`: CfnTag): Unit = tags(`value`.toList())
/**
* A fluent builder for [io.cloudshiftdev.awscdk.services.medialive.CfnMultiplex].
*/
@CdkDslMarker
public interface Builder {
/**
* A list of availability zones for the multiplex.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-availabilityzones)
* @param availabilityZones A list of availability zones for the multiplex.
*/
public fun availabilityZones(availabilityZones: List<String>)
/**
* A list of availability zones for the multiplex.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-availabilityzones)
* @param availabilityZones A list of availability zones for the multiplex.
*/
public fun availabilityZones(vararg availabilityZones: String)
/**
* A list of the multiplex output destinations.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-destinations)
* @param destinations A list of the multiplex output destinations.
*/
public fun destinations(destinations: IResolvable)
/**
* A list of the multiplex output destinations.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-destinations)
* @param destinations A list of the multiplex output destinations.
*/
public fun destinations(destinations: List<Any>)
/**
* A list of the multiplex output destinations.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-destinations)
* @param destinations A list of the multiplex output destinations.
*/
public fun destinations(vararg destinations: Any)
/**
* Configuration for a multiplex event.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-multiplexsettings)
* @param multiplexSettings Configuration for a multiplex event.
*/
public fun multiplexSettings(multiplexSettings: IResolvable)
/**
* Configuration for a multiplex event.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-multiplexsettings)
* @param multiplexSettings Configuration for a multiplex event.
*/
public fun multiplexSettings(multiplexSettings: MultiplexSettingsProperty)
/**
* Configuration for a multiplex event.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-multiplexsettings)
* @param multiplexSettings Configuration for a multiplex event.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f48a3161dab0e0572a7a8b048700145d2d36e6dc63d0a03419f9b9db2492680c")
public fun multiplexSettings(multiplexSettings: MultiplexSettingsProperty.Builder.() -> Unit)
/**
* The name of the multiplex.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-name)
* @param name The name of the multiplex.
*/
public fun name(name: String)
/**
* A collection of key-value pairs.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-tags)
* @param tags A collection of key-value pairs.
*/
public fun tags(tags: List<CfnTag>)
/**
* A collection of key-value pairs.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-tags)
* @param tags A collection of key-value pairs.
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl(
scope: SoftwareConstructsConstruct,
id: String,
) : Builder {
private val cdkBuilder: software.amazon.awscdk.services.medialive.CfnMultiplex.Builder =
software.amazon.awscdk.services.medialive.CfnMultiplex.Builder.create(scope, id)
/**
* A list of availability zones for the multiplex.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-availabilityzones)
* @param availabilityZones A list of availability zones for the multiplex.
*/
override fun availabilityZones(availabilityZones: List<String>) {
cdkBuilder.availabilityZones(availabilityZones)
}
/**
* A list of availability zones for the multiplex.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-availabilityzones)
* @param availabilityZones A list of availability zones for the multiplex.
*/
override fun availabilityZones(vararg availabilityZones: String): Unit =
availabilityZones(availabilityZones.toList())
/**
* A list of the multiplex output destinations.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-destinations)
* @param destinations A list of the multiplex output destinations.
*/
override fun destinations(destinations: IResolvable) {
cdkBuilder.destinations(destinations.let(IResolvable::unwrap))
}
/**
* A list of the multiplex output destinations.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-destinations)
* @param destinations A list of the multiplex output destinations.
*/
override fun destinations(destinations: List<Any>) {
cdkBuilder.destinations(destinations)
}
/**
* A list of the multiplex output destinations.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-destinations)
* @param destinations A list of the multiplex output destinations.
*/
override fun destinations(vararg destinations: Any): Unit = destinations(destinations.toList())
/**
* Configuration for a multiplex event.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-multiplexsettings)
* @param multiplexSettings Configuration for a multiplex event.
*/
override fun multiplexSettings(multiplexSettings: IResolvable) {
cdkBuilder.multiplexSettings(multiplexSettings.let(IResolvable::unwrap))
}
/**
* Configuration for a multiplex event.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-multiplexsettings)
* @param multiplexSettings Configuration for a multiplex event.
*/
override fun multiplexSettings(multiplexSettings: MultiplexSettingsProperty) {
cdkBuilder.multiplexSettings(multiplexSettings.let(MultiplexSettingsProperty::unwrap))
}
/**
* Configuration for a multiplex event.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-multiplexsettings)
* @param multiplexSettings Configuration for a multiplex event.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f48a3161dab0e0572a7a8b048700145d2d36e6dc63d0a03419f9b9db2492680c")
override fun multiplexSettings(multiplexSettings: MultiplexSettingsProperty.Builder.() -> Unit):
Unit = multiplexSettings(MultiplexSettingsProperty(multiplexSettings))
/**
* The name of the multiplex.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-name)
* @param name The name of the multiplex.
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
/**
* A collection of key-value pairs.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-tags)
* @param tags A collection of key-value pairs.
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag::unwrap))
}
/**
* A collection of key-value pairs.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-multiplex.html#cfn-medialive-multiplex-tags)
* @param tags A collection of key-value pairs.
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build(): software.amazon.awscdk.services.medialive.CfnMultiplex = cdkBuilder.build()
}
public companion object {
public val CFN_RESOURCE_TYPE_NAME: String =
software.amazon.awscdk.services.medialive.CfnMultiplex.CFN_RESOURCE_TYPE_NAME
public operator fun invoke(
scope: CloudshiftdevConstructsConstruct,
id: String,
block: Builder.() -> Unit = {},
): CfnMultiplex {
val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id)
return CfnMultiplex(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.medialive.CfnMultiplex):
CfnMultiplex = CfnMultiplex(cdkObject)
internal fun unwrap(wrapped: CfnMultiplex):
software.amazon.awscdk.services.medialive.CfnMultiplex = wrapped.cdkObject as
software.amazon.awscdk.services.medialive.CfnMultiplex
}
/**
* Multiplex MediaConnect output destination settings.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.medialive.*;
* MultiplexMediaConnectOutputDestinationSettingsProperty
* multiplexMediaConnectOutputDestinationSettingsProperty =
* MultiplexMediaConnectOutputDestinationSettingsProperty.builder()
* .entitlementArn("entitlementArn")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexmediaconnectoutputdestinationsettings.html)
*/
public interface MultiplexMediaConnectOutputDestinationSettingsProperty {
/**
* The MediaConnect entitlement ARN available as a Flow source.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexmediaconnectoutputdestinationsettings.html#cfn-medialive-multiplex-multiplexmediaconnectoutputdestinationsettings-entitlementarn)
*/
public fun entitlementArn(): String? = unwrap(this).getEntitlementArn()
/**
* A builder for [MultiplexMediaConnectOutputDestinationSettingsProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param entitlementArn The MediaConnect entitlement ARN available as a Flow source.
*/
public fun entitlementArn(entitlementArn: String)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexMediaConnectOutputDestinationSettingsProperty.Builder
=
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexMediaConnectOutputDestinationSettingsProperty.builder()
/**
* @param entitlementArn The MediaConnect entitlement ARN available as a Flow source.
*/
override fun entitlementArn(entitlementArn: String) {
cdkBuilder.entitlementArn(entitlementArn)
}
public fun build():
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexMediaConnectOutputDestinationSettingsProperty
= cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexMediaConnectOutputDestinationSettingsProperty,
) : CdkObject(cdkObject), MultiplexMediaConnectOutputDestinationSettingsProperty {
/**
* The MediaConnect entitlement ARN available as a Flow source.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexmediaconnectoutputdestinationsettings.html#cfn-medialive-multiplex-multiplexmediaconnectoutputdestinationsettings-entitlementarn)
*/
override fun entitlementArn(): String? = unwrap(this).getEntitlementArn()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}):
MultiplexMediaConnectOutputDestinationSettingsProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexMediaConnectOutputDestinationSettingsProperty):
MultiplexMediaConnectOutputDestinationSettingsProperty = CdkObjectWrappers.wrap(cdkObject)
as? MultiplexMediaConnectOutputDestinationSettingsProperty ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: MultiplexMediaConnectOutputDestinationSettingsProperty):
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexMediaConnectOutputDestinationSettingsProperty
= (wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexMediaConnectOutputDestinationSettingsProperty
}
}
/**
* Multiplex output destination settings.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.medialive.*;
* MultiplexOutputDestinationProperty multiplexOutputDestinationProperty =
* MultiplexOutputDestinationProperty.builder()
* .multiplexMediaConnectOutputDestinationSettings(MultiplexMediaConnectOutputDestinationSettingsProperty.builder()
* .entitlementArn("entitlementArn")
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexoutputdestination.html)
*/
public interface MultiplexOutputDestinationProperty {
/**
* Multiplex MediaConnect output destination settings.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexoutputdestination.html#cfn-medialive-multiplex-multiplexoutputdestination-multiplexmediaconnectoutputdestinationsettings)
*/
public fun multiplexMediaConnectOutputDestinationSettings(): Any? =
unwrap(this).getMultiplexMediaConnectOutputDestinationSettings()
/**
* A builder for [MultiplexOutputDestinationProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param multiplexMediaConnectOutputDestinationSettings Multiplex MediaConnect output
* destination settings.
*/
public
fun multiplexMediaConnectOutputDestinationSettings(multiplexMediaConnectOutputDestinationSettings: IResolvable)
/**
* @param multiplexMediaConnectOutputDestinationSettings Multiplex MediaConnect output
* destination settings.
*/
public
fun multiplexMediaConnectOutputDestinationSettings(multiplexMediaConnectOutputDestinationSettings: MultiplexMediaConnectOutputDestinationSettingsProperty)
/**
* @param multiplexMediaConnectOutputDestinationSettings Multiplex MediaConnect output
* destination settings.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("2569c3f12cb772a27991b1621a83c9f430ff4d781d3da6fbd420a85060180260")
public
fun multiplexMediaConnectOutputDestinationSettings(multiplexMediaConnectOutputDestinationSettings: MultiplexMediaConnectOutputDestinationSettingsProperty.Builder.() -> Unit)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexOutputDestinationProperty.Builder
=
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexOutputDestinationProperty.builder()
/**
* @param multiplexMediaConnectOutputDestinationSettings Multiplex MediaConnect output
* destination settings.
*/
override
fun multiplexMediaConnectOutputDestinationSettings(multiplexMediaConnectOutputDestinationSettings: IResolvable) {
cdkBuilder.multiplexMediaConnectOutputDestinationSettings(multiplexMediaConnectOutputDestinationSettings.let(IResolvable::unwrap))
}
/**
* @param multiplexMediaConnectOutputDestinationSettings Multiplex MediaConnect output
* destination settings.
*/
override
fun multiplexMediaConnectOutputDestinationSettings(multiplexMediaConnectOutputDestinationSettings: MultiplexMediaConnectOutputDestinationSettingsProperty) {
cdkBuilder.multiplexMediaConnectOutputDestinationSettings(multiplexMediaConnectOutputDestinationSettings.let(MultiplexMediaConnectOutputDestinationSettingsProperty::unwrap))
}
/**
* @param multiplexMediaConnectOutputDestinationSettings Multiplex MediaConnect output
* destination settings.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("2569c3f12cb772a27991b1621a83c9f430ff4d781d3da6fbd420a85060180260")
override
fun multiplexMediaConnectOutputDestinationSettings(multiplexMediaConnectOutputDestinationSettings: MultiplexMediaConnectOutputDestinationSettingsProperty.Builder.() -> Unit):
Unit =
multiplexMediaConnectOutputDestinationSettings(MultiplexMediaConnectOutputDestinationSettingsProperty(multiplexMediaConnectOutputDestinationSettings))
public fun build():
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexOutputDestinationProperty
= cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexOutputDestinationProperty,
) : CdkObject(cdkObject), MultiplexOutputDestinationProperty {
/**
* Multiplex MediaConnect output destination settings.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexoutputdestination.html#cfn-medialive-multiplex-multiplexoutputdestination-multiplexmediaconnectoutputdestinationsettings)
*/
override fun multiplexMediaConnectOutputDestinationSettings(): Any? =
unwrap(this).getMultiplexMediaConnectOutputDestinationSettings()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}):
MultiplexOutputDestinationProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexOutputDestinationProperty):
MultiplexOutputDestinationProperty = CdkObjectWrappers.wrap(cdkObject) as?
MultiplexOutputDestinationProperty ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: MultiplexOutputDestinationProperty):
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexOutputDestinationProperty
= (wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexOutputDestinationProperty
}
}
/**
* Contains configuration for a Multiplex event.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.medialive.*;
* MultiplexSettingsProperty multiplexSettingsProperty = MultiplexSettingsProperty.builder()
* .transportStreamBitrate(123)
* .transportStreamId(123)
* // the properties below are optional
* .maximumVideoBufferDelayMilliseconds(123)
* .transportStreamReservedBitrate(123)
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexsettings.html)
*/
public interface MultiplexSettingsProperty {
/**
* Maximum video buffer delay in milliseconds.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexsettings.html#cfn-medialive-multiplex-multiplexsettings-maximumvideobufferdelaymilliseconds)
*/
public fun maximumVideoBufferDelayMilliseconds(): Number? =
unwrap(this).getMaximumVideoBufferDelayMilliseconds()
/**
* Transport stream bit rate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexsettings.html#cfn-medialive-multiplex-multiplexsettings-transportstreambitrate)
*/
public fun transportStreamBitrate(): Number
/**
* Transport stream ID.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexsettings.html#cfn-medialive-multiplex-multiplexsettings-transportstreamid)
*/
public fun transportStreamId(): Number
/**
* Transport stream reserved bit rate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexsettings.html#cfn-medialive-multiplex-multiplexsettings-transportstreamreservedbitrate)
*/
public fun transportStreamReservedBitrate(): Number? =
unwrap(this).getTransportStreamReservedBitrate()
/**
* A builder for [MultiplexSettingsProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param maximumVideoBufferDelayMilliseconds Maximum video buffer delay in milliseconds.
*/
public fun maximumVideoBufferDelayMilliseconds(maximumVideoBufferDelayMilliseconds: Number)
/**
* @param transportStreamBitrate Transport stream bit rate.
*/
public fun transportStreamBitrate(transportStreamBitrate: Number)
/**
* @param transportStreamId Transport stream ID.
*/
public fun transportStreamId(transportStreamId: Number)
/**
* @param transportStreamReservedBitrate Transport stream reserved bit rate.
*/
public fun transportStreamReservedBitrate(transportStreamReservedBitrate: Number)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexSettingsProperty.Builder =
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexSettingsProperty.builder()
/**
* @param maximumVideoBufferDelayMilliseconds Maximum video buffer delay in milliseconds.
*/
override
fun maximumVideoBufferDelayMilliseconds(maximumVideoBufferDelayMilliseconds: Number) {
cdkBuilder.maximumVideoBufferDelayMilliseconds(maximumVideoBufferDelayMilliseconds)
}
/**
* @param transportStreamBitrate Transport stream bit rate.
*/
override fun transportStreamBitrate(transportStreamBitrate: Number) {
cdkBuilder.transportStreamBitrate(transportStreamBitrate)
}
/**
* @param transportStreamId Transport stream ID.
*/
override fun transportStreamId(transportStreamId: Number) {
cdkBuilder.transportStreamId(transportStreamId)
}
/**
* @param transportStreamReservedBitrate Transport stream reserved bit rate.
*/
override fun transportStreamReservedBitrate(transportStreamReservedBitrate: Number) {
cdkBuilder.transportStreamReservedBitrate(transportStreamReservedBitrate)
}
public fun build():
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexSettingsProperty =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexSettingsProperty,
) : CdkObject(cdkObject), MultiplexSettingsProperty {
/**
* Maximum video buffer delay in milliseconds.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexsettings.html#cfn-medialive-multiplex-multiplexsettings-maximumvideobufferdelaymilliseconds)
*/
override fun maximumVideoBufferDelayMilliseconds(): Number? =
unwrap(this).getMaximumVideoBufferDelayMilliseconds()
/**
* Transport stream bit rate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexsettings.html#cfn-medialive-multiplex-multiplexsettings-transportstreambitrate)
*/
override fun transportStreamBitrate(): Number = unwrap(this).getTransportStreamBitrate()
/**
* Transport stream ID.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexsettings.html#cfn-medialive-multiplex-multiplexsettings-transportstreamid)
*/
override fun transportStreamId(): Number = unwrap(this).getTransportStreamId()
/**
* Transport stream reserved bit rate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-multiplex-multiplexsettings.html#cfn-medialive-multiplex-multiplexsettings-transportstreamreservedbitrate)
*/
override fun transportStreamReservedBitrate(): Number? =
unwrap(this).getTransportStreamReservedBitrate()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): MultiplexSettingsProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexSettingsProperty):
MultiplexSettingsProperty = CdkObjectWrappers.wrap(cdkObject) as?
MultiplexSettingsProperty ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: MultiplexSettingsProperty):
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexSettingsProperty =
(wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.medialive.CfnMultiplex.MultiplexSettingsProperty
}
}
}
| 3
|
Kotlin
|
0
| 4
|
ddf2bfd2275b50bb86a667c4298dd92f59d7e342
| 34,015
|
kotlin-cdk-wrapper
|
Apache License 2.0
|
features/article/domain/interactors/src/main/java/kasem/sm/article/domain/interactors/GetInExploreArticles.kt
|
kasem-sm
| 456,508,892
| false
|
{"Kotlin": 432676, "Procfile": 53, "Shell": 10}
|
/*
* Copyright (C) 2021, <NAME>
* All rights reserved.
*/
package kasem.sm.article.domain.interactors
import javax.inject.Inject
import kasem.sm.article.datasource.cache.ArticleDatabaseService
import kasem.sm.article.datasource.network.ArticleApiService
import kasem.sm.article.datasource.utils.IsInExplore
import kasem.sm.core.domain.SlimeDispatchers
import kasem.sm.core.domain.Stage
import kasem.sm.core.domain.start
import kasem.sm.core.utils.getOrDefault
import kotlinx.coroutines.flow.Flow
class GetInExploreArticles @Inject constructor(
private val api: ArticleApiService,
private val cache: ArticleDatabaseService,
private val dispatchers: SlimeDispatchers,
) {
fun execute(): Flow<Stage> {
return dispatchers.default.start {
val articles = api.getExploreArticles()
.getOrThrow().data.getOrDefault()
cache.removeAllArticlesFromExplore()
articles.map {
val updatedData = cache.getArticleData(it.id)
.copy(third = IsInExplore(true))
cache.insert(it.toEntity(updatedData))
}
}
}
}
| 25
|
Kotlin
|
49
| 570
|
02543400476bac4248914c5e943ef58bac5a318a
| 1,145
|
SlimeKT
|
Apache License 2.0
|
src/main/java/com/dzen/campfire/api/models/account/Account.kt
|
ZeonXX
| 381,983,751
| false
|
{"Kotlin": 1087578}
|
package com.dzen.campfire.api.models.account
import com.sup.dev.java.libs.json.Json
import com.sup.dev.java.libs.json.JsonParsable
class Account : JsonParsable {
var id = 0L
var lvl = 0L
var lastOnlineDate = 0L
var name = ""
var imageId = 0L
var sex = 0L
var karma30 = 0L
var sponsor = 0L
var sponsorTimes = 0L
var accountEffects:Array<MAccountEffect> = emptyArray()
var dateCreate = 0L
constructor() {
}
constructor(id: Long, lvl: Long, lastOnlineDate: Long, name: String, imageId: Long, sex: Long, karma30: Long, sponsor: Long, sponsorTimes: Long, accountEffects: Array<MAccountEffect>) {
this.id = id
this.lvl = lvl
this.lastOnlineDate = lastOnlineDate
this.name = name
this.imageId = imageId
this.sex = sex
this.karma30 = karma30
this.sponsor = sponsor
this.sponsorTimes = sponsorTimes
this.accountEffects = accountEffects
}
override fun json(inp: Boolean, json: Json): Json {
id = json.m(inp, "J_ID", id)
dateCreate = json.m(inp, "J_DATE_CREATE", dateCreate)
lvl = json.m(inp, "J_LVL", lvl)
lastOnlineDate = json.m(inp, "J_LAST_ONLINE_DATE", lastOnlineDate)
name = json.m(inp, "J_NAME", name)
imageId = json.m(inp, "J_IMAGE_ID", imageId)
sex = json.m(inp, "sex", sex)
karma30 = json.m(inp, "karma30", karma30)
sponsor = json.m(inp, "sponsor", sponsor)
sponsorTimes = json.m(inp, "sponsorTimes", sponsorTimes)
accountEffects = json.m(inp, "accountEffects", accountEffects)
return json
}
}
| 0
|
Kotlin
|
2
| 5
|
6f3b371624fb66a065bcbaa6302830c574c55e9f
| 1,646
|
CampfireApi
|
Apache License 2.0
|
src/game/controllers/MultiplayerConnector.kt
|
YaroslavGamayunov
| 249,160,194
| false
| null |
package game.controllers
import game.Game
import game.GameActionsListener
import game.actions.GameActionSequence
import game.actions.GameStarted
import game.actions.MoveBegin
import game.actions.WrongIdException
import game.objects.GamePlayer
import logging.logInfo
import java.net.Socket
class ServerDataNotReceivedException(message: String) : Throwable(message)
class MultiplayerConnector(var socket: Socket, var playerName: String) : IGameServerConnector, GameActionsListener {
lateinit var client: IGameClient
fun waitForConnection() {
while (true) {
try {
getGameCopy()
} catch (e: ServerDataNotReceivedException) {
Thread.sleep(100)
continue
}
break
}
}
override fun getGameCopy(): Game {
var gameCopy = GameController.instance.getGame()
val playerID = getPlayerID()
if (gameCopy == null) {
throw ServerDataNotReceivedException("Game instance hasn't been received by client yet")
}
try {
gameCopy.getObjectByID(playerID)
}catch (ex : WrongIdException){
gameCopy.objects.add(GamePlayer(playerID))
}
logInfo(this, "Obtaining game copy")
return gameCopy
}
// override fun getGame(): Game {
// var game = GameController.instance.gameModel?.state?.game
//
// if (game == null) {
// throw ServerDataNotReceivedException("Game instance hasn't been received by client yet")
// }
//
// return game
// }
override fun getPlayerID(): Int {
var id: Int? = GameController.instance.getLocalPlayer()?.localPlayerInstance?.objectID
if (id == null) {
throw ServerDataNotReceivedException("Player ID hasn't been received by client yet")
}
return id
}
override fun runConnector(factory: IGameClientFactory) {
synchronized(this) {
GameController.instance.addGameActionListener(this)
GameController.instance.connectToServer(playerName, socket)
// todo rebuild because it blocks the thread
waitForConnection()
this.client = factory.createClient(this)
}
// val gameStarted = GameActionSequence(-1)
// gameStarted.actions.add(GameStarted())
// executeActionSequence(gameStarted)
//
// var game = GameController.instance.getGame(copy = false);
// while (game?.gameIsOver == false) {
// val newMove = GameActionSequence(-1)
// newMove.actions.add(MoveBegin(0))
// executeActionSequence(newMove)
// executeActionSequence(client.makeYourMove())
// }
}
// sends actions to server
private fun executeActionSequence(sequence: GameActionSequence) {
GameController.instance.onPlayerMoved(sequence, shouldUpdateModel = true)
if (sequence.playerID != client.owner.objectID) client.applyExternalActions(sequence)
}
// receives actions from server
override fun onSequenceReceived(sequence: GameActionSequence){
synchronized(this) {
logInfo(this, "Pushing sequence to client")
client.applyExternalActions(sequence)
for (action in sequence.actions) {
if (action is MoveBegin && action.playerID == getPlayerID()) {
executeActionSequence(client.makeYourMove())
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
49d185720123b7636c67cb52adb484deba059d33
| 3,515
|
tank-game
|
MIT License
|
compiler/testData/codegen/box/secondaryConstructors/fieldInitializerOptimization.kt
|
JetBrains
| 3,432,266
| false
| null |
// IGNORE_BACKEND: WASM
// WASM_MUTE_REASON: IGNORED_IN_JS
// IGNORE_BACKEND: JS
// IGNORE_BACKEND: JS_IR
// IGNORE_BACKEND: JS_IR_ES6
open class Base {
open fun setup() {}
init { setup() }
}
val placeHolder = Any()
class Derived : Base {
constructor() : super()
override fun setup() {
xBool = true
xByte = 1.toByte()
xChar = 2.toChar()
xShort = 3.toShort()
xInt = 4
xLong = 5L
xFloat = 6.0f
xDouble = 7.0
xRef = placeHolder
}
// Technically, this field initializer comes after the superclass
// constructor is called. However, we optimize away field initializers
// which set fields to their default value, which is why x ends up with
// value 1 after the constructor call.
var xBool = false
var xByte = 0.toByte()
var xChar = 0.toChar()
var xShort = 0.toShort()
var xInt = 0
var xLong = 0L
var xFloat = 0.0f
var xDouble = 0.0
var xRef: Any? = null
}
fun box(): String {
val d = Derived()
if (d.xBool != true) return "fail Bool"
if (d.xByte != 1.toByte()) return "fail Byte"
if (d.xChar != 2.toChar()) return "fail Char"
if (d.xShort != 3.toShort()) return "fail Short"
if (d.xInt != 4) return "fail Int"
if (d.xLong != 5L) return "fail Long"
if (d.xFloat != 6.0f) return "fail Float"
if (d.xDouble != 7.0) return "fail Double"
if (d.xRef != placeHolder) return "fail Ref"
return "OK"
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,481
|
kotlin
|
Apache License 2.0
|
ktls-dsl/lang/src/main/kotlin/io/kotless/dsl/dispatcher/Dispatcher.kt
|
tchigher
| 209,689,628
| true
|
{"Kotlin": 148053}
|
package io.kotless.dsl.dispatcher
import io.kotless.dsl.conversion.ConversionService
import io.kotless.dsl.events.HttpRequest
import io.kotless.dsl.events.HttpResponse
import io.kotless.dsl.lang.KotlessContext
import io.kotless.dsl.lang.http.*
import io.kotless.dsl.lang.http.okResponse
import io.kotless.dsl.reflection.FunctionCaller
import io.kotless.dsl.reflection.ReflectionScanner
import org.slf4j.LoggerFactory
import java.lang.reflect.InvocationTargetException
internal object Dispatcher {
private val logger = LoggerFactory.getLogger(Dispatcher::class.java)
private val pipeline by lazy { preparePipeline(ReflectionScanner.objectsWithSubtype<HttpRequestInterceptor>().sortedBy { it.priority }) }
fun dispatch(request: HttpRequest, resourceKey: RouteKey): HttpResponse {
return try {
KotlessContext.HTTP.request = request
pipeline(request, resourceKey)
} finally {
KotlessContext.HTTP.reset()
}
}
private fun preparePipeline(left: List<HttpRequestInterceptor>): (HttpRequest, RouteKey) -> HttpResponse {
if (left.isNotEmpty()) {
val interceptor = left.first()
return { req, key ->
interceptor.intercept(req, key, preparePipeline(left.drop(1)))
}
} else {
return { req, key -> processRequest(req, key) }
}
}
private fun processRequest(request: HttpRequest, resourceKey: RouteKey): HttpResponse {
logger.info("Passing request to route {}", resourceKey)
val func = RoutesCache[resourceKey] ?: return notFound()
logger.debug("Found $func for key $resourceKey")
val result = try {
FunctionCaller.call(func, request.allParams)
} catch (e: Exception) {
logger.error("Failed on call of function ${func.name}", if (e is InvocationTargetException) e.targetException else e)
return serverError(e.message)
}
logger.info("Route returned result")
return when (result) {
is HttpResponse -> result
else -> okResponse(result?.toString(), resourceKey.mimeType)
}
}
}
| 0
| null |
0
| 0
|
b4dabca64109041148a741f77a0639f50eb654d5
| 2,176
|
kotless
|
Apache License 2.0
|
app/src/main/java/bruhcollective/itaysonlab/jetispot/ui/dac/components_home/ToolbarComponent2Binder.kt
|
iTaysonLab
| 482,292,329
| false
|
{"Kotlin": 442702, "Java": 87616}
|
package bruhcollective.itaysonlab.jetispot.ui.dac.components_home
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.History
import androidx.compose.material.icons.rounded.Notifications
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import bruhcollective.itaysonlab.jetispot.ui.ext.dynamicUnpack
import bruhcollective.itaysonlab.jetispot.ui.navigation.LocalNavigationController
import bruhcollective.itaysonlab.jetispot.ui.shared.PreviewableAsyncImage
import com.spotify.home.dac.component.v1.proto.ToolbarComponent
import com.spotify.home.dac.component.v1.proto.ToolbarItemFeedComponent
import com.spotify.home.dac.component.v1.proto.ToolbarItemListeningHistoryComponent
import com.spotify.home.dac.component.v1.proto.ToolbarItemSettingsComponent
import com.spotify.home.dac.component.v2.proto.ToolbarComponentV2
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ToolbarComponent2Binder(
item: ToolbarComponentV2
) {
TopAppBar(title = {
Text(item.dayPartMessage, fontWeight = FontWeight.SemiBold)
}, actions = {
item.itemsList.forEach {
when (val protoItem = it.dynamicUnpack()) {
is ToolbarItemFeedComponent -> ToolbarItem(Icons.Rounded.Notifications, protoItem.navigateUri, protoItem.title)
is ToolbarItemListeningHistoryComponent -> ToolbarItem(Icons.Rounded.History, protoItem.navigateUri, protoItem.title)
is ToolbarItemSettingsComponent -> ToolbarItem(Icons.Rounded.Settings, protoItem.navigateUri, protoItem.title)
}
}
}, modifier = Modifier.statusBarsPadding(), windowInsets = WindowInsets(top = 0.dp), navigationIcon = {
val navController = LocalNavigationController.current
IconButton(onClick = {
navController.navigate("spotify:config") // TODO until we implement user pages
}, modifier = Modifier.padding(start = 8.dp, end = 6.dp)) {
PreviewableAsyncImage(imageUrl = item.profileButton.imageUri, placeholderType = "user", modifier = Modifier.size(36.dp).clip(CircleShape))
}
})
}
@Composable
private fun ToolbarItem(
icon: ImageVector,
navigateTo: String,
contentDesc: String
) {
val navController = LocalNavigationController.current
IconButton(onClick = {
navController.navigate(navigateTo)
}) {
Icon(icon, contentDescription = contentDesc)
}
}
| 15
|
Kotlin
|
18
| 344
|
6173bfa7872ae89664fdac9e42cf36538fe71166
| 2,881
|
jetispot
|
Apache License 2.0
|
app/src/main/java/co/astrnt/kyck/injection/component/FragmentComponent.kt
|
astrnt
| 159,479,226
| false
| null |
package co.astrnt.kyck.injection.component
import co.astrnt.kyck.injection.PerFragment
import co.astrnt.kyck.injection.module.FragmentModule
import dagger.Subcomponent
/**
* This component inject dependencies to all Fragments across the application
*/
@PerFragment
@Subcomponent(modules = [FragmentModule::class])
interface FragmentComponent
| 1
| null |
1
| 1
|
4219ca01df4ae589fc1f761eed8155a39c6b74b5
| 345
|
DemoSdkSampleKotlin
|
The Unlicense
|
app/src/main/java/co/astrnt/kyck/injection/component/FragmentComponent.kt
|
astrnt
| 159,479,226
| false
| null |
package co.astrnt.kyck.injection.component
import co.astrnt.kyck.injection.PerFragment
import co.astrnt.kyck.injection.module.FragmentModule
import dagger.Subcomponent
/**
* This component inject dependencies to all Fragments across the application
*/
@PerFragment
@Subcomponent(modules = [FragmentModule::class])
interface FragmentComponent
| 1
| null |
1
| 1
|
4219ca01df4ae589fc1f761eed8155a39c6b74b5
| 345
|
DemoSdkSampleKotlin
|
The Unlicense
|
src/main/kotlin/internals/instructions/memory/load.kt
|
ChippyPlus
| 850,474,357
| false
|
{"Kotlin": 113521, "Python": 2374, "F#": 446, "Java": 228, "Shell": 148}
|
package internals.instructions.memory
import data.memory.MemoryAddress
import data.registers.RegisterType
import errors
import internalMemory
import registers
/**
* Loads a value from memory into a register.
*
* @param memoryAddress The memory address to load from.
* @param destination The destination register to store the loaded value.
* @throws GeneralMemoryException If an error occurs during the memory load operation.
*/
fun Memory.load(memoryAddress: RegisterType, destination: RegisterType): Unit = try {
registers.write(
register = destination, value = internalMemory.read(MemoryAddress(registers.read(memoryAddress))).value!!
)
} catch (_: Exception) {
errors.GeneralDataTransferException("Load")
}
| 0
|
Kotlin
|
0
| 1
|
8f564320fbe226a0a1f8f6aca56b67c411f5cd68
| 738
|
MVM
|
MIT License
|
src/main/kotlin/com/github/kisaragieffective/dsl/mediawiki/struct/Node.kt
|
KisaragiEffective
| 267,619,092
| false
| null |
package com.github.kisaragieffective.dsl.mediawiki.struct
interface Node {
fun toWikiText() = toString()
}
| 1
|
Kotlin
|
0
| 0
|
2849d882ce8be02de4b26b63d52083e5d2e48486
| 111
|
MediaWikiDSL
|
MIT License
|
app/src/androidTest/java/ru/claus42/anothertodolistapp/tests/robots/TodoItemListTestRobot.kt
|
klauz42
| 679,216,403
| false
|
{"Kotlin": 257915}
|
package ru.claus42.anothertodolistapp.tests.robots
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.contrib.RecyclerViewActions
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.withText
import org.hamcrest.Matchers
import ru.claus42.anothertodolistapp.R
class TodoItemListTestRobot : BaseTestRobot() {
fun scrollToToDoWithDescription(description: String) {
scrollToMatchingItem(
R.id.recycler_view,
ViewMatchers.hasDescendant(ViewMatchers.withText(description))
)
}
fun scrollToToDoWithPosition(position: Int) {
onView(ViewMatchers.withId(R.id.recycler_view))
.perform(
RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(position)
)
}
fun openToDoWithDescription(description: String) {
onView(
Matchers.allOf(
ViewMatchers.withId(R.id.info_icon),
ViewMatchers.hasSibling(ViewMatchers.hasDescendant(ViewMatchers.withText(description)))
)
).perform(ViewActions.click())
}
fun checkToDoDoesNotExist(description: String) {
checkItemDoesNotExist(
R.id.recycler_view,
withText(description),
)
}
companion object {
fun todoItemList(func: TodoItemListTestRobot.() -> Unit) = TodoItemListTestRobot()
.apply { func() }
}
}
| 0
|
Kotlin
|
0
| 0
|
5b1a0521dcff700285ba47d23c42266c99b27ca0
| 1,569
|
Another-Todo-List-App
|
MIT License
|
app/src/main/java/com/vpr/scheduleapp/data/database/schedule/converters/DirectionConverter.kt
|
v1p3rrr
| 544,626,284
| false
|
{"Kotlin": 70700}
|
package com.vpr.scheduleapp.data.database.schedule.converters
import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.vpr.scheduleapp.data.database.schedule.entity.DirectionEntity
class DirectionConverter {
@TypeConverter
fun fromList(value: List<DirectionEntity>): String {
val type = object : TypeToken<List<DirectionEntity>>() {}.type
return Gson().toJson(value, type)
}
@TypeConverter
fun fromString(value: String) : List<DirectionEntity>{
val type = object : TypeToken<List<DirectionEntity>>() {}.type
return Gson().fromJson(value, type)
}
}
| 0
|
Kotlin
|
0
| 1
|
3cd08a8424b5e613f3ab9c7c915b386a4d685d56
| 664
|
ScheduleApp
|
MIT License
|
completion/tests/testData/keywords/SealedWithName.kt
|
JetBrains
| 278,369,660
| false
| null |
// COMPILER_ARGUMENTS: -XXLanguage:+SealedInterfaces -XXLanguage:+MultiPlatformProjects
seal<caret>
// EXIST: "sealed class SealedWithName"
// EXIST: "sealed interface SealedWithName"
// EXIST: "sealed class"
// EXIST: "sealed interface"
// NOTHING_ELSE
| 186
|
Kotlin
|
4323
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 254
|
intellij-kotlin
|
Apache License 2.0
|
compiler/testData/codegen/bytecodeText/invokedynamic/functionRefToJavaInterface.kt
|
JetBrains
| 3,432,266
| false
| null |
// TARGET_BACKEND: JVM
// JVM_TARGET: 1.8
// SAM_CONVERSIONS: INDY
// WITH_STDLIB
// FULL_JDK
fun hello() { println("Hello, world!") }
val test = Runnable(::hello)
// JVM_TEMPLATES:
// 1 public final class FunctionRefToJavaInterfaceKt
// 1 final synthetic class FunctionRefToJavaInterfaceKt\$sam\$java_lang_Runnable\$0
// 1 final synthetic class FunctionRefToJavaInterfaceKt\$test\$1
// JVM_IR_TEMPLATES:
// 1 INVOKEDYNAMIC
// 1 class FunctionRefToJavaInterfaceKt
| 179
| null |
5706
| 48,889
|
c46c3c26038158cf80a739431ac8807ac4bbbc0c
| 468
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/com/insyncwithfoo/pyright/configuration/application/Configurations.kt
|
InSyncWithFoo
| 762,967,939
| false
| null |
package com.insyncwithfoo.pyright.configuration.application
import com.intellij.openapi.components.BaseState
import org.jetbrains.annotations.SystemDependent
internal class Configurations : BaseState() {
var alwaysUseGlobal by property(false)
var globalExecutable by string(null)
var globalConfigurationFile by string(null)
var useEditorFont by property(false)
companion object {
fun create(
alwaysUseGlobal: Boolean,
globalExecutable: @SystemDependent String?,
globalConfigurationFile: @SystemDependent String?,
useEditorFont: Boolean
) =
Configurations().apply {
this.alwaysUseGlobal = alwaysUseGlobal
this.globalExecutable = globalExecutable
this.globalConfigurationFile = globalConfigurationFile
this.useEditorFont = useEditorFont
}
}
}
| 2
| null |
0
| 14
|
6a5362439a6397ef1ff8b6904be9060a9c5ea7de
| 935
|
pyright-for-pycharm
|
MIT License
|
src/test/kotlin/nl/kute/asstring/core/AsStringRecursiveObjectsTest.kt
|
JanHendrikVanHeusden
| 454,323,023
| false
|
{"Kotlin": 733032, "Java": 31861}
|
package nl.kute.asstring.core
import nl.kute.asstring.core.AsStringBuilder.Companion.asStringBuilder
import nl.kute.asstring.namedvalues.NamedSupplier
import nl.kute.helper.base.ObjectsStackVerifier
import nl.kute.helper.base.validateObjectsStack
import nl.kute.helper.helper.isObjectAsString
import nl.kute.reflection.util.simplifyClassName
import nl.kute.testobjects.kotlin.ClassWithToStringCallingAsString
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.util.LinkedList
import java.util.PriorityQueue
import java.util.TreeSet
/**
* This test class particularly aims to test various objects / constructs with self-references
* or circular mutual references: these should yield decent output, **without endless loops / stack overflow**.
* This is accomplished by keeping track of objects being processed by means of an object stack.
*
* The correct begin / end states of the object stack are tested "automagically" / implicitly in the
* `@BeforeEach` and `@AfterEach` methods of classes that implement [ObjectsStackVerifier].
*
* However, the tests in this class [AsStringRecursiveObjectsTest] depend even more heavy on the objects stack,
* so in tests where `asString()` is called more than once, these tests call [validateObjectsStack]`()`
* explicitly after each call to `asString()`
*/
class AsStringRecursiveObjectsTest: ObjectsStackVerifier {
@Test
fun `arrays without recursion should yield same output as contentDeepToString`() {
// arrange
val myArray: Array<Any> = arrayOf(0, 1, 2, 3)
myArray[2] = arrayOf(4, 5, 6)
// act, assert
assertThat(myArray.asString())
.`as`("Should return same result as `myArray.contentDeepToString()`")
.isEqualTo("[0, 1, [4, 5, 6], 3]")
.isEqualTo(myArray.contentDeepToString())
}
@Test
fun `arrays with self-referencing elements should yield decent output`() {
// arrange
val myArray: Array<Any> = arrayOf(0, 1, 2, 3, 4)
myArray[2] = arrayOf(4, 5, 6)
myArray[3] = myArray
myArray[4] = myArray
val expected =
"[0, 1, [4, 5, 6], recursive: ${myArray::class.simpleName}(...), recursive: ${myArray::class.simpleName}(...)]"
// act, assert
assertThat(myArray.asString()).isEqualTo(expected)
}
@Test
fun `arrays with mutually referencing elements should yield decent output`() {
// arrange
val myArray: Array<Any> = arrayOf("a0", "a1", "a2", "a3", "a4")
val myList: MutableList<Any> = mutableListOf("L0", "L1", "L2", "L3", "L4")
myArray[2] = myList
myArray[3] = myList
myList[3] = myArray
myList[1] = myArray
val expectedForArray = "[a0, a1, [L0, recursive: Array(...), L2, recursive: Array(...), L4], [L0, recursive: Array(...), L2, recursive: Array(...), L4], a4]"
val expectedForList = "[L0, [a0, a1, recursive: ArrayList(...), recursive: ArrayList(...), a4], L2, [a0, a1, recursive: ArrayList(...), recursive: ArrayList(...), a4], L4]"
// act, assert
assertThat(myArray.asString()).isEqualTo(expectedForArray)
validateObjectsStack()
assertThat(myList.asString()).isEqualTo(expectedForList)
validateObjectsStack()
}
@Test
fun `Objects with array properties with mutually referencing elements should yield decent output`() {
// arrange
class MyTestClass {
val myArray: Array<Any> = arrayOf("a0", "a1", "a2", "a3", "a4")
val myList: MutableList<Any> = mutableListOf("L0", "L1", "L2", "L3", "L4")
init {
myArray[2] = myList
myArray[3] = myList
myList[3] = myArray
myList[1] = myArray
}
}
// act, assert
val myTestObj = MyTestClass()
assertThat(myTestObj.asString())
.isObjectAsString(
"MyTestClass",
"myArray=[a0, a1, [L0, recursive: Array(...), L2, recursive: Array(...), L4], [L0, recursive: Array(...), L2, recursive: Array(...), L4], a4]",
"myList=[L0, [a0, a1, recursive: ArrayList(...), recursive: ArrayList(...), a4], L2, [a0, a1, recursive: ArrayList(...), recursive: ArrayList(...), a4], L4]"
)
}
@Test
fun `Collections without recursion should yield same output as their default toString method`() {
// arrange
val values = arrayOf("first", "second", "third")
listOf(
listOf(*values),
setOf(*values),
PriorityQueue(values.asList()),
HashMap<String, String>().apply { this.putAll(values.map { it to it }) },
LinkedList(values.asList()),
TreeSet(values.asList())
).forEachIndexed { i, it ->
assertThat(it.asString())
.`as`("asString() of expression #$i should adhere to toString()")
.isEqualTo(it.toString())
}
}
@Test
fun `Collections with self-referencing elements should yield decent output`() {
// arrange
val mutableList: MutableList<Any> = mutableListOf("first", "second", "third")
mutableList[1] = mutableList // self reference
mutableList.add(mutableList) // self reference
// act, assert
assertThat(mutableList.asString())
.isEqualTo("[first, recursive: ${mutableList::class.simpleName}(...), third, recursive: ${mutableList::class.simpleName}(...)]")
}
@Test
fun `Collections with mutually referencing elements should yield decent output`() {
// arrange
val list1: MutableList<Any> = mutableListOf("first 1", "second 1", "third 1")
val list2: LinkedList<Any> = LinkedList(listOf("first 2", "second 2", "third 2"))
list1.add(list2)
list1.add(list2)
list2.add(list1)
list2.add(list1)
val expected1 =
"[first 1, second 1, third 1, [first 2, second 2, third 2, recursive: ArrayList(...), recursive: ArrayList(...)]," +
" [first 2, second 2, third 2, recursive: ArrayList(...), recursive: ArrayList(...)]]"
val expected2 =
"[first 2, second 2, third 2, [first 1, second 1, third 1, recursive: LinkedList(...), recursive: LinkedList(...)]," +
" [first 1, second 1, third 1, recursive: LinkedList(...), recursive: LinkedList(...)]]"
// act, assert
assertThat(list1.asString()).isEqualTo(expected1)
validateObjectsStack()
assertThat(list2.asString()).isEqualTo(expected2)
validateObjectsStack()
}
@Test
fun `Objects with collection properties with mutually referencing elements should yield decent output`() {
// arrange
class MyTestClass {
val list1: MutableList<Any> = mutableListOf("first 1", "second 1", "third 1")
val list2: LinkedList<Any> = LinkedList(listOf("first 2", "second 2", "third 2"))
init {
list1.add(list2)
list1.add(list2)
list2.add(list1)
list2.add(list1)
}
}
val testObj = MyTestClass()
// act, assert
assertThat(testObj.asString())
.isObjectAsString(
"MyTestClass",
"list1=[first 1, second 1, third 1, [first 2, second 2, third 2," +
" recursive: ArrayList(...), recursive: ArrayList(...)], [first 2, second 2, third 2," +
" recursive: ArrayList(...), recursive: ArrayList(...)]]",
"list2=[first 2, second 2, third 2, [first 1, second 1, third 1," +
" recursive: LinkedList(...), recursive: LinkedList(...)], [first 1, second 1, third 1, " +
"recursive: LinkedList(...), recursive: LinkedList(...)]]"
)
}
@Suppress("unused")
private class GetSelfReference (val id: Int, var selfRef: GetSelfReference? = null, var otherRef: GetSelfReference? = null) {
override fun toString(): String = asString()
}
@Test
fun `objects with self reference should yield decent output`() {
// arrange
val testObj = GetSelfReference(1)
val other = GetSelfReference(2)
testObj.selfRef = testObj
testObj.otherRef = other
val className = GetSelfReference::class.simplifyClassName()
val expected = "$className(id=1, otherRef=$className(id=2, otherRef=null, selfRef=null), selfRef=recursive: $className(...))"
// act, assert
assertThat(testObj.asString()).isEqualTo(expected)
.isObjectAsString(
className,
"id=1",
"otherRef=${testObj.otherRef.asString()}",
"selfRef=recursive: $className(...)"
)
}
@Test
fun `lambdas with mutual reference should yield decent output`() {
assertThat(MutualReferencingLambdas().asString())
.isObjectAsString(
"MutualReferencingLambdas",
"lambda1=(() -> Unit) -> Unit",
"lambda2=(() -> Unit) -> Unit"
)
}
@Test
fun `Supplier that supplies an object whose toString calls asString`() {
val testObj = ClassWithToStringCallingAsString()
val namedSupplier = NamedSupplier("asStringCaller") { testObj }
val asStringBuilder = testObj.asStringBuilder()
.withAlsoNamed(namedSupplier)
.build()
assertThat(asStringBuilder.asString())
.isObjectAsString(
"ClassWithToStringCallingAsString",
"prop1=I am prop1",
withLastPropertyString = "asStringCaller=recursive: ClassWithToStringCallingAsString(...)"
)
assertThat(testObj)
.`as`("This assertion is just to prevent the testObj to be garbage collected prematurely")
.isNotNull
}
@Suppress("unused")
@Test
fun `objects with mutual reference should yield decent output`() {
// arrange
class Parent(val name: String, val children: MutableSet<Any> = mutableSetOf()) {
override fun toString(): String = asString()
}
@Suppress("CanBeParameter")
class Child(val name: String, val mother: Parent, val father: Parent) {
init {
mother.children.add(this)
father.children.add(this)
}
override fun toString(): String = asString()
}
val mother = Parent(name = "M")
val father = Parent(name = "F")
val child1 = Child("C1", mother, father)
val child2 = Child("C2", mother, father)
//@formatter:off
val expectedMother =
"Parent(children=[" +
"Child(father=Parent(children=[" +
"recursive: Child(...), " +
"Child(father=recursive: Parent(...), mother=recursive: Parent(...), name=C2)], " +
"name=F), " +
"mother=recursive: Parent(...), " +
"name=C1), " +
"Child(father=Parent(children=[" +
"Child(father=recursive: Parent(...), mother=recursive: Parent(...), name=C1), " +
"recursive: Child(...)], " +
"name=F), " +
"mother=recursive: Parent(...), " +
"name=C2)], " +
"name=M)"
val expectedFather =
"Parent(children=[" +
"Child(father=recursive: Parent(...), " +
"mother=Parent(children=[" +
"recursive: Child(...), " +
"Child(father=recursive: Parent(...), mother=recursive: Parent(...), name=C2)], " +
"name=M), " +
"name=C1), " +
"Child(father=recursive: Parent(...), " +
"mother=Parent(children=[" +
"Child(father=recursive: Parent(...), mother=recursive: Parent(...), name=C1), " +
"recursive: Child(...)], " +
"name=M), " +
"name=C2)], " +
"name=F)"
val expectedChild1 =
"Child(father=Parent(children=[" +
"recursive: Child(...), " +
"Child(father=recursive: Parent(...), " +
"mother=Parent(children=[" +
"recursive: Child(...), " +
"recursive: Child(...)], " +
"name=M), " +
"name=C2)], " +
"name=F), " +
"mother=Parent(children=[" +
"recursive: Child(...), " +
"Child(father=Parent(children=[" +
"recursive: Child(...), " +
"recursive: Child(...)], " +
"name=F), " +
"mother=recursive: Parent(...), " +
"name=C2)], " +
"name=M), " +
"name=C1)"
val expectedChild2 =
"Child(father=Parent(children=[" +
"Child(father=recursive: Parent(...), " +
"mother=Parent(children=[" +
"recursive: Child(...), " +
"recursive: Child(...)], " +
"name=M), " +
"name=C1), " +
"recursive: Child(...)], " +
"name=F), " +
"mother=Parent(children=[" +
"Child(father=Parent(children=[" +
"recursive: Child(...), " +
"recursive: Child(...)], " +
"name=F), " +
"mother=recursive: Parent(...), " +
"name=C1), " +
"recursive: Child(...)], " +
"name=M), " +
"name=C2)"
//@formatter:on
// act, assert
assertThat(mother.toString()).isEqualTo(expectedMother)
validateObjectsStack()
assertThat(father.toString()).isEqualTo(expectedFather)
validateObjectsStack()
assertThat(child1.toString()).isEqualTo(expectedChild1)
validateObjectsStack()
assertThat(child2.toString()).isEqualTo(expectedChild2)
validateObjectsStack()
}
}
private class MutualReferencingLambdas {
lateinit var lambda1: (() -> Unit) -> Unit
lateinit var lambda2: (() -> Unit) -> Unit
init {
lambda1 = {alambda -> println("${alambda.asString()}, lambda1 = ${lambda1.asString()}, lambda2 = ${lambda2.asString()}") }
lambda2 = {alambda -> println("${alambda.asString()}, lambda1 = ${lambda1.asString()}, lambda2 = ${lambda2.asString()}") }
}
}
| 0
|
Kotlin
|
0
| 1
|
6d83ba7e801cdd4dc27e321c9048ead4c365766c
| 15,348
|
Kute
|
MIT License
|
librococoa/src/main/kotlin/darwin/NSDraggingDestination.kt
|
wgpu4k
| 773,068,055
| false
|
{"Kotlin": 1819399, "Java": 1651224, "C": 1136043, "TypeScript": 966071, "HTML": 87125, "WGSL": 68238, "JavaScript": 8101, "CSS": 5773, "Shell": 253}
|
package darwin
import org.rococoa.cocoa.foundation.NSUInteger
interface NSDraggingDestination {
/**
* Original signature : `NSDragOperation draggingEntered(id<NSDraggingInfo>)</NSDraggingInfo>`<br></br>
* *native declaration : line 47*
*/
fun draggingEntered(sender: org.rococoa.ID?): NSUInteger?
/**
* Original signature : `NSDragOperation draggingUpdated(org.rococoa.ID)`<br></br>
* if the destination responded to draggingEntered: but not to draggingUpdated: the return value from draggingEntered: is used<br></br>
* *native declaration : line 48*
*/
fun draggingUpdated(sender: org.rococoa.ID?): NSUInteger?
/**
* Original signature : `void draggingExited(org.rococoa.ID)`<br></br>
* *native declaration : line 49*
*/
fun draggingExited(sender: org.rococoa.ID?)
/**
* Original signature : `BOOL prepareForDragOperation(org.rococoa.ID)`<br></br>
* *native declaration : line 50*
*/
fun prepareForDragOperation(sender: org.rococoa.ID?): Boolean
/**
* Original signature : `BOOL performDragOperation(org.rococoa.ID)`<br></br>
* *native declaration : line 51*
*/
fun performDragOperation(sender: org.rococoa.ID?): Boolean
/**
* Original signature : `void concludeDragOperation(org.rococoa.ID)`<br></br>
* *native declaration : line 52*
*/
fun concludeDragOperation(sender: org.rococoa.ID?)
/**
* draggingEnded: is implemented as of Mac OS 10.5<br></br>
* Original signature : `void draggingEnded(org.rococoa.ID)`<br></br>
* *native declaration : line 54*
*/
fun draggingEnded(sender: org.rococoa.ID?)
/**
* the receiver of -wantsPeriodicDraggingUpdates should return NO if it does not require periodic -draggingUpdated messages (eg. not autoscrolling or otherwise dependent on draggingUpdated: sent while mouse is stationary)<br></br>
* Original signature : `BOOL wantsPeriodicDraggingUpdates()`<br></br>
* *native declaration : line 57*
*/
fun wantsPeriodicDraggingUpdates(): Boolean
}
| 1
|
Kotlin
|
2
| 25
|
a7f0d7ffcd720e6c1a5da511655434627baff91e
| 1,967
|
wgpu4k
|
MIT License
|
compose/material3/material3/src/androidUnitTest/kotlin/androidx/compose/material3/carousel/MultiBrowseTest.kt
|
androidx
| 256,589,781
| false
| null |
/*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3.carousel
import androidx.compose.ui.unit.Density
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class MultiBrowseTest {
private val Density = Density(1f)
@Test
fun testMultiBrowse_doesNotResizeLargeWhenEnoughRoom() {
val itemSize = 120f // minSmallItemSize = 40.dp * 3
val keylineList = multiBrowseKeylineList(
density = Density,
carouselMainAxisSize = 500f,
preferredItemSize = itemSize,
itemSpacing = 0f,
itemCount = 10,
)!!
val strategy = Strategy { keylineList }.apply(500f)
assertThat(strategy.itemMainAxisSize).isEqualTo(itemSize)
}
@Test
fun testMultiBrowse_resizesItemLargerThanContainerToFit1Small() {
val itemSize = 200f
val keylineList = multiBrowseKeylineList(
density = Density,
carouselMainAxisSize = 100f,
preferredItemSize = itemSize,
itemSpacing = 0f,
itemCount = 10,
)!!
val strategy = Strategy { keylineList }.apply(100f)
val minSmallItemSize: Float = with(Density) { StrategyDefaults.MinSmallSize.toPx() }
val keylines = strategy.defaultKeylines
// If the item size given is larger than the container, the adjusted keyline list from
// the multi-browse keyline list should be [xSmall-Large-Small-xSmall]
assertThat(strategy.itemMainAxisSize).isAtMost(100f)
assertThat(keylines).hasSize(4)
assertThat(keylines[0].unadjustedOffset).isLessThan(0f)
assertThat(keylines[keylines.lastIndex].unadjustedOffset).isGreaterThan(100f)
assertThat(keylines[1].isFocal).isTrue()
assertThat(keylines[2].size).isEqualTo(minSmallItemSize)
}
@Test
fun testMultiBrowse_hasNoSmallItemsIfNotEnoughRoom() {
val minSmallItemSize: Float = with(Density) { StrategyDefaults.MinSmallSize.toPx() }
val keylineList = multiBrowseKeylineList(
density = Density,
carouselMainAxisSize = minSmallItemSize,
preferredItemSize = 200f,
itemSpacing = 0f,
itemCount = 10,
)!!
val strategy = Strategy { keylineList }.apply(minSmallItemSize)
val keylines = strategy.defaultKeylines
assertThat(strategy.itemMainAxisSize).isEqualTo(minSmallItemSize)
assertThat(keylines.firstFocal == keylines.firstNonAnchor)
assertThat(keylines.lastFocal == keylines.lastNonAnchor)
}
@Test
fun testMultiBrowse_isNullIfAvailableSpaceIsZero() {
val keylineList = multiBrowseKeylineList(
density = Density,
carouselMainAxisSize = 0f,
preferredItemSize = 200f,
itemSpacing = 0f,
itemCount = 10,
)
assertThat(keylineList).isNull()
}
@Test
fun testMultiBrowse_adjustsMediumSizeToBeProportional() {
val maxSmallItemSize: Float = with(Density) { StrategyDefaults.MaxSmallSize.toPx() }
val preferredItemSize = 200f
val carouselSize = preferredItemSize * 2 + maxSmallItemSize * 2
val keylineList = multiBrowseKeylineList(
density = Density,
carouselMainAxisSize = carouselSize,
preferredItemSize = preferredItemSize,
itemSpacing = 0f,
itemCount = 10,
)!!
val strategy = Strategy { keylineList }.apply(carouselSize)
val keylines = strategy.defaultKeylines
// Assert that there's only one small item, and a medium item that has a size between
// the large and small items
// We expect a keyline list of [xSmall-Large-Large-Medium-Small-xSmall]
assertThat(keylines).hasSize(6)
assertThat(keylines[1].isFocal).isTrue()
assertThat(keylines[2].isFocal).isTrue()
assertThat(keylines[3].size).isLessThan(keylines[2].size)
assertThat(keylines[4].size).isLessThan(keylines[3].size)
}
@Test
fun testMultiBrowse_withLessItemsThanKeylines() {
val maxSmallItemSize: Float = with(Density) { StrategyDefaults.MaxSmallSize.toPx() }
val preferredItemSize = 200f
val carouselSize = preferredItemSize * 2 + maxSmallItemSize * 2
val keylineList = multiBrowseKeylineList(
density = Density,
carouselMainAxisSize = carouselSize,
preferredItemSize = preferredItemSize,
itemSpacing = 0f,
itemCount = 3,
)!!
val strategy = Strategy { keylineList }.apply(carouselSize)
val keylines = strategy.defaultKeylines
// We originally expect a keyline list of [xSmall-Large-Large-Medium-Small-xSmall], but with
// a maximum keyline restriction of 3, we now expect [xSmall-Large-Large-Small-xSmall]
assertThat(keylines).hasSize(5)
assertThat(keylines[1].isFocal).isTrue()
assertThat(keylines[2].isFocal).isTrue()
assertThat(keylines[3].size).isLessThan(keylines[2].size)
}
}
| 27
| null |
911
| 4,986
|
35d53e9504e8bb9a2106c39db814176c9d63046b
| 5,780
|
androidx
|
Apache License 2.0
|
discussions/discussions-stubs/src/main/kotlin/DiscStubItems.kt
|
Piligrim678
| 600,730,971
| false
| null |
package ru.music.discussions.stubs
import ru.music.common.models.*
object DiscStubItems {
val DISCUSSION_FIRST: DiscDiscussion
get() = DiscDiscussion(
id = DiscId("678"),
title = "Helpmeplz",
ownerId = DiscUserId("user-01"),
soundUrl = "www.lorem.ipsum",
status = DiscStatus.OPEN,
permissionsClient = mutableListOf(
DiscPermissionsClient.READ,
DiscPermissionsClient.UPDATE,
DiscPermissionsClient.DELETE
)
)
val ALL_DISCUSSIONS = listOf(DISCUSSION_FIRST, DISCUSSION_FIRST, DISCUSSION_FIRST)
val USERS_DISCUSSIONS = listOf(DISCUSSION_FIRST, DISCUSSION_FIRST)
}
| 1
|
Kotlin
|
0
| 0
|
830345248c570cfbd74d5bc0455b2a451dd25dac
| 722
|
music
|
Apache License 2.0
|
app/src/main/kotlin/com/mgaetan89/showsrage/model/RealmString.kt
|
HD-CIPL
| 61,888,053
| true
|
{"Kotlin": 664263}
|
package com.mgaetan89.showsrage.model
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class RealmString : RealmObject() {
@PrimaryKey
open var value: String = ""
}
| 0
|
Kotlin
|
0
| 0
|
27453cd388a73cc2ff9abc69109a65fbf1ac5977
| 198
|
ShowsRage
|
Apache License 2.0
|
app/src/main/kotlin/com/aquamorph/frcmanager/fragments/AwardFragment.kt
|
AquaMorph
| 43,819,985
| false
|
{"Kotlin": 172917}
|
package com.aquamorph.frcmanager.fragments
import android.content.SharedPreferences
import android.os.Bundle
import android.os.SystemClock
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.aquamorph.frcmanager.R
import com.aquamorph.frcmanager.adapters.AwardAdapter
import com.aquamorph.frcmanager.decoration.Animations
import com.aquamorph.frcmanager.decoration.Divider
import com.aquamorph.frcmanager.models.tba.Award
import com.aquamorph.frcmanager.network.DataLoader
import com.aquamorph.frcmanager.utils.Constants
/**
* Displays a list of awards at a event
*
* @author <NAME>
* @version 3/25/2023
*/
class AwardFragment :
TabFragment(), SharedPreferences.OnSharedPreferenceChangeListener, RefreshFragment {
private var awards: ArrayList<Award> = ArrayList()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_team_schedule, container, false)
super.onCreateView(view, awards,
AwardAdapter(requireContext(), awards),
Divider(requireContext(), Constants.DIVIDER_WIDTH, 0))
prefs.registerOnSharedPreferenceChangeListener(this)
return view
}
override fun dataUpdate() {
awards.clear()
awards.addAll(DataLoader.awardDC.data)
filterAwards()
Constants.checkNoDataScreen(DataLoader.awardDC.data, recyclerView, emptyView)
Animations.loadAnimation(context, recyclerView, adapter,
firstLoad, DataLoader.awardDC.newData)
firstLoad = false
}
/**
* filterAwards() removes awards that were not given out.
*/
private fun filterAwards() {
var i = 0
while (i < awards.size) {
if (awards[i].recipientList.size == 1 &&
awards[i].recipientList[0].awardee == null &&
awards[i].recipientList[0].teamKey == null) {
awards.remove(awards[i])
} else {
i++
}
}
}
override fun onResume() {
super.onResume()
if (awards.isEmpty())
refresh()
}
/**
* refresh() loads dataLoader needed for this fragment.
*/
override fun refresh() {
if (DataLoader.eventKey != "") {
mSwipeRefreshLayout.isRefreshing = true
executor.execute {
while (!DataLoader.awardDC.complete) {
SystemClock.sleep(Constants.THREAD_WAIT_TIME.toLong())
}
handler.post {
if (context != null) {
dataUpdate()
mSwipeRefreshLayout.isRefreshing = false
}
}
}
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String?) {
if (key == "eventKey") {
refresh()
}
}
companion object {
/**
* newInstance creates and returns a new AwardFragment
*
* @return AwardFragment
*/
fun newInstance(): AwardFragment {
return AwardFragment()
}
}
}
| 12
|
Kotlin
|
1
| 0
|
a6a2c35c06a8e7a06b19f75dee0021d1fa5e92aa
| 3,308
|
FRC-Manager
|
Apache License 2.0
|
meistercharts-history/meistercharts-history-core/src/commonMain/kotlin/com/meistercharts/history/HistoryDecimalConfiguration.kt
|
Neckar-IT
| 599,079,962
| false
|
{"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114}
|
/**
* Copyright 2023 Neckar IT GmbH, Mössingen, Germany
*
* 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.meistercharts.history
import it.neckar.open.annotations.Slow
import it.neckar.open.collections.IntArrayList
import it.neckar.open.collections.emptyIntArray
import it.neckar.open.collections.fastForEachIndexed
import it.neckar.open.i18n.TextKey
import it.neckar.open.unit.other.ID
import kotlinx.serialization.Serializable
/**
* Contains the history configuration for data series that have decimal values.
*
* Should not be used directly - instead use [HistoryConfiguration]
*/
@Serializable
class HistoryDecimalConfiguration(
/**
* The ids of the data series.
*/
override val dataSeriesIds: @DecimalDataSeriesIndexInt IntArray,
/**
* The display names for each data series
* Has the same size as [dataSeriesIds]
*/
override val displayNames: List<TextKey>,
/**
* The units for each data series
*/
val units: List<HistoryUnit>,
) : AbstractHistoryConfiguration() {
init {
require(dataSeriesIds.size == displayNames.size) {
"size mismatch - display names: ${dataSeriesIds.size} vs ${displayNames.size}"
}
require(dataSeriesIds.size == units.size) {
"size mismatch - units: ${dataSeriesIds.size} vs ${units.size}"
}
}
/**
* Returns the data series id at the given index
*/
fun getDataSeriesId(dataSeriesIndex: DecimalDataSeriesIndex): DataSeriesId {
return DataSeriesId(getDataSeriesIdAsInt(dataSeriesIndex.value))
}
/**
* Returns the unit for the given data series index
*/
fun getUnit(dataSeriesIndex: DecimalDataSeriesIndex): HistoryUnit {
return units[dataSeriesIndex.value]
}
/**
* Returns the human-readable name for the *index* (not ID)
*/
fun getDisplayName(dataSeriesIndex: DecimalDataSeriesIndex): TextKey {
return displayNames[dataSeriesIndex.value]
}
/**
* Returns the data series index for a given data series id
*/
@Slow
fun getDataSeriesIndex(dataSeriesId: DataSeriesId): DecimalDataSeriesIndex {
return DecimalDataSeriesIndex(dataSeriesIds.indexOf(dataSeriesId.value))
}
fun dump(): String {
return buildString {
dataSeriesIds.fastForEachIndexed { index, dataSeriesIndexAsInt ->
append(dataSeriesIndexAsInt.toString().padStart(7))
append(": ")
append(displayNames[index].fallbackText.padEnd(25))
append(" | (")
append((units[index].name + ")").padEnd(15))
appendLine()
}
}
}
override fun toString(): String {
return "HistoryDecimalConfiguration(dataSeriesIds=${dataSeriesIds.contentToString()},\ndisplayNames=${displayNames})"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
if (!super.equals(other)) return false
other as HistoryDecimalConfiguration
if (!dataSeriesIds.contentEquals(other.dataSeriesIds)) return false
if (displayNames != other.displayNames) return false
return units == other.units
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + dataSeriesIds.contentHashCode()
result = 31 * result + displayNames.hashCode()
result = 31 * result + units.hashCode()
return result
}
companion object {
/**
* An empty history decimal configuration without any data series
*/
val empty: HistoryDecimalConfiguration = HistoryDecimalConfiguration(emptyIntArray(), emptyList(), emptyList())
}
/**
* Builder for [HistoryDecimalConfiguration]
*/
class Builder {
private val dataSeriesIds: @ID IntArrayList = IntArrayList()
private val displayNames: MutableList<TextKey> = mutableListOf()
private val units: MutableList<HistoryUnit> = mutableListOf()
/**
* Adds a decimal data series
*/
fun decimalDataSeries(id: DataSeriesId, displayName: TextKey, unit: HistoryUnit = HistoryUnit.None) {
require(dataSeriesIds.contains(id.value).not()) { "id <$id> already added" }
dataSeriesIds.add(id.value)
displayNames.add(displayName)
units.add(unit)
}
fun decimalDataSeries(id: DataSeriesId, displayName: String, unit: HistoryUnit = HistoryUnit.None) {
decimalDataSeries(id, TextKey.simple(displayName), unit)
}
fun build(): HistoryDecimalConfiguration {
return HistoryDecimalConfiguration(dataSeriesIds.toIntArray(), displayNames, units.toList())
}
}
}
| 3
|
Kotlin
|
3
| 5
|
ed849503e845b9d603598e8d379f6525a7a92ee2
| 5,026
|
meistercharts
|
Apache License 2.0
|
ECommerceTrainingProject/app/src/main/java/com/training/ecommerce/ui/home/MainActivity.kt
|
eslamfaisal
| 757,328,403
| false
|
{"Kotlin": 153908, "Dart": 60034, "JavaScript": 10092, "HTML": 6764, "CSS": 1066}
|
package com.training.ecommerce.ui.home
import android.app.ActivityOptions
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.lifecycleScope
import com.training.ecommerce.R
import com.training.ecommerce.databinding.ActivityMainBinding
import com.training.ecommerce.ui.account.fragments.AccountFragment
import com.training.ecommerce.ui.auth.AuthActivity
import com.training.ecommerce.ui.cart.fragments.CartFragment
import com.training.ecommerce.ui.common.viewmodel.UserViewModel
import com.training.ecommerce.ui.explore.fragments.ExploreFragment
import com.training.ecommerce.ui.home.adapter.HomeViewPagerAdapter
import com.training.ecommerce.ui.home.fragments.HomeFragment
import com.training.ecommerce.ui.offers.OffersFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val userViewModel: UserViewModel by viewModels()
private var _bindig: ActivityMainBinding? = null
private val binding get() = _bindig!!
override fun onCreate(savedInstanceState: Bundle?) {
initSplashScreen()
super.onCreate(savedInstanceState)
val isLoggedIn = runBlocking { userViewModel.isUserLoggedIn().first() }
if (!isLoggedIn) {
goToAuthActivity()
return
}
_bindig = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initViewModel()
initViews()
}
private fun initViews() {
initViewPager()
initBottomNavigationView()
}
private fun initBottomNavigationView() {
binding.bottomNavigationView.setOnItemSelectedListener {
when (it.itemId) {
R.id.homeFragment -> binding.homeViewPager.currentItem = 0
R.id.exploreFragment -> binding.homeViewPager.currentItem = 1
R.id.cartFragment -> binding.homeViewPager.currentItem = 2
R.id.offerFragment -> binding.homeViewPager.currentItem = 3
R.id.accountFragment -> binding.homeViewPager.currentItem = 4
}
true
}
}
private fun initViewPager() {
val fragments = listOf(
HomeFragment(),
ExploreFragment(),
CartFragment(),
OffersFragment(),
AccountFragment()
)
binding.homeViewPager.offscreenPageLimit = fragments.size
binding.homeViewPager.adapter = HomeViewPagerAdapter(this, fragments)
binding.homeViewPager.registerOnPageChangeCallback(
object : androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
binding.bottomNavigationView.menu.getItem(position).isChecked = true
}
}
)
}
private fun initViewModel() {
lifecycleScope.launch {
val userDetails = runBlocking { userViewModel.getUserDetails().first() }
Log.d(TAG, "initViewModel: user details ${userDetails.email}")
userViewModel.userDetailsState.collect {
Log.d(TAG, "initViewModel: user details updated ${it?.email}")
}
}
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume: ")
}
private fun goToAuthActivity() {
val intent = Intent(this, AuthActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val options = ActivityOptions.makeCustomAnimation(
this, android.R.anim.fade_in, android.R.anim.fade_out
)
startActivity(intent, options.toBundle())
finish()
}
private fun initSplashScreen() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
installSplashScreen()
} else {
setTheme(R.style.Theme_ECommerce)
}
}
override fun onDestroy() {
super.onDestroy()
_bindig = null
}
companion object {
private const val TAG = "MainActivity"
}
}
| 2
|
Kotlin
|
15
| 52
|
3348446527ef3c1e23c0ac0a9346792f3fba7c41
| 4,487
|
android-development-training
|
MIT License
|
apps/etterlatte-behandling/src/main/kotlin/behandling/omregning/OmregningService.kt
|
navikt
| 417,041,535
| false
|
{"Kotlin": 3977041, "TypeScript": 855520, "Handlebars": 19431, "Shell": 9939, "HTML": 1776, "CSS": 598, "Dockerfile": 520}
|
package no.nav.etterlatte.behandling.omregning
import kotlinx.coroutines.runBlocking
import no.nav.etterlatte.behandling.BehandlingService
import no.nav.etterlatte.behandling.GrunnlagService
import no.nav.etterlatte.behandling.revurdering.RevurderingService
import no.nav.etterlatte.libs.common.Vedtaksloesning
import no.nav.etterlatte.libs.common.behandling.Prosesstype
import no.nav.etterlatte.libs.common.behandling.RevurderingAarsak
import no.nav.etterlatte.libs.common.behandling.SakType
import java.time.LocalDate
import java.util.UUID
class OmregningService(
private val behandlingService: BehandlingService,
private val grunnlagService: GrunnlagService,
private val revurderingService: RevurderingService,
) {
fun opprettOmregning(
sakId: Long,
fraDato: LocalDate,
prosessType: Prosesstype,
): Triple<UUID, UUID, SakType> {
val forrigeBehandling =
behandlingService.hentSisteIverksatte(sakId)
?: throw IllegalArgumentException("Fant ikke forrige behandling i sak $sakId")
val persongalleri = runBlocking { grunnlagService.hentPersongalleri(sakId, forrigeBehandling.id) }
val behandling =
when (prosessType) {
Prosesstype.AUTOMATISK ->
revurderingService.opprettAutomatiskRevurdering(
sakId = sakId,
forrigeBehandling = forrigeBehandling,
revurderingAarsak = RevurderingAarsak.REGULERING,
virkningstidspunkt = fraDato,
kilde = Vedtaksloesning.GJENNY,
persongalleri = persongalleri,
)
Prosesstype.MANUELL -> throw Exception("Støtter ikke prosesstype MANUELL")
} ?: throw Exception("Opprettelse av revurdering feilet for $sakId")
return Triple(behandling.id, forrigeBehandling.id, behandling.sak.sakType)
}
}
| 14
|
Kotlin
|
0
| 5
|
d0b42ff1df660904897d6869868f440747ce74d5
| 1,965
|
pensjon-etterlatte-saksbehandling
|
MIT License
|
apps/etterlatte-behandling/src/main/kotlin/behandling/omregning/OmregningService.kt
|
navikt
| 417,041,535
| false
|
{"Kotlin": 3977041, "TypeScript": 855520, "Handlebars": 19431, "Shell": 9939, "HTML": 1776, "CSS": 598, "Dockerfile": 520}
|
package no.nav.etterlatte.behandling.omregning
import kotlinx.coroutines.runBlocking
import no.nav.etterlatte.behandling.BehandlingService
import no.nav.etterlatte.behandling.GrunnlagService
import no.nav.etterlatte.behandling.revurdering.RevurderingService
import no.nav.etterlatte.libs.common.Vedtaksloesning
import no.nav.etterlatte.libs.common.behandling.Prosesstype
import no.nav.etterlatte.libs.common.behandling.RevurderingAarsak
import no.nav.etterlatte.libs.common.behandling.SakType
import java.time.LocalDate
import java.util.UUID
class OmregningService(
private val behandlingService: BehandlingService,
private val grunnlagService: GrunnlagService,
private val revurderingService: RevurderingService,
) {
fun opprettOmregning(
sakId: Long,
fraDato: LocalDate,
prosessType: Prosesstype,
): Triple<UUID, UUID, SakType> {
val forrigeBehandling =
behandlingService.hentSisteIverksatte(sakId)
?: throw IllegalArgumentException("Fant ikke forrige behandling i sak $sakId")
val persongalleri = runBlocking { grunnlagService.hentPersongalleri(sakId, forrigeBehandling.id) }
val behandling =
when (prosessType) {
Prosesstype.AUTOMATISK ->
revurderingService.opprettAutomatiskRevurdering(
sakId = sakId,
forrigeBehandling = forrigeBehandling,
revurderingAarsak = RevurderingAarsak.REGULERING,
virkningstidspunkt = fraDato,
kilde = Vedtaksloesning.GJENNY,
persongalleri = persongalleri,
)
Prosesstype.MANUELL -> throw Exception("Støtter ikke prosesstype MANUELL")
} ?: throw Exception("Opprettelse av revurdering feilet for $sakId")
return Triple(behandling.id, forrigeBehandling.id, behandling.sak.sakType)
}
}
| 14
|
Kotlin
|
0
| 5
|
d0b42ff1df660904897d6869868f440747ce74d5
| 1,965
|
pensjon-etterlatte-saksbehandling
|
MIT License
|
rxmusicplayer/src/main/java/com/orfium/rx/musicplayer/playback/BasePlayback.kt
|
praycom
| 177,637,363
| true
|
{"Kotlin": 64361, "Java": 739}
|
package com.orfium.rx.musicplayer.playback
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioAttributes
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.net.wifi.WifiManager
import android.os.Build
import androidx.annotation.RequiresApi
import com.orfium.rx.musicplayer.media.Media
internal abstract class BasePlayback(
protected val context: Context,
private val audioManager: AudioManager,
private val wifiLock: WifiManager.WifiLock
) : Playback.PlayerCallback {
protected var playbackCallback: Playback.ManagerCallback? = null
@Volatile
protected var currentMedia: Media? = null
private val audioBecomingNoisyIntent = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)
private val audioNoisyReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY == intent.action) {
pause()
}
}
}
private val audioFocusChangeListener =
AudioManager.OnAudioFocusChangeListener { focusChange ->
when (focusChange) {
AudioManager.AUDIOFOCUS_GAIN -> {
if (playbackDelayed || resumeOnFocusGain) {
synchronized(focusLock) {
resumeOnFocusGain = false
playbackDelayed = false
}
play(currentMedia)
}
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
synchronized(focusLock) {
resumeOnFocusGain = isPlaying
playbackDelayed = false
}
pause()
}
AudioManager.AUDIOFOCUS_LOSS -> {
synchronized(focusLock) {
resumeOnFocusGain = false
playbackDelayed = false
}
pause()
}
}
}
private val focusLock = Any()
private var audioFocusRequest: AudioFocusRequest? = null
private var playbackDelayed = false
private var resumeOnFocusGain = false
private var receiverRegistered = false
init {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
audioFocusRequest = createAudioFocusRequest()
}
}
abstract fun startPlayer()
abstract fun pausePlayer()
abstract fun resumePlayer()
abstract fun stopPlayer()
override fun play(media: Media?) {
if (media != null && requestFocus() == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
registerWifiLock()
registerNoiseReceiver()
if (media == currentMedia) {
resumePlayer()
} else {
currentMedia = media
startPlayer()
}
}
}
override fun invalidateCurrent() {
currentMedia = null
}
override fun pause() {
pausePlayer()
unregisterWifiLock()
unregisterNoiseReceiver()
}
override fun complete() {
invalidateCurrent()
unregisterWifiLock()
unregisterNoiseReceiver()
}
override fun stop() {
stopPlayer()
releaseFocus()
invalidateCurrent()
unregisterWifiLock()
unregisterNoiseReceiver()
}
override fun setCallback(callback: Playback.ManagerCallback) {
playbackCallback = callback
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createAudioFocusRequest(): AudioFocusRequest =
AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN).run {
setAudioAttributes(
AudioAttributes.Builder().run {
setUsage(AudioAttributes.USAGE_MEDIA)
setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
build()
}
)
setAcceptsDelayedFocusGain(true)
setOnAudioFocusChangeListener(audioFocusChangeListener)
build()
}
private fun requestFocus(): Int {
val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
audioManager.requestAudioFocus(audioFocusRequest!!)
} else {
@Suppress("DEPRECATION")
audioManager.requestAudioFocus(audioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
}
synchronized(focusLock) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
playbackDelayed = result == AudioManager.AUDIOFOCUS_REQUEST_DELAYED
}
}
return result
}
private fun releaseFocus() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
audioManager.abandonAudioFocusRequest(audioFocusRequest!!)
} else {
@Suppress("DEPRECATION")
audioManager.abandonAudioFocus(audioFocusChangeListener)
}
}
private fun registerWifiLock() {
if (!wifiLock.isHeld) {
wifiLock.acquire()
}
}
private fun unregisterWifiLock() {
if (wifiLock.isHeld) {
wifiLock.release()
}
}
private fun registerNoiseReceiver() {
if (!receiverRegistered) {
context.registerReceiver(audioNoisyReceiver, audioBecomingNoisyIntent)
receiverRegistered = true
}
}
private fun unregisterNoiseReceiver() {
if (receiverRegistered) {
try {
context.unregisterReceiver(audioNoisyReceiver)
} catch (ignore: IllegalArgumentException) {
}
receiverRegistered = false
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6a8bc148b20e7d34e85c3740cfd333786f98cc93
| 5,936
|
RxMusicPlayer-android
|
Apache License 2.0
|
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/activity/flight/FlightDailyRecord.kt
|
Anime-Game-Servers
| 642,871,918
| false
|
{"Kotlin": 1651536}
|
package org.anime_game_servers.multi_proto.gi.data.activity.flight
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.Version.GI_1_1_0
import org.anime_game_servers.core.base.annotations.proto.ProtoModel
@AddedIn(GI_1_1_0)
@ProtoModel
internal interface FlightDailyRecord {
var bestScore: Int
var groupId: Int
var isTouched: Boolean
var startTime: Int
var watcherIdList: List<Int>
}
| 0
|
Kotlin
|
2
| 6
|
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
| 453
|
anime-game-multi-proto
|
MIT License
|
app/src/main/java/com/github/leonardoz/kanbapp/view/fragment/BoardsListFragment.kt
|
LeonardoZ
| 161,324,422
| false
| null |
package com.github.leonardoz.kanbapp.view.fragment
import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import com.github.leonardoz.kanbapp.KanbappApplication
import com.github.leonardoz.kanbapp.R
import com.github.leonardoz.kanbapp.data.entity.Board
import com.github.leonardoz.kanbapp.databinding.FragmentBoardsListBinding
import com.github.leonardoz.kanbapp.util.format
import com.github.leonardoz.kanbapp.view.adapter.BoardsAdapter
import com.github.leonardoz.kanbapp.view.dialog.ChangeNameDialog
import com.github.leonardoz.kanbapp.view.viewmodel.BoardsViewModel
import kotlinx.android.synthetic.main.fragment_boards_list.*
import javax.inject.Inject
class BoardsListFragment : Fragment() {
private lateinit var binding: FragmentBoardsListBinding
private lateinit var viewModel: BoardsViewModel
private lateinit var boardsAdapter: BoardsAdapter
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val navigationObserver = Observer<Any> {
activity?.let { activity ->
Navigation.findNavController(activity, R.id.nav_host_fragment)
.navigate(R.id.action_boardsListFragment_to_createBoardFragment)
}
}
private val boardRemovedObserver = Observer<Board> { board ->
activity?.let { activity ->
format(activity.getString(R.string.x_removed), board.name)
Toast.makeText(activity, "", Toast.LENGTH_SHORT)
}
}
private val boardsObserver = Observer<List<Board>> {
boardsAdapter.dataset = it
if (it.isEmpty()) {
boardsRecyclerView.visibility = View.GONE
emptyView.visibility = View.VISIBLE
} else {
boardsRecyclerView.visibility = View.VISIBLE
emptyView.visibility = View.GONE
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity?.applicationContext as KanbappApplication)
.appComponent
.injectBoardsListFragment(this)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentBoardsListBinding.inflate(inflater, container, false)
binding.setLifecycleOwner(this)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
initViewModel()
initRecycler()
}
private fun initViewModel() {
viewModel = ViewModelProviders.of(this, viewModelFactory)
.get(BoardsViewModel::class.java)
binding.let {
it.boardsViewModel = viewModel
viewModel.boards.observe(viewLifecycleOwner, boardsObserver)
viewModel.navigateToCreateBoardFragment.observe(viewLifecycleOwner, navigationObserver)
viewModel.informBoardWasRemoved.observe(viewLifecycleOwner, boardRemovedObserver)
}
}
private fun initRecycler() {
val linearLayoutManager = LinearLayoutManager(context)
boardsAdapter = BoardsAdapter(
::menuCallback,
::openBoardCallback
)
boardsRecyclerView.apply {
adapter = boardsAdapter
layoutManager = linearLayoutManager
setHasFixedSize(true)
}
}
override fun onDestroy() {
boardsRecyclerView?.adapter = null
super.onDestroy()
}
private fun menuCallback(item: MenuItem?, boardPosition: Int) {
when (item?.itemId) {
R.id.menu_change_name -> menuChangeNameClicked(boardPosition)
R.id.menu_remove -> removeBoard(boardPosition)
else -> false
}
}
private fun removeBoard(boardPosition: Int) {
val board = boardsAdapter.dataset[boardPosition]
AlertDialog.Builder(context)
.setTitle(format(getString(R.string.remove_board_ask), board.name))
.setPositiveButton(R.string.remove) { _: DialogInterface, i: Int ->
viewModel.removeBoard(board)
}
.setNegativeButton(R.string.cancel) { dialogInterface: DialogInterface, _ ->
dialogInterface.dismiss()
}.show()
}
private fun menuChangeNameClicked(boardPosition: Int) {
val changeNameDialog = ChangeNameDialog()
val args = Bundle()
val (id, name) = boardsAdapter.dataset[boardPosition]
args.putLong(ChangeNameDialog.ID_PARAM, id)
args.putString(ChangeNameDialog.NAME_PARAM, name)
changeNameDialog.arguments = args
val ft = childFragmentManager.beginTransaction()
val prev = childFragmentManager.findFragmentByTag(CHANGE_DIALOG_KEY)
if (prev != null) {
ft.remove(prev)
}
ft.addToBackStack(null)
changeNameDialog.show(ft, CHANGE_DIALOG_KEY)
true
}
private fun openBoardCallback(board: Board) {
activity?.let {
val action = BoardsListFragmentDirections
.actionBoardsListFragmentToBoardFragment(board.id.toString())
Navigation.findNavController(view!!).navigate(action)
}
}
companion object {
const val CHANGE_DIALOG_KEY = "CHANGE_DIALOG_KEY"
}
}
| 0
|
Kotlin
|
0
| 0
|
55715f293518fc6b4a0bf839238629cbca134807
| 5,781
|
kanbapp
|
MIT License
|
app/src/main/java/com/test/data/model/EventsRawDTO.kt
|
ETSEmpiricalStudyKotlinAndroidApps
| 496,716,943
| true
|
{"Kotlin": 111686, "Java": 1387}
|
package com.test.data.model
import com.google.gson.annotations.SerializedName
data class EventsRaw(
val events: List<EventRawItem>? = null,
val meta: MetaRaw? = null,
)
data class EventRawItem(
val id: String? = null,
val url: String? = null,
val title: String? = null,
@SerializedName("datetime_utc")
val utsTime: String? = null,
@SerializedName("created_at")
val createdAt: String? = null,
)
data class MetaRaw(
val total: String? = null,
)
| 0
| null |
0
| 0
|
4a06616b14298e4003fb0ed15b012f2f1b4cd19b
| 486
|
RoomPaging3TestProject
|
Apache License 2.0
|
app/src/main/java/com/jinwoo/machine_learning_kit/MainActivity.kt
|
jinusong
| 194,656,394
| false
| null |
package com.jinwoo.machine_learning_kit
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.startActivity
class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
main_trans_btn.onClick { startActivity<TransActivity>() }
main_text_btn.onClick { startActivity<TextActivity>() }
main_face_btn.onClick { startActivity<FaceActivity>() }
main_object_btn.onClick { startActivity<TrackObjectActivity>() }
}
}
| 0
|
Kotlin
|
0
| 0
|
00fe1ab6f22264449eef6bd885a6442c90399b05
| 725
|
Machine-learning-Kit
|
MIT License
|
server/src/main/kotlin/org/example/myhome/dto/DeviceMetaDataDto.kt
|
Chantico-org
| 73,012,491
| false
|
{"Kotlin": 25440}
|
package org.example.myhome.dto
data class DeviceMetaDataDto(
val deviceId: String,
val firmwareVersion: Int,
val deviceKey: String,
val sensors: List<Int>,
val controls: List<Int>
)
| 6
|
Kotlin
|
0
| 3
|
2ee5bfacd6d9dafac60b2cacfe9c9daaa5926a99
| 193
|
smart_house
|
MIT License
|
frogocoreconsumeapi/src/main/java/com/frogobox/coreapi/sport/model/Contract.kt
|
frogobox
| 389,577,716
| false
| null |
package com.frogobox.frogoconsumeapi.sport.model
import com.frogobox.frogoconsumeapi.sport.util.SportData.Contract.ID
import com.frogobox.frogoconsumeapi.sport.util.SportData.Contract.ID_PLAYER
import com.frogobox.frogoconsumeapi.sport.util.SportData.Contract.ID_TEAM
import com.frogobox.frogoconsumeapi.sport.util.SportData.Contract.STR_PLAYER
import com.frogobox.frogoconsumeapi.sport.util.SportData.Contract.STR_SPORT
import com.frogobox.frogoconsumeapi.sport.util.SportData.Contract.STR_TEAM
import com.frogobox.frogoconsumeapi.sport.util.SportData.Contract.STR_TEAM_BADGE
import com.frogobox.frogoconsumeapi.sport.util.SportData.Contract.STR_WAGE
import com.frogobox.frogoconsumeapi.sport.util.SportData.Contract.STR_YEAR_END
import com.frogobox.frogoconsumeapi.sport.util.SportData.Contract.STR_YEAR_START
import com.google.gson.annotations.SerializedName
/**
* Created by <NAME>
* FrogoBox Inc License
* =========================================
* TheSportDBApi
* Copyright (C) 08/03/2020.
* All rights reserved
* -----------------------------------------
* Name : <NAME>
* E-mail : <EMAIL>
* Github : github.com/amirisback
* LinkedIn : linkedin.com/in/faisalamircs
* -----------------------------------------
* FrogoBox Software Industries
* com.frogobox.frogoconsumeapi.sport.data.model
*
*/
data class Contract(
@SerializedName(ID)
var id: String? = null,
@SerializedName(ID_PLAYER)
var idPlayer: String? = null,
@SerializedName(ID_TEAM)
var idTeam: String? = null,
@SerializedName(STR_SPORT)
var strSport: String? = null,
@SerializedName(STR_PLAYER)
var strPlayer: String? = null,
@SerializedName(STR_TEAM)
var strTeam: String? = null,
@SerializedName(STR_TEAM_BADGE)
var strTeamBadge: String? = null,
@SerializedName(STR_YEAR_START)
var strYearStart: String? = null,
@SerializedName(STR_YEAR_END)
var strYearEnd: String? = null,
@SerializedName(STR_WAGE)
var strWage: String? = null
)
| 0
|
Kotlin
|
6
| 7
|
1dd90a037f9acb2ba30066f753d35f7b909621a6
| 2,013
|
frogo-consume-api
|
Apache License 2.0
|
glib-core/src/main/java/com/glib/core/ui/pager/GViewPager.kt
|
hgani
| 223,511,724
| false
|
{"Kotlin": 359993, "Java": 37596}
|
package com.glib.core.ui.pager
import android.content.Context
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import android.util.AttributeSet
import com.glib.core.ui.Ui
import com.glib.core.ui.view.ViewHelper
import java.util.*
class GViewPager : ViewPager {
private var helper = ViewHelper(this)
private var timer: Timer? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
fun width(width: Int?): GViewPager {
helper.width(width)
return this
}
fun height(height: Int?): GViewPager {
helper.height(height)
return this
}
fun bgColor(res: Int): GViewPager {
helper.bgColor(res)
return this
}
fun adapter(adapter: PagerAdapter): GViewPager {
super.setAdapter(adapter)
return this
}
// @Override
// protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//
// int height = 0;
//
// for (int i = 0; i < getChildCount(); i++) {
// View child = getChildAt(i);
//
// child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
//
// int h = child.getMeasuredHeight();
//
// if (h > height) height = h;
// }
//
// heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
//
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// }
fun padding(left: Int?, top: Int?, right: Int?, bottom: Int?): GViewPager {
helper.padding(left, top, right, bottom)
return this
}
fun margin(left: Int?, top: Int?, right: Int?, bottom: Int?): GViewPager {
helper.margin(left, top, right, bottom)
return this
}
// See http://stackoverflow.com/questions/17610085/how-to-switch-automatically-between-viewpager-pages
fun autoScroll(millis: Int): GViewPager {
if (timer == null) {
timer = Timer() // At this line a new Thread will be created
timer!!.scheduleAtFixedRate(RemindTask(), 0, millis.toLong())
}
return this
}
private inner class RemindTask : TimerTask() {
private var page = 0
override fun run() {
// As the TimerTask run on a seprate thread from UI thread we have
// to call runOnUiThread to do work on UI thread.
Ui.exec {
page++
if (page >= adapter!!.count) {
page = 0
// timer.cancel();
// // Showing a toast for just testing purpose
// Toast.makeText(getApplicationContext(), "Timer stoped",
// Toast.LENGTH_LONG).show();
}
this@GViewPager.currentItem = page
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9a7c56236d664f2b518310d12e5b0839382c2920
| 3,051
|
glib-android
|
Apache License 2.0
|
kotlin-mui-icons/src/main/generated/mui/icons/material/VaccinesRounded.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/VaccinesRounded")
package mui.icons.material
@JsName("default")
external val VaccinesRounded: SvgIconComponent
| 12
| null |
5
| 983
|
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
| 194
|
kotlin-wrappers
|
Apache License 2.0
|
src/main/kotlin/vjson/pl/ast/FunctionInvocation.kt
|
wkgcass
| 202,796,825
| false
| null |
/*
* The MIT License
*
* Copyright 2021 wkgcass (https://github.com/wkgcass)
*
* 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 io.vproxy.dep.vjson.pl.ast
import io.vproxy.dep.vjson.cs.LineCol
import io.vproxy.dep.vjson.ex.ParserException
import io.vproxy.dep.vjson.pl.inst.*
import io.vproxy.dep.vjson.pl.type.*
data class FunctionInvocation(
val target: Expr,
val args: List<Expr>
) : Expr() {
override fun copy(): FunctionInvocation {
val ret = FunctionInvocation(target.copy(), args.map { it.copy() })
ret.lineCol = lineCol
return ret
}
override fun check(ctx: TypeContext): TypeInstance {
this.ctx = ctx
val targetType = target.check(ctx)
val func = targetType.functionDescriptor(ctx)
?: throw ParserException("$this: unable to invoke $target, which is not a functional object", lineCol)
if (func.params.size != args.size) {
throw ParserException(
"$this: unable to invoke $target with $args, arguments count (${args.size}) parameters count (${func.params.size}) mismatch",
lineCol
)
}
for (idx in args.indices) {
val argType = args[idx].check(ctx)
val paramType = func.params[idx]
if (!TypeUtils.assignableFrom(paramType.type, argType)) {
throw ParserException(
"$this: unable to invoke $target with $args, args[$idx] $argType does not match params[$idx] $paramType",
lineCol
)
}
}
return func.returnType
}
override fun typeInstance(): TypeInstance {
return target.typeInstance().functionDescriptor(ctx)!!.returnType
}
override fun generateInstruction(): Instruction {
return buildFunctionInvocationInstruction(ctx, this, args.map { it.generateInstruction() })
}
override fun toString(indent: Int): String {
return "($target:$args)"
}
override fun toString(): String {
return toString(0)
}
companion object {
fun buildFunctionInvocationInstruction(ctx: TypeContext, func: FunctionInvocation, args: List<Instruction>): Instruction {
val funcDesc = func.target.typeInstance().functionDescriptor(ctx)!!
val funcInst = func.target.generateInstruction()
return invokeFunction(ctx, funcDesc, funcInst, args, func.lineCol)
}
fun invokeFunction(ctx: TypeContext, funcDesc: FunctionDescriptor, funcInst: Instruction, args: List<Instruction>, lineCol: LineCol):
Instruction {
return object : InstructionWithStackInfo(ctx.stackInfo(lineCol)) {
override suspend fun execute0(ctx: ActionContext, values: ValueHolder) {
if (funcInst is FunctionInstance) {
funcInst.ctxBuilder = { buildContext(ctx, it, values, funcDesc, args) }
funcInst.execute(ctx, values)
} else {
funcInst.execute(ctx, values)
val funcValue = values.refValue as Instruction
val newCtx = buildContext(ctx, ctx, values, funcDesc, args)
funcValue.execute(newCtx, values)
}
}
}
}
suspend fun buildContext(
callerCtx: ActionContext,
ctx: ActionContext,
values: ValueHolder,
funcDesc: FunctionDescriptor,
args: List<Instruction>
): ActionContext {
val newCtx = ActionContext(funcDesc.mem.memoryAllocator().getTotal(), ctx)
val newMem = newCtx.getCurrentMem()
for (i in args.indices) {
args[i].execute(callerCtx, values)
val param = funcDesc.params[i]
when (param.type) {
is IntType -> newMem.setInt(param.memIndex, values.intValue)
is LongType -> newMem.setLong(param.memIndex, values.longValue)
is FloatType -> newMem.setFloat(param.memIndex, values.floatValue)
is DoubleType -> newMem.setDouble(param.memIndex, values.doubleValue)
is BoolType -> newMem.setBool(param.memIndex, values.boolValue)
else -> newMem.setRef(param.memIndex, values.refValue)
}
}
return newCtx
}
}
}
| 4
| null |
35
| 43
|
f88bb5752596dfec1d02116df02b870c7fccf2dd
| 4,968
|
vjson
|
MIT License
|
next/kmp/browser/src/mobileMain/kotlin/org/dweb_browser/browser/desk/render/deskHelper.mobile.kt
|
BioforestChain
| 594,577,896
| false
|
{"Kotlin": 3364898, "TypeScript": 796189, "Swift": 368692, "Vue": 155144, "SCSS": 39016, "Objective-C": 17350, "HTML": 16888, "Shell": 13534, "JavaScript": 4687, "Svelte": 3504, "CSS": 818}
|
package org.dweb_browser.browser.desk.render
import androidx.compose.foundation.gestures.awaitDragOrCancellation
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.awaitTouchSlopOrCancellation
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
actual fun desktopGridLayout(): DesktopGridLayout =
DesktopGridLayout(
cells = GridCells.Adaptive(64.dp),
insets = WindowInsets(left = 28.dp, right = 28.dp),
horizontalSpace = 8.dp,
verticalSpace = 16.dp,
)
@Composable
actual fun Modifier.desktopAppItemActions(
onHoverStart: () -> Unit,
onHoverEnd: () -> Unit,
onDoubleTap: () -> Unit,
onOpenApp: () -> Unit,
onOpenAppMenu: () -> Unit,
) = this.composed {
val hoverStart by rememberUpdatedState(onHoverStart)
val hoverEnd by rememberUpdatedState(onHoverEnd)
val doubleTap by rememberUpdatedState(onDoubleTap)
val openApp by rememberUpdatedState(onOpenApp)
val openAppMenu by rememberUpdatedState(onOpenAppMenu)
pointerInput(Unit) {
detectTapGestures(
onPress = {
hoverStart()
},
onTap = {
hoverEnd()
openApp()
},
onLongPress = {
hoverEnd()
openAppMenu()
},
onDoubleTap = { doubleTap() },
)
}
.pointerInput(Unit) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
hoverStart()
val drag = awaitTouchSlopOrCancellation(down.id) { _, _ -> }
if (drag == null) {
hoverEnd()
} else {
awaitDragOrCancellation(drag.id)
hoverEnd()
}
}
}
}
| 62
|
Kotlin
|
4
| 13
|
57738069a4fbf3fc11ff64b527934698c32fecd9
| 2,115
|
dweb_browser
|
MIT License
|
DOCUMENT_STORE/src/main/kotlin/org/example/document_store/services/DocumentContentServiceImpl.kt
|
M4tT3d
| 874,249,564
| false
|
{"Kotlin": 354206, "TypeScript": 180680, "JavaScript": 3610, "Dockerfile": 2844, "CSS": 2078, "HTML": 302}
|
package org.example.document_store.services
import jakarta.persistence.EntityNotFoundException
import jakarta.transaction.Transactional
import org.example.document_store.dtos.CreateDocumentMetadataDTO
import org.example.document_store.dtos.DocumentContentDTO
import org.springframework.security.access.prepost.PreAuthorize
import org.example.document_store.dtos.toDto
import org.example.document_store.repositories.DocumentContentRepository
import org.example.document_store.repositories.DocumentMetadataRepository
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity
import org.springframework.stereotype.Service
@Service
@Transactional
@Configuration
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true)
class DocumentContentServiceImpl(
private val documentContentRepository: DocumentContentRepository,
private val documentMetadataRepository: DocumentMetadataRepository
) :
DocumentContentService {
override fun findById(id: Long): DocumentContentDTO {
if (!documentContentRepository.findById(id).isPresent) {
throw EntityNotFoundException("This id (${id}) does not exist")
}
return documentContentRepository.findById(id).map { it.toDto() }.get()
}
@PreAuthorize("authentication.principal.claims['roles'].contains('admin')||authentication.principal.claims['roles'].contains('operator')")
override fun update(createDocumentMetadataDTO: CreateDocumentMetadataDTO, id: Long): DocumentContentDTO {
val idContent = documentMetadataRepository.findById(id).get().documentContent.id
val newDocumentContent = documentContentRepository.findById(idContent).get()
newDocumentContent.content = createDocumentMetadataDTO.documentContentDTO.content
// val newDocumentContent = DocumentContent(createDocumentMetadataDTO.documentContentDTO.content)
// newDocumentContent.id = idContent
return documentContentRepository.save(newDocumentContent).toDto()
}
}
| 0
|
Kotlin
|
0
| 0
|
ccad8f0a41e77e03935e548b4f03969fc051a61f
| 2,083
|
wa2-project-job-placement
|
MIT License
|
yetutil/src/main/java/yet/ui/widget/listview/itemview/TextItemView.kt
|
yangentao
| 127,633,295
| false
| null |
package yet.ui.widget.listview.itemview
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.annotation.DrawableRes
import android.widget.TextView
import yet.theme.IconSize
import yet.theme.Space
import yet.ui.ext.*
import yet.ui.res.D
import yet.ui.res.sized
/**
* Created by <EMAIL> on 16/3/13.
*/
class TextItemView(context: Context) : TextView(context) {
init {
padding(Space.Normal, Space.Small, Space.Normal, Space.Small).gravityLeftCenter().textSizeA().textColorMajor()
}
fun icon(d: Drawable?) {
d?.sized(IconSize.Normal)
setCompoundDrawables(d, null, null, null)
}
fun icon(d: Drawable?, size: Int) {
d?.sized(size)
setCompoundDrawables(d, null, null, null)
}
fun icon(@DrawableRes resId: Int, size: Int) {
val d = D.sized(resId, size)
setCompoundDrawables(d, null, null, null)
}
fun icon(@DrawableRes resId: Int) {
val d = D.res(resId)
setCompoundDrawables(d, null, null, null)
}
}
| 0
|
Kotlin
|
0
| 1
|
c2e1330ab9cd2c57c069970628863d6a4778ed4d
| 971
|
ble
|
Apache License 2.0
|
app/src/main/java/com/sample/android/tmdb/ui/paging/main/movie/MoviesActivity.kt
|
Ali-Rezaei
| 158,464,119
| false
| null |
package com.sample.android.tmdb.ui.paging.main.movie
import com.sample.android.tmdb.R
import com.sample.android.tmdb.domain.Movie
import com.sample.android.tmdb.ui.feed.NavType
import com.sample.android.tmdb.ui.paging.main.MainActivity
abstract class MoviesActivity: MainActivity<Movie>() {
protected abstract val titleId: Int
override val screenTitle: String
get() = getString(titleId, getString(R.string.menu_movies))
override val navType: NavType?
get() = NavType.MOVIES
}
| 0
| null |
8
| 70
|
ea80dd0481f141e55e0d06073d50676758073d34
| 508
|
TMDb-Paging
|
The Unlicense
|
order-api/src/main/kotlin/org/heeheepresso/orderapi/orderHistory/menu/dto/request/OrderMenuHistoryCreateRequest.kt
|
HeeHeePresso
| 758,780,391
| false
|
{"Kotlin": 24643}
|
package org.heeheepresso.orderapi.orderHistory.menu.dto.request
import java.math.BigDecimal
data class OrderMenuHistoryCreateRequest(
val menuId: Long,
val price: BigDecimal,
val quantity: Int,
)
| 7
|
Kotlin
|
0
| 0
|
545f4409bb59b38825954208292f9a214ee430e9
| 210
|
Backend
|
Apache License 2.0
|
app/src/main/java/com/vitorpamplona/amethyst/ui/note/types/PrivateMessage.kt
|
retrnull
| 827,005,629
| false
| null |
/**
* Copyright (c) 2024 <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.vitorpamplona.amethyst.ui.note.types
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.vitorpamplona.amethyst.R
import com.vitorpamplona.amethyst.model.Note
import com.vitorpamplona.amethyst.ui.components.SensitivityWarning
import com.vitorpamplona.amethyst.ui.components.TranslatableRichTextViewer
import com.vitorpamplona.amethyst.ui.navigation.INav
import com.vitorpamplona.amethyst.ui.navigation.routeFor
import com.vitorpamplona.amethyst.ui.note.LoadDecryptedContent
import com.vitorpamplona.amethyst.ui.note.elements.DisplayUncitedHashtags
import com.vitorpamplona.amethyst.ui.screen.loggedIn.AccountViewModel
import com.vitorpamplona.amethyst.ui.screen.loggedIn.chatrooms.ChatroomHeader
import com.vitorpamplona.amethyst.ui.stringRes
import com.vitorpamplona.amethyst.ui.theme.StdVertSpacer
import com.vitorpamplona.amethyst.ui.theme.placeholderText
import com.vitorpamplona.amethyst.ui.theme.replyModifier
import com.vitorpamplona.quartz.encoders.toNpub
import com.vitorpamplona.quartz.events.ChatroomKeyable
import com.vitorpamplona.quartz.events.EmptyTagList
import com.vitorpamplona.quartz.events.PrivateDmEvent
import com.vitorpamplona.quartz.events.toImmutableListOfLists
@Composable
fun RenderPrivateMessage(
note: Note,
makeItShort: Boolean,
canPreview: Boolean,
quotesLeft: Int,
backgroundColor: MutableState<Color>,
accountViewModel: AccountViewModel,
nav: INav,
) {
val noteEvent = note.event as? PrivateDmEvent ?: return
val userRoom by
remember(note) {
derivedStateOf {
(note.event as? ChatroomKeyable)?.chatroomKey(accountViewModel.userProfile().pubkeyHex)
}
}
userRoom?.let {
if (it.users.size > 1 || (it.users.size == 1 && note.author == accountViewModel.account.userProfile())) {
ChatroomHeader(it, MaterialTheme.colorScheme.replyModifier.padding(10.dp), accountViewModel) {
routeFor(note, accountViewModel.userProfile())?.let {
nav.nav(it)
}
}
Spacer(modifier = StdVertSpacer)
}
}
val withMe = remember { noteEvent.with(accountViewModel.userProfile().pubkeyHex) }
if (withMe) {
LoadDecryptedContent(note, accountViewModel) { eventContent ->
val modifier = remember(note.event?.id()) { Modifier.fillMaxWidth() }
val isAuthorTheLoggedUser =
remember(note.event?.id()) { accountViewModel.isLoggedUser(note.author) }
val tags =
remember(note) { note.event?.tags()?.toImmutableListOfLists() ?: EmptyTagList }
if (makeItShort && isAuthorTheLoggedUser) {
Text(
text = eventContent,
color = MaterialTheme.colorScheme.placeholderText,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
} else {
val callbackUri = remember(note) { note.toNostrUri() }
SensitivityWarning(
note = note,
accountViewModel = accountViewModel,
) {
TranslatableRichTextViewer(
content = eventContent,
canPreview = canPreview && !makeItShort,
quotesLeft = quotesLeft,
modifier = modifier,
tags = tags,
backgroundColor = backgroundColor,
id = note.idHex,
callbackUri = callbackUri,
accountViewModel = accountViewModel,
nav = nav,
)
}
if (noteEvent.hasHashtags()) {
DisplayUncitedHashtags(noteEvent, eventContent, callbackUri, nav)
}
}
}
} else {
val recipient = noteEvent.recipientPubKeyBytes()?.toNpub() ?: "Someone"
TranslatableRichTextViewer(
stringRes(
id = R.string.private_conversation_notification,
"@${note.author?.pubkeyNpub()}",
"@$recipient",
),
canPreview = !makeItShort,
quotesLeft = 0,
modifier = Modifier.fillMaxWidth(),
tags = EmptyTagList,
backgroundColor = backgroundColor,
id = note.idHex,
callbackUri = note.toNostrUri(),
accountViewModel = accountViewModel,
nav = nav,
)
}
}
| 5
| null |
3
| 34
|
d33428614279300c503770c10a4305ca2a4d5ab6
| 6,290
|
garnet
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.