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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bot/connector-messenger/src/main/kotlin/model/send/AttachmentMessage.kt
|
theopenconversationkit
| 84,538,053
| false
| null |
/*
* Copyright (C) 2017/2021 e-voyageurs technologies
*
* 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.bot.connector.messenger.model.send
import ai.tock.bot.connector.ConnectorMessage
import ai.tock.bot.connector.messenger.model.send.AttachmentType.audio
import ai.tock.bot.connector.messenger.model.send.AttachmentType.file
import ai.tock.bot.connector.messenger.model.send.AttachmentType.image
import ai.tock.bot.connector.messenger.model.send.AttachmentType.template
import ai.tock.bot.connector.messenger.model.send.AttachmentType.video
import ai.tock.bot.engine.message.GenericMessage
/**
*
*/
class AttachmentMessage(val attachment: Attachment, quickReplies: List<QuickReply>? = null) :
Message(quickReplies?.run { if (isEmpty()) null else this }) {
override fun toGenericMessage(): GenericMessage? {
return when (attachment.type) {
audio, file, image, video -> GenericMessage(
this,
attachments = listOf(
ai.tock.bot.engine.message.Attachment(
(attachment.payload as UrlPayload).url ?: "",
attachment.type.toTockAttachmentType()
)
)
)
template -> attachment.payload.toGenericMessage()
}?.run {
if (quickReplies?.isNotEmpty() == true) {
copy(
choices = choices + quickReplies.mapNotNull { it.toChoice() },
locations = locations + quickReplies.mapNotNull { it.toLocation() }
)
} else {
this
}
}
}
override fun obfuscate(): ConnectorMessage {
return when (attachment.type) {
template -> AttachmentMessage(
attachment.copy(payload = attachment.payload.obfuscate()),
quickReplies
)
else -> this
}
}
override fun findElements(): List<Element> =
with(attachment.payload) {
when (this) {
is GenericPayload -> elements
is ListPayload -> elements
else -> emptyList()
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as AttachmentMessage
if (attachment != other.attachment) return false
if (quickReplies != other.quickReplies) return false
return true
}
override fun hashCode(): Int {
return attachment.hashCode()
}
override fun toString(): String {
return "AttachmentMessage(attachment=$attachment,quickReplies=$quickReplies)"
}
override fun copy(quickReplies: List<QuickReply>?): Message =
AttachmentMessage(attachment, quickReplies)
}
| 163
| null |
127
| 475
|
890f69960997ae9146747d082d808d92ee407fcb
| 3,376
|
tock
|
Apache License 2.0
|
app/src/main/java/com/celzero/bravedns/ui/OrbotBottomSheetFragment.kt
|
celzero
| 270,683,546
| false
| null |
/*
* Copyright 2020 RethinkDNS and its authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.celzero.bravedns.ui
import android.app.Dialog
import android.content.DialogInterface
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Bundle
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.widget.CompoundButton
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.text.HtmlCompat
import androidx.lifecycle.lifecycleScope
import com.celzero.bravedns.R
import com.celzero.bravedns.animation.Rotate3dAnimation
import com.celzero.bravedns.automaton.FirewallManager
import com.celzero.bravedns.data.AppConfig
import com.celzero.bravedns.databinding.BottomSheetOrbotBinding
import com.celzero.bravedns.databinding.DialogInfoRulesLayoutBinding
import com.celzero.bravedns.service.PersistentState
import com.celzero.bravedns.service.VpnController
import com.celzero.bravedns.util.OrbotHelper
import com.celzero.bravedns.util.Themes
import com.celzero.bravedns.util.Utilities
import com.celzero.bravedns.util.Utilities.Companion.isAtleastQ
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.android.ext.android.inject
/**
* One touch Orbot Integration.
* Bottom sheet dialog fragment shows UI that enables One touch
* Integration from the settings page.
*/
class OrbotBottomSheetFragment : BottomSheetDialogFragment() {
private var _binding: BottomSheetOrbotBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val b get() = _binding!!
private val persistentState by inject<PersistentState>()
private val appConfig by inject<AppConfig>()
private val orbotHelper by inject<OrbotHelper>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
_binding = BottomSheetOrbotBinding.inflate(inflater, container, false)
return b.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun getTheme(): Int = Themes.getBottomsheetCurrentTheme(isDarkThemeOn(),
persistentState.theme)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView()
setupClickListeners()
}
private fun isDarkThemeOn(): Boolean {
return resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
}
private fun initView() {
updateUi()
handleHttpUI()
}
private fun handleHttpUI() {
// http proxy is only supported on Android Q and above
if (!isAtleastQ()) {
b.bsOrbotHttpRl.visibility = View.GONE
b.bsOrbotBothRl.visibility = View.GONE
}
}
private fun setupClickListeners() {
b.bsOrbotApp.setOnClickListener {
orbotHelper.openOrbotApp()
}
b.bsOrbotRadioNone.setOnCheckedChangeListener(null)
b.bsOrbotRadioNone.setOnClickListener {
if (b.bsOrbotRadioNone.isChecked) {
handleOrbotStop()
}
}
b.bsOrbotNoneRl.setOnClickListener {
if (!b.bsOrbotRadioNone.isChecked) {
handleOrbotStop()
}
}
b.bsOrbotRadioSocks5.setOnCheckedChangeListener { _: CompoundButton, isSelected: Boolean ->
if (isSelected) {
persistentState.orbotConnectionStatus.postValue(true)
enableSocks5Orbot()
}
}
b.bsSocks5OrbotRl.setOnClickListener {
if (!b.bsOrbotRadioSocks5.isChecked) {
b.bsOrbotRadioSocks5.isChecked = true
persistentState.orbotConnectionStatus.postValue(true)
enableSocks5Orbot()
}
}
b.bsOrbotRadioHttp.setOnCheckedChangeListener { _: CompoundButton, isSelected: Boolean ->
if (isSelected) {
persistentState.orbotConnectionStatus.postValue(true)
enableHttpOrbot()
}
}
b.bsOrbotHttpRl.setOnClickListener {
if (!b.bsOrbotRadioHttp.isChecked) {
persistentState.orbotConnectionStatus.postValue(true)
b.bsOrbotRadioHttp.isChecked = true
enableHttpOrbot()
}
}
b.bsOrbotRadioBoth.setOnCheckedChangeListener { _: CompoundButton, isSelected: Boolean ->
if (isSelected) {
persistentState.orbotConnectionStatus.postValue(true)
enableSocks5HttpOrbot()
}
}
b.bsOrbotBothRl.setOnClickListener {
if (!b.bsOrbotRadioBoth.isChecked) {
persistentState.orbotConnectionStatus.postValue(true)
b.bsOrbotRadioBoth.isChecked = true
enableSocks5HttpOrbot()
}
}
b.orbotInfoIcon.setOnClickListener {
showDialogForInfo()
}
//Livedata value which will have the data whether the Orbot connection is initiated
//If initiated, show loading animation.
//else - allow user to select Orbot options
persistentState.orbotConnectionStatus.observe(viewLifecycleOwner, {
if (it) {
b.orbotIcon.setImageResource(R.drawable.orbot_disabled)
enableLoading()
} else {
disableLoading()
updateUi()
}
})
}
private fun handleOrbotStop() {
stopOrbot()
showStopOrbotDialog()
}
private fun updateUi() {
when (OrbotHelper.selectedProxyType) {
AppConfig.ProxyType.SOCKS5.name -> {
b.bsOrbotRadioSocks5.isChecked = true
b.orbotIcon.setImageResource(R.drawable.orbot_enabled)
b.orbotStatus.text = getString(R.string.orbot_bs_status_1)
}
AppConfig.ProxyType.HTTP.name -> {
b.bsOrbotRadioHttp.isChecked = true
b.orbotIcon.setImageResource(R.drawable.orbot_enabled)
b.orbotStatus.text = getString(R.string.orbot_bs_status_2)
}
AppConfig.ProxyType.HTTP_SOCKS5.name -> {
b.bsOrbotRadioBoth.isChecked = true
b.orbotIcon.setImageResource(R.drawable.orbot_enabled)
b.orbotStatus.text = getString(R.string.orbot_bs_status_3)
}
AppConfig.ProxyType.NONE.name -> {
updateOrbotNone()
}
else -> {
updateOrbotNone()
}
}
}
private fun updateOrbotNone() {
b.bsOrbotRadioNone.isChecked = true
b.bsOrbotRadioSocks5.isChecked = false
b.bsOrbotRadioHttp.isChecked = false
b.bsOrbotRadioBoth.isChecked = false
b.orbotIcon.setImageResource(R.drawable.orbot_disabled)
b.orbotStatus.text = getString(R.string.orbot_bs_status_4)
}
/**
* Disables the UI from selecting any other mode until the Orbot connection status is
* obtained/time out for the Orbot.
*/
private fun enableLoading() {
b.bsSocks5OrbotRl.isClickable = false
b.bsOrbotBothRl.isClickable = false
b.bsOrbotHttpRl.isClickable = false
b.bsOrbotNoneRl.isClickable = false
b.bsOrbotRadioGroup.isClickable = false
b.bsOrbotRadioSocks5.isClickable = false
b.bsOrbotRadioHttp.isClickable = false
b.bsOrbotRadioBoth.isClickable = false
b.bsOrbotRadioNone.isClickable = false
b.orbotStatus.text = getString(R.string.orbot_bs_status_trying_connect)
animateOrbotIcon()
}
/**
* Circular animation for the Orbot Icon.
*/
private fun animateOrbotIcon() {
// In some cases, the width of orbotIcon is 0 - For both width and measuredWidth.
// Convert the width(40dp) to pixel and add to animation parameter in case of 0
var width = b.orbotIcon.measuredWidth
if (width == 0) {
width = getCalculatedWidth()
}
val rotation = Rotate3dAnimation(0.0f, 360.0f * 4f, width / 2f, width / 2f, 20f, true)
rotation.fillAfter = true
rotation.interpolator = AccelerateInterpolator()
rotation.duration = 2.toLong() * 1000
rotation.repeatCount = Animation.INFINITE
b.orbotIcon.startAnimation(rotation)
}
// ref: https://stackoverflow.com/questions/4605527/converting-pixels-to-dp
// Calculate the width of the icon manually.
// Invoke this method when the width of the Orbot icon is returned as 0 by viewBinder.
private fun getCalculatedWidth(): Int {
val dip = 40f
val r: Resources = resources
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, r.displayMetrics).toInt()
}
private fun disableLoading() {
b.bsSocks5OrbotRl.isClickable = true
b.bsOrbotBothRl.isClickable = true
b.bsOrbotHttpRl.isClickable = true
b.bsOrbotNoneRl.isClickable = true
b.bsOrbotRadioGroup.isClickable = true
b.bsOrbotRadioSocks5.isClickable = true
b.bsOrbotRadioHttp.isClickable = true
b.bsOrbotRadioBoth.isClickable = true
b.bsOrbotRadioNone.isClickable = true
b.orbotIcon.clearAnimation()
}
/**
* Stop the Orbot - Calls the Orbot helper to initiate the stop orbot call.
*/
private fun stopOrbot() {
appConfig.removeAllProxies()
b.bsOrbotRadioSocks5.isChecked = false
b.bsOrbotRadioHttp.isChecked = false
b.bsOrbotRadioBoth.isChecked = false
b.bsOrbotRadioNone.isChecked = true
b.orbotIcon.setImageResource(R.drawable.orbot_disabled)
orbotHelper.stopOrbot(isInteractive = true)
}
/**
* Enable - Orbot with SOCKS5 mode
*/
private fun enableSocks5Orbot() {
b.bsOrbotRadioNone.isChecked = false
b.bsOrbotRadioHttp.isChecked = false
b.bsOrbotRadioBoth.isChecked = false
startOrbot(AppConfig.ProxyType.SOCKS5.name)
}
/**
* Enable - Orbot with HTTP mode
*/
private fun enableHttpOrbot() {
b.bsOrbotRadioNone.isChecked = false
b.bsOrbotRadioSocks5.isChecked = false
b.bsOrbotRadioBoth.isChecked = false
startOrbot(AppConfig.ProxyType.HTTP.name)
}
/**
* Enable - Orbot with SOCKS5 + HTTP mode
*/
private fun enableSocks5HttpOrbot() {
b.bsOrbotRadioNone.isChecked = false
b.bsOrbotRadioSocks5.isChecked = false
b.bsOrbotRadioHttp.isChecked = false
startOrbot(AppConfig.ProxyType.HTTP_SOCKS5.name)
}
/**
* Start the Orbot(OrbotHelper) - Intent action.
*/
private fun startOrbot(type: String) {
if (!FirewallManager.isOrbotInstalled()) {
return
}
if (VpnController.hasTunnel()) {
go {
uiCtx {
orbotHelper.startOrbot(type)
}
}
} else {
Utilities.showToastUiCentered(requireContext(),
getString(R.string.settings_socks5_vpn_disabled_error),
Toast.LENGTH_LONG)
}
}
private fun showStopOrbotDialog() {
val builder = AlertDialog.Builder(requireContext())
builder.setTitle(getString(R.string.orbot_stop_dialog_title))
builder.setMessage(getString(R.string.orbot_stop_dialog_message))
builder.setCancelable(true)
builder.setPositiveButton(
getString(R.string.orbot_stop_dialog_positive)) { dialogInterface, _ ->
dialogInterface.dismiss()
}
builder.setNegativeButton(getString(
R.string.orbot_stop_dialog_negative)) { dialogInterface: DialogInterface, _: Int ->
dialogInterface.dismiss()
orbotHelper.openOrbotApp()
}
builder.create().show()
}
private fun showDialogForInfo() {
val dialogBinding = DialogInfoRulesLayoutBinding.inflate(layoutInflater)
val dialog = Dialog(requireContext())
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setCanceledOnTouchOutside(true)
dialog.setContentView(dialogBinding.root)
val okBtn = dialogBinding.infoRulesDialogCancelImg
val descText = dialogBinding.infoRulesDialogRulesDesc
val titleText = dialogBinding.infoRulesDialogRulesTitle
var text = getString(R.string.orbot_explanation)
text = text.replace("\n", "<br /><br />")
val styledText = HtmlCompat.fromHtml(text, HtmlCompat.FROM_HTML_MODE_LEGACY)
descText.text = styledText
titleText.text = getString(R.string.orbot_title)
titleText.setCompoundDrawablesRelative(null, null, null, null)
okBtn.setOnClickListener {
dialog.dismiss()
}
dialog.show()
}
private fun go(f: suspend () -> Unit) {
lifecycleScope.launch {
f()
}
}
private suspend fun ioCtx(f: suspend () -> Unit) {
withContext(Dispatchers.IO) {
f()
}
}
private suspend fun uiCtx(f: suspend () -> Unit) {
withContext(Dispatchers.Main) {
f()
}
}
}
| 361
| null |
92
| 557
|
161674b1cdbdd72fefee5edd953179a637e00f6f
| 14,504
|
rethink-app
|
Apache License 2.0
|
osm/addr-osmify-kotlin/src/main/kotlin/Urlopener.kt
|
vmiklos
| 2,824,455
| false
| null |
/*
* Copyright 2020 <NAME>
*
* SPDX-License-Identifier: MIT
*/
package hu.vmiklos.addr_osmify
/**
* urlopen() interface, to be implemented using HTTP or mocking.
*/
interface Urlopener {
fun urlopen(urlString: String, data: String): String
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| 1
| null |
1
| 6
|
b83fd1eb10061d5eb2fc0c9a70748691c34e8890
| 306
|
vmexam
|
MIT License
|
src/main/kotlin/dev/supergrecko/vexe/llvm/target/Target.kt
|
arkencl
| 275,663,397
| true
|
{"Kotlin": 372536, "Makefile": 227}
|
package dev.supergrecko.vexe.llvm.target
import dev.supergrecko.vexe.llvm.internal.contracts.ContainsReference
import dev.supergrecko.vexe.llvm.internal.util.fromLLVMBool
import dev.supergrecko.vexe.llvm.internal.util.wrap
import org.bytedeco.javacpp.BytePointer
import org.bytedeco.llvm.LLVM.LLVMTargetRef
import org.bytedeco.llvm.global.LLVM
public class Target internal constructor() :
ContainsReference<LLVMTargetRef> {
public override lateinit var ref: LLVMTargetRef
internal set
public constructor(llvmRef: LLVMTargetRef) : this() {
ref = llvmRef
}
//region Target
/**
* Get the next [Target] in the iterator
*
* @see LLVM.LLVMGetNextTarget
*/
public fun getNextTarget(): Target? {
val next = LLVM.LLVMGetNextTarget(ref)
return wrap(next) { Target(it) }
}
/**
* Get this target's name
*
* @see LLVM.LLVMGetTargetName
*/
public fun getName(): String {
return LLVM.LLVMGetTargetName(ref).string
}
/**
* Get this target's description
*
* @see LLVM.LLVMGetTargetDescription
*/
public fun getDescription(): String {
return LLVM.LLVMGetTargetDescription(ref).string
}
/**
* Does this target have a target machine?
*
* @see LLVM.LLVMTargetHasTargetMachine
*/
public fun hasTargetMachine(): Boolean {
return LLVM.LLVMTargetHasTargetMachine(ref).fromLLVMBool()
}
/**
* Does this target have JIT support?
*
* @see LLVM.LLVMTargetHasJIT
*/
public fun hasJIT(): Boolean {
return LLVM.LLVMTargetHasJIT(ref).fromLLVMBool()
}
/**
* Does this target have an asm backend?
*
* @see LLVM.LLVMTargetHasAsmBackend
*/
public fun hasAsmBackend(): Boolean {
return LLVM.LLVMTargetHasAsmBackend(ref).fromLLVMBool()
}
/**
* Companion object for constructing targets which may fail upon
* construction. We use this over secondary constructors solely because
* they may fail.
*
* These constructors also have clashing overloads which would make
* constructor overloading obsolete
*/
public companion object {
/**
* Create a target from a name if it exists
*
* @see LLVM.LLVMGetTargetFromName
*/
public fun createFromName(name: String): Target {
val target = LLVM.LLVMGetTargetFromName(name)
return if (target != null) {
Target(target)
} else {
throw IllegalArgumentException(
"The specified target could " +
"not be found"
)
}
}
/**
* Create a target from a target triple
*
* @see LLVM.LLVMGetTargetFromTriple
*/
public fun createFromTriple(triple: String): Target {
val out = LLVMTargetRef()
val err = BytePointer(0L)
val t = BytePointer(triple)
val result = LLVM.LLVMGetTargetFromTriple(t, out, err)
return if (result == 0) {
Target(out)
} else {
throw RuntimeException(err.string)
}
}
}
//endregion Target
}
| 0
|
Kotlin
|
0
| 0
|
673522b620db4c8a619db5ccc5dfe62197b12f11
| 3,318
|
llvm4kt
|
Apache License 2.0
|
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/main/LangHolder.kt
|
na-ji
| 59,505,096
| true
|
{"Kotlin": 1164869, "Java": 139835, "Shell": 1127}
|
package eu.kanade.tachiyomi.ui.catalogue.main
import android.view.View
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.viewholders.FlexibleViewHolder
import eu.kanade.tachiyomi.R
import kotlinx.android.synthetic.main.catalogue_main_controller_card.view.*
import java.util.*
class LangHolder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter, true) {
fun bind(item: LangItem) {
itemView.title.text = when {
item.code == "" -> itemView.context.getString(R.string.other_source)
else -> {
val locale = Locale(item.code)
locale.getDisplayName(locale).capitalize()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5fc8580874975857e7f3887f4c193e2b415d30d2
| 707
|
tachiyomi
|
Apache License 2.0
|
app/src/main/java/com/bigboluo/kaptapplication/DogMeal.kt
|
pahoehoe
| 320,225,630
| false
|
{"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 1, "Kotlin": 25, "INI": 3, "Proguard": 4, "XML": 18, "Java": 1}
|
package com.bigboluo.kaptapplication
import com.bigboluo.annotation.Factory
import com.bigboluo.annotation.Meal
@Factory(
id = "DogMeal",
value = DogMeal::class
)
class DogMeal : Meal {
override fun eat() {
println("eat dog meal!")
}
}
| 0
|
Kotlin
|
0
| 1
|
23828431d6974a14010b9be5fdf9d204b638e3e3
| 261
|
kotlin_kapt_demo
|
MIT License
|
components/crypto/crypto-softhsm-impl/src/test/kotlin/net/corda/crypto/softhsm/impl/HSMRepositoryImplTest.kt
|
corda
| 346,070,752
| false
|
{"Kotlin": 18133184, "Java": 317933, "Smarty": 88013, "Shell": 47197, "Groovy": 28415, "TypeScript": 5826, "PowerShell": 4985, "Solidity": 2024}
|
package net.corda.crypto.softhsm.impl
import net.corda.crypto.cipher.suite.CRYPTO_TENANT_ID
import net.corda.crypto.core.CryptoTenants
import java.time.Instant
import javax.persistence.EntityManager
import net.corda.crypto.persistence.db.model.HSMAssociationEntity
import net.corda.crypto.persistence.db.model.HSMCategoryAssociationEntity
import net.corda.data.crypto.wire.hsm.HSMAssociationInfo
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.eq
import java.util.Collections.emptyList
class HSMRepositoryImplTest {
@Test
fun `findTenantAssociation returns null when there are no results`() {
val tenantCap = argumentCaptor<String>()
val categoryCap = argumentCaptor<String>()
val em = org.mockito.kotlin.mock<EntityManager> {
on { createQuery(any(), eq(HSMCategoryAssociationEntity::class.java)) } doAnswer {
org.mockito.kotlin.mock {
on { setParameter(eq("tenantId"), tenantCap.capture()) } doReturn it
on { setParameter(eq("category"), categoryCap.capture()) } doReturn it
on { resultList } doReturn emptyList()
}
}
}
HSMRepositoryImpl(
org.mockito.kotlin.mock {
on { createEntityManager() } doReturn em
},
CRYPTO_TENANT_ID
).use { hsmRepository ->
val test = hsmRepository.findTenantAssociation("tenant", "category")
assertThat(test).isNull()
assertThat(tenantCap.allValues.single()).isEqualTo("tenant")
assertThat(categoryCap.allValues.single()).isEqualTo("category")
}
}
@Test
fun `findTenantAssociation returns first value when there are results`() {
val hsmAssociation1 = HSMAssociationEntity("2", "tenant", "hsm", Instant.ofEpochMilli(0), "master_key")
val hsmCategoryAssociation1 = HSMCategoryAssociationEntity("1", "tenant", "category", hsmAssociation1, Instant.ofEpochMilli(0), 0)
val hsmAssociation2 = HSMAssociationEntity("2", "tenant", "hsm", Instant.ofEpochMilli(0), "master_key")
val hsmCategoryAssociation2 = HSMCategoryAssociationEntity("2", "tenant", "category", hsmAssociation2, Instant.ofEpochMilli(0), 0)
val tenantCap = argumentCaptor<String>()
val categoryCap = argumentCaptor<String>()
val em = org.mockito.kotlin.mock<EntityManager> {
on { createQuery(any(), eq(HSMCategoryAssociationEntity::class.java)) } doAnswer {
org.mockito.kotlin.mock {
on { setParameter(eq("tenantId"), tenantCap.capture()) } doReturn it
on { setParameter(eq("category"), categoryCap.capture()) } doReturn it
on { resultList } doReturn listOf(hsmCategoryAssociation1, hsmCategoryAssociation2)
}
}
}
HSMRepositoryImpl(
org.mockito.kotlin.mock {
on { createEntityManager() } doReturn em
},
CryptoTenants.CRYPTO
).use { hsmStore ->
val expected = HSMAssociationInfo("1", "tenant", "hsm", "category", "master_key", 0)
val test = hsmStore.findTenantAssociation("tenant", "category")
assertThat(test).usingRecursiveComparison().isEqualTo(expected)
assertThat(tenantCap.allValues.single()).isEqualTo("tenant")
assertThat(categoryCap.allValues.single()).isEqualTo("category")
}
}
@Test
fun getHSMUsage() {
}
@Test
fun associate() {
}
}
| 128
|
Kotlin
|
16
| 42
|
438bf3771a593c56f4f2583572c9b3063f784af4
| 3,774
|
corda-runtime-os
|
Apache License 2.0
|
app/src/main/java/com/byd/firstcode/kotlin/eight/ServiceActivity.kt
|
liufangqq
| 436,594,629
| false
| null |
package com.byd.firstcode.kotlin.eight
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import com.byd.firstcode.kotlin.MainActivity
import com.byd.firstcode.kotlin.R
import kotlinx.android.synthetic.main.activity_service.*
class ServiceActivity : AppCompatActivity() {
lateinit var downloadBinder: MyService.DownloadBinder
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
downloadBinder = service as MyService.DownloadBinder
downloadBinder.startDownload()
downloadBinder.getProgress()
}
override fun onServiceDisconnected(name: ComponentName?) {
}
}
//fun main(){
// val result1 = getGenericType<String>()
// val result2 = getGenericType<Int>()
// println("result1 is $result1")
// println("result2 is $result2")
//}
// fun main() {
// val student = Student("Tom", 19)
// val data = SimpleData<Student>(student)
// handleSimpleData(data)
// val studentData = data.get()
// }
fun main() {
val trans = object : Transformer<Person> {
override fun transform(name: String, age: Int): Person {
return Teacher(name, age)
}
}
handleTransformer(trans)
}
fun handleTransformer(trans: Transformer<Student>) {
// val student = Student("Tom",19)
val result = trans.transform("Tom", 19)
}
fun handleSimpleData(data: SimpleData<Person>) {
val personData = data.get()
Log.d("test10", personData.toString());
val teacher = Teacher("Jack", 35)
// data.set(teacher)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_service)
main()
// startActivity<MainActivity>(this)
// startActivity<MusicActivity>(this) {
// putExtra("p1", "1")
// putExtra("p2", "2")
// }
startIntentServiceBtn.setOnClickListener {
val intent = Intent(this, MyIntentService::class.java)
startService(intent)
}
startServiceBtn.setOnClickListener {
val intent = Intent(this, MyService::class.java)
startService(intent)
}
stopServiceBtn.setOnClickListener {
val intent = Intent(this, MyService::class.java)
stopService(intent)
}
bindServiceBtn.setOnClickListener {
val intent = Intent(this, MyService::class.java)
bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
unbindServiceBtn.setOnClickListener {
unbindService(connection)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fcb8f6450a07e4598bf034dbfaaaa47037586107
| 3,004
|
TestBYD
|
Apache License 2.0
|
codegen-client/src/test/kotlin/software/amazon/smithy/rust/codegen/client/smithy/protocols/eventstream/ClientEventStreamUnmarshallerGeneratorTest.kt
|
smithy-lang
| 308,027,791
| false
| null |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.rust.codegen.client.smithy.protocols.eventstream
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ArgumentsSource
import software.amazon.smithy.rust.codegen.client.testutil.clientIntegrationTest
import software.amazon.smithy.rust.codegen.core.rustlang.rust
import software.amazon.smithy.rust.codegen.core.testutil.EventStreamTestModels
import software.amazon.smithy.rust.codegen.core.testutil.EventStreamUnmarshallTestCases.writeUnmarshallTestCases
import software.amazon.smithy.rust.codegen.core.testutil.IntegrationTestParams
import software.amazon.smithy.rust.codegen.core.testutil.testModule
import software.amazon.smithy.rust.codegen.core.testutil.unitTest
class ClientEventStreamUnmarshallerGeneratorTest {
@ParameterizedTest
@ArgumentsSource(TestCasesProvider::class)
fun test(testCase: EventStreamTestModels.TestCase) {
clientIntegrationTest(
testCase.model,
IntegrationTestParams(service = "test#TestService", addModuleToEventStreamAllowList = true),
) { codegenContext, rustCrate ->
val generator = "crate::event_stream_serde::TestStreamUnmarshaller"
rustCrate.testModule {
rust("##![allow(unused_imports, dead_code)]")
writeUnmarshallTestCases(codegenContext, testCase, optionalBuilderInputs = false)
unitTest(
"unknown_message",
"""
let message = msg("event", "NewUnmodeledMessageType", "application/octet-stream", b"hello, world!");
let result = $generator::new().unmarshall(&message);
assert!(result.is_ok(), "expected ok, got: {:?}", result);
assert!(expect_event(result.unwrap()).is_unknown());
""",
)
unitTest(
"generic_error",
"""
let message = msg(
"exception",
"UnmodeledError",
"${testCase.responseContentType}",
br#"${testCase.validUnmodeledError}"#
);
let result = $generator::new().unmarshall(&message);
assert!(result.is_ok(), "expected ok, got: {:?}", result);
match expect_error(result.unwrap()) {
TestStreamError::Unhandled(err) => {
let message = format!("{}", crate::error::DisplayErrorContext(&err));
let expected = "message: \"unmodeled error\"";
assert!(message.contains(expected), "Expected '{message}' to contain '{expected}'");
}
kind => panic!("expected generic error, but got {:?}", kind),
}
""",
)
}
}
}
}
| 346
| null |
188
| 504
|
8d8e7ab7aa6c3b388ffb2365a29ab03f87c24507
| 3,108
|
smithy-rs
|
Apache License 2.0
|
buildSrc/src/main/kotlin/kotlinx/html/generate/main.kt
|
kowasm
| 586,987,800
| false
| null |
package kotlinx.html.generate
import java.io.*
fun generate(packg: String, todir: String, jsdir: String) {
fillRepository()
fillKdocRepositoryExtension()
File(todir).mkdirs()
File(jsdir).mkdirs()
FileOutputStream("$todir/gen-attr-traits.kt").writer().use {
it.with {
packg(packg)
emptyLine()
import("kotlinx.html.*")
import("kotlinx.html.impl.*")
emptyLine()
doNotEditWarning()
emptyLine()
emptyLine()
Repository.attributeFacades.values.forEach {
facade(it)
emptyLine()
}
}
}
Repository.tags.values.filterIgnored().groupBy { it.name[0] }.entries.forEach { e ->
FileOutputStream("$todir/gen-tags-${e.key}.kt").writer(Charsets.UTF_8).use {
it.with {
packg(packg)
emptyLine()
import("kotlinx.html.*")
import("kotlinx.html.impl.*")
import("kotlinx.html.attributes.*")
emptyLine()
doNotEditWarning()
emptyLine()
emptyLine()
e.value.forEach {
tagClass(it, emptySet())
}
}
}
}
FileOutputStream("$todir/gen-consumer-tags.kt").writer(Charsets.UTF_8).use {
it.with {
packg(packg)
emptyLine()
import("kotlinx.html.*")
import("kotlinx.html.impl.*")
import("kotlinx.html.attributes.*")
emptyLine()
doNotEditWarning()
emptyLine()
emptyLine()
Repository.tags.values.filterIgnored().forEach {
val contentlessTag = it.name.lowercase() in contentlessTags
if (it.possibleChildren.isEmpty() && it.name.lowercase() !in emptyTags && !contentlessTag) {
consumerBuilderShared(it, false)
} else if (contentlessTag) {
deprecated("This tag doesn't support content or requires unsafe (try unsafe {})")
suppress("DEPRECATION")
consumerBuilderShared(it, false)
}
consumerBuilderShared(it, true)
emptyLine()
}
}
}
FileOutputStream("$jsdir/gen-consumer-tags-js.kt").writer(Charsets.UTF_8).use {
it.with {
packg(packg + ".js")
emptyLine()
import("kotlinx.html.*")
import("kotlinx.html.impl.*")
import("kotlinx.html.attributes.*")
import("org.w3c.dom.*")
emptyLine()
doNotEditWarning()
emptyLine()
emptyLine()
Repository.tags.values.filterIgnored().forEach {
val contentlessTag = it.name.lowercase() in contentlessTags
if (it.possibleChildren.isEmpty() && it.name.lowercase() !in emptyTags && !contentlessTag) {
consumerBuilderJS(it, false)
} else if (contentlessTag) {
deprecated("This tag doesn't support content or requires unsafe (try unsafe {})")
suppress("DEPRECATION")
consumerBuilderJS(it, false)
}
consumerBuilderJS(it, true)
emptyLine()
}
}
}
FileOutputStream("$jsdir/gen-event-attrs-js.kt").writer(Charsets.UTF_8).use {
it.with {
packg(packg + ".js")
emptyLine()
import("kotlinx.html.*")
import("kotlinx.html.org.w3c.dom.events.Event")
emptyLine()
doNotEditWarning()
emptyLine()
emptyLine()
Repository.attributeFacades.filter { it.value.attributeNames.any { it.startsWith("on") } }.forEach { facade ->
facade.value.attributes.filter { it.name.startsWith("on") }.forEach {
eventProperty(facade.value.name.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() } + "Facade",
it)
}
}
}
}
FileOutputStream("$todir/gen-enums.kt").writer(Charsets.UTF_8).use {
it.with {
packg(packg)
emptyLine()
import("kotlinx.html.*")
emptyLine()
doNotEditWarning()
emptyLine()
emptyLine()
fun genEnumAttribute(attribute: AttributeInfo) {
if (!isEnumExcluded(attribute.enumTypeName)) {
if (attribute.type == AttributeType.ENUM) {
enum(attribute)
} else {
enumObject(attribute)
}
}
}
Repository.attributeFacades.values.forEach { facade ->
facade.attributes.filter { it.enumValues.isNotEmpty() }.filter { !isAttributeExcluded(it.name) }.forEach { attribute ->
genEnumAttribute(attribute)
}
}
Repository.tags.values.filterIgnored().forEach { tag ->
tag.attributes.filter { it.enumValues.isNotEmpty() }.filter { !isAttributeExcluded(it.name) }.forEach { attribute ->
genEnumAttribute(attribute)
}
}
}
}
FileOutputStream("$todir/gen-attributes.kt").writer(Charsets.UTF_8).use {
it.with {
packg(packg)
emptyLine()
import("kotlinx.html.*")
import("kotlinx.html.attributes.*")
emptyLine()
doNotEditWarning()
emptyLine()
emptyLine()
Repository.attributeDelegateRequests.toList().forEach {
attributePseudoDelegate(it)
}
}
}
FileOutputStream("$todir/gen-tag-unions.kt").writer(Charsets.UTF_8).use {
with(it) {
packg(packg)
emptyLine()
import("kotlinx.html.*")
import("kotlinx.html.impl.*")
import("kotlinx.html.attributes.*")
emptyLine()
doNotEditWarning()
emptyLine()
emptyLine()
Repository.groupUnions.values.forEach { union ->
clazz(Clazz(
name = union.name,
isInterface = true,
parents = union.superGroups + "Tag"
)) {}
emptyLine()
}
emptyLine()
emptyLine()
Repository.groupUnions.values.forEach { union ->
(union.additionalTags + union.ambiguityTags).mapNotNull { Repository.tags[it] }.filterIgnored().forEach { tag ->
htmlTagBuilders(union.name, tag)
}
emptyLine()
}
}
}
FileOutputStream("$todir/gen-tag-groups.kt").writer(Charsets.UTF_8).use {
with(it) {
packg(packg)
emptyLine()
import("kotlinx.html.*")
import("kotlinx.html.impl.*")
import("kotlinx.html.attributes.*")
emptyLine()
doNotEditWarning()
emptyLine()
emptyLine()
Repository.tagGroups.values.forEach { group ->
val unions = Repository.unionsByGroups[group.name].orEmpty().map { it.name }
clazz(Clazz(name = group.typeName, parents = unions + "Tag", isPublic = true, isInterface = true)) {
}
emptyLine()
}
Repository.tagGroups.values.forEach { group ->
val receiver = group.typeName
val unions = Repository.unionsByGroups[group.name].orEmpty()
group.tags.mapNotNull { Repository.tags[it] }.filterIgnored().filter { tag -> unions.count { tag.name in it.intersectionTags } == 0 }.forEach {
htmlTagBuilders(receiver, it)
}
}
}
}
FileOutputStream("$todir/gen-entities.kt").writer(Charsets.UTF_8).use {
it.with {
packg(packg)
emptyLine()
import("kotlinx.html.*")
emptyLine()
doNotEditWarning()
emptyLine()
emptyLine()
append("enum ")
clazz(Clazz(name = "Entities")) {
InputStreamReader("entities.txt".asResourceUrl().openStream()).useLines { lines ->
lines.filter { it.isNotEmpty() }.forEachIndexed { idx, ent ->
if (idx > 0) {
append(",")
}
indent()
append(ent)
emptyLine()
}
}
append(";")
appendLine()
variable(Var(name = "text", type = "String"))
appendLine()
getter()
defineIs(StringBuilder().apply {
append("&".quote())
append(" + ")
receiverDot("this")
functionCall("toString", emptyList())
append(" + ")
append(";".quote())
})
appendLine()
}
}
}
generateParentInterfaces(todir, packg)
}
| 95
| null |
5
| 315
|
a45430d559057f5a3e10ee88d26eba07103bf69d
| 9,519
|
kowasm
|
Apache License 2.0
|
kotest-assertions-shared/src/commonMain/kotlin/io/kotest/inspectors/Inspectors.kt
|
audkar
| 292,639,473
| false
| null |
package io.kotest.inspectors
fun <T> Sequence<T>.forAll(fn: (T) -> Unit) = toList().forAll(fn)
fun <T> Array<T>.forAll(fn: (T) -> Unit) = asList().forAll(fn)
fun <T> Collection<T>.forAll(fn: (T) -> Unit) {
val results = runTests(this, fn)
val passed = results.filterIsInstance<ElementPass<T>>()
if (passed.size < this.size) {
val msg = "${passed.size} elements passed but expected ${this.size}"
buildAssertionError(msg, results)
}
}
fun <T> Sequence<T>.forOne(fn: (T) -> Unit) = toList().forOne(fn)
fun <T> Array<T>.forOne(fn: (T) -> Unit) = asList().forOne(fn)
fun <T> Collection<T>.forOne(fn: (T) -> Unit) = forExactly(1, fn)
fun <T> Sequence<T>.forExactly(k: Int, fn: (T) -> Unit) = toList().forExactly(k, fn)
fun <T> Array<T>.forExactly(k: Int, fn: (T) -> Unit) = toList().forExactly(k, fn)
fun <T> Collection<T>.forExactly(k: Int, fn: (T) -> Unit) {
val results = runTests(this, fn)
val passed = results.filterIsInstance<ElementPass<T>>()
if (passed.size != k) {
val msg = "${passed.size} elements passed but expected $k"
buildAssertionError(msg, results)
}
}
fun <T> Sequence<T>.forSome(fn: (T) -> Unit) = toList().forSome(fn)
fun <T> Array<T>.forSome(fn: (T) -> Unit) = toList().forSome(fn)
fun <T> Collection<T>.forSome(fn: (T) -> Unit) {
val results = runTests(this, fn)
val passed = results.filterIsInstance<ElementPass<T>>()
if (passed.isEmpty()) {
buildAssertionError("No elements passed but expected at least one", results)
} else if (passed.size == size) {
buildAssertionError("All elements passed but expected < $size", results)
}
}
fun <T> Sequence<T>.forAny(fn: (T) -> Unit) = toList().forAny(fn)
fun <T> Array<T>.forAny(fn: (T) -> Unit) = toList().forAny(fn)
fun <T> Collection<T>.forAny(fn: (T) -> Unit) = forAtLeastOne(fn)
fun <T> Sequence<T>.forAtLeastOne(fn: (T) -> Unit) = toList().forAtLeastOne(fn)
fun <T> Array<T>.forAtLeastOne(fn: (T) -> Unit) = toList().forAtLeastOne(fn)
fun <T> Collection<T>.forAtLeastOne(f: (T) -> Unit) = forAtLeast(1, f)
fun <T> Sequence<T>.forAtLeast(k: Int, fn: (T) -> Unit) = toList().forAtLeast(k, fn)
fun <T> Array<T>.forAtLeast(k: Int, fn: (T) -> Unit) = toList().forAtLeast(k, fn)
fun <T> Collection<T>.forAtLeast(k: Int, fn: (T) -> Unit) {
val results = runTests(this, fn)
val passed = results.filterIsInstance<ElementPass<T>>()
if (passed.size < k) {
val msg = "${passed.size} elements passed but expected at least $k"
buildAssertionError(msg, results)
}
}
fun <T> Sequence<T>.forAtMostOne(fn: (T) -> Unit) = toList().forAtMostOne(fn)
fun <T> Array<T>.forAtMostOne(fn: (T) -> Unit) = toList().forAtMostOne(fn)
fun <T> Collection<T>.forAtMostOne(fn: (T) -> Unit) = forAtMost(1, fn)
fun <T> Sequence<T>.forAtMost(k: Int, fn: (T) -> Unit) = toList().forAtMost(k, fn)
fun <T> Array<T>.forAtMost(k: Int, fn: (T) -> Unit) = toList().forAtMost(k, fn)
fun <T> Collection<T>.forAtMost(k: Int, fn: (T) -> Unit) {
val results = runTests(this, fn)
val passed = results.filterIsInstance<ElementPass<T>>()
if (passed.size > k) {
val msg = "${passed.size} elements passed but expected at most $k"
buildAssertionError(msg, results)
}
}
fun <T> Sequence<T>.forNone(fn: (T) -> Unit) = toList().forNone(fn)
fun <T> Array<T>.forNone(fn: (T) -> Unit) = toList().forNone(fn)
fun <T> Collection<T>.forNone(f: (T) -> Unit) {
val results = runTests(this, f)
val passed = results.filterIsInstance<ElementPass<T>>()
if (passed.size != 0) {
val msg = "${passed.size} elements passed but expected ${0}"
buildAssertionError(msg, results)
}
}
| 0
| null |
0
| 1
|
6d9d202d60985d9f8cb471b07c366397d60605e3
| 3,613
|
kotest-assertions
|
Apache License 2.0
|
platform/backend/core/src/main/kotlin/io/hamal/core/adapter/topic/Append.kt
|
hamal-io
| 622,870,037
| false
|
{"Kotlin": 3917028, "C": 1401512, "TypeScript": 339641, "Lua": 170806, "C++": 40651, "Makefile": 11728, "Java": 7564, "JavaScript": 3076, "CMake": 2838, "CSS": 1567, "HTML": 1248, "Shell": 977}
|
package io.hamal.core.adapter.topic
import io.hamal.core.adapter.request.RequestEnqueuePort
import io.hamal.core.security.SecurityContext
import io.hamal.lib.domain.GenerateDomainId
import io.hamal.lib.domain._enum.RequestStatus
import io.hamal.lib.domain.request.TopicAppendEntryRequest
import io.hamal.lib.domain.request.TopicAppendEventRequested
import io.hamal.lib.domain.vo.RequestId
import org.springframework.stereotype.Component
fun interface TopicEventAppendPort {
operator fun invoke(req: TopicAppendEntryRequest): TopicAppendEventRequested
}
@Component
class TopicEventAppendAdapter(
private val topicGet: TopicGetPort,
private val generateDomainId: GenerateDomainId,
private val requestEnqueue: RequestEnqueuePort
) : TopicEventAppendPort {
override fun invoke(req: TopicAppendEntryRequest): TopicAppendEventRequested {
val topic = topicGet(req.topicId)
return TopicAppendEventRequested(
requestId = generateDomainId(::RequestId),
requestedBy = SecurityContext.currentAuthId,
requestStatus = RequestStatus.Submitted,
id = req.topicId,
payload = req.payload
).also(requestEnqueue::invoke)
}
}
| 39
|
Kotlin
|
0
| 0
|
c263adf12584f9ed4be14d3884daa88ab08313d3
| 1,215
|
hamal
|
Creative Commons Zero v1.0 Universal
|
shared/lib/res/src/jvmMain/kotlin/org/mobilenativefoundation/store/news/shared/lib/res/drawable/showIcon.jvm.kt
|
matt-ramotar
| 742,173,124
| false
|
{"Kotlin": 36554}
|
package org.mobilenativefoundation.store.news.shared.lib.res.drawable
import androidx.compose.ui.graphics.painter.Painter
actual val facebookLogo: Painter
get() = TODO("Not yet implemented")
| 1
|
Kotlin
|
0
| 0
|
6943b9218cd1aa765dc66145b75b1e63625091af
| 196
|
news
|
Apache License 2.0
|
shared/lib/res/src/jvmMain/kotlin/org/mobilenativefoundation/store/news/shared/lib/res/drawable/showIcon.jvm.kt
|
matt-ramotar
| 742,173,124
| false
|
{"Kotlin": 36554}
|
package org.mobilenativefoundation.store.news.shared.lib.res.drawable
import androidx.compose.ui.graphics.painter.Painter
actual val facebookLogo: Painter
get() = TODO("Not yet implemented")
| 1
|
Kotlin
|
0
| 0
|
6943b9218cd1aa765dc66145b75b1e63625091af
| 196
|
news
|
Apache License 2.0
|
reftagger/src/main/java/dev/mattrob/reftagger/repo/ScriptureRepo.kt
|
mattrob33
| 321,482,435
| false
| null |
package dev.mattrob.reftagger.repo
import android.content.Context
import dev.mattrob.reftagger.cache.ScriptureDiskCache
import dev.mattrob.reftagger.cache.ScriptureMemCache
import dev.mattrob.reftagger.data.Response
import dev.mattrob.reftagger.remote.ScriptureRemote
import dev.mattrob.reftagger.usecases.GetBibleGatewayApiUseCase
internal class ScriptureRepo(
getBibleGatewayApi: GetBibleGatewayApiUseCase,
appContext: Context? = null
) {
private val memCache = ScriptureMemCache.getInstance()
private val diskCache: ScriptureDiskCache? = if (appContext != null)
ScriptureDiskCache.getInstance(appContext)
else
null
private val remote = ScriptureRemote(getBibleGatewayApi)
fun getScripture(reference: String,
version: String,
onResult: (Response) -> Unit)
{
val memCachedText = memCache.getText(reference, version)
if (memCachedText != null) {
onResult(Response.Success(memCachedText))
return
}
diskCache?.let { diskCache ->
val diskCachedText = diskCache.getText(reference, version)
if (diskCachedText != null) {
memCache.putText(reference, version, diskCachedText)
onResult(Response.Success(diskCachedText))
return
}
}
remote.getScripture(reference, version) { response ->
when (response) {
is Response.Success -> {
memCache.putText(reference, version, response.text)
diskCache?.putText(reference, version, response.text)
onResult(Response.Success(response.text))
}
is Response.Error -> {
onResult(Response.Error(response.message))
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4b0690b35a029571711e7a629a3143a2b61d6971
| 1,563
|
RefTagger
|
Apache License 2.0
|
content-types/content-types-core-services/src/test/kotlin/org/orkg/contenttypes/domain/actions/visualization/VisualizationResourceCreatorUnitTest.kt
|
TIBHannover
| 197,416,205
| false
| null |
package org.orkg.contenttypes.domain.actions.visualization
import io.kotest.assertions.asClue
import io.kotest.matchers.shouldBe
import io.mockk.clearAllMocks
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.orkg.common.ThingId
import org.orkg.contenttypes.domain.actions.VisualizationState
import org.orkg.contenttypes.input.testing.fixtures.dummyCreateVisualizationCommand
import org.orkg.graph.domain.Classes
import org.orkg.graph.input.CreateResourceUseCase
import org.orkg.graph.input.ResourceUseCases
class VisualizationResourceCreatorUnitTest {
private val resourceService: ResourceUseCases = mockk()
private val visualizationResourceCreator = VisualizationResourceCreator(resourceService)
@BeforeEach
fun resetState() {
clearAllMocks()
}
@AfterEach
fun verifyMocks() {
confirmVerified(resourceService)
}
@Test
fun `Given a visualization create command, it crates a new visualization resource`() {
val command = dummyCreateVisualizationCommand()
val state = VisualizationState()
val resourceCreateCommand = CreateResourceUseCase.CreateCommand(
label = command.title,
classes = setOf(Classes.visualization),
extractionMethod = command.extractionMethod,
contributorId = command.contributorId,
observatoryId = command.observatories.firstOrNull(),
organizationId = command.organizations.firstOrNull()
)
val id = ThingId("Visualization")
every { resourceService.create(resourceCreateCommand) } returns id
val result = visualizationResourceCreator(command, state)
result.asClue {
it.authors.size shouldBe 0
it.visualizationId shouldBe id
}
verify(exactly = 1) { resourceService.create(resourceCreateCommand) }
}
}
| 0
| null |
2
| 5
|
f9de52bdf498fdc200e7f655a52cecff215c1949
| 2,036
|
orkg-backend
|
MIT License
|
sample/src/main/java/com/stfalcon/stfalconfixturer/sample/InfoActivity.kt
|
stfalcon-studio
| 155,727,695
| false
| null |
package com.stfalcon.stfalconfixturer.sample
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.stfalcon.stfalconfixturer.extensions.setFixtureTag
import kotlinx.android.synthetic.main.activity_info.*
class InfoActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_info)
secondNameEt.setFixtureTag("name")
secondAddressEt.setFixtureTag("address")
}
}
| 0
|
Kotlin
|
2
| 31
|
808b67e2adc06da499be6e19e1ea4154f0756169
| 527
|
StfalconFixturer-android
|
Apache License 2.0
|
feature/album/user/view/implementation/src/main/kotlin/com/savvasdalkitsis/uhuruphotos/feature/album/user/view/implementation/seam/action/SetAlbumId.kt
|
savvasdalkitsis
| 485,908,521
| false
|
{"Kotlin": 2667740, "Ruby": 1294, "PowerShell": 325, "Shell": 158}
|
/*
Copyright 2024 <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.savvasdalkitsis.uhuruphotos.feature.album.user.view.implementation.seam.action
import com.savvasdalkitsis.uhuruphotos.feature.album.user.view.implementation.seam.UserAlbumActionsContext
import com.savvasdalkitsis.uhuruphotos.feature.album.user.view.implementation.seam.UserAlbumMutation.ShowDeleteConfirmationDialog
import com.savvasdalkitsis.uhuruphotos.feature.album.user.view.implementation.ui.state.UserAlbumState
import com.savvasdalkitsis.uhuruphotos.foundation.seam.api.Mutation
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
data object DeleteUserAlbumRequested : UserAlbumAction() {
override fun UserAlbumActionsContext.handle(state: UserAlbumState): Flow<Mutation<UserAlbumState>> {
return flowOf(ShowDeleteConfirmationDialog(true))
}
}
| 71
|
Kotlin
|
26
| 358
|
a1159f2236f66fe533f7ba785d47e4201e10424a
| 1,358
|
uhuruphotos-android
|
Apache License 2.0
|
bubblepicker/src/main/java/com/igalata/bubblepicker/extensions.kt
|
AnimationStudy
| 91,865,916
| false
| null |
package com.igalata.bubblepicker
import android.graphics.Bitmap
import android.opengl.GLES20.*
import android.opengl.GLUtils
import com.igalata.bubblepicker.Constant.FLOAT_SIZE
import com.igalata.bubblepicker.Constant.TEXTURE_VERTICES
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
/**
* Created by irinagalata on 3/8/17.
*/
fun Float.sqr() = this * this
fun FloatBuffer.passToShader(programId: Int, name: String) {
position(0)
glGetAttribLocation(programId, name).let {
glVertexAttribPointer(it, 2, GL_FLOAT, false, 2 * FLOAT_SIZE, this)
glEnableVertexAttribArray(it)
}
}
fun FloatArray.toFloatBuffer() = ByteBuffer
.allocateDirect(size * FLOAT_SIZE)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()?.put(this)
fun FloatArray.passTextureVertices(index: Int) = put(index * 8, TEXTURE_VERTICES)
fun FloatArray.put(index: Int, another: FloatArray) = another.forEachIndexed { i, float -> this[index + i] = float }
fun Float.convertPoint(size: Int, scale: Float) = (2f * (this / size.toFloat()) - 1f) / scale
fun Float.convertValue(size: Int, scale: Float) = (2f * (this / size.toFloat())) / scale
fun Bitmap.toTexture(textureUnit: Int) {
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, textureUnit)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
GLUtils.texImage2D(GL_TEXTURE_2D, 0, this, 0)
recycle()
glBindTexture(GL_TEXTURE_2D, 0)
}
fun Int.even() = this % 2 == 0
| 1
| null |
1
| 2
|
202e8a3611d4dd4c70adeb95459bfc43e5000c22
| 1,584
|
Bubble-Picker
|
The Unlicense
|
generator/src/main/kotlin/com/divpundir/mavlink/generator/DeprecatedGen.kt
|
divyanshupundir
| 484,943,163
| false
|
{"Kotlin": 2680196}
|
package com.divpundir.mavlink.generator
import com.squareup.kotlinpoet.AnnotationSpec
import com.divpundir.mavlink.generator.models.DeprecatedModel
internal fun DeprecatedModel.generateAnnotation() = AnnotationSpec
.builder(Deprecated::class)
.addMember("message = %S", content ?: "")
.build()
| 5
|
Kotlin
|
6
| 36
|
b78842d3422a7c4d6a5ad6a712fc237e2d599e89
| 308
|
mavlink-kotlin
|
Apache License 2.0
|
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/large/TwoSpeechBubblesLarge.kt
|
SchweizerischeBundesbahnen
| 853,290,161
| false
|
{"Kotlin": 6728512}
|
package ch.sbb.compose_mds.sbbicons.large
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import ch.sbb.compose_mds.sbbicons.LargeGroup
public val LargeGroup.TwoSpeechBubblesLarge: ImageVector
get() {
if (_twoSpeechBubblesLarge != null) {
return _twoSpeechBubblesLarge!!
}
_twoSpeechBubblesLarge = Builder(name = "TwoSpeechBubblesLarge", defaultWidth = 48.0.dp,
defaultHeight = 48.0.dp, viewportWidth = 48.0f, viewportHeight = 48.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(6.5f, 9.0f)
lineTo(6.0f, 9.0f)
verticalLineToRelative(19.0f)
horizontalLineToRelative(6.0f)
verticalLineToRelative(5.207f)
lineToRelative(0.854f, -0.853f)
lineTo(17.207f, 28.0f)
lineTo(18.0f, 28.0f)
verticalLineToRelative(8.0f)
horizontalLineToRelative(11.793f)
lineToRelative(4.353f, 4.354f)
lineToRelative(0.854f, 0.853f)
lineTo(35.0f, 36.0f)
horizontalLineToRelative(6.0f)
lineTo(41.0f, 17.0f)
lineTo(31.0f, 17.0f)
lineTo(31.0f, 9.0f)
lineTo(6.5f, 9.0f)
moveTo(31.0f, 18.0f)
verticalLineToRelative(4.0f)
horizontalLineToRelative(5.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(-5.0f)
verticalLineToRelative(3.0f)
horizontalLineToRelative(5.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(-5.0f)
verticalLineToRelative(1.0f)
lineTo(19.0f, 28.0f)
verticalLineToRelative(7.0f)
horizontalLineToRelative(11.207f)
lineToRelative(0.147f, 0.146f)
lineTo(34.0f, 38.793f)
lineTo(34.0f, 35.0f)
horizontalLineToRelative(6.0f)
lineTo(40.0f, 18.0f)
close()
moveTo(7.0f, 27.0f)
lineTo(7.0f, 10.0f)
horizontalLineToRelative(23.0f)
verticalLineToRelative(17.0f)
lineTo(16.793f, 27.0f)
lineToRelative(-0.147f, 0.146f)
lineTo(13.0f, 30.793f)
lineTo(13.0f, 27.0f)
lineTo(7.0f, 27.0f)
moveToRelative(4.0f, -12.0f)
horizontalLineToRelative(14.0f)
verticalLineToRelative(-1.0f)
lineTo(11.0f, 14.0f)
close()
moveTo(23.0f, 23.0f)
lineTo(11.0f, 23.0f)
verticalLineToRelative(-1.0f)
horizontalLineToRelative(12.0f)
close()
moveTo(26.0f, 19.0f)
lineTo(11.0f, 19.0f)
verticalLineToRelative(-1.0f)
horizontalLineToRelative(15.0f)
close()
moveTo(33.0f, 30.0f)
lineTo(23.0f, 30.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(10.0f)
close()
}
}
.build()
return _twoSpeechBubblesLarge!!
}
private var _twoSpeechBubblesLarge: ImageVector? = null
| 0
|
Kotlin
|
0
| 1
|
090a66a40e1e5a44d4da6209659287a68cae835d
| 4,014
|
mds-android-compose
|
MIT License
|
src/main/kotlin/github/mewgrammer/shopbuddy/persistence/mapping/ShoppingListMapper.kt
|
Mewgrammer
| 503,052,371
| false
|
{"Kotlin": 43249}
|
package github.mewgrammer.shopbuddy.persistence.mapping
import github.mewgrammer.shopbuddy.api.model.ShoppingListDto
import github.mewgrammer.shopbuddy.api.model.request.CreateShoppingListDto
import github.mewgrammer.shopbuddy.persistence.model.ShoppingList
import github.mewgrammer.shopbuddy.persistence.model.ShoppingListItem
import org.mapstruct.Mapper
import org.mapstruct.Mapping
import org.mapstruct.Named
@Mapper(uses = [ShoppingListItemMapper::class])
interface ShoppingListMapper {
@Mapping(source = "items", target = "totalValue", qualifiedByName = ["totalValue"])
fun toDto(shoppingList: ShoppingList): ShoppingListDto
fun toEntity(dto: CreateShoppingListDto): ShoppingList
companion object {
@JvmStatic
@Named("totalValue")
fun calculateTotalValue(items: List<ShoppingListItem>?): Double {
return items?.sumOf { it.quantity * (it.product?.price ?: 0.0) } ?: 0.0
}
}
}
| 0
|
Kotlin
|
0
| 0
|
01f72fc46e7aaa358624b3ed8a3ab816a4982ba5
| 946
|
shopping-buddy
|
MIT License
|
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/empty/EmptyWhileBlock.kt
|
mlegy
| 330,361,375
| false
| null |
package io.gitlab.arturbosch.detekt.rules.empty
import io.gitlab.arturbosch.detekt.api.Config
import org.jetbrains.kotlin.psi.KtWhileExpression
/**
* Reports empty `while` expressions. Empty blocks of code serve no purpose and should be removed.
*
* @active since v1.0.0
* @author <NAME>
* @author <NAME>
*/
class EmptyWhileBlock(config: Config) : EmptyRule(config) {
override fun visitWhileExpression(expression: KtWhileExpression) {
expression.body?.addFindingIfBlockExprIsEmpty()
}
}
| 3
| null |
0
| 1
|
c37812e0b8af0ec304fcefce5152dfc9845d52c8
| 501
|
detekt
|
Apache License 2.0
|
app/src/main/kotlin/no/nav/k9punsj/rest/server/JournalpostInfoRoutes.kt
|
navikt
| 216,808,662
| false
| null |
package no.nav.k9punsj.rest.server
import no.nav.k9.sak.kontrakt.dokument.JournalpostIdDto
import no.nav.k9punsj.AuthenticationHandler
import no.nav.k9punsj.K9SakRoutes
import no.nav.k9punsj.RequestContext
import no.nav.k9punsj.journalpost.JournalpostService
import no.nav.k9punsj.rest.web.dto.AktørIdDto
import no.nav.k9punsj.rest.web.søkUferdigJournalposter
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.bodyValueAndAwait
import org.springframework.web.reactive.function.server.json
import kotlin.coroutines.coroutineContext
@Configuration
internal class JournalpostInfoRoutes(
private val authenticationHandler: AuthenticationHandler,
private val journalpostService: JournalpostService,
) {
private companion object {
private const val AktørIdKey = "aktor_id"
private val logger = LoggerFactory.getLogger(JournalpostInfoRoutes::class.java)
}
internal object Urls {
internal const val HentÅpneJournalposter = "/journalpost/uferdig/{${AktørIdKey}}"
internal const val HentÅpneJournalposterPost = "/journalpost/uferdig"
}
@Bean
fun JournalpostInfoRoutes() = K9SakRoutes(authenticationHandler) {
GET("/api${Urls.HentÅpneJournalposter}") { request ->
RequestContext(coroutineContext, request) {
val aktørId = request.aktørId()
val journalpostIder = journalpostService.finnJournalposterPåPersonBareFraFordel(aktørId)
.map { journalpost -> JournalpostIdDto(journalpost.journalpostId) }
return@RequestContext ServerResponse
.ok()
.json()
.bodyValueAndAwait(JournalpostIderDto(journalpostIder))
}
}
POST("/api${Urls.HentÅpneJournalposterPost}") { request ->
RequestContext(coroutineContext, request) {
val dto = request.søkUferdigJournalposter()
val journalpostIder = journalpostService.finnJournalposterPåPersonBareFraFordel(dto.aktorIdentDto)
.map { journalpost -> JournalpostIdDto(journalpost.journalpostId) }
val journalpostPåBarnet = dto.aktorIdentBarnDto?.let {
journalpostService.finnJournalposterPåPersonBareFraFordel(it)
.map { journalpost -> JournalpostIdDto(journalpost.journalpostId) }
}.orEmpty()
return@RequestContext ServerResponse
.ok()
.json()
.bodyValueAndAwait(JournalpostIderDto(journalpostIder, journalpostPåBarnet))
}
}
}
private fun ServerRequest.aktørId(): AktørIdDto = pathVariable(AktørIdKey)
data class JournalpostIderDto(
val journalpostIder: List<JournalpostIdDto>,
val journalpostIderBarn: List<JournalpostIdDto> = emptyList()
)
}
| 9
|
Kotlin
|
2
| 1
|
762efffe6b7fc6b9a968a93e1bb6344304f0f839
| 3,164
|
k9-punsj
|
MIT License
|
project-system-gradle-psd/testSrc/com/android/tools/idea/gradle/structure/model/helpers/ExtractVariableWorkerTest.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.structure.model.helpers
import com.android.sdklib.SdkVersionInfo
import com.android.tools.idea.gradle.structure.model.PsProjectImpl
import com.android.tools.idea.gradle.structure.model.android.AndroidModuleDescriptors
import com.android.tools.idea.gradle.structure.model.android.PsAndroidModule
import com.android.tools.idea.gradle.structure.model.android.PsAndroidModuleDefaultConfigDescriptors
import com.android.tools.idea.gradle.structure.model.android.PsBuildType
import com.android.tools.idea.gradle.structure.model.android.PsProductFlavor
import com.android.tools.idea.gradle.structure.model.android.asParsed
import com.android.tools.idea.gradle.structure.model.java.PsJavaModule
import com.android.tools.idea.gradle.structure.model.meta.Annotated
import com.android.tools.idea.gradle.structure.model.meta.DslText
import com.android.tools.idea.gradle.structure.model.meta.ModelPropertyCore
import com.android.tools.idea.gradle.structure.model.meta.ParsedValue
import com.android.tools.idea.gradle.structure.model.meta.annotated
import com.android.tools.idea.gradle.structure.model.meta.maybeValue
import com.android.tools.idea.testing.AndroidGradleTestCase
import com.android.tools.idea.testing.TestProjectPaths.PSD_SAMPLE_GROOVY
import com.android.tools.idea.testing.TestProjectPaths.PSD_SAMPLE_KOTLIN
import com.android.tools.idea.testing.TestProjectPaths.UNIT_TESTING
import com.intellij.pom.java.LanguageLevel
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.notNullValue
import org.hamcrest.CoreMatchers.nullValue
import org.hamcrest.MatcherAssert.assertThat
class ExtractVariableWorkerTest : AndroidGradleTestCase() {
private fun doTestExtractVariable() {
val resolvedProject = myFixture.project
val project = PsProjectImpl(resolvedProject)
val appModule = project.findModuleByName("app") as PsAndroidModule
val compileSdkVersion = AndroidModuleDescriptors.compileSdkVersion.bind(appModule)
run {
val worker = ExtractVariableWorker(compileSdkVersion)
val (newName, newProperty) = worker.changeScope(appModule.variables, "")
assertThat(newName, equalTo("compileSdkVersion"))
assertThat(newProperty.getParsedValue(), equalTo(SdkVersionInfo.HIGHEST_KNOWN_STABLE_API.toString().asParsed().annotated()))
worker.commit("compileSdkVersion")
assertThat(compileSdkVersion.getParsedValue(),
equalTo<Annotated<ParsedValue<String>>>(ParsedValue.Set.Parsed(SdkVersionInfo.HIGHEST_KNOWN_STABLE_API.toString(),
DslText.Reference("compileSdkVersion"))
.annotated()))
assertThat(appModule.variables.getOrCreateVariable("compileSdkVersion").value,
equalTo(SdkVersionInfo.HIGHEST_KNOWN_STABLE_API.asParsed<Any>()))
}
run {
val worker = ExtractVariableWorker(compileSdkVersion)
val (newName, newProperty) = worker.changeScope(appModule.variables, "")
assertThat(newName, equalTo("compileSdkVersion1")) // The second suggested name is the preferredName + "1".
assertThat(newProperty.getParsedValue(),
equalTo<Annotated<ParsedValue<String>>>(ParsedValue.Set.Parsed(SdkVersionInfo.HIGHEST_KNOWN_STABLE_API.toString(),
DslText.Reference("compileSdkVersion"))
.annotated()))
worker.commit("otherName")
assertThat(compileSdkVersion.getParsedValue(),
equalTo<Annotated<ParsedValue<String>>>(ParsedValue.Set.Parsed(SdkVersionInfo.HIGHEST_KNOWN_STABLE_API.toString(),
DslText.Reference("otherName"))
.annotated()))
assertThat(appModule.variables.getOrCreateVariable("otherName").value,
equalTo<ParsedValue<Any>>(
ParsedValue.Set.Parsed(SdkVersionInfo.HIGHEST_KNOWN_STABLE_API, DslText.Reference("compileSdkVersion"))))
}
}
fun testExtractVariableGroovy() {
loadProject(PSD_SAMPLE_GROOVY)
doTestExtractVariable()
}
fun testExtractVariableKotlin() {
loadProject(PSD_SAMPLE_KOTLIN)
doTestExtractVariable()
}
fun testExtractVariable_projectLevel() {
loadProject(PSD_SAMPLE_GROOVY)
val resolvedProject = myFixture.project
val project = PsProjectImpl(resolvedProject)
val appModule = project.findModuleByName("app") as PsAndroidModule
val compileSdkVersion = AndroidModuleDescriptors.compileSdkVersion.bind(appModule)
run {
val worker = ExtractVariableWorker(compileSdkVersion)
val (newName, newProperty) = worker.changeScope(appModule.variables, "")
assertThat(newName, equalTo("compileSdkVersion"))
assertThat(newProperty.getParsedValue(), equalTo(SdkVersionInfo.HIGHEST_KNOWN_STABLE_API.toString().asParsed().annotated()))
val (newName2, newProperty2) = worker.changeScope(project.variables, "renamedName")
assertThat(newName2, equalTo("renamedName"))
assertThat(newProperty2.getParsedValue(), equalTo(SdkVersionInfo.HIGHEST_KNOWN_STABLE_API.toString().asParsed().annotated()))
worker.commit("renamedName")
assertThat(compileSdkVersion.getParsedValue(),
equalTo<Annotated<ParsedValue<String>>>(ParsedValue.Set.Parsed(SdkVersionInfo.HIGHEST_KNOWN_STABLE_API.toString(),
DslText.Reference("renamedName"))
.annotated()))
assertThat(appModule.variables.getVariable("renamedName"), nullValue())
assertThat(project.variables.getOrCreateVariable("renamedName").value,
equalTo(SdkVersionInfo.HIGHEST_KNOWN_STABLE_API.asParsed<Any>()))
}
}
fun testExtractEmptyValue() {
loadProject(PSD_SAMPLE_GROOVY)
val resolvedProject = myFixture.project
val project = PsProjectImpl(resolvedProject)
val appModule = project.findModuleByName("app") as PsAndroidModule
val targetCompatibility = AndroidModuleDescriptors.targetCompatibility.bind(appModule)
run {
val worker = ExtractVariableWorker(targetCompatibility)
val (newName, newProperty) = worker.changeScope(appModule.variables, "")
assertThat(newName, equalTo("targetCompatibility"))
assertThat(newProperty.getParsedValue(), equalTo<Annotated<ParsedValue<LanguageLevel>>>(ParsedValue.NotSet.annotated()))
assertThat(worker.validate("targetCompatibility"), equalTo("Cannot bind a variable to an empty value."))
}
}
fun testExtractVariableWithBlankName() {
loadProject(PSD_SAMPLE_GROOVY)
val resolvedProject = myFixture.project
val project = PsProjectImpl(resolvedProject)
val appModule = project.findModuleByName("app") as PsAndroidModule
val targetCompatibility = AndroidModuleDescriptors.targetCompatibility.bind(appModule)
run {
val worker = ExtractVariableWorker(targetCompatibility)
val (newName, newProperty) = worker.changeScope(appModule.variables, "")
assertThat(newName, equalTo("targetCompatibility"))
assertThat(newProperty.getParsedValue(), equalTo<Annotated<ParsedValue<LanguageLevel>>>(ParsedValue.NotSet.annotated()))
assertThat(worker.validate(" "), equalTo("Variable name is required."))
}
}
fun testExtractAndroidModuleDependencyVersion() {
loadProject(UNIT_TESTING)
val resolvedProject = myFixture.project
val project = PsProjectImpl(resolvedProject)
val appModule = project.findModuleByName("app") as PsAndroidModule
val junit = appModule.dependencies.findLibraryDependencies("junit:junit:4.12").firstOrNull()
val mockito = appModule.dependencies.findLibraryDependencies("org.mockito:mockito-core:3.12.4").firstOrNull()
assertThat(junit, notNullValue())
assertThat(mockito, notNullValue())
run {
val junitVersion = junit!!.versionProperty.bind(Unit)
val worker = ExtractVariableWorker(junitVersion)
val (newName, newProperty) = worker.changeScope(appModule.variables, "")
assertThat(newName, equalTo("junitVersion"))
assertThat(newProperty.getParsedValue(),
equalTo<Annotated<ParsedValue<String>>>(ParsedValue.Set.Parsed("4.12", DslText.Literal).annotated()))
worker.commit("junitVersion")
assertThat(appModule.variables.getOrCreateVariable("junitVersion").value,
equalTo<ParsedValue<Any>>(ParsedValue.Set.Parsed("4.12", DslText.Literal)))
}
run {
val mockitoVersion = mockito!!.versionProperty.bind(Unit)
val worker = ExtractVariableWorker(mockitoVersion)
val (newName, newProperty) = worker.changeScope(appModule.variables, "")
assertThat(newName, equalTo("mockitoCoreVersion"))
assertThat(newProperty.getParsedValue(),
equalTo<Annotated<ParsedValue<String>>>(ParsedValue.Set.Parsed("3.12.4", DslText.Literal).annotated()))
worker.commit("mockitoCoreVersion")
assertThat(appModule.variables.getOrCreateVariable("mockitoCoreVersion").value,
equalTo<ParsedValue<Any>>(ParsedValue.Set.Parsed("3.12.4", DslText.Literal)))
}
}
fun testExtractJavaModuleDependencyVersion() {
loadProject(UNIT_TESTING)
val resolvedProject = myFixture.project
val project = PsProjectImpl(resolvedProject)
val javaModule = project.findModuleByName("javalib") as PsJavaModule
val junit = javaModule.dependencies.findLibraryDependencies("junit:junit:4.12").firstOrNull()
val mockito = javaModule.dependencies.findLibraryDependencies("org.mockito:mockito-core:3.12.4").firstOrNull()
assertThat(junit, notNullValue())
assertThat(mockito, notNullValue())
run {
val junitVersion = junit!!.versionProperty.bind(Unit)
val worker = ExtractVariableWorker(junitVersion)
val (newName, newProperty) = worker.changeScope(javaModule.variables, "")
assertThat(newName, equalTo("junitVersion"))
assertThat(newProperty.getParsedValue(),
equalTo<Annotated<ParsedValue<String>>>(ParsedValue.Set.Parsed("4.12", DslText.Literal).annotated()))
worker.commit("junitVersion")
assertThat(javaModule.variables.getOrCreateVariable("junitVersion").value,
equalTo<ParsedValue<Any>>(ParsedValue.Set.Parsed("4.12", DslText.Literal)))
}
run {
val mockitoVersion = mockito!!.versionProperty.bind(Unit)
val worker = ExtractVariableWorker(mockitoVersion)
val (newName, newProperty) = worker.changeScope(javaModule.variables, "")
assertThat(newName, equalTo("mockitoCoreVersion"))
assertThat(newProperty.getParsedValue(),
equalTo<Annotated<ParsedValue<String>>>(ParsedValue.Set.Parsed("3.12.4", DslText.Literal).annotated()))
worker.commit("mockitoCoreVersion")
assertThat(javaModule.variables.getOrCreateVariable("mockitoCoreVersion").value,
equalTo<ParsedValue<Any>>(ParsedValue.Set.Parsed("3.12.4", DslText.Literal)))
}
}
fun testPreferredVariableNames() {
loadProject(PSD_SAMPLE_GROOVY)
val resolvedProject = myFixture.project
val project = PsProjectImpl(resolvedProject)
val appModule = project.findModuleByName("app") as PsAndroidModule
fun <T : Any> checkPreferredName(property: ModelPropertyCore<T>, expectedName: String, expectedValue: T? = null) {
val worker = ExtractVariableWorker(property)
val (newName, newProperty) = worker.changeScope(appModule.variables, "")
assertThat(newName, equalTo(expectedName))
if (expectedValue != null) {
assertThat(newProperty.getParsedValue().value.maybeValue, equalTo(expectedValue))
}
worker.cancel()
}
// applicationId
run {
val applicationId = PsAndroidModuleDefaultConfigDescriptors.applicationId.bind(appModule.defaultConfig)
checkPreferredName(applicationId, "defaultApplicationId", "com.example.psd.sample.app.default")
}
run {
val applicationId =
PsProductFlavor.ProductFlavorDescriptors.applicationId.bind(appModule.productFlavors.find { it.name == "paid" }!!)
checkPreferredName(applicationId, "paidApplicationId", "com.example.psd.sample.app.paid")
}
// applicationIdSuffix
run {
val applicationIdSuffix = PsAndroidModuleDefaultConfigDescriptors.applicationIdSuffix.bind(appModule.defaultConfig)
checkPreferredName(applicationIdSuffix, "defaultApplicationIdSuffix")
}
run {
val applicationIdSuffix =
PsBuildType.BuildTypeDescriptors.applicationIdSuffix.bind(appModule.buildTypes.find { it.name == "release" }!!)
checkPreferredName(applicationIdSuffix, "releaseApplicationIdSuffix", "suffix")
}
run {
val applicationIdSuffix =
PsProductFlavor.ProductFlavorDescriptors.applicationIdSuffix.bind(appModule.productFlavors.find { it.name == "bar" }!!)
checkPreferredName(applicationIdSuffix, "barApplicationIdSuffix", "barSuffix")
}
// multiDexEnabled
run {
val multiDexEnabled = PsAndroidModuleDefaultConfigDescriptors.multiDexEnabled.bind(appModule.defaultConfig)
checkPreferredName(multiDexEnabled, "defaultMultiDexEnabled")
}
run {
val multiDexEnabled = PsBuildType.BuildTypeDescriptors.multiDexEnabled.bind(appModule.buildTypes.find { it.name == "release" }!!)
checkPreferredName(multiDexEnabled, "releaseMultiDexEnabled")
}
run {
val multiDexEnabled = PsProductFlavor.ProductFlavorDescriptors.multiDexEnabled.bind(
appModule.productFlavors.find { it.name == "bar" }!!)
checkPreferredName(multiDexEnabled, "barMultiDexEnabled")
}
// {max,min,target}SdkVersion
run {
val maxSdkVersion = PsAndroidModuleDefaultConfigDescriptors.maxSdkVersion.bind(appModule.defaultConfig)
val minSdkVersion = PsAndroidModuleDefaultConfigDescriptors.minSdkVersion.bind(appModule.defaultConfig)
val targetSdkVersion = PsAndroidModuleDefaultConfigDescriptors.targetSdkVersion.bind(appModule.defaultConfig)
checkPreferredName(maxSdkVersion, "defaultMaxSdkVersion", 26)
// do not be fooled by the literal 9 in psdSample/app/build.gradle: it gets overwritten on project setup
// (see AndroidGradleTests.updateMinSdkVersion)
checkPreferredName(minSdkVersion, "defaultMinSdkVersion", SdkVersionInfo.LOWEST_ACTIVE_API.toString())
checkPreferredName(targetSdkVersion, "defaultTargetSdkVersion", SdkVersionInfo.HIGHEST_KNOWN_STABLE_API.toString())
}
run {
val paidProductFlavor = appModule.productFlavors.find { it.name == "paid" }!!
val maxSdkVersion = PsProductFlavor.ProductFlavorDescriptors.maxSdkVersion.bind(paidProductFlavor)
val minSdkVersion = PsProductFlavor.ProductFlavorDescriptors.minSdkVersion.bind(paidProductFlavor)
val targetSdkVersion = PsProductFlavor.ProductFlavorDescriptors.targetSdkVersion.bind(paidProductFlavor)
checkPreferredName(maxSdkVersion, "paidMaxSdkVersion", 25)
checkPreferredName(minSdkVersion, "paidMinSdkVersion", "10")
checkPreferredName(targetSdkVersion, "paidTargetSdkVersion", "20")
}
// test{ApplicationId,FunctionalTest,HandleProfiling,InstrumentationRunner}
run {
val testApplicationId = PsAndroidModuleDefaultConfigDescriptors.testApplicationId.bind(appModule.defaultConfig)
val testFunctionalTest = PsAndroidModuleDefaultConfigDescriptors.testFunctionalTest.bind(appModule.defaultConfig)
val testHandleProfiling = PsAndroidModuleDefaultConfigDescriptors.testHandleProfiling.bind(appModule.defaultConfig)
val testInstrumentationRunner = PsAndroidModuleDefaultConfigDescriptors.testInstrumentationRunner.bind(appModule.defaultConfig)
checkPreferredName(testApplicationId, "defaultTestApplicationId", "com.example.psd.sample.app.default.test")
checkPreferredName(testFunctionalTest, "defaultTestFunctionalTest", false)
checkPreferredName(testHandleProfiling, "defaultTestHandleProfiling")
checkPreferredName(testInstrumentationRunner, "defaultTestInstrumentationRunner")
}
run {
val paidProductFlavor = appModule.productFlavors.find { it.name == "paid" }!!
val testApplicationId = PsProductFlavor.ProductFlavorDescriptors.testApplicationId.bind(paidProductFlavor)
val testFunctionalTest = PsProductFlavor.ProductFlavorDescriptors.testFunctionalTest.bind(paidProductFlavor)
val testHandleProfiling = PsProductFlavor.ProductFlavorDescriptors.testHandleProfiling.bind(paidProductFlavor)
val testInstrumentationRunner = PsProductFlavor.ProductFlavorDescriptors.testInstrumentationRunner.bind(paidProductFlavor)
checkPreferredName(testApplicationId, "paidTestApplicationId", "com.example.psd.sample.app.paid.test")
checkPreferredName(testFunctionalTest, "paidTestFunctionalTest", true)
checkPreferredName(testHandleProfiling, "paidTestHandleProfiling", true)
checkPreferredName(testInstrumentationRunner, "paidTestInstrumentationRunner")
}
// version{Code,Name,NameSuffix}
run {
val versionCode = PsAndroidModuleDefaultConfigDescriptors.versionCode.bind(appModule.defaultConfig)
val versionName = PsAndroidModuleDefaultConfigDescriptors.versionName.bind(appModule.defaultConfig)
val versionNameSuffix = PsAndroidModuleDefaultConfigDescriptors.versionNameSuffix.bind(appModule.defaultConfig)
checkPreferredName(versionCode, "defaultVersionCode", 1)
checkPreferredName(versionName, "defaultVersionName", "1.0")
checkPreferredName(versionNameSuffix, "defaultVersionNameSuffix", "vns")
}
run {
val versionNameSuffix = PsBuildType.BuildTypeDescriptors.versionNameSuffix.bind(appModule.buildTypes.find { it.name == "release" }!!)
checkPreferredName(versionNameSuffix, "releaseVersionNameSuffix", "vsuffix")
}
run {
val paidProductFlavor = appModule.productFlavors.find { it.name == "paid" }!!
val versionCode = PsProductFlavor.ProductFlavorDescriptors.versionCode.bind(paidProductFlavor)
val versionName = PsProductFlavor.ProductFlavorDescriptors.versionName.bind(paidProductFlavor)
val versionNameSuffix = PsProductFlavor.ProductFlavorDescriptors.versionNameSuffix.bind(paidProductFlavor)
checkPreferredName(versionCode, "paidVersionCode", 2)
checkPreferredName(versionName, "paidVersionName", "2.0")
checkPreferredName(versionNameSuffix, "paidVersionNameSuffix", "vnsFoo")
}
// buildType-only properties
run {
val releaseBuildType = appModule.buildTypes.find { it.name == "release" }!!
val debuggable = PsBuildType.BuildTypeDescriptors.debuggable.bind(releaseBuildType)
val jniDebuggable = PsBuildType.BuildTypeDescriptors.jniDebuggable.bind(releaseBuildType)
val minifyEnabled = PsBuildType.BuildTypeDescriptors.minifyEnabled.bind(releaseBuildType)
val renderscriptDebuggable = PsBuildType.BuildTypeDescriptors.renderscriptDebuggable.bind(releaseBuildType)
val renderscriptOptimLevel = PsBuildType.BuildTypeDescriptors.renderscriptOptimLevel.bind(releaseBuildType)
val testCoverageEnabled = PsBuildType.BuildTypeDescriptors.testCoverageEnabled.bind(releaseBuildType)
checkPreferredName(debuggable, "releaseDebuggable", false)
checkPreferredName(jniDebuggable, "releaseJniDebuggable", false)
checkPreferredName(minifyEnabled, "releaseMinifyEnabled", false)
checkPreferredName(renderscriptDebuggable, "releaseRenderscriptDebuggable")
checkPreferredName(renderscriptOptimLevel, "releaseRenderscriptOptimLevel", 2)
checkPreferredName(testCoverageEnabled, "releaseTestCoverageEnabled")
}
}
}
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 20,540
|
android
|
Apache License 2.0
|
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/ec2/CfnTransitGatewayRouteTablePropagation.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 142794926}
|
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.ec2
import io.cloudshiftdev.awscdk.CfnResource
import io.cloudshiftdev.awscdk.IInspectable
import io.cloudshiftdev.awscdk.TreeInspector
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import kotlin.String
import kotlin.Unit
import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct
import software.constructs.Construct as SoftwareConstructsConstruct
/**
* Enables the specified attachment to propagate routes to the specified propagation route table.
*
* For more information about enabling transit gateway route propagation, see
* [EnableTransitGatewayRouteTablePropagation](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_EnableTransitGatewayRouteTablePropagation.html)
* in the *Amazon EC2 API Reference* .
*
* 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.ec2.*;
* CfnTransitGatewayRouteTablePropagation cfnTransitGatewayRouteTablePropagation =
* CfnTransitGatewayRouteTablePropagation.Builder.create(this,
* "MyCfnTransitGatewayRouteTablePropagation")
* .transitGatewayAttachmentId("transitGatewayAttachmentId")
* .transitGatewayRouteTableId("transitGatewayRouteTableId")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetablepropagation.html)
*/
public open class CfnTransitGatewayRouteTablePropagation(
cdkObject: software.amazon.awscdk.services.ec2.CfnTransitGatewayRouteTablePropagation,
) : CfnResource(cdkObject), IInspectable {
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnTransitGatewayRouteTablePropagationProps,
) :
this(software.amazon.awscdk.services.ec2.CfnTransitGatewayRouteTablePropagation(scope.let(CloudshiftdevConstructsConstruct::unwrap),
id, props.let(CfnTransitGatewayRouteTablePropagationProps::unwrap))
)
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnTransitGatewayRouteTablePropagationProps.Builder.() -> Unit,
) : this(scope, id, CfnTransitGatewayRouteTablePropagationProps(props)
)
/**
*
*/
public open fun attrId(): String = unwrap(this).getAttrId()
/**
* 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))
}
/**
* The ID of the attachment.
*/
public open fun transitGatewayAttachmentId(): String =
unwrap(this).getTransitGatewayAttachmentId()
/**
* The ID of the attachment.
*/
public open fun transitGatewayAttachmentId(`value`: String) {
unwrap(this).setTransitGatewayAttachmentId(`value`)
}
/**
* The ID of the propagation route table.
*/
public open fun transitGatewayRouteTableId(): String =
unwrap(this).getTransitGatewayRouteTableId()
/**
* The ID of the propagation route table.
*/
public open fun transitGatewayRouteTableId(`value`: String) {
unwrap(this).setTransitGatewayRouteTableId(`value`)
}
/**
* A fluent builder for
* [io.cloudshiftdev.awscdk.services.ec2.CfnTransitGatewayRouteTablePropagation].
*/
@CdkDslMarker
public interface Builder {
/**
* The ID of the attachment.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetablepropagation.html#cfn-ec2-transitgatewayroutetablepropagation-transitgatewayattachmentid)
* @param transitGatewayAttachmentId The ID of the attachment.
*/
public fun transitGatewayAttachmentId(transitGatewayAttachmentId: String)
/**
* The ID of the propagation route table.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetablepropagation.html#cfn-ec2-transitgatewayroutetablepropagation-transitgatewayroutetableid)
* @param transitGatewayRouteTableId The ID of the propagation route table.
*/
public fun transitGatewayRouteTableId(transitGatewayRouteTableId: String)
}
private class BuilderImpl(
scope: SoftwareConstructsConstruct,
id: String,
) : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.ec2.CfnTransitGatewayRouteTablePropagation.Builder =
software.amazon.awscdk.services.ec2.CfnTransitGatewayRouteTablePropagation.Builder.create(scope,
id)
/**
* The ID of the attachment.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetablepropagation.html#cfn-ec2-transitgatewayroutetablepropagation-transitgatewayattachmentid)
* @param transitGatewayAttachmentId The ID of the attachment.
*/
override fun transitGatewayAttachmentId(transitGatewayAttachmentId: String) {
cdkBuilder.transitGatewayAttachmentId(transitGatewayAttachmentId)
}
/**
* The ID of the propagation route table.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetablepropagation.html#cfn-ec2-transitgatewayroutetablepropagation-transitgatewayroutetableid)
* @param transitGatewayRouteTableId The ID of the propagation route table.
*/
override fun transitGatewayRouteTableId(transitGatewayRouteTableId: String) {
cdkBuilder.transitGatewayRouteTableId(transitGatewayRouteTableId)
}
public fun build(): software.amazon.awscdk.services.ec2.CfnTransitGatewayRouteTablePropagation =
cdkBuilder.build()
}
public companion object {
public val CFN_RESOURCE_TYPE_NAME: String =
software.amazon.awscdk.services.ec2.CfnTransitGatewayRouteTablePropagation.CFN_RESOURCE_TYPE_NAME
public operator fun invoke(
scope: CloudshiftdevConstructsConstruct,
id: String,
block: Builder.() -> Unit = {},
): CfnTransitGatewayRouteTablePropagation {
val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id)
return CfnTransitGatewayRouteTablePropagation(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.ec2.CfnTransitGatewayRouteTablePropagation):
CfnTransitGatewayRouteTablePropagation = CfnTransitGatewayRouteTablePropagation(cdkObject)
internal fun unwrap(wrapped: CfnTransitGatewayRouteTablePropagation):
software.amazon.awscdk.services.ec2.CfnTransitGatewayRouteTablePropagation =
wrapped.cdkObject as
software.amazon.awscdk.services.ec2.CfnTransitGatewayRouteTablePropagation
}
}
| 1
|
Kotlin
|
0
| 4
|
953e78163afe1a14fd67b30dd666b11b3e05a2ec
| 7,046
|
kotlin-cdk-wrapper
|
Apache License 2.0
|
src/nl/hannahsten/texifyidea/reference/LatexUsagesProvider.kt
|
Hannah-Sten
| 62,398,769
| false
| null |
package nl.hannahsten.texifyidea.reference
import com.intellij.lang.cacheBuilder.DefaultWordsScanner
import com.intellij.lang.cacheBuilder.WordsScanner
import com.intellij.lang.findUsages.FindUsagesProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.tree.TokenSet
import nl.hannahsten.texifyidea.LatexLexerAdapter
import nl.hannahsten.texifyidea.psi.LatexTypes
class LatexUsagesProvider : FindUsagesProvider {
override fun getWordsScanner(): WordsScanner? {
return DefaultWordsScanner(
LatexLexerAdapter(),
// Identifiers.
TokenSet.create(
LatexTypes.COMMAND_TOKEN, LatexTypes.COMMANDS,
LatexTypes.BEGIN_COMMAND, LatexTypes.BEGIN_TOKEN,
LatexTypes.END_COMMAND, LatexTypes.END_TOKEN,
LatexTypes.PARAMETER_TEXT, LatexTypes.PARAMETER,
LatexTypes.REQUIRED_PARAM, LatexTypes.OPTIONAL_PARAM
),
// Comments.
TokenSet.create(LatexTypes.COMMENT_TOKEN, LatexTypes.COMMENT),
// Literals.
TokenSet.create(
LatexTypes.ENVIRONMENT_CONTENT, LatexTypes.CONTENT,
LatexTypes.MATH_CONTENT, LatexTypes.ENVIRONMENT,
LatexTypes.MATH_ENVIRONMENT, LatexTypes.DISPLAY_MATH,
LatexTypes.INLINE_MATH, LatexTypes.NO_MATH_CONTENT,
LatexTypes.GROUP, LatexTypes.OPTIONAL_PARAM
)
)
}
override fun getNodeText(element: PsiElement, useFullName: Boolean): String {
return element.node.text
}
override fun getDescriptiveName(element: PsiElement): String {
return element.text
}
override fun getType(element: PsiElement): String {
return element.node.elementType.toString()
}
override fun getHelpId(psiElement: PsiElement): String? {
return null
}
override fun canFindUsagesFor(psiElement: PsiElement): Boolean {
return psiElement is PsiNameIdentifierOwner
}
}
| 99
| null |
87
| 891
|
986550410e2fea91d1e93abfc683db1c8527c9d9
| 2,064
|
TeXiFy-IDEA
|
MIT License
|
app/src/main/java/com/honey96dev/homemadeproduct/p4customer/CustomerCartFragment.kt
|
honey96dev
| 179,335,457
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 53, "Kotlin": 29}
|
package com.honey96dev.homemadeproduct.p4customer
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import com.honey96dev.homemadeproduct.tools.G
import com.honey96dev.homemadeproduct.R
import com.squareup.picasso.Picasso
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.text.ParseException
import okhttp3.HttpUrl
class CustomerCartFragment : Fragment() {
internal var updateUIHandler: Handler? = null
internal var mCartID: String? = null
internal var mGetCartTask: GetCartTask? = null
internal var mImageView: ImageView? = null
internal var mNameView: EditText? = null
internal var mDescriptionView: EditText? = null
internal var mPriceView: EditText? = null
internal var mDateView: EditText? = null
internal var mQuantityView: EditText? = null
// String mImage;
internal var mName: String? = null
internal var mDescription: String? = null
internal var mImg1: String? = null
internal var mPrice: Double = 0.toDouble()
internal var mDate: String? = null
internal var mQuantity: String? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_customer_cart, container, false)
createUpdateUiHandler()
mImageView = rootView.findViewById<View>(R.id.image_view) as ImageView
mNameView = rootView.findViewById<View>(R.id.name_edit_text) as EditText
mDescriptionView = rootView.findViewById<View>(R.id.description_edit_text) as EditText
mPriceView = rootView.findViewById<View>(R.id.price_edit_text) as EditText
mDateView = rootView.findViewById<View>(R.id.date_edit_text) as EditText
mQuantityView = rootView.findViewById<View>(R.id.quantity_edit_text) as EditText
val cancelButton = rootView.findViewById<View>(R.id.cancel_button) as Button
val orderButton = rootView.findViewById<View>(R.id.order_button) as Button
cancelButton.setOnClickListener {
activity!!.finish()
}
orderButton.setOnClickListener {
Thread(Runnable {
val cartTask = OrderCartTask()
cartTask.execute()
}).start()
}
val intent = (activity as CustomerCartActivity).intent
mCartID = intent.getStringExtra(PRODUCT_ID_KEY)
mGetCartTask = GetCartTask()
mGetCartTask!!.execute()
return rootView
}
internal fun createUpdateUiHandler() {
if (updateUIHandler == null) {
updateUIHandler = object : Handler() {
override fun handleMessage(msg: Message) {
// Means the message is sent from child thread.
when (msg.what) {
MESSAGE_UPDATE_DISPLAY_PRODUCT_INFO_THREAD -> {
try {
if (mImg1!!.isNotBlank()) {
Picasso.get().load(mImg1)
.into(mImageView)
mImageView!!.background = null
} else {
mImageView!!.setImageBitmap(null)
}
} catch (e: Exception) {
mImageView!!.background = context!!.getDrawable(R.drawable.image_border)
e.printStackTrace()
}
mNameView!!.setText(mName)
mDescriptionView!!.setText(mDescription)
mPriceView!!.setText(mPrice.toString())
mDateView!!.setText(mDate)
mQuantityView!!.setText(mQuantity)
}
MESSAGE_SHOW_SAVE_PRODUCT_TOAST_THREAD -> Toast.makeText(context, R.string.message_product_saved, Toast.LENGTH_LONG).show()
MESSAGE_SHOW_INVALID_FILE_TOAST_THREAD -> Toast.makeText(context, R.string.message_invalid_file, Toast.LENGTH_LONG).show()
MESSAGE_SHOW_FILE_NOT_FOUND_TOAST_THREAD -> Toast.makeText(context, R.string.message_file_not_found, Toast.LENGTH_LONG).show()
MESSAGE_SHOW_SERVER_ERROR_TOAST_THREAD -> Toast.makeText(context, R.string.message_server_error, Toast.LENGTH_LONG).show()
MESSAGE_SHOW_IO_ERROR_TOAST_THREAD -> Toast.makeText(context, R.string.message_io_error, Toast.LENGTH_LONG).show()
MESSAGE_SHOW_ERROR_TOAST_THREAD -> Toast.makeText(context, R.string.message_error, Toast.LENGTH_LONG).show()
}
}
}
}
}
internal inner class GetCartTask() : AsyncTask<String, Void, String>() {
var mMethod = "GET"
val READ_TIMEOUT = 15000
val CONNECTION_TIMEOUT = 15000
override fun doInBackground(vararg params: String): String? {
val url = HttpUrl.Builder()
.scheme(G.SERVER_SCHEME)
.host(G.SERVER_IP)
.addPathSegment("get_cart.php")
.addQueryParameter("cart_id", mCartID)
.build()
var stringUrl = url.toString()
Log.e("product-api", stringUrl)
var result: String?
var inputLine: String
try {
//Create a URL object holding our url
val myUrl = URL(stringUrl)
//Create a connection
val connection = myUrl.openConnection() as HttpURLConnection
//Set methods and timeouts
connection.requestMethod = mMethod
connection.readTimeout = READ_TIMEOUT
connection.connectTimeout = CONNECTION_TIMEOUT
connection.setRequestProperty("Accept", "application/json")
connection.connect()
val streamReader = InputStreamReader(connection.inputStream)
val reader = BufferedReader(streamReader)
val stringBuilder = StringBuilder()
inputLine = reader.use(BufferedReader::readText)
stringBuilder.append(inputLine)
reader.close()
streamReader.close()
result = stringBuilder.toString()
} catch (e: IOException) {
e.printStackTrace()
result = null
}
return result
}
override fun onPostExecute(responseText: String?) {
super.onPostExecute(responseText)
if (responseText == null) {
return
}
try {
Log.e("products-api", responseText)
val json = JSONObject(responseText)
val item = json.getJSONObject("data")
mImg1 = item.getString("img1")
mName = item.getString("name")
mDescription = item.getString("description")
mPrice = item.getDouble("price")
mDate = item.getString("date")
mQuantity = item.getString("quantity")
// products.getJSONObject()
} catch (e: JSONException) {
e.printStackTrace()
} catch (e: ParseException) {
e.printStackTrace()
}
//
val message = Message()
message.what = MESSAGE_UPDATE_DISPLAY_PRODUCT_INFO_THREAD
updateUIHandler!!.sendMessage(message)
}
}
internal inner class OrderCartTask() : AsyncTask<String, Void, Boolean>() {
var mMethod = "GET"
val READ_TIMEOUT = 15000
val CONNECTION_TIMEOUT = 15000
override fun doInBackground(vararg params: String): Boolean? {
val url = HttpUrl.Builder()
.scheme(G.SERVER_SCHEME)
.host(G.SERVER_IP)
.addPathSegment("order_cart.php")
.addQueryParameter("cart_id", mCartID)
.build()
var stringUrl = url.toString()
Log.e("save-product-url", stringUrl)
var result: String?
var inputLine: String
try {
//============add=============
val myUrl = URL(stringUrl)
//Create a connection
val connection = myUrl.openConnection() as HttpURLConnection
//Set methods and timeouts
connection.requestMethod = mMethod
connection.readTimeout = READ_TIMEOUT
connection.connectTimeout = CONNECTION_TIMEOUT
// connection.setRequestProperty("Accept", "application/json");
connection.connect()
val streamReader = InputStreamReader(connection.inputStream)
val reader = BufferedReader(streamReader)
val stringBuilder = StringBuilder()
inputLine = reader.use(BufferedReader::readText)
stringBuilder.append(inputLine)
reader.close()
streamReader.close()
result = stringBuilder.toString()
Log.e("add-api", result)
val json = JSONObject(result)
result = json.getString("result")
return if (result != "success") {
false
} else true
} catch (e: IOException) {
e.printStackTrace()
result = null
} catch (e: JSONException) {
e.printStackTrace()
result = null
}
return false
}
override fun onPostExecute(responseText: Boolean?) {
super.onPostExecute(responseText)
if (responseText == true) {
val message = Message()
message.what = MESSAGE_SHOW_SAVE_PRODUCT_TOAST_THREAD
// message.arg1 = 1;
updateUIHandler!!.sendMessage(message)
}
}
}
companion object {
val PRODUCT_ID_KEY = "PRODUCT_ID_KEY"
internal val MESSAGE_UPDATE_DISPLAY_PRODUCT_INFO_THREAD = 1
internal val MESSAGE_SHOW_SAVE_PRODUCT_TOAST_THREAD = 2
internal val MESSAGE_SHOW_INVALID_FILE_TOAST_THREAD = 3
internal val MESSAGE_SHOW_FILE_NOT_FOUND_TOAST_THREAD = 4
internal val MESSAGE_SHOW_SERVER_ERROR_TOAST_THREAD = 5
internal val MESSAGE_SHOW_IO_ERROR_TOAST_THREAD = 6
internal val MESSAGE_SHOW_ERROR_TOAST_THREAD = 7
internal val REQUEST_GET_SINGLE_FILE = 1
/**
* Returns a new instance of this fragment for the given section
* number.
*/
fun newInstance(): CustomerCartFragment {
return CustomerCartFragment()
}
}
}
| 1
| null |
1
| 1
|
c41d4115e11a8449218d86879354d3d3bcbefdab
| 11,554
|
android-home-made-product
|
MIT License
|
android-uitests/testData/CatchUp/app/src/main/kotlin/io/sweers/catchup/ui/activity/MainActivity.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (c) 2018 <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 io.sweers.catchup.ui.activity
import android.app.Activity
import android.content.SharedPreferences
import android.os.Bundle
import androidx.fragment.app.transaction
import androidx.recyclerview.widget.RecyclerView.RecycledViewPool
import com.uber.autodispose.autoDisposable
import dagger.Binds
import dagger.Provides
import dagger.multibindings.Multibinds
import io.sweers.catchup.R
import io.sweers.catchup.data.LinkManager
import io.sweers.catchup.data.ServiceDao
import io.sweers.catchup.edu.Syllabus
import io.sweers.catchup.injection.scopes.PerActivity
import io.sweers.catchup.service.api.LinkHandler
import io.sweers.catchup.service.api.Service
import io.sweers.catchup.service.api.ServiceMeta
import io.sweers.catchup.serviceregistry.ResolvedCatchUpServiceRegistry
import io.sweers.catchup.ui.base.InjectingBaseActivity
import io.sweers.catchup.ui.fragments.PagerFragment
import io.sweers.catchup.ui.fragments.service.StorageBackedService
import io.sweers.catchup.util.customtabs.CustomTabActivityHelper
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Qualifier
class MainActivity : InjectingBaseActivity() {
@Inject
internal lateinit var customTab: CustomTabActivityHelper
@Inject
internal lateinit var linkManager: LinkManager
@Inject
internal lateinit var syllabus: Syllabus
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
syllabus.bind(this)
lifecycle()
.doOnStart(linkManager) { connect(this@MainActivity) }
.doOnStart(customTab) { bindCustomTabsService(this@MainActivity) }
.doOnStop(customTab) { unbindCustomTabsService(this@MainActivity) }
.doOnDestroy(customTab) { connectionCallback = null }
.autoDisposable(this)
.subscribe()
val viewGroup = viewContainer.forActivity(this)
layoutInflater.inflate(R.layout.activity_main, viewGroup)
if (savedInstanceState == null) {
supportFragmentManager.transaction {
add(R.id.fragment_container, PagerFragment())
}
}
}
@dagger.Module(includes = [ResolvedCatchUpServiceRegistry::class])
abstract class ServiceIntegrationModule {
@dagger.Module
companion object {
@TextViewPool
@Provides
@JvmStatic
@PerActivity
fun provideTextViewPool() = RecycledViewPool()
@VisualViewPool
@Provides
@JvmStatic
@PerActivity
fun provideVisualViewPool() = RecycledViewPool()
@Provides
@PerActivity
@JvmStatic
@FinalServices
fun provideFinalServices(serviceDao: ServiceDao,
serviceMetas: Map<String, @JvmSuppressWildcards ServiceMeta>,
sharedPreferences: SharedPreferences,
services: Map<String, @JvmSuppressWildcards Provider<Service>>): Map<String, Provider<Service>> {
return services
.filter {
serviceMetas[it.key]!!.enabled && sharedPreferences.getBoolean(
serviceMetas[it.key]!!.enabledPreferenceKey, true)
}
.mapValues { (_, value) ->
Provider { StorageBackedService(serviceDao, value.get()) }
}
}
}
@Multibinds
@PerActivity
abstract fun services(): Map<String, Service>
@Multibinds
abstract fun serviceMetas(): Map<String, ServiceMeta>
@Binds
@PerActivity
abstract fun provideActivity(activity: MainActivity): Activity
@Binds
@PerActivity
abstract fun provideLinkHandler(linkManager: LinkManager): LinkHandler
}
}
@Qualifier
annotation class TextViewPool
@Qualifier
annotation class VisualViewPool
@Qualifier
annotation class FinalServices
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 4,271
|
android
|
Apache License 2.0
|
Concurrency/EchoServer/src/main/kotlin/palbp/laboratory/echo/coroutines/Main_flows_101.kt
|
palbp
| 463,200,783
| false
|
{"Kotlin": 703005, "C": 16710, "Assembly": 891, "Dockerfile": 610, "Makefile": 383}
|
package palbp.laboratory.echo.coroutines
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import org.slf4j.LoggerFactory
import palbp.laboratory.echo.AsyncSemaphore
import java.net.Socket
import java.nio.channels.AsynchronousServerSocketChannel
import java.nio.channels.AsynchronousSocketChannel
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
private const val EXIT = "exit"
private val logger = LoggerFactory.getLogger("Coroutine and NIO2 based Echo Server")
/**
* Number of client sessions initiated during the server's current execution
*/
private val sessionCount = AtomicInteger(0)
/**
* Creates a client session, incrementing the number of initiated sessions.
*/
private fun createSession(): Int = sessionCount.incrementAndGet()
/**
* The server's entry point.
*/
fun main(args: Array<String>) {
val port = if (args.isEmpty() || args[0].toIntOrNull() == null) 8000 else args[0].toInt()
logger.info("Process id is = ${ProcessHandle.current().pid()}. Starting echo server at port $port")
val executor = Executors.newSingleThreadExecutor()
val serverSocket = createServerChannel("localhost", port, executor)
val scope = CoroutineScope(executor.asCoroutineDispatcher())
val throttle = AsyncSemaphore(2)
scope.launch {
serverSocket.toFlow(throttle).collect { sessionSocket ->
logger.info("Connection accepted")
launch {
try {
handleEchoSession(sessionSocket)
}
finally {
throttle.release()
}
}
}
logger.info("Parent coroutine ends")
}
readln()
logger.info("Shutting down...")
scope.cancel()
executor.shutdown()
val terminated = executor.awaitTermination(5, TimeUnit.SECONDS)
logger.info("Done. Executor terminated successfully? $terminated")
}
/**
* Serves the client connected to the given [Socket] instance
*/
private suspend fun handleEchoSession(sessionSocket: AsynchronousSocketChannel) {
val sessionId = createSession()
var echoCount = 0
sessionSocket.use {
logger.info("Accepted session $sessionId")
it.suspendingWriteLine("Welcome client number $sessionId!")
it.suspendingWriteLine("I'll echo everything you send me. Finish with '$EXIT'. Ready when you are!")
it.toFlow().collect { line ->
logger.info("Received line number '${++echoCount}'. Echoing it.")
it.suspendingWriteLine("($echoCount) Echo: $line")
}
it.suspendingWriteLine("Bye!")
logger.info("Session $sessionId ends")
}
}
/**
* Extension function that produces a flow of [AsynchronousSocketChannel] client connections from this
* [AsynchronousServerSocketChannel] instance.
*/
suspend fun AsynchronousServerSocketChannel.toFlow(throttle: AsyncSemaphore): Flow<AsynchronousSocketChannel> =
flow {
try {
while(true) {
throttle.acquire().await()
logger.info("Ready to accept connections")
val sessionSocket = suspendingAccept()
emit(sessionSocket)
}
}
finally {
logger.info("Flow of connections ends")
}
}
/**
* Extension function that produces a flow of client messages (text lines) received from this
* [AsynchronousSocketChannel] instance.
*/
suspend fun AsynchronousSocketChannel.toFlow(): Flow<String> =
flow {
while (true) {
val line = suspendingReadLine()
if (line == null || line == EXIT)
break
emit(line)
}
}
| 0
|
Kotlin
|
0
| 5
|
2b72493599cb4f6c22f952a77459510f8108805c
| 3,940
|
laboratory
|
MIT License
|
wallet/src/main/kotlin/com/faisaldev/wallet/service/WalletService.kt
|
Abdirashid26
| 852,094,827
| false
|
{"Kotlin": 68971, "Java": 5599}
|
package com.faisaldev.wallet.service
import com.faisaldev.user_service.utils.GlobalResponse
import com.faisaldev.wallet.dto.BalanceInquiryRequest
import com.faisaldev.wallet.dto.BalanceInquiryResponse
import com.faisaldev.wallet.dto.GetWalletAccountsDto
import com.faisaldev.wallet.model.Wallet
interface WalletService {
suspend fun performBalanceInquiry(balanceInquiryRequest: BalanceInquiryRequest) : GlobalResponse<BalanceInquiryResponse>
suspend fun getAllWallets(getWalletAccountsDto: GetWalletAccountsDto): List<Wallet>?
}
| 0
|
Kotlin
|
0
| 0
|
657856cf8109e6c854916d7d48161efe588d1cbd
| 541
|
Agent-Connect
|
Apache License 2.0
|
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/solid/AngleUp.kt
|
DevSrSouza
| 311,134,756
| false
| null |
package compose.icons.fontawesomeicons.solid
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.fontawesomeicons.SolidGroup
public val SolidGroup.AngleUp: ImageVector
get() {
if (_angleUp != null) {
return _angleUp!!
}
_angleUp = Builder(name = "AngleUp", defaultWidth = 320.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 320.0f, viewportHeight = 512.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(177.0f, 159.7f)
lineToRelative(136.0f, 136.0f)
curveToRelative(9.4f, 9.4f, 9.4f, 24.6f, 0.0f, 33.9f)
lineToRelative(-22.6f, 22.6f)
curveToRelative(-9.4f, 9.4f, -24.6f, 9.4f, -33.9f, 0.0f)
lineTo(160.0f, 255.9f)
lineToRelative(-96.4f, 96.4f)
curveToRelative(-9.4f, 9.4f, -24.6f, 9.4f, -33.9f, 0.0f)
lineTo(7.0f, 329.7f)
curveToRelative(-9.4f, -9.4f, -9.4f, -24.6f, 0.0f, -33.9f)
lineToRelative(136.0f, -136.0f)
curveToRelative(9.4f, -9.5f, 24.6f, -9.5f, 34.0f, -0.1f)
close()
}
}
.build()
return _angleUp!!
}
private var _angleUp: ImageVector? = null
| 17
| null |
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 1,879
|
compose-icons
|
MIT License
|
src/main/kotlin/me/bscal/runecraft/gui/runeboard/slots/GemSlot.kt
|
bscal
| 414,444,966
| false
| null |
package me.bscal.runecraft.gui.runeboard.slots
import me.bscal.runecraft.items.runeitems.BreakLevel
import me.bscal.runecraft.stats.StatInstance
import me.bscal.runecraft.stats.StatRegistry
import net.axay.kspigot.chat.KColors
import net.axay.kspigot.items.addLore
import net.axay.kspigot.items.itemStack
import net.axay.kspigot.items.meta
import net.axay.kspigot.items.name
import org.bukkit.Material
import org.bukkit.attribute.Attribute
import org.bukkit.attribute.AttributeModifier
import org.bukkit.inventory.ItemStack
abstract class GemSlot(itemStack: ItemStack) : BoardSlot(itemStack, 0, BreakLevel.UNBREAKABLE)
{
val Stats = ArrayList<StatInstance>()
init
{
GuiItemWrapper.GuiItem.item.meta {
this.addLore {
Stats.forEach { +it.GetStat().GetLoreString(it) } // TODO better way? thinking removing stat if deserialized
}
}
}
constructor() : this(ItemStack(Material.AIR))
}
class DiamondSlot : GemSlot(itemStack(Material.DIAMOND_BLOCK) {
meta {
name = "${KColors.LIGHTSKYBLUE}Diamond Gem"
}
})
{
init
{
Stats.add(StatRegistry.VANILLA_STAT.NewStatInstance(Attribute.GENERIC_ATTACK_DAMAGE, 1.0, AttributeModifier.Operation.ADD_NUMBER))
}
}
class EmeraldSlot : GemSlot(itemStack(Material.EMERALD_BLOCK) {
meta {
name = "${KColors.MEDIUMSPRINGGREEN}Emerald Gem"
}
})
{
init
{
Stats.add(StatRegistry.VANILLA_STAT.NewStatInstance(Attribute.GENERIC_MAX_HEALTH, 1.0, AttributeModifier.Operation.ADD_NUMBER))
}
}
class RedstoneSlot : GemSlot(itemStack(Material.REDSTONE_BLOCK) {
meta {
name = "${KColors.DARKRED}Ruby Gem"
}
})
{}
class LapisSlot : GemSlot(itemStack(Material.LAPIS_BLOCK) {
meta {
name = "${KColors.DARKBLUE}Sapphire Gem"
}
})
{}
class AmethystSlot : GemSlot(itemStack(Material.AMETHYST_BLOCK) {
meta {
name = "${KColors.DARKPURPLE}Amethyst Gem"
}
})
{}
| 0
|
Kotlin
|
0
| 0
|
29470ea09d74e83a3fabe0789d8f169de6a3fc20
| 1,823
|
RuneCraft
|
MIT License
|
defitrack-protocol-contracts/src/main/java/io/defitrack/protocol/kwenta/StakingRewardsV2Contract.kt
|
decentri-fi
| 426,174,152
| false
|
{"Kotlin": 1290412, "Java": 1948, "Dockerfile": 909}
|
package io.defitrack.protocol.kwenta
import io.defitrack.abi.TypeUtils.Companion.address
import io.defitrack.abi.TypeUtils.Companion.toAddress
import io.defitrack.abi.TypeUtils.Companion.uint256
import io.defitrack.evm.contract.BlockchainGateway
import io.defitrack.evm.contract.ContractCall
import io.defitrack.evm.contract.EvmContract
class StakingRewardsV2Contract(
blockchainGateway: BlockchainGateway, address: String
) : EvmContract(blockchainGateway, address) {
fun earnedfn(user: String): ContractCall {
return createFunction(
"earned",
listOf(user.toAddress()),
listOf(uint256())
)
}
val kwenta = constant<String>("kwenta", address())
fun claimFn(): ContractCall {
return createFunction("compound")
}
}
| 59
|
Kotlin
|
6
| 11
|
8b8d6713c9734d2b4015e7affe658e797c9a00be
| 801
|
defi-hub
|
MIT License
|
app/src/main/java/de/oljg/glac/feature_alarm/ui/components/AlarmListItem.kt
|
Ol-J-G
| 768,542,224
| false
|
{"Kotlin": 980887}
|
package de.oljg.glac.feature_alarm.ui.components
import android.net.Uri
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DeleteForever
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.outlined.Audiotrack
import androidx.compose.material.icons.outlined.Snooze
import androidx.compose.material.icons.outlined.WbTwilight
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import de.oljg.glac.R
import de.oljg.glac.feature_alarm.ui.utils.AlarmDefaults.ALARM_LIST_ITEM_BORDER_SIZE
import de.oljg.glac.feature_alarm.ui.utils.AlarmDefaults.ALARM_LIST_ITEM_HORIZONTAL_PADDING
import de.oljg.glac.feature_alarm.ui.utils.AlarmDefaults.ALARM_LIST_ITEM_PADDING
import de.oljg.glac.feature_alarm.ui.utils.AlarmDefaults.ALARM_LIST_ITEM_ROW_HEIGHT
import de.oljg.glac.feature_alarm.ui.utils.AlarmDefaults.ALARM_LIST_ITEM_SURFACE_CORNER_SIZE
import de.oljg.glac.feature_alarm.ui.utils.AlarmDefaults.ALARM_LIST_ITEM_TEXT_ICON_SPACE
import de.oljg.glac.feature_alarm.ui.utils.AlarmDefaults.localizedShortDateTimeFormatter
import de.oljg.glac.feature_alarm.ui.utils.Repetition
import de.oljg.glac.feature_alarm.ui.utils.evaluateAlarmRepetitionInfo
import de.oljg.glac.feature_alarm.ui.utils.prettyPrintAlarmSoundUri
import de.oljg.glac.ui.theme.glacColorScheme
import java.time.LocalDateTime
import kotlin.time.Duration
import kotlin.time.DurationUnit
@Composable
fun AlarmListItem(
alarmStart: LocalDateTime,
isLightAlarm: Boolean,
lightAlarmDuration: Duration,
repetition: Repetition,
snoozeDuration: Duration,
alarmSoundUri: Uri,
selected: Boolean,
onClick: () -> Unit,
onRemoveAlarm: () -> Unit,
onUpdateAlarm: () -> Unit
) {
val scrollState = rememberScrollState()
val borderColorUnselected = when (repetition) {
Repetition.NONE -> MaterialTheme.glacColorScheme.repetitionNone
Repetition.DAILY -> MaterialTheme.glacColorScheme.repetitionDaily
Repetition.WEEKLY -> MaterialTheme.glacColorScheme.repetitionWeekly
Repetition.MONTHLY -> MaterialTheme.glacColorScheme.repetitionMonthly
}
val borderColorSelected = MaterialTheme.colorScheme.surfaceTint
Surface(
shape = RoundedCornerShape(ALARM_LIST_ITEM_SURFACE_CORNER_SIZE),
tonalElevation = when {
selected -> 1.dp
else -> 0.dp
},
modifier = Modifier
.clip(RoundedCornerShape(ALARM_LIST_ITEM_SURFACE_CORNER_SIZE))
.padding(ALARM_LIST_ITEM_PADDING)
.border(
width = ALARM_LIST_ITEM_BORDER_SIZE,
color = when {
selected -> borderColorSelected
else -> borderColorUnselected
},
shape = RoundedCornerShape(ALARM_LIST_ITEM_SURFACE_CORNER_SIZE)
)
.clickable { onClick() }
) {
Column(modifier = Modifier.padding(ALARM_LIST_ITEM_PADDING)) {
Row( // Edit alarm, Repetitioninfo, Remove alarm
modifier = Modifier
.padding(vertical = ALARM_LIST_ITEM_PADDING * 2)
.fillMaxWidth()
.height(ALARM_LIST_ITEM_ROW_HEIGHT),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
IconButton(onClick = { onUpdateAlarm() }) {
Icon(
imageVector = Icons.Filled.Edit,
contentDescription = stringResource(R.string.update_alarm),
tint = MaterialTheme.colorScheme.primary
)
}
Text(
evaluateAlarmRepetitionInfo(repetition = repetition, alarmStart = alarmStart),
fontWeight = FontWeight.Medium
)
IconButton(onClick = { onRemoveAlarm() }) {
Icon(
imageVector = Icons.Filled.DeleteForever,
contentDescription = stringResource(R.string.remove_alarm),
tint = MaterialTheme.colorScheme.primary
)
}
}
HorizontalDivider(
modifier = Modifier
.fillMaxWidth(.95f)
.align(Alignment.CenterHorizontally)
)
if (repetition != Repetition.NONE) {
Row( // Next Alarm
modifier = Modifier
.padding(
horizontal = ALARM_LIST_ITEM_HORIZONTAL_PADDING,
vertical = ALARM_LIST_ITEM_PADDING
)
.fillMaxWidth()
.height(ALARM_LIST_ITEM_ROW_HEIGHT),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(stringResource(R.string.next_alarm))
Text(
text = localizedShortDateTimeFormatter.format(alarmStart),
fontStyle = FontStyle.Italic
)
}
}
/**
* Show time until next alarm (sound will start then (actual alarm start!), where light
* alarm will start at this time minus light alarm duration)
*/
AlarmCountdown(alarmStart = alarmStart)
HorizontalDivider(
modifier = Modifier
.fillMaxWidth(.95f)
.align(Alignment.CenterHorizontally)
)
Row( // Alarm sound, light alarm duration, snooze duration
modifier = Modifier
.padding(
horizontal = ALARM_LIST_ITEM_HORIZONTAL_PADDING,
vertical = ALARM_LIST_ITEM_PADDING * 2
)
.fillMaxWidth()
.height(ALARM_LIST_ITEM_ROW_HEIGHT),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
modifier = Modifier.fillMaxWidth(.45f),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(
ALARM_LIST_ITEM_TEXT_ICON_SPACE,
Alignment.Start
)
) {
Icon(
imageVector = Icons.Outlined.Audiotrack,
contentDescription = stringResource(id = R.string.alarm_sound)
)
Row(Modifier.horizontalScroll(scrollState)) {
Text(
text = alarmSoundUri.prettyPrintAlarmSoundUri(),
fontStyle = FontStyle.Italic,
maxLines = 1
)
}
}
Row(
modifier = Modifier.padding(start = ALARM_LIST_ITEM_TEXT_ICON_SPACE * 2),
horizontalArrangement = Arrangement.spacedBy(ALARM_LIST_ITEM_TEXT_ICON_SPACE)
) {
Icon(
imageVector = Icons.Outlined.WbTwilight,
contentDescription = stringResource(id = R.string.light_alarm_duration),
tint = if (isLightAlarm)
LocalContentColor.current else MaterialTheme.colorScheme.outlineVariant
)
Text(
text = lightAlarmDuration.toString(unit = DurationUnit.MINUTES),
fontStyle = FontStyle.Italic,
color = if (isLightAlarm)
Color.Unspecified else MaterialTheme.colorScheme.outlineVariant
)
}
Row(
modifier = Modifier.padding(start = ALARM_LIST_ITEM_TEXT_ICON_SPACE),
horizontalArrangement = Arrangement.spacedBy(
ALARM_LIST_ITEM_TEXT_ICON_SPACE,
Alignment.End
)
) {
Icon(
imageVector = Icons.Outlined.Snooze,
contentDescription = stringResource(id = R.string.snooze_duration)
)
Text(
snoozeDuration.toString(),
fontStyle = FontStyle.Italic,
maxLines = 1
)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b3cefafa190eae0aa95f55fc6903e327363c2efc
| 10,050
|
GLAC
|
Creative Commons Attribution 4.0 International
|
src/test/kotlin/Main.kt
|
MC-Challenge
| 305,181,487
| false
| null |
import net.challenge.configu.config.JsonConfig
import java.io.File
fun main() {
// ##############
// Example
// ##############
var modules = listOf<Module>()
modules += Module("FPS")
modules += Module("CPS")
// Loading the modules
modules.forEach { it.load() }
// Using a json config to save the values
val config = JsonConfig(File("config"), true)
// Register all modules in the config
modules.forEach { config.register(it) }
// Loading the config
config.load()
// Saving the config
config.save()
}
| 0
|
Kotlin
|
0
| 0
|
f500501a4014cf471ba9a1a6d1459a247d9388b5
| 578
|
Configu
|
Apache License 2.0
|
app/src/main/kotlin/me/sweetll/tucao/business/download/fragment/DownloadingFragment.kt
|
blackbbc
| 78,953,199
| false
| null |
package me.sweetll.tucao.business.download.fragment
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemLongClickListener
import me.sweetll.tucao.R
import me.sweetll.tucao.base.BaseFragment
import me.sweetll.tucao.business.download.DownloadActivity
import me.sweetll.tucao.business.download.adapter.DownloadingVideoAdapter
import me.sweetll.tucao.business.download.event.RefreshDownloadingVideoEvent
import me.sweetll.tucao.model.json.Part
import me.sweetll.tucao.model.json.Video
import me.sweetll.tucao.databinding.FragmentDownloadingBinding
import me.sweetll.tucao.extension.DownloadHelpers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class DownloadingFragment: BaseFragment(), DownloadActivity.ContextMenuCallback {
lateinit var binding: FragmentDownloadingBinding
val videoAdapter: DownloadingVideoAdapter by lazy {
DownloadingVideoAdapter(activity as DownloadActivity, DownloadHelpers.loadDownloadingVideos())
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_downloading, container, false)
return binding.root
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
}
fun setupRecyclerView() {
binding.videoRecycler.layoutManager = LinearLayoutManager(activity)
binding.videoRecycler.adapter = videoAdapter
binding.videoRecycler.recycledViewPool.setMaxRecycledViews(DownloadingVideoAdapter.TYPE_PART, 0)
binding.videoRecycler.recycledViewPool.setMaxRecycledViews(DownloadingVideoAdapter.TYPE_VIDEO, 0)
binding.videoRecycler.addOnItemTouchListener(object: OnItemLongClickListener() {
override fun onSimpleItemLongClick(helper: BaseQuickAdapter<*, *>, view: View, position: Int) {
if ((activity as DownloadActivity).currentActionMode != null) {
return
}
(activity as DownloadActivity).openContextMenu(this@DownloadingFragment, false)
videoAdapter.data.forEach {
when (it) {
is Video -> {
it.checkable = true
it.checked = false
it.subItems.forEach {
it.checkable = true
it.checked = false
}
}
is Part -> {
it.checkable = true
it.checked = false
}
}
}
videoAdapter.notifyDataSetChanged()
}
})
}
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onRefreshEvent(event: RefreshDownloadingVideoEvent) {
videoAdapter.setNewData(DownloadHelpers.loadDownloadingVideos())
}
override fun onDestroyContextMenu() {
videoAdapter.data.forEach {
when (it) {
is Video -> {
it.checkable = false
it.subItems.forEach { it.checkable = false }
}
is Part -> it.checkable = false
}
}
videoAdapter.notifyDataSetChanged()
}
override fun onClickDelete() {
DownloadHelpers.cancelDownload(
videoAdapter.data.flatMap {
when (it) {
is Video -> it.subItems
else -> listOf(it as Part)
}
}.distinctBy(Part::vid).filter(Part::checked)
)
}
override fun onClickPickAll(): Boolean {
if (videoAdapter.data.all {
when (it) {
is Video -> it.checked
is Part -> it.checked
else -> false
}
}) {
// 取消全选
videoAdapter.data.forEach {
when (it) {
is Video -> {
it.checked = false
it.subItems.forEach { it.checked = false }
}
is Part -> it.checked = false
}
}
videoAdapter.notifyDataSetChanged()
return false
} else {
// 全选
videoAdapter.data.forEach {
when (it) {
is Video -> {
it.checked = true
it.subItems.forEach { it.checked = true }
}
is Part -> it.checked = true
}
}
videoAdapter.notifyDataSetChanged()
return true
}
}
}
| 14
| null |
208
| 994
|
e0c29ae6c37fcca916a3aba3cbae61e74292ff99
| 5,406
|
Tucao
|
MIT License
|
java/com/mu/jan/problems/architecture/Paging.kt
|
Mukuljangir372
| 359,095,214
| false
| null |
package com.mu.jan.problems.architecture
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.utils.widget.MockView
import androidx.lifecycle.LiveData
import androidx.paging.*
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.mu.jan.problems.R
/**
* Paging 3 library is a part of android jetpack.
* It used for loading few items of list on screen at a time.
*
* To Implement Paging 3 library in your project. You need,
* 1. PagingSource or DataSource class
* - class having two params, PagingSource<Key,Value>
* - It means key = page number and Value = data class
*
* 2. Repo
* 3. PagingDataAdapter
*
*/
class PagingActivity: AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//..
/**
* val myAdapter = MyAdapter()
*
* recyclerView.apply {
* layoutManger = ...
* setHasFixedSize(true)
* adapter = myAdapter
* }
*
* lifeCycleScope.launch{
* viewModel.movieList.observe{ it ->
* myAdapter.submitData(it)
* }
* }
*
*/
}
}
class Movie{
val id: String? = null
override fun equals(other: Any?): Boolean {
return super.equals(other)
}
}
interface MovieApiService{
fun getList(): List<Movie>
}
//dataSource OR pagingSource
class MyDataSource(
private val apiService: MovieApiService
) : PagingSource<Int,Movie>(){
override fun getRefreshKey(state: PagingState<Int, Movie>): Int? {
//copied code from google
return state.anchorPosition?.let { anchorPosition ->
val anchorPage = state.closestPageToPosition(anchorPosition)
anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
}
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Movie> {
val nextPageNumber = params.key ?: 1
val response = apiService.getList()
return LoadResult.Page(
data = response,
prevKey = if(nextPageNumber==1) null else nextPageNumber - 1,
nextKey = nextPageNumber
)
}
}
//Repo
object MyRepo{
fun getList(apiService: MovieApiService): LiveData<PagingData<Movie>>{
return Pager(
config = PagingConfig(
pageSize = 50,
enablePlaceholders = false
),
pagingSourceFactory = { MyDataSource(apiService) }
).liveData
}
}
//adapter
class MyAdapter : PagingDataAdapter<Movie,MyAdapter.MyViewHolder>(DiffUtilCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.single_item,parent,false))
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
getItem(position)?.let { holder.onBind(it) }
}
inner class MyViewHolder(itemView: View
): RecyclerView.ViewHolder(itemView){
fun onBind(item: Movie){
}
}
object DiffUtilCallback : DiffUtil.ItemCallback<Movie>(){
override fun areItemsTheSame(oldItem: Movie, newItem: Movie): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Movie, newItem: Movie): Boolean {
return oldItem == newItem
}
}
}
| 0
|
Kotlin
|
0
| 1
|
bb15517c09041757d859126dc4f39d3409fdd35d
| 3,703
|
Android-Kotlin-Interview
|
Apache License 2.0
|
app/src/main/java/com/ivansison/kairos/views/adapters/WeatherTypeAdapter.kt
|
ivansison02
| 249,015,567
| false
| null |
package com.ivansison.kairos.views.adapters
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.ivansison.kairos.R
import com.ivansison.kairos.controllers.apis.OpenWeatherApi
import com.ivansison.kairos.models.WeatherType
import com.ivansison.kairos.views.activities.HomeActivity
class WeatherTypeAdapter(private val context: Context, private val parent: HomeActivity, private val items: ArrayList<WeatherType>) : RecyclerView.Adapter<WeatherTypeHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeatherTypeHolder {
return WeatherTypeHolder(LayoutInflater.from(context).inflate(R.layout.layout_weather_type_item, parent, false))
}
override fun onBindViewHolder(holder: WeatherTypeHolder, position: Int) {
val type: WeatherType = items[position]
holder.txtWeather.text = type.description!!.capitalize()
Glide.with(context).load( "${OpenWeatherApi.URL_ICON}${type.icon!!}${OpenWeatherApi.ICON_SIZE}")
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.ALL))
.apply(RequestOptions().error(R.drawable.ic_image_broken))
.into(holder.imgWeather)
}
override fun getItemCount(): Int {
return items.size
}
}
class WeatherTypeHolder (view: View) : RecyclerView.ViewHolder(view) {
val txtWeather: TextView = view.findViewById(R.id.txt_weather)
val imgWeather: ImageView = view.findViewById(R.id.img_weather)
}
| 0
|
Kotlin
|
0
| 0
|
3064a207b18203b4b7ea768b7f709ae4ebe0199c
| 1,804
|
kairos
|
MIT License
|
src/main/java/io/github/alexiscomete/lapinousecond/data/managesave/CacheCustom.kt
|
Alexiscomete
| 377,132,555
| false
| null |
package alexiscomete.managesave
import java.sql.SQLException
class CacheCustom<U>(private val table: Table, private val function: (Long) -> U) {
val hashMap = HashMap<Long, U>()
operator fun get(l: Long): U? {
var u = hashMap[l]
if (u == null) {
try {
val resultSet = saveManager.executeQuery("SELECT * FROM " + table.name + " WHERE id = " + l, true)
if (resultSet != null) {
if (resultSet.next()) {
u = function(l)
hashMap[l] = u
}
}
resultSet?.close()
} catch (throwables: SQLException) {
throwables.printStackTrace()
}
}
return u
}
fun add(id: Long) {
val hashMap = HashMap<String, String>()
hashMap["id"] = id.toString()
saveManager.insert(table.name, hashMap)
}
}
| 55
| null |
0
| 9
|
463451ddf5df27085bf6cf60a0b7d9da9b4d14f2
| 951
|
A-Discord-Adventure
|
MIT License
|
GUI/src/main/kotlin/logic/DiffSequenceInfo.kt
|
amosproj
| 705,002,381
| false
|
{"Kotlin": 283685, "Python": 2014, "Shell": 588}
|
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: <NAME> <<EMAIL>>
package logic
import algorithms.AlignmentElement
/**
* Utility class to get information about a diff sequence.
* @param diffSequence The diff sequence to get information about.
*/
class DiffSequenceInfo(private val diffSequence: Array<AlignmentElement>) {
/**
* Get count of insertions
* @return [Int] containing the number of insertions.
*/
fun getInsertions(): Int {
return diffSequence.count { it == AlignmentElement.INSERTION }
}
/**
* Get count of deletions
* @return [Int] containing the number of deletions.
*/
fun getDeletions(): Int {
return diffSequence.count { it == AlignmentElement.DELETION }
}
/**
* Get count of frames with pixel differences
* @return [Int] containing the number of frames with pixel differences.
*/
fun getFramesWithPixelDifferences(): Int {
return diffSequence.count { it == AlignmentElement.MATCH }
}
/**
* Get count of frames in reference video
* @return [Int] containing the number of frames in the reference video.
*/
fun getSizeOfVideoReference(): Int {
return diffSequence.size - getInsertions()
}
/**
* Get count of frames in current video
* @return [Int] containing the number of frames in the current video.
*/
fun getSizeOfVideoCurrent(): Int {
return diffSequence.size - getDeletions()
}
/**
* Get count of frames in diff
* @return [Int] containing the number of frames in the diff.
*/
fun getSizeOfDiff(): Int {
return diffSequence.size
}
}
| 60
|
Kotlin
|
2
| 6
|
9a47dadaf168bbdd36f0acdd1502496b10175ac2
| 1,683
|
amos2023ws03-gui-frame-diff
|
MIT License
|
core/networking/src/main/java/com/javi/core/networking/di/NetworkModule.kt
|
javierpe
| 465,529,405
| false
|
{"Kotlin": 336652}
|
package com.javi.core.networking.di
import com.javi.core.networking.BASE_URL
import com.squareup.moshi.Moshi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideRetrofit(
moshi: Moshi
): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
}
}
| 1
|
Kotlin
|
6
| 48
|
ae747ce383c62f3ab890929e723b87f13045e8bf
| 671
|
ArtGallery
|
Apache License 2.0
|
src/rider/main/kotlin/rider/RiderProjectOutputHost.kt
|
wdcossey
| 331,943,271
| true
|
{"Kotlin": 70160, "C#": 5502, "PowerShell": 2864}
|
package me.fornever.avaloniarider.rider
import com.intellij.openapi.components.Service
import com.intellij.openapi.project.Project
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rider.model.RdGetProjectOutputArgs
import com.jetbrains.rider.model.RdProjectOutput
import com.jetbrains.rider.model.riderProjectOutputModel
import com.jetbrains.rider.projectView.nodes.ProjectModelNode
import com.jetbrains.rider.projectView.solution
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import me.fornever.avaloniarider.idea.concurrency.ApplicationAnyModality
import me.fornever.avaloniarider.idea.concurrency.await
@Service
class RiderProjectOutputHost(private val project: Project) {
companion object {
fun getInstance(project: Project): RiderProjectOutputHost =
project.getService(RiderProjectOutputHost::class.java)
}
suspend fun getProjectOutput(lifetime: Lifetime, projectNode: ProjectModelNode): RdProjectOutput =
withContext(Dispatchers.ApplicationAnyModality) {
val model = project.solution.riderProjectOutputModel
val projectFilePath = projectNode.getVirtualFile()!!.path
model.getProjectOutput.start(lifetime, RdGetProjectOutputArgs(projectFilePath)).await(lifetime)
}
}
| 0
| null |
0
| 0
|
df39cdfff39b02e2dba23e6da44a41309cd6eee4
| 1,309
|
AvaloniaRider
|
MIT License
|
parser/src/main/kotlin/net/prettyrandom/thrift_kotlin/parser/visitors/StructVisitor.kt
|
TobiasBales
| 311,568,239
| false
| null |
package net.prettyrandom.thrift_kotlin.parser.visitors
import net.prettyrandom.thrift_kotlin.parser.domain.Struct
import net.prettyrandom.thrift_kotlin.parser.generated.parser.ThriftBaseVisitor
import net.prettyrandom.thrift_kotlin.parser.generated.parser.ThriftParser
class StructVisitor : ThriftBaseVisitor<Struct>() {
private val fieldVisitor = FieldVisitor()
override fun visitStruct(ctx: ThriftParser.StructContext): Struct {
return Struct(
name = ctx.IDENTIFIER().text,
fields = ctx.field().map { it.accept(fieldVisitor) }
)
}
}
| 0
|
Kotlin
|
0
| 1
|
248f2386aed54adc08216b8f939240eb262e91ef
| 590
|
thrift-kotlin
|
MIT License
|
platform/workspaceModel-core/test/com/intellij/workspace/api/SimplePropertiesInProxyBasedStorageTest.kt
|
moznuy
| 220,463,941
| false
|
{"Text": 3952, "XML": 4555, "Ant Build System": 13, "Shell": 472, "Markdown": 300, "Ignore List": 79, "Git Attributes": 9, "Batchfile": 30, "SVG": 1988, "Java": 64035, "C++": 15, "HTML": 2723, "Kotlin": 4553, "DTrace": 1, "Gradle": 71, "Java Properties": 94, "INI": 236, "JFlex": 27, "Objective-C": 19, "Groovy": 3324, "XSLT": 109, "JavaScript": 152, "CSS": 55, "JSON": 1065, "desktop": 1, "Python": 9910, "JAR Manifest": 12, "YAML": 376, "C#": 37, "Smalltalk": 17, "Diff": 128, "Erlang": 1, "Rich Text Format": 2, "AspectJ": 2, "Perl": 6, "HLSL": 2, "CoffeeScript": 3, "JSON with Comments": 42, "Vue": 11, "OpenStep Property List": 41, "Protocol Buffer": 2, "fish": 1, "EditorConfig": 211, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "PHP": 43, "Ruby": 4, "XML Property List": 77, "E-mail": 18, "Roff": 35, "Roff Manpage": 1, "Checksums": 58, "Java Server Pages": 8, "GraphQL": 20, "C": 43, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 2, "CMake": 6, "Microsoft Visual Studio Solution": 6, "VBScript": 1, "NSIS": 8, "Thrift": 3, "Cython": 10, "reStructuredText": 54, "TOML": 1, "Dockerfile": 1, "Regular Expression": 3, "JSON5": 4}
|
package com.intellij.workspace.api
import gnu.trove.THashSet
import gnu.trove.TObjectHashingStrategy
import org.jetbrains.annotations.TestOnly
import org.junit.Assert.*
import org.junit.Test
internal interface SampleEntity : TypedEntity {
val booleanProperty: Boolean
val stringProperty: String
val stringListProperty: List<String>
val fileProperty: VirtualFileUrl
}
internal interface ModifiableSampleEntity : SampleEntity, ModifiableTypedEntity<SampleEntity> {
override var booleanProperty: Boolean
override var stringProperty: String
override var stringListProperty: MutableList<String>
override var fileProperty: VirtualFileUrl
}
internal interface SelfModifiableSampleEntity : ModifiableTypedEntity<SelfModifiableSampleEntity> {
var intProperty: Int
}
internal fun TypedEntityStorageBuilder.addSampleEntity(stringProperty: String,
source: EntitySource = SampleEntitySource("test"),
booleanProperty: Boolean = false,
stringListProperty: MutableList<String> = ArrayList(),
fileProperty: VirtualFileUrl = VirtualFileUrlManager.fromUrl("file:///tmp")): SampleEntity {
return addEntity<ModifiableSampleEntity, SampleEntity>(source) {
this.booleanProperty = booleanProperty
this.stringProperty = stringProperty
this.stringListProperty = stringListProperty
this.fileProperty = fileProperty
}
}
internal fun TypedEntityStorage.singleSampleEntity() = entities(SampleEntity::class).single()
internal data class SampleEntitySource(val name: String) : EntitySource
class SimplePropertiesInProxyBasedStorageTest {
@Test
fun `add entity`() {
val builder = TypedEntityStorageBuilder.create()
val source = SampleEntitySource("test")
val entity = builder.addSampleEntity("hello", source, true, mutableListOf("one", "two"))
builder.checkConsistency()
assertTrue(entity.booleanProperty)
assertEquals("hello", entity.stringProperty)
assertEquals(listOf("one", "two"), entity.stringListProperty)
assertEquals(entity, builder.singleSampleEntity())
assertEquals(source, entity.entitySource)
}
@Test
fun `remove entity`() {
val builder = TypedEntityStorageBuilder.create()
val entity = builder.addSampleEntity("hello")
builder.removeEntity(entity)
builder.checkConsistency()
assertTrue(builder.entities(SampleEntity::class).toList().isEmpty())
}
@Test
fun `modify entity`() {
val builder = TypedEntityStorageBuilder.create()
val original = builder.addSampleEntity("hello")
val modified = builder.modifyEntity(ModifiableSampleEntity::class.java, original) {
stringProperty = "foo"
stringListProperty.add("first")
booleanProperty = true
fileProperty = VirtualFileUrlManager.fromUrl("file:///xxx")
}
builder.checkConsistency()
assertEquals("hello", original.stringProperty)
assertEquals(emptyList<String>(), original.stringListProperty)
assertEquals("foo", modified.stringProperty)
assertEquals(listOf("first"), modified.stringListProperty)
assertTrue(modified.booleanProperty)
assertEquals("file:///xxx", modified.fileProperty.url)
}
@Test
fun `edit self modifiable entity`() {
val builder = TypedEntityStorageBuilder.create()
val entity = builder.addEntity(SelfModifiableSampleEntity::class.java, SampleEntitySource("test")) {
intProperty = 42
}
assertEquals(42, entity.intProperty)
val modified = builder.modifyEntity(SelfModifiableSampleEntity::class.java, entity) {
intProperty = 239
}
builder.checkConsistency()
assertEquals(42, entity.intProperty)
assertEquals(239, modified.intProperty)
builder.removeEntity(modified)
builder.checkConsistency()
assertEquals(emptyList<SelfModifiableSampleEntity>(), builder.entities(SelfModifiableSampleEntity::class).toList())
}
@Test
fun `builder from storage`() {
val storage = TypedEntityStorageBuilder.create().apply {
addSampleEntity("hello")
}.toStorage()
storage.checkConsistency()
assertEquals("hello", storage.singleSampleEntity().stringProperty)
val builder = TypedEntityStorageBuilder.from(storage)
builder.checkConsistency()
assertEquals("hello", builder.singleSampleEntity().stringProperty)
builder.modifyEntity(ModifiableSampleEntity::class.java, builder.singleSampleEntity()) {
stringProperty = "good bye"
}
builder.checkConsistency()
assertEquals("hello", storage.singleSampleEntity().stringProperty)
assertEquals("good bye", builder.singleSampleEntity().stringProperty)
}
@Test
fun `snapshot from builder`() {
val builder = TypedEntityStorageBuilder.create()
builder.addSampleEntity("hello")
val snapshot = builder.toStorage()
snapshot.checkConsistency()
assertEquals("hello", builder.singleSampleEntity().stringProperty)
assertEquals("hello", snapshot.singleSampleEntity().stringProperty)
builder.modifyEntity(ModifiableSampleEntity::class.java, builder.singleSampleEntity()) {
stringProperty = "good bye"
}
builder.checkConsistency()
assertEquals("hello", snapshot.singleSampleEntity().stringProperty)
assertEquals("good bye", builder.singleSampleEntity().stringProperty)
}
@Test(expected = IllegalStateException::class)
fun `modifications are allowed inside special methods only`() {
val entity = TypedEntityStorageBuilder.create().addEntity(SelfModifiableSampleEntity::class.java, SampleEntitySource("test")) {
intProperty = 10
}
entity.intProperty = 30
}
@Test
fun `different entities with same properties`() {
val builder = TypedEntityStorageBuilder.create()
val foo1 = builder.addSampleEntity("foo1")
val foo2 = builder.addSampleEntity("foo1")
val bar = builder.addSampleEntity("bar")
builder.checkConsistency()
assertFalse(foo1 == foo2)
assertTrue(foo1.hasEqualProperties(foo1))
assertTrue(foo1.hasEqualProperties(foo2))
assertFalse(foo1.hasEqualProperties(bar))
val bar2 = builder.modifyEntity(ModifiableSampleEntity::class.java, bar) {
stringProperty = "bar2"
}
assertTrue(bar == bar2)
assertFalse(bar.hasEqualProperties(bar2))
val foo2a = builder.modifyEntity(ModifiableSampleEntity::class.java, foo2) {
stringProperty = "foo2"
}
assertFalse(foo1.hasEqualProperties(foo2a))
}
@Test
fun `change source`() {
val builder = TypedEntityStorageBuilder.create()
val source1 = SampleEntitySource("1")
val source2 = SampleEntitySource("2")
val foo = builder.addSampleEntity("foo", source1)
val foo2 = builder.changeSource(foo, source2)
assertEquals(source1, foo.entitySource)
assertEquals(source2, foo2.entitySource)
assertEquals(source2, builder.singleSampleEntity().entitySource)
assertEquals(foo2, builder.entitiesBySource { it == source2 }.values.flatMap { it.values.flatten() }.single())
assertTrue(builder.entitiesBySource { it == source1 }.values.all { it.isEmpty() })
}
}
@TestOnly
fun TypedEntityStorage.checkConsistency() {
val storage = this as ProxyBasedEntityStorage
storage.entitiesByType.forEach { (clazz, entities) ->
entities.forEach { assertTrue("Incorrect type key $clazz for entity of type ${it.unmodifiableEntityType}", it.unmodifiableEntityType.isAssignableFrom(clazz)) }
}
storage.entitiesBySource.forEach { (source, entities) ->
entities.forEach { assertEquals("Incorrect source key $source for entity ${it.id} with source ${it.entitySource}", source, it.entitySource) }
}
storage.entityById.forEach { (id, entity) ->
assertEquals("Incorrect id key $id for entity with id ${entity.id}", id, entity.id)
}
val allEntitiesByType = storage.entitiesByType.flatMapTo(THashSet(TObjectHashingStrategy.IDENTITY)) { it.value }
val allEntitiesBySource = storage.entitiesBySource.flatMapTo(THashSet(TObjectHashingStrategy.IDENTITY)) { it.value }
assertEquals(emptySet<TypedEntity>(), allEntitiesBySource - allEntitiesByType)
assertEquals(emptySet<TypedEntity>(), allEntitiesByType - allEntitiesBySource)
val allEntitiesByPersistentId = storage.entitiesByPersistentIdHash.flatMapTo(THashSet(TObjectHashingStrategy.IDENTITY)) { it.value }
val expectedEntitiesByPersistentId = allEntitiesByType.filterTo(THashSet(TObjectHashingStrategy.IDENTITY)) { TypedEntityWithPersistentId::class.java.isAssignableFrom((it as EntityData).unmodifiableEntityType) }
assertEquals(expectedEntitiesByPersistentId, allEntitiesByPersistentId)
storage.entitiesByPersistentIdHash.forEach { (hash, list) ->
list.forEach {
assertEquals(hash, (storage.createEntityInstance(it) as TypedEntityWithPersistentId).persistentId().hashCode())
}
}
val allEntitiesById = storage.entityById.values.toCollection(THashSet(TObjectHashingStrategy.IDENTITY))
assertEquals(emptySet<TypedEntity>(), allEntitiesBySource - allEntitiesById)
assertEquals(emptySet<TypedEntity>(), allEntitiesById - allEntitiesBySource)
val expectedReferrers = storage.entityById.values.flatMap { data ->
val result = mutableListOf<Pair<Long, Long>>()
data.collectReferences { result.add(it to data.id) }
result
}.groupBy({it.first}, {it.second})
storage.entityById.values.forEach { data ->
val expected = expectedReferrers[data.id]?.toSet()
val actual = storage.referrers[data.id]?.toSet()
assertEquals("Different referrers to $data", expected, actual)
}
val staleKeys = storage.referrers.keys - storage.entityById.keys
assertEquals(emptySet<Long>(), staleKeys)
fun assertReferrersEqual(expected: Map<Long, List<Long>>, actual: Map<Long, List<Long>>) {
assertEquals(expected.keys, actual.keys)
for (key in expected.keys) {
assertEquals(expected.getValue(key).toSet(), actual.getValue(key).toSet())
}
}
assertReferrersEqual(expectedReferrers, storage.referrers)
}
| 1
| null |
1
| 1
|
11de913f9a139f165a4aad0be4fb8160674d5240
| 10,044
|
intellij-community
|
Apache License 2.0
|
src/test/kotlin/no/nav/tilleggsstonader/sak/behandling/TestSaksbehandlingServiceTest.kt
|
navikt
| 685,490,225
| false
|
{"Kotlin": 1381580, "HTML": 33935, "Gherkin": 11030, "Shell": 924, "Dockerfile": 164}
|
package no.nav.tilleggsstonader.sak.behandling
import no.nav.tilleggsstonader.sak.IntegrationTest
import no.nav.tilleggsstonader.sak.behandling.barn.BarnRepository
import no.nav.tilleggsstonader.sak.behandling.domain.BehandlingStatus
import no.nav.tilleggsstonader.sak.behandlingsflyt.StegType
import no.nav.tilleggsstonader.sak.infrastruktur.mocks.PdlClientConfig.Companion.barn2Fnr
import no.nav.tilleggsstonader.sak.infrastruktur.mocks.PdlClientConfig.Companion.barnFnr
import no.nav.tilleggsstonader.sak.opplysninger.søknad.SøknadService
import no.nav.tilleggsstonader.sak.util.SøknadUtil
import no.nav.tilleggsstonader.sak.util.behandling
import no.nav.tilleggsstonader.sak.util.søknadBarnTilBehandlingBarn
import no.nav.tilleggsstonader.sak.vilkår.stønadsvilkår.VilkårService
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
internal class TestSaksbehandlingServiceTest() : IntegrationTest() {
@Autowired
lateinit var testSaksbehandlingService: TestSaksbehandlingService
@Autowired
lateinit var søknadService: SøknadService
@Autowired
lateinit var vilkårService: VilkårService
@Autowired
lateinit var barnRepository: BarnRepository
@Test
internal fun `skal oppfylle alle vilkår`() {
val behandling = testoppsettService.opprettBehandlingMedFagsak(
behandling(
status = BehandlingStatus.UTREDES,
steg = StegType.SEND_TIL_BESLUTTER,
),
)
val skjema = SøknadUtil.søknadskjemaBarnetilsyn(
barnMedBarnepass = listOf(
SøknadUtil.barnMedBarnepass(ident = barnFnr, navn = "navn1"),
SøknadUtil.barnMedBarnepass(ident = barn2Fnr, navn = "navn1"),
),
)
val søknad = søknadService.lagreSøknad(behandling.id, "journalpostId", skjema)
barnRepository.insertAll(søknadBarnTilBehandlingBarn(søknad.barn, behandling.id))
vilkårService.hentEllerOpprettVilkårsvurdering(behandling.id)
testSaksbehandlingService.utfyllVilkår(behandlingId = behandling.id)
assertThat(vilkårService.erAlleVilkårOppfylt(behandling.id)).isTrue
}
}
| 6
|
Kotlin
|
1
| 0
|
f6ec95a294a3a85a53b413216811453a278040b3
| 2,245
|
tilleggsstonader-sak
|
MIT License
|
app/src/main/java/pl/elpassion/elabyrinth/MainActivity.kt
|
elpassion
| 57,039,976
| false
|
{"Gradle": 5, "Java Properties": 2, "Shell": 2, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Kotlin": 13, "Proguard": 1, "Java": 2, "XML": 12}
|
package pl.elpassion.elabyrinth
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v7.app.AppCompatActivity
import android.view.*
import android.widget.ImageView
import pl.elpassion.elabyrinth.core.Direction
import pl.elpassion.elabyrinth.core.Game
import pl.elpassion.elabyrinth.core.LabyrinthSocket
import pl.elpassion.elabyrinth.core.Player
class MainActivity : AppCompatActivity() {
val labyrinth: ViewGroup by lazy { findViewById(R.id.labyrinth) as ViewGroup }
val socket by lazy { LabyrinthSocket() }
override fun onCreate(savedInstanceState: Bundle?) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState)
setContentView(R.layout.labyrinth)
socket.onGame(GameStateSavingProxy(onGame, onPlayersOnly))
findViewById(R.id.control_up).setOnClickListener { Thread { socket.move(Direction.UP) }.start() }
findViewById(R.id.control_right).setOnClickListener { Thread { socket.move(Direction.RIGHT) }.start() }
findViewById(R.id.control_left).setOnClickListener { Thread { socket.move(Direction.LEFT) }.start() }
findViewById(R.id.control_down).setOnClickListener { Thread { socket.move(Direction.DOWN) }.start() }
}
val onGame: (Game) -> Unit = { game ->
runOnUiThread({
labyrinth.removeAllViews()
game.map.forEach { row ->
val rowView = labyrinth.inflate(R.layout.row) as ViewGroup
row.forEach { cell ->
rowView.addView(rowView.inflate(cell.layoutRes))
}
labyrinth.addView(rowView)
}
game.players.forEach { player ->
val rowView = labyrinth.getChildAt(player.y) as ViewGroup
val cellView = rowView.getChildAt(player.x) as ImageView
cellView.setImageResource(player.imageResource)
}
})
}
val onPlayersOnly: (List<Player>, List<Player>) -> Unit = { old, new ->
runOnUiThread({
old.forEach { player ->
val rowView = labyrinth.getChildAt(player.y) as ViewGroup
val cellView = rowView.getChildAt(player.x) as ImageView
cellView.setImageDrawable(null)
}
new.forEach { player ->
val rowView = labyrinth.getChildAt(player.y) as ViewGroup
val cellView = rowView.getChildAt(player.x) as ImageView
cellView.setImageResource(player.imageResource)
}
})
}
}
fun ViewGroup.inflate(@LayoutRes layoutRes: Int): View {
return LayoutInflater.from(context).inflate(layoutRes, this, false)
}
| 1
| null |
1
| 1
|
72800b31ec78c22766ec9ce81e5c70c405d22708
| 2,830
|
el-abyrinth-android
|
MIT License
|
core/database/src/main/java/com/niyaj/database/model/ProductWiseOrderDto.kt
|
skniyajali
| 644,752,474
| false
|
{"Kotlin": 2028840}
|
package com.niyaj.database.model
import androidx.room.Embedded
import androidx.room.Relation
import com.niyaj.model.ProductAndQuantity
data class ProductWiseOrderDto(
@Embedded
val cartOrderEntity: CartOrderEntity,
@Relation(
parentColumn = "orderId",
entityColumn = "orderId",
entity = CartEntity::class,
projection = ["productId", "quantity"]
)
val cartItems: List<ProductAndQuantity>,
)
| 12
|
Kotlin
|
0
| 3
|
f068f418b7691ab2959e12ff6ec900c4bd92bfb5
| 445
|
PoposRoom
|
Apache License 2.0
|
save-plugins/warn-plugin/src/commonMain/kotlin/org/cqfn/save/plugin/warn/WarnPlugin.kt
|
cqfn
| 340,654,529
| false
| null |
package org.cqfn.save.plugin.warn
import org.cqfn.save.core.config.ExpectedWarningsFormat
import org.cqfn.save.core.config.TestConfig
import org.cqfn.save.core.files.createFile
import org.cqfn.save.core.files.readLines
import org.cqfn.save.core.logging.describe
import org.cqfn.save.core.logging.logDebug
import org.cqfn.save.core.logging.logWarn
import org.cqfn.save.core.plugin.ExtraFlags
import org.cqfn.save.core.plugin.ExtraFlagsExtractor
import org.cqfn.save.core.plugin.GeneralConfig
import org.cqfn.save.core.plugin.Plugin
import org.cqfn.save.core.plugin.resolvePlaceholdersFrom
import org.cqfn.save.core.result.DebugInfo
import org.cqfn.save.core.result.Fail
import org.cqfn.save.core.result.TestResult
import org.cqfn.save.core.utils.ExecutionResult
import org.cqfn.save.core.utils.ProcessExecutionException
import org.cqfn.save.core.utils.ProcessTimeoutException
import org.cqfn.save.plugin.warn.utils.ResultsChecker
import org.cqfn.save.plugin.warn.utils.Warning
import org.cqfn.save.plugin.warn.utils.collectWarningsFromSarif
import org.cqfn.save.plugin.warn.utils.collectionMultilineWarnings
import org.cqfn.save.plugin.warn.utils.collectionSingleWarnings
import org.cqfn.save.plugin.warn.utils.extractWarning
import org.cqfn.save.plugin.warn.utils.getLineNumber
import okio.FileNotFoundException
import okio.FileSystem
import okio.Path
import okio.Path.Companion.toPath
import kotlin.random.Random
private typealias WarningMap = Map<String, List<Warning>>
/**
* A plugin that runs an executable and verifies that it produces required warning messages.
* @property testConfig
*/
class WarnPlugin(
testConfig: TestConfig,
testFiles: List<String>,
fileSystem: FileSystem,
useInternalRedirections: Boolean = true,
redirectTo: Path? = null,
) : Plugin(
testConfig,
testFiles,
fileSystem,
useInternalRedirections,
redirectTo
) {
private lateinit var extraFlagsExtractor: ExtraFlagsExtractor
private lateinit var tmpDirName: String
override fun handleFiles(files: Sequence<TestFiles>): Sequence<TestResult> {
testConfig.validateAndSetDefaults()
val warnPluginConfig = testConfig.pluginConfigs.filterIsInstance<WarnPluginConfig>().single()
val generalConfig = testConfig.pluginConfigs.filterIsInstance<GeneralConfig>().single()
extraFlagsExtractor = ExtraFlagsExtractor(generalConfig, fs)
// Special trick to handle cases when tested tool is able to process directories.
// In this case instead of executing the tool with file names, we execute the tool with directories.
//
// In case, when user doesn't want to use directory mode, he needs simply not to pass [wildCardInDirectoryMode] and it will be null
return warnPluginConfig.wildCardInDirectoryMode?.let {
handleTestFile(files.map { it.test }.toList(), warnPluginConfig, generalConfig).asSequence()
} ?: run {
files.chunked(warnPluginConfig.batchSize!!.toInt()).flatMap { chunk ->
handleTestFile(chunk.map { it.test }, warnPluginConfig, generalConfig)
}
}
}
override fun rawDiscoverTestFiles(resourceDirectories: Sequence<Path>): Sequence<TestFiles> {
val warnPluginConfig = testConfig.pluginConfigs.filterIsInstance<WarnPluginConfig>().single()
val regex = warnPluginConfig.resourceNamePattern
// returned sequence is a sequence of groups of size 1
return resourceDirectories.flatMap { directory ->
fs.list(directory)
.filter { regex.matches(it.name) }
.map { Test(it) }
}
}
override fun cleanupTempDir() {
val tmpDir = (FileSystem.SYSTEM_TEMPORARY_DIRECTORY / WarnPlugin::class.simpleName!!)
if (fs.exists(tmpDir)) {
fs.deleteRecursively(tmpDir)
}
}
private fun createTestFiles(paths: List<Path>, warnPluginConfig: WarnPluginConfig): List<Path> {
logDebug("Trying to create temp files for: $paths")
tmpDirName = "${WarnPlugin::class.simpleName!!}-${Random.nextInt()}"
// don't think that it is really needed now
val dirPath = constructPathForCopyOfTestFile(tmpDirName, paths[0]).parent!!
createTempDir(dirPath)
val ignorePatterns = warnPluginConfig.ignoreLinesPatterns
return paths.map { path ->
val copyPath = constructPathForCopyOfTestFile(tmpDirName, path)
// creating the hierarchy for all files
fs.createDirectories(copyPath.parent!!)
fs.write(fs.createFile(copyPath)) {
fs.readLines(path)
.filter { line -> ignorePatterns.none { it.matches(line) } }
.map { write((it + "\n").encodeToByteArray()) }
}
copyPath
}
}
@Suppress(
"TOO_LONG_FUNCTION",
"SAY_NO_TO_VAR",
"LongMethod",
"ReturnCount",
"TOO_MANY_LINES_IN_LAMBDA",
"ComplexMethod"
)
private fun handleTestFile(
paths: List<Path>,
warnPluginConfig: WarnPluginConfig,
generalConfig: GeneralConfig
): Sequence<TestResult> {
// extracting all warnings from test resource files
val copyPaths: List<Path> = createTestFiles(paths, warnPluginConfig)
val expectedWarningsMap: WarningMap = copyPaths.zip(paths).associate { (copyPath, originalPath) ->
val warningsForCurrentPath = copyPath.collectWarningsWithLineNumbers(warnPluginConfig, generalConfig, paths, originalPath)
copyPath.name to warningsForCurrentPath
}
val extraFlagsList = copyPaths.mapNotNull { extraFlagsExtractor.extractExtraFlagsFrom(it) }.distinct()
require(extraFlagsList.size <= 1) {
"Extra flags for all files in a batch should be same, but you have batchSize=${warnPluginConfig.batchSize}" +
" and there are ${extraFlagsList.size} different sets of flags inside it, namely $extraFlagsList"
}
val extraFlags = extraFlagsList.singleOrNull() ?: ExtraFlags("", "")
if (expectedWarningsMap.isEmpty() && warnPluginConfig.expectedWarningsFormat == ExpectedWarningsFormat.IN_PLACE) {
logWarn(
"No expected warnings were found using the following regex pattern:" +
" [${generalConfig.expectedWarningsPattern}] in the test files: $paths." +
" If you have expected any warnings - please check 'expectedWarningsPattern' or capture groups" +
" in your 'save.toml' configuration"
)
} else if (expectedWarningsMap.isEmpty() && warnPluginConfig.expectedWarningsFormat == ExpectedWarningsFormat.SARIF) {
logWarn(
"No expected warnings were found when inspecting files ${warnPluginConfig.expectedWarningsFileName}" +
" for test files: $paths." +
" If you have expected any warnings - please make sure SARIF files exist, have correct name and contain" +
" relevant warnings."
)
}
// joining test files to string with a batchSeparator if the tested tool supports processing of file batches
// NOTE: SAVE will pass relative paths of Tests (calculated from testRootConfig dir) into the executed tool
val fileNamesForExecCmd =
warnPluginConfig.wildCardInDirectoryMode?.let {
// a hack to put only the root directory path to the execution command
// only in case a directory mode is enabled
var testRootPath = copyPaths[0].parent ?: ".".toPath()
while (testRootPath.parent != null && testRootPath.parent!!.name != tmpDirName) {
testRootPath = testRootPath.parent!!
}
"$testRootPath$it"
} ?: copyPaths.joinToString(separator = warnPluginConfig.batchSeparator!!)
logDebug("Constructed file name for execution for warn plugin: $fileNamesForExecCmd")
val execFlagsAdjusted = resolvePlaceholdersFrom(warnPluginConfig.execFlags, extraFlags, fileNamesForExecCmd)
val execCmd = "${generalConfig.execCmd} $execFlagsAdjusted"
val time = generalConfig.timeOutMillis!!.times(copyPaths.size)
val executionResult = try {
pb.exec(execCmd, testConfig.getRootConfig().directory.toString(), redirectTo, time)
} catch (ex: ProcessTimeoutException) {
logWarn("The following tests took too long to run and were stopped: $paths, timeout for single test: ${ex.timeoutMillis}")
return failTestResult(paths, ex, execCmd)
} catch (ex: ProcessExecutionException) {
return failTestResult(paths, ex, execCmd)
}
val stdout = getToolStdout(warnPluginConfig, executionResult)
val stderr = executionResult.stderr
val actualWarningsMap = stdout.mapNotNull {
with(warnPluginConfig) {
val line = it.getLineNumber(actualWarningsPattern!!, lineCaptureGroupOut)
it.extractWarning(
actualWarningsPattern,
fileNameCaptureGroupOut!!,
line,
columnCaptureGroupOut,
messageCaptureGroupOut!!,
benchmarkMode!!,
)
}
}
.groupBy { it.fileName }
.mapValues { (_, warning) -> warning.sortedBy { it.message } }
val resultsChecker = ResultsChecker(
expectedWarningsMap,
actualWarningsMap,
warnPluginConfig,
)
return paths.map { path ->
val results = resultsChecker.checkResults(path.name)
TestResult(
Test(path),
results.first,
DebugInfo(
execCmd,
stdout.filter { it.contains(path.name) }.joinToString("\n"),
stderr.filter { it.contains(path.name) }.joinToString("\n"),
null,
results.second,
),
)
}.asSequence()
}
@Suppress("SwallowedException")
private fun getToolStdout(
warnPluginConfig: WarnPluginConfig,
executionResult: ExecutionResult,
) = warnPluginConfig.testToolResFileOutput?.let {
val testToolResFilePath = testConfig.directory / warnPluginConfig.testToolResFileOutput
try {
fs.readLines(testToolResFilePath)
} catch (ex: FileNotFoundException) {
logWarn(
"Trying to read file \"${warnPluginConfig.testToolResFileOutput}\" that was set as an output for a tested tool with testToolResFileOutput," +
" but no such file found. Will use the stdout as an input."
)
executionResult.stdout
}
}
?: executionResult.stdout
private fun failTestResult(
paths: List<Path>,
ex: ProcessExecutionException,
execCmd: String
) = paths.map {
TestResult(
Test(it),
Fail(ex.describe(), ex.describe()),
DebugInfo(execCmd, null, ex.message, null, null),
)
}.asSequence()
/**
* method for getting warnings from test files:
* 1) reading the file
* 2) for each line get the warning
*/
@Suppress("AVOID_NULL_CHECKS")
private fun Path.collectWarningsWithLineNumbers(
warnPluginConfig: WarnPluginConfig,
generalConfig: GeneralConfig,
originalPaths: List<Path>,
originalPath: Path,
): List<Warning> = when {
warnPluginConfig.expectedWarningsFormat == ExpectedWarningsFormat.SARIF -> collectWarningsFromSarif(
warnPluginConfig,
originalPath,
originalPaths,
fs,
this
)
generalConfig.expectedWarningsEndPattern != null -> collectionMultilineWarnings(
warnPluginConfig,
generalConfig,
fs.readLines(this),
this,
)
else -> collectionSingleWarnings(
warnPluginConfig,
generalConfig,
fs.readLines(this),
this,
)
}
}
| 36
|
Kotlin
|
1
| 23
|
fb8df249f04bd2a5dab838cc12650a5f490ad3e5
| 12,374
|
save
|
MIT License
|
buildSrc/src/main/kotlin/Module.kt
|
ShabanKamell
| 283,243,423
| false
| null |
object AppModule {
const val app = ":app"
const val presentation = ":common:presentation"
const val core = ":common:core"
const val data = ":common:data"
const val bulletin = ":common:bulletin"
}
| 0
|
Kotlin
|
1
| 3
|
847ca9db8c0511a4a9b237d431ea1fc559ae43b0
| 216
|
TheMovies
|
Apache License 2.0
|
archive/src/main/kotlin/org/openrs2/archive/ArchiveCommand.kt
|
openrs2
| 315,027,372
| false
| null |
package org.openrs2.archive
import com.github.ajalt.clikt.core.NoOpCliktCommand
import com.github.ajalt.clikt.core.subcommands
import org.openrs2.archive.cache.CacheCommand
import org.openrs2.archive.client.ClientCommand
import org.openrs2.archive.key.KeyCommand
import org.openrs2.archive.name.NameCommand
import org.openrs2.archive.web.WebCommand
public fun main(args: Array<String>): Unit = ArchiveCommand().main(args)
public class ArchiveCommand : NoOpCliktCommand(name = "archive") {
init {
subcommands(
CacheCommand(),
ClientCommand(),
KeyCommand(),
NameCommand(),
WebCommand()
)
}
}
| 56
|
Kotlin
|
2
| 8
|
12eba96055ba13e8a8e3ec0ad3be7d93b3dd5b1b
| 677
|
openrs2
|
ISC License
|
kotlite-kapt/src/main/kotlin/kotlite/kapt/sqlite/repository/models.kt
|
mfarsikov
| 322,536,930
| false
| null |
package kotlite.kapt.sqlite.repository
import kotlite.aux.SqliteType
import kotlite.kapt.common.Pagination
import kotlite.kapt.model.db.TableMapping
import kotlite.kapt.model.klass.Klass
import kotlite.kapt.model.klass.QualifiedName
import kotlite.kapt.model.klass.Type
import kotlite.kapt.parser.KotlinType
data class Repo(
val superKlass: Klass,
val queryMethods: List<QueryMethod>,
val mappedKlass: TableMapping?,
val belongsToDb: QualifiedName,
)
data class QueryMethod(
val name: String,
val query: String,
val queryMethodParameters: List<QueryMethodParameter>,
val queryParameters: List<QueryParameter>,
val returnType: Type, //TODO remove?
val trueReturnType: Type,
val returnsCollection: Boolean,
val objectConstructor: ObjectConstructor?,
val returnsScalar: Boolean = false,
val pagination: Pagination?,
val type: QueryMethodType = QueryMethodType.SINGLE,
val orderParameterName: String? = null,
val optimisticallyLocked: Boolean,
val isStatement: Boolean = false,
)
enum class QueryMethodType { SINGLE, BATCH }
data class QueryMethodParameter(
val name: String,
val type: Type,
)
data class QueryParameter(
val positionInQuery: Int,
val kotlinType: Type,
val setterName: String,
val path: String,
val isJson: Boolean,
val isEnum: Boolean,
val isINClause: Boolean,
val SqliteType: SqliteType,
)
sealed class ObjectConstructor {
data class Constructor(
val fieldName: String?,
val className: QualifiedName,
val nestedFields: List<ObjectConstructor>,
) : ObjectConstructor()
data class Extractor(
val resultSetGetterName: String, //TODO remove in favor of kotlinType?
val columnName: String,
val fieldName: String?,
val fieldType: QualifiedName, //TODO remove in favor of kotlinType?
val isJson: Boolean,
val isEnum: Boolean,
val isPrimitive: Boolean,
val isNullable: Boolean,
val kotlinType: KotlinType?,
) : ObjectConstructor()
}
| 0
|
Kotlin
|
1
| 5
|
0f5eb9c801b9af4217c0203b7f0028edc6a0b941
| 2,071
|
kotlite
|
Apache License 2.0
|
bars/src/main/java/kekmech/ru/bars/rights/RightsFragmentView.kt
|
NuvaltsevAA
| 249,189,732
| true
|
{"Kotlin": 355287, "Shell": 46}
|
package kekmech.ru.bars.rights
import androidx.lifecycle.LifecycleOwner
interface RightsFragmentView : LifecycleOwner
| 0
| null |
0
| 0
|
94bd394725e495a13f818e94f674a5353dd29bcb
| 119
|
mpeiapp
|
MIT License
|
presentation/src/main/java/com/fredprojects/helloworld/presentation/features/jumps/JDCustomViews.kt
|
FredNekrasov
| 832,214,231
| false
| null |
package com.fredprojects.helloworld.presentation.features.jumps
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.fredprojects.helloworld.presentation.R
import com.fredprojects.helloworld.domain.core.utils.SortType
import com.fredprojects.helloworld.presentation.core.Action
import com.fredprojects.helloworld.presentation.core.FredRadioButton
@Composable
internal fun JDSortingSection(
sortType: SortType,
onSortingChange: (SortType) -> Unit
) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {
FredRadioButton(stringResource(R.string.ascendingSort), sortType is SortType.Ascending) { onSortingChange(SortType.Ascending) }
FredRadioButton(stringResource(R.string.descendingSort), sortType is SortType.Descending) { onSortingChange(SortType.Descending) }
}
}
@Composable
internal fun JDIconButton(onClick: Action, icon: ImageVector) {
IconButton(
onClick,
Modifier.padding(4.dp).border(2.dp, MaterialTheme.colors.onBackground, MaterialTheme.shapes.small)
) {
Icon(icon, icon.toString())
}
}
| 0
| null |
0
| 1
|
b91002f5a2a07e6373bb30f424a72cd411886704
| 1,473
|
jetpack-compose-projects
|
MIT License
|
app/src/main/java/jp/kuluna/eventgridview/sample/MainActivity.kt
|
Qixingchen
| 140,923,408
| false
| null |
package jp.kuluna.eventgridview.sample
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import jp.kuluna.eventgridview.Event
import jp.kuluna.eventgridview.EventGridAdapter
import jp.kuluna.eventgridview.sample.databinding.ActivityMainBinding
import java.util.*
class MainActivity : AppCompatActivity() {
private lateinit var adapter: EventGridAdapter
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
adapter = EventGridAdapter(this)
binding.eventGridView.adapter = adapter
binding.eventGridView.hourHeight = 60
binding.eventGridView.titleHeight = 40
binding.eventGridView.groupWidth = 40
binding.eventGridView.post {
binding.eventGridView.eventGridView.scrollToHour(6)
}
showEvents()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.reloadButton -> {
showEvents()
}
}
return true
}
private fun showEvents() {
binding.eventGridView.groupWidth = Random().nextInt(40) + 40
Toast.makeText(this, binding.eventGridView.groupWidth.toString(), Toast.LENGTH_LONG).show()
val period = 3
val startedAt = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 11)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
}.time
val endedAt = Calendar.getInstance().apply {
time = startedAt
add(Calendar.HOUR_OF_DAY, period)
}.time
val gridColor = ContextCompat.getColor(this, android.R.color.holo_blue_light)
val blackColor = ContextCompat.getColor(this, android.R.color.black)
val events: List<Event> = ArrayList<Event>().apply {
add(Event(
0,
"1",
startedAt,
endedAt,
"ドラッグ不可",
gridColor,
blackColor,
null,
null,
false))
add(Event(
1,
"2",
startedAt,
endedAt,
"ドラッグ可",
gridColor,
blackColor,
null,
null,
true))
}
binding.eventGridView.eventGridView.replace(events, Date())
}
}
| 1
| null |
1
| 1
|
a7d41e1f87944b4d66727845c11f9adfec63532e
| 2,982
|
EventGridView
|
MIT License
|
app/src/main/java/eu/ottop/yamlauncher/AppActionMenu.kt
|
ottop
| 841,162,872
| false
|
{"Kotlin": 112163}
|
package eu.ottop.yamlauncher
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.LauncherActivityInfo
import android.content.pm.LauncherApps
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.os.UserHandle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatButton
import androidx.lifecycle.lifecycleScope
import eu.ottop.yamlauncher.databinding.ActivityMainBinding
import eu.ottop.yamlauncher.settings.SharedPreferenceManager
import eu.ottop.yamlauncher.utils.Animations
import kotlinx.coroutines.launch
class AppActionMenu {
fun setActionListeners(
activity: MainActivity,
binding: ActivityMainBinding,
textView: TextView,
editLayout: LinearLayout,
actionMenu: View,
searchView: EditText,
appInfo: ApplicationInfo,
userHandle: UserHandle,
workProfile: Int,
launcherApps: LauncherApps,
appActivity: LauncherActivityInfo?
){
val animations = Animations(activity)
val sharedPreferenceManager = SharedPreferenceManager(activity)
actionMenu.findViewById<TextView>(R.id.info).setOnClickListener {
// Launch app info in phone settings
if (appActivity != null) {
launcherApps.startAppDetailsActivity(
appActivity.componentName,
userHandle,
null,
null
)
}
animations.fadeViewOut(actionMenu)
textView.visibility = View.VISIBLE
}
actionMenu.findViewById<TextView>(R.id.uninstall).setOnClickListener {
val intent = Intent(Intent.ACTION_DELETE)
intent.data = Uri.parse("package:${appInfo.packageName}")
intent.putExtra(Intent.EXTRA_USER, userHandle)
activity.startActivity(intent)
animations.fadeViewOut(actionMenu)
textView.visibility = View.VISIBLE
}
actionMenu.findViewById<TextView>(R.id.rename).setOnClickListener {
textView.visibility = View.INVISIBLE
animations.fadeViewIn(editLayout)
animations.fadeViewOut(actionMenu)
val editText = editLayout.findViewById<EditText>(R.id.appNameEdit)
val resetButton = editLayout.findViewById<AppCompatButton>(R.id.reset)
val app = Triple(appActivity!!, userHandle, workProfile)
searchView.visibility = View.INVISIBLE
editText.requestFocus()
// Open keyboard
val handler = Handler(Looper.getMainLooper())
handler.postDelayed({
val imm =
activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
}, 100)
binding.root.addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom ->
// If the keyboard is closed, exit editing mode
if (bottom - top > oldBottom - oldTop) {
editLayout.clearFocus()
animations.fadeViewOut(editLayout)
textView.visibility = View.VISIBLE
searchView.visibility = View.VISIBLE
}
}
editText.setOnEditorActionListener { _, actionId, _ ->
// Once the new name is confirmed, close the keyboard, save the new app name and update the apps on screen
if (actionId == EditorInfo.IME_ACTION_DONE) {
val imm =
activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(editText.windowToken, 0)
sharedPreferenceManager.setAppName(
appInfo.packageName,
workProfile,
editText.text.toString()
)
activity.lifecycleScope.launch {
activity.applySearch()
}
return@setOnEditorActionListener true
}
false
}
resetButton.setOnClickListener {
// If reset is pressed, close keyboard, remove saved edited name and update the apps on screen
val imm =
activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(editLayout.windowToken, 0)
sharedPreferenceManager.resetAppName(
app.first.applicationInfo.packageName,
app.third
)
activity.lifecycleScope.launch {
activity.applySearch()
}
}
}
actionMenu.findViewById<TextView>(R.id.hide).setOnClickListener {
editLayout.visibility = View.GONE
textView.visibility = View.GONE
actionMenu.visibility = View.GONE
activity.lifecycleScope.launch {
sharedPreferenceManager.setAppHidden(appInfo.packageName, workProfile, true)
activity.refreshAppMenu()
}
}
actionMenu.findViewById<TextView>(R.id.close).setOnClickListener {
animations.fadeViewOut(actionMenu)
textView.visibility = View.VISIBLE
}
}
}
| 0
|
Kotlin
|
0
| 1
|
84c37734c9ae4a2a0123814ca78e74b094d81cca
| 5,767
|
yam_launcher
|
MIT License
|
src/main/polkauction/core/model/dto/sidecar/FundInfoDto.kt
|
CrommVardek
| 366,623,025
| false
| null |
package polkauction.core.model.dto.sidecar
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import kotlinx.serialization.Serializable
@Serializable
@JsonIgnoreProperties(ignoreUnknown = true)
data class FundInfoDto(val depositor: String, val verifier: VerifierDto?, val deposit: String, val raised: String,
val end: String, val cap: String, val firstPeriod: String, val lastPeriod: String, val trieIndex: String)
| 0
| null |
2
| 2
|
58edc8e99c8cd148100497142af3f831664d796a
| 450
|
polk-auction-core
|
Apache License 2.0
|
repository/SoundRepository.kt
|
abhinavsingh1998
| 852,891,458
| false
|
{"Kotlin": 79019}
|
package com.example.soundmixer.repository
import androidx.lifecycle.LiveData
import com.example.soundmixer.data_base.Recording
import com.example.soundmixer.data_base.RecordingDao
import com.example.soundmixer.features.search.data_models.FileDetailsResponse
import com.example.soundmixer.features.search.data_models.SearchResponse
import com.example.soundmixer.network.ApiService
import com.example.soundmixer.network.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import retrofit2.Response
import java.io.File
class SoundRepository (private val dao: RecordingDao){
private val apiService: ApiService = RetrofitClient.instance.create(ApiService::class.java)
// Function to search for sounds based on a query
suspend fun searchSound(query: String): Response<SearchResponse> {
return apiService.searchSounds(query = "$query+sounds")
}
// Function to fetch file details, including the download URL
suspend fun fetchFileDetails(fileName: String): Response<FileDetailsResponse>? {
return try {
val response = apiService.getFileDetails(titles = fileName)
if (response.isSuccessful) {
response
} else {
// Handle error case appropriately (e.g., log the error)
null
}
} catch (e: Exception) {
// Handle the exception (e.g., log it or show a user-friendly message)
null
}
}
// Function to download the file and save metadata to Room DB
suspend fun downloadAndSaveFile(fileUrl: String, fileName: String): Boolean {
return try {
val request = Request.Builder()
.url(fileUrl)
.build()
val response = OkHttpClient().newCall(request).execute()
if (response.isSuccessful) {
val fileBytes = response.body?.bytes()
if (fileBytes != null) {
// Save the file locally
val localPath = saveFileLocally(fileBytes, fileName)
// Save file metadata in Room DB
val downloadedFile = Recording (
fileName = fileName,
filePath = localPath.toString()
)
dao.insert(downloadedFile)
true
} else {
false
}
} else {
false
}
} catch (e: Exception) {
// Handle the exception (e.g., log it)
false
}
}
fun getAllRecordings(): LiveData<List<Recording>> = dao.getAllRecordedFiles()
// Function to save the downloaded file locally
private fun saveFileLocally(fileBytes: ByteArray, fileName: String) {
val file = File("path/to/save/directory", fileName)
file.outputStream().use { outputStream ->
outputStream.write(fileBytes)
}
}
suspend fun insert(recording: Recording) {
dao.insert(recording)
}
suspend fun deleteById(fileId: Int) {
withContext(Dispatchers.IO) {
dao.deleteById(fileId)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
705ee5c477735d25557797f3916e338497cdc64c
| 3,290
|
Sound_mixer
|
MIT License
|
NavigationAdvancedSample/app/src/main/java/com/example/android/navigationadvancedsample/login/LoginFragment.kt
|
solidogen
| 402,474,910
| true
|
{"Kotlin": 521042, "Java": 240380, "Shell": 2978, "RenderScript": 2642}
|
package com.example.android.navigationadvancedsample.login
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.android.navigationadvancedsample.R
import com.example.android.navigationadvancedsample.databinding.FragmentLoginBinding
import kotlin.random.Random
class LoginFragment : Fragment() {
private var _binding: FragmentLoginBinding? = null
private val binding: FragmentLoginBinding get() = _binding!!
private val myId = Random.nextInt()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = FragmentLoginBinding.inflate(inflater, container, false)
.also { _binding = it }.root
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.loginLabel.text = "${binding.loginLabel.text} $myId"
binding.loginButton.setOnClickListener { findNavController().navigate(R.id.action_go_to_home) }
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 1
|
78a25703d73394fa54fe82909aaf52173ee0a0af
| 1,225
|
architecture-components-samples
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/codepipeline/actions/CodeCommitSourceActionDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.codepipeline.actions
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.codepipeline.actions.CodeCommitSourceAction
@Generated
public fun buildCodeCommitSourceAction(initializer: @AwsCdkDsl
CodeCommitSourceAction.Builder.() -> Unit): CodeCommitSourceAction =
CodeCommitSourceAction.Builder.create().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
a1cf8fbfdfef9550b3936de2f864543edb76348b
| 465
|
aws-cdk-kt
|
Apache License 2.0
|
native/commonizer/tests/org/jetbrains/kotlin/descriptors/commonizer/core/RootCommonizerTest.kt
|
kozaxinan
| 333,718,537
| false
| null |
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.descriptors.commonizer.core
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.jvm.JvmBuiltIns
import org.jetbrains.kotlin.builtins.konan.KonanBuiltIns
import org.jetbrains.kotlin.descriptors.commonizer.LeafTarget
import org.jetbrains.kotlin.descriptors.commonizer.SharedTarget
import org.jetbrains.kotlin.descriptors.commonizer.Target
import org.jetbrains.kotlin.descriptors.commonizer.cir.CirRoot
import org.jetbrains.kotlin.descriptors.commonizer.cir.factory.CirRootFactory
import org.jetbrains.kotlin.descriptors.commonizer.utils.MockBuiltInsProvider
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.junit.Test
class RootCommonizerTest : AbstractCommonizerTest<CirRoot, CirRoot>() {
@Test
fun allAreNative() = doTestSuccess(
expected = KONAN_BUILT_INS.toMock(
SharedTarget(
setOf(
LeafTarget("ios_x64", KonanTarget.IOS_X64),
LeafTarget("ios_arm64", KonanTarget.IOS_ARM64),
LeafTarget("ios_arm32", KonanTarget.IOS_ARM32)
)
)
),
KONAN_BUILT_INS.toMock(LeafTarget("ios_x64", KonanTarget.IOS_X64)),
KONAN_BUILT_INS.toMock(LeafTarget("ios_arm64", KonanTarget.IOS_ARM64)),
KONAN_BUILT_INS.toMock(LeafTarget("ios_arm32", KonanTarget.IOS_ARM32))
)
@Test
fun jvmAndNative1() = doTestSuccess(
expected = DEFAULT_BUILT_INS.toMock(
SharedTarget(
setOf(
LeafTarget("jvm1"),
LeafTarget("ios_x64", KonanTarget.IOS_X64),
LeafTarget("jvm2")
)
)
),
JVM_BUILT_INS.toMock(LeafTarget("jvm1")),
KONAN_BUILT_INS.toMock(LeafTarget("ios_x64", KonanTarget.IOS_X64)),
JVM_BUILT_INS.toMock(LeafTarget("jvm2"))
)
@Test
fun jvmAndNative2() = doTestSuccess(
expected = DEFAULT_BUILT_INS.toMock(
SharedTarget(
setOf(
LeafTarget("ios_x64", KonanTarget.IOS_X64),
LeafTarget("jvm"),
LeafTarget("ios_arm64", KonanTarget.IOS_ARM64)
)
)
),
KONAN_BUILT_INS.toMock(LeafTarget("ios_x64", KonanTarget.IOS_X64)),
JVM_BUILT_INS.toMock(LeafTarget("jvm")),
KONAN_BUILT_INS.toMock(LeafTarget("ios_arm64", KonanTarget.IOS_ARM64))
)
@Test
fun noNative1() = doTestSuccess(
expected = DEFAULT_BUILT_INS.toMock(
SharedTarget(
setOf(
LeafTarget("default1"),
LeafTarget("default2"),
LeafTarget("default3")
)
)
),
DEFAULT_BUILT_INS.toMock(LeafTarget("default1")),
DEFAULT_BUILT_INS.toMock(LeafTarget("default2")),
DEFAULT_BUILT_INS.toMock(LeafTarget("default3"))
)
@Test
fun noNative2() = doTestSuccess(
expected = DEFAULT_BUILT_INS.toMock(
SharedTarget(
setOf(
LeafTarget("jvm1"),
LeafTarget("default"),
LeafTarget("jvm2")
)
)
),
JVM_BUILT_INS.toMock(LeafTarget("jvm1")),
DEFAULT_BUILT_INS.toMock(LeafTarget("default")),
JVM_BUILT_INS.toMock(LeafTarget("jvm2"))
)
@Test
fun noNative3() = doTestSuccess(
expected = DEFAULT_BUILT_INS.toMock(
SharedTarget(
setOf(
LeafTarget("jvm1"),
LeafTarget("jvm2"),
LeafTarget("jvm3")
)
)
),
JVM_BUILT_INS.toMock(LeafTarget("jvm1")),
JVM_BUILT_INS.toMock(LeafTarget("jvm2")),
JVM_BUILT_INS.toMock(LeafTarget("jvm3"))
)
@Test(expected = IllegalStateException::class)
fun misconfiguration1() = doTestSuccess(
expected = KONAN_BUILT_INS.toMock(
SharedTarget(
setOf(
LeafTarget("ios_x64", KonanTarget.IOS_X64),
LeafTarget("ios_arm64", KonanTarget.IOS_ARM64),
LeafTarget("ios_arm32", KonanTarget.IOS_ARM32)
)
)
),
KONAN_BUILT_INS.toMock(LeafTarget("ios_x64")),
KONAN_BUILT_INS.toMock(LeafTarget("ios_arm64", KonanTarget.IOS_ARM64)),
KONAN_BUILT_INS.toMock(LeafTarget("ios_arm32", KonanTarget.IOS_ARM32))
)
@Test(expected = IllegalStateException::class)
fun misconfiguration2() = doTestSuccess(
expected = DEFAULT_BUILT_INS.toMock(
SharedTarget(
setOf(
LeafTarget("jvm1"),
LeafTarget("jvm2"),
LeafTarget("jvm3")
)
)
),
JVM_BUILT_INS.toMock(LeafTarget("jvm1", KonanTarget.IOS_X64)),
JVM_BUILT_INS.toMock(LeafTarget("jvm2")),
JVM_BUILT_INS.toMock(LeafTarget("jvm3"))
)
override fun createCommonizer() = RootCommonizer()
override fun isEqual(a: CirRoot?, b: CirRoot?) =
(a === b)
|| (a != null && b != null
&& a.target == b.target
&& a.builtInsClass == b.builtInsClass
&& a.builtInsClass == a.builtInsProvider.loadBuiltIns()::class.java.name
&& a.builtInsProvider.loadBuiltIns()::class.java == b.builtInsProvider.loadBuiltIns()::class.java)
private companion object {
inline val KONAN_BUILT_INS get() = KonanBuiltIns(LockBasedStorageManager.NO_LOCKS)
inline val JVM_BUILT_INS get() = JvmBuiltIns(LockBasedStorageManager.NO_LOCKS, JvmBuiltIns.Kind.FROM_CLASS_LOADER)
inline val DEFAULT_BUILT_INS get() = DefaultBuiltIns.Instance
fun KotlinBuiltIns.toMock(target: Target) = CirRootFactory.create(
target = target,
builtInsClass = this::class.java.name,
builtInsProvider = MockBuiltInsProvider(this)
)
}
}
| 1
| null |
1
| 1
|
f49cf2d5cabf8fb9833ec95e1151a00b8b53d087
| 6,422
|
kotlin
|
Apache License 2.0
|
app/src/main/kotlin/tech/hombre/bluetoothchatter/data/database/ChatDatabase.kt
|
HombreTech
| 470,059,579
| false
| null |
package tech.hombre.bluetoothchatter.data.database
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import tech.hombre.bluetoothchatter.data.entity.ChatMessage
import tech.hombre.bluetoothchatter.data.entity.Conversation
@Database(entities = [(ChatMessage::class), (Conversation::class)], version = 3)
@TypeConverters(Converter::class)
abstract class ChatDatabase: RoomDatabase() {
abstract fun conversationsDao(): ConversationsDao
abstract fun messagesDao(): MessagesDao
}
| 1
| null |
0
| 1
|
772d1d260a471ff2b4221a96c365d58ea05ef10f
| 535
|
BluetoothChat
|
Apache License 2.0
|
app/src/main/java/com/developers/currency_exchange/domain/repository/BalanceChanger.kt
|
KyrBabenko
| 734,741,533
| false
|
{"Kotlin": 60955}
|
package com.developers.currency_exchange.domain.repository
import java.math.BigDecimal
interface BalanceChanger {
suspend fun doTransaction(
sell: String,
sellAmount: BigDecimal,
receive: String,
receiveAmount: BigDecimal
)
}
| 0
|
Kotlin
|
0
| 0
|
a13936bbc901e391561dcbc179fac89d21ab7b00
| 268
|
currency_converter
|
Apache License 2.0
|
app/src/main/java/du/ducs/thoughtboard/MessageViewModel.kt
|
joshidipesh12
| 443,542,898
| false
|
{"Kotlin": 46606}
|
package du.ducs.messageboard
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.DocumentChange
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.firestore.ktx.toObject
import com.google.firebase.ktx.Firebase
import du.ducs.messageboard.model.Message
import java.util.*
class MessageViewModel : ViewModel() {
val user = Firebase.auth.currentUser
private val db = Firebase.firestore
// Instance of the current logged-in user, if any.
val currentUser: FirebaseUser?
get() = user
private val _newMessages = MutableLiveData<MutableList<Message>>()
// observe this variable to get new message updates
val newMessages: LiveData<MutableList<Message>>
get() = _newMessages
fun sendMessage(message: String) {
// Create message object from user information and provided values.
if(user?.email?.isNotBlank() == true){
val msg = Message(
message = message,
userId = user.displayName, emailId = user.email
)
db.collection(COLLECTION)
.add(msg.toHashMap())
.addOnSuccessListener { documentReference ->
Log.d(TAG, "Document added with ID: ${documentReference.id}")
}
.addOnFailureListener { e -> Log.d(TAG, "Error adding document", e) }
}
}
fun deleteMessage(msgId: String) {
db.collection(COLLECTION).document(msgId).delete()
.addOnSuccessListener { Log.d(TAG, "Document successfully deleted!") }
.addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) }
}
fun initMessages(msgCount: Int) {
db.collection(COLLECTION)
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(msgCount.toLong())
.addSnapshotListener { snapshot, e ->
if (e != null) {
Log.d(TAG, "listen failed", e)
return@addSnapshotListener
}
val newMessageList = mutableListOf<Message>()
for (doc in snapshot!!.documentChanges) {
if (doc.type == DocumentChange.Type.ADDED) {
val message = doc.document.toObject<Message>()
message.id = doc.document.id
newMessageList.add(message)
}
}
_newMessages.value = newMessageList
Log.d(TAG, "Messages: ${_newMessages.value}")
}
}
private fun getDayTwoTimeStamp(calendar: Calendar): Long {
val newCalendar = calendar.clone() as Calendar
newCalendar.add(Calendar.DATE,1)
Log.d(TAG, "Time 2: ${newCalendar.timeInMillis}")
return newCalendar.timeInMillis
}
private fun getDayOneTimeStamp(calendar: Calendar): Long {
Log.d(TAG, "Time 1: ${calendar.timeInMillis}")
return calendar.timeInMillis
}
companion object {
const val TAG = "MessageViewModel"
const val COLLECTION = "messages"
}
}
| 0
|
Kotlin
|
11
| 5
|
57fd2b2ee866aa0a464093f501295a80521a2b4f
| 3,364
|
ThoughtBoard-DUCS
|
MIT License
|
adaptive-lib-auto/src/commonTest/kotlin/fun/adaptive/auto/internal/frontend/FileFrontendTest.kt
|
spxbhuhb
| 788,711,010
| false
|
{"Kotlin": 2318583, "Java": 24560, "HTML": 7875, "JavaScript": 3880, "Shell": 687}
|
package `fun`.adaptive.auto.internal.frontend
import `fun`.adaptive.auto.PropertyTestSetup
import `fun`.adaptive.auto.backend.TestData
import `fun`.adaptive.utility.ensureTestPath
import `fun`.adaptive.utility.testPath
import `fun`.adaptive.utility.waitForReal
import kotlinx.coroutines.test.runTest
import kotlinx.io.files.Path
import kotlinx.io.files.SystemFileSystem
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.Duration.Companion.seconds
class FileFrontendTest {
@Test
fun fromOrigin() {
ensureTestPath()
val path = Path(testPath, "FileFrontendTest.fromOrigin.json")
val testData = TestData(12, "ab")
runTest {
SystemFileSystem.delete(path, mustExist = false)
with(PropertyTestSetup(testData)) {
val f1 = AdatClassFrontend(b1, wireFormat, testData, null, null, null).also { b1.frontEnd = it }
b2.frontEnd = FileFrontend(b2, wireFormat, null, null, null, null, json, path)
connect()
waitForReal(2.seconds) { SystemFileSystem.exists(path) }
fun read() = FileFrontend.read(path, json).second as TestData
assertEquals(testData, read())
f1.modify("i", 23)
assertEquals(TestData(23, "ab"), read())
f1.modify("i", 34)
assertEquals(TestData(34, "ab"), read())
f1.modify("s", "bc")
assertEquals(TestData(34, "bc"), read())
}
}
}
}
| 35
|
Kotlin
|
0
| 3
|
e7d8bb8682a6399675bc75d2976b862268d20fb5
| 1,585
|
adaptive
|
Apache License 2.0
|
app/src/main/java/com/jamesjmtaylor/blecompose/Scanning/PermissionView.kt
|
jamesjmtaylor
| 124,570,579
| false
| null |
package com.jamesjmtaylor.blecompose.Scanning
import android.content.Context
import android.content.pm.PackageManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.*
import androidx.core.content.ContextCompat
import timber.log.Timber
@Composable
fun PermissionView(context: Context, permissions: List<String>, onPermissionGranted: () -> Unit, onPermissionDenied: () -> Unit) {
val permissionsGranted = permissions.map {
val granted = (ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED)
Timber.d("$it permission already granted: $granted")
return@map granted
}.reduce { p1, p2 -> p1 && p2 }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { results ->
val allGranted = results.map {
Timber.d("${it.key} permission granted: ${it.value}")
it.value
}.reduce { p1, p2 -> p1 && p2 }
if (allGranted) onPermissionGranted()
else onPermissionDenied()
}
if (permissionsGranted) onPermissionGranted()
else SideEffect { launcher.launch(permissions.toTypedArray()) }
}
| 0
|
Kotlin
|
0
| 0
|
4f578c5ffbcab4919d561e5b235f58802652e75e
| 1,270
|
BLE-aOS
|
Apache License 2.0
|
src/main/kotlin/personalchallenges/RandomSelector.kt
|
saishaddai
| 840,608,325
| false
|
{"Kotlin": 44825}
|
package com.saishaddai.personalchallenges
import kotlin.random.Random.Default.nextInt
/**
* This is the whole logic of random selector
* The idea behind is to select random lines of random files.
*
* Files: Name of files available in a local data system
* each file as the Total Number of Lines (not blanks) in it
* Selections: A list of File names and the list of independent
* lines to retrieve from each file.
*
* Size: the number of total lines to retrieve. This is independent of
* the number of files. This number is provided by the user
* but at the same time, it is the sum of all the lines from all the selections
* Priorities: We randomly select how many lines we will retrieve of each file.
* For example
* File1, 3 lines to retrieve
* File2, 4 lines to retrieve
* File3, 2 lines to retrieve
* File4, 1 line to retrieve
*
* Again, notice that the sum of this example (10) must coincide with the size
* parameter in the method in getSelections method
*
*/
class RandomSelector {
data class Item(val fileName: String, val totalLines: Int)
data class Selection(val fileName: String, val questionLines : List<Int>)
fun getSelections(size: Int, list: List<Item>) : List<Selection>{
if(size <= 0) return emptyList()
// val priorities : Map<Item, Int> =
// throwDices(list.size)
// .getNumberOfPicksPerFile()
// priorities.forEach{priority ->
// priority.key.
// }
return emptyList()
}
fun throwDices(dices : Int) : List<Int> {
val validDices : Int = if(dices < 0) 0 else dices
return List(validDices) { nextInt(1, 6) }
}
// fun getPriorityMap(diceValues : List<Int>) {
//get sum of all the values in the dices
//iterate the list
//for each dice item, get its value with the following formula
//numberOfPicks = round( (itemValue * size ) / sum)
//with this value set an entry of the map: Filename to numberOfPicks
// 6+5 = 11 = 100%
// 6 -> (6*20)/11 = 10.9
// 5 -> (5*20)/11 = 9.09
// }
fun getNumberOfPicks(diceValue : Int, size : Int, sum: Int) =
Math.round(((diceValue * size ) / sum).toDouble()).toInt()
fun compensateValues(map: MutableMap<String, Int>, size: Int) : MutableMap<String, Int> {
//get sum of all the values of the map -> sumValues
val sum = map.values.sum()
//get distance between sumValues and size -> alpha
val alpha = size - sum
if (alpha == 0) {
return map
} else {
//get the minimum map entry with minimum value and add the alpha to it.
val minValue = map.values.min()
val key = map.filterValues { it == minValue }.keys.firstOrNull()
key?.let {
val newValue = map[key]?.plus(alpha)
newValue?.let {
map[key] = it
}
}
}
return map
}
fun itemToSelection(item: Item, picks: Int): Selection {
val selectedLines = mutableListOf<Int>()
repeat(picks) {
selectedLines.add(nextInt(item.totalLines))
}
return Selection(item.fileName, selectedLines)
}
}
| 0
|
Kotlin
|
0
| 0
|
9b5ab0e9d32e8a3db4aee00e58a9c203c7e0f122
| 3,262
|
KotlinChallenges
|
MIT License
|
platform/workspace/storage/testEntities/testSrc/com/intellij/platform/workspace/storage/testEntities/entities/ParentAndChildWithNulls.kt
|
ingokegel
| 72,937,917
| false
| null |
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.platform.workspace.storage.testEntities.entities
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
import kotlin.jvm.JvmStatic
import com.intellij.platform.workspace.storage.annotations.Child
import com.intellij.platform.workspace.storage.EntityType
import com.intellij.platform.workspace.storage.EntitySource
import com.intellij.platform.workspace.storage.GeneratedCodeApiVersion
import com.intellij.platform.workspace.storage.MutableEntityStorage
import com.intellij.platform.workspace.storage.WorkspaceEntity
interface ParentWithNulls : WorkspaceEntity {
val parentData: String
@Child
val child: ChildWithNulls?
//region generated code
@GeneratedCodeApiVersion(2)
interface Builder : ParentWithNulls, WorkspaceEntity.Builder<ParentWithNulls> {
override var entitySource: EntitySource
override var parentData: String
override var child: ChildWithNulls?
}
companion object : EntityType<ParentWithNulls, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(parentData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ParentWithNulls {
val builder = builder()
builder.parentData = parentData
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ParentWithNulls,
modification: ParentWithNulls.Builder.() -> Unit): ParentWithNulls = modifyEntity(
ParentWithNulls.Builder::class.java, entity, modification)
//endregion
interface ChildWithNulls : WorkspaceEntity {
val childData: String
//region generated code
@GeneratedCodeApiVersion(2)
interface Builder : ChildWithNulls, WorkspaceEntity.Builder<ChildWithNulls> {
override var entitySource: EntitySource
override var childData: String
}
companion object : EntityType<ChildWithNulls, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(childData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ChildWithNulls {
val builder = builder()
builder.childData = childData
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ChildWithNulls,
modification: ChildWithNulls.Builder.() -> Unit): ChildWithNulls = modifyEntity(
ChildWithNulls.Builder::class.java, entity, modification)
var ChildWithNulls.Builder.parentEntity: ParentWithNulls?
by WorkspaceEntity.extension()
//endregion
val ChildWithNulls.parentEntity: ParentWithNulls?
by WorkspaceEntity.extension()
| 249
| null |
5023
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 2,926
|
intellij-community
|
Apache License 2.0
|
wire-tests/src/commonTest/kotlin/com/squareup/wire/KotlinMapTest.kt
|
square
| 12,274,147
| false
| null |
/*
* Copyright 2018 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import com.squareup.wire.protos.kotlin.map.Mappy
import com.squareup.wire.protos.kotlin.map.Thing
import okio.ByteString
import okio.ByteString.Companion.decodeHex
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.fail
class KotlinMapTest {
private val adapter = Mappy.ADAPTER
@Test fun serialize() {
assertEquals(BYTES, ByteString.of(*adapter.encode(THREE)))
assertEquals(0, adapter.encode(EMPTY).size)
}
@Test fun deserialize() {
assertEquals(THREE, adapter.decode(BYTES))
val empty = adapter.decode(ByteArray(0))
assertNotNull(empty.things)
}
@IgnoreJs
@IgnoreNative
@Test fun mapsAreImmutable() {
val map = mutableMapOf("one" to Thing("One"))
val mappy = Mappy(things = map)
try {
(mappy.things as MutableMap<*, *>).clear()
fail()
} catch (_: UnsupportedOperationException) {
// Mutation failed as expected.
}
// Mutate the values used to create the map. Wire should have defensive copies.
map.clear()
assertEquals(mapOf("one" to Thing("One")), mappy.things)
}
companion object {
private val BYTES =
"0a0c0a036f6e6512050a034f6e650a0c0a0374776f12050a0354776f0a100a05746872656512070a055468726565".decodeHex()
private val EMPTY = Mappy(things = emptyMap())
private val THREE = Mappy(
things = mapOf(
"one" to Thing("One"),
"two" to Thing("Two"),
"three" to Thing("Three")
)
)
}
}
| 163
| null |
570
| 4,244
|
74715088d7d2ee1fdd6d3e070c8b413eefc7e5bd
| 2,134
|
wire
|
Apache License 2.0
|
if-rpc/src/main/kotlin/com/interactionfields/rpc/interceptor/FeignClientInterceptor.kt
|
Ashinch
| 397,369,377
| false
| null |
package com.interactionfields.rpc.interceptor
import feign.RequestInterceptor
import feign.RequestTemplate
import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
/**
* Request interceptor for Feign client.
*
* @author Ashinch
* @date 2021/08/25
*/
@Component
class FeignClientInterceptor : RequestInterceptor {
/**
* Convey the actual token in the request header.
*/
override fun apply(requestTemplate: RequestTemplate) {
val requestAttributes = RequestContextHolder.currentRequestAttributes()
val request = (requestAttributes as ServletRequestAttributes).request
val token = request.getHeader("Authorization")
requestTemplate.header("Authorization", token)
}
}
| 0
|
Kotlin
|
0
| 0
|
997910700454d7e36242a7871292535ca5b62ca6
| 857
|
interaction-fields
|
Apache License 2.0
|
android-uitests/testData/iosched/shared/src/main/java/com/google/samples/apps/iosched/shared/domain/sessions/LoadUserSessionsByDayUseCase.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sree.oneapp.shared.domain.sessions
import com.sree.oneapp.model.ConferenceDay
import com.sree.oneapp.model.Session
import com.sree.oneapp.model.userdata.UserSession
import com.sree.oneapp.shared.data.userevent.DefaultSessionAndUserEventRepository
import com.sree.oneapp.shared.data.userevent.UserEventMessage
import com.sree.oneapp.shared.domain.MediatorUseCase
import com.sree.oneapp.shared.domain.internal.DefaultScheduler
import com.sree.oneapp.shared.result.Result
import com.sree.oneapp.shared.schedule.UserSessionMatcher
import com.sree.oneapp.shared.util.TimeUtils.ConferenceDays
import org.threeten.bp.ZonedDateTime
import timber.log.Timber
import javax.inject.Inject
/**
* Loads sessions into lists keyed by [ConferenceDay].
*/
open class LoadUserSessionsByDayUseCase @Inject constructor(
private val userEventRepository: DefaultSessionAndUserEventRepository
) : MediatorUseCase<LoadUserSessionsByDayUseCaseParameters, LoadUserSessionsByDayUseCaseResult>() {
override fun execute(parameters: LoadUserSessionsByDayUseCaseParameters) {
val (sessionMatcher, userId) = parameters
Timber.d("LoadUserSessionsByDayUseCase: Refreshing sessions with user data")
result.postValue(Result.Loading)
val userSessionsObservable = userEventRepository.getObservableUserEvents(userId)
// Avoid duplicating sources and trigger an update on the LiveData from the base class.
result.removeSource(userSessionsObservable)
result.addSource(userSessionsObservable) {
DefaultScheduler.execute {
when (it) {
is Result.Success -> {
val userSessions = it.data.userSessionsPerDay.mapValues { (_, sessions) ->
sessions.filter { sessionMatcher.matches(it) }
.sortedBy { it.session.startTime }
}
// Compute type from tags now so it's done in the background
userSessions.forEach { it.value.forEach { it.session.type } }
val usecaseResult = LoadUserSessionsByDayUseCaseResult(
userSessionsPerDay = userSessions,
userMessage = it.data.userMessage,
userMessageSession = it.data.userMessageSession,
userSessionCount = userSessions.values.map { it.size }.sum(),
firstUnfinishedSession = findFirstUnfinishedSession(
userSessions, parameters.now
)
)
result.postValue(Result.Success(usecaseResult))
}
is Result.Error -> {
result.postValue(it)
}
}
}
}
}
/**
* During the conference, find the first session which has not finished so that the UI can
* scroll to it.
*/
private fun findFirstUnfinishedSession(
userSessions: Map<ConferenceDay, List<UserSession>>,
now: ZonedDateTime
): EventLocation? {
if (now.isAfter(ConferenceDays.first().start) && now.isBefore(ConferenceDays.last().end)) {
var unfinishedDay: ConferenceDay? = null
var unfinishedSessionIndex = -1
run loop@{
ConferenceDays.filter { now.isBefore(it.end) }
.forEach { day ->
userSessions[day]?.forEachIndexed { sessionIndex, userSession ->
if (userSession.session.endTime.isAfter(now)) {
unfinishedDay = day
unfinishedSessionIndex = sessionIndex
return@loop
}
}
}
}
val day = unfinishedDay
if (day != null && unfinishedSessionIndex != -1) {
return EventLocation(ConferenceDays.indexOf(day), unfinishedSessionIndex)
}
}
return null
}
}
data class LoadUserSessionsByDayUseCaseParameters(
val userSessionMatcher: UserSessionMatcher,
val userId: String?,
val now: ZonedDateTime = ZonedDateTime.now()
)
data class LoadUserSessionsByDayUseCaseResult(
val userSessionsPerDay: Map<ConferenceDay, List<UserSession>>,
/** A message to show to the user with important changes like reservation confirmations */
val userMessage: UserEventMessage? = null,
/** The session the user message is about, if any. */
val userMessageSession: Session? = null,
/** The total number of sessions. */
val userSessionCount: Int,
/** The location of the first session which has not finished or null. */
val firstUnfinishedSession: EventLocation? = null
)
data class EventLocation(val day: Int, val sessionIndex: Int)
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 5,587
|
android
|
Apache License 2.0
|
src/main/kotlin/me/nobaboy/nobaaddons/features/chatcommands/impl/dm/PartyMeCommand.kt
|
nobaboy
| 867,566,026
| false
|
{"Kotlin": 99251}
|
package me.nobaboy.nobaaddons.features.chatcommands.impl.dm
import me.nobaboy.nobaaddons.config.NobaConfigManager
import me.nobaboy.nobaaddons.features.chatcommands.ChatContext
import me.nobaboy.nobaaddons.features.chatcommands.IChatCommand
import me.nobaboy.nobaaddons.utils.Utils
import me.nobaboy.nobaaddons.utils.chat.HypixelCommands
class PartyMeCommand : IChatCommand {
override val name: String = "partyme"
override val aliases: MutableList<String> = mutableListOf("pme")
override val isEnabled: Boolean
get() = NobaConfigManager.get().chatCommands.dm.partyMe
override fun run(ctx: ChatContext) {
val playerName = Utils.getPlayerName() ?: return
if(ctx.user() == playerName) return
HypixelCommands.partyInvite(ctx.user())
}
}
| 0
|
Kotlin
|
1
| 0
|
2b337ee10c5f3668dc33ce0a5ab92501de529645
| 751
|
NobaAddons
|
The Unlicense
|
app/src/main/java/cn/tanghz17/bilidata/ui/upData/VolleySingleton.kt
|
TANGhz17
| 364,589,086
| false
| null |
package cn.tanghz17.bilidata.ui.home
import android.content.Context
import com.android.volley.RequestQueue
import com.android.volley.toolbox.Volley
class VolleySingleton private constructor(context: Context){
companion object {
private var INSTANCE : VolleySingleton?=null
fun getInstance(context: Context) =
INSTANCE?: synchronized(this) {
VolleySingleton(context).also { INSTANCE = it }
}
}
val requestQueue: RequestQueue by lazy {
Volley.newRequestQueue(context.applicationContext)
}
}
| 0
|
JavaScript
|
2
| 3
|
86544a53f15ad436509b036a549ef22862558d9f
| 572
|
BiliData
|
MIT License
|
src/main/kotlin/no/nav/klage/config/KafkaConfiguration.kt
|
navikt
| 261,756,831
| false
| null |
package no.nav.klage.config
import no.nav.klage.getLogger
import no.nav.slackposter.Severity
import no.nav.slackposter.SlackClient
import org.apache.kafka.clients.CommonClientConfigs.SECURITY_PROTOCOL_CONFIG
import org.apache.kafka.clients.consumer.ConsumerConfig
import org.apache.kafka.clients.producer.ProducerConfig
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.config.SaslConfigs
import org.apache.kafka.common.config.SslConfigs
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.kafka.common.serialization.StringSerializer
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory
import org.springframework.kafka.core.*
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer
import org.springframework.kafka.listener.SeekToCurrentErrorHandler
import org.springframework.util.backoff.FixedBackOff
import java.io.File
import java.time.Duration
import java.util.*
@Configuration
class KafkaConfiguration(private val slackClient: SlackClient) {
companion object {
@Suppress("JAVA_CLASS_ON_COMPANION")
private val logger = getLogger(javaClass.enclosingClass)
}
@Value("\${KAFKA_BOOTSTRAP_SERVERS}")
private lateinit var bootstrapServers: String
@Value("\${KAFKA_GROUP_ID}")
private lateinit var groupId: String
@Value("\${SERVICE_USER_USERNAME}")
private lateinit var username: String
@Value("\${SERVICE_USER_PASSWORD}")
private lateinit var password: String
@Value("\${spring.application.name}")
private lateinit var clientId: String
@Bean
fun kafkaListenerContainerFactory(): ConcurrentKafkaListenerContainerFactory<String, String> {
val factory = ConcurrentKafkaListenerContainerFactory<String, String>()
factory.consumerFactory = consumerFactory()
//Setup sending to dead-letter topic after two retries
val recoverer = DeadLetterPublishingRecoverer(kafkaTemplate()) f@
{ r, _ ->
val dltTopic = r.topic().toString() + "-DLT"
logger.debug("Message could not be processed and will be sent to DLT: {}", dltTopic)
slackClient.postMessage("Innsending av klage feilet og vil nå bli lagt på DLT", Severity.ERROR)
return@f TopicPartition(
dltTopic,
r.partition()
)
}
factory.setErrorHandler(
SeekToCurrentErrorHandler(recoverer, FixedBackOff(0L, 2L))
)
//Retry consumer/listener even if authorization fails at first
factory.setContainerCustomizer { container ->
container.containerProperties.authorizationExceptionRetryInterval = Duration.ofSeconds(10L)
}
return factory
}
@Bean
fun consumerFactory(): ConsumerFactory<String, String> {
return DefaultKafkaConsumerFactory(consumerProps())
}
@Bean
fun producerFactory(): ProducerFactory<String, String> {
return DefaultKafkaProducerFactory(producerProps())
}
@Bean
fun kafkaTemplate(): KafkaTemplate<String, String> {
return KafkaTemplate(producerFactory())
}
@Bean
fun producerProps(): Map<String, Any> {
val props: MutableMap<String, Any> = HashMap()
props[ProducerConfig.CLIENT_ID_CONFIG] = clientId
props[ProducerConfig.ACKS_CONFIG] = "all"
props[ProducerConfig.BOOTSTRAP_SERVERS_CONFIG] = bootstrapServers
props[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java
props[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java
props.putAll(commonSecurityProps())
return props
}
private fun consumerProps(): Map<String, Any> {
val props = mutableMapOf<String, Any>()
props[ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG] = bootstrapServers
props[ConsumerConfig.GROUP_ID_CONFIG] = groupId
props[ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG] = true
props[ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG] = Duration.ofDays(3).toMillis().toInt()
props[ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java
props[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java
props.putAll(commonSecurityProps())
return props
}
private fun commonSecurityProps(): Map<String, Any> {
val props: MutableMap<String, Any> = HashMap()
props[SaslConfigs.SASL_JAAS_CONFIG] =
"org.apache.kafka.common.security.plain.PlainLoginModule required username=\"$username\" password=\"$password\";"
props[SaslConfigs.SASL_MECHANISM] = "PLAIN"
System.getenv("NAV_TRUSTSTORE_PATH")?.let {
props[SECURITY_PROTOCOL_CONFIG] = "SASL_SSL"
props[SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG] = File(it).absolutePath
props[SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG] = System.getenv("NAV_TRUSTSTORE_PASSWORD")
}
return props
}
}
| 0
|
Kotlin
|
0
| 0
|
a4d0fce3b48f0f1b40f7d882d6f48bb92509e37c
| 5,208
|
klage-arkiver-journalpost
|
MIT License
|
plugin-bsp/workspacemodel/src/main/kotlin/org/jetbrains/plugins/bsp/workspacemodel/entities/BspEntitySource.kt
|
JetBrains
| 826,262,028
| false
|
{"Kotlin": 2427821, "Starlark": 355702, "Java": 168351, "Scala": 36560, "Python": 34754, "Lex": 14305, "Dockerfile": 7603, "Shell": 6429, "HTML": 1310, "Rust": 680, "Go": 428, "C++": 113}
|
package org.jetbrains.plugins.bsp.workspacemodel.entities
import com.intellij.platform.workspace.storage.EntitySource
public object BspEntitySource : EntitySource
public object BspDummyEntitySource : EntitySource
| 1
|
Kotlin
|
11
| 26
|
3038b5535a382a070428b2af27813c56aaf0d1de
| 216
|
hirschgarten
|
Apache License 2.0
|
app/src/main/java/com/kekulta/events/presentation/ui/theme/Theme.kt
|
kekulta
| 817,411,794
| false
| null |
package com.kekulta.events.ui.theme
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
const val scaleFactor = 1.25
@Composable
fun EventsTheme(
content: @Composable () -> Unit
) {
CompositionLocalProvider(
LocalColorScheme provides LightColorScheme,
LocalTypography provides EventsTypographyValue,
LocalSizeSystem provides EventsLocalSizeSystem,
) {
MaterialTheme(
content = content
)
}
}
object EventsTheme {
val colors: EventsColorScheme
@Composable get() = LocalColorScheme.current
val typography: EventsTypography
@Composable get() = LocalTypography.current
val sizes: EventsSizeSystem
@Composable get() = LocalSizeSystem.current
}
| 0
| null |
0
| 7
|
b2b08eb781e27927354109d638d89c76ffe024be
| 841
|
Events
|
MIT License
|
frogonewsapi/src/main/java/com/frogobox/frogonewsapi/data/response/ArticleResponse.kt
|
amirisback
| 245,812,111
| false
| null |
package com.frogobox.frogoconsumeapi.news.response
import com.frogobox.frogoconsumeapi.news.model.Article
import com.google.gson.annotations.SerializedName
/**
* Created by Faisal Amir
* FrogoBox Inc License
* =========================================
* NewsApi
* Copyright (C) 15/03/2020.
* All rights reserved
* -----------------------------------------
* Name : Muhammad Faisal Amir
* E-mail : faisalamircs@gmail.com
* Github : github.com/amirisback
* LinkedIn : linkedin.com/in/faisalamircs
* -----------------------------------------
* FrogoBox Software Industries
* com.frogobox.frogoconsumeapi.news.data.response
*
*/
data class ArticleResponse(
@SerializedName("status")
var status: String? = null,
@SerializedName("totalResults")
var totalResults: Int? = null,
@SerializedName("code")
var code: String? = null,
@SerializedName("message")
var message: String? = null,
@SerializedName("articles")
var articles: List<Article>? = null
)
| 2
| null |
5
| 9
|
2881f54f4c9b89ac24aa26f923f635e6a3cc098f
| 1,013
|
consumable-code-news-api
|
Apache License 2.0
|
app/src/main/java/com/example/c323p6notes/ConfirmDeleteDialogFragment.kt
|
kuzeybektas
| 703,330,136
| false
|
{"Kotlin": 14608}
|
package com.example.notesapp
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.DialogFragment
class ConfirmDeleteDialogFragment(val noteId:String, val clickListener: (noteId:String)-> Unit):DialogFragment() {
val TAG = "ConfirmDeleteDialogFragment"
interface myClickListener{
fun yesPressed()
}
var listener: myClickListener? = null
/*
method that creates the confirmation dialog to delete the note
@param savedInstanceState: Bundle
@returns created dialog
*/
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
AlertDialog.Builder(requireContext())
.setMessage("Are you sure you want to delete?")
//yes delete
.setPositiveButton("Yes"){_,_->clickListener(noteId)}
//no delete
.setNegativeButton("No"){_,_->}
//create dialog
.create()
companion object{
const val TAG = "ConfirmDeleteDialogFragment"
}
/*
method to attach listener
@param context: Context
*/
override fun onAttach(context: Context) {
super.onAttach(context)
try {
listener = context as myClickListener
}catch (e:Exception){
Log.d(TAG, e.message.toString())
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b6216bfb9fb5adf1948d4b0d9bc2590d1baa4424
| 1,404
|
NotesApp
|
Apache License 2.0
|
plugins/kotlin/idea/tests/testData/quickfix/addNoinline/withCrossinline.kt
|
ingokegel
| 72,937,917
| false
| null |
// "Add 'noinline' to parameter 'lambda'" "true"
// WITH_STDLIB
inline fun inlineFun(crossinline lambda: () -> Unit) {
<caret>lambda.toString()
}
// FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.AddInlineModifierFix
| 284
| null |
5162
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 227
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/noomit/radioalarm02/ui/radio_browser/home/RadioBrowserFragment.kt
|
tinted-knight
| 292,891,478
| false
| null |
package com.noomit.radioalarm02.ui.radio_browser.home
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ScrollView
import androidx.navigation.fragment.findNavController
import androidx.navigation.navGraphViewModels
import com.noomit.domain.server_manager.ServerState
import com.noomit.radioalarm02.R
import com.noomit.radioalarm02.ui.navigation.NavHelper
import com.noomit.radioalarm02.ui.radio_browser.RadioBrowserEvent
import com.noomit.radioalarm02.ui.radio_browser.RadioBrowserViewModel
import com.noomit.radioalarm02.util.fragment.ContourFragment
import com.noomit.radioalarm02.util.fragment.collect
import com.squareup.contour.utils.children
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.FlowPreview
@FlowPreview
@AndroidEntryPoint
class RadioBrowserFragment : ContourFragment<IRadioBrowserHomeLayout>() {
private val viewModel: RadioBrowserViewModel by navGraphViewModels(R.id.nav_radio_browser) {
defaultViewModelProviderFactory
}
override val contour: IRadioBrowserHomeLayout
get() = (view as ViewGroup).children.first() as IRadioBrowserHomeLayout
override val layout: View
get() {
val scrollView = ScrollView(context)
scrollView.addView(RadioBrowserHomeLayout(requireContext()))
scrollView.isVerticalScrollBarEnabled = true
return scrollView
}
override fun prepareView(savedState: Bundle?) {
contour.apply {
val adapter = ServerListAdapter(adapterListener)
delegate = viewModel
setServerAdapter(adapter)
showLoading()
btnSearchEnabled(false)
setSearchFields(viewModel.searchState.value.name, viewModel.searchState.value.tag)
}
}
override fun observeViewModel() {
collect(viewModel.availableServers) {
when (it) {
is ServerState.Loading -> contour.showLoading()
is ServerState.Values -> contour.update(content = it.values)
is ServerState.Failure -> contour.showError(getString(R.string.err_server_connection))
else -> contour.showLoading()
}
}
// collect(viewModel.activeServer) {
// when (it) {
// is ActiveServerState.None -> contour.update(activerServer = null)
// is ActiveServerState.Value -> contour.update(activerServer = it.serverInfo)
// else -> contour.showLoading()
// }
// }
collect(viewModel.searchState) {
contour.btnSearchEnabled(it.isValid)
}
}
override fun observeCommands() {
collect(viewModel.oneshotEvents) { event ->
when (event) {
is RadioBrowserEvent.LanguageList -> findNavController().navigate(
R.id.action_radioBrowser_to_languageList,
Bundle().apply { putString(NavHelper.title, getString(R.string.nav_label_languages)) }
)
is RadioBrowserEvent.TagList -> findNavController().navigate(
R.id.action_radioBrowser_to_languageList,
Bundle().apply { putString("title", getString(R.string.nav_label_tags)) }
)
is RadioBrowserEvent.TopVoted -> findNavController().navigate(
R.id.action_radioBrowser_to_stationList,
Bundle().apply { putString("title", getString(R.string.nav_label_topvoted)) }
)
is RadioBrowserEvent.Search -> findNavController().navigate(
R.id.action_radioBrowser_to_stationList,
Bundle().apply { putString("title", getString(R.string.nav_label_search)) }
)
}
}
}
private val adapterListener: ServerClick = {
viewModel.setServer(it)
contour.serverListCollapse()
}
}
| 0
| null |
0
| 1
|
32aab4a755daac92973a74509cf2f372ab4537c5
| 3,974
|
RadioAlarm04
|
Apache License 2.0
|
app/src/main/java/io/github/gusriil/moviemagnet/widget/MarginDecoration.kt
|
superosystem
| 479,150,681
| false
|
{"Kotlin": 225959, "Java": 7644}
|
package io.github.gusriil.moviemagnet.widget
import android.content.Context
import android.graphics.Rect
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import io.github.gusriil.moviemagnet.R
class MarginDecoration(context: Context) : RecyclerView.ItemDecoration() {
private val margin: Int = context.resources.getDimensionPixelSize(R.dimen.padding_small)
override fun getItemOffsets(
outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
outRect.set(margin, margin, margin, margin)
}
}
| 0
|
Kotlin
|
0
| 3
|
91a2d005aab478bb5c864210fe0cbd2286daf2ad
| 571
|
MovieMagnet
|
MIT License
|
library/src/darwinCommonMain/kotlin/Wallet.kt
|
DrewCarlson
| 228,961,452
| false
| null |
/*
* Created by <NAME>.
* Copyright (c) 2021 Breadwinner AG. All right reserved.
*
* See the LICENSE file at the project root for license information.
* See the CONTRIBUTORS file at the project root for a list of contributors.
*/
package com.blockset.walletkit
import walletkit.core.*
import walletkit.core.WKWalletState.WK_WALLET_STATE_CREATED
import walletkit.core.WKWalletState.WK_WALLET_STATE_DELETED
import kotlinx.cinterop.*
import kotlinx.coroutines.CoroutineScope
import kotlin.native.concurrent.*
public actual class Wallet internal constructor(
core: WKWallet,
public actual val manager: WalletManager,
public actual val scope: CoroutineScope,
take: Boolean
) {
internal val core: WKWallet =
if (take) checkNotNull(wkWalletTake(core))
else core
init {
freeze()
}
public actual val system: System
get() = manager.system
public actual val unit: UnitWK
get() = UnitWK(checkNotNull(wkWalletGetUnit(core)), false)
public actual val unitForFee: UnitWK
get() = UnitWK(checkNotNull(wkWalletGetUnitForFee(core)), false)
public actual val balance: Amount
get() = Amount(checkNotNull(wkWalletGetBalance(core)), false)
public actual val transfers: List<Transfer>
get() = memScoped {
val count = alloc<ULongVar>()
val coreTransfers = wkWalletGetTransfers(core, count.ptr)
if (coreTransfers == null) {
emptyList()
} else {
defer { wkMemoryFree(coreTransfers) }
List(count.value.toInt()) { i ->
Transfer(checkNotNull(coreTransfers[i]), this@Wallet, false)
}
}
}
public actual fun getTransferByHash(hash: TransferHash?): Transfer? =
transfers.singleOrNull { it.hash == hash }
public actual val target: Address
get() = getTargetForScheme(manager.addressScheme)
public actual fun getTargetForScheme(scheme: AddressScheme): Address {
val coreAddress = checkNotNull(wkWalletGetAddress(core, scheme.toCore()))
return Address(coreAddress, false)
}
public actual val currency: Currency
get() = Currency(checkNotNull(wkWalletGetCurrency(core)), false)
public actual val name: String
get() = unit.currency.name
public actual val state: WalletState
get() = when (wkWalletGetState(core)) {
WK_WALLET_STATE_CREATED -> WalletState.CREATED
WK_WALLET_STATE_DELETED -> WalletState.DELETED
else -> error("Unknown wkWalletGetState result")
}
public actual fun hasAddress(address: Address): Boolean {
return wkWalletHasAddress(core, address.core)
}
/*internal actual fun createTransferFeeBasis(
pricePerCostFactor: Amount,
costFactor: Double
): TransferFeeBasis? {
val coreFeeBasis = wkWalletCreateFeeBasis(core, pricePerCostFactor.core, costFactor)
return TransferFeeBasis(coreFeeBasis ?: return null, false)
}*/
public actual fun createTransfer(
target: Address,
amount: Amount,
estimatedFeeBasis: TransferFeeBasis,
transferAttributes: Set<TransferAttribute>
): Transfer? = memScoped {
val attrs = transferAttributes.map(TransferAttribute::core).toCValues()
val count = attrs.size.toULong()
val coreTransfer = wkWalletCreateTransfer(core, target.core, amount.core, estimatedFeeBasis.core, count, attrs)
Transfer(coreTransfer ?: return null, this@Wallet, false)
}
internal fun transferBy(core: WKTransfer): Transfer? {
return if (WK_TRUE == wkWalletHasTransfer(this.core, core)) {
Transfer(core, this, true)
} else null
}
internal fun transferByCoreOrCreate(core: WKTransfer): Transfer? {
return transferBy(core) ?: Transfer(core, this, true)
}
public actual suspend fun estimateFee(
target: Address,
amount: Amount,
fee: NetworkFee,
attributes: Set<TransferAttribute>
): TransferFeeBasis {
val attrsLength = 0uL
val attrs = attributes.map { it.core }.toCValues()
wkWalletManagerEstimateFeeBasis(
manager.core, core, null, target.core, amount.core, fee.core, attrsLength, attrs)
TODO("Not implemented")
}
public actual suspend fun estimateLimitMaximum(target: Address, fee: NetworkFee): Amount {
TODO()
}
public actual suspend fun estimateLimitMinimum(target: Address, fee: NetworkFee): Amount {
TODO()
}
actual override fun equals(other: Any?): Boolean =
other is Wallet && WK_TRUE == wkWalletEqual(core, other.core)
actual override fun hashCode(): Int = core.hashCode()
internal fun getTransfer(coreTransfer: WKTransfer): Transfer? {
return if (wkWalletHasTransfer(core, coreTransfer) == WK_TRUE) {
Transfer(coreTransfer, this, true)
} else null
}
}
| 4
|
Kotlin
|
1
| 1
|
6a6b20a69e6307d89ad7ce3494fb794411fb7e76
| 5,087
|
WalletKit-Kotlin
|
The Unlicense
|
domain/src/main/java/com/telen/easylineup/domain/model/TeamType.kt
|
kaygenzo
| 177,859,247
| false
| null |
/*
Copyright (c) <NAME>. 2010-2024
*/
package com.telen.easylineup.domain.model
import android.content.Context
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import com.telen.easylineup.domain.R
/**
* @property id
* @property position
* @property title
* @property sportResId
* @property defaultStrategy
*/
enum class TeamType(
val id: Int,
val position: Int,
@StringRes val title: Int,
@DrawableRes val sportResId: Int,
val defaultStrategy: TeamStrategy
) {
UNKNOWN(0, -1, 0, 0, TeamStrategy.STANDARD),
BASEBALL(
1,
0,
R.string.title_baseball,
R.drawable.pitcher_baseball_team,
TeamStrategy.STANDARD
),
SOFTBALL(
2,
1,
R.string.title_softball,
R.drawable.pitcher_softball_team,
TeamStrategy.STANDARD
),
BASEBALL_5(
3,
2,
R.string.title_baseball_5,
R.drawable.pitcher_baseball5_team,
TeamStrategy.B5_DEFAULT
),
;
fun getStrategies(): Array<TeamStrategy> {
return when (this) {
SOFTBALL -> arrayOf(
TeamStrategy.STANDARD,
TeamStrategy.FIVE_MAN_STANDARD,
TeamStrategy.SLOWPITCH
)
BASEBALL_5 -> arrayOf(TeamStrategy.B5_DEFAULT)
else -> arrayOf(TeamStrategy.STANDARD, TeamStrategy.FIVE_MAN_STANDARD)
}
}
fun getStrategiesDisplayName(context: Context): Array<String>? {
return when (this) {
SOFTBALL -> context.resources.getStringArray(R.array.softball_strategy_array)
BASEBALL -> context.resources.getStringArray(R.array.baseball_strategy_array)
else -> null
}
}
companion object {
fun getTypeById(id: Int): TeamType {
values().forEach {
if (it.id == id) {
return it
}
}
return UNKNOWN
}
}
}
| 1
| null |
1
| 1
|
152fa21de470e81d368b26a4f18de5d5198ef8fc
| 2,000
|
EasyLineUp
|
Apache License 2.0
|
CryptoAC/src/commonMain/kotlin/eu/fbk/st/cryptoac/core/CoreParameters.kt
|
stfbk
| 292,768,224
| false
|
{"JavaScript": 22741621, "Kotlin": 2367601, "Shell": 14642, "Batchfile": 9481, "SCSS": 6830, "CSS": 5868, "Open Policy Agent": 2902, "HTML": 984, "Assembly": 419}
|
package eu.fbk.st.cryptoac.core
import eu.fbk.st.cryptoac.parameters.ServiceParameters
import eu.fbk.st.cryptoac.SafeRegex
import eu.fbk.st.cryptoac.model.unit.User
import eu.fbk.st.cryptoac.crypto.CryptoType
import eu.fbk.st.cryptoac.ac.opa.ACServiceRBACOPAParameters
import eu.fbk.st.cryptoac.ac.ACServiceParameters
import eu.fbk.st.cryptoac.ac.dynsec.ACServiceRBACDynSecParameters
import eu.fbk.st.cryptoac.ac.xacmlauthzforce.ACServiceRBACXACMLAuthzForceParameters
import eu.fbk.st.cryptoac.dm.cryptoac.DMServiceCryptoACParameters
import eu.fbk.st.cryptoac.dm.mqtt.DMServiceMQTTParameters
import eu.fbk.st.cryptoac.dm.DMServiceParameters
import eu.fbk.st.cryptoac.dm.DMServiceRemoteUPParameters
import eu.fbk.st.cryptoac.rm.cryptoac.RMServiceRBACCryptoACParameters
import eu.fbk.st.cryptoac.rm.RMServiceParameters
import eu.fbk.st.cryptoac.mm.MMServiceParameters
import eu.fbk.st.cryptoac.mm.redis.MMServiceRedisParameters
import eu.fbk.st.cryptoac.mm.MMServiceRemoteUPParameters
import eu.fbk.st.cryptoac.mm.mysql.MMServiceABACMySQLParameters
import eu.fbk.st.cryptoac.mm.mysql.MMServiceRBACMySQLParameters
import eu.fbk.st.cryptoac.rm.RMServiceRemoteUPParameters
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.*
import mu.KotlinLogging
private val logger = KotlinLogging.logger {}
/**
* Base parameters for configuring the core
* object, i.e., the [user], the [coreType],
* the [cryptoType] and the [versionNumber]
* of the parameters. Then, beside these base
* parameters, we need to know the parameters
* to configure the services, i.e.:
* - [rmServiceParameters];
* - [mmServiceParameters];
* - [dmServiceParameters];
* - [acServiceParameters].
*/
@Serializable
abstract class CoreParameters : ServiceParameters {
abstract var user: User
abstract val coreType: CoreType
abstract val cryptoType: CryptoType
abstract val versionNumber: Int
abstract val rmServiceParameters: RMServiceParameters?
abstract val mmServiceParameters: MMServiceParameters
abstract val dmServiceParameters: DMServiceParameters
abstract val acServiceParameters: ACServiceParameters?
/**
* Check the parameters are valid through regular
* expressions and return true if they are, false otherwise
*/
override fun checkParameters(): Boolean =
if (!SafeRegex.TEXT.matches(user.name)) {
logger.warn { "Username ${user.name} does not respect TEXT regex" }
false
} else if (
user.asymEncKeys != null && (
!SafeRegex.BASE64.matches(user.asymEncKeys!!.public) ||
!SafeRegex.BASE64.matches(user.asymEncKeys!!.private)
)
) {
logger.warn { "Encryption keys does not respect BASE64 regex" }
false
} else if (
user.asymSigKeys != null && (
!SafeRegex.BASE64.matches(user.asymSigKeys!!.public) ||
!SafeRegex.BASE64.matches(user.asymSigKeys!!.private)
)
) {
logger.warn { "Signing keys does not respect BASE64 regex" }
false
} else if (versionNumber !in 1..1) {
logger.warn {
"Parameters version is not supported (version" +
" number is $versionNumber, supported are 1..1"
}
false
} else {
rmServiceParameters?.checkParameters() ?: true &&
mmServiceParameters.checkParameters() &&
dmServiceParameters.checkParameters() &&
acServiceParameters?.checkParameters() ?: true
}
/** Update updatable fields */
override fun update(updatedParameters: ServiceParameters) {
if (updatedParameters is CoreParameters) {
updatedParameters.rmServiceParameters?.let { rmServiceParameters?.update(it) }
mmServiceParameters.update(updatedParameters.mmServiceParameters)
dmServiceParameters.update(updatedParameters.dmServiceParameters)
updatedParameters.acServiceParameters?.let { acServiceParameters?.update(it) }
} else {
val message = "Given a non-subclass of ${this::class} for update"
logger.error { message }
throw IllegalStateException(message)
}
}
/** Obscure (e.g., delete values of) sensitive fields */
override fun obscureSensitiveFields() {
user.asymEncKeys?.private = "***"
user.asymSigKeys?.private = "***"
rmServiceParameters?.obscureSensitiveFields()
mmServiceParameters.obscureSensitiveFields()
dmServiceParameters.obscureSensitiveFields()
acServiceParameters?.obscureSensitiveFields()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is CoreParameters) return false
if (user != other.user) return false
if (coreType != other.coreType) return false
if (cryptoType != other.cryptoType) return false
if (versionNumber != other.versionNumber) return false
if (rmServiceParameters != other.rmServiceParameters) return false
if (mmServiceParameters != other.mmServiceParameters) return false
if (dmServiceParameters != other.dmServiceParameters) return false
if (acServiceParameters != other.acServiceParameters) return false
return true
}
override fun hashCode(): Int {
var result = user.hashCode()
result = 31 * result + coreType.hashCode()
result = 31 * result + cryptoType.hashCode()
result = 31 * result + versionNumber
result = 31 * result + (rmServiceParameters?.hashCode() ?: 0)
result = 31 * result + mmServiceParameters.hashCode()
result = 31 * result + dmServiceParameters.hashCode()
result = 31 * result + (acServiceParameters?.hashCode() ?: 0)
return result
}
}
val myJson = Json {
encodeDefaults = true
serializersModule = SerializersModule {
/** AC */
polymorphic(ACServiceParameters::class) {
subclass(ACServiceRBACXACMLAuthzForceParameters::class)
subclass(ACServiceRBACOPAParameters::class)
subclass(ACServiceRBACDynSecParameters::class)
}
/** DM */
polymorphic(DMServiceParameters::class) {
subclass(DMServiceCryptoACParameters::class)
subclass(DMServiceMQTTParameters::class)
}
polymorphic(DMServiceRemoteUPParameters::class) {
subclass(DMServiceCryptoACParameters::class)
subclass(DMServiceMQTTParameters::class)
}
/** MM */
polymorphic(MMServiceParameters::class) {
subclass(MMServiceABACMySQLParameters::class)
subclass(MMServiceRBACMySQLParameters::class)
subclass(MMServiceRedisParameters::class)
}
polymorphic(MMServiceRemoteUPParameters::class) {
subclass(MMServiceABACMySQLParameters::class)
subclass(MMServiceRBACMySQLParameters::class)
subclass(MMServiceRedisParameters::class)
}
/** RM */
polymorphic(RMServiceParameters::class) {
subclass(RMServiceRBACCryptoACParameters::class)
}
polymorphic(RMServiceRemoteUPParameters::class) {
subclass(RMServiceRBACCryptoACParameters::class)
}
/** Core */
polymorphic(CoreParameters::class) {
subclass(CoreParametersRBAC::class)
}
}
}
| 0
|
JavaScript
|
0
| 2
|
13958f84e7e8c5e40a78afc5c737e6443bc1ac37
| 7,554
|
CryptoAC
|
Apache License 2.0
|
data/model/src/dog/del/data/model/ApiCredential.kt
|
dogbin
| 117,153,857
| false
| null |
package dog.del.data.model
import dog.del.commons.Date
interface ApiCredential<U : User<*>> {
// We never store actual, full api keys
var keyHash: String
// User chosen name for the key to easily identify it in the dashboard
var name: String
// The user this key belongs to
var user: U
// Creation date/time of the key
var created: Date
// Actions which can be performed using this key
var canCreateDocuments: Boolean
var canUpdateDocuments: Boolean
var canDeleteDocuments: Boolean
}
| 15
| null |
51
| 361
|
ab9db4a8751e9b870a02a3867899c0f67fe50c9a
| 536
|
dogbin
|
MIT License
|
projects/core/koin-core/src/commonTest/kotlin/org/koin/Components.kt
|
InsertKoinIO
| 93,515,203
| false
| null |
package non_official.pokeum.debris
class Simple {
class ComponentA
class ComponentB(val a: ComponentA)
class ComponentC(val b: ComponentB)
interface ComponentInterface1
interface ComponentInterface2
class Component1 : ComponentInterface1, ComponentInterface2
class Component2 : ComponentInterface1
class UserComponent(val c1: ComponentInterface1)
class MySingle(val id: Int)
class MySingleWithNull(val id: Int?)
class MyIntFactory(val id: Int)
class MyStringFactory(val s: String)
class AllFactory(val ints: MyIntFactory, val strings: MyStringFactory)
}
@Suppress("unused")
class Errors {
class Boom {
init {
error("Got error while init :(")
}
}
class CycleA(val b: CycleB)
class CycleB(val a: CycleA)
}
| 79
| null |
711
| 8,934
|
f870a02fd32a2cf1ff8b69406ebf555c26ffe39f
| 804
|
koin
|
Apache License 2.0
|
trustagent/src/com/google/android/libraries/car/trustagent/util/TimeProvider.kt
|
google
| 415,118,653
| false
|
{"Kotlin": 865761, "Java": 244253}
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.trustagent.util
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
/** A time provider that will provide current time stamp in the ISO 8601 format. */
object TimeProvider {
fun createCurrentTimeStamp() = DateTimeFormatter.ISO_DATE_TIME.format(OffsetDateTime.now())
}
| 1
|
Kotlin
|
5
| 18
|
912fd5cff1f08577d679bfaff9fc0666b8093367
| 924
|
android-auto-companion-android
|
Apache License 2.0
|
pumps/src/main/kotlin/fund/cyber/pump/bitcoin/BitcoinKafkaStorageActionTemplateFactory.kt
|
rezon99
| 118,602,344
| true
|
{"Kotlin": 180690, "Shell": 190}
|
package fund.cyber.pump.bitcoin
import fund.cyber.node.common.Chain
import fund.cyber.node.common.ChainEntity.TRANSACTION
import fund.cyber.node.kafka.PumpEvent
import fund.cyber.node.kafka.PumpEvent.DROPPED_BLOCK
import fund.cyber.node.kafka.PumpEvent.NEW_BLOCK
import fund.cyber.node.kafka.entityTopic
import fund.cyber.node.model.BitcoinTransaction
import fund.cyber.pump.kafka.KafkaStorageActionTemplate
import fund.cyber.pump.kafka.KafkaStorageActionTemplateFactory
import org.apache.kafka.clients.producer.ProducerRecord
class BitcoinKafkaStorageActionTemplateFactory(
chain: Chain
) : KafkaStorageActionTemplateFactory<BitcoinBlockBundle> {
private val transactionsTopic = chain.entityTopic(TRANSACTION)
override fun constructActionTemplate(bundle: BitcoinBlockBundle): KafkaStorageActionTemplate {
val newBlockTxesRecords = bundle.transactions.map { tx -> asRecord(NEW_BLOCK, tx) }
val droppedBlockTxesRecords = bundle.transactions.map { tx -> asRecord(DROPPED_BLOCK, tx) }
return KafkaStorageActionTemplate(newBlockTxesRecords, droppedBlockTxesRecords)
}
private fun asRecord(event: PumpEvent, tx: BitcoinTransaction): ProducerRecord<PumpEvent, BitcoinTransaction>
= ProducerRecord(transactionsTopic, event, tx)
}
| 0
|
Kotlin
|
0
| 0
|
d2248b89a2192432a3af47d68a51c60d0ab16b3c
| 1,288
|
cyber-search
|
MIT License
|
Desafios em Kotlin/1164 - Número Perfeito/Main.kt
|
lucasmarcuzo
| 386,427,361
| false
|
{"Text": 5, "Markdown": 6, "C#": 178, "Git Attributes": 1, "JSON": 3, "SQL": 49, "Kotlin": 174, "Java": 177, "XML": 8, "Ignore List": 2, "JavaScript": 163}
|
import java.util.*
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val x = scan.nextInt()
for (i in 0 until x) {
var valor = 0
var total = 0
valor = scan.nextInt()
for (j in 1 until valor) {
if (valor % j == 0) {
total += j
}
}
if (valor == total) {
println("$valor eh perfeito")
} else {
println("$valor nao eh perfeito")
}
}
scan.close()
}
| 0
|
Java
|
12
| 22
|
0238d847dac30cabeccbccb657da96128c2d5a5c
| 513
|
Beecrowd
|
MIT License
|
vito/core-impl/src/main/java/com/facebook/fresco/vito/core/impl/ProgressLayerHandler.kt
|
facebook
| 31,533,997
| false
|
{"Java": 2895425, "Kotlin": 1024596, "C++": 183862, "C": 53836, "Makefile": 10411, "Python": 10096, "Shell": 840}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.core.impl
import android.content.res.Resources
import android.graphics.drawable.Drawable
import com.facebook.common.references.CloseableReference
import com.facebook.datasource.DataSource
import com.facebook.fresco.vito.options.ImageOptions
import com.facebook.fresco.vito.renderer.DrawableImageDataModel
import com.facebook.imagepipeline.image.CloseableImage
import kotlin.math.roundToInt
fun KFrescoVitoDrawable.setupProgressLayer(resources: Resources, imageOptions: ImageOptions) {
val drawable = imageOptions.createProgressDrawable(resources)
if (drawable == null) {
progressLayer?.reset()
progressLayer = null
return
}
var layer = progressLayer
if (layer == null) {
layer = ImageLayerDataModel(callbackProvider)
progressLayer = layer
}
drawable.setProgress(0f)
layer.configure(
dataModel = DrawableImageDataModel(drawable),
canvasTransformation = imageOptions.createProgressCanvasTransformation())
}
fun KFrescoVitoDrawable.hideProgressLayer() {
progressLayer?.reset()
}
fun KFrescoVitoDrawable.updateProgress(dataSource: DataSource<CloseableReference<CloseableImage>>) {
progressLayer?.getDataModel().maybeGetDrawable()?.apply {
if (dataSource.isFinished) {
return@apply
}
setProgress(dataSource.progress)
}
}
/** Set the progress for a given progress Drawable. The value must be between 0 and 1 */
fun Drawable.setProgress(progress: Float) {
level = (progress * 10000).roundToInt()
toggleAnimation(level <= 9990)
// TODO(T105148151): Support imageOptions.shouldAlwaysShowProgressImmediately()
}
| 233
|
Java
|
3774
| 17,073
|
dbb46cebfffeeabf289db5f4a8d64950ba1e020d
| 1,809
|
fresco
|
MIT License
|
ui/src/commonMain/kotlin/kosh/ui/transaction/NetworkFeesCard.kt
|
niallkh
| 855,100,709
| false
|
{"Kotlin": 1813876, "Swift": 594}
|
package kosh.ui.transaction
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import arrow.core.raise.nullable
import kosh.domain.entities.TransactionEntity
import kosh.domain.models.web3.Transaction
import kosh.domain.models.web3.gasPrice
import kosh.domain.utils.orZero
import kosh.presentation.token.rememberNativeToken
import kosh.presentation.transaction.EstimateGasState
import kosh.presentation.transaction.GasPricesState
import kosh.presentation.transaction.GasSpeedState
import kosh.presentation.transaction.get
import kosh.presentation.transaction.rememberEstimateGas
import kosh.presentation.transaction.rememberGasPrices
import kosh.presentation.transaction.rememberGasSpeed
import kosh.ui.component.placeholder.placeholder
import kosh.ui.component.text.KeyValueRow
import kosh.ui.component.text.TextAmount
import kosh.ui.component.text.TextHeader
import kosh.ui.component.text.TextNumber
import kosh.ui.failure.AppFailureItem
import kosh.ui.transaction.calls.TokenAmountItem
@Composable
fun NetworkFeesCard(
transaction: Transaction?,
modifier: Modifier = Modifier,
gasPrices: GasPricesState? = transaction?.chainId?.let { rememberGasPrices(it) },
gasSpeed: GasSpeedState = rememberGasSpeed(),
gasEstimation: EstimateGasState? = transaction?.let { rememberEstimateGas(transaction) },
) {
val gasPrice = gasPrices?.prices?.get(gasSpeed.speed)
Column(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
TextHeader("Network Fees")
var expanded by rememberSaveable { mutableStateOf(false) }
val token = transaction?.chainId?.let { rememberNativeToken(it) }
OutlinedCard(
onClick = { expanded = !expanded }
) {
gasPrices?.failure?.let {
AppFailureItem(it) { gasPrices.retry() }
} ?: gasEstimation?.failure?.let {
AppFailureItem(it) { gasEstimation.retry() }
} ?: run {
TokenAmountItem(
token?.entity,
nullable {
ensureNotNull(gasPrice).gasPrice *
ensureNotNull(gasEstimation?.estimation).gas.toLong()
}
) {
Text("Max Amount")
}
}
AnimatedVisibility(expanded) {
Column(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
KeyValueRow(
modifier = Modifier.placeholder(transaction == null),
key = { Text("Estimated Gas Used") },
value = { TextNumber(gasEstimation?.estimation?.estimated.orZero()) }
)
KeyValueRow(
modifier = Modifier.placeholder(transaction == null),
key = { Text("Gas Limit") },
value = { TextNumber(gasEstimation?.estimation?.gas.orZero()) }
)
KeyValueRow(
modifier = Modifier.placeholder(gasPrice == null || token == null),
key = { Text("Max Base Gas Price") },
value = {
TextAmount(
gasPrice?.base.orZero(),
token?.entity?.symbol.orEmpty(),
token?.entity?.decimals
)
}
)
KeyValueRow(
modifier = Modifier.placeholder(gasPrice == null || token == null),
key = { Text("Priority Gas Price") },
value = {
TextAmount(
gasPrice?.priority.orZero(),
token?.entity?.symbol.orEmpty(),
token?.entity?.decimals
)
}
)
Spacer(Modifier.height(8.dp))
}
}
}
}
}
@Composable
fun NetworkFeesCard(
transaction: TransactionEntity.Eip1559,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
TextHeader("Network Fees")
var expanded by rememberSaveable { mutableStateOf(false) }
val token = rememberNativeToken(transaction.networkId)
OutlinedCard(
onClick = { expanded = !expanded }
) {
if (transaction.receipt != null) {
val amount = transaction.receipt?.gasPrice?.gasPrice.orZero() *
transaction.receipt?.gasUsed?.toLong().orZero()
TokenAmountItem(token.entity, amount) {
Text("Amount")
}
} else {
val amount = transaction.gasPrice.gasPrice * transaction.gasLimit.toLong()
TokenAmountItem(token.entity, amount) {
Text("Max Amount")
}
}
AnimatedVisibility(expanded) {
Column(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
if (transaction.receipt != null) {
KeyValueRow(
key = { Text("Gas Used") },
value = { TextNumber(transaction.receipt?.gasUsed ?: 0u) }
)
}
KeyValueRow(
key = { Text("Gas Limit") },
value = { TextNumber(transaction.gasLimit) }
)
if (transaction.receipt != null) {
KeyValueRow(
key = { Text("Base Gas Price") },
value = {
TextAmount(
transaction.receipt?.gasPrice?.base.orZero(),
token.entity?.symbol.orEmpty(),
token.entity?.decimals
)
}
)
}
KeyValueRow(
key = { Text("Max Base Gas Price") },
value = {
TextAmount(
transaction.gasPrice.base.orZero(),
token.entity?.symbol.orEmpty(),
token.entity?.decimals
)
}
)
KeyValueRow(
key = { Text("Priority Gas Price") },
value = {
TextAmount(
transaction.gasPrice.priority.orZero(),
token.entity?.symbol.orEmpty(),
token.entity?.decimals
)
}
)
Spacer(Modifier.height(8.dp))
}
}
}
}
}
| 0
|
Kotlin
|
0
| 3
|
f48555a563dfee5b07184771a6c94c065765d570
| 8,041
|
kosh
|
MIT License
|
src/main/year_2017/day02/day03.kt
|
rolf-rosenbaum
| 572,864,107
| false
| null |
package year_2017.day02
import readInput
fun part1(input: List<String>): Int = input.map { line ->
line.split(" ").map { it.toInt() }.sortedDescending()
}.sumOf { it.first() - it.last() }
fun part2(input: List<String>): Int = input.map { line ->
line.split(" ").map { it.toInt() }.sortedDescending()
}.sumOf { line ->
line.findDivisionResult()
}
fun main() {
val input = readInput("main/year_2017/day02/Day02")
println(part1(input))
println(part2(input))
}
fun List<Int>.findDivisionResult(): Int {
forEachIndexed { index, candidate ->
(index + 1 until size).forEach {
if (candidate % this[it] == 0) return candidate / this[it]
}
}
error("no even division found")
}
| 0
|
Kotlin
|
0
| 2
|
81c84a1305e0af1f76d6c1394b642156ba7c008c
| 736
|
aoc-2022
|
Apache License 2.0
|
app/src/main/java/com/example/counts/EditFragment.kt
|
jirois
| 262,518,092
| false
| null |
package com.example.counts
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import com.example.counts.databinding.EditFragmentBinding
/**
* A simple [Fragment] subclass.
*/
class EditFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
val binding = DataBindingUtil.inflate<EditFragmentBinding>(inflater, R.layout.edit_fragment, container, false)
binding.addBtn.setOnClickListener {v: View ->
v.findNavController().navigate(R.id.action_editFragment_to_listFragment)
}
setHasOptionsMenu(true)
return binding.root
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.add_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.listFragment -> {
saveItem()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun saveItem() {
}
}
| 1
|
Kotlin
|
0
| 0
|
0c65db514806ab1518be5e40db08e9e03f35a451
| 1,328
|
counts
|
MIT License
|
app/src/main/java/com/example/counts/EditFragment.kt
|
jirois
| 262,518,092
| false
| null |
package com.example.counts
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import com.example.counts.databinding.EditFragmentBinding
/**
* A simple [Fragment] subclass.
*/
class EditFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
val binding = DataBindingUtil.inflate<EditFragmentBinding>(inflater, R.layout.edit_fragment, container, false)
binding.addBtn.setOnClickListener {v: View ->
v.findNavController().navigate(R.id.action_editFragment_to_listFragment)
}
setHasOptionsMenu(true)
return binding.root
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.add_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.listFragment -> {
saveItem()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun saveItem() {
}
}
| 1
|
Kotlin
|
0
| 0
|
0c65db514806ab1518be5e40db08e9e03f35a451
| 1,328
|
counts
|
MIT License
|
test/src/me/anno/tests/ui/ScrollbarOverdraw.kt
|
AntonioNoack
| 456,513,348
| false
| null |
package me.anno.tests.ui
import me.anno.config.DefaultConfig.style
import me.anno.studio.StudioBase
import me.anno.ui.base.groups.PanelList
import me.anno.ui.base.scrolling.ScrollPanelY
import me.anno.ui.base.text.TextPanel
import me.anno.ui.debug.TestStudio.Companion.testUI3
fun main() {
testUI3("Scrollbar Overdraw") {
StudioBase.instance?.enableVSync = true
val main = ScrollPanelY(style)
val list = main.child as PanelList
for (i in 0 until 100) {
list.add(TextPanel("Text $i", style))
}
main
}
}
| 0
|
Kotlin
|
2
| 9
|
94bc7c74436aa567ec3c19f386dd67af0f1ced00
| 571
|
RemsEngine
|
Apache License 2.0
|
app/src/main/java/dev/alibagherifam/mentha/theme/Typography.kt
|
alibagherifam
| 586,387,395
| false
| null |
package com.alibagherifam.mentha.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.alibagherifam.mentha.R
val AppFontFamily = FontFamily(
Font(R.font.nunito_medium),
Font(R.font.nunito_bold, FontWeight.Bold)
)
val AppTypography = Typography(
displayLarge = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Bold,
fontSize = 24.sp,
letterSpacing = 0.sp
),
displayMedium = TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 21.sp,
letterSpacing = 0.sp
),
displaySmall = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Bold,
fontSize = 20.sp,
letterSpacing = 0.sp
),
headlineLarge = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Bold,
fontSize = 19.sp,
letterSpacing = 0.sp
),
headlineMedium = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
letterSpacing = 0.sp
),
headlineSmall = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Bold,
fontSize = 17.sp,
letterSpacing = 0.sp
),
titleLarge = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Bold,
fontSize = 16.sp,
letterSpacing = 0.sp
),
titleMedium = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Normal,
fontSize = 15.sp,
letterSpacing = 0.sp
),
titleSmall = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
letterSpacing = 0.sp
),
bodyLarge = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Normal,
fontSize = 15.sp,
letterSpacing = 0.sp
),
bodyMedium = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
letterSpacing = 0.sp
),
bodySmall = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
letterSpacing = 0.sp
),
labelLarge = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
letterSpacing = 0.sp
),
labelMedium = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = AppFontFamily,
fontWeight = FontWeight.Normal,
fontSize = 10.sp,
letterSpacing = 0.sp
)
)
| 1
|
Kotlin
|
1
| 9
|
35283da73663fbe24a0b15d75a8cfbeb4e203814
| 2,938
|
mentha
|
Apache License 2.0
|
stripe/src/main/java/com/stripe/android/view/DateUtils.kt
|
swdreams
| 235,817,887
| false
|
{"Kotlin": 190728, "Java": 131412}
|
package com.seamlesspay.ui.utils
import androidx.annotation.IntRange
import androidx.annotation.Size
import androidx.annotation.VisibleForTesting
import java.util.Calendar
internal object DateUtils {
private const val MAX_VALID_YEAR = 9980
/**
* Checks to see if the string input represents a valid month.
*
* @param monthString user input representing the month
* @return `true` if the string is a number between "01" and "12" inclusive,
* `false` otherwise
*/
@JvmStatic
fun isValidMonth(monthString: String?): Boolean {
return try {
monthString?.toInt() in 1..12
} catch (numEx: NumberFormatException) {
false
}
}
/**
* Separates raw string input of the format MMYY into a "month" group and a "year" group.
* Either or both of these may be incomplete. This method does not check to see if the input
* is valid.
*
* @param expiryInput up to four characters of user input
* @return a length-2 array containing the first two characters in the 0 index, and the last
* two characters in the 1 index. "123" gets split into {"12" , "3"}, and "1" becomes {"1", ""}.
*/
@Size(2)
@JvmStatic
fun separateDateStringParts(@Size(max = 4) expiryInput: String): Array<String> {
return if (expiryInput.length >= 2) {
listOf(
expiryInput.substring(0, 2),
expiryInput.substring(2)
).toTypedArray()
} else {
listOf(expiryInput, "").toTypedArray()
}
}
/**
* Checks whether or not the input month and year has yet expired.
*
* @param expiryMonth An integer representing a month. Only values 1-12 are valid,
* but this is called by user input, so we have to check outside that range.
* @param expiryYear An integer representing the full year (2017, not 17). Only positive values
* are valid, but this is called by user input, so we have to check outside
* for otherwise nonsensical dates. This code cannot validate years greater
* than [9980][MAX_VALID_YEAR] because of how we parse years in [convertTwoDigitYearToFour].
* @return `true` if the current month and year is the same as or later than the input
* month and year, `false` otherwise. Note that some cards expire on the first of the
* month, but we don't validate that here.
*/
@JvmStatic
fun isExpiryDataValid(expiryMonth: Int, expiryYear: Int): Boolean {
return isExpiryDataValid(expiryMonth, expiryYear, Calendar.getInstance())
}
@JvmStatic
fun isExpiryDataInThePast(expiryMonth: Int, expiryYear: Int): Boolean {
val calendar = Calendar.getInstance()
val currentYear = calendar.get(Calendar.YEAR)
return when {
expiryYear < currentYear -> true
else -> { // the card expires this year
val readableMonth = calendar.get(Calendar.MONTH) + 1
expiryMonth < readableMonth
}
}
}
@VisibleForTesting
@JvmStatic
fun isExpiryDataValid(expiryMonth: Int, expiryYear: Int, calendar: Calendar): Boolean {
if (expiryMonth < 1 || expiryMonth > 12) {
return false
}
if (expiryYear < 0 || expiryYear > MAX_VALID_YEAR) {
return false
}
val currentYear = calendar.get(Calendar.YEAR)
return when {
expiryYear < currentYear -> false
expiryYear > currentYear -> true
else -> { // the card expires this year
val readableMonth = calendar.get(Calendar.MONTH) + 1
expiryMonth >= readableMonth
}
}
}
/**
* Creates a string value to be entered into an expiration date text field
* without a divider. For instance, (1, 2020) => "0120". It doesn't matter if
* the year is two-digit or four. (1, 20) => "0120".
*
* Note: A four-digit year will be truncated, so (1, 2720) => "0120". If the year
* date is 3 digits, the data will be considered invalid and the empty string will be returned.
* A one-digit date is valid (represents 2001, for instance).
*
* @param month a month of the year, represented as a number between 1 and 12
* @param year a year number, either in two-digit form or four-digit form
* @return a length-four string representing the date, or an empty string if input is invalid
*/
@JvmStatic
fun createDateStringFromIntegerInput(
@IntRange(from = 1, to = 12) month: Int,
@IntRange(from = 0, to = 9999) year: Int
): String {
var monthString = month.toString()
if (monthString.length == 1) {
monthString = "0$monthString"
}
var yearString = year.toString()
// Three-digit years are invalid.
if (yearString.length == 3) {
return ""
}
if (yearString.length > 2) {
yearString = yearString.substring(yearString.length - 2)
} else if (yearString.length == 1) {
yearString = "0$yearString"
}
return monthString + yearString
}
/**
* Converts a two-digit input year to a four-digit year. As the current calendar year
* approaches a century, we assume small values to mean the next century. For instance, if
* the current year is 2090, and the input value is "18", the user probably means 2118,
* not 2018. However, in 2017, the input "18" probably means 2018. This code should be
* updated before the year 9981.
*
* @param inputYear a two-digit integer, between 0 and 99, inclusive
* @return a four-digit year
*/
@IntRange(from = 1000, to = 9999)
@JvmStatic
fun convertTwoDigitYearToFour(@IntRange(from = 0, to = 99) inputYear: Int): Int {
return convertTwoDigitYearToFour(inputYear, Calendar.getInstance())
}
@VisibleForTesting
@IntRange(from = 1000, to = 9999)
@JvmStatic
fun convertTwoDigitYearToFour(
@IntRange(from = 0, to = 99) inputYear: Int,
calendar: Calendar
): Int {
val year = calendar.get(Calendar.YEAR)
// Intentional integer division
var centuryBase = year / 100
if (year % 100 > 80 && inputYear < 20) {
centuryBase++
} else if (year % 100 < 20 && inputYear > 80) {
centuryBase--
}
return centuryBase * 100 + inputYear
}
}
| 11
|
Kotlin
|
1
| 2
|
e43ccf75a8c7972fab95098757f5f5cae6aa40b1
| 6,517
|
stripe-android
|
MIT License
|
kotlin/src/main/kotlin/net/timafe/angkor/domain/enums/EntityType.kt
|
developeramarish
| 421,096,390
| true
|
{"TypeScript": 249912, "Kotlin": 235138, "Go": 98214, "HTML": 71679, "HCL": 57246, "Makefile": 40023, "Shell": 31220, "SCSS": 27983, "Dockerfile": 4029, "JavaScript": 3892, "PLpgSQL": 2280, "CSS": 1037}
|
package net.timafe.angkor.domain.enums
import net.timafe.angkor.config.annotations.ManagedEntity
import java.util.*
enum class EntityType(val path: String) {
DISH("dishes"),
PLACE("places"),
NOTE("notes"),
AREA("areas"),
USER("users"),
LINK("links"),
VIDEO("videos"), // prefix (still) /links
FEED("feeds"), // prefix (still) /links
TOUR("tours"), // prefix (still) /links
EVENT("events");
// simply capitalize ... but the method was deprecated in kotlin, and this is what they came up with :-)
fun friendlyName() = name.lowercase()
.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
companion object {
fun fromEntityAnnotation(entity: Any): EntityType {
val annotations = entity::class.annotations
val ano =
annotations.firstOrNull { it is ManagedEntity } as? ManagedEntity // https://stackoverflow.com/a/39806461/4292075
return ano?.entityType
?: throw IllegalArgumentException("${entity::class} does not support ${ManagedEntity::class} Annotation")
}
}
}
| 0
| null |
0
| 0
|
f074d69eff8ba6768b5ecb0f9196e279ccb7bf7e
| 1,156
|
angkor
|
Apache License 2.0
|
src/main/java/be/hize/nes/features/misc/Facing.kt
|
superhize
| 668,339,493
| false
|
{"Kotlin": 159424, "Java": 33860}
|
package be.hize.nes.features.misc
import at.hannibal2.skyhanni.events.LorenzTickEvent
import at.hannibal2.skyhanni.utils.LorenzUtils
import be.hize.nes.NES
import be.hize.nes.events.GuiRenderEvent
import be.hize.nes.features.misc.coordinate.Facing
import be.hize.nes.utils.RenderUtils.renderStrings
import net.minecraft.client.Minecraft
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
class Facing {
private val config get() = NES.feature.misc.facing
private var display = emptyList<String>()
@SubscribeEvent
fun onRenderOverlay(event: GuiRenderEvent.GameOverlayRenderEvent) {
if (!isEnabled()) return
config.position.renderStrings(display, posLabel = "Facing")
}
private fun update() {
display = updateDisplay()
}
private fun updateDisplay() = buildList {
if (Minecraft.getMinecraft().thePlayer != null) {
add("§6Facing: §b${Facing.parse(Minecraft.getMinecraft().thePlayer.rotationYaw).abbreviated}")
}else{
return emptyList<String>()
}
}
@SubscribeEvent
fun onTick(event: LorenzTickEvent) {
if (!isEnabled()) return
update()
}
private fun isEnabled() = config.enabled && LorenzUtils.inSkyBlock
}
| 1
|
Kotlin
|
0
| 3
|
6d91b042c8c0822d5f1359bf7a92b98ae5da338e
| 1,264
|
NES-public
|
The Unlicense
|
v2-model/src/commonMain/kotlin/com/bselzer/gw2/v2/model/superadventurebox/zone/SabZone.kt
|
Woody230
| 388,820,096
| false
|
{"Kotlin": 750899}
|
package com.bselzer.gw2.v2.model.superadventurebox.zone
import com.bselzer.ktx.value.identifier.Identifiable
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class SabZone(
/**
* The id of the world.
*/
@SerialName("id")
override val id: SabZoneId = SabZoneId(),
/**
* The difficulty mode cleared.
*/
@SerialName("mode")
val difficulty: String = "",
/**
* The number of the world.
*/
@SerialName("world")
val world: Int = 0,
/**
* The number of the zone.
*/
@SerialName("zone")
val zone: Int = 0
) : Identifiable<SabZoneId, Int>
| 2
|
Kotlin
|
0
| 2
|
32f1fd4fc4252dbe886b6fc0f4310cf34ac2ef27
| 673
|
GW2Wrapper
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.