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
src/main/kotlin/com/github/vini2003/blade/common/widget/base/SlotListWidget.kt
Mixinors
285,046,508
false
null
package com.github.vini2003.blade.common.widget.base import com.github.vini2003.blade.Blade import com.github.vini2003.blade.client.data.PartitionedTexture import com.github.vini2003.blade.common.miscellaneous.Position import com.github.vini2003.blade.common.miscellaneous.Size import com.github.vini2003.blade.common.miscellaneous.Rectangle import com.github.vini2003.blade.common.utilities.Networks import com.github.vini2003.blade.common.utilities.Positions import com.github.vini2003.blade.common.collection.base.HandledWidgetCollection import com.github.vini2003.blade.common.collection.base.WidgetCollection import net.minecraft.client.render.VertexConsumerProvider import net.minecraft.client.util.math.MatrixStack import net.minecraft.inventory.Inventory import net.minecraft.inventory.SimpleInventory import kotlin.math.max import kotlin.math.min open class SlotListWidget( var inventory: Inventory = SimpleInventory(0), var widthInSlots: Int = 0, var heightInSlots: Int = 0, var maximumSlots: Int = 0 ) : AbstractWidget(), WidgetCollection { var scrollbarTexture = PartitionedTexture(Blade.identifier("textures/widget/scrollbar.png"), 18F, 18F, 0.11111111111111111111F, 0.11111111111111111111F, 0.11111111111111111111F, 0.16666666666666666667F) var scrollerTexture = PartitionedTexture(Blade.identifier("textures/widget/scroller.png"), 18F, 18F, 0.11111111111111111111F, 0.11111111111111111111F, 0.11111111111111111111F, 0.11111111111111111111F) var scrollerFocusTexture = PartitionedTexture(Blade.identifier("textures/widget/scroller_focus.png"), 18F, 18F, 0.11111111111111111111F, 0.11111111111111111111F, 0.11111111111111111111F, 0.11111111111111111111F) override val widgets: ArrayList<AbstractWidget> = ArrayList() private var row = 0 private var scrollerHeld = false private var updateScrollerRectangle: Boolean = false private var updateScrollbarRectangle: Boolean = false private var scrollerRectangleCached: Rectangle = Rectangle.empty() private var scrollbarRectangleCached: Rectangle = Rectangle.empty() private val bottomRow: Int get() = maximumSlots - heightInSlots private val totalRows: Int get() = inventory.size() / widthInSlots private val scrollerHeight: Float get() = min(size.height - 2, heightInSlots.toFloat() / totalRows.toFloat() * (size.height - 2)) private val scrollerY: Float get() = max(y + 2, min(y + size.height - scrollerHeight, row.toFloat() / totalRows.toFloat() * size.height + y + 1)) private val scrollerRectangle: Rectangle get() { return if (updateScrollerRectangle) { scrollerRectangleCached = Rectangle(Position.of(position.x + size.width - 1 - 16F, scrollerY - 1), Size.of(16F, scrollerHeight)) updateScrollerRectangle = false return scrollerRectangleCached } else { scrollerRectangleCached } } private val scrollbarRectangle: Rectangle get() { return if (updateScrollbarRectangle) { scrollbarRectangleCached = Rectangle(Position.of(position.x + size.width - 1 - 16F, position.y + 1), Size.of(16F, size.height - 2)) updateScrollbarRectangle = false return scrollbarRectangleCached } else { scrollbarRectangleCached } } override fun addWidget(widget: AbstractWidget) { widgets.add(widget) handled?.also { widget.onAdded(it, this) } widgets.forEach { _ -> widget.onLayoutChanged() } super.addWidget(widget) } override fun removeWidget(widget: AbstractWidget) { widgets.remove(widget) handled?.also { widget.onRemoved(it, this) } widgets.forEach { _ -> widget.onLayoutChanged() } super.removeWidget(widget) } override fun onLayoutChanged() { super.onLayoutChanged() updateScrollerRectangle = true updateScrollbarRectangle = true } override fun onAdded(handled: HandledWidgetCollection, immediate: WidgetCollection) { super.onAdded(handled, immediate) synchronize.add(Networks.MOUSE_SCROLL) synchronize.add(Networks.MOUSE_CLICK) widthInSlots = (size.width / 18 - 1).toInt() heightInSlots = (size.height / 18).toInt() maximumSlots = inventory.size() / widthInSlots for (h in 0 until heightInSlots) { for (w in 0 until widthInSlots) { if ((inventory.size() >= h + w)) { val slot = SlotWidget(0 + h * widthInSlots + w, inventory) slot.position = position.offset(w * 18, h * 18) slot.size = Size.of(18F, 18F) widgets.add(slot) immediate.addWidget(slot) } } } } override fun onMouseClicked(x: Float, y: Float, button: Int) { if (handler!!.client) { super.onMouseClicked(x, y, button) } if (scrollerRectangle.isWithin(x, y)) { scrollerHeld = true } else if (scrollbarRectangle.isWithin(x, y)) { if (y > scrollerY) { onMouseScrolled(x, y, -1.0) } else if (y < scrollerY) { onMouseScrolled(x, y, 1.0) } } } override fun onMouseReleased(x: Float, y: Float, button: Int) { if (handler!!.client) { super.onMouseReleased(x, y, button) } scrollerHeld = false } override fun onMouseDragged(x: Float, y: Float, button: Int, deltaX: Double, deltaY: Double) { if (handler!!.client) { super.onMouseDragged(x, y, button, deltaX, deltaY) } if (scrollerHeld) { if (deltaY > 0) { while (scrollerY < y - scrollerHeight / 2 && row < bottomRow) { onMouseScrolled(x, y, -deltaY) } } else if (deltaY < 0) { while (scrollerY > y - scrollerHeight / 2 && row > 0) { onMouseScrolled(x, y, -deltaY) } } } } override fun onMouseScrolled(x: Float, y: Float, deltaY: Double) { if (handler!!.client) { if (focused || scrollerHeld) { super.onMouseScrolled(x, y, deltaY) } else { return } } if (deltaY > 0 && row > 0) { --row widgets.forEach { it as SlotWidget val slot = it.backendSlot!! if (slot.index - widthInSlots >= 0) { slot.index = slot.index - widthInSlots } handler!!.sendContentUpdates() } } else if (deltaY < 0 && row < bottomRow) { ++row widgets.forEach { it as SlotWidget val slot = it.backendSlot!! if (slot.index + widthInSlots <= inventory.size()) { slot.index = slot.index + widthInSlots } handler!!.sendContentUpdates() } } updateScrollerRectangle = true updateScrollbarRectangle = true } override fun drawWidget(matrices: MatrixStack, provider: VertexConsumerProvider) { if (hidden) return scrollbarTexture.draw(matrices, provider, position.x + size.width - 18F, position.y, 18F, size.height) val scrollerFocus = scrollerRectangle.isWithin(Positions.mouseX, Positions.mouseY) if (scrollerFocus || scrollerHeld) { scrollerFocusTexture.draw(matrices, provider, position.x + size.width - 18F + 1F, scrollerY - 1, 16F, scrollerHeight) } else { scrollerTexture.draw(matrices, provider, position.x + size.width - 18F + 1F, scrollerY - 1, 16F, scrollerHeight) } } }
0
Kotlin
0
6
95573c8c2fc9cfd268ebab6dcb86f74857731323
6,837
Blade
Creative Commons Zero v1.0 Universal
app/src/main/java/io/github/alessandrojean/toshokan/service/cover/CoverProviderWebsite.kt
alessandrojean
495,493,156
false
null
package io.github.alessandrojean.toshokan.service.cover import androidx.annotation.StringRes import io.github.alessandrojean.toshokan.R enum class CoverProviderWebsite(@StringRes val title: Int, val url: String) { AMAZON(R.string.amazon, "https://amazon.com"), LOJA_PANINI(R.string.loja_panini, "https://panini.com.br"), JBC(R.string.jbc, "https://editorajbc.com.br"), NEWPOP(R.string.newpop, "https://www.newpop.com.br"), PIPOCA_E_NANQUIM(R.string.pipoca_e_nanquim, "https://pipocaenanquim.com.br"), SHUEISHA(R.string.shueisha, "https://www.shueisha.co.jp"), VENETA(R.string.veneta, "https://veneta.com.br"), VIZ_MEDIA(R.string.viz_media, "https://www.viz.com/read") }
11
Kotlin
1
5
96717312b7a5090901c8604cd069d9468995e99e
688
toshokan-android
MIT License
src/main/kotlin/com/pms/placemanagementsystemserverside/service/user/impl/UserServiceImpl.kt
sge-sistema-gerenciador-de-espacos
178,943,974
false
null
package com.pms.placemanagementsystemserverside.service.user.impl import com.pms.placemanagementsystemserverside.dto.ProfessorLackPostRequest import com.pms.placemanagementsystemserverside.models.enums.ActivationModelStatusEnum import com.pms.placemanagementsystemserverside.models.enums.UserTypeEnum import com.pms.placemanagementsystemserverside.models.user.UserModel import com.pms.placemanagementsystemserverside.repository.user.UserRepository import com.pms.placemanagementsystemserverside.service.space.SpaceService import com.pms.placemanagementsystemserverside.service.user.UserService import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service @Service class UserServiceImpl : UserService { @Autowired private lateinit var spaceService: SpaceService @Autowired private lateinit var userRepository: UserRepository override fun create(userModel: UserModel): UserModel { return userRepository.create(userModel) } override fun read(): List<UserModel> { return userRepository.read() } override fun readActiveByType(userTypeEnum: UserTypeEnum): List<UserModel> { return read().filter { it.type == userTypeEnum && it.status == ActivationModelStatusEnum.ACTIVE } } override fun update(userModel: UserModel) { if (userModel.status == ActivationModelStatusEnum.INACTIVE) { val date = DateTimeFormat.forPattern("yyyy-MM-dd").print(DateTime()) userModel.evasionDate = date } userRepository.update(userModel) } override fun delete(id: Long) { userRepository.delete(id) } override fun professorLack(professorLackPostRequest: ProfessorLackPostRequest) { val professor = userRepository.read().find { it.id == professorLackPostRequest.professorId }!! spaceService.read().forEach { space -> space.schedulingModels.forEach { scheduling -> if (professor.id == scheduling.professor?.id) { scheduling.schedulingDateModels.forEach { if (it.date == professorLackPostRequest.date) { it.status = ActivationModelStatusEnum.INACTIVE } } } } } professor.professorLack = professorLackPostRequest.date } }
0
Kotlin
0
0
d402ddb56d523062a4cfbff245a1c4d49aec7ba6
2,484
place-management-system-server-side
MIT License
app/src/main/java/com/fuchsia/shotokanwkf/activity/NavBar.kt
fuchsialab
373,359,223
false
{"Kotlin": 107961, "Java": 42854}
package com.fuchsia.shotokanwkf.activity import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.view.View import android.view.WindowManager import android.widget.ImageView import android.widget.LinearLayout import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.blogspot.atifsoftwares.animatoolib.Animatoo import com.fuchsia.shotokanwkf.R @Suppress("DEPRECATION") class NavBar : AppCompatActivity() { var home:LinearLayout? = null var share:LinearLayout? = null var policy:LinearLayout? = null var moreapp:LinearLayout? = null var rate:LinearLayout? = null @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_nav_bar) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;// set status text dark home = findViewById(R.id.home) home?.setOnClickListener { finish() Animatoo.animateSwipeLeft(this); } share = findViewById(R.id.share) share?.setOnClickListener { val sharingIntent = Intent(Intent.ACTION_SEND) sharingIntent.type = "text/plain" val shareBody = "Download Shotokan Karate App and Learn. https://play.google.com/store/apps/details?id=com.fuchsia.shotokanwkf" sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Shotokan WKF") sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody) startActivity(Intent.createChooser(sharingIntent, "Share via")) finish() } policy = findViewById(R.id.policy) policy?.setOnClickListener { val browse = Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.lkmkm))) startActivity(browse) finish() } moreapp = findViewById(R.id.moreapp) moreapp?.setOnClickListener { val browses = Intent( Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/collection/cluster?clp=igM4ChkKEzUzNjIwODY3OTExNjgyNTA2MTkQCBgDEhkKEzUzNjIwODY3OTExNjgyNTA2MTkQCBgDGAA%3D:S:ANO1ljJMw2s&gsr=CjuKAzgKGQoTNTM2MjA4Njc5MTE2ODI1MDYxORAIGAMSGQoTNTM2MjA4Njc5MTE2ODI1MDYxORAIGAMYAA%3D%3D:S:ANO1ljI3U6g") ) startActivity(browses) finish() } rate = findViewById(R.id.rate) rate?.setOnClickListener { val appPackageName = packageName try { startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("market://details?id=$appPackageName") ) ) } catch (anfe: ActivityNotFoundException) { startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName") ) ) } finish() } val arow = findViewById<ImageView>(R.id.arrow) arow.setOnClickListener { finish() Animatoo.animateSwipeLeft(this); } } @Deprecated("Deprecated in Java") override fun onBackPressed() { finish() Animatoo.animateSwipeLeft(this); } }
0
Kotlin
0
0
7412c05f58da6423ba8f273873aee7ee1417e6b3
3,944
Shotokan-WKF
MIT License
chatkit/src/main/java/com/ekoapp/ekosdk/uikit/chat/messages/adapter/EkoMessageItemUtil.kt
AmityCo
313,244,597
false
null
package com.ekoapp.ekosdk.uikit.chat.messages.adapter import android.view.LayoutInflater import android.view.ViewGroup import com.ekoapp.ekosdk.EkoClient import com.ekoapp.ekosdk.message.EkoMessage import com.ekoapp.ekosdk.uikit.chat.R import com.ekoapp.ekosdk.uikit.chat.messages.viewHolder.* import com.ekoapp.ekosdk.uikit.chat.messages.viewModel.EkoAudioMsgViewModel import com.ekoapp.ekosdk.uikit.chat.messages.viewModel.EkoImageMsgViewModel import com.ekoapp.ekosdk.uikit.chat.messages.viewModel.EkoTextMessageViewModel import com.ekoapp.ekosdk.uikit.chat.messages.viewModel.EkoUnknownMsgViewModel import com.ekoapp.ekosdk.uikit.chat.util.MessageType class EkoMessageItemUtil { fun getViewHolder( inflater: LayoutInflater, parent: ViewGroup, itemType: Int, iViewHolder: EkoMessageListAdapter.ICustomViewHolder?, listener: IAudioPlayCallback ): EkoChatMessageBaseViewHolder { return when (itemType) { MessageType.MESSAGE_ID_TEXT_RECEIVER -> getReceiverTextMsgViewHolder( inflater, parent, itemType, iViewHolder ) MessageType.MESSAGE_ID_TEXT_SENDER -> getSenderTextMsgViewHolder( inflater, parent, itemType, iViewHolder ) MessageType.MESSAGE_ID_IMAGE_RECEIVER -> getReceiverImageMsgViewHolder( inflater, parent, itemType, iViewHolder ) MessageType.MESSAGE_ID_IMAGE_SENDER -> getSenderImageMsgViewHolder( inflater, parent, itemType, iViewHolder ) MessageType.MESSAGE_ID_AUDIO_RECEIVER -> getReceiverAudioMsgViewHolder( inflater, parent, itemType, iViewHolder, listener ) MessageType.MESSAGE_ID_AUDIO_SENDER -> getSenderAudioMsgViewHolder( inflater, parent, itemType, iViewHolder, listener ) MessageType.MESSAGE_ID_CUSTOM_RECEIVER -> getReceiverCustomMessageViewHolder( inflater, parent, itemType, iViewHolder ) MessageType.MESSAGE_ID_CUSTOM_SENDER -> getSenderCustomMessageViewHolder( inflater, parent, itemType, iViewHolder ) else -> getUnknownMessageViewHolder(inflater, parent) } } private fun getReceiverTextMsgViewHolder( inflater: LayoutInflater, parent: ViewGroup, itemType: Int, iViewHolder: EkoMessageListAdapter.ICustomViewHolder? ): EkoChatMessageBaseViewHolder { return if (iViewHolder?.getViewHolder(inflater, parent, itemType) != null) { iViewHolder.getViewHolder(inflater, parent, itemType)!! } else { val itemViewModel = EkoTextMessageViewModel() EkoTextMsgReceiverViewHolder( inflater.inflate( R.layout.amity_item_text_message_receiver, parent, false ), itemViewModel, parent.context ) } } private fun getSenderTextMsgViewHolder( inflater: LayoutInflater, parent: ViewGroup, itemType: Int, iViewHolder: EkoMessageListAdapter.ICustomViewHolder? ): EkoChatMessageBaseViewHolder { return if (iViewHolder?.getViewHolder(inflater, parent, itemType) != null) { iViewHolder.getViewHolder(inflater, parent, itemType)!! } else { val itemViewModel = EkoTextMessageViewModel() EkoTextMsgSenderViewHolder( inflater.inflate( R.layout.amity_item_text_message_sender, parent, false ), itemViewModel, parent.context ) } } private fun getReceiverImageMsgViewHolder( inflater: LayoutInflater, parent: ViewGroup, itemType: Int, iViewHolder: EkoMessageListAdapter.ICustomViewHolder? ): EkoChatMessageBaseViewHolder { return if (iViewHolder?.getViewHolder(inflater, parent, itemType) != null) { iViewHolder.getViewHolder(inflater, parent, itemType)!! } else { val itemViewModel = EkoImageMsgViewModel() EkoImageMsgReceiverViewHolder( inflater.inflate( R.layout.amity_item_image_msg_receiver, parent, false ), itemViewModel, parent.context ) } } private fun getSenderImageMsgViewHolder( inflater: LayoutInflater, parent: ViewGroup, itemType: Int, iViewHolder: EkoMessageListAdapter.ICustomViewHolder? ): EkoChatMessageBaseViewHolder { return if (iViewHolder?.getViewHolder(inflater, parent, itemType) != null) { iViewHolder.getViewHolder(inflater, parent, itemType)!! } else { val itemViewModel = EkoImageMsgViewModel() EkoImageMsgSenderViewHolder( inflater.inflate( R.layout.amity_item_image_msg_sender, parent, false ), itemViewModel, parent.context ) } } private fun getReceiverAudioMsgViewHolder( inflater: LayoutInflater, parent: ViewGroup, itemType: Int, iViewHolder: EkoMessageListAdapter.ICustomViewHolder?, listener: IAudioPlayCallback ): EkoChatMessageBaseViewHolder { return if (iViewHolder?.getViewHolder(inflater, parent, itemType) != null) { iViewHolder.getViewHolder(inflater, parent, itemType)!! } else { val itemViewModel = EkoAudioMsgViewModel() EkoAudioMsgReceiverViewHolder( inflater.inflate( R.layout.amity_item_audio_message_receiver, parent, false ), itemViewModel, parent.context, listener ) } } private fun getSenderAudioMsgViewHolder( inflater: LayoutInflater, parent: ViewGroup, itemType: Int, iViewHolder: EkoMessageListAdapter.ICustomViewHolder?, listener: IAudioPlayCallback ): EkoChatMessageBaseViewHolder { return if (iViewHolder?.getViewHolder(inflater, parent, itemType) != null) { iViewHolder.getViewHolder(inflater, parent, itemType)!! } else { val itemViewModel = EkoAudioMsgViewModel() EkoAudioMsgSenderViewHolder( inflater.inflate( R.layout.amity_item_audio_message_sender, parent, false ), itemViewModel, parent.context, listener ) } } private fun getUnknownMessageViewHolder(inflater: LayoutInflater, parent: ViewGroup): EkoChatMessageBaseViewHolder { return EkoUnknownMessageViewHolder( inflater.inflate( R.layout.amity_item_unknown_message, parent, false ), EkoUnknownMsgViewModel() ) } private fun getSenderCustomMessageViewHolder( inflater: LayoutInflater, parent: ViewGroup, itemType: Int, iViewHolder: EkoMessageListAdapter.ICustomViewHolder? ): EkoChatMessageBaseViewHolder { return if (iViewHolder?.getViewHolder(inflater, parent, itemType) != null) { iViewHolder.getViewHolder(inflater, parent, itemType)!! } else { EkoUnknownMessageViewHolder( inflater.inflate( R.layout.amity_item_unknown_message, parent, false ), EkoUnknownMsgViewModel() ) } } private fun getReceiverCustomMessageViewHolder( inflater: LayoutInflater, parent: ViewGroup, itemType: Int, iViewHolder: EkoMessageListAdapter.ICustomViewHolder? ): EkoChatMessageBaseViewHolder { return if (iViewHolder?.getViewHolder(inflater, parent, itemType) != null) { iViewHolder.getViewHolder(inflater, parent, itemType)!! } else { EkoUnknownMessageViewHolder( inflater.inflate( R.layout.amity_item_unknown_message, parent, false ), EkoUnknownMsgViewModel() ) } } fun getMessageType(message: EkoMessage?): Int { if (message == null) { return MessageType.MESSAGE_ID_UNKNOWN } return getContentType(message, message.getUserId() == EkoClient.getUserId()) } private fun getContentType(message: EkoMessage, isSelf: Boolean): Int { return when (message.getDataType()) { EkoMessage.DataType.TEXT -> if (isSelf) { MessageType.MESSAGE_ID_TEXT_SENDER } else { MessageType.MESSAGE_ID_TEXT_RECEIVER } EkoMessage.DataType.IMAGE -> if (isSelf) { MessageType.MESSAGE_ID_IMAGE_SENDER } else { MessageType.MESSAGE_ID_IMAGE_RECEIVER } EkoMessage.DataType.FILE -> if (isSelf) { MessageType.MESSAGE_ID_FILE_SENDER } else { MessageType.MESSAGE_ID_FILE_RECEIVER } EkoMessage.DataType.AUDIO -> if (isSelf) { MessageType.MESSAGE_ID_AUDIO_SENDER } else { MessageType.MESSAGE_ID_AUDIO_RECEIVER } EkoMessage.DataType.CUSTOM -> if (isSelf) { MessageType.MESSAGE_ID_CUSTOM_SENDER } else { MessageType.MESSAGE_ID_CUSTOM_RECEIVER } else -> MessageType.MESSAGE_ID_UNKNOWN } } }
4
Kotlin
1
0
d4fe097da96f71ab281c9b39fafdaa901aed377c
10,021
ASC-UIKit-Android
Microsoft Public License
src/main/kotlin/net/wiredtomato/letsgocooking/LetsGoCooking.kt
wired-tomato
849,024,713
false
{"Kotlin": 52296, "Java": 1664}
package net.wiredtomato.letsgocooking import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking import net.minecraft.util.Identifier import net.wiredtomato.letsgocooking.api.player.gameData import net.wiredtomato.letsgocooking.api.registry.LGCRegistries import net.wiredtomato.letsgocooking.init.LGCBlocks import net.wiredtomato.letsgocooking.init.LGCGameTypes import net.wiredtomato.letsgocooking.init.LGCItems import net.wiredtomato.letsgocooking.init.LGCScreens import net.wiredtomato.letsgocooking.networking.GameElementInteractionPayload import org.slf4j.Logger import org.slf4j.LoggerFactory @Suppress("unused") object LetsGoCooking { const val MODID = "lets_go_cooking" @JvmField val log: Logger = LoggerFactory.getLogger(LetsGoCooking::class.simpleName) fun init() { LGCRegistries LGCItems LGCBlocks LGCGameTypes LGCScreens log.info("Hello from Common") PayloadTypeRegistry.playC2S().register(GameElementInteractionPayload.ID, GameElementInteractionPayload.CODEC) ServerPlayNetworking.registerGlobalReceiver(GameElementInteractionPayload.ID) { payload, ctx -> val player = ctx.player() val currentGame = player.gameData.currentGame currentGame?.handleServerElementInteraction(payload.elementId, player, payload.interaction) } } fun id(path: String) = Identifier.of(MODID, path) }
0
Kotlin
0
0
27e3c1c7e88fbb36b6eb18ab7b6c80a5c5e84ba2
1,500
LetsGoCooking
MIT License
feature/recognize-text/src/main/java/ru/tech/imageresizershrinker/feature/recognize/text/presentation/components/UiDownloadData.kt
T8RIN
478,710,402
false
null
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package ru.tech.imageresizershrinker.feature.recognize.text.presentation.components import android.os.Parcelable import kotlinx.parcelize.Parcelize import ru.tech.imageresizershrinker.feature.recognize.text.domain.DownloadData import ru.tech.imageresizershrinker.feature.recognize.text.domain.RecognitionType @Parcelize data class UiDownloadData( val type: RecognitionType, val languageCode: String, val name: String, val localizedName: String ) : Parcelable fun DownloadData.toUi() = UiDownloadData(type, languageCode, name, localizedName)
24
null
90
3,817
486410d4a9ea3c832fc5aa63eb5bdc7b1fab871d
1,260
ImageToolbox
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/appstream/CfnApplicationEntitlementAssociationPropsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.appstream import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.appstream.CfnApplicationEntitlementAssociationProps @Generated public fun buildCfnApplicationEntitlementAssociationProps(initializer: @AwsCdkDsl CfnApplicationEntitlementAssociationProps.Builder.() -> Unit): CfnApplicationEntitlementAssociationProps = CfnApplicationEntitlementAssociationProps.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
535
aws-cdk-kt
Apache License 2.0
app/src/main/java/com/rohitneel/instagramclone/ui/screen/FeedScreen.kt
rohitneel1234
741,797,976
false
{"Kotlin": 120113}
package com.rohitneel.instagramclone.ui.screen import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CornerSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.AddCircle import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarColors import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.graphics.toColorInt import androidx.navigation.NavController import com.rohitneel.instagramclone.viewmodel.InstagramViewModel import com.rohitneel.instagramclone.R import com.rohitneel.instagramclone.common.CommonImage import com.rohitneel.instagramclone.common.CommonProgressSpinner import com.rohitneel.instagramclone.common.LikeAnimation import com.rohitneel.instagramclone.common.NavParams import com.rohitneel.instagramclone.common.UserImageCard import com.rohitneel.instagramclone.common.navigateTo import com.rohitneel.instagramclone.models.PostData import com.rohitneel.instagramclone.models.Stories import com.rohitneel.instagramclone.navigation.DestinationScreen import com.rohitneel.instagramclone.ui.theme.LIGHT_BLUE import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun FeedScreen(navController: NavController, viewModel: InstagramViewModel) { val userDataLoading = viewModel.inProgress.value val userData = viewModel.userData.value val personalizedFeed = viewModel.postFeed.value val personalizedFeedLoading = viewModel.postFeedProgress.value Column( modifier = Modifier .fillMaxSize() .background(Color.LightGray) ) { TopAppBar(title = { Image( painter = painterResource(id = R.drawable.ic_instagram_title_logo), contentDescription = null, Modifier.padding(8.dp) ) }, colors = TopAppBarColors( containerColor = Color.White, scrolledContainerColor = Color.White, navigationIconContentColor = Color.White, titleContentColor = Color.White, actionIconContentColor = Color.Black ), actions = { Row { IconButton(onClick = { //navController.navigate(NavigationItem.Notification.route) }) { Icon( painterResource(id = R.drawable.ic_notifications), contentDescription = null, Modifier.padding(8.dp) ) } IconButton(onClick = { //navController.navigate(NavigationItem.ChatList.route) }) { Icon( painterResource(id = R.drawable.ic_message), contentDescription = null, Modifier.padding(8.dp) ) } } }) Row( modifier = Modifier .fillMaxWidth() .wrapContentHeight() .background(Color.White) ) { Column { Box( modifier = Modifier .clickable { } ) { UserImageCard(userImage = userData?.imageUrl) Card( shape = CircleShape, border = BorderStroke(width = 2.dp, color = Color.White), modifier = Modifier .size(32.dp) .align(Alignment.BottomEnd) .padding(bottom = 8.dp, end = 8.dp) ) { Icon( tint = LIGHT_BLUE, imageVector = Icons.Default.AddCircle, contentDescription = null ) } } Text( text = "Your story", fontSize = 10.sp, textAlign = TextAlign.Center, modifier = Modifier.width(60.dp).padding(start = 10.dp), overflow = TextOverflow.Ellipsis, maxLines = 1 ) } StoriesSection(storyList = getStories()) } PostsList( posts = personalizedFeed, modifier = Modifier.weight(1f), loading = personalizedFeedLoading or userDataLoading, navController = navController, viewModel = viewModel, currentUserId = userData?.userId ?: "" ) } } @Composable fun StoriesSection(storyList: List<Stories>) { LazyRow { items(storyList) {story -> StoryItem(story = story) } } } fun getStories(): List<Stories> = listOf( Stories(userName = "instagram", profile = R.drawable.ic_instagram_app_logo), Stories(userName = "instagram", profile = R.drawable.ic_instagram_app_logo), Stories(userName = "instagram", profile = R.drawable.ic_instagram_app_logo), Stories(userName = "instagram", profile = R.drawable.ic_instagram_app_logo) ) @Composable fun StoryItem(story: Stories) { Column(modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp)) { Image( painter = painterResource(id = story.profile), contentDescription = "story title", modifier = Modifier .size(60.dp) .border( width = 2.dp, brush = Brush.linearGradient( listOf( Color("#DE0046".toColorInt()), Color("#F7A34B".toColorInt()) ) ), shape = CircleShape ) .padding(5.dp) .clip(CircleShape), contentScale = ContentScale.Crop ) Spacer(modifier = Modifier.height(4.dp)) Text( text = story.userName, fontSize = 10.sp, textAlign = TextAlign.Center, modifier = Modifier.width(60.dp), overflow = TextOverflow.Ellipsis, maxLines = 1 ) } } @Composable fun PostsList( posts: List<PostData>, modifier: Modifier, loading: Boolean, navController: NavController, viewModel: InstagramViewModel, currentUserId: String ) { Box(modifier = modifier) { LazyColumn { items(items = posts) { Post(post = it, currentUserId = currentUserId, viewModel = viewModel) { navigateTo( navController, DestinationScreen.SinglePost, NavParams("post", it) ) } } } if (loading) { CommonProgressSpinner() } } } @Composable fun Post(post: PostData, currentUserId: String, viewModel: InstagramViewModel, onPostClick: () -> Unit) { val likeAnimation = remember { mutableStateOf(false) } val dislikeAnimation = remember { mutableStateOf(false) } Card( shape = RoundedCornerShape(corner = CornerSize(4.dp)), modifier = Modifier .fillMaxWidth() .wrapContentHeight() .padding(top = 4.dp, bottom = 4.dp) ) { Column { Row( modifier = Modifier .fillMaxWidth() .height(50.dp) .background(Color.White), verticalAlignment = Alignment.CenterVertically ) { Card(shape = CircleShape, modifier = Modifier .padding(4.dp) .size(32.dp) ) { CommonImage(data = post.userImage, contentScale = ContentScale.Crop) } Text(text = post.userName ?: "", fontWeight = FontWeight.Bold, modifier = Modifier.padding(4.dp)) } Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { val modifier = Modifier .fillMaxWidth() .defaultMinSize(minHeight = 150.dp) .pointerInput(Unit) { detectTapGestures( onDoubleTap = { if (post.likes?.contains(currentUserId) == true) { dislikeAnimation.value = true } else { likeAnimation.value = true } viewModel.onLikePost(post) }, onTap = { onPostClick.invoke() } ) } CommonImage( data = post.postImage, modifier = modifier, contentScale = ContentScale.FillWidth ) if (likeAnimation.value) { CoroutineScope(Dispatchers.Main).launch { delay(1000L) likeAnimation.value = false } LikeAnimation() } if (dislikeAnimation.value) { CoroutineScope(Dispatchers.Main).launch { delay(1000L) dislikeAnimation.value = false } LikeAnimation() } } } } }
0
Kotlin
0
1
b16cc6f8b65a2024cc824d20da2921ae628fea47
12,024
Instagram-clone
MIT License
Basics/AllAboutFunc.kt
uzairkabeer1
567,604,702
false
null
fun main() { println("Enter your name: ") val name = readLine()!! val cond = displayGreeting(name) println(message = cond) val values = displayGreet("Umair") println(values) var sum = addition(10, 20, 30, 40) println("The sum of numbers are: $sum") } //simple function fun displayGreeting(name: String): Boolean { println("Hi, $name how are you going?") return true } /* the parameters are declared explicitly by "val" means they're immutable even in the func */ //single expression functions fun displayGreet(name: String): String = "Hi, $name how are you going" //using vararg as a function parameter fun addition(vararg number: Int): Int { var result: Int = 0 for (num in number) { result += num } return result }// vararg basically works like an arrayList
0
Kotlin
0
1
7f81f1f983b44d63d1b3419d883183ab379cf3b6
829
Full-Kotlin-Guide
MIT License
1/ColorMyView/app/src/main/java/udacity/aos/colormyview/MainActivity.kt
chiaz91
393,010,970
false
null
package udacity.aos.colormyview import android.graphics.Color import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setListeners() } /** * Attaches listeners to all the views. */ private fun setListeners(){ // add 'kotlin-android-extensions' plugin in build.gradle val clickableViews: List<View> = listOf(box_one_text, box_two_text, box_three_text, box_four_text, box_five_text, constraint_layout, red_button, yellow_button, green_button) for (item in clickableViews) { item.setOnClickListener { makeColored(item) } } } /** * Sets the background color of a view depending on it's resource id. * This is a way of using one click handler to do similar operations on a group of views. * * Demonstrates three different ways of setting colors. * * Using a color constant from the Color class. * * Using an Android color resource * * Using a custom color defined in color.xml */ fun makeColored(view: View) { when (view.id) { // Boxes using Color class colors for background R.id.box_one_text -> view.setBackgroundColor(Color.DKGRAY) R.id.box_two_text -> view.setBackgroundColor(Color.GRAY) // Boxes using Android color resources for background R.id.box_three_text -> view.setBackgroundResource(android.R.color.holo_green_light) R.id.box_four_text -> view.setBackgroundResource(android.R.color.holo_green_dark) R.id.box_five_text -> view.setBackgroundResource(android.R.color.holo_green_light) // Boxes using custom colors for background R.id.red_button -> box_three_text.setBackgroundResource(R.color.my_red) R.id.yellow_button -> box_four_text.setBackgroundResource(R.color.my_yellow) R.id.green_button -> box_five_text.setBackgroundResource(R.color.my_green) else -> view.setBackgroundColor(Color.LTGRAY) } } }
0
Kotlin
0
0
670b2447b3826bd56bd29ad984871e267def9423
2,348
udacity-aos-learn
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/ZeroSymmetric.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: ZeroSymmetric * * Full name: System`ZeroSymmetric * * ZeroSymmetric[{s , …, s }] represents the symmetry of a zero tensor in the slots s . * Usage: 1 n i * * Options: None * * Attributes: Protected * * local: paclet:ref/ZeroSymmetric * Documentation: web: http://reference.wolfram.com/language/ref/ZeroSymmetric.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun zeroSymmetric(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("ZeroSymmetric", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,090
mathemagika
Apache License 2.0
app/src/test/java/com/miguelbrmfreitas/itunes_searcher/DoubleExtensionsTest.kt
MiguelbrmFreitas
548,562,167
false
{"Kotlin": 31180}
package com.miguelbrmfreitas.itunes_searcher import com.miguelbrmfreitas.domain.util.extensions.toPrice import org.junit.Assert import org.junit.Test class DoubleExtensionsTest { companion object { const val FAKE_DOUBLE_1 = 2.19 const val FAKE_DOUBLE_2 = 0.99 } @Test fun givenDouble_toPrice_conversionIsCorrect() { Assert.assertEquals("$2.19", FAKE_DOUBLE_1.toPrice()) Assert.assertEquals("$0.99", FAKE_DOUBLE_2.toPrice()) } }
0
Kotlin
0
4
330dec36427618e74ae5bf132889d5fba3b0e87f
482
iTunes-searcher
MIT License
src/main/kotlin/top/ntutn/starseasdk/proxy/AliasProcessor.kt
rfkhx
523,771,073
false
null
package top.ntutn.starseasdk.proxy import com.google.auto.service.AutoService import javax.annotation.processing.AbstractProcessor import javax.annotation.processing.Processor import javax.annotation.processing.RoundEnvironment import javax.annotation.processing.SupportedAnnotationTypes import javax.lang.model.element.TypeElement import javax.tools.FileObject import javax.tools.StandardLocation @AutoService(Processor::class) @SupportedAnnotationTypes("top.ntutn.starseasdk.proxy.NewestApi") class AliasProcessor : AbstractProcessor() { override fun process(set: MutableSet<out TypeElement>?, roundEnvironment: RoundEnvironment?): Boolean { if (set.isNullOrEmpty() || roundEnvironment == null) { return false } val outputPackageName = processingEnv.options["aliasprocessor.package"]!! val suffix = processingEnv.options["aliasprocessor.suffix"]?:"" var outputContent = """ package $outputPackageName /** * generated by AliasProcessor * 这个类是对tg机器人框架starsea提供的最新版本API的alias * 用于固定包名,避免升级版本号后有一大片包名要改 * have a nice day. */ """.trimIndent() roundEnvironment.getElementsAnnotatedWith(NewestApi::class.java).forEach { it as TypeElement outputContent += "\ntypealias ${it.simpleName}${suffix} = ${it.qualifiedName}\n" } val filerSourceFile: FileObject = processingEnv.filer.createResource( StandardLocation.SOURCE_OUTPUT, outputPackageName, "CompatAlias.kt" ) with(filerSourceFile.openOutputStream()) { write(outputContent.toByteArray()) flush() close() } return true } }
1
Kotlin
0
0
d957445fcb8ef99e73b5809ff15780805c46fe43
1,780
starseasdk
MIT License
yc-core-ical/src/test/kotlin/mikufan/cx/yc/core/ical/util/ResourceUtil.kt
CXwudi
556,059,867
false
{"Kotlin": 89778, "Java": 718}
package mikufan.cx.yc.core.ical.util import org.springframework.util.ResourceUtils /** * @author CX无敌 * 2023-01-03 */ fun loadResourceAsString(resourceName: String): String { val stream = ResourceUtils::class.java.classLoader.getResourceAsStream(resourceName) if (stream != null) { return stream.bufferedReader().use { it.readText() } } else { throw IllegalArgumentException("resource not found: $resourceName") } }
5
Kotlin
0
2
68604d12d99970d11887376f86cdfda9c7373abf
438
youcal
MIT License
android/src/main/java/dev/matinzd/healthconnect/utils/ExceptionsUtils.kt
matinzd
586,126,466
false
null
package dev.matinzd.healthconnect.utils import android.os.RemoteException import com.facebook.react.bridge.Promise import okio.IOException class ClientNotInitialized : Exception("Health Connect client is not initialized") class InvalidRecordType : Exception("Record type is not valid") class InvalidTemperature : Exception("Temperature is not valid") class InvalidEnergy : Exception("Energy is not valid") class InvalidPower : Exception("Power is not valid") class InvalidBloodGlucoseLevel : Exception("Blood glucose level is not valid") class InvalidBloodPressure : Exception("Blood pressure is not valid") class InvalidMass : Exception("Mass is not valid") class InvalidLength : Exception("Length is not valid") class AggregationNotSupported : Exception("Aggregation is not supported for this record") fun Promise.rejectWithException(exception: Exception) { val code = when (exception) { is SecurityException -> "PERMISSION_ERROR" is UnsupportedOperationException -> "SDK_VERSION_ERROR" is IOException -> "IO_EXCEPTION" is IllegalStateException -> "SERVICE_UNAVAILABLE" is IllegalArgumentException -> "ARGUMENT_VALIDATION_ERROR" is RemoteException -> "UNDERLYING_ERROR" is InvalidRecordType -> "INVALID_RECORD_TYPE" is ClientNotInitialized -> "CLIENT_NOT_INITIALIZED" is InvalidTemperature -> "INVALID_TEMPERATURE" is InvalidEnergy -> "INVALID_ENERGY" is InvalidPower -> "INVALID_POWER" is InvalidBloodGlucoseLevel -> "INVALID_BLOOD_GLUCOSE_LEVEL" is InvalidBloodPressure -> "INVALID_BLOOD_PRESSURE" is InvalidMass -> "INVALID_MASS" is AggregationNotSupported -> "AGGREGATION_NOT_SUPPORTED" else -> "UNKNOWN_ERROR" } this.reject(code, exception.message) }
4
null
12
98
018e38a57290ea065eed8f20b472e88b883aa763
1,732
react-native-health-connect
MIT License
app/android/ui/app/public/src/main/kotlin/build/wallet/ui/app/dev/UiModelNotImplemented.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.ui.app.dev import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import build.wallet.ui.components.label.Label import build.wallet.ui.model.Model import build.wallet.ui.tokens.LabelType import build.wallet.ui.tooling.PreviewWalletTheme @Composable internal fun UiModelNotImplemented(model: Model) { Box( modifier = Modifier .fillMaxSize() .border(width = 5.dp, color = Color.Red) .padding(5.dp), contentAlignment = Alignment.Center ) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Label( text = "\uD83D\uDEA7 Can’t display ${model::class.simpleName}.", type = LabelType.Label2 ) Label( text = "Forgot to update AppUiModelMap?", type = LabelType.Label2 ) } } } @Preview @Composable private fun NotImplementedModelPreview() { PreviewWalletTheme { UiModelNotImplemented(SomeModel) } } private object SomeModel : Model()
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
1,405
bitkey
MIT License
app/src/main/java/br/com/meiadois/decole/util/extension/Date.kt
meiadois
256,744,460
false
null
package br.com.meiadois.decole.util.extension import android.annotation.SuppressLint import java.text.SimpleDateFormat import java.util.* @SuppressLint("SimpleDateFormat") fun Date.isFetchNeeded(): Boolean { val formatter = SimpleDateFormat("dd/MM/yyyy") val now = Date() val nowWithZeroTime = formatter.parse(formatter.format(now)) val lastFetchWithZeroTime = formatter.parse(formatter.format(this)) return lastFetchWithZeroTime!!.before(nowWithZeroTime) }
0
Kotlin
1
2
f9c861124d3a1031bf0b802465eaa166c16f1693
481
decole-android
MIT License
.teamcity/builds/kotlinlang/buidTypes/BuildReferenceDocs.kt
JetBrains
14,397,208
false
{"JavaScript": 235602, "SCSS": 178179, "TypeScript": 119560, "Python": 76209, "HTML": 55006, "CSS": 46244, "FreeMarker": 10231, "Shell": 8942, "XSLT": 3883, "Dockerfile": 1397}
package builds.kotlinlang.buidTypes import jetbrains.buildServer.configs.kotlin.BuildType import jetbrains.buildServer.configs.kotlin.* import jetbrains.buildServer.configs.kotlin.buildSteps.ScriptBuildStep import jetbrains.buildServer.configs.kotlin.buildSteps.script import java.io.File import java.nio.file.Paths private fun readScript(name: String): String { val file = File(Paths.get("scripts/$name.mjs").toAbsolutePath().toString()) return file.readText() } object BuildReferenceDocs : BuildType({ name = "Reference Docs" description = "Build documentation pages https://kotlinlang.org/docs/" artifactRules = """ +:images => docs.zip!images +:static => docs.zip!static +:pages/*.html => docs.zip +:pages/*.json => docs.zip """.trimIndent() params { param("WEBHELP_FRONTEND_VERSION", "6.11.0-footer") param("WH_DOCS_PATH_REGEX", "docs") param("WH_PROJECT_NAME", "kotlin-reference") } steps { script { name = "Fix paths" scriptContent = """ find pages -type f -name '*.html' -exec sed -i -E 's/((https?:)?\/\/resources.jetbrains.com)?\/storage\/help-app\/v[0-9]\//static\/v3\//g' {} + find pages -type f -name '*.html' -exec sed -i -E "s/((https?:)?\/\/resources.jetbrains.com)?\/help\/app\//static\//g" {} + find pages -type f -name '*.html' -exec sed -i -E "s/(static\/v3\/app.css)/\1?v=%WEBHELP_FRONTEND_VERSION%/g" {} + """.trimIndent() dockerImage = "alpine" dockerImagePlatform = ScriptBuildStep.ImagePlatform.Linux } script { name = "Fix WRS-6159" scriptContent = """ #!/usr/bin/env bash ":" //# comment; exec /usr/bin/env node --input-type=module - "${'$'}@" < "${'$'}0" ${readScript("fix-wrs/index")} """.trimIndent() dockerImage = "node:22-slim" dockerImagePlatform = ScriptBuildStep.ImagePlatform.Linux dockerPull = true } } dependencies { dependency(AbsoluteId("Documentation_TransitioningProducts_KotlinReferenceWithCoroutines")) { snapshot {} artifacts { cleanDestination = true artifactRules = """ +:webHelpImages.zip!** => images/ +:webHelpKR2.zip!** => pages/ """.trimIndent() } } artifacts(BuildWebHelpFrontend) { buildRule = lastPinned("+:*") cleanDestination = true artifactRules = "+:static.zip!** => static/v3" } } })
21
JavaScript
3831
1,464
8e84d7206edbfb913db4674762a46a79c3d94a5c
2,491
kotlin-web-site
Apache License 2.0
clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitsResponseWithAnalytics.kt
algolia
419,291,903
false
null
/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ package com.algolia.client.model.analytics import kotlinx.serialization.* import kotlinx.serialization.json.* /** * TopHitsResponseWithAnalytics * * @param hits A list of top hits with their count and analytics. */ @Serializable public data class TopHitsResponseWithAnalytics( /** A list of top hits with their count and analytics. */ @SerialName(value = "hits") val hits: List<TopHitWithAnalytics>, ) : GetTopHitsResponse
40
PHP
8
25
f14b2b4e48702209dcb0c09561a2c1c3361f75eb
618
api-clients-automation
MIT License
payment/src/main/kotlin/io/liquidsoftware/base/payment/application/port/out/PaymentEventPort.kt
edreyer
445,325,795
false
{"Kotlin": 204259, "Procfile": 119}
package io.liquidsoftware.base.payment.application.port.out import io.liquidsoftware.base.payment.application.port.`in`.PaymentEvent import io.liquidsoftware.base.payment.application.port.`in`.PaymentMethodEvent internal interface PaymentEventPort { suspend fun <T: PaymentMethodEvent> handle(event: T): T suspend fun <T: PaymentEvent> handle(event: T): T }
7
Kotlin
12
49
8e006542b23bb90823c66dfe59a70476370a912c
368
modulith
MIT License
app/src/main/java/com/example/classvista_admin/Models/CourseYear/Data.kt
abdulqaderpatel
732,734,663
false
{"Kotlin": 146089}
package com.example.classvista_admin.Models.CourseYear data class Data( val admin_id: Int=0, val course_id: Int=0, val created_at: String="", val id: String="", val subject_name: String="", val updated_at: String="" )
0
Kotlin
0
0
4d4ef065e82ea55b6d42b63f954d50998a7d511c
242
ClassVista_admin
MIT License
bittrader-candle-api/src/test/kotlin/org/kentunc/bittrader/candle/api/infrastructure/repository/dao/BBandsStrategyParamsDaoTest.kt
ken-tunc
430,691,495
false
null
package org.kentunc.bittrader.candle.api.infrastructure.repository.dao import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow import org.kentunc.bittrader.candle.api.infrastructure.repository.entity.BBandsParamsEntity import org.kentunc.bittrader.candle.api.infrastructure.repository.entity.StrategyParamsPrimaryKey import org.kentunc.bittrader.candle.api.test.CandleApiTest import org.kentunc.bittrader.common.domain.model.market.ProductCode import org.kentunc.bittrader.common.domain.model.time.Duration import org.springframework.beans.factory.annotation.Autowired import org.springframework.r2dbc.core.DatabaseClient @CandleApiTest internal class BBandsStrategyParamsDaoTest { @Autowired private lateinit var target: StrategyParamsDao @Autowired private lateinit var databaseClient: DatabaseClient private val bBandsParamsEntities = listOf( // old BBandsParamsEntity( productCode = ProductCode.BTC_JPY, duration = Duration.DAYS, timeFrame = 20, buyK = 2.0, sellK = 1.0, ), // latest BBandsParamsEntity( productCode = ProductCode.BTC_JPY, duration = Duration.DAYS, timeFrame = 18, buyK = 1.8, sellK = 0.8, ), ) @BeforeEach fun setUp() { databaseClient.sql("delete from bbands_params") .then() .block() bBandsParamsEntities.forEach { databaseClient.sql("insert into bbands_params (product_code, duration, time_frame, buy_k, sell_k) values ($1, $2, $3, $4, $5)") .bind("$1", it.productCode.toString()) .bind("$2", it.duration.toString()) .bind("$3", it.timeFrame) .bind("$4", it.buyK) .bind("$5", it.sellK) .then() .block() } } @Test fun testSelectLatestOne_notHit() = runBlocking { val actual = target.selectLatestOne<BBandsParamsEntity>(StrategyParamsPrimaryKey(ProductCode.BTC_JPY, Duration.MINUTES)) assertNull(actual) } @Test fun testSelectLatestOne_hit() = runBlocking { val actual = target.selectLatestOne<BBandsParamsEntity>(StrategyParamsPrimaryKey(ProductCode.BTC_JPY, Duration.DAYS)) assertEquals(bBandsParamsEntities.last(), actual) } @Test fun testInsert(): Unit = runBlocking { val entity = BBandsParamsEntity( productCode = ProductCode.ETH_JPY, duration = Duration.HOURS, timeFrame = 22, buyK = 2.2, sellK = 1.2 ) assertDoesNotThrow { target.insert(entity) } } }
2
Kotlin
0
0
757c83fd604e5758a5e67bbfd98b33c1d9cc1961
2,949
bittrader
MIT License
commons-crypto/src/main/kotlin/com/healthmetrix/connector/commons/crypto/AesKey.kt
smart4health
593,624,617
false
null
package com.healthmetrix.connector.commons.crypto import com.healthmetrix.connector.commons.AllOpen import com.healthmetrix.connector.commons.decodeBase64 import com.healthmetrix.connector.commons.logger import net.logstash.logback.argument.StructuredArguments import java.nio.ByteBuffer import java.security.SecureRandom import java.util.Arrays import javax.crypto.Cipher import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.SecretKeySpec class InvalidAesKeyException : Exception() @AllOpen class AesKey(private val aesKey: SecretKeySpec) { fun encrypt(input: ByteArray): ByteArray { // TODO any relation to the instance in with? val iv = with(SecureRandom()) { val buf = ByteArray(12) nextBytes(buf) buf } val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, aesKey, GCMParameterSpec(128, iv)) } val cipherText = cipher.doFinal(input) val msg = with(ByteBuffer.allocate(4 + iv.size + cipherText.size)) { putInt(iv.size) put(iv) put(cipherText) }.array() Arrays.fill(iv, 0) return msg } fun decrypt(input: ByteArray): ByteArray? = try { val (iv, cipherText) = with(ByteBuffer.wrap(input)) { val ivLength = int if (ivLength !in (12..16)) { throw IllegalArgumentException("invalid iv length") } val iv = ByteArray(ivLength).also { get(it) } val cipherText = ByteArray(remaining()).also { get(it) } iv to cipherText } val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.DECRYPT_MODE, aesKey, GCMParameterSpec(128, iv)) } cipher.doFinal(cipherText) } catch (ex: Exception) { logger.warn("Error occurred AES decrypting ByteArray {}", StructuredArguments.kv("ex", ex::class.java.canonicalName)) null } companion object { fun buildFromB64String(keyB64: String): AesKey { return keyB64.decodeBase64() .let(this::validateAesKeyBytes) .let { keyBytes -> SecretKeySpec(keyBytes, "AES") } .let(::AesKey) } private fun validateAesKeyBytes(keyBytes: ByteArray?): ByteArray { if (keyBytes == null) { logger.warn("AES key is not in valid base64 encoding") throw InvalidAesKeyException() } if (keyBytes.isEmpty()) { logger.warn("AES key size must not be empty") throw InvalidAesKeyException() } if (keyBytes.size > 16) { logger.warn("AES key size must not be greater than 16") throw InvalidAesKeyException() } return keyBytes } } }
0
Kotlin
0
1
976d36079fa4171da0f78ad5812181cb6e3da6bc
2,924
connector-service
MIT License
android/app/src/main/java/com/codechef/ffds/MessagesFragment.kt
CodeChefVIT
367,407,732
false
null
package com.codechef.ffds import android.content.Context import android.content.Intent import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import com.codechef.ffds.Api.retrofitService import com.codechef.ffds.databinding.MessagesFragmentBinding import com.google.gson.Gson import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.ByteArrayOutputStream import java.util.* import java.util.concurrent.ExecutionException class MessagesFragment : Fragment() { private lateinit var binding: MessagesFragmentBinding private val conversations = ArrayList<Conversation>() private val messages = ArrayList<Messages>() private val matches = ArrayList<Messages>() private val profiles = ArrayList<Profile>() private val chats = ArrayList<Chat>() private var user = Profile() private lateinit var matchAdapter: MessageAdapter private lateinit var messageAdapter: MessageAdapter private lateinit var viewModel: UserViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = MessagesFragmentBinding.inflate(layoutInflater) return binding.root } override fun onViewCreated(root: View, savedInstanceState: Bundle?) { super.onViewCreated(root, savedInstanceState) binding.apply { matchAdapter = MessageAdapter(requireContext(), matches, false) matchesRecyclerView.layoutManager = LinearLayoutManager( context, LinearLayoutManager.HORIZONTAL, false ) matchesRecyclerView.adapter = matchAdapter messageAdapter = MessageAdapter(requireContext(), messages, true) messagesRecyclerView.layoutManager = LinearLayoutManager(context) messagesRecyclerView.adapter = messageAdapter matchAdapter.setOnItemClickListener(object : MessageAdapter.OnItemClickListener { override fun onItemClick(position: Int) { val intent = Intent(activity, ChatActivity::class.java) intent.putExtra("Name", matches[position].name) intent.putExtra("ID", matches[position].id) intent.putExtra("ConversationId", matches[position].conversationId) startActivity(intent) } }) messageAdapter.setOnItemClickListener(object : MessageAdapter.OnItemClickListener { override fun onItemClick(position: Int) { val intent = Intent(activity, ChatActivity::class.java) intent.putExtra("Name", messages[position].name) intent.putExtra("ID", messages[position].id) intent.putExtra("ConversationId", messages[position].conversationId) startActivity(intent) } }) showHideViews() viewModel = ViewModelProvider( this@MessagesFragment, UserViewModelFactory(requireActivity().application) ).get( UserViewModel::class.java ) val prefs = requireContext().getSharedPreferences("MY PREFS", Context.MODE_PRIVATE) viewModel.getUserData(prefs.getString("id", "")!!) .observe(viewLifecycleOwner, { currentUser: Profile -> user = currentUser updateRecyclerView() updateData(user) }) } } private fun updateRecyclerView() { viewModel.getAllConversations() .observe(viewLifecycleOwner, { conversations: List<Conversation> -> matches.clear() messages.clear() for ((members, _id) in conversations) { var id = members[1] if (id == user._id) id = members[0] viewModel.getUserData(id).observe(viewLifecycleOwner, { profile: Profile? -> if (profile != null) { viewModel.getLastMessage(_id) .observe(viewLifecycleOwner, { chat: Chat? -> if (chat == null) matches.add( Messages( "", profile.userArray, profile.name, profile._id, _id ) ) else messages.add( Messages( chat.text, profile.userArray, profile.name, profile._id, _id ) ) if (messages.size + matches.size == conversations.size) showHideViews() }) } }) } }) } private fun updateData(user: Profile?) { retrofitService.getAllConversations(user!!.token)!! .enqueue(object : Callback<ConversationList?> { override fun onFailure(call: Call<ConversationList?>, t: Throwable) { Toast.makeText(context, "All Conversation: " + t.message, Toast.LENGTH_SHORT) .show() } override fun onResponse( call: Call<ConversationList?>, response: Response<ConversationList?> ) { if (response.message() == "OK") { val conversationList = response.body() if (conversationList != null) { conversations.addAll(conversationList.matchedOnly) conversations.addAll(conversationList.hasMessages) if (conversations.isNotEmpty()) { profiles.clear() chats.clear() getData(user, 0) } } } else { val gson = Gson() val (_,message) = gson.fromJson(response.errorBody()?.charStream(), Error::class.java) Toast.makeText( requireContext(), "Error ${response.code()}: $message", Toast.LENGTH_SHORT ).show() } } }) } private fun getData(user: Profile?, count: Int) { val (members, _id) = conversations[count] var id = members[1] if (id == user!!._id) id = members[0] retrofitService.getUserDetail(id)!!.enqueue(object : Callback<Profile?> { override fun onFailure(call: Call<Profile?>, t: Throwable) { Toast.makeText(context, "User details: " + t.message, Toast.LENGTH_SHORT).show() } override fun onResponse(call: Call<Profile?>, response: Response<Profile?>) { if (response.message() == "OK") { val profile = response.body() if (profile != null) { profiles.add(profile.copy(userArray = getByteArray(profile.userImage.url))) retrofitService.getAllMessages(user.token, _id)!! .enqueue(object : Callback<ArrayList<Chat>?> { override fun onFailure(call: Call<ArrayList<Chat>?>, t: Throwable) { Toast.makeText( context, "all messages: " + t.message, Toast.LENGTH_SHORT ).show() } override fun onResponse( call: Call<ArrayList<Chat>?>, response: Response<ArrayList<Chat>?> ) { if (response.message() == "OK") { val chat = response.body() if (chat != null) for (ch in chat) chats.add(ch.copy(type = getType(user, ch))) if (profiles.size == conversations.size) { viewModel.insertAllMessages(*chats.toTypedArray()) viewModel.insertUser(*profiles.toTypedArray()) viewModel.insertAllConversations(*conversations.toTypedArray()) } else getData(user, count + 1) } else { val gson = Gson() val (_,message) = gson.fromJson(response.errorBody()?.charStream(), Error::class.java) Toast.makeText( requireContext(), "Error ${response.code()}: all msgs: $message", Toast.LENGTH_SHORT ).show() } } }) } } else Toast.makeText( requireContext(), "details: " + response.message(), Toast.LENGTH_SHORT ).show() } }) } private fun getType(user: Profile?, chat: Chat): ItemType { return if (chat.senderId == user!!._id) ItemType.Sent else ItemType.Received } private fun getByteArray(url: String): List<Byte> { var bitmap: Bitmap? = null if (url.isEmpty()) bitmap = BitmapFactory.decodeResource(Resources.getSystem(), R.drawable.profile_image) else { try { bitmap = Glide.with(this).asBitmap().load(Uri.parse(url)).submit().get() } catch (e: ExecutionException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } } val stream = ByteArrayOutputStream() bitmap!!.compress(Bitmap.CompressFormat.PNG, 100, stream) return stream.toByteArray().toList() } private fun showHideViews() { binding.apply { if (matches.isEmpty()) { noMatches.visibility = View.VISIBLE matchesRecyclerView.visibility = View.GONE } else { matchAdapter.submitList(matches) matchesRecyclerView.visibility = View.VISIBLE noMatches.visibility = View.GONE } if (messages.isEmpty()) { noMessages.visibility = View.VISIBLE messagesRecyclerView.visibility = View.GONE } else { messageAdapter.submitList(messages) messagesRecyclerView.visibility = View.VISIBLE noMessages.visibility = View.GONE } } } }
4
Kotlin
6
3
9d03f10326181f54818fd5681ad5eddf6a2b71a5
12,316
FFDSv2
MIT License
epli/app/src/main/java/com/example/epli/network/models/GetUsersSeriesInfoRequest.kt
Uliana2303
544,899,725
false
{"Kotlin": 136839}
package com.example.epli.network.models import kotlinx.serialization.Serializable @Serializable data class GetUsersSeriesInfoRequest( val userId: Int, val seriesId: Int )
0
Kotlin
1
0
ac10c539bfd1127339b68af95a7c09ffbcdf1685
182
summer-practice
MIT License
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/outlined/TrayAndArrowUp.kt
alexzhirkevich
636,411,288
false
{"Kotlin": 4456601, "Ruby": 2310, "Swift": 2101, "Shell": 856, "HTML": 762}
package io.github.alexzhirkevich.cupertino.icons.outlined import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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 io.github.alexzhirkevich.cupertino.icons.CupertinoIcons public val CupertinoIcons.Outlined.TrayAndArrowUp: ImageVector get() { if (_trayAndArrowUp != null) { return _trayAndArrowUp!! } _trayAndArrowUp = Builder(name = "TrayAndArrowUp", defaultWidth = 27.6328.dp, defaultHeight = 29.6133.dp, viewportWidth = 27.6328f, viewportHeight = 29.6133f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.6797f, 27.1641f) lineTo(23.9531f, 27.1641f) curveTo(26.4141f, 27.1641f, 27.6328f, 25.9453f, 27.6328f, 23.5312f) lineTo(27.6328f, 16.5938f) curveTo(27.6328f, 15.5273f, 27.5039f, 15.0f, 26.9648f, 14.3672f) lineTo(23.2734f, 9.7969f) curveTo(21.8203f, 8.0273f, 21.293f, 7.6172f, 19.207f, 7.6172f) lineTo(16.9102f, 7.6172f) lineTo(16.9102f, 9.2695f) lineTo(19.3477f, 9.2695f) curveTo(20.2031f, 9.2695f, 20.7422f, 9.4219f, 21.4219f, 10.2656f) lineTo(25.2422f, 15.0469f) curveTo(25.7227f, 15.6445f, 25.5469f, 15.8789f, 24.9023f, 15.8789f) lineTo(17.4375f, 15.8789f) curveTo(16.8281f, 15.8789f, 16.5469f, 16.3477f, 16.5469f, 16.8281f) lineTo(16.5469f, 16.875f) curveTo(16.5469f, 18.2344f, 15.4805f, 19.6641f, 13.8164f, 19.6641f) curveTo(12.1641f, 19.6641f, 11.0977f, 18.2344f, 11.0977f, 16.875f) lineTo(11.0977f, 16.8281f) curveTo(11.0977f, 16.3477f, 10.8047f, 15.8789f, 10.1953f, 15.8789f) lineTo(2.7539f, 15.8789f) curveTo(2.0742f, 15.8789f, 1.9453f, 15.6094f, 2.4023f, 15.0469f) lineTo(6.1875f, 10.3008f) curveTo(6.8906f, 9.4336f, 7.4297f, 9.2695f, 8.2852f, 9.2695f) lineTo(10.7344f, 9.2695f) lineTo(10.7344f, 7.6172f) lineTo(8.4258f, 7.6172f) curveTo(6.3398f, 7.6172f, 5.8359f, 8.0156f, 4.3477f, 9.832f) lineTo(0.668f, 14.3672f) curveTo(0.1523f, 14.9883f, 0.0f, 15.5273f, 0.0f, 16.5938f) lineTo(0.0f, 23.5312f) curveTo(0.0f, 25.9453f, 1.2305f, 27.1641f, 3.6797f, 27.1641f) close() moveTo(3.7031f, 25.2773f) curveTo(2.5313f, 25.2773f, 1.8867f, 24.6445f, 1.8867f, 23.4258f) lineTo(1.8867f, 17.6016f) lineTo(9.3164f, 17.6016f) curveTo(9.5977f, 19.793f, 11.4375f, 21.4102f, 13.8164f, 21.4102f) curveTo(16.1953f, 21.4102f, 18.0352f, 19.7812f, 18.3164f, 17.6016f) lineTo(25.7461f, 17.6016f) lineTo(25.7461f, 23.4258f) curveTo(25.7461f, 24.6445f, 25.0898f, 25.2773f, 23.9297f, 25.2773f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.8164f, 17.2734f) curveTo(14.3203f, 17.2734f, 14.7539f, 16.8516f, 14.7539f, 16.3594f) lineTo(14.7539f, 4.3242f) lineTo(14.6719f, 2.5781f) lineTo(15.4688f, 3.3984f) lineTo(17.2383f, 5.2969f) curveTo(17.4023f, 5.4844f, 17.6484f, 5.5781f, 17.8828f, 5.5781f) curveTo(18.3633f, 5.5781f, 18.7266f, 5.2266f, 18.7266f, 4.7578f) curveTo(18.7266f, 4.5f, 18.6328f, 4.3125f, 18.457f, 4.1367f) lineTo(14.4961f, 0.3164f) curveTo(14.2617f, 0.082f, 14.0625f, 0.0f, 13.8164f, 0.0f) curveTo(13.582f, 0.0f, 13.3711f, 0.082f, 13.1367f, 0.3164f) lineTo(9.1758f, 4.1367f) curveTo(9.0f, 4.3125f, 8.9063f, 4.5f, 8.9063f, 4.7578f) curveTo(8.9063f, 5.2266f, 9.2578f, 5.5781f, 9.7383f, 5.5781f) curveTo(9.9727f, 5.5781f, 10.2188f, 5.4844f, 10.3945f, 5.2969f) lineTo(12.1641f, 3.3984f) lineTo(12.9609f, 2.5664f) lineTo(12.8906f, 4.3242f) lineTo(12.8906f, 16.3594f) curveTo(12.8906f, 16.8516f, 13.3125f, 17.2734f, 13.8164f, 17.2734f) close() } } .build() return _trayAndArrowUp!! } private var _trayAndArrowUp: ImageVector? = null
1
Kotlin
14
362
60fd9234eb9f2df97bc8523ea2ed344ad7f58655
5,457
compose-cupertino
Apache License 2.0
Task2/src/main/kotlin/ru/spbau/mit/testing/pages/ForumsPage.kt
e5l
91,070,528
false
null
package ru.spbau.mit.testing.pages import org.openqa.selenium.WebDriver import ru.spbau.mit.testing.Locators class ForumsPage(driver: WebDriver) : BasePage(driver) { val commentsBlock get() = driver.findElement(Locators.commentsBlock) val topOffers get() = driver.findElements(Locators.topOffers) }
0
Kotlin
0
0
691d54f7c15d9f952a7c065cf6e1392bbb4249f5
307
Testing
The Unlicense
app/src/main/java/com/example/expensetrackerapp/data/Expense.kt
Lerampen
758,345,582
false
{"Kotlin": 109002}
package com.example.expensetrackerapp.data import androidx.annotation.NonNull import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "expenseTable") data class Expense ( @PrimaryKey(autoGenerate = true) var expId : Int = 0, var expName : String , var expAmount : Double, var expCategory : String , // var expDate: String = "", var expType: String ) { }
0
Kotlin
0
0
f844bc2256b1b61b54b1196af2ebf9f6c591ef82
407
expense-tracker
Apache License 2.0
sample/src/main/java/com/anggrayudi/materialpreference/sample/SettingsActivity.kt
Phoenix-626
232,622,866
true
{"Kotlin": 381708}
package com.anggrayudi.materialpreference.sample import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.view.Menu import androidx.appcompat.app.AppCompatDelegate import com.anggrayudi.materialpreference.PreferenceActivityMaterial import com.anggrayudi.materialpreference.PreferenceFragmentMaterial import com.anggrayudi.materialpreference.PreferenceManager class SettingsActivity : PreferenceActivityMaterial(), SharedPreferences.OnSharedPreferenceChangeListener { private var settingsFragment: SettingsFragment? = null override fun onCreate(savedInstanceState: Bundle?) { applyDayNightTheme() super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) setSupportActionBar(findViewById(R.id.toolbar)) supportActionBar!!.setDisplayHomeAsUpEnabled(true) if (savedInstanceState == null) { settingsFragment = SettingsFragment.newInstance(null) supportFragmentManager.beginTransaction().add(R.id.fragment_container, settingsFragment!!, TAG).commit() } else { onBackStackChanged() } } private fun applyDayNightTheme() { val preferences = PreferenceManager.getDefaultSharedPreferences(this) AppCompatDelegate.setDefaultNightMode(if (preferences.getBoolean(PrefKey.ENABLE_DARK_THEME, false)) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO) } override fun onBuildPreferenceFragment(rootKey: String?): PreferenceFragmentMaterial { return SettingsFragment.newInstance(rootKey) } override fun onBackStackChanged() { settingsFragment = supportFragmentManager.findFragmentByTag(TAG) as SettingsFragment? title = settingsFragment!!.preferenceFragmentTitle } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) menu.findItem(R.id.action_donate).intent = Intent(this, DonationActivity::class.java) return super.onCreateOptionsMenu(menu) } override fun onStop() { PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this) super.onStop() } override fun onStart() { super.onStart() PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this) } override fun onSharedPreferenceChanged(preferences: SharedPreferences, key: String) { if (key == PrefKey.ENABLE_DARK_THEME) { recreate() } } companion object { private const val TAG = "SettingsActivity" } }
0
null
0
0
da43dee38cf0f3877243849c1062a7c4808e09c3
2,689
MaterialPreference
Apache License 2.0
src/main/kotlin/com/jordanbegian/apitemplate/handlers/ProjectHandlers.kt
jordan-begian
595,221,675
false
null
package com.jordanbegian.apitemplate.handlers import com.jordanbegian.apitemplate.models.ProjectData import org.springframework.web.reactive.function.server.ServerRequest import com.jordanbegian.apitemplate.services.ProjectService import org.springframework.http.HttpStatus import org.springframework.stereotype.Component import org.springframework.web.client.HttpClientErrorException import org.springframework.web.reactive.function.server.ServerResponse import org.springframework.web.reactive.function.server.bodyToMono import org.springframework.web.reactive.function.server.json import reactor.core.publisher.Mono import reactor.kotlin.core.publisher.switchIfEmpty import reactor.kotlin.core.publisher.toMono @Component class ProjectHandlers( private val projectService: ProjectService ) { fun submitRequest(serverRequest: ServerRequest): Mono<ServerResponse> = serverRequest.bodyToMono<ProjectData>() .flatMap { projectService.submitRequest(it) } .flatMap { ServerResponse.ok().json().bodyValue(it) } fun retrieveAll(serverRequest: ServerRequest): Mono<ServerResponse> = serverRequest .toMono() .flatMap { projectService.retrieveAll() } .flatMap { response -> ServerResponse.ok().json().bodyValue(response) } fun retrieveById(serverRequest: ServerRequest): Mono<ServerResponse> = serverRequest .pathVariable("project-data-id") .toMono() .filter { requestId -> !requestId.isNullOrBlank() } .switchIfEmpty { Mono.error(HttpClientErrorException(HttpStatus.BAD_REQUEST, "Please provide an id")) } .flatMap { requestId -> projectService.retrieveById(requestId) } .flatMap { projectData -> ServerResponse.ok().json().bodyValue(projectData) } }
13
Kotlin
0
0
8aa4d7a3f798ec6af84cf00aa67acef353768b88
1,851
api-template
Apache License 2.0
SearchBook/app/src/main/java/ec/com/pmyb/searchbook/ReaderApplication.kt
PaulMarcelo
571,028,620
false
{"Kotlin": 159459}
package ec.com.pmyb.searchbook import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class ReaderApplication: Application(){ }
0
Kotlin
0
0
80f3447739ed06a0588969fdbe11f037f1176430
164
u-pd-android-jetpack-compose-comprehensive-bootcamp-2022
Apache License 2.0
src/main/kotlin/codecomputer/Selectors.kt
russhwolf
71,001,471
false
null
package codecomputer /** * A `Select` outputs the `a` input if `select` is false or the `b` input if select is true. * * This class represents the *2-Line-to-1-Line Selector* on page 169 of *Code* * * @see MultiSelector */ class Selector(select: Readable, a: Readable, b: Readable) : Readable by (select and b) or (!select and a) /** * A `MultiSelector` reads out a value in the `data` input indicated by the `select` input. The `data` input should have * length equal to `2^N`, where `N` is the length of the `select` input. * * If the `select` input has length `1` and the `data` input has length `2`, this reduces to the [Selector] class. * * This class represents the *8-Line-to-1-Line Data Selector* on page 194 of *Code*. */ class MultiSelector(select: List<Readable>, data: List<Readable>) : Readable by InnerSelectorDecoder(select, data).let(::MultiOr) /** * A `MultiDecoder` takes in a `data` input and returns a list where the output addressed by the `select` input is equal * to `data`, and all other outputs are false. The output will have length equal to `2^N`, where `N` is the length of * the `select` input. * * This class represents the *3-to-8 Decoder* presented on page 197 of *Code*. */ class MultiDecoder(select: List<Readable>, data: Readable) : List<Readable> by InnerSelectorDecoder(select, (1..(1 shl select.size)).map { data }) private class InnerSelectorDecoder(selection: List<Readable>, data: List<Readable>) : List<Readable> by (data.mapIndexed { i, dataBit -> dataBit and MultiAnd(selection.mapIndexed { j, selectionBit -> if ((i / (1 shl j)) % 2 == 0) !selectionBit else selectionBit }) })
0
Kotlin
1
6
5061ab2fb39cdb560f4bede67f074a8489f91bca
1,744
Code-Computer
MIT License
helper/src/main/kotlin/me/lucko/helper/messaging/KChannelListener.kt
Nyaadanbou
415,516,750
false
{"Gradle Kotlin DSL": 10, "Text": 1, "Shell": 1, "Markdown": 2, "Batchfile": 1, "Ignore List": 1, "Kotlin": 35, "Java": 366, "YAML": 6, "INI": 1}
/* * This file is part of helper, licensed under the MIT License. * * Copyright (c) lucko (Luck) <<EMAIL>> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.lucko.helper.messaging /** * Represents an object listening to messages sent on the channel. * * @param <T> the channel message type */ fun interface KChannelListener<T> { /** * Called when a message is posted to this listener. * * This method is called asynchronously. * * @param agent the agent which forwarded the message. * @param message the message */ suspend fun onMessage(agent: KChannelAgent<T>, message: T) }
1
null
1
1
a0110d3d1ab6124186911e89c6dcc5eaadaf5a18
1,713
helper
MIT License
libnavigation-core/src/main/java/com/mapbox/navigation/core/routeoptions/MapboxRouteOptionsProvider.kt
karanveer0802
279,296,063
true
{"Java Properties": 3, "Markdown": 11, "Gradle": 45, "Shell": 6, "YAML": 2, "Batchfile": 2, "JSON": 24, "Ignore List": 28, "Makefile": 1, "INI": 40, "Proguard": 16, "XML": 541, "HTML": 8, "Kotlin": 506, "Text": 13, "Java": 523, "JavaScript": 2, "Python": 2}
package com.mapbox.navigation.core.routeoptions import android.location.Location import com.mapbox.api.directions.v5.models.RouteOptions import com.mapbox.base.common.logger.Logger import com.mapbox.base.common.logger.model.Message import com.mapbox.base.common.logger.model.Tag import com.mapbox.geojson.Point import com.mapbox.navigation.base.trip.model.RouteProgress /** * Default implementation of [RouteOptionsProvider] */ internal class MapboxRouteOptionsProvider( private val logger: Logger ) : RouteOptionsProvider { private companion object { const val DEFAULT_REROUTE_BEARING_TOLERANCE = 90.0 } /** * Provides a new instance of *RouteOptions* based on initial *RouteOptions*, *RouteProgress* and * current *Location* * * Returns *null* if a new [RouteOptions] instance cannot be combined based on the input given. */ override fun update( routeOptions: RouteOptions?, routeProgress: RouteProgress?, location: Location? ): RouteOptionsProvider.RouteOptionsResult { if (routeOptions == null || routeProgress == null || location == null) { val msg = "Cannot combine RouteOptions, invalid inputs. routeOptions, " + "routeProgress, and location mustn't be null" logger.w( Tag("MapboxRouteOptionsProvider"), Message(msg) ) return RouteOptionsProvider.RouteOptionsResult.Error(Throwable(msg)) } val optionsBuilder = routeOptions.toBuilder() val coordinates = routeOptions.coordinates() routeProgress.currentLegProgress?.legIndex?.let { index -> optionsBuilder .coordinates( coordinates.drop(index + 1).toMutableList().apply { add(0, Point.fromLngLat(location.longitude, location.latitude)) } ) .bearingsList(let { val bearings = mutableListOf<List<Double>?>() val originTolerance = routeOptions.bearingsList()?.getOrNull(0)?.getOrNull(1) ?: DEFAULT_REROUTE_BEARING_TOLERANCE val currentAngle = location.bearing.toDouble() bearings.add(listOf(currentAngle, originTolerance)) val originalBearings = routeOptions.bearingsList() if (originalBearings != null) { bearings.addAll(originalBearings.subList(index + 1, coordinates.size)) } else { while (bearings.size < coordinates.size) { bearings.add(null) } } bearings }) .radiusesList(let radiusesList@{ if (routeOptions.radiusesList().isNullOrEmpty()) { return@radiusesList emptyList<Double>() } mutableListOf<Double>().also { it.addAll(routeOptions.radiusesList()!!.subList(index, coordinates.size)) } }) .approachesList(let approachesList@{ if (routeOptions.approachesList().isNullOrEmpty()) { return@approachesList emptyList<String>() } mutableListOf<String>().also { it.addAll(routeOptions.approachesList()!!.subList(index, coordinates.size)) } }) .waypointIndicesList(let waypointIndicesList@{ if (routeOptions.waypointIndicesList().isNullOrEmpty()) { return@waypointIndicesList emptyList<Int>() } mutableListOf<Int>().also { it.addAll( routeOptions.waypointIndicesList()!!.subList( index, coordinates.size ) ) } }) .waypointNamesList(let waypointNamesList@{ if (routeOptions.waypointNamesList().isNullOrEmpty()) { return@waypointNamesList emptyList<String>() } mutableListOf<String>().also { it.add("") it.addAll( routeOptions.waypointNamesList()!!.subList( index + 1, coordinates.size ) ) } }) .waypointTargetsList(let waypointTargetsList@{ if (routeOptions.waypointTargetsList().isNullOrEmpty()) { return@waypointTargetsList emptyList<Point>() } mutableListOf<Point?>().also { it.add(null) it.addAll( routeOptions.waypointTargetsList()!!.subList( index + 1, coordinates.size ) ) } }) } return RouteOptionsProvider.RouteOptionsResult.Success(optionsBuilder.build()) } }
0
null
0
0
6c52c50c7194798a23f334c90e36aa48937758fe
5,496
mapbox-navigation-android
Apache License 2.0
src/main/kotlin/com/atlassian/performance/tools/jiraactions/api/page/TopNav.kt
atlassian-forks
379,904,817
true
{"Kotlin": 170208, "Java": 1959}
package com.atlassian.performance.tools.jiraactions.api.page import org.openqa.selenium.By import org.openqa.selenium.WebDriver import org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable class TopNav(private val driver: WebDriver) { private val createButtonLocator = By.id("create_link") fun openIssueCreateDialog(): IssueCreateDialog { driver.wait(elementToBeClickable(createButtonLocator)).click() return IssueCreateDialog(driver) } fun isPresent(): Boolean { return driver.findElements(createButtonLocator).any() } }
0
null
0
0
5f56267d91b5138755f6796f32cedddb89e944ad
587
jira-actions
Apache License 2.0
src/main/kotlin/xyz/luan/games/minecraft/ultimatestorage/containers/BaseChestContainer.kt
luanpotter
326,282,577
false
null
package xyz.luan.games.minecraft.ultimatestorage.containers import net.minecraft.entity.player.PlayerEntity import net.minecraft.entity.player.PlayerInventory import net.minecraft.inventory.container.Slot import net.minecraft.network.PacketBuffer import xyz.luan.games.minecraft.ultimatestorage.registry.BlockRegistry import xyz.luan.games.minecraft.ultimatestorage.screens.BgSegment import xyz.luan.games.minecraft.ultimatestorage.tiles.BaseChestTileEntity class BaseChestContainer constructor( windowId: Int, private val tile: BaseChestTileEntity, playerInventory: PlayerInventory, ) : GenericContainer(BlockRegistry.baseChestContainer.get(), windowId) { val rows get() = tile.rows private val cols get() = tile.cols override val inventorySize get() = tile.inventorySize init { setup(playerInventory) } constructor(windowId: Int, playerInventory: PlayerInventory, extraData: PacketBuffer) : this( windowId, playerInventory.player.world.getTileEntity(extraData.readBlockPos()) as BaseChestTileEntity, playerInventory, ) private fun setup(inventory: PlayerInventory) { val firstBlock = BgSegment.top.height + 1 val secondBlock = firstBlock + BgSegment.divider.height + rows * 18 addPlayerInventorySlots(inventory, secondBlock) // Slots for chest for (chestRow in 0 until rows) { for (chestCol in 0 until cols) { val x = 12 + chestCol * 18 val y = firstBlock + chestRow * 18 addSlot(Slot(tile.chestInventory, chestCol + chestRow * cols, x, y)) } } } override fun canInteractWith(playerIn: PlayerEntity): Boolean { return true // TODO this } }
0
Kotlin
0
2
6c676bb618dd7f12b7c8c79b040442d18d82407b
1,790
ultimate-storage
MIT License
src/test/kotlin/no/nav/bidrag/person/hendelse/DevLauncher.kt
navikt
517,990,382
false
null
package no.nav.bidrag.person.hendelse import no.nav.bidrag.person.hendelse.konfigurasjon.ApplicationConfig import no.nav.security.token.support.test.spring.TokenGeneratorConfiguration import org.springframework.boot.builder.SpringApplicationBuilder import org.springframework.context.annotation.Import @Import(TokenGeneratorConfiguration::class, ApplicationConfig::class) class DevLauncher fun main(args: Array<String>) { val app = SpringApplicationBuilder(DevLauncher::class.java) .profiles("dev") app.run(*args) }
2
Kotlin
0
0
73a661b658c7bc18c7784f4db44319e1ac73ab31
535
bidrag-person-hendelse
MIT License
app/src/main/java/de/oljg/glac/feature_clock/ui/settings/components/character/FontWeightSelector.kt
Ol-J-G
768,542,224
false
{"Kotlin": 980887}
package de.oljg.glac.feature_clock.ui.settings.components.character import androidx.compose.runtime.Composable import de.oljg.glac.core.ui.components.DropDownSelector import de.oljg.glac.core.utils.FontWeight import de.oljg.glac.feature_clock.ui.settings.utils.ClockSettingsDefaults.FONT_WEIGHTS import de.oljg.glac.feature_clock.ui.settings.utils.ClockSettingsDefaults.SELECTOR_PADDING @Composable fun FontWeightSelector( label: String, selectedFontWeight: FontWeight, onNewFontWeightSelected: (String) -> Unit ) { DropDownSelector( type = FontWeight::class, startPadding = SELECTOR_PADDING / 3, label = label, selectedValue = selectedFontWeight.name, onNewValueSelected = onNewFontWeightSelected, values = FONT_WEIGHTS ) }
0
Kotlin
0
0
b3cefafa190eae0aa95f55fc6903e327363c2efc
796
GLAC
Creative Commons Attribution 4.0 International
app/src/main/java/softspark/com/inventorypilot/home/domain/useCases/cart/DeleteCartItemUseCaseImpl.kt
Landony04
836,511,304
false
{"Kotlin": 294205}
package softspark.com.inventorypilot.home.domain.useCases.cart import softspark.com.inventorypilot.home.data.repositories.CartRepository import javax.inject.Inject class DeleteCartItemUseCaseImpl @Inject constructor( private val cartRepository: CartRepository ) : DeleteCartItemUseCase { override suspend fun invoke(cartItemId: String) = cartRepository.deleteCartItem(cartItemId) }
1
Kotlin
0
0
f5c3a1ce959aac23270a6d08728498a52bcd5e01
391
inventory-pilot
MIT License
app/src/main/java/com/bunkalogic/bunkalist/db/NewTimeLineEventGlobal.kt
bunkalogic
171,318,735
false
{"Kotlin": 544892}
package com.bunkalogic.bunkalist.db data class NewTimeLineEventGlobal(val message: TimelineMessage)
0
Kotlin
0
2
1b5c1d40f0e7514de3a666614cdf6fe88e21ca3f
100
BunkaList-Replaced-
Apache License 2.0
kotlinpoet-dsl/src/main/kotlin/com/hendraanggrian/kotlinpoet/AnnotationSpec.kt
hendraanggrian
209,613,746
false
{"Kotlin": 163919}
@file:OptIn(ExperimentalContracts::class) package com.hendraanggrian.kotlinpoet import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.DelicateKotlinPoetApi import com.squareup.kotlinpoet.ParameterizedTypeName import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract import kotlin.reflect.KClass public val ANNOTATION_FILE: AnnotationSpec.UseSiteTarget = AnnotationSpec.UseSiteTarget.FILE public val ANNOTATION_PROPERTY: AnnotationSpec.UseSiteTarget = AnnotationSpec.UseSiteTarget.PROPERTY public val ANNOTATION_FIELD: AnnotationSpec.UseSiteTarget = AnnotationSpec.UseSiteTarget.FIELD public val ANNOTATION_GET: AnnotationSpec.UseSiteTarget = AnnotationSpec.UseSiteTarget.GET public val ANNOTATION_SET: AnnotationSpec.UseSiteTarget = AnnotationSpec.UseSiteTarget.SET public val ANNOTATION_RECEIVER: AnnotationSpec.UseSiteTarget = AnnotationSpec.UseSiteTarget.RECEIVER public val ANNOTATION_PARAM: AnnotationSpec.UseSiteTarget = AnnotationSpec.UseSiteTarget.PARAM public val ANNOTATION_SETPARAM: AnnotationSpec.UseSiteTarget = AnnotationSpec.UseSiteTarget.SETPARAM public val ANNOTATION_DELEGATE: AnnotationSpec.UseSiteTarget = AnnotationSpec.UseSiteTarget.DELEGATE public fun ClassName.asAnnotationSpec(): AnnotationSpec = AnnotationSpec.builder(this).build() public fun ParameterizedTypeName.asAnnotationSpec(): AnnotationSpec = AnnotationSpec.builder(this).build() /** * Creates new [AnnotationSpec] by populating newly created [AnnotationSpecBuilder] using provided * [configuration]. */ public inline fun buildAnnotationSpec( type: ClassName, configuration: AnnotationSpecBuilder.() -> Unit, ): AnnotationSpec { contract { callsInPlace(configuration, InvocationKind.EXACTLY_ONCE) } return AnnotationSpecBuilder(AnnotationSpec.builder(type)).apply(configuration).build() } /** * Creates new [AnnotationSpec] by populating newly created [AnnotationSpecBuilder] using provided * [configuration]. */ public inline fun buildAnnotationSpec( type: ParameterizedTypeName, configuration: AnnotationSpecBuilder.() -> Unit, ): AnnotationSpec { contract { callsInPlace(configuration, InvocationKind.EXACTLY_ONCE) } return AnnotationSpecBuilder(AnnotationSpec.builder(type)).apply(configuration).build() } /** * Inserts new [AnnotationSpec] by populating newly created [AnnotationSpecBuilder] using provided * [configuration]. */ public inline fun AnnotationSpecHandler.annotation( type: ClassName, configuration: AnnotationSpecBuilder.() -> Unit, ): AnnotationSpec { contract { callsInPlace(configuration, InvocationKind.EXACTLY_ONCE) } return buildAnnotationSpec(type, configuration).also(::annotation) } /** * Inserts new [AnnotationSpec] by populating newly created [AnnotationSpecBuilder] using provided * [configuration]. */ public inline fun AnnotationSpecHandler.annotation( type: ParameterizedTypeName, configuration: AnnotationSpecBuilder.() -> Unit, ): AnnotationSpec { contract { callsInPlace(configuration, InvocationKind.EXACTLY_ONCE) } return buildAnnotationSpec(type, configuration).also(::annotation) } /** * Inserts new [AnnotationSpec] by populating newly created [AnnotationSpecBuilder] using provided * [configuration]. */ @DelicateKotlinPoetApi(DELICATE_API) public inline fun AnnotationSpecHandler.annotation( type: Class<out Annotation>, configuration: AnnotationSpecBuilder.() -> Unit, ): AnnotationSpec { contract { callsInPlace(configuration, InvocationKind.EXACTLY_ONCE) } return buildAnnotationSpec(type.name2, configuration).also(::annotation) } /** * Inserts new [AnnotationSpec] by populating newly created [AnnotationSpecBuilder] using provided * [configuration]. */ public inline fun AnnotationSpecHandler.annotation( type: KClass<out Annotation>, configuration: AnnotationSpecBuilder.() -> Unit, ): AnnotationSpec { contract { callsInPlace(configuration, InvocationKind.EXACTLY_ONCE) } return buildAnnotationSpec(type.name, configuration).also(::annotation) } /** Convenient method to insert [AnnotationSpec] using reified type. */ public inline fun <reified T> AnnotationSpecHandler.annotation(): AnnotationSpec = T::class.name.asAnnotationSpec().also(::annotation) /** Invokes DSL to configure [AnnotationSpec] collection. */ public fun AnnotationSpecHandler.annotations(configuration: AnnotationSpecHandlerScope.() -> Unit) { contract { callsInPlace(configuration, InvocationKind.EXACTLY_ONCE) } AnnotationSpecHandlerScope.of(this).configuration() } /** Responsible for managing a set of [AnnotationSpec] instances. */ public interface AnnotationSpecHandler { public fun annotation(annotation: AnnotationSpec) public fun annotation(type: ClassName): AnnotationSpec = type.asAnnotationSpec().also(::annotation) public fun annotation(type: ParameterizedTypeName): AnnotationSpec = type.asAnnotationSpec().also(::annotation) @DelicateKotlinPoetApi(DELICATE_API) public fun annotation(type: Class<out Annotation>): AnnotationSpec = type.name2.asAnnotationSpec().also(::annotation) public fun annotation(type: KClass<out Annotation>): AnnotationSpec = type.name.asAnnotationSpec().also(::annotation) } /** * Receiver for the `annotations` block providing an extended set of operators for the * configuration. */ @KotlinpoetDsl public open class AnnotationSpecHandlerScope private constructor( handler: AnnotationSpecHandler, ) : AnnotationSpecHandler by handler { public companion object { public fun of(handler: AnnotationSpecHandler): AnnotationSpecHandlerScope = AnnotationSpecHandlerScope(handler) } /** @see annotation */ public operator fun ClassName.invoke( configuration: AnnotationSpecBuilder.() -> Unit, ): AnnotationSpec = buildAnnotationSpec(this, configuration).also(::annotation) /** @see annotation */ public operator fun ParameterizedTypeName.invoke( configuration: AnnotationSpecBuilder.() -> Unit, ): AnnotationSpec = buildAnnotationSpec(this, configuration).also(::annotation) /** @see annotation */ @OptIn(DelicateKotlinPoetApi::class) public operator fun Class<*>.invoke( configuration: AnnotationSpecBuilder.() -> Unit, ): AnnotationSpec = buildAnnotationSpec(name2, configuration).also(::annotation) /** @see annotation */ public operator fun KClass<*>.invoke( configuration: AnnotationSpecBuilder.() -> Unit, ): AnnotationSpec = buildAnnotationSpec(name, configuration).also(::annotation) } /** Wrapper of [AnnotationSpec.Builder], providing DSL support as a replacement to Java builder. */ @KotlinpoetDsl public class AnnotationSpecBuilder( private val nativeBuilder: AnnotationSpec.Builder, ) { public val members: MutableList<CodeBlock> get() = nativeBuilder.members public val tags: MutableMap<KClass<*>, Any> get() = nativeBuilder.tags public fun member(format: String, vararg args: Any) { nativeBuilder.addMember(format, *args) } public fun member(code: CodeBlock) { nativeBuilder.addMember(code) } public var useSiteTarget: AnnotationSpec.UseSiteTarget? @Deprecated(NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter() set(value) { nativeBuilder.useSiteTarget(value) } public fun build(): AnnotationSpec = nativeBuilder.build() }
1
Kotlin
0
4
4a661f7ea0a7e75b85809ad9b032a6987eeda5e0
7,588
kotlinpoet-dsl
Apache License 2.0
comet-api/src/test/kotlin/ren/natsuyuk1/comet/api/test/command/TestCommandManager.kt
StarWishsama
173,288,057
false
null
package ren.natsuyuk1.comet.api.test.command import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import ren.natsuyuk1.comet.api.command.CommandManager import ren.natsuyuk1.comet.api.database.DatabaseManager import ren.natsuyuk1.comet.api.message.buildMessageWrapper import ren.natsuyuk1.comet.api.test.database.initTestDatabase import ren.natsuyuk1.comet.api.test.fakeComet import ren.natsuyuk1.comet.api.test.fakeSender import ren.natsuyuk1.comet.api.user.UserPermissionTable import ren.natsuyuk1.comet.api.user.UserTable @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TestCommandManager { @BeforeAll fun init() { initTestDatabase() DatabaseManager.loadTables(UserTable, UserPermissionTable) CommandManager.init() CommandManager.registerCommand(HELP) { comet, sender, subject, wrapper, user -> TestHelpCommand( comet, sender, subject, wrapper, user ) } CommandManager.registerCommand(PERMISSION) { comet, sender, subject, wrapper, user -> TestPermissionCommand( comet, sender, subject, wrapper, user ) } } @Test fun testCommandExecute() { runBlocking { CommandManager.executeCommand( fakeComet, fakeSender, fakeSender, buildMessageWrapper { appendText("/help") } ).join() } } @Test fun testPermission() { runBlocking { CommandManager.executeCommand( fakeComet, fakeSender, fakeSender, buildMessageWrapper { appendText("/perm") } ).join() } } }
19
null
20
193
19ed20ec4003a37be3bc2dfc6b55a9e2548f0542
1,965
Comet-Bot
MIT License
src/test/kotlin/dev/aspid812/virtualfs/VirtualFileSystemBackendTest.kt
Const-Grigoryev
372,778,547
false
null
package dev.aspid812.virtualfs import dev.aspid812.virtualfs.mock.BlockStorageMock import org.junit.Assert import org.junit.Test import java.nio.ByteBuffer class VirtualFileSystemBackendTest { @Test fun `allocate() - Enough vacant blocks`() { val storage = BlockStorageMock().apply { addHeaderIndexBlock { firstVacantBlock = 1U } addDataBlock { nextDataBlock = 2U } addDataBlock { nextDataBlock = 0U } } val subj = VirtualFileSystemBackend(storage) val allocated = subj.allocate(1) Assert.assertEquals(1, allocated.size) Assert.assertEquals(1U, allocated[0]) Assert.assertEquals(2U, storage.readHeaderIndexBlock(0U).firstVacantBlock) Assert.assertEquals(0U, storage.readDataBlock(2U).nextDataBlock) } @Test fun `allocate() - Too few vacant blocks`() { val storage = BlockStorageMock().apply { addHeaderIndexBlock { firstVacantBlock = 1U } addDataBlock { nextDataBlock = 2U } addDataBlock { nextDataBlock = 0U } } val subj = VirtualFileSystemBackend(storage) val allocated = subj.allocate(3) Assert.assertEquals(3, allocated.size) Assert.assertEquals(1U, allocated[0]) Assert.assertEquals(2U, allocated[1]) Assert.assertEquals(3U, allocated[2]) Assert.assertEquals(0U, storage.readHeaderIndexBlock(0U).firstVacantBlock) } @Test fun `free() - Free multiple blocks`() { // Vacant block chain: 0 -> 1 -> 3 (-> 0) // Chain to be prepended: 2 -> 4 (-> 0) val storage = BlockStorageMock().apply { addHeaderIndexBlock { firstVacantBlock = 1U } addDataBlock { nextDataBlock = 3U } addDataBlock { nextDataBlock = 4U } addDataBlock { nextDataBlock = 0U } addDataBlock { nextDataBlock = 0U } } val subj = VirtualFileSystemBackend(storage) subj.free(2U, 4U) // Vacant block chain: 0 -> 2 -> 4 -> 3 -> 1 (-> 0) Assert.assertEquals(2U, storage.readHeaderIndexBlock(0U).firstVacantBlock) Assert.assertEquals(3U, storage.readDataBlock(1U).nextDataBlock) Assert.assertEquals(4U, storage.readDataBlock(2U).nextDataBlock) Assert.assertEquals(0U, storage.readDataBlock(3U).nextDataBlock) Assert.assertEquals(1U, storage.readDataBlock(4U).nextDataBlock) } @Test fun `free() - Free single block`() { // Vacant block chain: 0 -> 1 -> 3 (-> 0) // Chain to be prepended: 2 (-> 0) val storage = BlockStorageMock().apply { addHeaderIndexBlock { firstVacantBlock = 1U } addDataBlock { nextDataBlock = 3U } addDataBlock { nextDataBlock = 0U } addDataBlock { nextDataBlock = 0U } } val subj = VirtualFileSystemBackend(storage) subj.free(2U, 2U) // Vacant block chain: 0 -> 2 -> 3 -> 1 (-> 0) Assert.assertEquals(2U, storage.readHeaderIndexBlock(0U).firstVacantBlock) Assert.assertEquals(3U, storage.readDataBlock(1U).nextDataBlock) Assert.assertEquals(1U, storage.readDataBlock(2U).nextDataBlock) Assert.assertEquals(0U, storage.readDataBlock(3U).nextDataBlock) } @Test fun `free() - Initially empty vacant block chain`() { // Vacant block chain: 0 (-> 0) // Chain to be prepended: 1 -> 2 (-> 0) val storage = BlockStorageMock().apply { addHeaderIndexBlock { firstVacantBlock = 0U } addDataBlock { nextDataBlock = 2U } addDataBlock { nextDataBlock = 0U } } val subj = VirtualFileSystemBackend(storage) subj.free(1U, 2U) // Vacant block chain: 0 -> 1 -> 2 (-> 0) Assert.assertEquals(1U, storage.readHeaderIndexBlock(0U).firstVacantBlock) Assert.assertEquals(2U, storage.readDataBlock(1U).nextDataBlock) Assert.assertEquals(0U, storage.readDataBlock(2U).nextDataBlock) } @Test fun `buildIndex()`() { val storage = BlockStorageMock().apply { addHeaderIndexBlock { nextIndexBlock = 1U prevIndexBlock = 2U } addFileIndexBlock { nextIndexBlock = 2U prevIndexBlock = 0U fileSize = 22L fileName = "foo" } addFileIndexBlock { nextIndexBlock = 0U prevIndexBlock = 1U fileSize = 33L fileName = "bar" } } val subj = VirtualFileSystemBackend(storage) val index = subj.buildIndex() Assert.assertEquals(2, index.size) Assert.assertEquals("foo", index[0].name) Assert.assertEquals(22L, index[0].size) Assert.assertEquals(1U, index[0].handle) Assert.assertEquals("bar", index[1].name) Assert.assertEquals(33L, index[1].size) Assert.assertEquals(2U, index[1].handle) } @Test fun `createFile() - Empty file index`() { val storage = BlockStorageMock().apply { addHeaderIndexBlock {} } val subj = VirtualFileSystemBackend(storage) val created = subj.createFile("foo") Assert.assertEquals(created, storage.readHeaderIndexBlock(0U).nextIndexBlock) Assert.assertEquals(created, storage.readHeaderIndexBlock(0U).prevIndexBlock) Assert.assertEquals(0U, storage.readFileIndexBlock(created).nextIndexBlock) Assert.assertEquals(0U, storage.readFileIndexBlock(created).prevIndexBlock) } @Test fun `createFile() - Non-empty file index`() { val storage = BlockStorageMock().apply { addHeaderIndexBlock { nextIndexBlock = 1U prevIndexBlock = 1U } addFileIndexBlock { nextIndexBlock = 0U prevIndexBlock = 0U } } val subj = VirtualFileSystemBackend(storage) val created = subj.createFile("foo") Assert.assertEquals(1U, storage.readHeaderIndexBlock(0U).nextIndexBlock) Assert.assertEquals(created, storage.readHeaderIndexBlock(0U).prevIndexBlock) Assert.assertEquals(created, storage.readFileIndexBlock(1U).nextIndexBlock) Assert.assertEquals(0U, storage.readFileIndexBlock(1U).prevIndexBlock) Assert.assertEquals(0U, storage.readFileIndexBlock(created).nextIndexBlock) Assert.assertEquals(1U, storage.readFileIndexBlock(created).prevIndexBlock) } @Test fun `createFile() - File attributes are set`() { val storage = BlockStorageMock().apply { addHeaderIndexBlock {} } val subj = VirtualFileSystemBackend(storage) val created = subj.createFile("foo") Assert.assertEquals(0L, storage.readFileIndexBlock(created).fileSize) Assert.assertEquals("foo", storage.readFileIndexBlock(created).fileName) } @Test fun `deleteFile() - Non-empty file`() { // File entry list: 0 <-> 2 <-> 1 (<-> 0) // Data block chains: 1 -> 3 (-> 0), 2 (-> 0) val storage = BlockStorageMock().apply { addHeaderIndexBlock { nextIndexBlock = 2U prevIndexBlock = 1U } addFileIndexBlock { nextIndexBlock = 0U prevIndexBlock = 2U firstDataBlock = 3U lastDataBlock = 3U } addFileIndexBlock { nextIndexBlock = 1U prevIndexBlock = 0U } addDataBlock { nextDataBlock = 0U } } val subj = VirtualFileSystemBackend(storage) subj.deleteFile(1U) // File entry list: 0 <-> 2 (<-> 0) Assert.assertEquals(2U, storage.readHeaderIndexBlock(0U).nextIndexBlock) Assert.assertEquals(2U, storage.readHeaderIndexBlock(0U).prevIndexBlock) Assert.assertEquals(0U, storage.readFileIndexBlock(2U).nextIndexBlock) Assert.assertEquals(0U, storage.readFileIndexBlock(2U).prevIndexBlock) // Vacant block chain: 0 -> 1 -> 3 (-> 0) Assert.assertEquals(1U, storage.readHeaderIndexBlock(0U).firstVacantBlock) Assert.assertEquals(3U, storage.readDataBlock(1U).nextDataBlock) Assert.assertEquals(0U, storage.readDataBlock(3U).nextDataBlock) } @Test fun `deleteFile() - Empty file`() { // File entry list: 0 <-> 2 <-> 1 (<-> 0) // Data block chains: 1 -> 3 (-> 0), 2 (-> 0) val storage = BlockStorageMock().apply { addHeaderIndexBlock { nextIndexBlock = 2U prevIndexBlock = 1U } addFileIndexBlock { nextIndexBlock = 0U prevIndexBlock = 2U firstDataBlock = 3U lastDataBlock = 3U } addFileIndexBlock { nextIndexBlock = 1U prevIndexBlock = 0U } addDataBlock { nextDataBlock = 0U } } val subj = VirtualFileSystemBackend(storage) subj.deleteFile(2U) // File entry list: 0 <-> 1 (<-> 0) Assert.assertEquals(1U, storage.readHeaderIndexBlock(0U).nextIndexBlock) Assert.assertEquals(1U, storage.readHeaderIndexBlock(0U).prevIndexBlock) Assert.assertEquals(0U, storage.readFileIndexBlock(1U).nextIndexBlock) Assert.assertEquals(0U, storage.readFileIndexBlock(1U).prevIndexBlock) // Vacant block chain: 0 -> 2 (-> 0) Assert.assertEquals(2U, storage.readHeaderIndexBlock(0U).firstVacantBlock) Assert.assertEquals(0U, storage.readDataBlock(2U).nextDataBlock) } @Test fun `deleteFile() - Last file remain`() { // File entry list: 0 <-> 1 (<-> 0) // Data block chains: 1 -> 2 (-> 0) val storage = BlockStorageMock().apply { addHeaderIndexBlock { nextIndexBlock = 1U prevIndexBlock = 1U } addFileIndexBlock { nextIndexBlock = 0U prevIndexBlock = 0U firstDataBlock = 2U lastDataBlock = 2U } addDataBlock { nextDataBlock = 0U } } val subj = VirtualFileSystemBackend(storage) subj.deleteFile(1U) // File entry list: 0 (<-> 0) Assert.assertEquals(0U, storage.readHeaderIndexBlock(0U).nextIndexBlock) Assert.assertEquals(0U, storage.readHeaderIndexBlock(0U).prevIndexBlock) // Vacant block chain: 0 -> 1 -> 2 (-> 0) Assert.assertEquals(1U, storage.readHeaderIndexBlock(0U).firstVacantBlock) Assert.assertEquals(2U, storage.readDataBlock(1U).nextDataBlock) Assert.assertEquals(0U, storage.readDataBlock(2U).nextDataBlock) } @Test fun `loadFile() - Regular case`() { val storage = BlockStorageMock().apply { addHeaderIndexBlock { nextIndexBlock = 1U prevIndexBlock = 1U } addFileIndexBlock { nextIndexBlock = 0U prevIndexBlock = 0U fileSize = 6L firstDataBlock = 2U lastDataBlock = 3U } addDataBlock { nextDataBlock = 3U fileData = byteArrayOf(1, 2, 3) } addDataBlock { nextDataBlock = 0U fileData = byteArrayOf(4, 5, 6) } } val subj = VirtualFileSystemBackend(storage) val loadedData = subj.loadFile(1U) Assert.assertArrayEquals(byteArrayOf(1, 2, 3, 4, 5, 6), loadedData) } @Test fun `loadFile() - Buffer is smaller than the file`() { val storage = BlockStorageMock().apply { addHeaderIndexBlock { nextIndexBlock = 1U prevIndexBlock = 1U } addFileIndexBlock { nextIndexBlock = 0U prevIndexBlock = 0U fileSize = 6L firstDataBlock = 2U lastDataBlock = 3U } addDataBlock { nextDataBlock = 3U fileData = byteArrayOf(1, 2, 3) } addDataBlock { nextDataBlock = 0U fileData = byteArrayOf(4, 5, 6) } } val subj = VirtualFileSystemBackend(storage) val loadedData = subj.loadFile(1U) Assert.assertArrayEquals(byteArrayOf(1, 2, 3, 4), loadedData) } @Test fun `loadFile() - Buffer is larger than the file`() { val storage = BlockStorageMock().apply { addHeaderIndexBlock { nextIndexBlock = 1U prevIndexBlock = 1U } addFileIndexBlock { nextIndexBlock = 0U prevIndexBlock = 0U fileSize = 6L firstDataBlock = 2U lastDataBlock = 3U } addDataBlock { nextDataBlock = 3U fileData = byteArrayOf(1, 2, 3) } addDataBlock { nextDataBlock = 0U fileData = byteArrayOf(4, 5, 6) } } val subj = VirtualFileSystemBackend(storage) val loadedData = subj.loadFile(1U) Assert.assertArrayEquals(byteArrayOf(1, 2, 3, 4, 5, 6), loadedData) } @Test fun `storeFile()`() { val storage = BlockStorageMock().apply { addHeaderIndexBlock { nextIndexBlock = 1U prevIndexBlock = 1U } addFileIndexBlock { nextIndexBlock = 0U prevIndexBlock = 0U } } val subj = VirtualFileSystemBackend(storage) val storedData = byteArrayOf(1, 2, 3, 4, 5, 6) subj.storeFile(1U, storedData, 0, storedData.size) Assert.assertEquals(6, storage.readFileIndexBlock(1U).fileSize) Assert.assertEquals(2U, storage.readFileIndexBlock(1U).firstDataBlock) Assert.assertEquals(3U, storage.readFileIndexBlock(1U).lastDataBlock) Assert.assertArrayEquals(byteArrayOf(1, 2, 3, 4), storage.readDataBlock(2U).fileData) Assert.assertArrayEquals(byteArrayOf(5, 6), storage.readDataBlock(3U).fileData) } }
0
Kotlin
0
0
bda30b1b8fc11126bce238dbc0f38cce5397d815
12,034
VirtualFileSystem
MIT License
brd-android/kyc/src/main/java/com/rockwallet/kyc/ui/features/stateselection/StateSelectionAdapter.kt
rockwalletcode
598,550,195
false
null
package com.rockwallet.kyc.ui.features.stateselection import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.rockwallet.kyc.data.model.CountryState import com.rockwallet.kyc.databinding.ListItemStateBinding class StateSelectionAdapter(private val callback: (CountryState) -> Unit) : ListAdapter<CountryState, StateSelectionAdapter.ViewHolder>( CountryDiffCallback ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( ListItemStateBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind( state = getItem(position), callback = callback ) } class ViewHolder(val binding: ListItemStateBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(state: CountryState, callback: (CountryState) -> Unit) { with(binding) { tvTitle.text = state.name root.setOnClickListener { callback(state) } } } } object CountryDiffCallback : DiffUtil.ItemCallback<CountryState>() { override fun areItemsTheSame(oldItem: CountryState, newItem: CountryState) = oldItem.code == newItem.code override fun areContentsTheSame(oldItem: CountryState, newItem: CountryState) = oldItem.name == newItem.name } }
0
Kotlin
0
0
5eea47948c125678a59ada98bc95f865c81b8531
1,651
oss-wallet-android
MIT License
app/src/main/java/com/sunnyweather/android/logic/model/DailyResponse.kt
caicancan
383,820,978
false
null
package com.sunnyweather.android.logic.model import com.google.gson.annotations.SerializedName import java.util.* import javax.xml.transform.Result data class DailyResponse(val status:String,val result: Result){ data class Result(val daily:Daily) data class Daily(val temperature:List<Temperature>,val skycon:List<Skycon>,@SerializedName("life_index") val lifeIndex:LifeIndex) data class Temperature(val max:Float,val min :Float) data class Skycon(val value:String,val date:Date) data class LifeIndex(val coldRisk:List<LifeDescripition>,val carWashing:List<LifeDescripition>,val ultraviolet:List<LifeDescripition>,val dressing:List<LifeDescripition>) data class LifeDescripition(val desc:String) }
0
Kotlin
0
0
c7212bda57b8bc4b2032264d3b7c5b8b06e351a0
726
SunnyWeather
Apache License 2.0
dominion-app/src/commonMain/kotlin/io/ashdavies/dominion/Collection.kt
ashdavies
36,688,248
false
{"Kotlin": 243450, "HCL": 20680, "Shell": 3934, "Mustache": 2101}
package io.ashdavies.dominion internal inline fun <T, K, V> Collection<T>.associateNotNull( transform: (T) -> Pair<K, V>?, ): Map<K, V> = buildMap { for (element in this@associateNotNull) { val pair = transform(element) ?: continue put(pair.first, pair.second) } }
41
Kotlin
31
117
11e4ecfcbd6ba63f4b69871ee7f7e04b9dc06506
294
playground.ashdavies.dev
Apache License 2.0
mmock-runtime/src/commonMain/kotlin/com/pega/mmock/backend/unsafe/DefaultInstance.kt
pegasystems
294,162,816
false
null
/* * Copyright 2020 Pegasystems Inc. All rights reserved. * Use of this source code is governed by a Apache 2.0 license that can be found in the LICENSE file. */ package com.pega.mmock.backend.unsafe @OptIn(ExperimentalUnsignedTypes::class) inline fun <reified T> defaultInstance(): T { return when (T::class) { Boolean::class -> false as T Int::class -> 0 as T Short::class -> 0.toShort() as T Long::class -> 0L as T Byte::class -> 0x0.toByte() as T UInt::class -> 0u as T UShort::class -> 0.toUShort() as T ULong::class -> 0.toULong() as T UByte::class -> 0x0u.toUByte() as T Double::class -> 0.0 as T Char::class -> '\n' as T String::class -> "" as T // Primitive arrays BooleanArray::class -> booleanArrayOf() as T IntArray::class -> intArrayOf() as T ShortArray::class -> shortArrayOf() as T LongArray::class -> longArrayOf() as T FloatArray::class -> floatArrayOf() as T ByteArray::class -> byteArrayOf() as T DoubleArray::class -> doubleArrayOf() as T CharArray::class -> charArrayOf() as T UIntArray::class -> uintArrayOf() as T UShortArray::class -> ushortArrayOf() as T ULongArray::class -> ulongArrayOf() as T UByteArray::class -> ubyteArrayOf() as T else -> createUnsafe() } } inline fun <reified T> defaultArrayInstance(): Array<T> = arrayOf() inline fun <reified T> defaultListInstance(): List<T> = listOf() inline fun <reified T> defaultMutableListInstance(): MutableList<T> = mutableListOf() inline fun <reified T> defaultSetInstance(): Set<T> = setOf() inline fun <reified T, reified E> defaultMapInstance(): Map<T, E> = mapOf() inline fun <reified T, reified E> defaultMutableMapInstance(): MutableMap<T, E> = mutableMapOf() inline fun <reified T> defaultMutableSetInstance(): MutableSet<T> = mutableSetOf()
12
Kotlin
0
9
6689bcaa9970d1daf139b1d9cc794d47b0d9c0c9
1,959
mmock
Apache License 2.0
lib-chain-ethereum/src/main/java/com/smallraw/chain/ethereum/network/Ropsten.kt
QuincySx
262,699,409
false
null
package com.smallraw.chain.ethereum.network import com.smallraw.crypto.core.extensions.hexToByteArray class Ropsten : BaseNetwork() { override val id: Long = 3 override val genesisBlockHash: ByteArray = "41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d".hexToByteArray() }
1
C
6
26
0beea2170ea56e2dd224fe0e174d5ac2951632ca
306
ChainWallet
Apache License 2.0
src/main/kotlin/org/bymc/gomoku/game/common/GameSituation.kt
watermirror
539,082,095
false
{"Kotlin": 235223}
package org.bymc.gomoku.game.common import org.bymc.gomoku.model.common.param.GameState import org.bymc.gomoku.model.common.param.Stone import java.util.Date /** * 游戏情况。 * * @author: zheng.chez * @since: 2022/09/22 */ data class GameSituation( /** * 棋局状态。 */ val state: GameState, /** * 当前回合执行方。 */ val roundActor: Stone, /** * 已经存在的落子次数。 */ val dropCount: Int, /** * 当前局面能否执行悔棋操作。当前回合执行方如果尚未落子记录,则不能悔棋。 */ val retractionAvailable: Boolean, /** * 开始时间。 */ val beginTime: Date, /** * 结束时间。当 state 为 PLAYING 时恒为 null。 */ val endTime: Date?, /** * 最近落子时间。当 dropCount 为 0 时恒为 null。 */ val lastDropTime: Date? )
0
Kotlin
0
2
cb6b9caa0de191097eab5fcd08f76bbdbb991a1b
746
gomoku
MIT License
src/main/kotlin/org/teamvoided/shippost/config/StickableConfig.kt
TeamVoided
648,231,566
false
{"Kotlin": 58664}
package org.teamvoided.shippost.config import net.minecraft.item.Items import org.teamvoided.shippost.init.SpItems object StickableConfig { val STICKABLE = listOf( Items.STICK, Items.END_ROD, Items.BONE, Items.DEBUG_STICK, SpItems.NETHERITE_STICK, ) val STICKABLE_EXPLOSIVE = listOf(Items.FIREWORK_ROCKET) val STICKABLE_FLAMMABLE = listOf(Items.BLAZE_ROD) val flammableLength = 100 }
0
Kotlin
0
2
bf2ce69d266f77f3a897ef27080fc3902544e5c1
447
TheShippostMod
MIT License
integration/camunda-bpm/taskpool-collector/src/main/kotlin/io/holunda/polyflow/taskpool/collector/task/TaskServiceCollectorService.kt
holunda-io
135,994,693
false
{"Kotlin": 1271745}
package io.holunda.polyflow.taskpool.collector.task import io.holunda.camunda.taskpool.api.task.EngineTaskCommandFilter import io.holunda.polyflow.taskpool.asCreateCommand import io.holunda.polyflow.taskpool.callInProcessEngineContext import io.holunda.polyflow.taskpool.collector.CamundaTaskpoolCollectorProperties import io.holunda.polyflow.view.query.PageableSortableQuery import org.camunda.bpm.engine.TaskService import org.camunda.bpm.engine.impl.db.entitymanager.DbEntityManager import org.camunda.bpm.engine.impl.interceptor.CommandContext import org.camunda.bpm.engine.impl.interceptor.CommandContextListener import org.camunda.bpm.engine.impl.interceptor.CommandExecutor import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity import org.springframework.context.ApplicationEventPublisher /** * Service to collect tasks and fire the corresponding commands using Camunda Task Service. */ class TaskServiceCollectorService( private val taskService: TaskService, private val commandExecutor: CommandExecutor, private val camundaTaskpoolCollectorProperties: CamundaTaskpoolCollectorProperties, private val applicationEventPublisher: ApplicationEventPublisher, private val engineTaskCommandFilter: EngineTaskCommandFilter ) { /** * Collects tasks existing inm the Camunda task service * sends commands for all which are not filtered away by the filter. * In combination with [TaskAggregateEngineTaskCommandFilter] this can be used to initialize * the event store with tasks from the engine. * @param activeOnly parameter controlling if only active tasks are collected. * @param firstResult first result of filtered command list to be sent * @param maxResults last result of filtered command list to be sent */ fun collectAndPopulateExistingTasks(activeOnly: Boolean = true, firstResult: Int = 0, maxResults: Int = 1000) { callInProcessEngineContext(newContext = true) { commandExecutor.execute { innerContext -> innerContext.registerCommandContextListener(object : CommandContextListener { override fun onCommandContextClose(commandContext: CommandContext) { // Remove all cached entities from the inner context because we don't want to accidentally flush any changes that could cause // OptimisticLockingExceptions in the outer context. // (We don't change any variables but there are situations where _reading_ a variable also causes a change, e.g. when the serialized form of a // complex variable has changed because properties have been added since creation of the variable. Another example: A variable containing a Set // has been created and serialized from a LinkedHashSet with a specific order, but is deserialized to a HashSet with a different iteration order. // When this is serialized again, the serialized form will look different because the order has changed. (commandContext.sessions[DbEntityManager::class.java] as? DbEntityManager)?.dbEntityCache?.apply { cachedEntities.forEach { remove(it) } } } override fun onCommandFailed(commandContext: CommandContext, t: Throwable) { } }) // query val engineTasks = taskService .createTaskQuery() .initializeFormKeys() .let { if (activeOnly) { it.active() } else { it } }.list() // create commands val commands = engineTasks.filterIsInstance<TaskEntity>().map { task -> task.asCreateCommand(camundaTaskpoolCollectorProperties.applicationName) } // filter and limit val filtered = commands.filter { command -> engineTaskCommandFilter.test(command) }.let { if (firstResult < it.size) { it.subList(firstResult, maxResults.coerceAtMost(it.size)) } else { it } } // publish filtered.forEach { applicationEventPublisher.publishEvent(it) } } } } }
21
Kotlin
26
68
0a80b87e49127b355d62f8a32e91a6c355d11419
4,072
camunda-bpm-taskpool
Apache License 2.0
Codelabs/Dependency Injection/Dagger/MySimpleLogin/app/src/main/java/com/dicoding/mysimplelogin/di/StorageModule.kt
patriciafiona
731,611,881
false
{"Kotlin": 298580}
package com.dicoding.mysimplelogin.di import android.content.Context import com.dicoding.mysimplelogin.SessionManager import dagger.Module import dagger.Provides @Module class StorageModule { @Provides fun provideSessionManager(context: Context): SessionManager = SessionManager(context) }
0
Kotlin
0
1
4e29e2e206d92ac6c3e041909c9120e85685938a
299
Dicoding---Menjadi-Android-Developer-Expert
MIT License
Chapter3/src/main/kotlin/Composite.kt
Atesh19
403,209,099
true
{"Kotlin": 20172}
class Squad(private val units: List<StormTrooper>) { fun move(x: Long, y: Long) { for (u in units) { u.move(x, y) } } fun attack(x: Long, y: Long) { for (u in units) { u.attackRebel(x, y) } } } fun main() { // TODO varargs? val bobaFett = StormTrooper(Rifle(), RegularLegs()) val squad = Squad(listOf(bobaFett.copy(), bobaFett.copy(), bobaFett.copy())) }
0
null
0
0
7101a3d4dde0ab70f10ef63efdc56e0f0d594d90
442
Kotlin-Design-Patterns-and-Best-Practices
MIT License
app/src/main/java/org/devstrike/app/citrarb/features/news/savednews/SavedNewsDetail.kt
Devstrike-DigTech
555,884,168
false
null
/* * Copyright (c) 2022. * <NAME> * For Afro Connect Technologies * Under the Authority of Devstrike Digital Ltd. * */ package org.devstrike.app.citrarb.features.news.savednews import android.content.Intent import android.os.Bundle import android.text.method.ScrollingMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.navArgs import dagger.hilt.android.AndroidEntryPoint import org.devstrike.app.citrarb.R import org.devstrike.app.citrarb.base.BaseFragment import org.devstrike.app.citrarb.databinding.FragmentSavedNewsDetailBinding import org.devstrike.app.citrarb.features.news.data.NewsApi import org.devstrike.app.citrarb.features.news.data.NewsDao import org.devstrike.app.citrarb.features.news.newsLanding.NewsViewModel import org.devstrike.app.citrarb.features.news.newsLanding.data.local.SavedNewsListData import org.devstrike.app.citrarb.features.news.repositories.NewsRepoImpl import org.devstrike.app.citrarb.network.undoSnackbar import org.devstrike.app.citrarb.utils.loadImage import javax.inject.Inject import kotlin.properties.Delegates /* * Fragment class to display the detailed content of the locally saved news * */ @AndroidEntryPoint class SavedNewsDetail : BaseFragment<NewsViewModel, FragmentSavedNewsDetailBinding, NewsRepoImpl>() { @set:Inject var newsApi: NewsApi by Delegates.notNull<NewsApi>() @set:Inject var newsDao: NewsDao by Delegates.notNull<NewsDao>() private val newsDetailViewModel: NewsViewModel by activityViewModels() val args by navArgs<SavedNewsDetailArgs>() lateinit var savedNewsDetails: SavedNewsListData private var shareIntent: Intent by Delegates.notNull() private var shareMessage: String by Delegates.notNull() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //the passed details from the list UI is fetched from the nav args savedNewsDetails = args.savedNewsDetail with(binding) { //populate the UI newsDetailNewsTitle.text = savedNewsDetails.title newsDetailText.text = savedNewsDetails.article newsDetailNewsAuthor.text = savedNewsDetails.author newsDetailImage.loadImage(savedNewsDetails.coverPhoto) //using the defined utility class for implementing Glide //enable scrolling in the news detail textview newsDetailText.movementMethod = ScrollingMovementMethod() //implement the share news link feature newsDetailIvShareNews.setOnClickListener { shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_SUBJECT, savedNewsDetails.title) shareMessage = "\nCheck out this news \n${savedNewsDetails.link}" shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage) requireContext().startActivity(Intent.createChooser(shareIntent, "Share via: ")) //requireView().snackbar("Share Feature Coming Soon...") } //implement the save and unsave functionality newsDetailIvSaveNews.setOnClickListener { newsDetailViewModel.deleteNews(savedNewsDetails.uid) newsDetailIvSaveNews.setImageResource(R.drawable.ic_unsaved_bookmark) requireView().undoSnackbar("News Deleted From Saves") { newsDetailViewModel.undoDeleteNews(savedNewsDetails) newsDetailIvSaveNews.setImageResource(R.drawable.ic_saved_bookmark) } } } } override fun getFragmentRepo() = NewsRepoImpl(newsApi, newsDao) override fun getViewModel() = NewsViewModel::class.java override fun getFragmentBinding( inflater: LayoutInflater, container: ViewGroup? ) = FragmentSavedNewsDetailBinding.inflate(inflater, container, false) }
43
Kotlin
0
0
c5ea61d83b8211d949efaee0a1215d9b284f570f
4,091
CITRARB--Android-App
Apache License 2.0
src/main/kotlin/sosteam/deamhome/domain/item/service/ItemDeleteService.kt
S-OSTeam
686,862,885
false
{"Kotlin": 119438}
package sosteam.deamhome.domain.item.service import kotlinx.coroutines.reactor.awaitSingleOrNull import org.springframework.stereotype.Service import sosteam.deamhome.domain.category.exception.CategoryNotFoundException import sosteam.deamhome.domain.category.repository.ItemCategoryRepository import sosteam.deamhome.domain.item.exception.ItemNotFoundException import sosteam.deamhome.domain.item.repository.ItemRepository import sosteam.deamhome.global.image.provider.ImageProvider @Service class ItemDeleteService ( private val itemRepository: ItemRepository, private val itemCategoryRepository: ItemCategoryRepository, private val imageProvider: ImageProvider ) { suspend fun deleteItem(id: String) : String { val category = itemCategoryRepository.findCategoryByItemId(id) ?: throw CategoryNotFoundException() category.itemDetailCategories.forEach { detailCategory -> if (id in detailCategory.itemIdList) { detailCategory.itemIdList.remove(id) return@forEach } } val item = itemRepository.findById(id).awaitSingleOrNull() ?: throw ItemNotFoundException() // 근데 이미지는 지워지는데 폴더는 그대로 있는데 어떡하지 item.images.map { imageProvider.deleteImage(it.path) } itemCategoryRepository.save(category).awaitSingleOrNull() itemRepository.deleteItemById(id) return id } }
5
Kotlin
0
0
d98d98625ee123e4ead059f0118465cc2b45f69f
1,453
shop-api
MIT License
src/main/kotlin/me/ilex/statistics/rank.kt
AlexMiroshnikov
344,885,605
false
null
package me.ilex.statistics import java.math.BigInteger fun rank(seq: DoubleArray): Array<BigInteger> { val sortedSeq = seq.sorted().toTypedArray() var rank = 1.toBigInteger() var min = sortedSeq.first() val ranks = mutableMapOf(min to rank) sortedSeq.forEach { if (it != min) { rank++ min = it } ranks[it] = rank } return seq.map { ranks[it]!! }.toTypedArray() } fun rank(seq: IntArray): Array<BigInteger> = rank(seq.map { it.toDouble() }.toDoubleArray())
1
Kotlin
0
2
de89bf3a826091258ab83b620350be5987825f2b
538
kt-statistics
MIT License
myandroidutil/src/main/java/com/starsoft/myandroidutil/LifeDataUtils/ErrorHandler.kt
DmitryStarkin
315,625,438
false
{"Kotlin": 339532, "Java": 29960}
/* * Copyright (c) 2022. <NAME> Contacts: <EMAIL> * * 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 * //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.starsoft.myandroidutil.LifeDataUtils import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.starsoft.myandroidutil.R import com.starsoft.myandroidutil.providers.mainContext import java.net.SocketTimeoutException import java.net.UnknownHostException import kotlin.coroutines.cancellation.CancellationException /** * Created by <NAME> on 07.02.2022 10:52. */ open class ErrorHandler( private val context: Context, error: MutableLiveData<Event<String>> ) { companion object{ fun getInstance(): ErrorHandler = ErrorHandler(mainContext, MutableLiveData()) } private val _error = error fun getError(): LiveData<Event<String>> = _error open fun handleThrowable(throwable: Throwable) { when (throwable) { is UnknownHostException -> { _error.postValue(Event(context.getString(R.string.no_internet_error))) } is SocketTimeoutException -> { _error.postValue(Event(context.getString(R.string.server_time_out_error))) } is CancellationException -> { // nothing to do } is InterruptedException -> { // nothing to do } else -> { throwable.message?.let { message -> _error.postValue(Event(message)) } } } } }
0
Kotlin
0
3
81499c5f97421bbe892c47fa1e46bab569f641d2
2,078
my_android_utils
Apache License 2.0
app/src/main/java/com/andro/indie/school/pokedex/mapper/PokemonMapper.kt
herisulistiyanto
345,693,378
false
null
package com.andro.indie.school.pokedex.mapper import com.andro.indie.school.core.base.BaseMapper import com.andro.indie.school.pokedex.data.model.remote.PokemonModel import com.andro.indie.school.pokedex.domain.model.Pokemon import java.util.Locale /** * Created by herisulistiyanto on 02/03/21. * KjokenKoddinger */ class PokemonMapper : BaseMapper<Pair<String, PokemonModel>, Pokemon> { override fun toDomainModel(model: Pair<String, PokemonModel>): Pokemon { return with(model) { val nextUrl = first val pokemonModel = second Pokemon( id = pokemonModel.generatePokemonId(), name = pokemonModel.name.capitalize(Locale.US), url = pokemonModel.url, imgUrl = pokemonModel.generateImgUrl(), nextUrl = nextUrl ) } } override fun toModel(domain: Pokemon): Pair<String, PokemonModel> { return with(domain) { nextUrl to PokemonModel( name = name, url = url ) } } fun toListDomainModel(data: Pair<String, List<PokemonModel>>): List<Pokemon> { val nextUrl = data.first val listPokemonModel = data.second return listPokemonModel.map { pokemonModel -> Pokemon( id = pokemonModel.generatePokemonId(), name = pokemonModel.name.capitalize(Locale.US), url = pokemonModel.url, imgUrl = pokemonModel.generateImgUrl(), nextUrl = nextUrl ) } } private fun PokemonModel.generateImgUrl(): String { val index = generatePokemonId() return "https://pokeres.bastionbot.org/images/pokemon/$index.png" } private fun PokemonModel.generatePokemonId(): String { return url.split("/".toRegex()).dropLast(1).last() } }
0
Kotlin
0
0
ed7cbacfadc2baf91540f5713329173b6dae5169
1,914
pokedex-compose
The Unlicense
sample-android/src/main/java/tv/abema/fragfit/MainActivity.kt
abema
312,185,075
false
null
package tv.abema.fragfit import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import tv.abema.flagfit.DebugAnnotationAdapter import tv.abema.flagfit.FlagType import tv.abema.flagfit.Flagfit import tv.abema.flagfit.Flagfit.Companion.ENV_IS_DEBUG_KEY import tv.abema.flagfit.ReleaseAnnotationAdapter import tv.abema.fragfit.ui.theme.FlagfitSampleTheme class MainActivity : ComponentActivity() { private val sampleFlagSource = SampleFlagSource() private val flagfit = Flagfit( flagSources = listOf(sampleFlagSource), baseEnv = mapOf( ENV_IS_DEBUG_KEY to BuildConfig.DEBUG, ), annotationAdapters = listOf( DebugAnnotationAdapter(), ReleaseAnnotationAdapter(), ) + FlagType.annotationAdapters() ) private val sampleFlagService: SampleFlagService = flagfit.create() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { FlagfitSampleTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { FragfitSampleComponent(sampleFlagService) } } } } }
2
null
2
93
a956d4e2be81bbae9e45121c3ee5bab31d5bab55
1,399
flagfit
Apache License 2.0
sykepenger-model/src/test/kotlin/no/nav/helse/ArbeidsgiverperiodeBuilder.kt
navikt
193,907,367
false
null
package no.nav.helse import no.nav.helse.hendelser.Periode import no.nav.helse.person.SykdomstidslinjeVisitor import no.nav.helse.sykdomstidslinje.Dag import no.nav.helse.sykdomstidslinje.Sykdomstidslinje import no.nav.helse.sykdomstidslinje.SykdomstidslinjeHendelse import no.nav.helse.økonomi.Økonomi import java.time.LocalDate internal class ArbeidsgiverperiodeBuilder(private val arbeidsgiverperiodeteller: Arbeidsgiverperiodeteller, private val mediator: ArbeidsgiverperiodeMediator) : SykdomstidslinjeVisitor, Arbeidsgiverperiodeteller.Observatør { init { arbeidsgiverperiodeteller.observer(this) } private var tilstand: Tilstand = Initiell override fun postVisitSykdomstidslinje(tidslinje: Sykdomstidslinje, låstePerioder: MutableList<Periode>) { fridager.somFeriedager() } private fun tilstand(tilstand: Tilstand) { if (this.tilstand == tilstand) return this.tilstand.leaving(this) this.tilstand = tilstand this.tilstand.entering(this) } override fun arbeidsgiverperiodedag() { tilstand(Arbeidsgiverperiode) } override fun sykedag() { tilstand(Utbetaling) } override fun arbeidsgiverperiodeAvbrutt() { mediator.arbeidsgiverperiodeAvbrutt() } private fun MutableList<LocalDate>.somSykedager() { onEach { arbeidsgiverperiodeteller.inc() tilstand.feriedagSomSyk(this@ArbeidsgiverperiodeBuilder, it) }.clear() } private fun MutableList<LocalDate>.somFeriedager() { onEach { arbeidsgiverperiodeteller.dec() mediator.fridag(it) }.clear() } override fun visitDag(dag: Dag.Sykedag, dato: LocalDate, økonomi: Økonomi, kilde: SykdomstidslinjeHendelse.Hendelseskilde) { fridager.somSykedager() arbeidsgiverperiodeteller.inc() tilstand.sykdomsdag(this, dato, økonomi) } override fun visitDag(dag: Dag.SykHelgedag, dato: LocalDate, økonomi: Økonomi, kilde: SykdomstidslinjeHendelse.Hendelseskilde) { fridager.somSykedager() arbeidsgiverperiodeteller.inc() tilstand.sykdomshelg(this, dato, økonomi) } override fun visitDag(dag: Dag.Feriedag, dato: LocalDate, kilde: SykdomstidslinjeHendelse.Hendelseskilde) { tilstand.feriedag(this, dato) } override fun visitDag(dag: Dag.Arbeidsdag, dato: LocalDate, kilde: SykdomstidslinjeHendelse.Hendelseskilde) { tilstand(Initiell) fridager.somFeriedager() arbeidsgiverperiodeteller.dec() mediator.arbeidsdag(dato) } override fun visitDag(dag: Dag.FriskHelgedag, dato: LocalDate, kilde: SykdomstidslinjeHendelse.Hendelseskilde) { tilstand(Initiell) fridager.somFeriedager() arbeidsgiverperiodeteller.dec() mediator.fridag(dato) } private val fridager = mutableListOf<LocalDate>() private interface Tilstand { fun entering(builder: ArbeidsgiverperiodeBuilder) {} fun sykdomsdag(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate, økonomi: Økonomi) { builder.mediator.utbetalingsdag(dato, økonomi) } fun sykdomshelg(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate, økonomi: Økonomi) { builder.mediator.utbetalingsdag(dato, økonomi) } fun feriedagSomSyk(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate) fun feriedag(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate) fun leaving(builder: ArbeidsgiverperiodeBuilder) {} } private object Initiell : Tilstand { override fun feriedag(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate) { builder.arbeidsgiverperiodeteller.dec() builder.mediator.fridag(dato) } override fun feriedagSomSyk(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate) { throw IllegalStateException() } } private object Arbeidsgiverperiode : Tilstand { override fun sykdomsdag(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate, økonomi: Økonomi) { builder.mediator.arbeidsgiverperiodedag(dato, økonomi) } override fun sykdomshelg(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate, økonomi: Økonomi) { builder.mediator.arbeidsgiverperiodedag(dato, økonomi) } override fun feriedagSomSyk(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate) { builder.mediator.arbeidsgiverperiodedag(dato, Økonomi.ikkeBetalt()) } override fun feriedag(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate) { builder.fridager.add(dato) } } private object Utbetaling : Tilstand { override fun entering(builder: ArbeidsgiverperiodeBuilder) { builder.mediator.arbeidsgiverperiodeFerdig() } override fun feriedag(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate) { builder.fridager.add(dato) } override fun feriedagSomSyk(builder: ArbeidsgiverperiodeBuilder, dato: LocalDate) { builder.mediator.fridag(dato) } } }
0
Kotlin
2
3
9572b362ab94daa6a730331c309a1cdc0ec25e3e
5,159
helse-spleis
MIT License
plugin/src/test/kotlin/org/jetbrains/hackathon2024/visitor/DeprecatingMethodVisitorTest.kt
ALikhachev
858,702,876
false
{"Kotlin": 37448, "Java": 265}
package org.jetbrains.hackathon2024.visitor import org.jetbrains.hackathon2024.parser.ProguardParser import org.jetbrains.hackathon2024.utils.parseClassFile import org.junit.jupiter.api.Test import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassWriter import java.io.File class DeprecatingMethodVisitorTest { @Test fun testMethodVisitor() { val classFilePath = "build/classes/kotlin/test/org/jetbrains/hackathon2024/test/ClassWithMethodToBeDeprecated.class" val someClass = File(classFilePath) val outputFile = kotlin.io.path.createTempFile(suffix = ".class").toFile() val specification = ProguardParser().parse("class org.jetbrains.hackathon2024.test.ClassWithMethodToBeDeprecated { public void *(); }") .first() someClass.inputStream().use { inputStream -> val classReader = ClassReader(inputStream) val classWriter = ClassWriter(classReader, ClassWriter.COMPUTE_FRAMES) val methodVisitor = DeprecatingClassMethodVisitor( classWriter, "Deprecated method message", specification.methodSpecifications, ) classReader.accept(methodVisitor, ClassReader.EXPAND_FRAMES) outputFile.writeBytes(classWriter.toByteArray()) } val parsedClassFile = parseClassFile(outputFile.absolutePath) val numberOfDeprecatedMethodsInClassFile = parsedClassFile.split( """ | Deprecated: true | RuntimeVisibleAnnotations: | 0: #34(#35=s#36) | kotlin.Deprecated( | message="Deprecated method message" | ) """.trimMargin() ).size - 1 assert(numberOfDeprecatedMethodsInClassFile == 3) { "ClassVisitor should add kotlin.Deprecated annotation, but it didn't.\n$parsedClassFile" } } }
0
Kotlin
0
0
8e6470ece4f3e04980223f9fe0efc8201024d127
2,004
kapifence
Apache License 2.0
springmvc-automapping/src/main/kotlin/nxcloud/ext/springmvc/automapping/spi/AutoMappingFieldArgumentResolver.kt
Sunshow
588,022,200
false
null
package nxcloud.ext.springmvc.automapping.spi import org.springframework.core.MethodParameter import org.springframework.web.context.request.NativeWebRequest import java.lang.reflect.Field /** * 解析入参对象中的自定义类型的属性字段 */ interface AutoMappingFieldArgumentResolver { fun supportsParameter( field: Field, parameterObj: Any?, parameter: MethodParameter, resolvedParameterType: Class<*>, webRequest: NativeWebRequest, ): Boolean fun resolveArgument( field: Field, parameterObj: Any?, parameter: MethodParameter, resolvedParameterType: Class<*>, webRequest: NativeWebRequest, ): Any? }
0
Kotlin
0
0
ec3cbaa526a496eb72371b5e595029e773987487
663
nxcloud-springmvc-automapping
Apache License 2.0
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress1050017.kt
pointillion
428,683,199
true
{"Kotlin": 1212476, "HTML": 26704, "CSS": 26127, "JavaScript": 1640}
package xyz.qwewqa.relive.simulator.core.presets.dress.generated import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute import xyz.qwewqa.relive.simulator.core.stage.actor.StatData import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType import xyz.qwewqa.relive.simulator.stage.character.Character import xyz.qwewqa.relive.simulator.stage.character.DamageType import xyz.qwewqa.relive.simulator.stage.character.Position val dress1050017 = PartialDressBlueprint( id = 1050017, name = "舞台少女", baseRarity = 4, character = Character.Maya, attribute = Attribute.Moon, damageType = DamageType.Normal, position = Position.Middle, positionValue = 22050, stats = StatData( hp = 2740, actPower = 221, normalDefense = 181, specialDefense = 94, agility = 205, dexterity = 5, critical = 50, accuracy = 0, evasion = 0, ), growthStats = StatData( hp = 90250, actPower = 3660, normalDefense = 2990, specialDefense = 1550, agility = 3380, ), actParameters = mapOf( ActType.Act1 to listOf( ActParameters( values = listOf(147, 154, 161, 168, 176), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ActType.Act2 to listOf( ActParameters( values = listOf(97, 102, 106, 111, 116), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(20, 22, 24, 27, 30), times = listOf(3, 3, 3, 3, 3), ), ActParameters( values = listOf(20, 22, 24, 27, 30), times = listOf(3, 3, 3, 3, 3), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ActType.Act3 to listOf( ActParameters( values = listOf(165, 173, 181, 189, 198), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ActType.ClimaxAct to listOf( ActParameters( values = listOf(5000, 5500, 6000, 6500, 7500), times = listOf(2, 2, 2, 2, 2), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ), autoSkillRanks = listOf(1, 4, 9, null), autoSkillPanels = listOf(0, 0, 5, 0), rankPanels = listOf( listOf( StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.SpecialDefense, 1), ), listOf( StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.Agility, 7), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 3), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 3), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Hp, 3), StatBoost(StatBoostType.ActPower, 3), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Hp, 4), ), listOf( StatBoost(StatBoostType.SpecialDefense, 3), StatBoost(StatBoostType.NormalDefense, 7), StatBoost(StatBoostType.NormalDefense, 3), StatBoost(StatBoostType.Agility, 8), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 4), StatBoost(StatBoostType.Hp, 4), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 4), StatBoost(StatBoostType.Act1Level, 0), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.SpecialDefense, 8), StatBoost(StatBoostType.ActPower, 5), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Hp, 5), ), listOf( StatBoost(StatBoostType.Hp, 5), StatBoost(StatBoostType.NormalDefense, 8), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Agility, 9), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 5), StatBoost(StatBoostType.NormalDefense, 8), StatBoost(StatBoostType.NormalDefense, 4), ), listOf( StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.Agility, 11), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.SpecialDefense, 6), ), listOf( StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.NormalDefense, 6), ), ), friendshipPanels = listOf( StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.SpecialDefense, 1), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.SpecialDefense, 1), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), ), remakeParameters = listOf( StatData( hp = 7200, actPower = 480, normalDefense = 900, specialDefense = 150, agility = 240, ), StatData( hp = 12000, actPower = 800, normalDefense = 1500, specialDefense = 250, agility = 400, ), StatData( hp = 19200, actPower = 1280, normalDefense = 2400, specialDefense = 400, agility = 640, ), StatData( hp = 24000, actPower = 1600, normalDefense = 3000, specialDefense = 500, agility = 800, ), ), )
0
Kotlin
0
0
53479fe3d1f4a067682509376afd87bdd205d19d
10,044
relive-simulator
MIT License
src/main/kotlin/structure/specialStrucures/RandomCuboidLines.kt
Reddek2000
297,017,912
true
{"Kotlin": 197224}
package structure.specialStrucures import structure.* import structure.helperClasses.CuboidConstrains import structure.helperClasses.Point import structure.helperClasses.SpookyWall import kotlin.math.roundToInt import kotlin.random.Random fun RandomCuboidLines.run(): List<SpookyWall> { val l= mutableListOf<SpookyWall>() val c = CuboidConstrains(p1, p2) val trueCount = count ?: c.duration.roundToInt() val r = Random(seed?: Random.nextInt()) repeat(trueCount) { val z1 = c.sz + it.toDouble() / trueCount * c.duration val z2 = z1 + 1.0 / trueCount * c.duration // selects a random Side val randomSide = r.nextInt(randomSidePicker) // selects a random Section val randomSection = r.nextInt(1, sections) val randomX = c.sx + c.width / sections * randomSection val randomY = c.sy + c.height / sections * randomSection // selects the first Point of the line val lineP1 = when (randomSide) { 0 -> Point(c.sx, randomY, z1) 1 -> Point(c.ex, randomY, z1) 2 -> Point(randomX, c.sy, z1) 3 -> Point(randomX, c.ey, z1) else -> Point(0, 0, 0) // never happens } // calculates the end X and Y val randomEndX = lineP1.x + if (r.nextBoolean()) -c.width / sections else c.width / sections val randomEndY = lineP1.y + if (r.nextBoolean()) -c.height / sections else c.height / sections val lineP2 = when (randomSide) { 0 -> lineP1.copy(y = randomEndY, z = z2) 1 -> lineP1.copy(y = randomEndY, z = z2) 2 -> lineP1.copy(x = randomEndX, z = z2) 3 -> lineP1.copy(x = randomEndX, z = z2) else -> Point(0, 0, 0) // never happens } l.addAll(line(lineP1, lineP2, amount)) } return l.toList() }
0
null
0
0
32873f427f85e851ce6c42064c7399feb08ac740
1,857
beatwalls
MIT License
app/src/main/java/com/yuchen/howyo/data/source/remote/HowYoRemoteDataSource.kt
ione0213
418,168,888
false
{"Kotlin": 509380}
package com.yuchen.howyo.data.source.remote import android.net.Uri import androidx.lifecycle.MutableLiveData import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.Query import com.google.firebase.storage.FirebaseStorage import com.yuchen.howyo.HowYoApplication import com.yuchen.howyo.R import com.yuchen.howyo.data.* import com.yuchen.howyo.data.source.HowYoDataSource import com.yuchen.howyo.home.notification.NotificationType import com.yuchen.howyo.plan.checkorshoppinglist.MainItemType import com.yuchen.howyo.signin.UserManager import com.yuchen.howyo.util.Logger import java.util.* import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine object HowYoRemoteDataSource : HowYoDataSource { private const val PATH_COVERS = "images" private const val PATH_USERS = "users" private const val PATH_PLANS = "plans" private const val PATH_DAYS = "days" private const val PATH_SCHEDULES = "schedules" private const val PATH_CHECK_SHOPPING_LIST = "check_shopping_lists" private const val PATH_COMMENTS = "comments" private const val PATH_GROUP_MESSAGE = "group_messages" private const val PATH_NOTIFICATION = "notifications" private const val PATH_PAYMENT = "payments" private const val KEY_POSITION = "position" private const val KEY_CREATED_TIME = "created_time" private const val KEY_EMAIL = "email" private const val KEY_ID = "id" private const val KEY_AUTHOR_ID = "author_id" private const val KEY_PRIVACY = "privacy" private const val KEY_COLLECTED = "plan_collected_list" private const val KEY_PLAN_ID = "plan_id" private const val KEY_MAIN_TYPE = "main_type" private const val KEY_TO_USER_ID = "to_user_id" private const val KEY_FROM_USER_ID = "from_user_id" private const val KEY_NOTIFICATION_TYPE = "notification_type" override suspend fun signOut() { FirebaseAuth.getInstance().signOut() } override suspend fun createUser(user: User): Result<String> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_USERS) .whereEqualTo(KEY_EMAIL, user.email) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { when { task.result.size() == 0 -> { val users = FirebaseFirestore.getInstance().collection(PATH_USERS) val document = users.document() user.id = document.id document .set(user) .addOnCompleteListener { createUserTask -> if (createUserTask.isSuccessful) { continuation.resume(Result.Success(user.id)) } else { createUserTask.exception?.let { Logger.w("[${this::class.simpleName}] Error creating user. ${it.message}") continuation.resume(Result.Error(it)) return@let } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } task.result.size() > 0 -> { continuation.resume(Result.Success(task.result.first().id)) } } } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error creating user. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume(Result.Fail(HowYoApplication.instance.getString(R.string.nothing))) } } } override suspend fun getUser(userId: String): Result<User> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_USERS) .whereEqualTo(KEY_ID, userId) .get() .addOnCompleteListener { task -> val user: User if (task.isSuccessful) { if (task.result != null) { when { task.result.size() > 0 -> { user = task.result.first().toObject(User::class.java) continuation.resume(Result.Success(user)) } else -> { continuation.resume(Result.Fail("No user")) } } } } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error getting user. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume(Result.Fail(HowYoApplication.instance.getString(R.string.nothing))) } } } override fun getLiveUser(userId: String): MutableLiveData<User> { val liveData = MutableLiveData<User>() FirebaseFirestore.getInstance() .collection(PATH_USERS) .whereEqualTo(KEY_ID, userId) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener live user detect:$userId") exception?.let { Logger.w("[${this::class.simpleName}] Error getting user. ${it.message}") } if (snapshot != null) { when { snapshot.size() > 0 -> { liveData.value = snapshot.first().toObject(User::class.java) } } } } return liveData } override fun getLiveUsers(userIdList: List<String>): MutableLiveData<List<User>> { val liveData = MutableLiveData<List<User>>() when (userIdList.size) { 0 -> { } else -> { FirebaseFirestore.getInstance() .collection(PATH_USERS) .whereIn(KEY_ID, userIdList) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting users. ${it.message}") } val list = mutableListOf<User>() if (snapshot != null) { for (document in snapshot) { Logger.d(document.id + " => " + document.data) val user = document.toObject(User::class.java) list.add(user) } } liveData.value = list } } } return liveData } override suspend fun getUsers(userIdList: List<String>): Result<List<User>> = suspendCoroutine { continuation -> when (userIdList.size) { 0 -> { continuation.resume(Result.Success(listOf())) } else -> { FirebaseFirestore.getInstance() .collection(PATH_USERS) .whereIn(KEY_ID, userIdList) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { val list = mutableListOf<User>() if (task.result != null) { for (document in task.result) { Logger.d(document.id + " => " + document.data) val user = document.toObject(User::class.java) list.add(user) } continuation.resume(Result.Success(list)) } } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error getting users. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume( Result.Fail( HowYoApplication.instance.getString( R.string.nothing ) ) ) } } } } } override suspend fun updateUser(user: User): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_USERS) .document(user.id) .set(user) .addOnSuccessListener { Logger.i("Update: $user") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error updating user. ${it.message}") continuation.resume(Result.Error(it)) } } override suspend fun uploadPhoto(imgUri: Uri, fileName: String): Result<String> = suspendCoroutine { continuation -> val storageRef = FirebaseStorage.getInstance().reference.child("$PATH_COVERS/$fileName") storageRef.putFile(imgUri) .addOnCompleteListener { task -> if (task.isSuccessful) { task.result.storage.downloadUrl.addOnCompleteListener { if (it.isSuccessful) { continuation.resume(Result.Success(it.result.toString())) } else { task.exception?.let { exception -> Logger.w("[${this::class.simpleName}] Error uploading img. ${exception.message}") continuation.resume(Result.Error(exception)) return@let } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error uploading img. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override suspend fun deletePhoto(fileName: String): Result<Boolean> = suspendCoroutine { continuation -> FirebaseStorage.getInstance().reference .child("$PATH_COVERS/$fileName") .delete() .addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error deleting img. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override suspend fun createPlan(plan: Plan): Result<String> = suspendCoroutine { continuation -> val plans = FirebaseFirestore.getInstance().collection(PATH_PLANS) val document = plans.document() plan.id = document.id document .set(plan) .addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(document.id)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error creating plan. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override suspend fun getPlan(planId: String): Result<Plan> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_PLANS) .whereEqualTo("id", planId) .get() .addOnCompleteListener { task -> val plan: Plan if (task.isSuccessful) { plan = task.result.first().toObject(Plan::class.java) continuation.resume(Result.Success(plan)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error getting documents. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume(Result.Fail(HowYoApplication.instance.getString(R.string.nothing))) } } } override fun getLivePlan(planId: String): MutableLiveData<Plan?> { val liveData = MutableLiveData<Plan?>() FirebaseFirestore.getInstance() .collection(PATH_PLANS) .whereEqualTo("id", planId) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener live plan detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting plan. ${it.message}") } if (snapshot != null) { if (snapshot.size() != 0) { liveData.value = snapshot.first().toObject(Plan::class.java) } } } return liveData } override suspend fun getPlans(authorList: List<String>): Result<List<Plan>> = suspendCoroutine { continuation -> when (authorList.size) { 0 -> { continuation.resume(Result.Success(listOf())) } else -> { FirebaseFirestore.getInstance() .collection(PATH_PLANS) .whereIn(KEY_AUTHOR_ID, authorList) .whereEqualTo(KEY_PRIVACY, "public") .orderBy(KEY_CREATED_TIME, Query.Direction.DESCENDING) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { val list = mutableListOf<Plan>() if (task.result != null) { for (document in task.result) { Logger.d(document.id + " => " + document.data) val plan = document.toObject(Plan::class.java) list.add(plan) } continuation.resume(Result.Success(list)) } } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error getting schedules. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume( Result.Fail( HowYoApplication.instance.getString( R.string.nothing ) ) ) } } } } } override suspend fun getAllPlans(): Result<List<Plan>> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_PLANS) .orderBy(KEY_CREATED_TIME, Query.Direction.DESCENDING) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { val list = mutableListOf<Plan>() if (task.result != null) { for (document in task.result) { Logger.d(document.id + " => " + document.data) val plan = document.toObject(Plan::class.java) list.add(plan) } continuation.resume(Result.Success(list)) } } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error getting schedules. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume( Result.Fail( HowYoApplication.instance.getString( R.string.nothing ) ) ) } } } override suspend fun getAllPublicPlans(): Result<List<Plan>> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_PLANS) .whereEqualTo(KEY_PRIVACY, "public") .orderBy(KEY_CREATED_TIME, Query.Direction.DESCENDING) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { val list = mutableListOf<Plan>() if (task.result != null) { for (document in task.result) { Logger.d(document.id + " => " + document.data) val plan = document.toObject(Plan::class.java) list.add(plan) } continuation.resume(Result.Success(list)) } } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error getting schedules. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume( Result.Fail( HowYoApplication.instance.getString( R.string.nothing ) ) ) } } } override fun getLivePlans(authorList: List<String>): MutableLiveData<List<Plan>> { val liveData = MutableLiveData<List<Plan>>() when (authorList.size) { 0 -> { } else -> { FirebaseFirestore.getInstance() .collection(PATH_PLANS) .whereIn(KEY_AUTHOR_ID, authorList) .orderBy(KEY_CREATED_TIME, Query.Direction.DESCENDING) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting plans. ${it.message}") } val list = mutableListOf<Plan>() if (snapshot != null) { for (document in snapshot) { Logger.d(document.id + " => " + document.data) val plan = document.toObject(Plan::class.java) list.add(plan) } } liveData.value = list } } } return liveData } override fun getAllLivePublicPlans(): MutableLiveData<List<Plan>> { val liveData = MutableLiveData<List<Plan>>() FirebaseFirestore.getInstance() .collection(PATH_PLANS) .whereEqualTo(KEY_PRIVACY, "public") .orderBy(KEY_CREATED_TIME, Query.Direction.DESCENDING) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting plans. ${it.message}") } val list = mutableListOf<Plan>() if (snapshot != null) { for (document in snapshot) { Logger.d(document.id + " => " + document.data) val plan = document.toObject(Plan::class.java) list.add(plan) } } liveData.value = list } return liveData } override fun getLivePublicPlans(authorList: List<String>): MutableLiveData<List<Plan>> { val liveData = MutableLiveData<List<Plan>>() when (authorList.size) { 0 -> { } else -> { FirebaseFirestore.getInstance() .collection(PATH_PLANS) .whereIn(KEY_AUTHOR_ID, authorList) .whereEqualTo(KEY_PRIVACY, "public") .orderBy(KEY_CREATED_TIME, Query.Direction.DESCENDING) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting plans. ${it.message}") } val list = mutableListOf<Plan>() if (snapshot != null) { for (document in snapshot) { Logger.d(document.id + " => " + document.data) val plan = document.toObject(Plan::class.java) list.add(plan) } } liveData.value = list } } } return liveData } override fun getLiveCollectedPublicPlans(authorList: List<String>): MutableLiveData<List<Plan>> { val liveData = MutableLiveData<List<Plan>>() when (authorList.size) { 0 -> { } else -> { FirebaseFirestore.getInstance() .collection(PATH_PLANS) .whereArrayContainsAny(KEY_COLLECTED, authorList) .whereEqualTo(KEY_PRIVACY, "public") .orderBy(KEY_CREATED_TIME, Query.Direction.DESCENDING) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting plans. ${it.message}") } val list = mutableListOf<Plan>() if (snapshot != null) { for (document in snapshot) { Logger.d(document.id + " => " + document.data) val plan = document.toObject(Plan::class.java) list.add(plan) } } liveData.value = list } } } return liveData } override suspend fun updatePlan(plan: Plan): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_PLANS) .document(plan.id) .set(plan) .addOnSuccessListener { Logger.i("Update: $plan") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error updating plan. ${it.message}") continuation.resume(Result.Error(it)) } } override suspend fun deletePlan(plan: Plan): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_PLANS) .document(plan.id) .delete() .addOnSuccessListener { Logger.i("Delete: $plan") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error deleting plan. ${it.message}") continuation.resume(Result.Error(it)) } } override suspend fun createDay(position: Int, planId: String): Result<Day> = suspendCoroutine { continuation -> val dayRef = FirebaseFirestore.getInstance().collection(PATH_DAYS) val document = dayRef.document() val day = Day( document.id, planId, position = position ) document .set(day) .addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(day)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error creating day. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume(Result.Fail(HowYoApplication.instance.getString(R.string.nothing))) } } } override suspend fun updateDay(day: Day): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_DAYS) .document(day.id) .set(day) .addOnSuccessListener { Logger.i("Update: $day") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error updating day. ${it.message}") continuation.resume(Result.Error(it)) } } override suspend fun deleteDay(day: Day): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_DAYS) .document(day.id) .delete() .addOnSuccessListener { Logger.i("Delete: $day") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error deleting day. ${it.message}") continuation.resume(Result.Error(it)) } } override suspend fun deleteDaysWithBatch(list: List<Day>): Result<Boolean> = suspendCoroutine { continuation -> val db = FirebaseFirestore.getInstance() db.runBatch { batch -> list.forEach { day -> val document = db.collection(PATH_DAYS).document(day.id) batch.delete(document) } }.addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error deleting Days. ${it.message}") continuation.resume(Result.Error(it)) return@let } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override fun getLiveDays(planId: String): MutableLiveData<List<Day>> { val liveData = MutableLiveData<List<Day>>() FirebaseFirestore.getInstance() .collection(PATH_DAYS) .whereEqualTo(KEY_PLAN_ID, planId) .orderBy(KEY_POSITION, Query.Direction.ASCENDING) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting days. ${it.message}") } val list = mutableListOf<Day>() if (snapshot != null) { for (document in snapshot) { Logger.d(document.id + " => " + document.data) val day = document.toObject(Day::class.java) list.add(day) } } liveData.value = list } return liveData } override suspend fun getDays(planId: String): Result<List<Day>> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_DAYS) .whereEqualTo(KEY_PLAN_ID, planId) .orderBy(KEY_POSITION, Query.Direction.ASCENDING) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { val list = mutableListOf<Day>() if (task.result.size() != 0) { for (document in task.result) { Logger.d(document.id + " => " + document.data) val day = document.toObject(Day::class.java) list.add(day) } continuation.resume(Result.Success(list)) } } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error getting days. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume(Result.Fail(HowYoApplication.instance.getString(R.string.nothing))) } } } override suspend fun createSchedule(schedule: Schedule): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_SCHEDULES) .whereEqualTo("day_id", schedule.dayId) .orderBy(KEY_POSITION, Query.Direction.ASCENDING) .get() .addOnCompleteListener { task -> val lastSchedule: Schedule if (task.isSuccessful) { when (task.result.size()) { 0 -> { schedule.position = 0 } else -> { lastSchedule = task.result.last().toObject(Schedule::class.java) schedule.position = lastSchedule.position.plus(1) } } val schedules = FirebaseFirestore.getInstance().collection(PATH_SCHEDULES) val document = schedules.document() schedule.id = document.id document .set(schedule) .addOnCompleteListener { scheduleTask -> if (scheduleTask.isSuccessful) { continuation.resume(Result.Success(true)) } else { scheduleTask.exception?.let { Logger.w("[${this::class.simpleName}] Error creating schedule. ${it.message}") continuation.resume(Result.Error(it)) return@let } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } else { continuation.resume(Result.Success(false)) } } } override suspend fun createScheduleWithBatch(list: List<Schedule>): Result<Boolean> = suspendCoroutine { continuation -> val db = FirebaseFirestore.getInstance() db.runBatch { batch -> list.forEach { schedule -> val document = db.collection(PATH_SCHEDULES).document() schedule.id = document.id batch.set(document, schedule) } }.addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error coping schedule. ${it.message}") continuation.resume(Result.Error(it)) return@let } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override suspend fun updateSchedule(schedule: Schedule): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_SCHEDULES) .document(schedule.id) .set(schedule) .addOnSuccessListener { Logger.i("Update: $schedule") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error updating schedule. ${it.message}") continuation.resume(Result.Error(it)) } } override suspend fun deleteSchedule(schedule: Schedule): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_SCHEDULES) .document(schedule.id) .delete() .addOnSuccessListener { Logger.i("Delete: $schedule") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error deleting schedule. ${it.message}") continuation.resume(Result.Error(it)) } } override suspend fun deleteScheduleWithBatch(list: List<Schedule>): Result<Boolean> = suspendCoroutine { continuation -> val db = FirebaseFirestore.getInstance() db.runBatch { batch -> list.forEach { schedule -> val document = db.collection(PATH_SCHEDULES).document(schedule.id) batch.delete(document) } }.addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error deleting Schedule. ${it.message}") continuation.resume(Result.Error(it)) return@let } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override fun getLiveSchedules(planId: String): MutableLiveData<List<Schedule>> { val liveData = MutableLiveData<List<Schedule>>() FirebaseFirestore.getInstance() .collection(PATH_SCHEDULES) .whereEqualTo(KEY_PLAN_ID, planId) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting schedules. ${it.message}") } val list = mutableListOf<Schedule>() if (snapshot != null) { for (document in snapshot) { val schedule = document.toObject(Schedule::class.java) list.add(schedule) } } liveData.value = list } return liveData } override suspend fun getSchedules(planId: String): Result<List<Schedule>> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_SCHEDULES) .whereEqualTo(KEY_PLAN_ID, planId) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { val list = mutableListOf<Schedule>() if (task.result.size() != 0) { for (document in task.result) { Logger.d(document.id + " => " + document.data) val schedule = document.toObject(Schedule::class.java) list.add(schedule) } continuation.resume(Result.Success(list)) } } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error getting schedules. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume(Result.Fail(HowYoApplication.instance.getString(R.string.nothing))) } } } override suspend fun createCheckShopList(checkShoppingList: CheckShoppingList): Result<Boolean> = suspendCoroutine { continuation -> val mainCheckListRef = FirebaseFirestore.getInstance().collection( PATH_CHECK_SHOPPING_LIST ) val document = mainCheckListRef.document() checkShoppingList.id = document.id document .set(checkShoppingList) .addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error creating main check list. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume(Result.Fail(HowYoApplication.instance.getString(R.string.nothing))) } } } override suspend fun createCheckShopListWithBatch(list: List<CheckShoppingList>): Result<Boolean> = suspendCoroutine { continuation -> val db = FirebaseFirestore.getInstance() db.runBatch { batch -> list.forEach { checkShoppingList -> val document = db.collection(PATH_CHECK_SHOPPING_LIST).document() checkShoppingList.id = document.id batch.set(document, checkShoppingList) } }.addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error creating CheckShopList. ${it.message}") continuation.resume(Result.Error(it)) return@let } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override suspend fun updateCheckShopList(checkShoppingList: CheckShoppingList): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_CHECK_SHOPPING_LIST) .document(checkShoppingList.id) .set(checkShoppingList) .addOnSuccessListener { Logger.i("Update: $checkShoppingList") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error updating schedule. ${it.message}") continuation.resume(Result.Error(it)) } } override suspend fun deleteCheckShopList(checkShoppingList: CheckShoppingList): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_CHECK_SHOPPING_LIST) .document(checkShoppingList.id) .delete() .addOnSuccessListener { Logger.i("Delete: $checkShoppingList") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error deleting checkShoppingList. ${it.message}") continuation.resume(Result.Error(it)) } } override suspend fun deleteCheckShopListWithPlanID(planId: String): Result<Boolean> = suspendCoroutine { continuation -> val firebaseRef = FirebaseFirestore.getInstance() val collectionRef = firebaseRef.collection(PATH_CHECK_SHOPPING_LIST) val deleteResults = mutableListOf<Boolean>() collectionRef.whereEqualTo(KEY_PLAN_ID, planId) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { task.result.forEach { val db = FirebaseFirestore.getInstance() db.runBatch { batch -> val document = db.collection(PATH_CHECK_SHOPPING_LIST).document(it.id) batch.delete(document) }.addOnCompleteListener { subTask -> if (subTask.isSuccessful) { deleteResults.add(true) } else { deleteResults.add(false) } } } continuation.resume( when (!deleteResults.contains(false)) { true -> Result.Success(true) false -> Result.Success(false) } ) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error deleting main check list. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume(Result.Fail(HowYoApplication.instance.getString(R.string.nothing))) } } } override fun getLiveCheckShopList( planId: String, mainType: MainItemType ): MutableLiveData<List<CheckShoppingList>> { val liveData = MutableLiveData<List<CheckShoppingList>>() FirebaseFirestore.getInstance() .collection(PATH_CHECK_SHOPPING_LIST) .whereEqualTo(KEY_PLAN_ID, planId) .whereEqualTo(KEY_MAIN_TYPE, mainType.value) .orderBy(KEY_CREATED_TIME, Query.Direction.ASCENDING) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting comments. ${it.message}") } val list = mutableListOf<CheckShoppingList>() if (snapshot != null) { for (document in snapshot) { Logger.d(document.id + " => " + document.data) val checkShoppingList = document.toObject(CheckShoppingList::class.java) list.add(checkShoppingList) } } liveData.value = list } return liveData } override suspend fun createComment(comment: Comment): Result<Boolean> = suspendCoroutine { continuation -> val comments = FirebaseFirestore.getInstance().collection(PATH_COMMENTS) val document = comments.document() comment.id = document.id document .set(comment) .addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error creating comment. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override suspend fun deleteComment(comment: Comment): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_COMMENTS) .document(comment.id) .delete() .addOnSuccessListener { Logger.i("Delete: $comment") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error deleting comment. ${it.message}") continuation.resume(Result.Error(it)) } } override suspend fun deleteCommentWithBatch(list: List<Comment>): Result<Boolean> = suspendCoroutine { continuation -> val db = FirebaseFirestore.getInstance() db.runBatch { batch -> list.forEach { comment -> val document = db.collection(PATH_COMMENTS).document(comment.id) batch.delete(document) } }.addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error deleting Comment. ${it.message}") continuation.resume(Result.Error(it)) return@let } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override suspend fun getComments(planId: String): Result<List<Comment>> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_COMMENTS) .whereEqualTo(KEY_PLAN_ID, planId) .orderBy(KEY_POSITION, Query.Direction.DESCENDING) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { val list = mutableListOf<Comment>() if (task.result != null) { for (document in task.result) { Logger.d(document.id + " => " + document.data) val comment = document.toObject(Comment::class.java) list.add(comment) } continuation.resume(Result.Success(list)) } } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error getting days. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume(Result.Fail(HowYoApplication.instance.getString(R.string.nothing))) } } } override fun getLiveComments(planId: String): MutableLiveData<List<Comment>> { val liveData = MutableLiveData<List<Comment>>() FirebaseFirestore.getInstance() .collection(PATH_COMMENTS) .whereEqualTo(KEY_PLAN_ID, planId) .orderBy(KEY_CREATED_TIME, Query.Direction.DESCENDING) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting comments. ${it.message}") } val list = mutableListOf<Comment>() if (snapshot != null) { for (document in snapshot) { Logger.d(document.id + " => " + document.data) val comment = document.toObject(Comment::class.java) list.add(comment) } } liveData.value = list } return liveData } override suspend fun createGroupMessage(groupMessage: GroupMessage): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_GROUP_MESSAGE) .document() .set(groupMessage) .addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error creating group message. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override fun getLiveGroupMessages(planId: String): MutableLiveData<List<GroupMessage>> { val liveData = MutableLiveData<List<GroupMessage>>() when (planId.isEmpty()) { true -> { } else -> { FirebaseFirestore.getInstance() .collection(PATH_GROUP_MESSAGE) .whereEqualTo(KEY_PLAN_ID, planId) .orderBy(KEY_CREATED_TIME, Query.Direction.ASCENDING) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener! detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting GroupMessages. ${it.message}") } val list = mutableListOf<GroupMessage>() if (snapshot != null) { for (document in snapshot) { Logger.d(document.id + " => " + document.data) val groupMessage = document.toObject(GroupMessage::class.java) list.add(groupMessage) } } liveData.value = list } } } return liveData } override suspend fun createNotification(notification: Notification): Result<Boolean> = suspendCoroutine { continuation -> val notifications = FirebaseFirestore.getInstance().collection(PATH_NOTIFICATION) val document = notifications.document() notification.id = document.id document .set(notification) .addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error creating notification. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override fun getLiveNotifications(): MutableLiveData<List<Notification>> { val liveData = MutableLiveData<List<Notification>>() FirebaseFirestore.getInstance() .collection(PATH_NOTIFICATION) .whereEqualTo(KEY_TO_USER_ID, UserManager.userId) .orderBy(KEY_CREATED_TIME, Query.Direction.DESCENDING) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting Notifications. ${it.message}") } val list = mutableListOf<Notification>() if (snapshot != null) { for (document in snapshot) { Logger.d(document.id + " => " + document.data) val notification = document.toObject(Notification::class.java) list.add(notification) } } liveData.value = list } return liveData } override suspend fun updateNotificationWithBatch(list: List<Notification>): Result<Boolean> = suspendCoroutine { continuation -> val db = FirebaseFirestore.getInstance() db.runBatch { batch -> list.forEach { notification -> val document = db.collection(PATH_NOTIFICATION).document(notification.id) batch.set(document, notification) } }.addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error updating Notifications. ${it.message}") continuation.resume(Result.Error(it)) return@let } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override suspend fun deleteFollowNotification( toUserId: String, fromUserId: String ): Result<Boolean> = suspendCoroutine { continuation -> val deleteResults = mutableListOf<Boolean>() FirebaseFirestore.getInstance() .collection(PATH_NOTIFICATION) .whereEqualTo(KEY_FROM_USER_ID, fromUserId) .whereEqualTo(KEY_TO_USER_ID, toUserId) .whereEqualTo(KEY_NOTIFICATION_TYPE, NotificationType.FOLLOW.type) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { if (task.result.size() != 0) { task.result.forEach { val db = FirebaseFirestore.getInstance() db.runBatch { batch -> val document = db.collection(PATH_NOTIFICATION).document(it.id) batch.delete(document) }.addOnCompleteListener { subTask -> if (subTask.isSuccessful) { deleteResults.add(true) } else { deleteResults.add(false) } } } } continuation.resume( when (!deleteResults.contains(false)) { true -> Result.Success(true) false -> Result.Success(false) } ) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error deleting notifications. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume(Result.Fail(HowYoApplication.instance.getString(R.string.nothing))) } } } override suspend fun createPayment(payment: Payment): Result<Boolean> = suspendCoroutine { continuation -> val payments = FirebaseFirestore.getInstance().collection(PATH_PAYMENT) val document = payments.document() payment.id = document.id document .set(payment) .addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(true)) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error creating payment. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume( Result.Fail(HowYoApplication.instance.getString(R.string.nothing)) ) } } } override suspend fun deletePayment(payment: Payment): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_PAYMENT) .document(payment.id) .delete() .addOnSuccessListener { Logger.i("Delete: $payment") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error deleting payment. ${it.message}") continuation.resume(Result.Error(it)) } } override suspend fun updatePayment(payment: Payment): Result<Boolean> = suspendCoroutine { continuation -> FirebaseFirestore.getInstance() .collection(PATH_PAYMENT) .document(payment.id) .set(payment) .addOnSuccessListener { Logger.i("Update: $payment") continuation.resume(Result.Success(true)) }.addOnFailureListener { Logger.w("[${this::class.simpleName}] Error updating payment. ${it.message}") continuation.resume(Result.Error(it)) } } override fun getLivePayments(planId: String): MutableLiveData<List<Payment>> { val liveData = MutableLiveData<List<Payment>>() FirebaseFirestore.getInstance() .collection(PATH_PAYMENT) .whereEqualTo(KEY_PLAN_ID, planId) .orderBy(KEY_CREATED_TIME, Query.Direction.DESCENDING) .addSnapshotListener { snapshot, exception -> Logger.i("addSnapshotListener detect") exception?.let { Logger.w("[${this::class.simpleName}] Error getting payments. ${it.message}") } val list = mutableListOf<Payment>() if (snapshot != null) { for (document in snapshot) { Logger.d(document.id + " => " + document.data) val day = document.toObject(Payment::class.java) list.add(day) } } liveData.value = list } return liveData } override suspend fun deleteDataListsWithPlanID( planId: String, type: DeleteDataType ): Result<Boolean> = suspendCoroutine { continuation -> val collectionName = when (type) { DeleteDataType.DAYS -> PATH_DAYS DeleteDataType.SCHEDULES -> PATH_SCHEDULES DeleteDataType.COMMENTS -> PATH_COMMENTS DeleteDataType.CHECK_SHOP_LIST -> PATH_CHECK_SHOPPING_LIST DeleteDataType.GROUP_MSG -> PATH_GROUP_MESSAGE DeleteDataType.NOTIFICATION -> PATH_NOTIFICATION DeleteDataType.PAYMENT -> PATH_PAYMENT } val firebaseRef = FirebaseFirestore.getInstance() val collectionRef = firebaseRef.collection(collectionName) val deleteResults = mutableListOf<Boolean>() collectionRef.whereEqualTo(KEY_PLAN_ID, planId) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { if (task.result.size() != 0) { task.result.forEach { val db = FirebaseFirestore.getInstance() db.runBatch { batch -> val document = db.collection(collectionName).document(it.id) batch.delete(document) }.addOnCompleteListener { subTask -> if (subTask.isSuccessful) { deleteResults.add(true) } else { deleteResults.add(false) } } } } continuation.resume( when (!deleteResults.contains(false)) { true -> Result.Success(true) false -> Result.Success(false) } ) } else { task.exception?.let { Logger.w("[${this::class.simpleName}] Error deleting group messages. ${it.message}") continuation.resume(Result.Error(it)) return@addOnCompleteListener } continuation.resume(Result.Fail(HowYoApplication.instance.getString(R.string.nothing))) } } } }
0
Kotlin
0
0
b63a8c79f881923bb049ada5081fdde63280639f
67,336
HowYo
MIT License
src/main/kotlin/days/Day15.kt
TheMrMilchmann
571,779,671
false
null
/* * Copyright (c) 2022 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package days import utils.* import kotlin.math.* fun main() { data class Point(val x: Long, val y: Long) { infix fun distanceTo(other: Point): Long = (abs(x - other.x) + abs(y - other.y)) } data class Line(val a: Point, val b: Point) { infix fun intersect(other: Line): Point? { val abX = a.x - b.x val abY = a.y - b.y val acX = a.x - other.a.x val acY = a.y - other.a.y val cdX = other.a.x - other.b.x val cdY = other.a.y - other.b.y val t = (acX.toDouble() * cdY - acY * cdX) / (abX * cdY - abY * cdX) val u = (acX.toDouble() * abY - acY * abX) / (abX * cdY - abY * cdX) if (t < 0 || 1 < t || u < 0 || 1 < u) return null return Point( x = (a.x + t * (b.x - a.x)).toLong(), y = (a.y + t * (b.y - a.y)).toLong() ) } } data class ScanArea( val center: Point, val beacon: Point, val range: Long = center distanceTo beacon ) { fun getScansOnRow(row: Long): LongRange { val verticalDistance = abs(center.y - row) if (verticalDistance > range) return LongRange.EMPTY val horizontalDistance = range - verticalDistance return (center.x - horizontalDistance)..(center.x + horizontalDistance) } } val data = readInput().map { val (sX, sY, bX, bY) = """(-)?\d+""".toRegex().findAll(it).take(4).toList() Point(sX.value.toLong(), sY.value.toLong()) to Point(bX.value.toLong(), bY.value.toLong()) } val scanAreas = data.map { (sensor, beacon) -> ScanArea(sensor, beacon) } fun part1(): Int { val row = 2_000_000L val beacons = scanAreas.mapNotNull { if (it.beacon.y == row) it.beacon.x else null }.toSet() return scanAreas.flatMap { it.getScansOnRow(row) }.filter { it !in beacons }.toSet().size } fun part2(): Long { val space = 4_000_000L val lines = sequence { yield(Line(Point(0, 0), Point(space, 0))) yield(Line(Point(0, 0), Point(0, space))) yield(Line(Point(space, 0), Point(space, space))) yield(Line(Point(0, space), Point(space, space))) scanAreas.forEach { val t = it.center.copy(y = it.center.y - it.range - 1) val b = it.center.copy(y = it.center.y + it.range + 1) val l = it.center.copy(x = it.center.x - it.range - 1) val r = it.center.copy(x = it.center.x + it.range + 1) yield(Line(t, r)) yield(Line(r, b)) yield(Line(b, l)) yield(Line(l, t)) } } val (x, y) = lines.flatMap { a -> lines.mapNotNull { b -> a intersect b } } .filter { (x, y) -> x in 0..space && y in 0..space } .first { p -> scanAreas.none { it.center distanceTo p <= it.range } } return (x * space) + y } println("Part 1: ${part1()}") println("Part 2: ${part2()}") }
0
Kotlin
0
3
2e01ab62e44d965a626198127699720563ed934b
4,213
AdventOfCode2022
MIT License
lib/src/main/kotlin/bstrees/model/dataBases/serialize/strategies/AvlStrategy.kt
spbu-coding-2022
617,202,886
false
null
package bstrees.model.dataBases.serialize.strategies import bstrees.model.dataBases.serialize.SerializeStrategy import bstrees.model.dataBases.serialize.types.SerializableNode import bstrees.model.dataBases.serialize.types.SerializableTree import bstrees.model.trees.avl.AvlNode import bstrees.model.trees.avl.AvlTree class AvlStrategy<K : Comparable<K>, V>( serializeKey: (K) -> String, serializeValue: (V) -> String, deserializeKey: (String) -> K, deserializeValue: (String) -> V ) : SerializeStrategy<K, V, Int, AvlNode<K, V>, AvlTree<K, V>>( serializeKey, serializeValue, deserializeKey, deserializeValue ) { override fun serializeNode(node: AvlNode<K, V>): SerializableNode = SerializableNode( serializeKey(node.key), serializeValue(node.value), serializeMetadata(node.height), node.leftNode?.let { serializeNode(it) }, node.rightNode?.let { serializeNode(it) } ) override fun deserializeNode(node: SerializableNode): AvlNode<K, V> { val avlnode: AvlNode<K, V> = AvlNode(deserializeKey(node.key), deserializeValue(node.value)) if (node.metadata[0] != 'H') throw Exception("Wrong metadata. Impossible to deserialize") avlnode.height = deserializeMetadata(node.metadata) node.leftNode?.let { deserializeNode(it) } node.rightNode?.let { deserializeNode(it) } linkParents(avlnode) return avlnode } override fun serializeTree(tree: AvlTree<K, V>, treeName: String) = SerializableTree( name = treeName, treeType = "AVL", root = tree.root?.let { serializeNode(it) } ) override fun deserializeTree(tree: SerializableTree): AvlTree<K, V> { if (tree.treeType != "AVL") throw Exception("Wrong tree type. Impossible to deserialize") val avltree = AvlTree<K, V>() avltree.root = tree.root?.let { deserializeNode(it) } return avltree } override fun serializeMetadata(meta: Int) = "H$meta" override fun deserializeMetadata(meta: String) = meta.substring(1).toInt() }
1
Kotlin
1
4
512967517f7223b500e20db3aad6f1fbfe790887
2,088
trees-6
Apache License 2.0
buildata-runtime/src/commonMain/kotlin/io/github/virelion/buildata/access/DynamicAccessor.kt
Virelion
330,246,253
false
null
/* * Copyright 2021 <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.github.virelion.buildata.access import io.github.virelion.buildata.Builder import io.github.virelion.buildata.path.IntIndexPathIdentifier import io.github.virelion.buildata.path.PathIdentifier import io.github.virelion.buildata.path.RecordedPath import io.github.virelion.buildata.path.StringIndexPathIdentifier import io.github.virelion.buildata.path.StringNamePathIdentifier /** * Marker for code-generated class dynamic elements access. */ class DynamicAccessor(private val builder: Builder<*>) { @Throws(ElementNotFoundException::class) operator fun <R> get(path: String): R? { return get(*RecordedPath.Parser.parse(path).path.toTypedArray()) } @Throws(ElementNotFoundException::class) operator fun <R> get(vararg path: PathIdentifier): R? { if (path.isEmpty()) return builder.build() as R val element: PathAccessProcessingAccumulator = path .fold(PathAccessProcessingAccumulator(builder, listOf())) { acc, pathIdentifier -> resolvePathIdentifier(pathIdentifier, acc) } if (element.item is Builder<*>) { return element.item.build() as R } return element.item as R } private data class PathAccessProcessingAccumulator( val item: Any?, val pathProcessed: List<PathIdentifier> ) private fun resolvePathIdentifier( pathElement: PathIdentifier, acc: PathAccessProcessingAccumulator ): PathAccessProcessingAccumulator { return try { when (pathElement) { is IntIndexPathIdentifier -> resolveIntIndexPathIdentifier(pathElement, acc) is StringIndexPathIdentifier -> resolveStringIndexPathIdentifier(pathElement, acc) is StringNamePathIdentifier -> resolveStringNamePathIdentifier(pathElement, acc) } } catch (e: Exception) { handleException(e, pathElement, acc) } } private fun resolveIntIndexPathIdentifier( pathElement: IntIndexPathIdentifier, acc: PathAccessProcessingAccumulator ): PathAccessProcessingAccumulator { return when (acc.item) { is List<*> -> { // additional check for KotlinJS if (pathElement.index >= acc.item.size) throw IndexOutOfBoundsException() acc.item[pathElement.index] } is Array<*> -> { // additional check for KotlinJS if (pathElement.index >= acc.item.size) throw IndexOutOfBoundsException() acc.item[pathElement.index] } is Map<*, *> -> { if (pathElement.index !in acc.item) throw IndexOutOfBoundsException() acc.item[pathElement.index] } is IntAccessible -> acc.item.accessElement(pathElement.index) else -> throw ElementNotFoundException( pathProcessed = RecordedPath(acc.pathProcessed), lastItemProcessed = acc.item, lastProcessedPathIdentifier = pathElement ) }.let { PathAccessProcessingAccumulator(it, acc.pathProcessed + pathElement) } } private fun resolveStringIndexPathIdentifier( pathElement: StringIndexPathIdentifier, acc: PathAccessProcessingAccumulator ): PathAccessProcessingAccumulator { return when (acc.item) { is Map<*, *> -> { if (pathElement.index !in acc.item) throw IndexOutOfBoundsException() acc.item[pathElement.index] } is StringAccessible -> acc.item.accessElement(pathElement.index) else -> throw ElementNotFoundException( pathProcessed = RecordedPath(acc.pathProcessed), lastItemProcessed = acc.item, lastProcessedPathIdentifier = pathElement ) }.let { PathAccessProcessingAccumulator(it, acc.pathProcessed + pathElement) } } private fun resolveStringNamePathIdentifier( pathElement: StringNamePathIdentifier, acc: PathAccessProcessingAccumulator ): PathAccessProcessingAccumulator { if (acc.item !is StringAccessible) { throw ElementNotFoundException( pathProcessed = RecordedPath(acc.pathProcessed), lastItemProcessed = acc.item, lastProcessedPathIdentifier = pathElement ) } return acc.item.accessElement(pathElement.name) .let { PathAccessProcessingAccumulator(it, acc.pathProcessed + pathElement) } } private fun handleException( e: Exception, pathElement: PathIdentifier, acc: PathAccessProcessingAccumulator ): Nothing { when (e) { is MissingPropertyException, is IndexOutOfBoundsException -> { val item = if (acc.item is Builder<*>) { acc.item.build() } else { acc.item } throw ElementNotFoundException( pathProcessed = RecordedPath(acc.pathProcessed), lastItemProcessed = item, lastProcessedPathIdentifier = pathElement ) } else -> throw e } } }
22
Kotlin
0
11
e5fb247e29213e95653008a68f5bcadae71ea6c5
5,904
buildata
Apache License 2.0
app/src/main/java/com/antonbermes/instagramapiexample/ui/details/DetailsFragment.kt
AntonBermes
212,747,185
false
null
package com.antonbermes.instagramapiexample.ui.details import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.antonbermes.instagramapiexample.R import com.antonbermes.instagramapiexample.database.ImagesDatabase import com.antonbermes.instagramapiexample.databinding.FragmentDetailsBinding import com.antonbermes.instagramapiexample.repository.Status import com.antonbermes.instagramapiexample.ui.MyFragment class DetailsFragment : MyFragment() { private val dataSource by lazy { ImagesDatabase.getInstance(application).imagesDao } private val token by lazy { arguments?.let { DetailsFragmentArgs.fromBundle(it).token } ?: "" } private val imageId by lazy { arguments?.let { DetailsFragmentArgs.fromBundle(it).imageId } ?: "" } private val viewModelFactory by lazy { DetailsViewModelFactory(dataSource, token, imageId) } private val viewModel by lazy { ViewModelProviders.of(this, viewModelFactory).get(DetailsViewModel::class.java) } private lateinit var binding: FragmentDetailsBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_details, container, false) binding.lifecycleOwner = viewLifecycleOwner binding.viewModel = viewModel binding.swipeRefreshLayout.setOnRefreshListener { viewModel.refresh() } viewModel.status.observe(viewLifecycleOwner, Observer { it?.let { when(it) { is Status.StartLoading -> { binding.swipeRefreshLayout.isRefreshing = true dismissSnackbar() } is Status.StopLoading -> { binding.swipeRefreshLayout.isRefreshing = false } is Status.Error -> { binding.swipeRefreshLayout.isRefreshing = false showSnackbar(it.error, binding.coordinatorLayout) } } } }) return binding.root } override fun snackbarAction() { viewModel.refresh() } }
0
Kotlin
0
0
d6063ecd5ddc4ca94f00c022b2eb2575679c800f
2,458
InstagramApiExample
Apache License 2.0
app/src/main/java/com/github/jokar/zhihudaily/model/event/SettingModel.kt
MichaelJokAr
94,307,617
false
null
package com.github.jokar.zhihudaily.model.event import android.arch.lifecycle.Lifecycle import android.arch.lifecycle.LifecycleOwner import android.support.annotation.NonNull import android.support.v7.app.AppCompatActivity import android.text.format.Formatter import com.bumptech.glide.load.engine.cache.DiskCache import com.github.jokar.zhihudaily.model.event.callback.SingleDataCallBack import com.github.jokar.zhihudaily.utils.image.ImageLoader import com.trello.rxlifecycle2.android.lifecycle.kotlin.bindUntilEvent import io.reactivex.Flowable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.io.File /** * Created by JokAr on 2017/7/4. */ class SettingModel(var activity: AppCompatActivity) { /** * 清除图片缓存 */ fun clearImageCache(@NonNull callBack: SingleDataCallBack<String>) { Flowable.just("") .observeOn(Schedulers.newThread()) .unsubscribeOn(Schedulers.newThread()) .bindUntilEvent(activity, Lifecycle.Event.ON_DESTROY) .map { //清除图片缓存 ImageLoader.clearDiskCache(activity.applicationContext) val file = File(activity.applicationContext.cacheDir, DiskCache.Factory.DEFAULT_DISK_CACHE_DIR) val size = calculateSize(file) return@map Formatter.formatFileSize(activity.applicationContext, size) } .observeOn(AndroidSchedulers.mainThread()) .subscribe { s -> callBack.data("$s") } } /** * 获取图片缓存 */ fun getImageCacheSize(@NonNull lifecycle: LifecycleOwner, @NonNull callBack: SingleDataCallBack<String>) { val file = File(activity.applicationContext.cacheDir, DiskCache.Factory.DEFAULT_DISK_CACHE_DIR) Flowable.just(file) .subscribeOn(Schedulers.computation()) .bindUntilEvent(lifecycle, Lifecycle.Event.ON_DESTROY) .unsubscribeOn(Schedulers.computation()) .map { file1 -> calculateSize(file1) } .map<Any> { size -> Formatter.formatFileSize(activity.applicationContext, size) } .observeOn(AndroidSchedulers.mainThread()) .subscribe { s -> callBack.data("$s") } } fun calculateSize(dir: File?): Long { if (dir == null) { return 0 } if (!dir.isDirectory) return dir.length() var result: Long = 0 val children = dir.listFiles() if (children != null) for (child in children) result += calculateSize(child) return result } }
4
Kotlin
15
97
0dbe6181fea8f45b161ead2392e0e3d1c620959f
2,759
ZhihuDaily
Apache License 2.0
src/main/kotlin/no/nav/k9brukerdialogprosessering/common/Ytelse.kt
navikt
585,578,757
false
null
package no.nav.k9brukerdialogprosessering.common import no.nav.k9brukerdialogprosessering.meldinger.endringsmelding.PSBEndringsmeldingTopologyConfiguration.Companion.PSB_ENDRINGSMELDING_CLEANUP_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.endringsmelding.PSBEndringsmeldingTopologyConfiguration.Companion.PSB_ENDRINGSMELDING_MOTTATT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.endringsmelding.PSBEndringsmeldingTopologyConfiguration.Companion.PSB_ENDRINGSMELDING_PREPROSESSERT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.ettersendelse.EttersendelseTopologyConfiguration.Companion.ETTERSENDELSE_CLEANUP_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.ettersendelse.EttersendelseTopologyConfiguration.Companion.ETTERSENDELSE_MOTTATT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.ettersendelse.EttersendelseTopologyConfiguration.Companion.ETTERSENDELSE_PREPROSESSERT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgpengerutbetalingat.OMPUtbetalingATTopologyConfiguration.Companion.OMP_UTB_AT_CLEANUP_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgpengerutbetalingat.OMPUtbetalingATTopologyConfiguration.Companion.OMP_UTB_AT_MOTTATT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgpengerutbetalingat.OMPUtbetalingATTopologyConfiguration.Companion.OMP_UTB_AT_PREPROSESSERT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgpengerutbetalingsnf.OMPUtbetalingSNFTopologyConfiguration.Companion.OMP_UTB_SNF_CLEANUP_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgpengerutbetalingsnf.OMPUtbetalingSNFTopologyConfiguration.Companion.OMP_UTB_SNF_MOTTATT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgpengerutbetalingsnf.OMPUtbetalingSNFTopologyConfiguration.Companion.OMP_UTB_SNF_PREPROSESSERT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgspengeraleneomsorg.OMPAleneomsorgTopologyConfiguration.Companion.OMP_AO_CLEANUP_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgspengeraleneomsorg.OMPAleneomsorgTopologyConfiguration.Companion.OMP_AO_MOTTATT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgspengeraleneomsorg.OMPAleneomsorgTopologyConfiguration.Companion.OMP_AO_PREPROSESSERT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgspengerkronisksyktbarn.OMPKSTopologyConfiguration.Companion.OMP_UTV_KS_SØKNAD_CLEANUP_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgspengerkronisksyktbarn.OMPKSTopologyConfiguration.Companion.OMP_UTV_KS_SØKNAD_MOTTATT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgspengerkronisksyktbarn.OMPKSTopologyConfiguration.Companion.OMP_UTV_KS_SØKNAD_PREPROSESSERT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgspengermidlertidigalene.OMPMidlertidigAleneTopologyConfiguration.Companion.OMP_MA_CLEANUP_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgspengermidlertidigalene.OMPMidlertidigAleneTopologyConfiguration.Companion.OMP_MA_MOTTATT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.omsorgspengermidlertidigalene.OMPMidlertidigAleneTopologyConfiguration.Companion.OMP_MA_PREPROSESSERT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.pleiepengerilivetsslutttfase.PILSTopologyConfiguration.Companion.PILS_CLEANUP_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.pleiepengerilivetsslutttfase.PILSTopologyConfiguration.Companion.PILS_MOTTATT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.pleiepengerilivetsslutttfase.PILSTopologyConfiguration.Companion.PILS_PREPROSESSERT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.pleiepengersyktbarn.PSBTopologyConfiguration.Companion.PSB_CLEANUP_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.pleiepengersyktbarn.PSBTopologyConfiguration.Companion.PSB_MOTTATT_TOPIC import no.nav.k9brukerdialogprosessering.meldinger.pleiepengersyktbarn.PSBTopologyConfiguration.Companion.PSB_PREPROSESSERT_TOPIC enum class Ytelse(val tittel: String) { OMSORGSPENGER_UTVIDET_RETT("Søknad om ekstra omsorgsdager for barn som har kronisk/langvarig sykdom eller funksjonshemning"), OMSORGSPENGER_MIDLERTIDIG_ALENE("Søknad om ekstra omsorgsdager når den andre forelderen ikke kan ha tilsyn med barn"), ETTERSENDELSE("Ettersendelse av dokumentasjon"), OMSORGSDAGER_ALENEOMSORG("Søknad om ekstra omsorgsdager ved aleneomsorg"), OMSORGSPENGER_UTBETALING_ARBEIDSTAKER("Søknad om utbetaling av omsorgspenger når arbeidsgiver ikke utbetaler"), OMSORGSPENGER_UTBETALING_SNF("Søknad om utbetaling av omsorgspenger for selvstendig næringsdrivende og frilansere"), PLEIEPENGER_LIVETS_SLUTTFASE("Søknad om pleiepenger i livets sluttfase"), PLEIEPENGER_SYKT_BARN("Søknad om pleiepenger for sykt barn"), PLEIEPENGER_SYKT_BARN_ENDRINGSMELDING("Endringsmelding for pleiepenger sykt barn"); companion object { fun fraTopic(topic: String): Ytelse = when (topic) { PSB_MOTTATT_TOPIC, PSB_PREPROSESSERT_TOPIC, PSB_CLEANUP_TOPIC -> PLEIEPENGER_SYKT_BARN PSB_ENDRINGSMELDING_MOTTATT_TOPIC, PSB_ENDRINGSMELDING_PREPROSESSERT_TOPIC, PSB_ENDRINGSMELDING_CLEANUP_TOPIC -> PLEIEPENGER_SYKT_BARN_ENDRINGSMELDING ETTERSENDELSE_MOTTATT_TOPIC, ETTERSENDELSE_PREPROSESSERT_TOPIC, ETTERSENDELSE_CLEANUP_TOPIC -> ETTERSENDELSE OMP_UTV_KS_SØKNAD_MOTTATT_TOPIC, OMP_UTV_KS_SØKNAD_PREPROSESSERT_TOPIC, OMP_UTV_KS_SØKNAD_CLEANUP_TOPIC -> OMSORGSPENGER_UTVIDET_RETT PILS_MOTTATT_TOPIC, PILS_PREPROSESSERT_TOPIC, PILS_CLEANUP_TOPIC -> PLEIEPENGER_LIVETS_SLUTTFASE OMP_UTB_AT_MOTTATT_TOPIC, OMP_UTB_AT_PREPROSESSERT_TOPIC, OMP_UTB_AT_CLEANUP_TOPIC -> OMSORGSPENGER_UTBETALING_ARBEIDSTAKER OMP_UTB_SNF_MOTTATT_TOPIC, OMP_UTB_SNF_PREPROSESSERT_TOPIC, OMP_UTB_SNF_CLEANUP_TOPIC -> OMSORGSPENGER_UTBETALING_SNF OMP_MA_MOTTATT_TOPIC, OMP_MA_PREPROSESSERT_TOPIC, OMP_MA_CLEANUP_TOPIC -> OMSORGSPENGER_MIDLERTIDIG_ALENE OMP_AO_MOTTATT_TOPIC, OMP_AO_PREPROSESSERT_TOPIC, OMP_AO_CLEANUP_TOPIC -> OMSORGSDAGER_ALENEOMSORG else -> { throw IllegalArgumentException("Kan ikke finne ytelse for topic: $topic") } } } }
3
Kotlin
0
0
e7e0038c71f6291447bcb4c0088d27dd464faf0a
6,237
k9-brukerdialog-prosessering
MIT License
app/src/main/java/com/hudson/wanandroid/ui/fragment/setting/DefaultSettingFragment.kt
HudsonAndroid
278,809,991
false
null
package com.hudson.wanandroid.ui.fragment.setting import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.activityViewModels import androidx.lifecycle.ViewModelProvider import androidx.navigation.Navigation import com.google.gson.Gson import com.hudson.wanandroid.R import com.hudson.wanandroid.data.common.WanAndroidConfig import com.hudson.wanandroid.data.common.fromJson import com.hudson.wanandroid.data.entity.baiduEngine import com.hudson.wanandroid.databinding.FragmentDefaultSettingBinding import com.hudson.wanandroid.databinding.FragmentSearchDefaultBinding import com.hudson.wanandroid.di.Injectable import com.hudson.wanandroid.ui.util.autoCleared import com.hudson.wanandroid.viewmodel.SearchModel import com.hudson.wanandroid.viewmodel.SettingModel import javax.inject.Inject class DefaultSettingFragment : Fragment(), Injectable { private var binding by autoCleared<FragmentDefaultSettingBinding>() @Inject lateinit var viewModelFactory : ViewModelProvider.Factory private val settingModel: SettingModel by activityViewModels { viewModelFactory } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentDefaultSettingBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.engine = settingModel.searchEngine val string = WanAndroidConfig(requireContext()).getString( WanAndroidConfig.COMMON_BROWSER_SEARCH_TOOL, null ) val engine = if(string != null) Gson().fromJson(string) else baiduEngine settingModel.searchEngine.value = engine binding.lifecycleOwner = this binding.tvBrowserContent.setOnClickListener { Navigation.findNavController(binding.root) .navigate(DefaultSettingFragmentDirections .actionDefaultSettingFragmentToSearchSelectFragment()) } } }
1
Kotlin
1
0
4c0a43cf0fc4cb6d8c4b30a79f5e5301aff7a2d8
2,238
WanAndroidJetpack
Apache License 2.0
app/src/main/java/de/cleema/android/MainActivity.kt
sandstorm
840,235,083
false
{"Kotlin": 955115, "Ruby": 1773}
/* * Created by Kumpels and Friends on 2023-01-17 * Copyright © 2023 Kumpels and Friends. All rights reserved. */ package de.cleema.android import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.core.view.WindowCompat.setDecorFitsSystemWindows import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navDeepLink import com.google.accompanist.systemuicontroller.rememberSystemUiController import dagger.hilt.android.AndroidEntryPoint import de.cleema.android.core.data.UserRepository import de.cleema.android.core.models.DeepLinking import de.cleema.android.core.styling.CleemaTheme import de.cleema.android.login.LoginScreen import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) applyDebugSettings() setDecorFitsSystemWindows(window, false) setContent { // Update the system bars to be translucent val systemUiController = rememberSystemUiController() SideEffect { systemUiController.setSystemBarsColor(Color.Transparent, darkIcons = false) systemUiController.setNavigationBarColor(Color.Transparent) } CleemaTheme { NavHost(navController = rememberNavController(), "login") { composable( "login", deepLinks = listOf( navDeepLink { uriPattern = "${BuildConfig.apiUrl}/${DeepLinking.accountConfirmation}?confirmation={${DeepLinking.confirmationCode}}" }, navDeepLink { uriPattern = "${BuildConfig.baseUrl}/invites/{${DeepLinking.invitationCode}}" }) ) { LoginScreen(modifier = Modifier.padding(0.dp)) } } } } } @Inject lateinit var userRepository: UserRepository private fun applyDebugSettings() { if (BuildConfig.DEBUG) { intent.extras?.getBoolean("wipeuser")?.let { wipeUser -> if (wipeUser) { CoroutineScope(Dispatchers.IO).launch { userRepository.deleteUser() } } } } } } @ExperimentalMaterial3Api @Preview(showBackground = true) @Composable fun DefaultPreview() { CleemaTheme { App() } }
0
Kotlin
0
1
ddcb7ddedbbefb8045e7299e14a2ad47329fc53e
3,320
cleema-android
MIT License
app/src/main/java/com/example/kotlin_mvvm_clean_architecture_demo/presentation/viewmodel/tvshow/TVShowViewModelFactory.kt
caramelWaffle
291,373,142
false
null
package com.example.kotlin_mvvm_clean_architecture_demo.presentation.viewmodel.tvshow import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.kotlin_mvvm_clean_architecture_demo.domain.usecase.TVShowUseCase class TVShowViewModelFactory(private val tvShowUseCase: TVShowUseCase): ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(TVShowViewModel::class.java)){ return TVShowViewModel( tvShowUseCase ) as T } throw IllegalArgumentException() } }
0
Kotlin
0
0
d8b8ac5f828e0f3fccb418b142a8d06eda87f135
634
Kotlin-MVVM-Clean-Architecture-Demo
MIT License
app/src/main/java/fi/kroon/vadret/presentation/warning/display/model/ElapsedTime.kt
marvinmosa
241,497,201
true
{"Kotlin": 871560}
package fi.kroon.vadret.presentation.warning.display.model data class ElapsedTime( val diffInMillis: Long, val resId: Int )
0
null
0
0
f8149920c34bb3bc5e3148785ce217e37e596fbe
132
android
Apache License 2.0
app/src/main/java/com/wolkowiczmateusz/securitysocialoffline/extentions/ActivityExtentions.kt
MateuszWolkowicz
200,810,450
false
null
package com.wolkowiczmateusz.securitysocialoffline.extentions import android.app.Activity import android.content.Intent import android.opengl.Visibility import android.view.View import com.wolkowiczmateusz.securitysocialoffline.HomeActivity import com.wolkowiczmateusz.securitysocialoffline.SecretActivity import com.wolkowiczmateusz.securitysocialoffline.SignInActivity import com.wolkowiczmateusz.securitysocialoffline.SignUpActivity import com.wolkowiczmateusz.securitysocialoffline.Storage fun Activity.startSecretActivity(requestCode: Int, mode: Int = SecretActivity.MODE_CREATE, password: String? = null, secretData: Storage.SecretData? = null) { val intent = Intent(this, SecretActivity::class.java) intent.putExtra("mode", mode) password?.let { intent.putExtra("password", password) } secretData?.let { intent.putExtra("secret", secretData) } startActivityForResult(intent, requestCode) } fun Activity.startHomeActivity(finishCallingActivity: Boolean = true) = startActivity(HomeActivity::class.java, finishCallingActivity) fun Activity.startSignUpActivity(finishCallingActivity: Boolean = true) = startActivity(SignUpActivity::class.java, finishCallingActivity) fun Activity.startSignInActivity(finishCallingActivity: Boolean = true) = startActivity(SignInActivity::class.java, finishCallingActivity) private fun Activity.startActivity(cls: Class<*>, finishCallingActivity: Boolean = true) { val intent = Intent(this, cls) startActivity(intent) finishCallingActivity.let { finish() } }
0
Kotlin
0
2
199d6293859a2940296a166d59c3fd4a6c57d9da
1,532
security-social-offline
Apache License 2.0
amazon/sns/fake/src/main/kotlin/org/http4k/connect/amazon/sns/FakeSNS.kt
http4k
295,641,058
false
{"Kotlin": 1624429, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675}
package org.http4k.connect.amazon.sns import org.http4k.aws.AwsCredentials import org.http4k.chaos.ChaoticHttpHandler import org.http4k.chaos.start import org.http4k.connect.amazon.core.model.AwsAccount import org.http4k.connect.amazon.core.model.Region import org.http4k.connect.amazon.sns.model.MessageAttribute import org.http4k.connect.storage.InMemory import org.http4k.connect.storage.Storage import org.http4k.core.Method.POST import org.http4k.routing.bind import org.http4k.routing.routes class FakeSNS( topics: Storage<List<SNSMessage>> = Storage.InMemory(), awsAccount: AwsAccount = AwsAccount.of("1234567890"), private val region: Region = Region.of("ldn-north-1"), ) : ChaoticHttpHandler() { override val app = routes( "/" bind POST to routes( createTopic(topics, awsAccount, region), deleteTopic(topics, awsAccount, region), listTopics(topics, awsAccount, region), publish(topics, awsAccount, region), publishBatch(topics, awsAccount, region) ) ) /** * Convenience function to get a SNS client */ fun client() = SNS.Http(region, { AwsCredentials("accessKey", "secret") }, this) } data class SNSMessage(val message: String, val subject: String?, val attributes: List<MessageAttribute>) fun main() { FakeSNS().start() }
7
Kotlin
17
37
94e71e6bba87d9c79ac29f7ba23bdacd0fdf354c
1,356
http4k-connect
Apache License 2.0
IronTracker/app/src/main/java/com/example/irontracker/ui/scoreboard/ScoreboardAdapter.kt
zhenyuanlu
796,742,557
false
{"Kotlin": 31011}
package com.example.irontracker.ui.scoreboard import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.irontracker.R class ScoreboardAdapter(private val scoreboardList: List<ScoreboardItem>) : RecyclerView.Adapter<ScoreboardAdapter.ScoreboardViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ScoreboardViewHolder { val itemView = LayoutInflater.from(parent.context) .inflate(R.layout.item_scoreboard, parent, false) return ScoreboardViewHolder(itemView) } override fun onBindViewHolder(holder: ScoreboardViewHolder, position: Int) { val currentItem = scoreboardList[position] holder.userNameTextView.text = currentItem.userName holder.userScoreTextView.text = currentItem.userScore.toString() holder.userRankTextView.text = (position + 1).toString() // Set the ranking number } override fun getItemCount(): Int { return scoreboardList.size } class ScoreboardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val userNameTextView: TextView = itemView.findViewById(R.id.user_name) val userScoreTextView: TextView = itemView.findViewById(R.id.user_score) val userRankTextView: TextView = itemView.findViewById(R.id.user_rank) } }
0
Kotlin
0
0
49f2ea14b19a23395f7f951a35f88a823922e97a
1,440
ironTracker
MIT License
src/main/kotlin/dagger/cafeteras/BombasModule.kt
joseluisgs
486,502,940
false
null
package dagger.cafeteras import dagger.Binds import dagger.Module @Module internal abstract class BombasModule { @Binds // No devuelvo nada, solo bindeo el objeto,por eso no privider abstract fun providePump(bomba: Termosifon): Bomba }
0
Kotlin
4
16
6e1adc643f20c460b5869c12c6d73c933f39caa7
245
Kotlin-DI-Ejemplos
MIT License
app/src/main/java/com/akshay/roomaccounting/utility/MoshiAdapters.kt
anandwana001
470,781,738
false
null
/** * Created by anandwana001 on * 27, February, 2022 **/ package com.akshay.roomaccounting.utility import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.Types import javax.inject.Inject /** * This is a Moshi specific adapter to parse the json of object or list data. */ class MoshiAdapters @Inject constructor( val moshi: Moshi ) { inline fun <reified T> toJsonFromList(value: List<T>): String { return toListJsonAdapter<T>().toJson(value) } inline fun <reified T> toListfromJson(value: String): List<T>? { return toListJsonAdapter<T>().fromJson(value) } inline fun <reified T> toJson(value: T): String { return toJsonAdapter<T>().toJson(value) } inline fun <reified T> fromJson(value: String): T? { return toJsonAdapter<T>().fromJson(value) } inline fun <reified T> toListJsonAdapter(): JsonAdapter<List<T>> { val listType = Types.newParameterizedType(List::class.java, T::class.java) return moshi.adapter(listType) } inline fun <reified T> toJsonAdapter(): JsonAdapter<T> { return moshi.adapter(T::class.java) } }
2
null
2
29
9901444c7e94063f80c244b7b3b54a09a2141727
1,126
RoomAccounting
MIT License
app/src/main/java/xyz/teamgravity/roomtrigger/data/model/CountModel.kt
raheemadamboev
524,062,862
false
{"Kotlin": 13975}
package xyz.teamgravity.roomtrigger.data.model data class CountModel( val id: Long = 0, val count: Int, )
0
Kotlin
0
0
a18940bf0549881efe72d741b935a88d5ee17be7
115
room-trigger
Apache License 2.0
android/src/main/java/com/reactnativekeyboardcontroller/log/Logger.kt
kirillzyusko
482,596,054
false
{"TypeScript": 313244, "Kotlin": 124719, "Swift": 59411, "Objective-C++": 26156, "JavaScript": 16315, "Objective-C": 14055, "Ruby": 5246, "Java": 902, "Shell": 149, "C": 103}
package com.reactnativekeyboardcontroller.log import android.util.Log import com.reactnativekeyboardcontroller.BuildConfig object Logger { private val enabled = BuildConfig.DEBUG fun i( tag: String?, message: String, throwable: Throwable? = null, ) { if (enabled) { Log.i(tag, message, throwable) } } fun w( tag: String?, message: String, throwable: Throwable? = null, ) { if (enabled) { Log.w(tag, message, throwable) } } }
24
TypeScript
71
1,639
ee4aadaf212c2ade1251f61ac0bc01b67e63d209
495
react-native-keyboard-controller
MIT License
app/src/main/java/com/wechantloup/side/modules/home/HomeActivity.kt
Pilou44
187,889,252
false
null
package com.wechantloup.side.modules.home import android.Manifest import android.annotation.SuppressLint import android.content.pm.PackageManager import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.MarkerOptions import com.wechantloup.side.R import com.wechantloup.side.domain.bean.ToiletBean import com.wechantloup.side.modules.core.BaseActivity class HomeActivity: BaseActivity<HomeContract.Presenter>(), HomeContract.View, OnMapReadyCallback, LocationListener, GoogleMap.OnInfoWindowClickListener { companion object { private const val PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2702 private const val LOCATION_REFRESH_TIME = 2000L // ms private const val LOCATION_REFRESH_DISTANCE = 2F // m } private var mMap: GoogleMap? = null private var mLocationManager: LocationManager? = null private var mPositionMarker: Marker? = null private var mDataReady = false private var mMapReady = false private var mMoveOnFirstPosition = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment? mapFragment!!.getMapAsync(this) mLocationManager = getSystemService(LOCATION_SERVICE) as LocationManager if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION ) } if (savedInstanceState == null) { mMoveOnFirstPosition = true mPresenter.retrieveToiletsList() } } override fun onResume() { super.onResume() if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationManager?.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, this) } } override fun onPause() { super.onPause() if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationManager?.removeUpdates(this) } } @SuppressLint("MissingPermission") override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mLocationManager?.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, this) } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } override fun onMapReady(map: GoogleMap?) { mMapReady = true mMap = map mMap!!.setInfoWindowAdapter(CustomInfoWindowAdapter(this)) mMap!!.setOnInfoWindowClickListener(this) if (mDataReady) { displayToilets() } } override fun onLocationChanged(location: Location) { val position = LatLng(location.latitude, location.longitude) if (mPositionMarker == null) { mPositionMarker = mMap?.addMarker(MarkerOptions().position(position).icon(BitmapDescriptorFactory.fromResource(R.drawable.position_marker))) if (mMoveOnFirstPosition) { mMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(position, 12.0f)) } } else { mPositionMarker?.position = position } } override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) { // Nothing to do } override fun onProviderEnabled(provider: String?) { // Nothing to do } override fun onProviderDisabled(provider: String?) { // Nothing to do } override fun notifyToiletsListRetrieved() { mDataReady = true if (mMapReady) { displayToilets() } } private fun displayToilets() { mMap?.clear() val goToPosition = mPositionMarker == null mPositionMarker = null val toilets = mPresenter.getToiletsList() for (toilet in toilets!!) { val marker = mMap!!.addMarker(MarkerOptions().position(toilet.getPosition()).icon(BitmapDescriptorFactory.fromResource(R.drawable.toilet_marker))) marker.tag = toilet } if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { val location = mLocationManager!!.getLastKnownLocation(LocationManager.GPS_PROVIDER) location?.let { val position = LatLng(location.latitude, location.longitude) mPositionMarker = mMap?.addMarker(MarkerOptions().position(position).icon(BitmapDescriptorFactory.fromResource(R.drawable.position_marker))) if (goToPosition && mMoveOnFirstPosition) { mMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(position, 12.0f)) } } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater: MenuInflater = menuInflater inflater.inflate(R.menu.home_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.refresh -> { refresh() true } R.id.list -> { val position = when (mPositionMarker) { null -> null else -> mPositionMarker!!.position } mPresenter.showAsList(position) true } R.id.favorites -> { val position = when (mPositionMarker) { null -> null else -> mPositionMarker!!.position } mPresenter.showFavorites(position) true } else -> super.onOptionsItemSelected(item) } } private fun refresh() { mMap?.clear() mPositionMarker?.let { mPositionMarker = mMap?.addMarker(MarkerOptions().position(mPositionMarker!!.position!!).icon(BitmapDescriptorFactory.fromResource(R.drawable.position_marker))) } mPresenter.retrieveToiletsList() } override fun onInfoWindowClick(marker: Marker) { mPresenter.openToilet(marker.tag as ToiletBean) } override fun notifyItemModified() { mMap?.let { displayToilets() } } }
0
Kotlin
0
0
0bae574d1c95ec8c0e72435a0d74d07e011203b7
7,717
side
Apache License 2.0
thrifty-java-codegen/src/main/kotlin/com/bendb/thrifty/gen/FieldNamer.kt
benjamin-bader
52,393,048
false
{"Kotlin": 968674, "Java": 139202, "Thrift": 60186, "ANTLR": 4742, "Shell": 361}
/* * Thrifty * * Copyright (c) <NAME> * Copyright (c) Microsoft Corporation * * All rights reserved. * * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.bendb.thrifty.gen import com.bendb.thrifty.schema.Field import com.bendb.thrifty.schema.FieldNamingPolicy internal class FieldNamer( private val namingPolicy: FieldNamingPolicy ) { private val nameCache = mutableMapOf<Field, String>() fun getName(field: Field) = nameCache.computeIfAbsent(field) { namingPolicy.apply(it.name) } }
0
Kotlin
0
1
b1a6c4a871016bb2a24c4c5e4ae9c39a1e31cc27
1,114
thrifty
Apache License 2.0
app/src/main/java/uk/co/jakelee/pixelbookshop/utils/Xp.kt
JakeSteam
233,470,501
false
{"Kotlin": 133420}
package uk.co.jakelee.pixelbookshop.utils import kotlin.math.floor import kotlin.math.pow import kotlin.math.sqrt class Xp { companion object { private const val levelModifier = 0.05 fun xpToLevel(xp: Long) = (levelModifier * sqrt(xp.toDouble())).toInt() fun levelToXp(level: Int) = (level / levelModifier).pow(2).toInt() fun getNextLevel(xp: Long) = xpToLevel(xp) + 1 fun getLevelProgress(xp: Long): Int { val currentLevel = xpToLevel(xp) val currentLevelXp = levelToXp(currentLevel) val nextLevelXp = levelToXp(currentLevel + 1) val neededXP = (nextLevelXp - currentLevelXp).toDouble() val earnedXP = nextLevelXp - xp val progress = 100 - (earnedXP / neededXP * 100) return floor(progress).toInt() } } }
0
Kotlin
0
1
cdf133de12bfd99c6aa5dddd43d406090a7176a9
856
PixelBookshop
MIT License
player/src/main/java/com/kafka/player/PlayerModule.kt
vipulyaara
170,554,386
false
null
package com.kafka.player import android.app.Application import android.app.NotificationManager import android.content.Context import com.kafka.player.playback.player.Player import com.kafka.player.playback.player.RealPlayer import com.kafka.player.timber.permissions.PermissionsManager import com.kafka.player.timber.permissions.RealPermissionsManager import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent @Module @InstallIn(ApplicationComponent::class) abstract class MediaModuleBinds { @Binds abstract fun bindPlayer(realPlayer: RealPlayer): Player @Binds abstract fun bindPermissionsManager(realPermissionsManager: RealPermissionsManager): PermissionsManager } @Module @InstallIn(ApplicationComponent::class) class MediaModule { @Provides fun providesNotificationService(application: Application): NotificationManager = application.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager @Provides fun providesContentResolver(application: Application) = application.applicationContext.contentResolver }
0
Kotlin
4
18
71a639047c246aa62c33fa472ab70100da25f727
1,164
Kafka
Apache License 2.0
src/test/kotlin/com/ohelshem/api/ApiEngineTest.kt
OhelShem
52,084,451
false
null
/* * Copyright 2016 <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.ohelshem.api import com.github.kittinunf.fuel.Fuel import com.ohelshem.api.controller.declaration.ApiEngine import com.ohelshem.api.util.BaseTestCase import com.ohelshem.api.util.getData import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.fail /** * Test [ApiEngine] integration with remove server. the credentials are stored on `resources` folder, under `credentials.txt` * where the first line is the id, and the second line is password */ class ApiEngineTest : BaseTestCase() { val apiEngine: ApiEngine = ApiFactory.create(colorProvider) @org.junit.Test fun testProvider() { Fuel.testMode { } val (id, password) = "credentials.txt".getData().split(System.lineSeparator()) val (response, exception) = apiEngine.call(id, password, 0) if (response != null) { assertNotNull(response.userData) assertNotEquals(0, response.changesDate) assertNotEquals(0, response.serverUpdateDate) } else { fail("should not fail with $exception") } } }
0
Kotlin
0
0
ffe361e0d5064a2c09640c9e59fd2345818cab8d
1,699
api-jvm
Apache License 2.0
src/main/kotlin/me/kqn/gptbot/HookPlugin.kt
kqnan
585,183,274
false
null
package me.kqn.gptbot import org.black_ixx.playerpoints.PlayerPoints import org.black_ixx.playerpoints.PlayerPointsAPI import org.bukkit.Bukkit object HookPlugin { val playerPointsAPI:PlayerPointsAPI init { playerPointsAPI= PlayerPointsAPI(Bukkit.getPluginManager().getPlugin("PlayerPoints") as PlayerPoints?) } }
0
Kotlin
0
1
d03df945f260b3ff8886076d5a86a58cb86b051a
337
GptBot
Creative Commons Zero v1.0 Universal
nft/core/src/main/kotlin/com/rarible/protocol/nft/core/service/item/meta/ContentMetaService.kt
NFTDroppr
418,665,809
true
{"Kotlin": 2329156, "Scala": 37343, "Shell": 6001, "HTML": 547}
package com.rarible.protocol.nft.core.service.item.meta import com.fasterxml.jackson.databind.ObjectMapper import com.rarible.core.cache.CacheService import com.rarible.core.cache.get import com.rarible.core.common.orNull import com.rarible.core.common.toOptional import com.rarible.protocol.nft.core.model.ContentMeta import com.rarible.protocol.nft.core.model.ItemProperties import com.rarible.protocol.nft.core.model.MediaMeta import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import reactor.core.publisher.Mono import reactor.kotlin.core.publisher.whenComplete @Service class ContentMetaService( private val mapper: ObjectMapper, private val mediaMetaService: MediaMetaService, private val ipfsService: IpfsService, @Autowired(required = false) private val cacheService: CacheService? ) { fun getByProperties(properties: ItemProperties): Mono<ContentMeta> { val imageMediaMeta = when { properties.imagePreview != null -> getMediaMeta(ipfsService.resolveRealUrl(properties.imagePreview)) properties.image != null -> getMediaMeta(ipfsService.resolveRealUrl(properties.image)) else -> Mono.empty() } val animationMediaMeta = when { properties.animationUrl != null -> getMediaMeta(ipfsService.resolveRealUrl(properties.animationUrl)) else -> Mono.empty() } return Mono.zip( imageMediaMeta.toOptional(), animationMediaMeta.toOptional() ) { p1, p2 -> ContentMeta( p1.orNull(), p2.orNull() ) } } fun resetByProperties(properties: ItemProperties): Mono<Void> { return listOfNotNull( properties.image, properties.imagePreview, properties.animationUrl ) .map { ipfsService.resolveRealUrl(it) } .map { cacheService?.reset(it, mediaMetaService) ?: Mono.empty() } .map { it.onErrorResume { Mono.empty() } } .whenComplete() } private fun getMediaMeta(url: String): Mono<MediaMeta> { return cacheService.get(url, mediaMetaService, true) .map { mapper.convertValue(it, MediaMeta::class.java) } .onErrorResume { Mono.empty() } } }
0
Kotlin
0
1
b1efdaceab8be95429befe80ce1092fab3004d18
2,376
ethereum-indexer
MIT License
src/test/kotlin/com/atlassian/performance/tools/infrastructure/api/os/UbuntuTest.kt
atlassian
172,059,830
false
{"Kotlin": 209879}
package com.atlassian.performance.tools.infrastructure.api.os import com.atlassian.performance.tools.ssh.api.DetachedProcess import com.atlassian.performance.tools.ssh.api.SshConnection import com.atlassian.performance.tools.ssh.api.SshHost import com.atlassian.performance.tools.ssh.api.auth.PasswordAuthentication import org.apache.logging.log4j.Level import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.threeten.extra.Interval import java.io.File import java.nio.file.Path import java.time.Duration import java.time.Instant import java.util.concurrent.CompletableFuture import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger import java.util.function.Supplier class UbuntuTest { @Test fun shouldBeParallelOnDifferentSshConnections() { val executor = Executors.newCachedThreadPool() val concurrency = 4 val hostsSoFar = AtomicInteger(0) val singleInstall = Supplier { val host = SshHost( ipAddress = "127.0.0." + hostsSoFar.incrementAndGet(), userName = "u", authentication = PasswordAuthentication("p"), port = 1 ) TimingSshConnection(host).use { ssh -> Ubuntu().install(ssh, listOf("whatever")) ssh.timeInteraction() } } val installs = (1..concurrency).map { CompletableFuture.supplyAsync(singleInstall, executor) } val sshInteractions = installs.map { it.get(5, TimeUnit.SECONDS) } val actualOverlaps = sshInteractions.zipWithNext { a, b -> a.overlaps(b) } val expectedOverlaps = (1 until concurrency).map { true } assertThat(actualOverlaps) .`as`("all SSH interactions overlap: $sshInteractions") .isEqualTo(expectedOverlaps) } private class TimingSshConnection( private val sshHost: SshHost ) : SshConnection { private var firstRequest: Instant? = null private var lastResponse: Instant? = null fun timeInteraction(): Interval = Interval.of( firstRequest ?: throw Exception("There was no first SSH interaction"), lastResponse ?: throw Exception("There was no last SSH interaction") ) override fun execute( cmd: String, timeout: Duration, stdout: Level, stderr: Level ): SshConnection.SshResult { if (firstRequest == null) { firstRequest = Instant.now() } Thread.sleep(300) lastResponse = Instant.now() return SshConnection.SshResult(0, "", "") } override fun safeExecute( cmd: String, timeout: Duration, stdout: Level, stderr: Level ): SshConnection.SshResult { return execute(cmd, timeout, stdout, stderr) } override fun getHost(): SshHost = sshHost override fun close() { } override fun download(remoteSource: String, localDestination: Path) { throw Exception("Unexpected call") } override fun startProcess(cmd: String): DetachedProcess { throw Exception("Unexpected call") } override fun stopProcess(process: DetachedProcess) { throw Exception("Unexpected call") } override fun upload(localSource: File, remoteDestination: String) { throw Exception("Unexpected call") } } }
7
Kotlin
26
11
181558f71409dd93b0aa50e44566a069ab6620e2
3,623
infrastructure
Apache License 2.0
tilbakekreving/domain/src/main/kotlin/tilbakekreving/domain/kravgrunnlag/påsak/KravgrunnlagStatusendringPåSakHendelse.kt
navikt
227,366,088
false
{"Kotlin": 9043533, "Shell": 4369, "TSQL": 1233, "Dockerfile": 800}
package tilbakekreving.domain.kravgrunnlag.påsak import no.nav.su.se.bakover.common.domain.Saksnummer import no.nav.su.se.bakover.common.tid.Tidspunkt import no.nav.su.se.bakover.hendelse.domain.HendelseId import no.nav.su.se.bakover.hendelse.domain.Hendelsesversjon import no.nav.su.se.bakover.hendelse.domain.Sakshendelse import tilbakekreving.domain.kravgrunnlag.Kravgrunnlagstatus import java.util.UUID /** * I noen tilfeller endrer ikke selve kravgrunnlaget seg, men kun statusen. * I disse tilfellene vil vi få en [KravgrunnlagStatusendringPåSakHendelse]. * Denne enkle meldingen har ikke et kontrollfelt som endringsmeldingene, så vi må bruke jmsTidspunktet for å sortere hendelsene. * * ### Eksempel 1 - Endring av feilutbetalte måneder: * Når det utføres endringer på feilutbetalte måneder, og Oppdrag ikke umiddelbart beregner resultatet, vil Oppdrag initielt sende oss statusen [Kravgrunnlagstatus.Sperret]. * Dette indikerer at en beregning pågår. * Etter at oppdrag har fullført beregningen, som ofte skjer innen samme dag, oppdateres statusen basert på resultatet av beregningen: * - Hvis kravgrunnlaget ikke har endret seg som følge av beregningen, vil statusen oppdateres til ENDR, som reflekterer ingen endring i kravgrunnlaget. * - Hvis det derimot er en endring i kravgrunnlaget etter beregningen, vil Oppdrag sende et oppdatert [Kravgrunnlag] med statusen ENDR, som indikerer at det har skjedd en endring. * Det er viktig å merke seg at systemet ikke vil generere en ekstra statusendring; det er en enten-eller situasjon basert på resultatet av beregningen. * ### Eksempel 2 - Kansellering av feilutbetalte måneder: * Dersom endringen av kravgrunnlaget fører til at det ikke er noen feilutbetaling igjen, vil vi få en status AVSL. * * TODO jah: Utvid denne beskrivelsen med flere eksempler etter hvert som de dukker opp i preprod/produksjon. */ data class KravgrunnlagStatusendringPåSakHendelse( override val hendelseId: HendelseId, override val versjon: Hendelsesversjon, override val sakId: UUID, override val hendelsestidspunkt: Tidspunkt, override val tidligereHendelseId: HendelseId, override val saksnummer: Saksnummer, /** Dette er en ekstern id som genereres og eies av Oppdrag. Den er transient i vårt system. Endringer/statusendringer på et kravgrunnlag vil ha samme id. */ override val eksternVedtakId: String, /** TODO jah: Antar at ikke alle disse statusene kan oppstå for statusendringer. Noen brukes kun av kravgrunnlaget. */ override val status: Kravgrunnlagstatus, override val eksternTidspunkt: Tidspunkt, ) : KravgrunnlagPåSakHendelse { init { require(versjon.value > 1L) { "Bare en liten guard mot å opprette en hendelse med versjon 1, siden den er reservert for SakOpprettetHendelse" } } override val entitetId: UUID = sakId override fun compareTo(other: Sakshendelse): Int { require(this.entitetId == other.entitetId) return this.versjon.compareTo(other.versjon) } companion object { fun fraPersistert( hendelseId: HendelseId, hendelsestidspunkt: Tidspunkt, forrigeVersjon: Hendelsesversjon, entitetId: UUID, sakId: UUID, tidligereHendelseId: HendelseId, status: Kravgrunnlagstatus, eksternVedtakId: String, saksnummer: Saksnummer, eksternTidspunkt: Tidspunkt, ): KravgrunnlagStatusendringPåSakHendelse { return KravgrunnlagStatusendringPåSakHendelse( hendelseId = hendelseId, hendelsestidspunkt = hendelsestidspunkt, sakId = sakId, versjon = forrigeVersjon, tidligereHendelseId = tidligereHendelseId, status = status, eksternVedtakId = eksternVedtakId, saksnummer = saksnummer, eksternTidspunkt = eksternTidspunkt, ).also { require(it.entitetId == entitetId) { "Den persistert entitetId var ulik den utleda fra domenet:${it.entitetId} vs. $entitetId." } } } } }
1
Kotlin
1
1
bcfe10b28af8a9a8592c0cf8422d19b6892ee872
4,223
su-se-bakover
MIT License
fontawesome/src/de/msrd0/fontawesome/icons/FA_GLIDE_G.kt
msrd0
363,665,023
false
null
/* @generated * * This file is part of the FontAwesome Kotlin library. * https://github.com/msrd0/fontawesome-kt * * This library is not affiliated with FontAwesome. * * 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 de.msrd0.fontawesome.icons import de.msrd0.fontawesome.Icon import de.msrd0.fontawesome.Style import de.msrd0.fontawesome.Style.BRANDS object FA_GLIDE_G: Icon { override val name get() = "Glide G" override val unicode get() = "f2a6" override val styles get() = setOf(BRANDS) override fun svg(style: Style) = when(style) { BRANDS -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M407.1 211.2c-3.5-1.4-11.6-3.8-15.4-3.8-37.1 0-62.2 16.8-93.5 34.5l-.9-.9c7-47.3 23.5-91.9 23.5-140.4C320.8 29.1 282.6 0 212.4 0 97.3 0 39 113.7 39 198.4 39 286.3 90.3 335 177.6 335c12 0 11-1 11 3.8-16.9 128.9-90.8 133.1-90.8 94.6 0-39.2 45-58.6 45.5-61-.3-12.2-47-27.6-58.9-27.6-33.9.1-52.4 51.2-52.4 79.3C32 476 64.8 512 117.5 512c77.4 0 134-77.8 151.4-145.4 15.1-60.5 11.2-63.3 19.7-67.6 32.2-16.2 57.5-27 93.8-27 17.8 0 30.5 3.7 58.9 8.4 2.9 0 6.7-2.9 6.7-5.8 0-8-33.4-60.5-40.9-63.4zm-175.3-84.4c-9.3 44.7-18.6 89.6-27.8 134.3-2.3 10.2-13.3 7.8-22 7.8-38.3 0-49-41.8-49-73.1 0-47 18-109.3 61.8-133.4 7-4.1 14.8-6.7 22.6-6.7 18.6 0 20 13.3 20 28.7-.1 14.3-2.7 28.5-5.6 42.4z"/></svg>""" else -> null } }
0
Kotlin
0
0
2fc4755051325e730e9d012c9dfe94f5ea800fdd
1,878
fontawesome-kt
Apache License 2.0
app/src/main/java/org/gittner/osmbugs/OsmBugsMyLocationNewOverlay.kt
ChristopherGittner
11,003,677
false
{"Kotlin": 139829}
package org.gittner.osmbugs import org.osmdroid.views.MapView import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay class OsmBugsMyLocationNewOverlay(mapView: MapView, followCb: (Boolean) -> Unit) : MyLocationNewOverlay(mapView) { private val mFollowCb : (Boolean) -> Unit init { mFollowCb = followCb } override fun enableFollowLocation() { super.enableFollowLocation() mFollowCb(true) } override fun disableFollowLocation() { super.disableFollowLocation() mFollowCb(false) } }
8
Kotlin
5
23
df69fd8f09ee09c12e6d75d2e72bfd3683f3b53c
563
OSMBugs
MIT License
jvm-runtime/testdata/kotlin/kotlinserver/src/main/kotlin/xyz/block/ftl/test/Shape.kt
TBD54566975
607,506,228
false
{"Go": 2022889, "TypeScript": 265733, "Java": 250084, "Shell": 36119, "Rust": 32551, "Kotlin": 23597, "PLpgSQL": 18003, "Just": 15838, "HCL": 4495, "JavaScript": 2073, "Mustache": 1586, "HTML": 549, "MDX": 191, "CSS": 59}
package xyz.block.ftl.test import xyz.block.ftl.Enum @Enum enum class Shape(val value: String) { Circle("circle"), Square("square"), Triangle("triangle"); }
245
Go
7
21
ce5715e45add6bbf22912708b5bdcf04be068f30
165
ftl
Apache License 2.0
src/test/kotlin/de/joshi/modpackdownloader/parser/ManifestParserTest.kt
Joshyx
604,108,373
false
null
package de.joshi.modpackdownloader.parser import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* import java.io.File import java.io.FileNotFoundException class ManifestParserTest { private val modpackFile = File("src/test/resources/modpack") @Test fun getManifestThrowsException() { assertThrows(FileNotFoundException::class.java) { ManifestParser().getManifest(File("sadf/dsajkvxcym/asdas")) } } @Test fun getManifestSuccessfully() { assertDoesNotThrow { ManifestParser().getManifest(modpackFile) } } }
0
Kotlin
1
2
9c6582d217127e8468f4da2dad2f5ba69c919cf0
612
ModpackDownloader
MIT License
airwallex/src/main/java/com/airwallex/android/model/parser/CreatePaymentConsentParamsParser.kt
nieqiyuan
390,658,464
true
{"Kotlin": 562120}
package com.airwallex.android.model.parser import com.airwallex.android.model.* import com.airwallex.android.model.AirwallexJsonUtils import org.json.JSONObject class CreatePaymentConsentParamsParser : ModelJsonParser<CreatePaymentConsentParams> { override fun parse(json: JSONObject): CreatePaymentConsentParams { return CreatePaymentConsentParams( clientSecret = json.optString(FIELD_CLIENTSECRET), customerId = json.optString(FIELD_CUSTOMERID), paymentMethodId = json.optString(FIELD_PAYMENTMETHODID), nextTriggeredBy = PaymentConsent.NextTriggeredBy.fromValue(AirwallexJsonUtils.optString(json, FIELD_NEXTTRIGGEREDBY))!!, merchantTriggerReason = PaymentConsent.MerchantTriggerReason.fromValue(AirwallexJsonUtils.optString(json, FIELD_MERCHANTTRIGGERREASON))!!, paymentMethodType = PaymentMethodType.fromValue(AirwallexJsonUtils.optString(json, FIELD_TYPE))!!, requiresCvc = json.optBoolean(FIELD_REQUESTCVC) ) } private companion object { private const val FIELD_CLIENTSECRET = "clientSecret" private const val FIELD_CUSTOMERID = "customerId" private const val FIELD_PAYMENTMETHODID = "paymentMethodId" private const val FIELD_NEXTTRIGGEREDBY = "nextTriggeredBy" private const val FIELD_MERCHANTTRIGGERREASON = "merchantTriggerReason" private const val FIELD_TYPE = "paymentMethodType" private const val FIELD_REQUESTCVC = "requiresCvc" } }
0
Kotlin
0
1
72b5befb79147a2f012d66d1136e9d37bb77950f
1,521
airwallex-payment-android
MIT License
data/legacy/src/commonMain/kotlin/app/tivi/data/mappers/ShowIdToTraktOrImdbIdMapper.kt
chrisbanes
100,624,553
false
{"Kotlin": 1003653, "Swift": 24790, "HTML": 23782, "Ruby": 4088, "Shell": 3317, "Python": 1228}
// Copyright 2018, <NAME> and the Tivi project contributors // SPDX-License-Identifier: Apache-2.0 package app.tivi.data.mappers import app.tivi.data.daos.TiviShowDao import app.tivi.data.db.DatabaseTransactionRunner import me.tatarka.inject.annotations.Inject @Inject class ShowIdToTraktOrImdbIdMapper( private val showDao: TiviShowDao, private val transactionRunner: DatabaseTransactionRunner, ) : Mapper<Long, String?> { override fun map(from: Long): String? = transactionRunner { showDao.getTraktIdForShowId(from)?.toString() ?: showDao.getImdbIdForShowId(from) } }
23
Kotlin
876
6,626
e261ffbded01c1439b93c550cd6e714c13bb9192
609
tivi
Apache License 2.0
draw/src/main/java/com/divyanshu/draw/widget/tools/drawing/PathAction.kt
hydrolythe
353,694,404
false
null
package com.divyanshu.draw.widget.tools.drawing import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import com.divyanshu.draw.widget.Action import com.divyanshu.draw.widget.Line import com.divyanshu.draw.widget.Move import com.divyanshu.draw.widget.Quad import com.divyanshu.draw.widget.tools.CanvasAction import java.io.ObjectInputStream import java.io.Serializable import java.util.LinkedList // TODO: remove redundant paintOptions class PathAction(private val paint: Paint) : Path(), Serializable, CanvasAction { init { paint.apply { // Same for every path style = Paint.Style.STROKE strokeJoin = Paint.Join.ROUND strokeCap = Paint.Cap.ROUND } } private val actions = LinkedList<Action>() override fun drawOn(canvas: Canvas) { canvas.drawPath(this, paint) } private fun readObject(inputStream: ObjectInputStream) { inputStream.defaultReadObject() val copiedActions = actions.map { it } copiedActions.forEach { it.perform(this) } } override fun reset() { actions.clear() super.reset() } override fun moveTo(x: Float, y: Float) { actions.add(Move(x, y)) super.moveTo(x, y) } override fun lineTo(x: Float, y: Float) { actions.add(Line(x, y)) super.lineTo(x, y) } override fun quadTo(x1: Float, y1: Float, x2: Float, y2: Float) { actions.add(Quad(x1, y1, x2, y2)) super.quadTo(x1, y1, x2, y2) } override fun isEmpty(): Boolean { return actions.isEmpty() } }
0
Kotlin
0
0
14c6aec4b3c0a42bc73a7f779964d166fffeea20
1,666
FAITHAndroid
The Unlicense
src/jsMain/kotlin/pouchdb/index.pouchdb_find.module_pouchdb-find.kt
epabst
60,592,428
false
null
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION") package pouchdb import kotlin.js.* @JsModule("pouchdb-find") external val pouchdb_find: Plugin
14
Kotlin
2
3
5d5129e556c8b168b0a0b838eec694664af37902
251
kotlin-showcase
Apache License 2.0