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
sample-app/src/main/kotlin/io/github/ilyapavlovskii/kmm/force/update/sample/MainActivity.kt
IlyaPavlovskii
617,508,906
false
null
package io.github.ilyapavlovskii.kmm.force.update.sample import android.net.Uri 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 io.github.ilyapavlovskii.kmm.force.update.model.ForceUpdateType import io.github.ilyapavlovskii.kmm.force.update.presentation.AppUpdateScreen import io.github.ilyapavlovskii.kmm.force.update.sample.ui.MainScreen import io.github.ilyapavlovskii.kmm.force.update.ui.ForceUpdateTheme internal class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ForceUpdateTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { MainScreen(useCase = useCase) AppUpdateScreen( getForceUpdateEventFlowUseCase = useCase, applicationUri = Uri.parse("https://play.google.com/store/apps/details?id=by.bulba.ipsc.calculator"), onCancelListener = { useCase.update(ForceUpdateType.ABSENT) }, onMediumUpdateClick = { useCase.update(ForceUpdateType.ABSENT) }, ) } } } } }
0
Kotlin
0
0
aa995a9b897a007507640a29698e8da45957657c
1,560
force-update
Apache License 2.0
composeApp/src/commonMain/kotlin/di/RepoModule.kt
FrankieShao
815,291,399
false
{"Kotlin": 347190, "Swift": 657}
package di import core.domain.repo.AccountRepo import core.domain.repo.AccountRepoImpl import core.domain.repo.AuthRepo import core.domain.repo.AuthRepoImpl import core.domain.repo.ConfigureRepo import core.domain.repo.ConfigureRepoImpl import org.koin.dsl.module /** * @author <NAME> * @created 10/06/2024 * Description: Repo koin module, responsible for repo related dependencies */ val RepoModule = module { single<AccountRepo> { AccountRepoImpl(get(), get()) } single<AuthRepo> { AuthRepoImpl(get(), get()) } single<ConfigureRepo> { ConfigureRepoImpl(get()) } }
0
Kotlin
0
0
5137399a0b2d5554aa49377ed5d853cfece5dc68
583
FlickFusion
MIT License
src/main/kotlin/org/beckn/one/sandbox/bap/client/order/cancel/mappers/CancelClientResponseMapper.kt
OSSVerse
853,138,400
false
{"Kotlin": 651081, "Jinja": 3324}
package org.beckn.one.sandbox.bap.client.order.cancel.mappers import arrow.core.Either import org.beckn.one.sandbox.bap.client.shared.dtos.ClientCancelResponse import org.beckn.one.sandbox.bap.client.shared.services.GenericOnPollMapper import org.beckn.one.sandbox.bap.errors.HttpError import org.beckn.protocol.schemas.ProtocolContext import org.beckn.protocol.schemas.ProtocolOnCancel class CancelClientResponseMapper : GenericOnPollMapper<ProtocolOnCancel, ClientCancelResponse> { override fun transform( input: List<ProtocolOnCancel>, context: ProtocolContext ): Either<HttpError, ClientCancelResponse> = Either.Right( ClientCancelResponse( context = context, message = input.firstOrNull()?.message, error = input.firstOrNull()?.error ) ) }
0
Kotlin
0
8
b3ca6a6455f41b9d53bbb35f5c01e31c1fde2638
802
OSSVerse-buyer-app
Apache License 2.0
preferences/src/main/java/com/sensorberg/filepreferences/FileAccess.kt
sensorberg
219,981,581
false
null
package com.sensorberg.filepreferences interface FileAccess { fun loadData(): String? fun saveData(data: String) }
0
Kotlin
1
0
16e0a203eaa621ac9e243e1da1b1763c9e3ea9f0
117
file-preferences
MIT License
db/src/testFixtures/kotlin/com/dzirbel/kotify/db/BlockingTransaction.kt
dzirbel
211,595,180
false
null
package com.dzirbel.kotify.db import kotlinx.coroutines.runBlocking import org.jetbrains.exposed.sql.Transaction import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** * Blocking wrapper around [KotifyDatabase.transaction] for use in tests. */ fun <T> KotifyDatabase.blockingTransaction(statement: Transaction.() -> T): T { contract { callsInPlace(statement, InvocationKind.EXACTLY_ONCE) } return withSynchronousTransactions { runBlocking { transaction(name = null, statement = statement) } } }
2
Kotlin
2
37
8302361dabb135584eb6c8264cf0fc0e9b9e6c03
573
kotify
MIT License
app/router/src/main/java/com/gmail/jiangyang5157/router/fragment/setup/AsFragmentActivity.kt
jiangyang5157
553,993,370
false
null
package com.gmail.jiangyang5157.router.fragment.setup import androidx.fragment.app.FragmentActivity import com.gmail.jiangyang5157.router.error.RouterException interface AsFragmentActivity fun AsFragment.isFragmentActivity() = this is FragmentActivity fun AsFragmentActivity.expectThisToBeAFragmentActivity() = this as? FragmentActivity ?: throw RouterException( "Expect ${this::class.java.simpleName} is an androidx.fragment.app.FragmentActivity" )
0
Kotlin
0
0
bd3252ce62e592405fa2ffa4ce82e3dbab339df2
470
kotlin-multiplatform-mobile
MIT License
integration-test-core/src/main/kotlin/integration/core/WrappedStringTypeConverter.kt
komapper
349,909,214
false
{"Kotlin": 2652019, "Java": 57131}
package integration.core import org.komapper.core.spi.DataTypeConverter import kotlin.reflect.KClass class WrappedStringTypeConverter : DataTypeConverter<WrappedString, String> { override val exteriorClass: KClass<WrappedString> = WrappedString::class override val interiorClass: KClass<String> = String::class override fun unwrap(exterior: WrappedString): String { return exterior.value } override fun wrap(interior: String): WrappedString { return WrappedString(interior) } }
10
Kotlin
13
282
66dad22411fe5aebb51b7227a8eb9247a88891cf
522
komapper
Apache License 2.0
app/src/main/java/com/example/netbond/UserSearchBarFragment.kt
G10on
564,528,324
false
null
package com.example.netbond import android.os.Bundle import androidx.core.os.bundleOf import android.text.Editable import android.text.TextWatcher import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.size import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import com.bumptech.glide.Glide import com.example.netbond.databinding.AcceptUserTemplateBinding import com.example.netbond.databinding.FragmentUserSearchBarBinding import com.example.netbond.databinding.SearchUserTemplateBinding import com.example.netbond.services.StorageService import com.example.netbond.services.Utils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import androidx.fragment.app.setFragmentResult import com.example.netbond.models.UserViewModel class UserSearchBarFragment : Fragment() { private lateinit var binding: FragmentUserSearchBarBinding private val storageService = StorageService() private val utils = Utils() private val viewModel: UserViewModel by activityViewModels() private var actualUsername = "" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { setActualUsername() // Inflate the layout for this fragment binding = FragmentUserSearchBarBinding.inflate(inflater, container, false) CoroutineScope(Dispatchers.Main).launch { setSearchBarListener() if ((binding.pendingRequests.visibility == View.VISIBLE) && (binding.usersList.size == 0)) { setReceivedRequests() } } return binding.root } private fun setActualUsername() { viewModel.user.observe(viewLifecycleOwner) { actualUsername = it.username!! } } private fun setSearchBarListener() { binding.searchBar.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun afterTextChanged(s: Editable?) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { binding.usersList.removeAllViews() if (!s.isNullOrEmpty()) { binding.pendingRequests.visibility = View.GONE setSearchUsers(s) } else { binding.pendingRequests.visibility = View.VISIBLE setReceivedRequests() } } }) } private fun setSearchUsers(searchedText: CharSequence) { CoroutineScope(Dispatchers.Main).launch { val users = storageService.getUsers() for (user in users) { if (user.name!!.contains(searchedText)) { val bind = SearchUserTemplateBinding.inflate(layoutInflater, binding.usersList, true) bind.nameUser.text = user.name bind.userPoints.text = user.n_points.toString() val username = "@" + user.username bind.userName.text = username Glide.with(this@UserSearchBarFragment).load(user.profile_image).into(bind.userImage) if (actualUsername != user.username) { bind.root.setOnClickListener { setFragmentResult("requestKey", bundleOf("bundleKey" to user.username)) findNavController().navigate(R.id.externalUserProfileFragment) } // Actual user clicks on his own user } else { bind.root.setOnClickListener { findNavController().navigate(R.id.userProfileFragment) } } } } } } private fun setReceivedRequests() { CoroutineScope(Dispatchers.Main).launch { val requests = storageService.getReceivedRequests(actualUsername) for (request in requests) { val bind = AcceptUserTemplateBinding.inflate(layoutInflater, binding.usersList, true) bind.root.setOnClickListener { setFragmentResult("requestKey", bundleOf("bundleKey" to request.username)) findNavController().navigate(R.id.externalUserProfileFragment) } bind.nameUser.text = request.name val username = "@" + request.username bind.userName.text = username Glide.with(this@UserSearchBarFragment).load(request.profile_image).into(bind.userImage) bind.userPoints.text = request.n_points.toString() bind.acceptButton.setOnClickListener { acceptUser(request.username!!, bind) } } } } private fun acceptUser(username: String, bind: AcceptUserTemplateBinding) { CoroutineScope(Dispatchers.Main).launch { // Actual User storageService.deleteReceivedRequest(actualUsername, username) storageService.addFollower(actualUsername, username) storageService.incrementFollowers(actualUsername, 1) // Accepted User storageService.deleteSentRequest(username, actualUsername) storageService.addFollowing(username, actualUsername) storageService.incrementFollowings(username, 1) val message = "Successfully added $username to your followers" utils.displayMessage(requireContext(), message) // Refresh Received Requests binding.usersList.removeView(bind.root) } } }
0
Kotlin
0
0
fa0b729fe5b1f28e3e6239b3f8c799957f97fcaf
5,929
netbond
Apache License 2.0
ndarray/ndarray-core/src/commonMain/kotlin/io/kinference/ndarray/extensions/bitwise/or/BitOrUtils.kt
JetBrains-Research
244,400,016
false
null
package io.kinference.ndarray.extensions.bitwise.or import io.kinference.primitives.types.PrimitiveType infix fun PrimitiveType.or(other: PrimitiveType): PrimitiveType = throw UnsupportedOperationException()
4
Kotlin
5
95
e47129b6f1e2a60bf12404d8126701ce7ef4db3a
211
kinference
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnTemplateBarChartFieldWellsPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 63959868}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.quicksight import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.quicksight.CfnTemplate /** * The field wells of a `BarChartVisual` . * * This is a union type structure. For this structure to be valid, only one of the attributes can be * defined. * * Example: * ``` * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-template-barchartfieldwells.html) */ @CdkDslMarker public class CfnTemplateBarChartFieldWellsPropertyDsl { private val cdkBuilder: CfnTemplate.BarChartFieldWellsProperty.Builder = CfnTemplate.BarChartFieldWellsProperty.builder() /** @param barChartAggregatedFieldWells The aggregated field wells of a bar chart. */ public fun barChartAggregatedFieldWells(barChartAggregatedFieldWells: IResolvable) { cdkBuilder.barChartAggregatedFieldWells(barChartAggregatedFieldWells) } /** @param barChartAggregatedFieldWells The aggregated field wells of a bar chart. */ public fun barChartAggregatedFieldWells( barChartAggregatedFieldWells: CfnTemplate.BarChartAggregatedFieldWellsProperty ) { cdkBuilder.barChartAggregatedFieldWells(barChartAggregatedFieldWells) } public fun build(): CfnTemplate.BarChartFieldWellsProperty = cdkBuilder.build() }
3
Kotlin
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,643
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/java/com/innercirclesoftware/trimio/app/Injection.kt
maciej-kaznowski
163,348,833
false
{"Kotlin": 47701}
package com.innercirclesoftware.trimio.app import android.content.Context import android.content.res.AssetManager import com.innercirclesoftware.trimio.trim.periodic.TrimScheduler import com.innercirclesoftware.trimio.ui.base.ActivityComponent import dagger.Component import dagger.Module import dagger.Provides import javax.inject.Scope @Retention(AnnotationRetention.RUNTIME) @Scope annotation class PerApp @PerApp @Component( modules = [ AppModule::class, WorkModule::class ] ) interface AppComponent { fun newActivityComponent(): ActivityComponent.Builder fun inject(app: App) fun getContext(): Context fun getTrimScheduler(): TrimScheduler fun getAssetManager(): AssetManager } @Module class AppModule(private val app: App) { @Provides @PerApp fun providesAppContext(): Context { return app } @Provides @PerApp fun providesAssetManager(): AssetManager { return app.assets } }
1
Kotlin
0
0
66b3d72445fe57985a773d1a508747709399178e
984
TrimIO
Apache License 2.0
plugin/src/main/kotlin/top/iseason/bukkit/mmogem/ui/RebuildUI.kt
Iseason2000
802,720,492
false
{"Kotlin": 264289, "Java": 43993}
package top.iseason.bukkit.mmogem.ui import io.lumine.mythic.lib.UtilityMethods import io.lumine.mythic.lib.api.item.NBTItem import net.Indyuce.mmoitems.MMOItems import net.Indyuce.mmoitems.api.item.mmoitem.LiveMMOItem import net.Indyuce.mmoitems.api.player.PlayerData import net.Indyuce.mmoitems.api.util.NumericStatFormula import net.Indyuce.mmoitems.api.util.NumericStatFormula.FormulaInputType import net.Indyuce.mmoitems.stat.data.DoubleData import org.bukkit.entity.HumanEntity import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack import top.iseason.bukkit.mmoforge.uitls.kparser.ExpressionParser import top.iseason.bukkit.mmogem.Config import top.iseason.bukkit.mmogem.Lang import top.iseason.bukkit.mmogem.MMOGem import top.iseason.bukkit.mmogem.VaultHook.takeMoney import top.iseason.bukkit.mmogem.stat.RebuildTimes import top.iseason.bukkittemplate.hook.PlaceHolderHook import top.iseason.bukkittemplate.ui.container.ChestUI import top.iseason.bukkittemplate.ui.slot.* import top.iseason.bukkittemplate.utils.bukkit.ItemUtils.applyMeta import top.iseason.bukkittemplate.utils.bukkit.ItemUtils.decrease import top.iseason.bukkittemplate.utils.bukkit.MessageUtils.formatBy import top.iseason.bukkittemplate.utils.bukkit.MessageUtils.sendColorMessage import top.iseason.bukkittemplate.utils.bukkit.MessageUtils.toColor class RebuildUI(val player: Player) : ChestUI( PlaceHolderHook.setPlaceHolder(RebuildUIConfig.title, player), RebuildUIConfig.row, RebuildUIConfig.clickDelay ) { init { for ((index, item) in RebuildUIConfig.background) { Icon(item, index).setup() } } val inputSlot = run { val (slots, item) = RebuildUIConfig.input val index = slots[0] InputSlot(index, item).setup() } val outputSlot = run { val (slots, item) = RebuildUIConfig.result val index = slots[0] OutputSlot(index, item).setup() } val materialSlot = run { val (slots, item) = RebuildUIConfig.material val index = slots[0] MaterialSlot(index, item).setup() } val button = run { val (slots, item) = RebuildUIConfig.button slots.map { ButtonSlot(it, item).setup() } } inner class InputSlot(index: Int, items: HashMap<String, ItemStack>) : IOSlot(index, items["default"]) { var mmoItem: LiveMMOItem? = null var typeId: String? = null init { inputFilter { val nbtItem = NBTItem.get(it) ?: return@inputFilter false if (!nbtItem.hasType()) return@inputFilter false val type = MMOItems.getType(nbtItem)!!.id val id = MMOItems.getID(nbtItem)!! val typeId = UtilityMethods.enumName("$type:$id") val config = Config.rebuildMaterials[typeId] if (config == null) { val msg = PlaceHolderHook.setPlaceHolder(Lang.rebuild__deny, player) player.sendColorMessage(msg) return@inputFilter false } val liveMMOItem = LiveMMOItem(it) val times = (liveMMOItem.getData(RebuildTimes) as? DoubleData)?.value ?: 0.0 if (times >= config.guarantee) { val msg = PlaceHolderHook.setPlaceHolder(Lang.rebuild__max, player) player.sendColorMessage(msg) return@inputFilter false } if (!liveMMOItem.gemstones.isEmpty()) { val msg = PlaceHolderHook.setPlaceHolder(Lang.rebuild__has_gem, player) player.sendColorMessage(msg) return@inputFilter false } mmoItem = liveMMOItem this@InputSlot.typeId = typeId true } onInput(true) { val config = Config.rebuildMaterials[typeId]!! val mId = materialSlot.typeId for (buttonSlot in button) { buttonSlot.setInput(config) } outputSlot.ejectSilently(player) if (mId != null) { if (mId != config.normalMaterial && mId != config.specialMaterial) { materialSlot.ejectSilently(player) } else materialSlot.onInput.invoke(materialSlot, materialSlot.itemStack!!) } } onOutput(true) { mmoItem = null materialSlot.ejectSilently(player) for (buttonSlot in button) { buttonSlot.reset() } outputSlot.reset() this@InputSlot.typeId = null } } override fun reset() { super.reset() this@InputSlot.typeId = null mmoItem = null } } inner class OutputSlot(index: Int, items: HashMap<String, ItemStack>) : IOSlot(index, items["default"]) { var isPreview = false init { inputAble(false) outputAble(false) } fun setPreview() { val mmo = inputSlot.mmoItem!! itemStack = MMOItems.plugin.templates.getTemplate(mmo.type, mmo.id)!! .newBuilder(PlayerData.get(player).rpg, true) .build().newBuilder().build(true) isPreview = true outputAble(false) } override fun reset() { super.reset() isPreview = false } override fun ejectSilently(humanEntity: HumanEntity) { if (isPreview) { reset() return } super.ejectSilently(humanEntity) } } inner class ButtonSlot(index: Int, items: HashMap<String, ItemStack>) : Button(items["default"], index) { private val available: ItemStack = items["available"]!! private val input: ItemStack = items["input"]!! private var state = 0 init { onClicked { when (state) { 1 -> { val config = Config.rebuildMaterials[inputSlot.typeId]!! val mmoItem = inputSlot.mmoItem!! val times = (mmoItem.getData(RebuildTimes) as? DoubleData)?.value ?: 0.0 val express = Config.rebuildGoldExp.trim().replace("{rebuild}", times.toInt().toString()) val gold = ExpressionParser().evaluate(express) if (!player.takeMoney(gold)) { player.sendColorMessage(Lang.rebuild__no_money) return@onClicked } val isGuarantee = times >= config.guarantee - 1 || materialSlot.typeId == config.specialMaterial val template = MMOItems.plugin.templates.getTemplate(mmoItem.type, mmoItem.id)!! val newMMO = template .newBuilder(PlayerData.get(player).rpg) .build() if (isGuarantee) { for (stat in newMMO.stats) { val numericStatFormula = template.baseItemData[stat] as? NumericStatFormula ?: continue val calculate = numericStatFormula.calculate(0.0, FormulaInputType.UPPER_BOUND) newMMO.setData(stat, DoubleData(calculate)) } newMMO.setData(RebuildTimes, DoubleData(config.guarantee.toDouble())) } else { newMMO.setData(RebuildTimes, DoubleData(times + 1)) } outputSlot.itemStack = newMMO.newBuilder().buildSilently() val amount = materialSlot.itemStack!!.amount var consume = 1 if (inputSlot.typeId == config.normalMaterial) { consume = config.normalConsume } else if (inputSlot.typeId == config.specialMaterial) { consume = config.specialConsume } if (amount == consume) materialSlot.reset() else materialSlot.itemStack!!.decrease(consume) val itemName = MMOGem.getItemName(inputSlot.typeId!!) inputSlot.reset() outputSlot.outputAble(true) outputSlot.isPreview = false val msg = PlaceHolderHook.setPlaceHolder(Lang.rebuild__success.formatBy(itemName), player) player.sendColorMessage(msg) if (times >= config.guarantee - 1) { val msg = PlaceHolderHook.setPlaceHolder(Lang.rebuild__no_max.formatBy(itemName), player) player.sendColorMessage(msg) } else if (materialSlot.typeId == config.specialMaterial) { val msg = PlaceHolderHook.setPlaceHolder(Lang.rebuild__special.formatBy(itemName), player) player.sendColorMessage(msg) } reset() } else -> return@onClicked } } } fun setInput(config: Config.RebuildConfig) { val string = RebuildUIConfig.buttonSection .getString("input-lore", "- {1} 个 {0}")!! itemStack = input.clone().applyMeta { val rawLore = if (hasLore()) lore!!.toMutableList() else ArrayList() val lore1 = string.formatBy(MMOGem.getItemName(config.normalMaterial).toColor(), config.normalConsume) val lore2 = string.formatBy(MMOGem.getItemName(config.specialMaterial).toColor(), config.specialConsume) rawLore.add(lore1) rawLore.add(lore2) lore = rawLore } state = 2 } fun setAvailable(gold: Double, rebuild: Int, maxRebuild: Int) { itemStack = available.clone().applyMeta { if (hasDisplayName()) setDisplayName( displayName .replace("{gold}", gold.toString()) .replace("{rebuild}", rebuild.toString()) .replace("{max-rebuild}", maxRebuild.toString()) ) if (hasLore()) lore = lore!!.map { it.replace("{gold}", gold.toString()) .replace("{rebuild}", rebuild.toString()) .replace("{max-rebuild}", maxRebuild.toString()) } } state = 1 outputSlot.setPreview() } override fun reset() { super.reset() state = 0 } } inner class MaterialSlot(index: Int, items: HashMap<String, ItemStack>) : IOSlot(index, items["default"]) { var typeId: String? = null init { lockable(false) inputFilter { if (inputSlot.mmoItem == null) return@inputFilter false val nbtItem = NBTItem.get(it) ?: return@inputFilter false if (!nbtItem.hasType()) return@inputFilter false val config = Config.rebuildMaterials[inputSlot.typeId]!! val type = MMOItems.getType(nbtItem)!!.id val id = MMOItems.getID(nbtItem)!! val typeId = UtilityMethods.enumName("$type:$id") val result = config.normalMaterial == typeId || config.specialMaterial == typeId this@MaterialSlot.typeId = typeId result } onInput { val config = Config.rebuildMaterials[inputSlot.typeId]!! val amount = itemStack!!.amount if (typeId == config.normalMaterial && amount >= config.normalConsume) { val times = (inputSlot.mmoItem!!.getData(RebuildTimes) as? DoubleData)?.value ?: 0.0 val express = Config.rebuildGoldExp.trim().replace("{rebuild}", times.toInt().toString()) val evaluate = ExpressionParser().evaluate(express) for (buttonSlot in button) { buttonSlot.setAvailable(evaluate, times.toInt(), config.guarantee) } } else if (typeId == config.specialMaterial && amount >= config.specialConsume) { val times = (inputSlot.mmoItem!!.getData(RebuildTimes) as? DoubleData)?.value ?: 0.0 val express = Config.rebuildGoldExp.trim().replace("{rebuild}", times.toInt().toString()) val evaluate = ExpressionParser().evaluate(express) for (buttonSlot in button) { buttonSlot.setAvailable(evaluate, times.toInt(), config.guarantee) } } else { for (buttonSlot in button) { buttonSlot.setInput(config) } } } onOutput { outputSlot.ejectSilently(player) val config = Config.rebuildMaterials[inputSlot.typeId] if (itemStack != null && config != null) { onInput(itemStack!!) } else { for (buttonSlot in button) { buttonSlot.reset() } } } } override fun reset() { super.reset() typeId = null } } }
0
Kotlin
0
0
4e531adf2e66a6e74e8d326d10d876f56d9dc74a
14,052
MMOGem
MIT License
app/src/main/java/com/loongwind/frp/client/ui/FrpcConfigListActivity.kt
loongwind
525,796,108
false
{"Kotlin": 49568}
package com.loongwind.frp.client.ui import android.content.Intent import android.os.Bundle import android.view.View import com.loongwind.ardf.base.BaseBindingViewModelActivity import com.loongwind.ardf.base.event.EVENT_BACK import com.loongwind.frp.client.constant.EVENT_RESULT import com.loongwind.frp.client.constant.KEY_ID import com.loongwind.frp.client.databinding.ActivityFrpServiceBinding import com.loongwind.frp.client.vm.FrpServiceVM class FrpcConfigListActivity : BaseBindingViewModelActivity<ActivityFrpServiceBinding, FrpServiceVM>() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.isSelectMode = true } override fun initDataBinding(binding: ActivityFrpServiceBinding) { super.initDataBinding(binding) binding.fab.visibility = View.GONE } override fun onEvent(eventId: Int) { super.onEvent(eventId) if(eventId == EVENT_RESULT){ val intent = Intent() intent.putExtra(KEY_ID, viewModel.selectedConfig.get()?.id) setResult(RESULT_OK, intent) finish() } } }
0
Kotlin
0
0
a7daf9f1d7e262e930b10a88d09a063f632065de
1,151
android-frp-client
Apache License 2.0
gltf-gradle-plugin/src/test/kotlin/com/github/dwursteisen/gltf/PluginTest.kt
minigdx
242,223,166
false
null
package com.github.dwursteisen.gltf import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.TaskOutcome import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File class PluginTest { @Rule @JvmField val temporaryFolder = TemporaryFolder() lateinit var buildFile: File @Before fun setUp() { buildFile = temporaryFolder.newFile("build.gradle.kts") File("src/test/resources/cube.gltf").copyTo(temporaryFolder.newFolder("src", "main", "resources").resolve("cube.gltf"), true) buildFile.writeText( """ plugins { kotlin("jvm") version "1.4.20" id("com.github.minigdx.gradle.plugin.gltf") version "1.0-SNAPSHOT" } group = "org.example" version = "1.0-SNAPSHOT" repositories { mavenCentral() jcenter() mavenLocal() } dependencies { implementation(kotlin("stdlib-jdk8")) } gltfPlugin { create("assets") { this.gltfDirectory.set(project.file("src/main/resources/")) this.target.set(project.buildDir) } } tasks { compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } } """.trimIndent() ) } @Test fun runParser() { val result = GradleRunner.create() .withProjectDir(temporaryFolder.root) .withArguments(":gltf") .withPluginClasspath() .build() assertEquals(result.task(":gltf")?.outcome, TaskOutcome.SUCCESS) } }
1
Kotlin
2
2
180f42091dc8d3ab2c3249423bc0dbc5fb891b20
1,632
minigdx-glft-parser
MIT License
module-server/src/main/kotlin/de/twomartens/wahlrecht/service/ElectionResultService.kt
2martens
673,979,017
false
null
package de.twomartens.wahlrecht.service import de.twomartens.wahlrecht.model.db.ElectionResult import de.twomartens.wahlrecht.repository.ElectionResultRepository import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.web.server.ResponseStatusException @Service class ElectionResultService(private val repository: ElectionResultRepository) { private val electionResults: MutableMap<String, ElectionResult> by lazy { fetchResults() } fun getElectionResult(electionName: String): ElectionResult { return electionResults[electionName] ?: throw ResponseStatusException( HttpStatus.NOT_FOUND, "no election result found for $electionName" ) } fun storeResult(electionResult: ElectionResult): Boolean { var result = electionResult val id = result.electionName val existing = electionResults[id] val needsUpdate = result != existing if (!needsUpdate) { return false } var createdNew = true if (existing != null) { existing.overallResults = result.overallResults existing.constituencyResults = result.constituencyResults result = existing createdNew = false } val stored = repository.save(result) electionResults[id] = stored return createdNew } private fun fetchResults(): MutableMap<String, ElectionResult> { return repository.findAll().asSequence() .map { Pair(it.electionName, it) } .toMap() .toMutableMap() } }
0
Kotlin
0
0
a25a1f927f33c20b4a7fd0444403c7c706225204
1,676
wahlrecht
Apache License 2.0
best_practices/contrib/depression_detection/app/app-side/DepressionTest-dev/app/src/main/java/com/chris/depression/ui/survey/SurveyState.kt
Ascend
313,282,739
false
null
/* * Copyright 2022 Leon. */ package com.chris.depression.ui.survey import androidx.annotation.StringRes import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue @Stable class QuestionState( val question: Question, val questionIndex: Int, val totalQuestionsCount: Int, val showPrevious: Boolean, val showDone: Boolean ) { var enableNext by mutableStateOf(false) var answer by mutableStateOf<Answer<*>?>(null) } sealed class SurveyState { data class Start( @StringRes val surveyTitle: Int, val surveyStart: SurveyStart ) : SurveyState() data class Questions( val surveyTitle: String, val questionsState: List<QuestionState> ) : SurveyState() { var currentQuestionIndex by mutableStateOf(0) } data class Result( val surveyTitle: String, val surveyResult: SurveyResult ) : SurveyState() }
0
Python
27
68
fc2aea93e48be8f8cee51d0c6c1b13a08155f83a
1,016
samples
Apache License 2.0
app/src/main/java/com/boltuix/android/NotesViewModel.kt
BoltUIX
542,468,449
false
{"Kotlin": 12601}
package com.boltuix.android import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.launch class NotesViewModel(application: Application) : AndroidViewModel(application) { // DataStore private val uiDataStore = UIModePreference(application) // get UI mode val getUIMode = uiDataStore.uiMode // save UI mode fun saveToDataStore(isNightMode: Boolean) { viewModelScope.launch(IO) { uiDataStore.saveToDataStore(isNightMode) } } }
0
Kotlin
0
2
e9a597922a5482b01909283832e628ee0ebbba58
617
Dark-theme-Material-Design
Apache License 2.0
app/src/main/java/com/boltuix/android/NotesViewModel.kt
BoltUIX
542,468,449
false
{"Kotlin": 12601}
package com.boltuix.android import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.launch class NotesViewModel(application: Application) : AndroidViewModel(application) { // DataStore private val uiDataStore = UIModePreference(application) // get UI mode val getUIMode = uiDataStore.uiMode // save UI mode fun saveToDataStore(isNightMode: Boolean) { viewModelScope.launch(IO) { uiDataStore.saveToDataStore(isNightMode) } } }
0
Kotlin
0
2
e9a597922a5482b01909283832e628ee0ebbba58
617
Dark-theme-Material-Design
Apache License 2.0
debugger/src/main/kotlin/org/rust/debugger/settings/RsBreakOnPanicConfigurableUi.kt
nikolai-frolov
436,156,261
true
{"Kotlin": 9001687, "Rust": 126471, "Python": 90150, "HTML": 19230, "Lex": 12287, "Shell": 760, "Java": 688, "RenderScript": 89}
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.debugger.settings import com.intellij.ui.components.JBCheckBox import com.intellij.ui.layout.LayoutBuilder class RsBreakOnPanicConfigurableUi : RsDebuggerUiComponent() { private val breakOnPanicCheckBox: JBCheckBox = JBCheckBox("Break on panic", RsDebuggerSettings.getInstance().breakOnPanic) override fun reset(settings: RsDebuggerSettings) { breakOnPanicCheckBox.isSelected = settings.breakOnPanic } override fun isModified(settings: RsDebuggerSettings): Boolean = settings.breakOnPanic != breakOnPanicCheckBox.isSelected override fun apply(settings: RsDebuggerSettings) { settings.breakOnPanic = breakOnPanicCheckBox.isSelected } override fun buildUi(builder: LayoutBuilder) { with(builder) { row { breakOnPanicCheckBox() } } } }
1
null
0
0
c5369c809bdefd1f098ed4e3bb2244fa0f221a98
956
intellij-rust
MIT License
android/library-magiccube/src/main/java/com/hellobike/magiccube/model/rule/FontSizeRuleModel.kt
hellof2e
651,011,094
false
{"Kotlin": 499995, "Objective-C": 421129, "JavaScript": 39299, "Java": 29943, "Swift": 24514, "Ruby": 5345, "TypeScript": 3969, "Shell": 255}
package com.hellobike.magiccube.model.rule /** * * @Description: java类作用描述 * @Author: nikozxh * @CreateDate: 2021/2/2 4:58 PM */ class FontSizeRuleModel { }
3
Kotlin
9
60
8123fdaafa9ee7eaeee43fb73789b7fa3feac697
178
Wukong
Apache License 2.0
app/src/main/java/com/cesarwillymc/agrostest/common/Bindings.kt
cesarwillymc
392,344,387
false
null
package com.cesarwillymc.agrostest.common import android.view.View import android.widget.EditText import android.widget.ImageView import androidx.cardview.widget.CardView import androidx.databinding.BindingAdapter import com.bumptech.glide.Glide import com.cesarwillymc.agrostest.R @BindingAdapter("app:visibilityText") fun setVisibilty(view: View, isVisible: Boolean) { if (isVisible) { view.visibility = View.VISIBLE } else { view.visibility = View.GONE } } @BindingAdapter("app:errorText") fun setError(tInputLayout: EditText, str: String?) { if (str.isNullOrEmpty()) { tInputLayout.error = null } else { tInputLayout.error = str } } @BindingAdapter("app:enabledView") fun CardView.setEnabledView(enabled: Boolean) { this.isEnabled=enabled if(enabled){ setCardBackgroundColor(context.getColor(R.color.enabled)) }else{ setCardBackgroundColor(context.getColor(R.color.disable)) } } @BindingAdapter("imageUrl", requireAll = false) fun ImageView.imageUrl(url: String?) { Glide.with(this).load(url).placeholder(R.drawable.loading).error(R.drawable.nofound).into(this) }
0
Kotlin
0
0
8b8e63e33027431477462f28a2b1529decd75578
1,170
AgrosTest
Apache License 2.0
core/src/main/kotlin/org/rewedigital/dialog/model/google/Device.kt
rewe-digital-incubator
169,550,416
false
null
package org.rewedigital.dialog.model.google data class Device(val location: Location?) { data class Location( val coordinates: Coordinates?, val formattedAddress: String?, val zipCode: String?, val city: String?, val postalAddress: Any?, val name: String?, val phoneNumber: String?, val notes: String?, val placeId: String? ) { data class Coordinates( val latitude: Double?, val longitude: Double? ) } }
3
Kotlin
5
10
7ea2fac743323acd9e17f41eb4511df1782b874d
529
dialog
MIT License
client/android/ui-test-common/src/main/java/com/yandex/test/idling/SimpleIdlingResource.kt
divkit
523,491,444
false
{"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38}
package com.yandex.test.idling import android.content.ContentValues.TAG import android.os.Handler import android.os.Looper import android.util.Log import androidx.test.espresso.IdlingPolicies import androidx.test.espresso.IdlingResource abstract class SimpleIdlingResource( private val pollingIntervalMillis: Long = 1_000L, val description: String? = null ) : IdlingResource { private lateinit var resourceCallback: IdlingResource.ResourceCallback private lateinit var handler: Handler private val finishTime = System.currentTimeMillis() + with(IdlingPolicies.getDynamicIdlingResourceErrorPolicy()) { idleTimeoutUnit.toMillis(idleTimeout) } private var isIdle: Boolean = false override fun isIdleNow(): Boolean { handler.removeCallbacksAndMessages(null) if (isIdle) return true isIdle = checkIdle() Log.i(TAG, "$description idle: $isIdle timeout: $finishTime") if (isIdle) { resourceCallback.onTransitionToIdle() } else if (System.currentTimeMillis() + pollingIntervalMillis < finishTime) { handler.postDelayed({ isIdleNow }, pollingIntervalMillis) } return isIdle } protected abstract fun checkIdle(): Boolean override fun registerIdleTransitionCallback(resourceCallback: IdlingResource.ResourceCallback) { handler = Handler(Looper.getMainLooper()) this.resourceCallback = resourceCallback } override fun getName() = description ?: toString() }
5
Kotlin
128
2,240
dd102394ed7b240ace9eaef9228567f98e54d9cf
1,521
divkit
Apache License 2.0
src/main/kotlin/com/mthaler/aparser/dice/Roll.kt
mthaler
324,088,102
false
{"Kotlin": 39194}
package com.mthaler.aparser.dice interface Roll { fun d(sides: Int): Int }
0
Kotlin
0
0
c261caeb7c4261c56d8f37666e031162b73967a1
79
arithmetic-expression-parser
Apache License 2.0
src/applications/quantum/QuantumFourierTransform.kt
EtherTyper
114,335,931
false
null
package applications.quantum fun QFT(qubits: Int) = QuantumCircuit.circuit(qubits, { for (i in 0 until qubits) { applyGate(listOf(i), QuantumGate.H) for (j in i + 1 until qubits) { applyGate(listOf(j, i), QuantumGate.controlled( QuantumGate.R( (j - i + 1).toDouble() ) )) } } }).evaluate
1
Kotlin
0
5
415941464f2c59ce9df546e7881067be980f59e5
413
MathLibrary
MIT License
domain/src/commonMain/kotlin/space/compoze/hiero/domain/collectionitem/interactor/CollectionItemUpdateById.kt
Firely-Pasha
644,746,942
false
null
package space.compoze.hiero.domain.collectionitem.interactor import arrow.core.raise.either import space.compoze.hiero.domain.collectionitem.CollectionItemNotification import space.compoze.hiero.domain.collectionitem.CollectionItemNotifier import space.compoze.hiero.domain.collectionitem.CollectionItemRepository import space.compoze.hiero.domain.collectionitem.model.data.CollectionItemModel import space.compoze.hiero.domain.collectionitem.model.mutation.CollectionItemMutationData class CollectionItemUpdateById( private val collectionItemGetByIds: CollectionItemGetByIds, private val collectionItemRepository: CollectionItemRepository, private val collectionItemNotifier: CollectionItemNotifier, ) { operator fun invoke( collectionItemId: Long, data: CollectionItemMutationData, ) = either { val item = collectionItemGetByIds(listOf(collectionItemId)).bind().first() invoke(item, data).bind() } operator fun invoke( collectionItem: CollectionItemModel, data: CollectionItemMutationData, ) = either { collectionItemRepository.update(collectionItem.id, data).bind().also { collectionItemNotifier.notify( CollectionItemNotification.Changed(collectionItem, it) ) } } }
0
null
0
1
de86473ed3fa46647b1cb4db91987a1aa2848c78
1,314
hiero-japanese
MIT License
app/src/main/java/com/sandoval/bogosunny/data/AppApiHelper.kt
juanchosandox90
226,907,473
false
null
package com.sandoval.bogosunny.data import com.sandoval.bogosunny.data.network.ApiHelper import com.sandoval.bogosunny.data.network.ApiService import com.sandoval.bogosunny.data.network.model.forecast.Forecast import com.sandoval.bogosunny.data.network.model.weather.CurrentWeather import io.reactivex.Observable import javax.inject.Inject class AppApiHelper @Inject constructor( private val apiService: ApiService ) : ApiHelper { override fun getCurrentLocationWeather( lat: String, lon: String, appId: String, units: String ): Observable<CurrentWeather> { return apiService.getCurrentLocationWeather(lat, lon, appId, units) } override fun getCityWeather( cityName: String, appId: String, units: String ): Observable<CurrentWeather> { return apiService.getCityWeather(cityName, appId, units) } override fun getCurrentLocationForecast( lat: String, lon: String, appId: String, units: String, count: String ): Observable<Forecast> { return apiService.getCurrentLocationForecast(lat, lon, appId, units, count) } override fun getCityForecast( cityName: String, appId: String, units: String, count: String ): Observable<Forecast> { return apiService.getCityForecast(cityName, appId, units, count) } }
0
Kotlin
0
1
75787c095e17e8882d144f265254f1862c337802
1,414
BogoSunny
Apache License 2.0
app/src/main/java/io/github/yaraki/animateit/deck/s09container/CheeseCardFragment.kt
yaraki
232,034,207
false
{"Kotlin": 140014, "CSS": 105802, "HTML": 13600}
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.yaraki.animateit.deck.s09container import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import androidx.appcompat.widget.Toolbar import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.* import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.navigation.findNavController import androidx.navigation.fragment.FragmentNavigatorExtras import androidx.transition.Fade import androidx.transition.Transition import com.google.android.material.appbar.AppBarLayout import com.google.android.material.card.MaterialCardView import io.github.yaraki.animateit.R import io.github.yaraki.animateit.deck.DeckViewModel import io.github.yaraki.animateit.transition.FAST_OUT_LINEAR_IN import io.github.yaraki.animateit.transition.LARGE_COLLAPSE_DURATION import io.github.yaraki.animateit.transition.LARGE_EXPAND_DURATION import io.github.yaraki.animateit.transition.LINEAR_OUT_SLOW_IN class CheeseCardFragment : Fragment() { companion object { const val ARG_NAV = "nav" } private val viewModel: CheeseCardViewModel by viewModels() private val deckViewModel: DeckViewModel by activityViewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) exitTransition = Fade(Fade.OUT).apply { duration = LARGE_EXPAND_DURATION / 2 interpolator = FAST_OUT_LINEAR_IN } reenterTransition = Fade(Fade.IN).apply { duration = LARGE_COLLAPSE_DURATION / 2 startDelay = LARGE_COLLAPSE_DURATION / 2 interpolator = LINEAR_OUT_SLOW_IN } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.cheese_card_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val toolbar: Toolbar = view.findViewById(R.id.toolbar) val content: FrameLayout = view.findViewById(R.id.content) val card: MaterialCardView = view.findViewById(R.id.card) val cardContent: ConstraintLayout = view.findViewById(R.id.card_content) val image: ImageView = view.findViewById(R.id.image) val name: TextView = view.findViewById(R.id.name) ViewCompat.setOnApplyWindowInsetsListener(view.parent as View) { _, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) toolbar.updateLayoutParams<AppBarLayout.LayoutParams> { topMargin = systemBars.top } content.updatePadding( left = systemBars.left, right = systemBars.right, bottom = systemBars.bottom ) insets } ViewCompat.setTransitionName(card, "card") ViewGroupCompat.setTransitionGroup(cardContent, true) viewModel.cheese.observe(viewLifecycleOwner) { cheese -> name.text = cheese.name image.setImageResource(cheese.image) } val nav = arguments?.getBoolean(ARG_NAV, true) ?: true deckViewModel.slowContainer.observe(viewLifecycleOwner) { slow -> if (slow) { (exitTransition as? Transition)?.duration = (LARGE_EXPAND_DURATION / 2) * 10 (reenterTransition as? Transition)?.run { duration = (LARGE_COLLAPSE_DURATION / 2) * 10 startDelay = (LARGE_COLLAPSE_DURATION / 2) * 10 } } else { (exitTransition as? Transition)?.duration = LARGE_EXPAND_DURATION / 2 (reenterTransition as? Transition)?.run { duration = LARGE_COLLAPSE_DURATION / 2 startDelay = LARGE_COLLAPSE_DURATION / 2 } } } card.setOnClickListener { v -> if (nav) { v.findNavController().navigate( CheeseCardFragmentDirections.actionArticle(), FragmentNavigatorExtras( card to CheeseArticleFragment.TRANSITION_NAME_BACKGROUND ) ) } } } }
0
Kotlin
1
59
e828bb5809379bd0933f26267d9047afce6e890a
5,110
AnimateIt
Apache License 2.0
app/src/main/java/com/example/car_builder/ViewModels/CarPartViewModel.kt
EikeMB
700,591,077
false
{"Kotlin": 92113}
package com.example.car_builder.ViewModels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.car_builder.CRUD.CarPartRepository import com.example.car_builder.CarPart import com.example.car_builder.PartType import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch class CarPartViewModel(private val carPartRepository: CarPartRepository): ViewModel() { private val _typeParts = MutableStateFlow(listOf<CarPart>()) val typeParts: StateFlow<List<CarPart>> = _typeParts.asStateFlow() private val _allParts = MutableStateFlow(listOf<CarPart>()) val allParts: StateFlow<List<CarPart>> = _allParts.asStateFlow() private val _activePart = MutableStateFlow(CarPart("", "", 0, "", PartType.Body, 0)) val activePart: StateFlow<CarPart> = _activePart.asStateFlow() suspend fun getPartsOfType(type: PartType){ viewModelScope.launch { carPartRepository.getPartsOfType(type).collect() {typeParts -> _typeParts.value = typeParts } } } suspend fun getAllParts(){ viewModelScope.launch { carPartRepository.getParts().collect() { parts -> _allParts.value = parts } } } suspend fun getPart(part: CarPart){ viewModelScope.launch { carPartRepository.getPart(part.name).collect() { part -> _activePart.value = part } } } fun addPart(part: CarPart){ viewModelScope.launch { carPartRepository.addCarPart(part) } } fun deletePart(part: CarPart){ viewModelScope.launch { carPartRepository.delete(part) } } }
3
Kotlin
0
0
a7833fed4b4408ab743bae9658eb067178e18dd9
1,832
AppDev2_Project
MIT License
app/src/test/kotlin/no/nav/k9punsj/rest/eksternt/k9sak/TestK9SakService.kt
navikt
216,808,662
false
null
package no.nav.k9punsj.rest.eksternt.k9sak import no.nav.k9punsj.TestProfil import no.nav.k9punsj.felles.FagsakYtelseType import no.nav.k9punsj.felles.dto.ArbeidsgiverMedArbeidsforholdId import no.nav.k9punsj.felles.dto.PeriodeDto import no.nav.k9punsj.integrasjoner.k9sak.Fagsak import no.nav.k9punsj.integrasjoner.k9sak.K9SakService import org.springframework.stereotype.Component @Component @TestProfil internal class TestK9SakService : K9SakService { override suspend fun hentPerioderSomFinnesIK9( søker: String, barn: String, fagsakYtelseType: FagsakYtelseType ): Pair<List<PeriodeDto>?, String?> = Pair(emptyList(), null) override suspend fun hentArbeidsforholdIdFraInntektsmeldinger( søker: String, fagsakYtelseType: FagsakYtelseType, periodeDto: PeriodeDto ): Pair<List<ArbeidsgiverMedArbeidsforholdId>?, String?> { // simulerer svar på denne return if (søker == "02020050123") { Pair(listOf(ArbeidsgiverMedArbeidsforholdId("randomOrgNummer", listOf("randomArbeidsforholdId"))), null) } else { Pair(emptyList(), null) } } override suspend fun hentFagsaker(søker: String): Pair<Set<Fagsak>?, String?> = Pair( first = setOf( Fagsak(saksnummer = "ABC123", no.nav.k9.kodeverk.behandling.FagsakYtelseType.PLEIEPENGER_SYKT_BARN, null), Fagsak(saksnummer = "DEF456", no.nav.k9.kodeverk.behandling.FagsakYtelseType.PLEIEPENGER_NÆRSTÅENDE, null), Fagsak(saksnummer = "GHI789", no.nav.k9.kodeverk.behandling.FagsakYtelseType.OMSORGSPENGER_KS, null) ), second = null ) }
9
Kotlin
2
1
7993f85b435e54a1ef9a676e76e598ead2b7df66
1,664
k9-punsj
MIT License
app/src/main/java/com/nab/weatherforecast/ui/DailyForecastViewHolder.kt
phuongnguyen2302
517,059,024
false
null
package com.nab.weatherforecast.ui import androidx.recyclerview.widget.RecyclerView import com.nab.weatherforecast.databinding.DailyForecastItemBinding class DailyForecastViewHolder(private val binding: DailyForecastItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(itemModel: DailyForecastItemViewModel) { binding.itemModel = itemModel binding.executePendingBindings() } }
0
Kotlin
0
0
76179d8c809481a633e4dab8084365d51e4d2cd4
419
weather_forecast
Apache License 2.0
app/src/main/java/com/bth/reciperadar/presentation/screens/inventoryscreen/InventoryScreen.kt
BryanAafjes
718,555,578
false
{"Kotlin": 284855}
package com.bth.reciperadar.presentation.screens.inventoryscreen import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.bth.reciperadar.domain.controllers.IngredientController import com.bth.reciperadar.domain.controllers.InventoryController import com.bth.reciperadar.presentation.viewmodels.IngredientViewModel import com.bth.reciperadar.presentation.viewmodels.InventoryViewModel import com.bth.reciperadar.presentation.viewmodels.toDomain import com.bth.reciperadar.presentation.viewmodels.toViewModel import com.bth.reciperadar.ui.theme.WarningRed import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @Composable fun InventoryScreen( ingredientController: IngredientController, inventoryController: InventoryController ) { var searchText by remember { mutableStateOf( "") } var inventory by remember { mutableStateOf<InventoryViewModel?>(InventoryViewModel("", "", emptyList())) } var ingredients by remember { mutableStateOf<List<IngredientViewModel>>(emptyList()) } var isIngredientFound by remember { mutableStateOf( true) } val state = rememberScrollState() LaunchedEffect(Unit) { withContext(Dispatchers.IO) { try { val inventoryModel = inventoryController.getInventory() if (inventoryModel != null) { inventory = inventoryModel.toViewModel() ingredients = inventory?.ingredients ?: emptyList() } } catch (e: Exception) { e.printStackTrace() } } } DisposableEffect(Unit) { onDispose { CoroutineScope(Dispatchers.IO).launch { try { if (inventory != null) { inventory!!.ingredients = ingredients inventoryController.createOrUpdateInventory(inventory?.toDomain()!!) } } catch (e: Exception) { e.printStackTrace() } } } } if (inventory != null) { Column( modifier = Modifier .padding(horizontal = 20.dp) .fillMaxHeight() .fillMaxWidth() .verticalScroll(state) ) { Text( text = "Inventory", color = MaterialTheme.colorScheme.onBackground, textAlign = TextAlign.Start, fontSize = 30.sp, fontWeight = FontWeight.Bold, modifier = Modifier .fillMaxWidth() .padding(vertical = 20.dp) ) OutlinedTextField( value = searchText, onValueChange = { searchText = it }, placeholder = { Text(text = "Type ingredient name to add:") }, singleLine = true, trailingIcon = { IconButton(onClick = { CoroutineScope(Dispatchers.IO).launch { try { val foundIngredient = ingredientController.searchIngredientsByName(searchText) if (foundIngredient != null) { ingredients = ingredients.plus(foundIngredient.toViewModel()) isIngredientFound = true } else { isIngredientFound = false } searchText = "" } catch (e: Exception) { e.printStackTrace() } } }) { Icon( imageVector = Icons.Default.Check, contentDescription = "search_icon" ) } }, shape = RoundedCornerShape(20.dp, 20.dp, 20.dp, 20.dp), colors = OutlinedTextFieldDefaults.colors(focusedBorderColor = MaterialTheme.colorScheme.primary), modifier = Modifier .fillMaxWidth() .padding(bottom = 10.dp) ) if (!isIngredientFound) { Card( modifier = Modifier.align(Alignment.CenterHorizontally), colors = CardDefaults.cardColors(containerColor = WarningRed) ) { Text( "Ingredient not found, please try again.", modifier = Modifier.align(Alignment.CenterHorizontally).padding(10.dp) ) } } Row( modifier = Modifier.fillMaxWidth() ) { IngredientList( ingredientList = ingredients, onIngredientRemove = { ingredient -> ingredients = ingredients.minus(ingredient) } ) } } } }
0
Kotlin
0
0
41498c9ca684e2f3511e99801dd8bd0d21a9e8d3
6,667
RecipeRadar
MIT License
app/src/main/java/com/redeyesncode/thinklogical/onboard/MainActivity.kt
RedEyesNCode
510,875,627
false
null
package com.redeyesncode.thinklogical.onboard import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import androidx.appcompat.app.AppCompatActivity import androidx.viewpager.widget.PagerAdapter import androidx.viewpager.widget.ViewPager.OnPageChangeListener import com.redeyesncode.thinklogical.R import com.redeyesncode.thinklogical.auth.LoginActivity import com.redeyesncode.thinklogical.databinding.ActivityIntroBinding class MainActivity : AppCompatActivity() { private lateinit var binding:ActivityIntroBinding private var layouts: IntArray = intArrayOf( R.layout.intro_one_layout, R.layout.intro_one_layout, R.layout.intro_one_layout, R.layout.intro_one_layout) private var dots: Array<ImageView?> = arrayOfNulls<ImageView>(layouts.size) private var myViewPagerAdapter: MyViewPagerAdapter = MyViewPagerAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityIntroBinding.inflate(layoutInflater) setContentView(binding.root) initView() } private fun initView() { binding.pager.adapter =myViewPagerAdapter binding.pager.addOnPageChangeListener(viewPageChangeListener) // layouts of all welcome sliders binding.btnGetStarted.setOnClickListener { var intentLogin = Intent(this@MainActivity,LoginActivity::class.java) startActivity(intentLogin) finish() } addBottomDots(0) } private fun addBottomDots(currentPage: Int) { val layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) layoutParams.gravity = Gravity.CENTER_VERTICAL layoutParams.setMargins(2, 0, 2, 0) binding.layoutDots.removeAllViews() for (i in dots.indices) { dots[i] = ImageView(this) dots[i]!!.setBackground(resources.getDrawable(R.drawable.dot_in_active)) dots[i]!!.setScaleX(0.8.toFloat()) dots[i]!!.setScaleY(0.8.toFloat()) dots[i]!!.setLayoutParams(layoutParams) binding.layoutDots.addView(dots[i]) } if (dots.size > 0) dots[currentPage]!!.setBackground(resources.getDrawable(R.drawable.dot_active)) } var viewPageChangeListener: OnPageChangeListener = object : OnPageChangeListener { override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { } override fun onPageSelected(position: Int) { addBottomDots(position) if (position == 3) { binding.btnGetStarted.text = "Login >" } else { binding.btnGetStarted.text = "Skip" } } override fun onPageScrollStateChanged(state: Int) {} } /** * View pager adapter */ inner class MyViewPagerAdapter : PagerAdapter() { private var layoutInflater: LayoutInflater? = null override fun instantiateItem(container: ViewGroup, position: Int): Any { layoutInflater = this@MainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater? val view: View = layoutInflater!!.inflate(layouts.get(position), container, false) container.addView(view) return view } override fun getCount(): Int { return layouts.size } override fun isViewFromObject(view: View, obj: Any): Boolean { return view === obj } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { val view = `object` as View container.removeView(view) } } }
0
Kotlin
0
0
4b6172e985ed918376b1279927e1b838e189ecdc
4,049
illogical-crash
Apache License 2.0
presentation/src/main/java/ir/fallahpoor/enlightened/presentation/searchnews/view/SearchNewsFragment.kt
MasoodFallahpoor
166,662,510
false
null
package ir.fallahpoor.enlightened.presentation.searchnews.view import android.app.Activity import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.Toast import androidx.appcompat.widget.SearchView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import ir.fallahpoor.enlightened.R import ir.fallahpoor.enlightened.presentation.app.App import ir.fallahpoor.enlightened.presentation.common.EndlessOnScrollListener import ir.fallahpoor.enlightened.presentation.newslist.model.NewsModel import ir.fallahpoor.enlightened.presentation.searchnews.di.DaggerSearchNewsComponent import ir.fallahpoor.enlightened.presentation.searchnews.view.state.* import ir.fallahpoor.enlightened.presentation.searchnews.viewmodel.SearchNewsViewModel import ir.fallahpoor.enlightened.presentation.searchnews.viewmodel.SearchNewsViewModelFactory import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.fragment_search_news.* import javax.inject.Inject class SearchNewsFragment : Fragment() { @Inject lateinit var searchNewsViewModelFactory: SearchNewsViewModelFactory private lateinit var searchNewsViewModel: SearchNewsViewModel private var newsAdapter = NewsAdapter() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(R.layout.fragment_search_news, container, false) override fun onActivityCreated(savedInstanceState: Bundle?) { injectViewModel() super.onActivityCreated(savedInstanceState) setupRecyclerView() setupViewModel(savedInstanceState != null) subscribeToViewModel() setupSearchView() } private fun injectViewModel() { DaggerSearchNewsComponent.builder() .appComponent((activity?.application as App).appComponent) .build() .inject(this) } private fun setupRecyclerView() { with(searchResultsRecyclerView) { layoutManager = LinearLayoutManager(context) adapter = newsAdapter addOnScrollListener(object : EndlessOnScrollListener(layoutManager as LinearLayoutManager) { override fun onLoadMore() { searchNewsViewModel.searchMoreNews() } }) } } private fun setupViewModel(isActivityRestored: Boolean) { searchNewsViewModel = ViewModelProviders.of(this, searchNewsViewModelFactory) .get(SearchNewsViewModel::class.java) if (isActivityRestored) { searchNewsViewModel.adjustState() } } private fun subscribeToViewModel() { searchNewsViewModel.getViewStateLiveData().observe( this, Observer { viewState -> run { hideLoading() when (viewState) { is LoadingState -> showLoading() is DataLoadedState -> renderNews(viewState.news) is LoadDataErrorState -> renderLoadNewsError(viewState.errorMessage) is MoreDataLoadedState -> renderMoreNews(viewState.news) is LoadMoreDataErrorState -> renderLoadMoreNewsError(viewState.errorMessage) } } }) } private fun setupSearchView() { searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { searchNewsViewModel.searchNews(query!!) hideKeyboard() return true } override fun onQueryTextChange(newText: String?): Boolean { return true } }) } private fun hideKeyboard() { val imm: InputMethodManager = context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view?.rootView?.windowToken, 0) view?.clearFocus() } private fun showLoading() { loading.visibility = View.VISIBLE } private fun hideLoading() { loading.visibility = View.INVISIBLE } private fun renderNews(newsList: List<NewsModel>) { if (newsList.isEmpty()) { noResultTextView.visibility = View.VISIBLE noResultTextView.text = getString(R.string.no_search_result_formatted, searchView.query) } else { noResultTextView.visibility = View.GONE newsAdapter = createNewsAdapter(newsList) searchResultsRecyclerView.adapter = newsAdapter } tryAgainView.visibility = View.GONE } private fun renderLoadNewsError(errorMessage: String) { noResultTextView.visibility = View.GONE tryAgainView.setErrorMessage(errorMessage) tryAgainView.setTryAgainButtonClickListener( View.OnClickListener { searchNewsViewModel.searchNews(searchView.query.toString()) }) tryAgainView.visibility = View.VISIBLE } private fun renderMoreNews(news: List<NewsModel>) { newsAdapter.addNews(news.minus(newsAdapter.getNews())) } private fun renderLoadMoreNewsError(errorMessage: String) { Toast.makeText(activity, errorMessage, Toast.LENGTH_SHORT).show() } private fun createNewsAdapter(newsList: List<NewsModel>) = NewsAdapter(newsList) { news: NewsModel -> navHostFragment.findNavController().navigate( SearchNewsFragmentDirections.actionSearchNewsFragmentToNewsDetailsFragment(news.url) ) } }
0
Kotlin
0
0
d772ca3d0a8e7d15769a36398186ab13c7bc6e30
5,995
Enlightened
Apache License 2.0
app/src/test/kotlin/kt/school/starlord/model/data/room/converter/PriceConverterTest.kt
suhocki
174,985,255
false
null
package kt.school.starlord.model.data.room.converter import androidx.test.ext.junit.runners.AndroidJUnit4 import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import io.mockk.every import io.mockk.mockk import kt.school.starlord.domain.entity.product.Price import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.koin.test.AutoCloseKoinTest import org.koin.test.mock.declare import org.mockito.ArgumentMatchers @RunWith(AndroidJUnit4::class) class PriceConverterTest : AutoCloseKoinTest() { private val moshi: Moshi = mockk() private val adapter = mockk<JsonAdapter<Price>>() private val converter by lazy { PriceConverter() } @Before fun setUp() { declare { single { moshi } } every { moshi.adapter(Price::class.java) } returns adapter } @Test fun `from Room type`() { // Given val json = ArgumentMatchers.anyString() val price: Price = mockk() every { adapter.fromJson(json) } returns price // When val result = converter.fromRoomType(json) // Then assert(result == price) } @Test fun `to Room type`() { // Given val json = ArgumentMatchers.anyString() val price: Price = mockk() every { adapter.toJson(price) } returns json // When val result = converter.toRoomType(price) // Then assert(result == json) } }
19
Kotlin
0
1
09a3bb151a3dfe6982adf7ca246f8b0b077e3644
1,486
starlord
MIT License
app/src/main/java/com/example/coinmarket/view/MarketAdapter.kt
MohsenJafaritadi
751,207,258
false
{"Kotlin": 27832}
package com.example.coinmarket.view.marketActivity import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.lifecycle.LiveData import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.coinmarket.R import com.example.coinmarket.model.apiManager.BASE_URL_IMAGE import com.example.coinmarket.model.CoinsData import com.example.coinmarket.databinding.ItemRecyclerMarketBinding class MarketAdapter( private val data: List<CoinsData.Data>, private val recyclerCallback: RecyclerCallback, ) : RecyclerView.Adapter<MarketAdapter.MarketViewHolder>() { lateinit var binding: ItemRecyclerMarketBinding inner class MarketViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { @SuppressLint("ResourceAsColor") fun binViews(dataCoin: CoinsData.Data) { binding.txtCoinMain.text = dataCoin.coinInfo.fullName if (dataCoin.dISPLAY != null) binding.txtPrice.text = dataCoin.dISPLAY.uSD?.pRICE if (dataCoin.rAW?.uSD?.cHANGE24HOUR != null) { val taghit = dataCoin.rAW.uSD.cHANGE24HOUR if (taghit > 0) { binding.txtTaghir.setTextColor( ContextCompat.getColor( binding.root.context, R.color.colorGain ) ) binding.txtTaghir.text = dataCoin.rAW.uSD.cHANGE24HOUR.toString().substring(0, 4) + "%" } else if (taghit < 0) { binding.txtTaghir.setTextColor( ContextCompat.getColor( binding.root.context, R.color.colorLoss ) ) binding.txtTaghir.text = dataCoin.rAW.uSD.cHANGE24HOUR.toString().substring(0, 5) + "%" } else { binding.txtTaghir.text = "0%" } } val marketCap = dataCoin.rAW?.uSD?.mKTCAP?.div(1000000000) val indexDot = marketCap.toString().indexOf('.') try { binding.txtMarketCap.text = "$" + dataCoin.rAW?.uSD?.mKTCAP.toString().substring(0, indexDot + 3) + "B " } catch (e: Exception) { } Glide .with(itemView) .load(BASE_URL_IMAGE + dataCoin.coinInfo.imageUrl) .into(binding.imgItem) itemView.setOnClickListener { recyclerCallback.onCoinItemClicked(dataCoin) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MarketViewHolder { val inflater = LayoutInflater.from(parent.context) binding = ItemRecyclerMarketBinding.inflate(inflater, parent, false) return MarketViewHolder(binding.root) } override fun onBindViewHolder(holder: MarketViewHolder, position: Int) { holder.binViews(data[position]) } override fun getItemCount(): Int = data.size interface RecyclerCallback { fun onCoinItemClicked(coinsData: CoinsData.Data) { } } }
0
Kotlin
0
0
e4345cd847e6fb49a3641df00ee8e214aa2dc03f
3,393
CoinMarket
MIT License
uniflow-androidx/src/main/java/io/uniflow/androidx/flow/DataFlowObserver.kt
Dollym89
299,012,928
true
{"Kotlin": 106492, "Shell": 236}
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.uniflow.androidx.flow import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.Observer import io.uniflow.core.flow.data.Event import io.uniflow.core.flow.data.UIEvent import io.uniflow.core.flow.data.UIState import io.uniflow.core.logger.UniFlowLogger /** * DataFlow Observers for states & events * * @author Arnaud Giuliani */ /** * Listen incoming states (UIState) on given AndroidDataFlow */ fun LifecycleOwner.onStates(vm: AndroidDataFlow, handleStates: (UIState) -> Unit) { vm.dataPublisher.states.observe(this, Observer { state: UIState? -> state?.let { UniFlowLogger.debug("onStates - $this <- $state") handleStates(state) } }) } /** * Listen incoming events (Event<UIEvent>) on given AndroidDataFlow */ fun LifecycleOwner.onEvents(vm: AndroidDataFlow, handleEvents: (Event<*>) -> Unit) { vm.dataPublisher.events.observe(this, Observer { event -> event?.let { UniFlowLogger.debug("onEvents - $this <- $event") handleEvents(event) } }) } /** * Listen incoming events & `peek` them (UIEvent) on given AndroidDataFlow */ fun LifecycleOwner.onPeekEvents(vm: AndroidDataFlow, handleEvents: (UIEvent) -> Unit) { vm.dataPublisher.events.observe(this, Observer { event -> event?.let { event.peek().let { UniFlowLogger.debug("onPeekEvents - $this <- $event") handleEvents(it) } } }) } /** * Listen incoming events & `take` them (UIEvent) on given AndroidDataFlow */ fun LifecycleOwner.onTakeEvents(vm: AndroidDataFlow, handleEvents: (UIEvent) -> Unit) { vm.dataPublisher.events.observe(this, Observer { event -> event?.let { event.take()?.let { UniFlowLogger.debug("onTakeEvents - $this <- $event") handleEvents(it) } } }) }
0
null
0
0
36d2914e1588470c5f904b5707a463d5802adf45
2,534
uniflow-kt
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/ecs/patterns/ApplicationMultipleTargetGroupsFargateServiceDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.ecs.patterns import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.String import kotlin.Unit import software.amazon.awscdk.services.ecs.patterns.ApplicationMultipleTargetGroupsFargateService import software.amazon.awscdk.services.ecs.patterns.ApplicationMultipleTargetGroupsFargateServiceProps import software.constructs.Construct @Generated public fun Construct.applicationMultipleTargetGroupsFargateService(id: String): ApplicationMultipleTargetGroupsFargateService = ApplicationMultipleTargetGroupsFargateService(this, id) @Generated public fun Construct.applicationMultipleTargetGroupsFargateService(id: String, initializer: @AwsCdkDsl ApplicationMultipleTargetGroupsFargateService.() -> Unit): ApplicationMultipleTargetGroupsFargateService = ApplicationMultipleTargetGroupsFargateService(this, id).apply(initializer) @Generated public fun Construct.applicationMultipleTargetGroupsFargateService(id: String, props: ApplicationMultipleTargetGroupsFargateServiceProps): ApplicationMultipleTargetGroupsFargateService = ApplicationMultipleTargetGroupsFargateService(this, id, props) @Generated public fun Construct.applicationMultipleTargetGroupsFargateService( id: String, props: ApplicationMultipleTargetGroupsFargateServiceProps, initializer: @AwsCdkDsl ApplicationMultipleTargetGroupsFargateService.() -> Unit, ): ApplicationMultipleTargetGroupsFargateService = ApplicationMultipleTargetGroupsFargateService(this, id, props).apply(initializer) @Generated public fun Construct.buildApplicationMultipleTargetGroupsFargateService(id: String, initializer: @AwsCdkDsl ApplicationMultipleTargetGroupsFargateService.Builder.() -> Unit): ApplicationMultipleTargetGroupsFargateService = ApplicationMultipleTargetGroupsFargateService.Builder.create(this, id).apply(initializer).build()
1
Kotlin
0
0
b22e397ff37c5fce365a5430790e5d83f0dd5a64
1,926
aws-cdk-kt
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/animate/ClearSkyAnimation.kt
maheshwari-e
348,775,071
false
null
package com.example.androiddevchallenge.animate import androidx.compose.animation.core.* import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.R @Composable fun ClearSkyBackground(){ Image( painter = painterResource(id = R.drawable.ic_clear_sky_bg), contentDescription = null, modifier = Modifier.testTag("Clear Sky Background").fillMaxSize(), contentScale = ContentScale.Crop ) } @Composable fun ClearSkyAnimation(){ Box( modifier = Modifier.testTag("Clear Sky Animation") .height(250.dp) .fillMaxWidth() ) { SparklingStar(image = R.drawable.ic_star_bg1) SparklingStar(delayMillis = 150, modifier = Modifier .align(Alignment.TopCenter) .padding(top = 20.dp, end = 20.dp), image = R.drawable.ic_star_bg2) SparklingStar(image = R.drawable.ic_star_bg3, modifier = Modifier .align(Alignment.TopEnd) .padding(end = 50.dp), delayMillis = 300 ) SparklingStar(image = R.drawable.ic_star_bg1, modifier = Modifier.align(Alignment.Center), delayMillis = 600) SparklingStar(image = R.drawable.ic_star_bg2, modifier = Modifier .align(Alignment.CenterStart) .padding(start = 50.dp, bottom = 50.dp), delayMillis = 800) SparklingStar(image = R.drawable.ic_star_bg3, modifier = Modifier .align(Alignment.CenterEnd) .padding(end = 50.dp, top = 50.dp)) SparklingStar( image = R.drawable.ic_star_bg1, modifier = Modifier.align(Alignment.BottomEnd), delayMillis = 150 ) SparklingStar( image = R.drawable.ic_star_bg2, modifier = Modifier .align(Alignment.BottomCenter) .padding(start = 20.dp, bottom = 20.dp), delayMillis = 300 ) SparklingStar( image = R.drawable.ic_star_bg3, modifier = Modifier .align(Alignment.BottomStart) .padding(start = 50.dp), delayMillis = 600 ) SparklingStar(image = R.drawable.ic_star_bg1, delayMillis = 800) } } @Composable fun SparklingStar(modifier: Modifier = Modifier, delayMillis: Int = 0, image: Int) { val infiniteTransition = rememberInfiniteTransition() val scale by infiniteTransition.animateFloat( initialValue = 0f, targetValue = 1f, animationSpec = infiniteRepeatable( animation = tween( durationMillis = 2000, delayMillis = delayMillis ), repeatMode = RepeatMode.Reverse ) ) Image( painter = painterResource(id = image), contentDescription = null, modifier = modifier .size(20.dp) .graphicsLayer( scaleX = scale, scaleY = scale ) ) }
0
Kotlin
0
0
e88a7bd7361b69db4ecf847422d39a0bd46289e0
3,519
week4-jetpack-compose-challenge
Apache License 2.0
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/carousel/CarouselState.kt
androidx
256,589,781
false
{"Kotlin": 101448370, "Java": 64375670, "C++": 9133578, "AIDL": 605967, "Python": 310682, "Shell": 187759, "TypeScript": 40586, "HTML": 32277, "Groovy": 25622, "Svelte": 20307, "ANTLR": 19860, "CMake": 18003, "C": 16982, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3.carousel import androidx.annotation.FloatRange import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.gestures.ScrollScope import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.foundation.pager.PagerState import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable /** * The state that can be used to control all types of carousels. * * @param currentItem the current item to be scrolled to. * @param currentItemOffsetFraction the offset of the current item as a fraction of the item's size. * This should vary between -0.5 and 0.5 and indicates how to offset the current item from the * snapped position. * @param itemCount the number of items this Carousel will have. */ @ExperimentalMaterial3Api class CarouselState( currentItem: Int = 0, @FloatRange(from = -0.5, to = 0.5) currentItemOffsetFraction: Float = 0f, itemCount: () -> Int ) : ScrollableState { var itemCountState = mutableStateOf(itemCount) internal var pagerState: PagerState = PagerState(currentItem, currentItemOffsetFraction, itemCountState.value) override val isScrollInProgress: Boolean get() = pagerState.isScrollInProgress override fun dispatchRawDelta(delta: Float): Float { return pagerState.dispatchRawDelta(delta) } override suspend fun scroll( scrollPriority: MutatePriority, block: suspend ScrollScope.() -> Unit ) { pagerState.scroll(scrollPriority, block) } @ExperimentalMaterial3Api companion object { /** * To keep current item and item offset saved */ val Saver: Saver<CarouselState, *> = listSaver( save = { listOf( it.pagerState.currentPage, it.pagerState.currentPageOffsetFraction, it.pagerState.pageCount, ) }, restore = { CarouselState( currentItem = it[0] as Int, currentItemOffsetFraction = it[1] as Float, itemCount = { it[2] as Int }, ) } ) } } /** * Creates a [CarouselState] that is remembered across compositions. * * @param initialItem The initial item that should be scrolled to. * @param itemCount The number of items this Carousel will have. */ @ExperimentalMaterial3Api @Composable fun rememberCarouselState( initialItem: Int = 0, itemCount: () -> Int, ): CarouselState { return rememberSaveable(saver = CarouselState.Saver) { CarouselState( currentItem = initialItem, currentItemOffsetFraction = 0F, itemCount = itemCount ) }.apply { itemCountState.value = itemCount } } /** * Interface to hold information about a Carousel item and its size. * * Example of CarouselItemInfo usage: * @sample androidx.compose.material3.samples.FadingHorizontalMultiBrowseCarouselSample */ @ExperimentalMaterial3Api sealed interface CarouselItemInfo { /** The size of the carousel item in the main axis */ val size: Float /** * The minimum size in the main axis of the carousel item, eg. the size of the item when it * scrolls off the sides of the carousel */ val minSize: Float /** * The maximum size in the main axis of the carousel item, eg. the size of the item when it is * at a focal position */ val maxSize: Float } /** * Gets the start offset of the carousel item from its full size. This offset can be used to pin any * carousel item content to the left side of the item (or right if RTL). */ @OptIn(ExperimentalMaterial3Api::class) fun CarouselItemInfo.startOffset(): Float { return (maxSize - size) / 2f } /** * Gets the end offset of the carousel item from its full size. This offset can be used to pin any * carousel item content to the right side of the item (or left if RTL). */ @OptIn(ExperimentalMaterial3Api::class) fun CarouselItemInfo.endOffset(): Float { return maxSize - (maxSize - size) / 2f } @OptIn(ExperimentalMaterial3Api::class) internal class CarouselItemInfoImpl : CarouselItemInfo { val sizeState = mutableFloatStateOf(0f) override val size: Float get() = sizeState.floatValue val minSizeState = mutableFloatStateOf(0f) override val minSize: Float get() = minSizeState.floatValue val maxSizeState = mutableFloatStateOf(0f) override val maxSize: Float get() = maxSizeState.floatValue override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is CarouselItemInfoImpl) return false if (sizeState != other.sizeState) return false if (minSizeState != other.minSizeState) return false if (maxSizeState != other.maxSizeState) return false return true } override fun hashCode(): Int { var result = sizeState.hashCode() result = 31 * result + minSizeState.hashCode() result = 31 * result + maxSizeState.hashCode() return result } }
25
Kotlin
918
5,019
063c6938121b19f73d04517b1e7fdcb9e3309403
6,086
androidx
Apache License 2.0
app/src/main/java/me/boger/geographic/core/AppConfiguration.kt
bogerchan
103,030,572
false
null
package me.boger.geographic.core import android.content.Context import android.graphics.Typeface import android.util.DisplayMetrics import android.util.TypedValue import me.boger.geographic.util.Timber /** * Created by BogerChan on 2017/6/26. */ object AppConfiguration { var screenWidth: Int = 0 var screenHeight: Int = 0 var primaryTypeface: Typeface = Typeface.DEFAULT var iconFont: Typeface = Typeface.DEFAULT private var displayMetrics: DisplayMetrics? = null fun init(context: Context) { val metrics = context.applicationContext.resources.displayMetrics screenWidth = metrics.widthPixels screenHeight = metrics.heightPixels displayMetrics = metrics try { primaryTypeface = Typeface.createFromAsset(context.applicationContext.assets, "font/HYRunYuan-35W.ttf") iconFont = Typeface.createFromAsset(context.applicationContext.assets, "font/iconfont.ttf") } catch (e: Exception) { Timber.e(e) } } fun dp2px(dp: Int): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), displayMetrics) }
0
Kotlin
3
11
60f93464110f9763da7a6c799577cbafbd90fdb6
1,143
National-Geography
Apache License 2.0
app/src/main/java/com/jefftrotz/fitnesstracker/ui/screens/exercise/CreateExerciseScreen.kt
jmtrotz
517,871,632
false
{"Kotlin": 100631}
package com.jefftrotz.fitnesstracker.ui.screens.exercise import androidx.compose.runtime.Composable import androidx.navigation.NavController @Composable fun CreateExerciseScreen(navController: NavController) { }
0
Kotlin
0
0
23c73d1ce91b7cb0cd2a527f3bd05fc9f1596392
214
Fitness-Tracker-App
Apache License 2.0
boutique/src/shoppingcart/Inventory.kt
paalfb
173,618,465
false
null
package shoppingcart class Inventory { companion object { private var inventory: MutableList<ItemQuantity> = mutableListOf() fun buildInventory(cleanup: Boolean) { if (cleanup) inventory.clear() inventory.add(30.bread) inventory.add(40.juice) inventory.add(50.chocolate) inventory.add(34.coffee) inventory.add(14.strawberryJam) inventory.add(24.cheese) inventory.add(100.eggs) } fun addItems(items: ItemQuantity) { when { (inventory.containsItem(items.item)) -> { inventory.set( inventory.indexOf(inventory[inventory.getKey(items.item)]), ItemQuantity(inventory[inventory.getKey(items.item)].qty + items.qty, inventory[inventory.getKey(items.item)].item)) } (!inventory.contains((items))) -> inventory.add(items) } } fun removeItems(other: ItemQuantity) { when { (this.inventory.containsItem(other.item)) -> { when { (this.inventory[this.inventory.getKey(other.item)].qty > other.qty) -> { this.inventory.set( this.inventory.indexOf(this.inventory[this.inventory.getKey(other.item)]), ItemQuantity(this.inventory[this.inventory.getKey(other.item)].qty - other.qty, this.inventory[this.inventory.getKey(other.item)].item)) } (this.inventory[this.inventory.getKey(other.item)].qty <= other.qty) -> { this.inventory.removeAt(this.inventory.getKey(other.item)) } } } } } fun itemCount(item: Item): Int { return if ((!inventory.isEmpty()) && inventory.containsItem(item)) this.items(item) else 0 } private fun items(item: Item): Int = inventory.get(inventory.getKey(item)).qty private fun MutableList<ItemQuantity>.containsItem(other: Item): Boolean { val filtered = this.filter { vareBeholdning: ItemQuantity -> vareBeholdning.erVareType(other) }.size return filtered > 0 } private fun MutableList<ItemQuantity>.getKey(other: Item): Int { val iterator = this.listIterator() var index: Int = 0 while (iterator.hasNext()) { val el = iterator.next().item.equals(other) when { el -> return index } index += 1 } return -1 } } }
0
Kotlin
0
1
0e678b5d2b5d603278a920567daa9efd4802e65a
2,911
Boutique
MIT License
app/src/main/java/com/example/clubdeportivo/screens/HomeUserScreen.kt
tiago-appdev
803,323,597
false
{"Kotlin": 38452}
package com.example.clubdeportivo.screens import android.annotation.SuppressLint import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Button import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.NavController import androidx.navigation.NavHostController import com.example.clubdeportivo.navigation.AppScreens @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun MenuUserScreen(navController: NavController){ Scaffold() { HomeBodyContent(navController) } } @Composable fun HomeBodyContent(navController: NavController){ Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = "Pantalla Home Usuario") Button(onClick = { navController.navigate(AppScreens.LoginScreen.route) }) { Text(text = "Atras!") } } }
0
Kotlin
0
0
6832d9f705d5c3d6b0f1ce844e04a996df71c5fe
1,341
club-deportivo-android
MIT License
app/src/main/kotlin/jp/cordea/mackerelclient/adapter/ServiceAdapter.kt
ariarijp
55,407,057
true
{"Kotlin": 156801}
package jp.cordea.mackerelclient.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import jp.cordea.mackerelclient.R import jp.cordea.mackerelclient.api.response.Service /** * Created by CORDEA on 2016/01/11. */ class ServiceAdapter(context: Context, val items: List<Service>) : ArrayAdapter<Service>(context, R.layout.list_item_service) { override fun getItem(position: Int): Service? { return items[position] } override fun getCount(): Int { return items.size } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.list_item_service, parent, false) val item = getItem(position) item ?: return convertView val name: TextView = view.findViewById(R.id.name) as TextView name.text = item.name val role: TextView = view.findViewById(R.id.role) as TextView role.text = item.roles.size.let { if (it <= 1) context.resources.getString(R.string.format_role).format(it) else if (it > 99) context.resources.getString(R.string.format_roles_ex) else context.resources.getString(R.string.format_roles).format(it) } val detail: TextView = view.findViewById(R.id.detail) as TextView detail.text = item.memo return view } }
0
Kotlin
0
0
cde9b545372cf4a4f5d1020e7e144bcbd71db05c
1,617
MackerelClient
Apache License 2.0
app/src/main/java/com/example/echangeapp/domain/repositories/AvailableCurrencyRepository.kt
dtx12
273,499,039
false
null
package com.example.echangeapp.domain.repositories import com.example.echangeapp.domain.models.Currency import com.example.echangeapp.domain.models.CurrencyAmount interface AvailableCurrencyRepository { fun read(base: Currency): CurrencyAmount fun update(amount: CurrencyAmount) }
0
Kotlin
0
0
61b3a2265811262ce413a246230fa7418cd7e2c8
290
ExchangeTestTask
MIT License
examples/src/jvmMain/kotlin/org/kobjects/parserlib/examples/basic/BasicShell.kt
kobjects
455,979,563
false
{"Kotlin": 17076, "Ruby": 1599}
package org.kobjects.parserlib.examples.basic; import org.kobjects.parserlib.examples.basic.Interpreter suspend fun main() { Interpreter().runShell() }
0
Kotlin
0
3
55990d510ef3323e1ac826b6812a26d6cd3d8149
157
parsek
Apache License 2.0
app/src/main/java/ar/com/play2play/framework/bluetooth/BluetoothStateProviderImp.kt
UTN-FRBA-Mobile
365,641,042
false
null
package ar.com.play2play.framework.bluetooth import android.bluetooth.BluetoothAdapter import ar.com.play2play.data.bluetooth.BluetoothStateProvider class BluetoothStateProviderImp : BluetoothStateProvider { private val bluetoothAdapter by lazy { BluetoothAdapter.getDefaultAdapter() } override fun isEnabled() = bluetoothAdapter.isEnabled }
0
Kotlin
1
0
da5e0c7a2c648cda4ae4192b254495f3de83b4b3
354
Play2Play
MIT License
usvm-core/src/test/kotlin/org/usvm/solver/SoftConstraintsTest.kt
UnitTestBot
586,907,774
false
null
package org.usvm.solver import io.ksmt.expr.KBitVec32Value import io.ksmt.solver.z3.KZ3Solver import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import org.usvm.UComponents import org.usvm.UContext import org.usvm.UTypeSystem import org.usvm.constraints.UPathConstraints import org.usvm.memory.emptyInputArrayLengthRegion import org.usvm.model.ULazyModelDecoder import org.usvm.model.buildTranslatorAndLazyDecoder import kotlin.test.assertSame open class SoftConstraintsTest<Field, Type, Method> { private lateinit var ctx: UContext private lateinit var softConstraintsProvider: USoftConstraintsProvider<Field, Type> private lateinit var typeSystem: UTypeSystem<Type> private lateinit var translator: UExprTranslator<Field, Type> private lateinit var decoder: ULazyModelDecoder<Field, Type, Method> private lateinit var solver: USolverBase<Field, Type, Method> @BeforeEach fun initialize() { typeSystem = mockk<UTypeSystem<Type>>(relaxed = true) val components: UComponents<*, *, *> = mockk() every { components.mkTypeSystem(any()) } returns typeSystem ctx = UContext(components) softConstraintsProvider = USoftConstraintsProvider(ctx) val translatorWithDecoder = buildTranslatorAndLazyDecoder<Field, Type, Method>(ctx) translator = translatorWithDecoder.first decoder = translatorWithDecoder.second solver = USolverBase(ctx, KZ3Solver(ctx), translator, decoder, softConstraintsProvider) } @Test fun testItWorks() = with(ctx) { val fstRegister = mkRegisterReading(idx = 0, bv32Sort) val sndRegister = mkRegisterReading(idx = 1, bv32Sort) val expr = mkBvSignedLessOrEqualExpr(fstRegister, sndRegister) val pc = UPathConstraints<Type>(ctx) pc += expr val result = solver.checkWithSoftConstraints(pc) as USatResult val model = result.model val fstRegisterValue = model.eval(fstRegister) val sndRegisterValue = model.eval(sndRegister) assertSame(fstRegisterValue, sndRegisterValue) } @Test @Disabled("How to count number of calls correctly?") fun expressionsCalculatesSoftConstraintsOnlyOnce() = with(ctx) { val fstRegister = mkRegisterReading(idx = 0, bv32Sort) val sndRegister = mkRegisterReading(idx = 1, bv32Sort) val thirdRegister = mkRegisterReading(idx = 2, bv32Sort) val fstExpr = mkBvSignedLessOrEqualExpr(fstRegister, sndRegister) val sndExpr = mkBvSignedLessOrEqualExpr(sndRegister, thirdRegister) val sameAsFirstExpr = mkBvSignedLessOrEqualExpr(fstRegister, sndRegister) val softConstraintsProvider = mockk<USoftConstraintsProvider<Field, Type>>() every { softConstraintsProvider.provide(any()) } answers { callOriginal() } val pc = UPathConstraints<Type>(ctx) pc += fstExpr pc += sndExpr pc += sameAsFirstExpr val solver = USolverBase(ctx, KZ3Solver(ctx), translator, decoder, softConstraintsProvider) val result = solver.checkWithSoftConstraints(pc) as USatResult val model = result.model verify(exactly = 1) { softConstraintsProvider.transform(fstRegister) softConstraintsProvider.transform(sndRegister) softConstraintsProvider.transform(thirdRegister) softConstraintsProvider.transform(fstExpr) softConstraintsProvider.transform(sndExpr) softConstraintsProvider.transform(sameAsFirstExpr) softConstraintsProvider.provide(sndExpr) } verify(exactly = 2) { softConstraintsProvider.provide(fstExpr) } val fstEvaluated = model.eval(fstRegister) val sndEvaluated = model.eval(sndRegister) val thirdEvaluated = model.eval(thirdRegister) assertSame(fstEvaluated, sndEvaluated) assertSame(fstEvaluated, thirdEvaluated) } @Test fun softConflictingWithPathConstraints() = with(ctx) { val arrayType = IntArray::class val inputRef = mkRegisterReading(0, addressSort) val secondInputRef = mkRegisterReading(1, addressSort) val region = emptyInputArrayLengthRegion(arrayType, sizeSort) .write(inputRef, mkRegisterReading(3, sizeSort), guard = trueExpr) val size = 25 val reading = region.read(secondInputRef) val pc = UPathConstraints<Type>(ctx) pc += reading eq size.toBv() pc += inputRef eq secondInputRef pc += (inputRef eq nullRef).not() val result = (solver.checkWithSoftConstraints(pc)) as USatResult val model = result.model val value = model.eval(mkInputArrayLengthReading(region, inputRef)) assertSame(size.toBv(), value) } @Test fun testUnsatCore() = with(ctx) { val arrayType = IntArray::class val inputRef = mkRegisterReading(0, addressSort) val region = emptyInputArrayLengthRegion(arrayType, sizeSort) .write(inputRef, mkRegisterReading(3, sizeSort), guard = trueExpr) val pc = UPathConstraints<Type>(ctx) pc += (inputRef eq nullRef).not() val result = (solver.checkWithSoftConstraints(pc)) as USatResult val model = result.model val value = model.eval(mkInputArrayLengthReading(region, inputRef)) assert((value as KBitVec32Value).intValue < 10) } @Test fun testSimpleComparisonExpression(): Unit = with(ctx) { val inputRef = mkRegisterReading(0, bv32Sort) val bvValue = 0.toBv() val expression = mkBvSignedLessOrEqualExpr(bvValue, inputRef).not() val pc = UPathConstraints<Type>(ctx) pc += expression val result = (solver.checkWithSoftConstraints(pc)) as USatResult val model = result.model model.eval(expression) } }
4
Kotlin
0
2
a504c78f51690c551c6080d2c964c6a352b761f2
6,007
usvm
Apache License 2.0
app/src/main/java/tk/paulmburu/moviesreview/utils/NetworkUtils.kt
Paulmburu
239,030,330
false
null
package tk.paulmburu.moviesreview.utils import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkRequest import android.os.Build import androidx.annotation.RequiresApi import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import java.net.ConnectException import java.net.UnknownHostException object NetworkUtils { @RequiresApi(Build.VERSION_CODES.LOLLIPOP) fun getNetworkStatus( context: Context ): LiveData<Boolean> { val isAvailableLiveData = MutableLiveData<Boolean>() val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val nr = NetworkRequest.Builder() cm.registerNetworkCallback(nr.build(), @RequiresApi(Build.VERSION_CODES.LOLLIPOP) object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { super.onAvailable(network) isAvailableLiveData.postValue(true) } override fun onLost(network: Network) { super.onLost(network) isAvailableLiveData.postValue(false) } }) return isAvailableLiveData } } suspend fun <T> executeNonBlocking( execute: suspend () -> ResultState<T> ): ResultState<T> { return try { execute() } catch (e: UnknownHostException) { Error<T>(e) } catch (e: ConnectException) { Error<T>(e) } }
4
Kotlin
7
11
e1b5b2f9a3593abc9a566f6da18b4e508ecfb60d
1,515
MoviesReview
Apache License 2.0
android/src/main/java/com/traccar/TraccarClientBridge.kt
victorlpgazolli
665,777,648
false
null
package com.traccar import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.util.Log import androidx.core.content.ContextCompat import com.facebook.react.bridge.ReactApplicationContext import com.traccar.Constants.Companion.KEY_DEVICE import com.traccar.Constants.Companion.KEY_INTERVAL import com.traccar.Constants.Companion.KEY_URL class TraccarClientBridge(context: ReactApplicationContext) { private var reactContext: ReactApplicationContext private var sharedPreferences: SharedPreferences private lateinit var alarmManager: AlarmManager private lateinit var alarmIntent: PendingIntent private var interval: Int = 15000 init { reactContext = context sharedPreferences = reactContext.getSharedPreferences("main", Context.MODE_PRIVATE) } fun startTrackingService() { Log.i(TAG, "start!") try { val intent = Intent(reactContext, TrackingService::class.java) reactContext.startService(intent) ContextCompat.startForegroundService(reactContext, Intent(reactContext, TrackingService::class.java)) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { alarmManager.setInexactRepeating( AlarmManager.ELAPSED_REALTIME_WAKEUP, interval.toLong(), interval.toLong(), alarmIntent ) } } catch (e: Exception) { Log.e(TAG, "startTrackingService: " + e.message) } } fun stopTrackingService() { Log.i(TAG, "stop!") try { val intent = Intent(reactContext, TrackingService::class.java) reactContext.stopService(intent) } catch (e: Exception) { Log.e(TAG, "startTrackingService: " + e.message) } } fun setupTrackingService(desiredUrl: String, desiredDeviceId: String, desiredInterval: Int) { Log.i(TAG, "setup!") try { interval = desiredInterval sharedPreferences.edit().putString(KEY_DEVICE, desiredDeviceId).apply() sharedPreferences.edit().putString(KEY_URL, desiredUrl).apply() sharedPreferences.edit().putInt(KEY_INTERVAL, interval).apply() alarmManager = reactContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager val originalIntent = Intent(reactContext, AutostartReceiver::class.java) originalIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND) val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE } else { PendingIntent.FLAG_UPDATE_CURRENT } alarmIntent = PendingIntent.getBroadcast(reactContext, 0, originalIntent, flags) } catch (e: Exception) { Log.e(TAG, "setupTrackingService: " + e.message) } } companion object { private val TAG = "Traccar"+TraccarClientBridge::class.java.simpleName } }
0
Kotlin
0
3
517e967a6766ad2bcec0cac18bb242d682694e91
3,092
react-native-traccar
MIT License
mineme-craft/src/main/kotlin/me/ddevil/mineme/craft/ui/mine/UnloadedMineDisplay.kt
BrunoSilvaFreire
89,026,535
false
null
package me.ddevil.mineme.craft.ui.mine import me.ddevil.mineme.craft.mine.config.InvalidMineConfig import me.ddevil.mineme.craft.mine.config.MineConfig import me.ddevil.mineme.craft.mine.config.ValidMineConfig import me.ddevil.mineme.craft.ui.UIResources import me.ddevil.shiroi.craft.message.MessageManager import me.ddevil.shiroi.craft.util.ShiroiItemBuilder import me.ddevil.shiroi.ui.api.component.misc.ClickableItemSlotComponent import me.ddevil.shiroi.ui.api.misc.Action import me.ddevil.shiroi.ui.api.updater.ItemUpdater import me.ddevil.util.exception.ArgumentOutOfRangeException import org.bukkit.inventory.ItemStack class UnloadedMineDisplay( val mine: MineConfig, val messageManager: MessageManager, action: Action ) : ClickableItemSlotComponent(createUpdater(mine, messageManager), getIcon(mine), id = null, action = action) fun getIcon(mine: MineConfig): ItemStack { if (mine is ValidMineConfig) { return mine.icon } else { return UIResources.INVALID_CONFIG_ICON } } private fun createUpdater(mine: MineConfig, messageManager: MessageManager): ItemUpdater { if (mine is ValidMineConfig) { return object : ItemUpdater { override fun update(oldItem: ItemStack): ItemStack { return ShiroiItemBuilder(messageManager, mine.icon) .setName("$5${mine.file.name}") .setLore(listOf( "$1${mine.name}$3($2${mine.alias}$3)", "$3World: $2${mine.world}", "$3Type: $1${mine.type}", "$5Click to load mine." )).build() } } } else if (mine is InvalidMineConfig) { return object : ItemUpdater { override fun update(oldItem: ItemStack): ItemStack { return ShiroiItemBuilder(messageManager, UIResources.INVALID_CONFIG_ICON) .setName("$4${mine.file.name}") .setLore(getLore(mine)) .build() } private fun getLore(mine: InvalidMineConfig): List<String> { val lore = ArrayList<String>() lore += "$3Errors:" mine.missingFields.mapTo(lore) { "$3- $4$it" } return lore } } } throw ArgumentOutOfRangeException("mine") }
0
Kotlin
0
0
6cdfb74a10a5b78d929df9e8bd36b0da626378f4
2,449
MineMe2
Do What The F*ck You Want To Public License
erikflowers-weather-icons/src/commonMain/kotlin/compose/icons/weathericons/NightSnowWind.kt
DevSrSouza
311,134,756
false
null
package compose.icons.weathericons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.WeatherIcons public val WeatherIcons.NightSnow: ImageVector get() { if (_nightSnow != null) { return _nightSnow!! } _nightSnow = Builder(name = "NightSnow", defaultWidth = 30.0.dp, defaultHeight = 30.0.dp, viewportWidth = 30.0f, viewportHeight = 30.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.23f, 16.89f) curveToRelative(0.0f, 1.33f, 0.47f, 2.48f, 1.4f, 3.44f) reflectiveCurveToRelative(2.07f, 1.47f, 3.4f, 1.53f) curveToRelative(0.12f, 0.0f, 0.18f, -0.06f, 0.18f, -0.17f) verticalLineToRelative(-1.34f) curveToRelative(0.0f, -0.11f, -0.06f, -0.17f, -0.18f, -0.17f) curveToRelative(-0.86f, -0.05f, -1.59f, -0.39f, -2.19f, -1.03f) curveToRelative(-0.6f, -0.64f, -0.9f, -1.39f, -0.9f, -2.26f) curveToRelative(0.0f, -0.83f, 0.28f, -1.55f, 0.85f, -2.17f) curveToRelative(0.57f, -0.61f, 1.27f, -0.97f, 2.1f, -1.07f) lineToRelative(0.53f, -0.04f) curveToRelative(0.13f, 0.0f, 0.2f, -0.06f, 0.2f, -0.18f) lineToRelative(0.07f, -0.54f) curveToRelative(0.11f, -1.08f, 0.56f, -1.99f, 1.37f, -2.72f) curveToRelative(0.81f, -0.73f, 1.76f, -1.1f, 2.85f, -1.1f) curveToRelative(1.09f, 0.0f, 2.04f, 0.37f, 2.86f, 1.1f) curveToRelative(0.82f, 0.73f, 1.28f, 1.64f, 1.4f, 2.72f) lineToRelative(0.08f, 0.57f) curveToRelative(0.0f, 0.12f, 0.06f, 0.19f, 0.17f, 0.19f) horizontalLineToRelative(1.62f) curveToRelative(0.91f, 0.0f, 1.68f, 0.32f, 2.33f, 0.95f) curveToRelative(0.64f, 0.63f, 0.97f, 1.4f, 0.97f, 2.28f) curveToRelative(0.0f, 0.86f, -0.3f, 1.61f, -0.91f, 2.25f) curveToRelative(-0.61f, 0.64f, -1.34f, 0.99f, -2.19f, 1.04f) curveToRelative(-0.12f, 0.0f, -0.19f, 0.06f, -0.19f, 0.17f) verticalLineToRelative(1.34f) curveToRelative(0.0f, 0.11f, 0.06f, 0.17f, 0.19f, 0.17f) curveToRelative(1.34f, -0.04f, 2.47f, -0.55f, 3.4f, -1.51f) curveToRelative(0.93f, -0.97f, 1.39f, -2.12f, 1.39f, -3.45f) curveToRelative(0.0f, -0.71f, -0.14f, -1.38f, -0.43f, -2.01f) curveToRelative(0.79f, -0.96f, 1.18f, -2.07f, 1.18f, -3.32f) curveToRelative(0.0f, -0.95f, -0.24f, -1.83f, -0.71f, -2.64f) reflectiveCurveToRelative(-1.11f, -1.45f, -1.92f, -1.92f) reflectiveCurveToRelative(-1.68f, -0.7f, -2.62f, -0.7f) curveToRelative(-1.55f, 0.0f, -2.85f, 0.58f, -3.89f, 1.73f) curveToRelative(-0.81f, -0.43f, -1.71f, -0.65f, -2.71f, -0.65f) curveToRelative(-1.41f, 0.0f, -2.67f, 0.44f, -3.76f, 1.32f) reflectiveCurveToRelative(-1.8f, 2.0f, -2.11f, 3.36f) curveToRelative(-1.11f, 0.26f, -2.02f, 0.84f, -2.74f, 1.74f) curveTo(4.59f, 14.71f, 4.23f, 15.74f, 4.23f, 16.89f) close() moveTo(10.62f, 21.01f) curveToRelative(0.0f, 0.22f, 0.08f, 0.41f, 0.24f, 0.57f) curveToRelative(0.17f, 0.17f, 0.36f, 0.25f, 0.58f, 0.25f) curveToRelative(0.23f, 0.0f, 0.43f, -0.08f, 0.59f, -0.23f) reflectiveCurveToRelative(0.24f, -0.35f, 0.24f, -0.59f) curveToRelative(0.0f, -0.24f, -0.08f, -0.43f, -0.23f, -0.59f) curveToRelative(-0.16f, -0.16f, -0.35f, -0.23f, -0.59f, -0.23f) curveToRelative(-0.24f, 0.0f, -0.43f, 0.08f, -0.59f, 0.23f) curveTo(10.7f, 20.57f, 10.62f, 20.77f, 10.62f, 21.01f) close() moveTo(10.62f, 24.64f) curveToRelative(0.0f, 0.24f, 0.08f, 0.43f, 0.24f, 0.58f) curveToRelative(0.16f, 0.16f, 0.36f, 0.24f, 0.58f, 0.24f) curveToRelative(0.24f, 0.0f, 0.43f, -0.08f, 0.59f, -0.23f) curveToRelative(0.16f, -0.16f, 0.23f, -0.35f, 0.23f, -0.59f) curveToRelative(0.0f, -0.24f, -0.08f, -0.44f, -0.24f, -0.6f) reflectiveCurveToRelative(-0.35f, -0.25f, -0.59f, -0.25f) curveToRelative(-0.23f, 0.0f, -0.43f, 0.08f, -0.59f, 0.25f) reflectiveCurveTo(10.62f, 24.4f, 10.62f, 24.64f) close() moveTo(13.81f, 22.9f) curveToRelative(0.0f, 0.23f, 0.08f, 0.44f, 0.25f, 0.61f) reflectiveCurveToRelative(0.36f, 0.27f, 0.58f, 0.27f) curveToRelative(0.23f, 0.0f, 0.43f, -0.09f, 0.6f, -0.26f) curveToRelative(0.17f, -0.17f, 0.25f, -0.38f, 0.25f, -0.62f) curveToRelative(0.0f, -0.22f, -0.08f, -0.41f, -0.25f, -0.58f) curveToRelative(-0.17f, -0.17f, -0.37f, -0.25f, -0.6f, -0.25f) curveToRelative(-0.22f, 0.0f, -0.41f, 0.08f, -0.58f, 0.25f) reflectiveCurveTo(13.81f, 22.68f, 13.81f, 22.9f) close() moveTo(13.81f, 19.31f) curveToRelative(0.0f, 0.23f, 0.08f, 0.42f, 0.24f, 0.58f) reflectiveCurveToRelative(0.36f, 0.24f, 0.59f, 0.24f) curveToRelative(0.24f, 0.0f, 0.44f, -0.08f, 0.6f, -0.24f) reflectiveCurveToRelative(0.25f, -0.35f, 0.25f, -0.59f) reflectiveCurveToRelative(-0.08f, -0.43f, -0.25f, -0.6f) reflectiveCurveToRelative(-0.37f, -0.25f, -0.6f, -0.25f) curveToRelative(-0.23f, 0.0f, -0.42f, 0.08f, -0.59f, 0.25f) reflectiveCurveTo(13.81f, 19.08f, 13.81f, 19.31f) close() moveTo(13.81f, 26.58f) curveToRelative(0.0f, 0.23f, 0.08f, 0.43f, 0.25f, 0.6f) curveToRelative(0.17f, 0.17f, 0.36f, 0.25f, 0.59f, 0.25f) curveToRelative(0.23f, 0.0f, 0.43f, -0.08f, 0.6f, -0.25f) curveToRelative(0.17f, -0.17f, 0.25f, -0.37f, 0.25f, -0.6f) curveToRelative(0.0f, -0.22f, -0.08f, -0.41f, -0.25f, -0.58f) curveToRelative(-0.17f, -0.17f, -0.37f, -0.25f, -0.6f, -0.25f) curveToRelative(-0.22f, 0.0f, -0.41f, 0.08f, -0.58f, 0.25f) curveTo(13.9f, 26.17f, 13.81f, 26.36f, 13.81f, 26.58f) close() moveTo(17.05f, 21.01f) curveToRelative(0.0f, 0.21f, 0.08f, 0.4f, 0.24f, 0.57f) curveToRelative(0.17f, 0.17f, 0.37f, 0.25f, 0.6f, 0.25f) curveToRelative(0.23f, 0.0f, 0.43f, -0.08f, 0.59f, -0.23f) curveToRelative(0.16f, -0.16f, 0.24f, -0.35f, 0.24f, -0.59f) curveToRelative(0.0f, -0.24f, -0.08f, -0.43f, -0.23f, -0.59f) curveToRelative(-0.16f, -0.16f, -0.35f, -0.23f, -0.59f, -0.23f) curveToRelative(-0.24f, 0.0f, -0.44f, 0.08f, -0.6f, 0.23f) curveTo(17.13f, 20.57f, 17.05f, 20.77f, 17.05f, 21.01f) close() moveTo(17.05f, 24.64f) curveToRelative(0.0f, 0.22f, 0.08f, 0.42f, 0.24f, 0.58f) reflectiveCurveToRelative(0.36f, 0.24f, 0.6f, 0.24f) curveToRelative(0.24f, 0.0f, 0.43f, -0.08f, 0.59f, -0.23f) curveToRelative(0.16f, -0.16f, 0.23f, -0.35f, 0.23f, -0.59f) curveToRelative(0.0f, -0.24f, -0.08f, -0.44f, -0.24f, -0.6f) curveToRelative(-0.16f, -0.17f, -0.35f, -0.25f, -0.59f, -0.25f) curveToRelative(-0.23f, 0.0f, -0.43f, 0.08f, -0.6f, 0.25f) reflectiveCurveTo(17.05f, 24.4f, 17.05f, 24.64f) close() moveTo(18.03f, 9.02f) curveToRelative(0.68f, -0.68f, 1.5f, -1.01f, 2.48f, -1.01f) curveToRelative(0.98f, 0.0f, 1.81f, 0.35f, 2.5f, 1.04f) reflectiveCurveToRelative(1.03f, 1.53f, 1.03f, 2.52f) curveToRelative(0.0f, 0.59f, -0.17f, 1.2f, -0.51f, 1.84f) curveToRelative(-0.96f, -0.96f, -2.13f, -1.44f, -3.5f, -1.44f) horizontalLineToRelative(-0.31f) curveTo(19.44f, 10.8f, 18.87f, 9.82f, 18.03f, 9.02f) close() } } .build() return _nightSnow!! } private var _nightSnow: ImageVector? = null
17
null
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
9,161
compose-icons
MIT License
app/src/main/java/com/ceos/jetpackshowcase/ui/theme/Type.kt
helsing45
795,664,509
false
{"Kotlin": 112682}
package com.ceos.jetpackshowcase.ui.theme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Typography import androidx.compose.runtime.Composable import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val typography = Typography( headlineLarge = TextStyle( fontWeight = FontWeight.Bold, fontSize = 32.sp, lineHeight = 32.sp, letterSpacing = 0.sp ), headlineSmall = TextStyle( fontWeight = FontWeight.SemiBold, fontSize = 24.sp, lineHeight = 32.sp, letterSpacing = 0.sp ), titleLarge = TextStyle( fontWeight = FontWeight.Normal, fontSize = 18.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), bodyLarge = TextStyle( fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.15.sp ), bodyMedium = TextStyle( fontWeight = FontWeight.Medium, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.25.sp ), labelMedium = TextStyle( fontWeight = FontWeight.SemiBold, fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) ) val TextStyle.secondary: TextStyle @Composable get() { return this.copy(color = MaterialTheme.colorScheme.secondary) } val TextStyle.error: TextStyle @Composable get() { return this.copy(color = MaterialTheme.colorScheme.error) }
0
Kotlin
0
0
10b4340316a436db7d81f4af4a513edb1b552116
1,621
JetpackShowcase
MIT License
app/src/main/java/com/mastomas/comicbookbrowser/koin/KoinModules.kt
LiveMasTomas
332,991,594
false
null
package com.mastomas.comicbookbrowser.koin import com.mastomas.comicbookbrowser.repository.MarvelCharacterRepository import com.mastomas.comicbookbrowser.repository.MarvelComicRepository import com.mastomas.comicbookbrowser.viewmodel.CharacterDetailViewModel import com.mastomas.comicbookbrowser.viewmodel.CharacterViewModel import com.mastomas.comicbookbrowser.webservice.MarvelApiWebService import kotlinx.serialization.ExperimentalSerializationApi import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module @ExperimentalSerializationApi val mainModule = module { factory { MarvelApiWebService.create() } single { MarvelCharacterRepository(get()) } single { MarvelComicRepository(get()) } viewModel { CharacterViewModel(get()) } viewModel { CharacterDetailViewModel(get()) } }
0
Kotlin
0
4
8ce4745a19e330d4b3d10ef60b08f8e28dc671b4
817
ComicBookBrowser
Apache License 2.0
app/src/main/kotlin/ss/proximityservice/data/AppStorageModule.kt
vothanhkiet
144,178,604
true
{"Kotlin": 25327}
package ss.proximityservice.data import android.content.Context import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class AppStorageModule { @Singleton @Provides fun provideSharedPerferencesAppStorage(context: Context) : AppStorage { return SharedPreferencesAppStorage(context) } }
0
Kotlin
0
0
d42f032ceabb40cabb8f6c6aef468686993069aa
338
ProximityService
Apache License 2.0
app/src/main/java/com/rmakiyama/skeleton/data/DummyRepository.kt
rmakiyama
252,239,199
false
null
package com.rmakiyama.skeleton.data import com.rmakiyama.skeleton.model.Dummy import kotlinx.coroutines.flow.Flow interface DummyRepository { fun dummies(): Flow<List<Dummy>> suspend fun save(dummy: Dummy) }
0
Kotlin
0
3
3ae4aa3fe433d0c988f82627a89a14eee7e26f35
220
android-skeleton
Apache License 2.0
app/src/main/java/com/example/week3day5/adapters/AdapterProduct.kt
Carat12
318,337,149
false
null
package com.example.week3day5.adapters import android.content.Context import android.content.Intent import android.graphics.Paint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.example.week3day5.R import com.example.week3day5.activities.ProductDetailActivity import com.example.week3day5.app.Config import com.example.week3day5.database.DBHelper import com.example.week3day5.models.Product import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.item_product.view.* import kotlinx.android.synthetic.main.layout_product_information.view.* import kotlinx.android.synthetic.main.layout_update_order_item_count.view.* class AdapterProduct(var mContext: Context, var dbHelper: DBHelper) : RecyclerView.Adapter<AdapterProduct.ViewHolder>() { private var proList: ArrayList<Product> = ArrayList() lateinit var listener: onAdapterListener override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(mContext).inflate(R.layout.item_product, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(proList[position], position) } override fun getItemCount(): Int { return proList.size } fun setData(data: ArrayList<Product>) { proList = data notifyDataSetChanged() } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(product: Product, position: Int) { itemView.txt_view_product_name.text = product.productName itemView.txt_view_product_price.text = "\$${product.price}" itemView.txt_view_product_price_original.text = "\$${product.mrp}" itemView.txt_view_product_price_original.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG itemView.txt_view_product_price_save.text = "Save: \$${Product.roundPrice(product.mrp - product.price)}" Picasso .get() .load(Config.IMAGE_URL + product.image) .placeholder(R.drawable.ic_baseline_image_24) .error(R.drawable.ic_baseline_broken_image_24) .into(itemView.img_view_product) itemView.setOnClickListener { listener.onItemClicked(it, position) } val quantityInCart = dbHelper.getOrderItemQuantity(product) if (quantityInCart == 0) { itemView.layout_update_item_count.isVisible = false itemView.btn_add_product.isVisible = true itemView.btn_add_product.setOnClickListener { listener.onAddButtonClicked(it, position) } } else { itemView.btn_add_product.isVisible = false itemView.layout_update_item_count.isVisible = true itemView.text_view_count.text = quantityInCart.toString() itemView.btn_decrement_count.setImageResource( if (quantityInCart == 1) R.drawable.ic_baseline_delete_outline_24 else R.drawable.ic_baseline_horizontal_rule_24 ) itemView.btn_increment_count.setOnClickListener { listener.onIncreaseButtonClicked(itemView, position) } itemView.btn_decrement_count.setOnClickListener { listener.onDecreaseButtonClicked(itemView, position) } } } } interface onAdapterListener { fun onItemClicked(itemView: View, position: Int) fun onAddButtonClicked(itemView: View, position: Int) fun onIncreaseButtonClicked(itemView: View, position: Int) fun onDecreaseButtonClicked(itemView: View, position: Int) } fun setOnAdapterListener(adapterListener: onAdapterListener) { listener = adapterListener } fun getItemData(position: Int): Product { return proList[position] } }
0
Kotlin
0
0
0dfb1038c0800f1afc9d8e5ea3f8b8229110e2f2
4,205
grocery
Apache License 2.0
features/game/src/main/java/com/ribsky/game/utils/adapter/Adapters.kt
nexy791
607,748,138
false
null
package com.ribsky.game.utils.adapter import com.ribsky.game.model.PayLoadModel import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory object Adapters { private val moshi: Moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() val user = adapter<PayLoadModel.User>() val score = adapter<PayLoadModel.Score>() val config = adapter<PayLoadModel.Config>() val type = adapter<PayLoadModel.Type>() private inline fun <reified T> adapter(): JsonAdapter<T> = moshi.adapter(T::class.java)!! }
0
Kotlin
0
7
d2e9f7c04635e1793bfe8f421b4bc5ef162556c0
625
dymka
Apache License 2.0
leo/src/main/kotlin/me/adkhambek/leo/recycler/LeoAdapter.kt
MrAdkhambek
235,808,012
false
null
package me.adkhambek.leo.recycler import android.view.LayoutInflater import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.viewbinding.ViewBinding import me.adkhambek.leo.LeoAdapter import me.adkhambek.leo.LeoAdapterDsl import me.adkhambek.leo.LeoItemBindListener import me.adkhambek.leo.LeoItemBinding import me.adkhambek.leo.core.LeoAdapterAsync import me.adkhambek.leo.core.LeoAdapterSync @LeoAdapterDsl fun <T, VB : ViewBinding> RecyclerView.setupAdapter( getViewBinding: LeoItemBinding<VB>, layoutManager: LinearLayoutManager = LinearLayoutManager(context), listener: LeoItemBindListener<T, VB> ): LeoAdapter<T> { val inflater: LayoutInflater = LayoutInflater.from(context) this.layoutManager = layoutManager val leoAdapter: LeoAdapterSync<T, VB> = LeoAdapterSync(inflater, getViewBinding, listener) this.adapter = leoAdapter return leoAdapter } @LeoAdapterDsl fun <T, VB : ViewBinding> RecyclerView.setupAdapter( getViewBinding: LeoItemBinding<VB>, diffUtil: DiffUtil.ItemCallback<T>, layoutManager: LinearLayoutManager = LinearLayoutManager(context), listener: LeoItemBindListener<T, VB> ): LeoAdapter<T> { val inflater: LayoutInflater = LayoutInflater.from(context) this.layoutManager = layoutManager val leoAdapter: LeoAdapterAsync<T, VB> = LeoAdapterAsync(inflater, diffUtil, getViewBinding, listener) this.adapter = leoAdapter return leoAdapter }
0
Kotlin
1
3
6d325b2eb089de26930f88f9f1c7a1cb0a15ab0f
1,547
LeoAdapter
MIT License
sample/src/wasmJsMain/kotlin/amaterek/util/ui/mvi/sample/ui/FinishApp.wasmJs.kt
amaterek
782,964,945
false
{"Kotlin": 14872, "Swift": 671}
package amaterek.util.ui.mvi.sample.ui actual fun finishApp(context: Any) { // TODO How to exit app on iOS? }
0
Kotlin
0
0
6f333707b3da1ce4d25882ad3a4869dd5d61ba97
114
kmp-mvi
Apache License 2.0
vxutil-vertigram/src/main/kotlin/ski/gagar/vxutil/vertigram/throttling/HasChatId.kt
gagarski
314,041,476
false
null
package ski.gagar.vxutil.vertigram.throttling import ski.gagar.vxutil.vertigram.types.ChatId interface HasChatId { val chatId: ChatId? } interface HasChatIdLong { val chatId: Long? }
0
Kotlin
0
0
9cb9209e905df3602fc87147c317ca75fdc12ad0
194
vxutil
Apache License 2.0
notifications/src/main/java/com/acg/mangalive/notifications/data/model/NotificationsResponseDto.kt
mangalive
507,894,145
false
{"Kotlin": 108313}
package com.acg.mangalive.notifications.data.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class NotificationsResponseDto( @SerialName("status") val status: String, @SerialName("message") val message: String, @SerialName("cards") val cards: List<NotificationsCardDto>, )
0
Kotlin
0
2
b7649723de9b735d9bbf4e02237fd5bd204ba674
345
mangalive-android-old
Apache License 2.0
indicator/src/main/java/com/zhpan/indicator/drawer/BaseDrawer.kt
TrendingTechnology
254,259,839
true
{"Kotlin": 27011, "Java": 3889}
package com.zhpan.indicator.drawer import android.graphics.Paint import android.graphics.RectF import com.zhpan.indicator.option.IndicatorOptions /** * <pre> * Created by zhpan on 2019/11/23. * Description: </pre> * */ abstract class BaseDrawer internal constructor(internal var mIndicatorOptions: IndicatorOptions) : IDrawer { private val mMeasureResult: MeasureResult internal var maxWidth: Float = 0.toFloat() internal var minWidth: Float = 0.toFloat() internal var mPaint: Paint = Paint() internal var mRectF: RectF protected val isWidthEquals: Boolean get() = mIndicatorOptions.normalSliderWidth == mIndicatorOptions.checkedSliderWidth init { mPaint.isAntiAlias = true mMeasureResult = MeasureResult() mRectF = RectF() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int): MeasureResult { maxWidth = mIndicatorOptions.normalSliderWidth.coerceAtLeast(mIndicatorOptions.checkedSliderWidth) minWidth = mIndicatorOptions.normalSliderWidth.coerceAtMost(mIndicatorOptions.checkedSliderWidth) mMeasureResult.setMeasureResult(measureWidth(), measureHeight()) return mMeasureResult } protected open fun measureHeight(): Int { return mIndicatorOptions.sliderHeight.toInt() } private fun measureWidth(): Int { val pageSize = mIndicatorOptions.pageSize val indicatorGap = mIndicatorOptions.sliderGap return ((pageSize - 1) * indicatorGap + maxWidth + (pageSize - 1) * minWidth).toInt() } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { } inner class MeasureResult { var measureWidth: Int = 0 internal set var measureHeight: Int = 0 internal set internal fun setMeasureResult(measureWidth: Int, measureHeight: Int) { this.measureWidth = measureWidth this.measureHeight = measureHeight } } }
0
null
0
0
d6505847cc8adc19e13678482e70d0009ee22177
2,011
viewpagerindicator-1
Apache License 2.0
src/main/kotlin/Assertions.kt
navikt
410,792,264
false
{"Kotlin": 24560, "JavaScript": 594}
package no.nav import org.hl7.fhir.r5.model.OperationOutcome import org.opentest4j.AssertionFailedError class UnexpectedIssue(val issueSpec: Specification.Issue, val source: String?) : AssertionFailedError("Unexpected $issueSpec at $source") { companion object { fun test(testSpec: Specification.TestCase, outcome: OperationOutcome): List<UnexpectedIssue> { val unexpectedErrorFailures = outcome.issue .map { UnexpectedIssue(it.toData(), it.sourceUrl()) } .filter { it.issueSpec.severity.failure() } .filterNot { testSpec.expectedIssues.any { expected -> expected.semanticallyEquals(it.issueSpec) } } val color = if (unexpectedErrorFailures.isEmpty()) Color.SUCCESSFUL else Color.FAILED println(color.paint(" ${unexpectedErrorFailures.count()} unexpected errors!")) return unexpectedErrorFailures } } } class MissingIssue(val issueSpec: Specification.Issue) : AssertionFailedError("Expected issue was not found: $issueSpec.") { companion object { fun test(testSpec: Specification.TestCase, outcome: OperationOutcome): List<MissingIssue> { val issues = outcome.issue.map { it.toData() } val missingIssueFailures = testSpec.expectedIssues .filterNot { expected -> issues.any { expected.semanticallyEquals(it) } } .map { MissingIssue(it) } val foundCount = testSpec.expectedIssues.count() - missingIssueFailures.count() val color = if (foundCount == testSpec.expectedIssues.count()) Color.SUCCESSFUL else Color.FAILED println(color.paint(" Found $foundCount of ${testSpec.expectedIssues.count()} expected issues!")) return missingIssueFailures } } }
11
Kotlin
1
2
7d1cee838d7167eda335577b2cb536dd1381e24b
1,805
fhir-validator-junit-engine
MIT License
common/src/main/java/de/nicidienase/chaosflix/common/entities/PlaybackProgressDao.kt
MHohenberg
116,195,964
true
{"Java Properties": 2, "YAML": 2, "Gradle": 5, "Shell": 1, "SVG": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 4, "Proguard": 3, "Java": 50, "XML": 58, "Kotlin": 5, "HTML": 1}
package de.nicidienase.chaosflix.common.entities import android.arch.persistence.room.Dao import android.arch.persistence.room.Insert import android.arch.persistence.room.Query import io.reactivex.Flowable /** * Created by felix on 04.10.17. */ @Dao interface PlaybackProgressDao{ @Query("SELECT * from playback_progress") fun getAll(): Flowable<List<PlaybackProgress>> @Query("SELECT * from playback_progress WHERE event_id = :arg0 LIMIT 1") fun getProgressForEvent(id:Int): Flowable<PlaybackProgress> @Insert fun saveProgress(progress: PlaybackProgress) }
0
Java
0
0
8ad75f93258da6a0176a58e80d86a4beaa1090b4
588
chaosflix
MIT License
kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/spec/dsl/callbackorder/AfterTestOrderTest.kt
kotest
47,071,082
false
{"Gradle Kotlin DSL": 57, "JSON": 18, "Markdown": 1115, "Java Properties": 1, "Shell": 2, "Text": 5, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 2, "EditorConfig": 1, "SVG": 4, "Kotlin": 1691, "TOML": 1, "INI": 4, "YAML": 18, "JavaScript": 4, "CSS": 3, "MDX": 22, "HTTP": 3, "Java": 1}
package com.sksamuel.kotest.engine.spec.dsl.callbackorder import io.kotest.core.spec.style.DescribeSpec import io.kotest.matchers.shouldBe class AfterTestOrderTest : DescribeSpec({ var trail = "" afterSpec { trail shouldBe "3215421211" } afterTest { trail += "1" } describe("nested level 1") { afterTest { trail += "2" } it("test level 1") { trail += "3" } describe("nested level 2") { afterTest { trail += "4" } it("test level 2") { trail += "5" } } } })
137
Kotlin
623
4,318
e7f7e52a732010fae899d1fcc4d074c055463e0b
612
kotest
Apache License 2.0
viewpager2/integration-tests/testapp/src/androidTest/java/com/example/androidx/viewpager2/test/ViewInteractions.kt
forksource
173,054,394
true
{"INI": 6, "Shell": 12, "Markdown": 11, "Java": 3562, "Kotlin": 851, "HTML": 18, "Python": 9, "Proguard": 20, "Java Properties": 6, "Gradle Kotlin DSL": 3}
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androidx.viewpager2.test import androidx.test.espresso.Espresso.onView import androidx.test.espresso.ViewInteraction import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom import androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA import androidx.test.espresso.matcher.ViewMatchers.isDisplayingAtLeast import androidx.test.espresso.matcher.ViewMatchers.withChild import androidx.test.espresso.matcher.ViewMatchers.withParent import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.tabs.TabLayout import org.hamcrest.CoreMatchers.allOf fun onViewPager(): ViewInteraction { return onView(isAssignableFrom(ViewPager2::class.java)) } fun onCurrentPage(): ViewInteraction { return onView(allOf( withParent(withParent(isAssignableFrom(ViewPager2::class.java))), isDisplayingAtLeast(50) )) } fun onTab(withText: String): ViewInteraction { return onView( allOf( isDescendantOfA(isAssignableFrom(TabLayout::class.java)), withChild(withText(withText)) ) ) }
0
Java
0
0
3b2cbdd7e43301a0c07ddbec0095deeeb13b5dfb
1,770
platform_frameworks_support
Apache License 2.0
core/src/main/java/org/futo/circles/core/view/LoadingButton.kt
circles-project
615,347,618
false
{"Kotlin": 1307644, "C": 137821, "C++": 12364, "Shell": 3202, "CMake": 1680, "Ruby": 922}
package org.futo.circles.core.view import android.content.Context import android.os.Parcelable import android.util.AttributeSet import android.util.TypedValue import android.view.LayoutInflater import android.view.View import androidx.constraintlayout.widget.ConstraintLayout import org.futo.circles.core.R import org.futo.circles.core.databinding.ViewLoadingButtonBinding import org.futo.circles.core.extensions.getAttributes import org.futo.circles.core.extensions.setIsVisible class LoadingButtonState( val superSavedState: Parcelable?, val isLoading: Boolean, val text: String, val isEnabled: Boolean ) : View.BaseSavedState(superSavedState), Parcelable class LoadingButton( context: Context, attrs: AttributeSet? = null ) : ConstraintLayout(context, attrs) { private val binding = ViewLoadingButtonBinding.inflate(LayoutInflater.from(context), this) private var buttonText: String = "" var isLoading: Boolean = false private set init { getAttributes(attrs, R.styleable.LoadingButton) { getText(R.styleable.LoadingButton_android_text)?.let { buttonText = it.toString() binding.button.text = it } getDimensionPixelSize(R.styleable.LoadingButton_android_textSize, 0).takeIf { it > 0 } ?.let { binding.button.setTextSize(TypedValue.COMPLEX_UNIT_PX, it.toFloat()) } getDimensionPixelSize(R.styleable.LoadingButton_textPadding, 0).takeIf { it > 0 } ?.let { binding.button.setPadding(it, it, it, it) } binding.button.isEnabled = getBoolean(R.styleable.LoadingButton_android_enabled, true) } } override fun onSaveInstanceState(): Parcelable { val superState = super.onSaveInstanceState() return LoadingButtonState(superState, isLoading, buttonText, isEnabled) } override fun onRestoreInstanceState(state: Parcelable?) { val loadingButtonState = state as? LoadingButtonState super.onRestoreInstanceState(loadingButtonState?.superSavedState ?: state) post { setText(loadingButtonState?.text ?: "") setIsLoading(loadingButtonState?.isLoading ?: false) isEnabled = loadingButtonState?.isEnabled ?: true } } override fun setOnClickListener(l: OnClickListener?) { binding.button.setOnClickListener(l) } fun setText(text: String) { binding.button.text = text buttonText = text } fun setIsLoading(isLoading: Boolean) { this.isLoading = isLoading binding.loader.setIsVisible(isLoading) binding.button.isEnabled = !isLoading binding.button.text = if (isLoading) "" else buttonText } override fun setEnabled(isEnabled: Boolean) { super.setEnabled(isEnabled) binding.button.isEnabled = isEnabled } }
8
Kotlin
4
29
7edec708f9c491a7b6f139fc2f2aa3e2b7149112
2,991
circles-android
Apache License 2.0
src/main/kotlin/top/myrest/myflow/fileconverter/Pdf2ImageActionHandler.kt
myrestop
652,200,641
false
{"Kotlin": 8312}
package top.myrest.myflow.fileconverter import java.io.File import cn.hutool.core.img.ImgUtil import cn.hutool.core.io.FileUtil import cn.hutool.core.swing.DesktopUtil import org.apache.pdfbox.pdmodel.PDDocument import org.apache.pdfbox.rendering.PDFRenderer class Pdf2ImageActionHandler : BaseConverterActionHandler("pdf2image", "./logos/pdf2image.png", "pdf-to-image") { override fun isSupport(file: File): Boolean = file.exists() && file.isFile && file.name.endsWith(".pdf") override fun convert(file: File) { val name = FileUtil.mainName(file) val doc = PDDocument.load(file) val renderer = PDFRenderer(doc) for (i in 0 until doc.numberOfPages) { val image = renderer.renderImageWithDPI(i, 300f) ImgUtil.write(image, FileUtil.file(file.parentFile, name + "_" + (i + 1) + ".png")) } DesktopUtil.open(file.parentFile) } }
0
Kotlin
0
1
b1b605a3b1e1969ec8b8df24c1108352f36e976c
914
myflow-fileconverter
MIT License
src/commonMain/kotlin/net/notjustanna/lin/ast/node/access/SubscriptAccessExpr.kt
annathelibri
280,314,655
false
{"Kotlin": 323273}
package net.notjustanna.lin.ast.node.access import net.notjustanna.lin.ast.node.Expr import net.notjustanna.lin.ast.visitor.NodeMapVisitor import net.notjustanna.lin.ast.visitor.NodeVisitor import net.notjustanna.lin.ast.visitor.NodeVisitor1 import net.notjustanna.lin.ast.visitor.NodeVisitorR import net.notjustanna.tartar.api.lexer.Section public data class SubscriptAccessExpr( val target: Expr, val arguments: List<Expr>, override val section: Section? = null ) : Expr { /* @automation(ast.impl SubscriptAccessExpr,Expr)-start */ override fun accept(visitor: NodeVisitor) { visitor.visitSubscriptAccessExpr(this) } override fun accept(visitor: NodeMapVisitor): Expr { return visitor.visitSubscriptAccessExpr(this) } override fun <R> accept(visitor: NodeVisitorR<R>): R { return visitor.visitSubscriptAccessExpr(this) } override fun <T> accept(visitor: NodeVisitor1<T>, param0: T) { visitor.visitSubscriptAccessExpr(this, param0) } /* @automation-end */ }
17
Kotlin
0
7
9178bacb49385bdbbbebceb54d757ecf96b37705
1,048
Lin
MIT License
app/src/androidTest/java/uk/gov/onelogin/e2e/JourneyController.kt
govuk-one-login
671,139,547
false
{"Kotlin": 611350, "Shell": 12866, "Ruby": 1762}
package uk.gov.onelogin.e2e import uk.gov.onelogin.e2e.controller.PhoneController /** * Functional interface that acts as an abstraction for performing a section of the User's journey. */ fun interface JourneyController { /** * Completes the User interaction necessary for the given [JourneyController]. * * The UI elements that the User interacts with are specific to the implementation. * * @param controller The [PhoneController] used for interacting in an automated way. */ fun performJourney(controller: PhoneController) }
2
Kotlin
0
4
8158433162764dc72a99006c51c8e84206e101bc
571
mobile-android-one-login-app
MIT License
app/src/main/java/com/creative/qrcodescanner/data/entity/UserSettingData.kt
dantech0xff
735,255,021
false
{"Kotlin": 166617}
package com.creative.qrcodescanner.data.entity import android.content.Context import androidx.compose.runtime.Stable import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.preferencesDataStore @Stable data class UserSettingData( val isEnableVibrate: Boolean, val isEnableSound: Boolean, val isPremium: Boolean = false, val isKeepScanning: Boolean = false, ) { companion object { internal val PREFERENCES_NAME = UserSettingData::class.java.name } } val Context.userSettingPreferences by preferencesDataStore(name = UserSettingData.PREFERENCES_NAME) @Stable object SettingPreferencesKey { val IS_ENABLE_VIBRATE = booleanPreferencesKey("is_enable_vibrate") val IS_ENABLE_SOUND = booleanPreferencesKey("is_enable_sound") val IS_PREMIUM = booleanPreferencesKey("is_premium") val IS_KEEP_SCANNING = booleanPreferencesKey("is_keep_scanning") }
0
Kotlin
0
9
b204cc786b5c5e146056c7ab66cc58ce5d8d66e1
936
compose-barcode-scanner
MIT License
common/src/main/kotlin/io/github/natanfudge/genericutils/superclasses/KBlockEntity.kt
natanfudge
669,064,047
false
null
package io.github.natanfudge.genericutils.superclasses import io.github.natanfudge.genericutils.inventory.ListenableInventory import io.github.natanfudge.genericutils.inventory.readItemsNbt import io.github.natanfudge.genericutils.inventory.writeItemsNbt import net.minecraft.block.BlockState import net.minecraft.block.entity.BlockEntity import net.minecraft.nbt.NbtCompound import net.minecraft.network.Packet import net.minecraft.network.listener.ClientPlayPacketListener import net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket import net.minecraft.util.math.BlockPos abstract class KBlockEntity( private val type: KBlockEntityType<*>, pos: BlockPos, state: BlockState, /** KBlockEntity will save the inventory for you */ private val inventory: ListenableInventory? = null, ) : BlockEntity(type, pos, state) { // clientRequiresNbt implementation override fun toInitialChunkDataNbt(): NbtCompound { return if (type.clientRequiresNbt) createNbt() else super.toInitialChunkDataNbt() } override fun toUpdatePacket(): Packet<ClientPlayPacketListener>? { return if (type.clientRequiresNbt) return BlockEntityUpdateS2CPacket.create(this) else super.toUpdatePacket() } private val inventoryOnChangeHandle = inventory?.onChange("KBlockEntity") { markDirty() } override fun markRemoved() { super.markRemoved() inventoryOnChangeHandle?.unsubscribe() } override fun writeNbt(nbt: NbtCompound) { inventory?.writeItemsNbt(nbt) super.writeNbt(nbt) } override fun readNbt(nbt: NbtCompound) { inventory?.readItemsNbt(nbt) super.readNbt(nbt) } }
0
Kotlin
0
0
cfe4a9605d7c6c2a58228f1736489b4773c0b5d8
1,681
HardCraft
Creative Commons Zero v1.0 Universal
superrvadapter/src/main/java/com/pawanjeswani/superrvadapter/BinderAbstract.kt
YeWintNaing05
213,709,496
true
{"Kotlin": 8375}
package com.pawanjeswani.superrvadapter import android.view.View internal interface BinderAbstract<RH, BH> { /** * For creating view holder for views between elements from * @param view * And return the view holder */ fun onCreateViewHolderBetweenElements(view: View): BH /** * For creating view holder for real view from * @param view * And return the view holder */ fun onCreateRealViewHolder(view: View): RH /** * for creating other item with DummyObject */ fun createOtherItemList() }
0
Kotlin
0
0
e02359d9af11332cfc284ff6001e8d2185818125
569
SuperAdapter
Apache License 2.0
app/src/main/java/net/lunis/unlocklimiter/MainActivity.kt
lslunis
269,117,334
false
null
package net.lunis.unlocklimiter import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) startForegroundService(Intent(this, ScreenLockStateService::class.java)) } }
0
Kotlin
0
0
944e161fbf9be9f01244cf358fd3ccbda4175088
417
UnlockLimiter
Apache License 2.0
codec/src/commonMain/kotlin/com/inkapplications/ack/codec/extension/TransmitterInfoCodec.kt
InkApplications
277,934,100
false
null
package com.inkapplications.ack.codec.extension import com.inkapplications.ack.codec.SimpleCodec import com.inkapplications.ack.codec.chunk.requireStartsWith import com.inkapplications.ack.codec.digit import com.inkapplications.ack.codec.digitBasedValue import com.inkapplications.ack.codec.format.fixedLength import com.inkapplications.ack.codec.format.orZero import com.inkapplications.ack.structures.TransmitterInfo import inkapplications.spondee.measure.Bels import inkapplications.spondee.measure.Feet import inkapplications.spondee.measure.Watts import inkapplications.spondee.spatial.Degrees import inkapplications.spondee.structure.Deci import inkapplications.spondee.structure.of import inkapplications.spondee.structure.value import kotlin.math.log10 import kotlin.math.pow import kotlin.math.roundToInt object TransmitterInfoCodec: SimpleCodec<TransmitterInfo> { private const val PREFIX = "PHG" private const val POWER_EXPONENT = 2 private const val HEIGHT_BASE = 2.0 private const val HEIGHT_MULTIPLIER = 10 private const val DIRECTION_MULTIPLIER = 45 override fun decode(data: String): TransmitterInfo { data.requireStartsWith(PREFIX) val power = data[3] .digit .toFloat() .pow(POWER_EXPONENT) .let(Watts::of) val height = data[4] .digitBasedValue .toInt() .let { HEIGHT_BASE.pow(it) } .times(HEIGHT_MULTIPLIER) .let(Feet::of) val gain = data[5] .digit .toInt() .let { Bels.of(Deci, it) } val direction = data[6] .digit .toInt() .times(DIRECTION_MULTIPLIER) .takeIf { it != 0 } ?.let(Degrees::of) return TransmitterInfo(power, height, gain, direction) } override fun encode(data: TransmitterInfo): String { val power = data.power ?.value(Watts) ?.pow(1.0 / POWER_EXPONENT) ?.roundToInt() .orZero() .fixedLength(1) val height = data.height ?.value(Feet) ?.div(HEIGHT_MULTIPLIER) ?.let { log10(it) } ?.div(log10(HEIGHT_BASE)) ?.roundToInt() .orZero() .fixedLength(1) val gain = data.gain ?.value(Deci, Bels) ?.roundToInt() .orZero() .fixedLength(1) val direction = data.direction ?.value(Degrees) ?.div(DIRECTION_MULTIPLIER) ?.roundToInt() .orZero() .fixedLength(1) return "$PREFIX$power$height$gain$direction" } }
4
Kotlin
1
0
665be5fd074f047ff018ab428b69e680cc101a9b
2,714
Karps
MIT License
ssh/src/main/kotlin/id/yoframework/ssh/Ssh.kt
danurahadi
168,310,742
true
{"Kotlin": 149782, "Shell": 785}
/* * Copyright (C)2018 - Deny Prasetyo <jasoet87@gmail.com> * * 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 id.yoframework.ssh import com.jcraft.jsch.Channel import com.jcraft.jsch.ChannelDirectTCPIP import com.jcraft.jsch.ChannelExec import com.jcraft.jsch.ChannelForwardedTCPIP import com.jcraft.jsch.ChannelSftp import com.jcraft.jsch.ChannelShell import com.jcraft.jsch.JSch import com.jcraft.jsch.Session import id.yoframework.core.extension.resource.homeDir import java.io.File import java.io.File.separator import java.util.* typealias Ssh = JSch enum class ChannelType(val type: String) { SESSION("session"), SHELL("shell"), EXEC("exec"), X11("x11"), AGENT_FORWARDING("auth-agent@openssh.com"), DIRECT_TCP_IP("direct-tcpip"), FORWARDED_TCP_IP("forwarded-tcpip"), SFTP("sftp"), SUBSYSTEM("subsystem") } fun privateKeyLocation(homeDir: String = homeDir(), path: String = ".ssh${separator}id_rsa"): String { return "$homeDir$separator$path" } fun knownHostLocation(homeDir: String = homeDir(), path: String = ".ssh${separator}known_hosts"): String { return "$homeDir$separator$path" } fun Session.setConfig(propertyMap: Map<String, String>) { val config = Properties().apply { put("StrictHostKeyChecking", "no") putAll(propertyMap) } this.setConfig(config) } fun createSsh( privateKeyLocation: Pair<String, String> = privateKeyLocation() to "", knownHostLocation: String = knownHostLocation(), customize: (Ssh) -> Unit = {} ): Ssh { val ssh = Ssh() if (File(privateKeyLocation.first).exists()) { ssh.addIdentity(privateKeyLocation.first, privateKeyLocation.second) } if (File(knownHostLocation).exists()) { ssh.setKnownHosts(knownHostLocation) } customize(ssh) return ssh } fun Ssh.createSession( user: String, host: String, port: Int = 22, daemonThread: Boolean = false, properties: Map<String, String> = emptyMap(), customize: (Session) -> Unit = {} ): Session { val session = this.getSession(user, host, port) session.setDaemonThread(daemonThread) session.setConfig(properties) customize(session) return session } suspend fun <T> Session.use(timeout: Int = 0, operation: suspend Session.() -> T): T { try { if (!this.isConnected) { this.connect(timeout) } return operation(this) } finally { this.disconnect() } } fun Session.openChannel(type: ChannelType): Channel { return this.openChannel(type.type) } inline fun <reified T : Channel> Session.openChannel(): T { return when (T::class) { ChannelShell::class -> this.openChannel(ChannelType.SHELL) as T ChannelExec::class -> this.openChannel(ChannelType.EXEC) as T ChannelDirectTCPIP::class -> this.openChannel(ChannelType.DIRECT_TCP_IP) as T ChannelForwardedTCPIP::class -> this.openChannel(ChannelType.FORWARDED_TCP_IP) as T ChannelSftp::class -> this.openChannel(ChannelType.SFTP) as T else -> throw IllegalArgumentException("Unsupported Class ${T::class.simpleName}") } } suspend fun <T> Channel.use(timeout: Int = 0, operation: suspend Channel.() -> T): T { try { if (!this.isConnected) { this.connect(timeout) } return operation(this) } finally { this.disconnect() } }
0
Kotlin
0
0
b24bee0c560b0068266851ad402200e2fb867043
3,910
yoframework
Apache License 2.0
impact/src/main/java/com/kronos/mebium/android/AndroidApplicationHandler.kt
Leifzhang
564,589,854
false
{"Kotlin": 22346}
package com.kronos.mebium.android import com.kronos.mebium.action.Handler /** * @Author LiABao * @Since 2022/10/26 */ class AndroidApplicationHandler : Handler { override fun handle(args: Array<String>) { } }
0
Kotlin
1
24
51f366d00d4a5c46a2ea3f4125898807f9988ecc
223
TheNext
Apache License 2.0
src/com/hxz/mpxjs/web/symbols/VueWebTypesMergedSymbol.kt
wuxianqiang
508,329,768
false
{"Kotlin": 1447881, "Vue": 237479, "TypeScript": 106023, "JavaScript": 93869, "HTML": 17163, "Assembly": 12226, "Lex": 11227, "Java": 2846, "Shell": 1917, "Pug": 338}
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.hxz.mpxjs.web.symbols //import com.intellij.javascript.web.js.jsType //import com.intellij.lang.documentation.DocumentationTarget //import com.intellij.lang.javascript.psi.JSType //import com.intellij.model.Pointer //import com.intellij.navigation.TargetPresentation //import com.intellij.openapi.util.text.StringUtil //import com.intellij.util.containers.Stack //import com.intellij.webSymbols.* //import com.intellij.webSymbols.completion.WebSymbolCodeCompletionItem //import com.intellij.webSymbols.documentation.WebSymbolDocumentation //import com.intellij.webSymbols.documentation.WebSymbolDocumentationTarget //import com.intellij.webSymbols.html.WebSymbolHtmlAttributeValue //import com.intellij.webSymbols.query.WebSymbolsCodeCompletionQueryParams //import com.intellij.webSymbols.query.WebSymbolsNameMatchQueryParams //import com.intellij.webSymbols.utils.merge //import org.jetbrains.annotations.Nls //import com.hxz.mpxjs.codeInsight.toAsset //import javax.swing.Icon // //class VueWebTypesMergedSymbol(override val matchedName: String, // sourceSymbol: PsiSourcedWebSymbol, // val webTypesSymbols: Collection<WebSymbol>) // : PsiSourcedWebSymbolDelegate<PsiSourcedWebSymbol>(sourceSymbol) { // // private val symbols: List<WebSymbol> = sequenceOf(sourceSymbol) // .plus(webTypesSymbols).toList() // // private val originalName: String? // get() = symbols.getOrNull(1) // ?.name // ?.takeIf { toAsset(it) != toAsset(name) } // // override val name: String // get() = matchedName // // override val origin: WebSymbolOrigin // get() = symbols.getOrNull(1)?.origin ?: super.origin // // override fun getModificationCount(): Long = // symbols.sumOf { it.modificationCount } // // override val nameSegments: List<WebSymbolNameSegment> // get() = listOf(WebSymbolNameSegment( // 0, matchedName.length, symbols // )) // // override val description: String? // get() = symbols.firstNotNullOfOrNull { it.description } // // override val descriptionSections: Map<String, String> // get() = symbols.asSequence() // .flatMap { it.descriptionSections.entries } // .distinctBy { it.key } // .associateBy({ it.key }, { it.value }) // // override val docUrl: String? // get() = symbols.firstNotNullOfOrNull { it.docUrl } // // override val icon: Icon? // get() = symbols.firstNotNullOfOrNull { it.icon } // // override val deprecated: Boolean // get() = symbols.any { it.deprecated } // // override val experimental: Boolean // get() = symbols.any { it.experimental } // // override val required: Boolean? // get() = symbols.firstNotNullOfOrNull { it.required } // // override val defaultValue: String? // get() = symbols.firstNotNullOfOrNull { it.defaultValue } // // override val priority: WebSymbol.Priority? // get() = symbols.asSequence().mapNotNull { it.priority }.maxOrNull() // // override val proximity: Int? // get() = symbols.asSequence().mapNotNull { it.proximity }.maxOrNull() // // override val type: JSType? // get() = symbols.firstNotNullOfOrNull { it.jsType } // // override val attributeValue: WebSymbolHtmlAttributeValue? // get() = symbols.asSequence().map { it.attributeValue }.merge() // // override val properties: Map<String, Any> // get() = symbols.asSequence() // .flatMap { it.properties.entries } // .distinctBy { it.key } // .associateBy({ it.key }, { it.value }) // // override val queryScope: Sequence<WebSymbolsScope> // get() = sequenceOf(this) // // override val documentation: WebSymbolDocumentation // get() = WebSymbolDocumentation.create(this).let { doc -> // originalName // ?.let { doc.withDefinition(StringUtil.escapeXmlEntities(it) + " as " + doc.definition) } // ?: doc // } // // override fun getDocumentationTarget(): DocumentationTarget = // VueMergedSymbolDocumentationTarget(this, originalName ?: name) // // override fun getSymbols(namespace: SymbolNamespace?, // kind: SymbolKind, // name: String?, // params: WebSymbolsNameMatchQueryParams, // scope: Stack<WebSymbolsScope>): List<WebSymbolsScope> = // symbols // .flatMap { // it.getSymbols(namespace, kind, name, params, scope) // } // .takeIf { it.isNotEmpty() } // ?.let { list -> // val containers = mutableListOf<WebSymbolsScope>() // var psiSourcedWebSymbol: PsiSourcedWebSymbol? = null // val webSymbols = mutableListOf<WebSymbol>() // for (item in list) { // when (item) { // is PsiSourcedWebSymbol -> { // if (psiSourcedWebSymbol == null) { // psiSourcedWebSymbol = item // } // else webSymbols.add(item) // } // is WebSymbol -> webSymbols.add(item) // else -> containers.add(item) // } // } // if (psiSourcedWebSymbol != null) { // containers.add(VueWebTypesMergedSymbol(psiSourcedWebSymbol.matchedName, psiSourcedWebSymbol, webSymbols)) // } // else { // containers.addAll(webSymbols) // } // containers // } // ?: emptyList() // // override fun getCodeCompletions(namespace: SymbolNamespace?, // kind: SymbolKind, // name: String?, // params: WebSymbolsCodeCompletionQueryParams, // scope: Stack<WebSymbolsScope>): List<WebSymbolCodeCompletionItem> = // symbols.asSequence() // .flatMap { it.getCodeCompletions(namespace, kind, name, params, scope) } // .groupBy { it.name } // .values // .map { items -> // if (items.size == 1) // items[0] // else { // var psiSourcedWebSymbol: PsiSourcedWebSymbol? = null // val symbols = mutableListOf<WebSymbol>() // items.asSequence().mapNotNull { it.symbol }.forEach { // if (it is PsiSourcedWebSymbol && psiSourcedWebSymbol == null) // psiSourcedWebSymbol = it // else symbols.add(it) // } // psiSourcedWebSymbol?.let { // items[0].withSymbol(VueWebTypesMergedSymbol(it.matchedName, it, symbols)) // } ?: items[0] // } // } // // override fun createPointer(): Pointer<out WebSymbol> { // val pointers = symbols.map { it.createPointer() } // val matchedName = matchedName // return Pointer { // val symbols = pointers.map { it.dereference() ?: return@Pointer null } // VueWebTypesMergedSymbol(matchedName, // symbols[0] as? PsiSourcedWebSymbol ?: return@Pointer null, // symbols.subList(1, symbols.size)) // } // } // // class VueMergedSymbolDocumentationTarget( // override val symbol: WebSymbol, // @Nls val displayName: String, // ) : WebSymbolDocumentationTarget { // // override fun presentation(): TargetPresentation { // return TargetPresentation.builder(displayName) // .icon(symbol.icon) // .presentation() // } // // override fun createPointer(): Pointer<out DocumentationTarget> { // val pointer = symbol.createPointer() // val displayName = this.displayName // return Pointer<DocumentationTarget> { // pointer.dereference()?.let { VueMergedSymbolDocumentationTarget(it, displayName) } // } // } // } // //}
2
Kotlin
0
4
e069e8b340ab04780ac13eab375d900f21bc7613
7,699
intellij-plugin-mpx
Apache License 2.0
Code/app/src/main/java/com/istudio/pokedex/ui/screens/pokemon_list/composables/PokemonSearchBar.kt
devrath
593,250,622
false
{"Kotlin": 81693}
package com.istudio.pokedex.ui.screens.pokemon_list.composables import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp @Composable fun PokemonSearch(){ /** * This function gets called when someone enters something * From here, We can call a function in the view model */ SearchBar( hint = "Search", modifier = Modifier.fillMaxWidth().padding(16.dp) ){ /** * This function gets called when someone enters something * From here, We can call a function in the view model */ } } @Composable fun SearchBar( modifier: Modifier = Modifier, hint: String = "", onSearch: (String) -> Unit = {} ) { // Value for actual text var text by remember { mutableStateOf("") } // The boolean value will be true if hint displayed is true els it will be false var isHintDisplayed by remember { mutableStateOf(hint != "") } Box(modifier = modifier) { BasicTextField( value = text, onValueChange = { // Assign the new text value text = it // Function that we trigger on value changed onSearch(it) }, maxLines = 1, singleLine = true, textStyle = TextStyle(color = Color.Black), modifier = Modifier .fillMaxWidth() .shadow(5.dp, CircleShape) .background(Color.White, CircleShape) .padding(horizontal = 20.dp, 12.dp) .onFocusChanged { /** * User clicked the text field, So we can hide the hint here * * If hte text field has focus we hide the hint & else show it */ /** * User clicked the text field, So we can hide the hint here * * If hte text field has focus we hide the hint & else show it */ /** * User clicked the text field, So we can hide the hint here * * If hte text field has focus we hide the hint & else show it */ /** * User clicked the text field, So we can hide the hint here * * If hte text field has focus we hide the hint & else show it */ isHintDisplayed = !it.hasFocus } ) if (isHintDisplayed) { Text( text = text, color = Color.LightGray, modifier = Modifier .padding(horizontal = 20.dp, 12.dp) ) } } }
0
Kotlin
1
7
3f7c261c677faeda5d66a8edea1ae6a6fe00fe76
3,487
PokedexApp
Apache License 2.0
shared/src/commonMain/kotlin/com/haeyum/shared/data/repository/translation/TranslationDataSource.kt
kisa002
584,385,916
false
{"Kotlin": 223546, "Ruby": 1722, "Swift": 860}
package com.haeyum.shared.data.repository.translation import com.haeyum.shared.data.model.detect.DetectionsResponse import com.haeyum.shared.data.model.languages.LanguagesResponse import com.haeyum.shared.data.model.translate.TranslateResponse interface TranslationDataSource { suspend fun translate(q: String, target: String, source: String): TranslateResponse suspend fun detectLanguage(q: String): DetectionsResponse suspend fun getLanguages(target: String) : LanguagesResponse }
1
Kotlin
2
51
fbe00ebee9ae05c5e10986b7dedabc4609c0085e
496
Transer
MIT License
src/test/java/io/github/pixee/maven/operator/test/util.kt
pixee
533,511,100
false
{"Kotlin": 164126, "Java": 1873}
package io.github.pixee.maven.operator.test import io.github.pixee.maven.operator.ProjectModel import io.github.pixee.maven.operator.Util.which import org.apache.commons.lang3.SystemUtils import org.dom4j.Document import org.dom4j.io.SAXReader import java.io.File import java.io.FileInputStream internal fun ProjectModel.getRuntimeResolvedProperties(): Map<String, String> = this.getEffectivePom().rootElement.elements("properties").flatMap { it.elements() } .associate { it.name to it.text } internal fun ProjectModel.getEffectivePom(): Document { val tmpInputFile = File.createTempFile("tmp-pom-orig", ".xml") tmpInputFile.writeBytes(this.pomFile.resultPomBytes) val tmpOutputFile = File.createTempFile("tmp-pom", ".xml") val processArgs: MutableList<String> = mutableListOf<String>( which("mvn")!!.absolutePath, "-B", "-N", "-f", tmpInputFile.absolutePath, ) if (SystemUtils.IS_OS_WINDOWS) { processArgs.addAll(0, listOf("cmd.exe", "/c")) } if (this.activeProfiles.isNotEmpty()) { // TODO Aldrin: How safe is not to escape those things? My concern is that deactivating a profile uses '!', // and I'm not sure how shell escaping rules play a part on that processArgs.addAll(listOf("-P", this.activeProfiles.joinToString(","))) } processArgs.addAll( listOf( "help:effective-pom", "-Doutput=${tmpOutputFile.absolutePath}" ) ) val psBuilder = ProcessBuilder(processArgs).inheritIO() psBuilder.environment().putAll(System.getenv()) val process = psBuilder.start() val retCode = process.waitFor() if (0 != retCode) throw IllegalStateException("Unexpected return code from maven: $retCode") return SAXReader().read(FileInputStream(tmpOutputFile)) }
2
Kotlin
1
1
8e13abe14705a024791d8d9e1f0b554257e4cd2d
1,941
pom-operator
MIT License
app/src/main/java/mx/com/movieschallenge/data/model/MovieData.kt
gibranhit
334,838,656
false
null
package mx.com.movieschallenge.data.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) @Entity(tableName = "movies", indices = [Index(value = ["title"], unique = true)]) data class MovieData( @PrimaryKey val id: Long = 0, @ColumnInfo var title: String? = null, @ColumnInfo val overview: String? = null, @ColumnInfo @SerializedName("release_date") val releaseDate: String? = null, @ColumnInfo @Json(name = "vote_average") val voteAverage: Double? = null, @ColumnInfo @Json(name = "vote_count") val voteCount: Long? = null, @Json(name = "poster_path") val posterPath: String? = null, @ColumnInfo val isFavorite: Boolean? = null, @ColumnInfo var page: Int? = null )
0
Kotlin
1
0
260a87cb477e617281786b0b7ac726f6c2b825e9
1,060
Movies-Challenge
MIT License
feature/game-board/src/main/kotlin/com/ekezet/othello/feature/gameboard/GameBoardModels.kt
atomgomba
754,770,216
false
{"Kotlin": 153818}
package com.ekezet.othello.feature.gameboard import androidx.compose.animation.core.AnimationConstants.DefaultDurationMillis import androidx.compose.runtime.Immutable import androidx.compose.ui.graphics.Color import com.ekezet.hurok.ActionEmitter import com.ekezet.hurok.ViewState import com.ekezet.othello.core.data.models.Disk import com.ekezet.othello.core.data.models.DiskCount import com.ekezet.othello.core.data.models.Position import com.ekezet.othello.core.game.OthelloGameState import com.ekezet.othello.core.game.data.BoardDisplayOptions import com.ekezet.othello.core.game.data.IGameSettings import com.ekezet.othello.core.game.data.defaultDarkStrategy import com.ekezet.othello.core.game.data.defaultDisplayOptions import com.ekezet.othello.core.game.data.defaultGameState import com.ekezet.othello.core.game.data.defaultLightStrategy import com.ekezet.othello.core.game.strategy.HumanPlayer import com.ekezet.othello.core.game.strategy.Strategy import com.ekezet.othello.feature.gameboard.ui.viewModels.BoardList import com.ekezet.othello.feature.gameboard.ui.viewModels.BoardOverlayList /** * Give a little time for humans to follow changes on the board */ internal const val ACTION_DELAY_MILLIS: Long = DefaultDurationMillis .times(1.5F) .toLong() data class GameBoardModel( internal val gameState: OthelloGameState = defaultGameState, override val displayOptions: BoardDisplayOptions = defaultDisplayOptions, override val lightStrategy: Strategy? = defaultLightStrategy, override val darkStrategy: Strategy? = defaultDarkStrategy, internal val nextMovePosition: Position? = null, internal val passed: Boolean = false, internal val ended: GameEnd? = null, ) : IGameSettings { internal val currentDisk: Disk inline get() = gameState.currentDisk internal val Disk.isHumanPlayer: Boolean get() = when (this) { Disk.Light -> lightStrategy == HumanPlayer Disk.Dark -> darkStrategy == HumanPlayer else -> error("Expected Light or Dark, but was $this") } internal fun resetNextTurn( nextState: OthelloGameState = defaultGameState, passed: Boolean = false, ) = copy( gameState = if (passed) nextState.lastState else nextState, nextMovePosition = null, ended = null, passed = passed, ) internal fun pickNextMoveAt(position: Position?) = copy( nextMovePosition = position, ) } @Immutable internal data class GameBoardState( val board: BoardList, val overlay: BoardOverlayList, val currentTurn: Int, val currentDisk: Disk, val darkStrategyName: String?, val lightStrategyName: String?, val opponentName: String?, val diskCount: DiskCount, val nextMovePosition: Position?, val displayOptions: BoardDisplayOptions, val ended: GameEnd?, val celebrate: Boolean, val isHumanPlayer: Boolean, val passed: Boolean, ) : ViewState<GameBoardModel, Unit>() { internal val boardBackground: Color inline get() = if (displayOptions.isGrayscaleMode) { Color(0xFFC0C0C0) } else { Color(0xFF338033) } } typealias GameBoardEmitter = ActionEmitter<GameBoardModel, Unit> sealed interface GameEnd { data class EndedWin(val winner: Disk) : GameEnd data object EndedTie : GameEnd }
0
Kotlin
0
0
80ad9a2bd4e35e819db98c7b2590103e60989c52
3,369
othello
Apache License 2.0
src/main/kotlin/ltd/lths/wireless/ikuai/entourage/command/Command.kt
LTHS20
487,755,461
false
null
package ltd.lths.wireless.ikuai.entourage.command import taboolib.common.platform.command.CommandCompleter import taboolib.common.platform.command.CommandExecutor import taboolib.common.platform.command.CommandStructure import taboolib.common.platform.command.component.CommandBase /** * ikuai-entourage * ltd.lths.wireless.ikuai.entourage.command.Command * * @author Score2 * @since 2022/06/08 0:18 */ data class Command( val command: CommandStructure, val executor: CommandExecutor, val completer: CommandCompleter, val commandBuilder: CommandBase.() -> Unit ) { val aliases get() = listOf(command.name, *command.aliases.toTypedArray()) fun register() = CommandManager.register(this) fun unregister() = CommandManager.unregister(this) }
0
Kotlin
0
3
22f7a15a63e9808de132e743a5186412e2012d2c
794
ikuai-entourage
MIT License
mockzilla-management-ui/common/src/commonMain/kotlin/com/apadmi/mockzilla/desktop/engine/connection/NetworkingUtils.kt
Apadmi-Engineering
570,496,992
false
{"Kotlin": 477134, "Dart": 135302, "Swift": 46784, "Ruby": 14009, "Objective-C": 76}
// Adapted from: https://github.com/ViToni/JmDNS-examples/blob/master/jmdns-examples/src/main/java/org/kromo/examples/network/NetworkUtils.java package com.apadmi.mockzilla.desktop.engine.connection import java.net.DatagramSocket import java.net.InetAddress import java.net.InetSocketAddress import java.net.NetworkInterface import java.util.Enumeration private const val googleDnsPort = 53 private val googleDns = InetSocketAddress("8.8.8.8", googleDnsPort) fun Enumeration<NetworkInterface>.isLocalIpAddress( address: String ) = toList().any { networkInterface -> networkInterface.inetAddresses.toList().any { it.hostAddress == address } } suspend fun Enumeration<NetworkInterface>.findMdnsAddresses(): List<InetAddress> = toList() .filterNot { networkInterface -> !networkInterface.isUp || // a down interface is not useful for us, isn't it !networkInterface.supportsMulticast() || // MC is required for mDNS networkInterface.isPointToPoint || // we care only about regular interfaces networkInterface.isLoopback // don't care about loopback addresses }.firstNotNullOfOrNull { networkInterface -> networkInterface.inetAddresses.toList() .filterNot { it.isLinkLocalAddress } .filter { runCatching { DatagramSocket(0, it).use { datagramSocket -> // try to connect to *somewhere* datagramSocket.connect(googleDns) } }.getOrNull() != null } } ?: emptyList()
10
Kotlin
8
29
9712fe59464b39d42e02c22a11a78964f437c502
1,581
Mockzilla
MIT License
src/main/kotlin/ar/edu/unq/peluqueriayabackend/service/emailSender/impl/EmailServiceImpl.kt
lisar01
253,115,230
false
null
package ar.edu.unq.peluqueriayabackend.service.emailSender.impl import ar.edu.unq.peluqueriayabackend.service.emailSender.EmailServiceAPI import org.springframework.beans.factory.annotation.Autowired import org.springframework.core.io.FileSystemResource import org.springframework.mail.SimpleMailMessage import org.springframework.mail.javamail.JavaMailSender import org.springframework.mail.javamail.MimeMessageHelper import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Service import java.io.File @Service class EmailServiceImpl(@Autowired private val emailSender:JavaMailSender):EmailServiceAPI { @Async("threadPoolTaskExecutor") override fun sendEmail(to: String, subject: String, text: String) { val message = SimpleMailMessage() message.setTo(to) message.setSubject(subject) message.setText(text) emailSender.send(message) } @Async("threadPoolTaskExecutor") override fun sendMessageWithAttachment(to: String, subject: String, text: String, pathToAttachment: String) { val message = emailSender.createMimeMessage() val helper = MimeMessageHelper(message, true) helper.setTo(to) helper.setSubject(subject) helper.setText(text) val file = FileSystemResource(File(pathToAttachment)) helper.addAttachment("Invoice", file) emailSender.send(message) } }
0
Kotlin
0
0
6d265ee1650fcba9d585d2272db4dda82f8d1174
1,452
peluqueriaya-backend
MIT License
app/src/main/java/com/jxareas/techhub/data/cache/model/CachedFavorite.kt
jxareas
503,617,148
false
{"Kotlin": 96040}
package com.jxareas.techhub.data.cache.model import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey import androidx.room.TypeConverters import com.jxareas.techhub.data.cache.constants.CacheConstants import com.jxareas.techhub.data.cache.converters.DateConverter import java.util.* @Entity( tableName = "favorites", foreignKeys = [ ForeignKey( entity = CachedCourse::class, parentColumns = [CacheConstants.COURSE_KEY], childColumns = [CacheConstants.COURSE_KEY], onDelete = ForeignKey.NO_ACTION, onUpdate = ForeignKey.CASCADE ) ], indices = [Index("courseId", unique = true)] ) data class CachedFavorite( @PrimaryKey(autoGenerate = true) val favoriteId: Int = 0, val courseId: Int, @TypeConverters(DateConverter::class) var dateAdded: Date ) : CachedEntity
0
Kotlin
7
41
ee28eb2992a2acca6e46ac5a928118e81ba3f861
934
TechHub
MIT License
src/main/kotlin/xyz/chlamydomonos/hyphacraft/items/utils/StyleUtil.kt
Chlamydomonos
832,406,228
false
{"Kotlin": 331361, "Java": 6074}
package xyz.chlamydomonos.hyphacraft.items.utils import net.minecraft.network.chat.Style object StyleUtil { val TOOLTIP = Style.EMPTY.withFont(Style.DEFAULT_FONT).withColor(0x808080) }
0
Kotlin
0
0
66942935b237b4ce243958544411809a09118e35
190
HyphaCraft
MIT License
app/src/main/java/com/shubham/pokedexapp/data/remote/response/Emerald.kt
shubham230523
434,489,494
false
null
package com.shubham.pokedexapp.data.remote.response data class Emerald( val front_default: String, val front_shiny: String )
0
Kotlin
0
0
cece7b0fb79cf0779ef0ea5d2101ff637352ccff
133
Pokedex-App
MIT License
app/src/main/java/com/shopemaa/android/storefront/utils/Utils.kt
shopemaa
522,682,752
false
{"Kotlin": 141588, "Makefile": 159, "Java": 155}
package com.shopemaa.android.storefront.utils import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import androidx.core.util.PatternsCompat import com.google.gson.Gson import com.google.zxing.* import com.google.zxing.common.HybridBinarizer import com.shopemaa.android.storefront.api.graphql.StoreBySecretQuery import com.shopemaa.android.storefront.contants.Constants import com.shopemaa.android.storefront.storage.CacheStorage import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import java.io.File import java.util.* import kotlin.math.roundToInt object Utils { private val dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") const val LocalCallbackSuccessUrl = "https://local-callback-success/" const val LocalCallbackFailureUrl = "https://local-callback-failure/" fun formatAmount(ctx: Context, amount: Int): String { return String.format("%s %.2f", getStore(ctx).currency, amount.toDouble() / 100.00) } fun formatAmount(ctx: Context, amount: Int, reverseCurrency: Boolean): String { if (reverseCurrency.not()) { return formatAmount(ctx, amount) } return String.format("%.2f %s", amount.toDouble() / 100.00, getStore(ctx).currency) } fun discountedPrice(discount: Int, amount: Int): Int { return amount - ((discount * amount) / 100) } fun formatDateWithTime(v: String): String { return DateTime.parse(v, dateTimeFormatter).toLocalDateTime().toString("dd/MM/yyyy hh:mm a") } fun formatDate(v: String): String { return DateTime.parse(v, dateTimeFormatter).toLocalDateTime().toString("dd/MM/yyyy") } fun isEmail(v: String): Boolean { return PatternsCompat.EMAIL_ADDRESS.matcher(v).matches() } fun getScreenWidthDp(ctx: Context): Int { return (ctx.resources.displayMetrics.widthPixels / ctx.resources.displayMetrics.scaledDensity).roundToInt() } fun getScreenHeightDp(ctx: Context): Int { return (ctx.resources.displayMetrics.heightPixels / ctx.resources.displayMetrics.scaledDensity).roundToInt() } fun getStore(ctx: Context): StoreBySecretQuery.StoreBySecret { val c = CacheStorage(ctx) return Gson().fromJson( c.get(Constants.shopLabel), StoreBySecretQuery.StoreBySecret::class.java ) } private fun rotateBitmap(source: Bitmap, angle: Float): Bitmap { val matrix = Matrix() matrix.postRotate(angle) return Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true) } @Throws(Exception::class) fun parseQRCodeFromImage(f: File): String { var result: String = "" try { val bitMap = BitmapFactory.decodeFile(f.absolutePath) ?: throw Exception("Bitmap is NULL") val intArray = JUtil.getIntArray(bitMap.width * bitMap.height) bitMap.getPixels(intArray, 0, bitMap.width, 0, 0, bitMap.width, bitMap.height) bitMap.recycle() val source = RGBLuminanceSource(bitMap.width, bitMap.height, intArray) val binaryBitmap = BinaryBitmap(HybridBinarizer(source)) val tmpHintsMap: Map<DecodeHintType, Any> = mutableMapOf() tmpHintsMap.plus(Pair(DecodeHintType.TRY_HARDER, true)) tmpHintsMap.plus( Pair( DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat::class.java) ) ) val reader = MultiFormatReader() val decoded = reader.decode(binaryBitmap, tmpHintsMap) result = decoded.text } catch (e: NotFoundException) { try { var bitMap = BitmapFactory.decodeFile(f.absolutePath) ?: throw Exception("Bitmap is NULL") bitMap = rotateBitmap(bitMap, 90f) val intArray = JUtil.getIntArray(bitMap.width * bitMap.height) bitMap.getPixels(intArray, 0, bitMap.width, 0, 0, bitMap.width, bitMap.height) bitMap.recycle() val source = RGBLuminanceSource(bitMap.width, bitMap.height, intArray) val binaryBitmap = BinaryBitmap(HybridBinarizer(source)) val tmpHintsMap: Map<DecodeHintType, Any> = mutableMapOf() tmpHintsMap.plus(Pair(DecodeHintType.TRY_HARDER, true)) tmpHintsMap.plus( Pair( DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat::class.java) ) ) val reader = MultiFormatReader() val decoded = reader.decode(binaryBitmap, tmpHintsMap) result = decoded.text } catch (e: Exception) { throw e } } catch (e: Exception) { throw e } return result } }
0
Kotlin
3
9
3f471a20f1c01a62284c0da4a82bd85a203ccfc8
5,052
ShopemaaAndroidStorefront
MIT License
modules/core/src/main/kotlin/wrapper/VNodeDataBuilder.kt
eEQK
208,978,173
true
{"Kotlin": 90137, "CSS": 16605, "HTML": 557, "JavaScript": 156}
@file:Suppress("unused") package wrapper import cssdsl.CssRule import cssdsl.CssRulesBlock import external.vue.* open class VNodeDataBuilder<P, A, D> : VNodeData<P, A, D> { var children: ArrayList<VNode> = arrayListOf() var propsBuilder: (P.() -> Unit)? = null var attributeBuilder: (A.() -> Unit)? = null var domPropsBuilder: (D.() -> Unit)? = null operator fun String.unaryPlus() { children.add(this.unsafeCast<VNode>()) } fun child(child: VNode) { children.add(child) } fun props(builder: P.() -> Unit) { propsBuilder = builder } fun attrs(builder: A.() -> Unit) { attributeBuilder = builder } fun domProps(builder: D.() -> Unit) { domPropsBuilder = builder } fun style(builder: CssRulesBlock) { val vCssRule = CssRule.of(builder) style = vCssRule.toString() } fun directives(builder: VDirectivesBuilder.() -> Unit) { directives = VDirectivesBuilder().apply(builder).vDirectives.toTypedArray() } fun scopedSlots(builder: VScopedSlotsBuilder.() -> Unit) { VScopedSlotsBuilder().apply(builder) } fun on(builder: VOnEvents.() -> Unit) { VOnEvents().apply(builder) } fun nativeOn(builder: VOnEvents.() -> Unit) { VOnEvents().apply(builder) } fun <R> addOnEvent(eventName: String, callback: EventCallback<R>) { on ?: run { on = VOnEvents() } on!![eventName] = callback } fun <R> addOnEvents(eventName: String, builder: EventCallbacksBuilder<R>) { on ?: run { on = VOnEvents() } on!![eventName] = arrayListOf<EventCallback<R>>().apply(builder).toTypedArray() } inner class VScopedSlotsBuilder { operator fun <Props> String.invoke(scopedSlot: ScopedSlot<Props>) { scopedSlots ?: run { scopedSlots = VScopedSlots() } scopedSlots!![this] = scopedSlot } operator fun String.invoke(normalizedScopedSlot: NormalizedScopedSlot) { scopedSlots ?: run { scopedSlots = VScopedSlots() } scopedSlots!![this] = normalizedScopedSlot } } inner class VOnEvents : VWebEvents() { operator fun <R> String.invoke(callback: EventCallback<R>) = addOnEvent(this, callback) fun custom(eventName: String, builder: EventCallbacksBuilder<Any>) = addOnEvents(eventName, builder) } }
0
Kotlin
0
2
b0a87e432879a4a96076cfda27023f1b5cff8315
2,418
kotlin-vue
Apache License 2.0
app/src/main/java/com/example/bitfit2/MainActivity.kt
kamrynbrown
545,211,768
false
null
package com.example.bitfit2 import android.app.Activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.bitfit2.Data.Food import com.example.bitfit2.Data.FoodDatabase import com.google.android.material.bottomnavigation.BottomNavigationView import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { lateinit var BottomNav: BottomNavigationView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) BottomNav = findViewById(R.id.BottomNav) supportFragmentManager.beginTransaction().replace(R.id.Frame, DashboardFragment()).commit() BottomNav.setOnNavigationItemSelectedListener(BottomNavigationView.OnNavigationItemSelectedListener { lateinit var selectedfragement:Fragment when(it.itemId){ R.id.Dashboard->{ selectedfragement = DashboardFragment() } R.id.AddNewFood->{ selectedfragement = AddFoodFragment() } } supportFragmentManager.beginTransaction().replace(R.id.Frame, selectedfragement).commit() true }) } }
2
Kotlin
0
0
0049f0309e4e2581e8b589d42b8a513b2d959e20
1,577
BitFit1
Apache License 2.0
src/test/kotlin/no/nav/sosialhjelp/modia/digisossak/event/EventTestData.kt
navikt
216,780,859
false
{"Kotlin": 461383, "Dockerfile": 427}
package no.nav.sosialhjelp.modia.digisossak.event import no.nav.sbl.soknadsosialhjelp.digisos.soker.JsonAvsender import no.nav.sbl.soknadsosialhjelp.digisos.soker.JsonFilreferanse import no.nav.sbl.soknadsosialhjelp.digisos.soker.JsonForvaltningsbrev import no.nav.sbl.soknadsosialhjelp.digisos.soker.JsonHendelse import no.nav.sbl.soknadsosialhjelp.digisos.soker.filreferanse.JsonDokumentlagerFilreferanse import no.nav.sbl.soknadsosialhjelp.digisos.soker.filreferanse.JsonSvarUtFilreferanse import no.nav.sbl.soknadsosialhjelp.digisos.soker.hendelse.JsonDokumentasjonEtterspurt import no.nav.sbl.soknadsosialhjelp.digisos.soker.hendelse.JsonDokumentasjonkrav import no.nav.sbl.soknadsosialhjelp.digisos.soker.hendelse.JsonDokumenter import no.nav.sbl.soknadsosialhjelp.digisos.soker.hendelse.JsonForelopigSvar import no.nav.sbl.soknadsosialhjelp.digisos.soker.hendelse.JsonSaksStatus import no.nav.sbl.soknadsosialhjelp.digisos.soker.hendelse.JsonSoknadsStatus import no.nav.sbl.soknadsosialhjelp.digisos.soker.hendelse.JsonTildeltNavKontor import no.nav.sbl.soknadsosialhjelp.digisos.soker.hendelse.JsonUtbetaling import no.nav.sbl.soknadsosialhjelp.digisos.soker.hendelse.JsonVedtakFattet import no.nav.sbl.soknadsosialhjelp.digisos.soker.hendelse.JsonVedtaksfil import no.nav.sbl.soknadsosialhjelp.digisos.soker.hendelse.JsonVilkar import no.nav.sosialhjelp.api.fiks.DigisosSak import no.nav.sosialhjelp.api.fiks.DigisosSoker import no.nav.sosialhjelp.api.fiks.DokumentInfo import no.nav.sosialhjelp.api.fiks.OriginalSoknadNAV import no.nav.sosialhjelp.api.fiks.Tilleggsinformasjon import java.time.ZonedDateTime import java.time.format.DateTimeFormatter const val dokumentlagerId_1 = "1" const val dokumentlagerId_2 = "2" const val svarUtId = "42" const val svarUtNr = 42 const val enhetsnavn = "The Office" const val enhetsnr = "2317" const val navKontor = "1337" const val navKontor2 = "2244" const val tittel_1 = "tittel" const val tittel_2 = "tittel2" const val referanse_1 = "sak1" const val referanse_2 = "sak2" const val utbetaling_ref_1 = "utbetaling 1" const val vilkar_ref_1 = "ulike vilkar" const val dokumentasjonkrav_ref_1 = "dette må du gjøre for å få pengene" const val dokumenttype = "dokumentasjonstype" const val tilleggsinfo = "ekstra info" val avsender: JsonAvsender = JsonAvsender().withSystemnavn("test").withSystemversjon("123") private val now = ZonedDateTime.now() val tidspunkt_soknad = now.minusHours(11).toEpochSecond() * 1000L val tidspunkt_1: String = now.minusHours(10).format(DateTimeFormatter.ISO_DATE_TIME) val tidspunkt_2: String = now.minusHours(9).format(DateTimeFormatter.ISO_DATE_TIME) val tidspunkt_3: String = now.minusHours(8).format(DateTimeFormatter.ISO_DATE_TIME) val tidspunkt_4: String = now.minusHours(7).format(DateTimeFormatter.ISO_DATE_TIME) val tidspunkt_5: String = now.minusHours(6).format(DateTimeFormatter.ISO_DATE_TIME) val tidspunkt_6: String = now.minusHours(5).format(DateTimeFormatter.ISO_DATE_TIME) val innsendelsesfrist: String = now.plusDays(7).format(DateTimeFormatter.ISO_DATE_TIME) val DOKUMENTLAGER_1: JsonDokumentlagerFilreferanse = JsonDokumentlagerFilreferanse().withType(JsonFilreferanse.Type.DOKUMENTLAGER).withId(dokumentlagerId_1) val DOKUMENTLAGER_2: JsonDokumentlagerFilreferanse = JsonDokumentlagerFilreferanse().withType(JsonFilreferanse.Type.DOKUMENTLAGER).withId(dokumentlagerId_2) val SVARUT_1: JsonSvarUtFilreferanse = JsonSvarUtFilreferanse().withType(JsonFilreferanse.Type.DOKUMENTLAGER).withId(svarUtId).withNr(svarUtNr) val SOKNADS_STATUS_MOTTATT: JsonSoknadsStatus = JsonSoknadsStatus() .withType(JsonHendelse.Type.SOKNADS_STATUS) .withStatus(JsonSoknadsStatus.Status.MOTTATT) val SOKNADS_STATUS_UNDERBEHANDLING: JsonSoknadsStatus = JsonSoknadsStatus() .withType(JsonHendelse.Type.SOKNADS_STATUS) .withStatus(JsonSoknadsStatus.Status.UNDER_BEHANDLING) val SOKNADS_STATUS_FERDIGBEHANDLET: JsonSoknadsStatus = JsonSoknadsStatus() .withType(JsonHendelse.Type.SOKNADS_STATUS) .withStatus(JsonSoknadsStatus.Status.FERDIGBEHANDLET) val TILDELT_NAV_KONTOR: JsonTildeltNavKontor = JsonTildeltNavKontor() .withType(JsonHendelse.Type.TILDELT_NAV_KONTOR) .withNavKontor(navKontor) val TILDELT_NAV_KONTOR_2: JsonTildeltNavKontor = JsonTildeltNavKontor() .withType(JsonHendelse.Type.TILDELT_NAV_KONTOR) .withNavKontor(navKontor2) val TILDELT_EMPTY_NAV_KONTOR: JsonTildeltNavKontor = JsonTildeltNavKontor() .withType(JsonHendelse.Type.TILDELT_NAV_KONTOR) .withNavKontor("") val SAK1_SAKS_STATUS_UNDERBEHANDLING: JsonSaksStatus = JsonSaksStatus() .withType(JsonHendelse.Type.SAKS_STATUS) .withStatus(JsonSaksStatus.Status.UNDER_BEHANDLING) .withTittel(tittel_1) .withReferanse(referanse_1) val SAK1_UTEN_SAKS_STATUS_ELLER_TITTEL: JsonSaksStatus = JsonSaksStatus() .withType(JsonHendelse.Type.SAKS_STATUS) .withReferanse(referanse_1) val SAK1_SAKS_STATUS_IKKEINNSYN: JsonSaksStatus = JsonSaksStatus() .withType(JsonHendelse.Type.SAKS_STATUS) .withStatus(JsonSaksStatus.Status.IKKE_INNSYN) .withTittel(tittel_1) .withReferanse(referanse_1) val SAK2_SAKS_STATUS_UNDERBEHANDLING: JsonSaksStatus = JsonSaksStatus() .withType(JsonHendelse.Type.SAKS_STATUS) .withStatus(JsonSaksStatus.Status.UNDER_BEHANDLING) .withTittel(tittel_2) .withReferanse(referanse_2) val SAK1_VEDTAK_FATTET_INNVILGET: JsonVedtakFattet = JsonVedtakFattet() .withType(JsonHendelse.Type.VEDTAK_FATTET) .withSaksreferanse(referanse_1) .withVedtaksfil(JsonVedtaksfil().withReferanse(DOKUMENTLAGER_1)) .withUtfall(JsonVedtakFattet.Utfall.INNVILGET) val SAK1_VEDTAK_FATTET_UTEN_UTFALL: JsonVedtakFattet = JsonVedtakFattet() .withType(JsonHendelse.Type.VEDTAK_FATTET) .withSaksreferanse(referanse_1) .withVedtaksfil(JsonVedtaksfil().withReferanse(DOKUMENTLAGER_1)) val SAK1_VEDTAK_FATTET_AVSLATT: JsonVedtakFattet = JsonVedtakFattet() .withType(JsonHendelse.Type.VEDTAK_FATTET) .withSaksreferanse(referanse_1) .withVedtaksfil(JsonVedtaksfil().withReferanse(DOKUMENTLAGER_2)) .withUtfall(JsonVedtakFattet.Utfall.AVSLATT) val SAK2_VEDTAK_FATTET: JsonVedtakFattet = JsonVedtakFattet() .withType(JsonHendelse.Type.VEDTAK_FATTET) .withSaksreferanse(referanse_2) .withVedtaksfil(JsonVedtaksfil().withReferanse(SVARUT_1)) .withUtfall(JsonVedtakFattet.Utfall.INNVILGET) val DOKUMENTASJONETTERSPURT: JsonDokumentasjonEtterspurt = JsonDokumentasjonEtterspurt() .withType(JsonHendelse.Type.DOKUMENTASJON_ETTERSPURT) .withDokumenter(mutableListOf(JsonDokumenter().withInnsendelsesfrist(innsendelsesfrist).withDokumenttype(dokumenttype).withTilleggsinformasjon(tilleggsinfo))) .withForvaltningsbrev(JsonForvaltningsbrev().withReferanse(DOKUMENTLAGER_1)) val DOKUMENTASJONETTERSPURT_TOM_DOKUMENT_LISTE: JsonDokumentasjonEtterspurt = JsonDokumentasjonEtterspurt() .withType(JsonHendelse.Type.DOKUMENTASJON_ETTERSPURT) .withForvaltningsbrev(JsonForvaltningsbrev().withReferanse(DOKUMENTLAGER_1)) val DOKUMENTASJONETTERSPURT_UTEN_FORVALTNINGSBREV: JsonDokumentasjonEtterspurt = JsonDokumentasjonEtterspurt() .withType(JsonHendelse.Type.DOKUMENTASJON_ETTERSPURT) .withDokumenter(mutableListOf(JsonDokumenter().withInnsendelsesfrist(innsendelsesfrist).withDokumenttype(dokumenttype).withTilleggsinformasjon(tilleggsinfo))) val FORELOPIGSVAR: JsonForelopigSvar = JsonForelopigSvar() .withType(JsonHendelse.Type.FORELOPIG_SVAR) .withForvaltningsbrev(JsonForvaltningsbrev().withReferanse(SVARUT_1)) val UTBETALING: JsonUtbetaling = JsonUtbetaling() .withType(JsonHendelse.Type.UTBETALING) .withUtbetalingsreferanse(utbetaling_ref_1) .withSaksreferanse(referanse_1) .withRammevedtaksreferanse(null) .withStatus(JsonUtbetaling.Status.UTBETALT) .withBelop(1234.56) .withBeskrivelse(tittel_1) .withForfallsdato("2019-12-31") .withUtbetalingsdato("2019-12-24") .withFom("2019-12-01") .withTom("2019-12-31") .withAnnenMottaker(false) .withMottaker("fnr") .withKontonummer("kontonummer") .withUtbetalingsmetode("pose med krølla femtilapper") val UTBETALING_ANNEN_MOTTAKER: JsonUtbetaling = JsonUtbetaling() .withType(JsonHendelse.Type.UTBETALING) .withUtbetalingsreferanse(utbetaling_ref_1) .withSaksreferanse(referanse_1) .withRammevedtaksreferanse(null) .withStatus(JsonUtbetaling.Status.UTBETALT) .withBelop(1234.56) .withBeskrivelse(tittel_1) .withForfallsdato("2019-12-31") .withUtbetalingsdato("2019-12-24") .withFom(null) .withTom(null) .withAnnenMottaker(true) .withMottaker("utleier") .withKontonummer(null) .withUtbetalingsmetode("pose med krølla femtilapper") val VILKAR_OPPFYLT: JsonVilkar = JsonVilkar() .withType(JsonHendelse.Type.VILKAR) .withVilkarreferanse(vilkar_ref_1) .withUtbetalingsreferanse(listOf(utbetaling_ref_1)) .withBeskrivelse("beskrivelse") .withStatus(JsonVilkar.Status.RELEVANT) val DOKUMENTASJONKRAV_OPPFYLT: JsonDokumentasjonkrav = JsonDokumentasjonkrav() .withType(JsonHendelse.Type.DOKUMENTASJONKRAV) .withDokumentasjonkravreferanse(dokumentasjonkrav_ref_1) .withUtbetalingsreferanse(listOf(utbetaling_ref_1)) .withBeskrivelse("beskrivelse") .withStatus(JsonDokumentasjonkrav.Status.OPPFYLT) val DOKUMENTASJONKRAV_RELEVANT: JsonDokumentasjonkrav = JsonDokumentasjonkrav() .withType(JsonHendelse.Type.DOKUMENTASJONKRAV) .withDokumentasjonkravreferanse(dokumentasjonkrav_ref_1) .withUtbetalingsreferanse(listOf(utbetaling_ref_1)) .withBeskrivelse("beskrivelse") .withStatus(JsonDokumentasjonkrav.Status.RELEVANT) fun resetHendelser() { SOKNADS_STATUS_MOTTATT.withHendelsestidspunkt(null) SOKNADS_STATUS_UNDERBEHANDLING.withHendelsestidspunkt(null) SOKNADS_STATUS_FERDIGBEHANDLET.withHendelsestidspunkt(null) TILDELT_NAV_KONTOR.withHendelsestidspunkt(null) TILDELT_NAV_KONTOR_2.withHendelsestidspunkt(null) SAK1_SAKS_STATUS_UNDERBEHANDLING.withHendelsestidspunkt(null) SAK1_SAKS_STATUS_IKKEINNSYN.withHendelsestidspunkt(null) SAK2_SAKS_STATUS_UNDERBEHANDLING.withHendelsestidspunkt(null) SAK1_VEDTAK_FATTET_INNVILGET.withHendelsestidspunkt(null) SAK1_VEDTAK_FATTET_AVSLATT.withHendelsestidspunkt(null) SAK2_VEDTAK_FATTET.withHendelsestidspunkt(null) DOKUMENTASJONETTERSPURT.withHendelsestidspunkt(null) DOKUMENTASJONETTERSPURT_UTEN_FORVALTNINGSBREV.withHendelsestidspunkt(null) DOKUMENTASJONETTERSPURT_TOM_DOKUMENT_LISTE.withHendelsestidspunkt(null) FORELOPIGSVAR.withHendelsestidspunkt(null) UTBETALING.withHendelsestidspunkt(null) DOKUMENTASJONKRAV_OPPFYLT.withHendelsestidspunkt(null) VILKAR_OPPFYLT.withHendelsestidspunkt(null) } val defaultDigisosSak = DigisosSak( fiksDigisosId = "123", sokerFnr = "fnr", fiksOrgId = "", kommunenummer = "0301", sistEndret = 1L, originalSoknadNAV = OriginalSoknadNAV( navEksternRefId = "eksternRef", metadata = "some other id", vedleggMetadata = "", soknadDokument = DokumentInfo( filnavn = "soknad.json", dokumentlagerDokumentId = "soknaddokumentlagerid", storrelse = 99L ), vedlegg = emptyList(), timestampSendt = tidspunkt_soknad ), ettersendtInfoNAV = null, digisosSoker = DigisosSoker( metadata = "some id", dokumenter = emptyList(), timestampSistOppdatert = 123L ), tilleggsinformasjon = Tilleggsinformasjon( enhetsnummer = enhetsnr ) )
1
Kotlin
0
1
562e5f9c2d1e2eeae562c2549e30f9782b3039df
11,589
sosialhjelp-modia-api
MIT License
androidApp/src/main/java/com/nbs/kmm/sample/android/presentation/post/PostStoryActivity.kt
nbsmobile
597,042,861
false
{"Kotlin": 144840, "Swift": 52478, "Ruby": 2440, "Java": 1515}
package com.nbs.kmm.sample.android.presentation.post import android.content.Context import android.content.Intent import androidx.activity.viewModels import com.nbs.kmm.sample.android.R import com.nbs.kmm.sample.android.base.SampleBaseActivity import com.nbs.kmm.sample.android.databinding.ActivityPostStoryBinding import com.nbs.kmm.sample.android.presentation.reuse.camera.CameraActivity import com.nbs.kmm.sample.android.presentation.reuse.camera.PhotoResult import com.nbs.kmm.sample.android.utils.data.Resource import com.nbs.kmm.sample.android.utils.showToast import com.nbs.kmm.sample.android.utils.util.showErrorAlert import com.nbs.kmm.sample.android.viewmodel.StoryViewModel import org.koin.androidx.viewmodel.ext.android.viewModel import java.io.File class PostStoryActivity : SampleBaseActivity<ActivityPostStoryBinding>() { companion object { const val UPLOAD_PHOTO_STORY_CODE = 3434 @JvmStatic fun start(context: Context) { context.startActivity(Intent(context, PostStoryActivity::class.java)) } } override fun getViewBinding() = ActivityPostStoryBinding.inflate(layoutInflater) private val storyViewModel: StoryViewModel by viewModel() private lateinit var selectedFile: File override fun initIntent() {} override fun initUI() { setupToolbar(binding.layoutToolbar.toolbar, "Tambah Story", true) } override fun initAction() { with(binding) { cuivPhotoStory.setOnClickListener { cuivPhotoStory.openCamera(UPLOAD_PHOTO_STORY_CODE) } btnPost.setOnClickListener { storyViewModel.uploadStory( selectedFile.readBytes(), edtDescription.text.toString() ) } } } override fun initProses() {} override fun initObservers() { storyViewModel.uploadStoryResult.observe(this) { when (it) { is Resource.Loading -> { showLoading() } is Resource.Success -> { hideLoading() showToast(getString(R.string.upload_success)) finish() } is Resource.Failure -> { hideLoading() showErrorAlert(it.throwable, it.message.toString()) } else -> {} } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == RESULT_OK) { data?.let { val result = it.getSerializableExtra(CameraActivity.PHOTO_RESULT_PATH) as PhotoResult selectedFile = result.resultFile if (requestCode == UPLOAD_PHOTO_STORY_CODE) { binding.cuivPhotoStory.setResultImage(selectedFile.absolutePath) } } } } }
2
Kotlin
19
71
83396b2c1354f07e7c0cfc580de4ac851bd4efb2
3,037
incio
MIT License
Matcheap/app/src/main/java/com/sandy/seoul_matcheap/ui/store/StoreListFragment.kt
SANDY-9
677,761,441
false
{"Kotlin": 217577, "Java": 2281}
package com.sandy.seoul_matcheap.ui.store import android.location.Location import android.os.Bundle import android.view.* import android.widget.* import androidx.fragment.app.* import androidx.navigation.fragment.navArgs import androidx.paging.PagingData import androidx.paging.filter import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.tabs.TabLayout import com.sandy.seoul_matcheap.R import com.sandy.seoul_matcheap.data.store.dao.StoreItem import com.sandy.seoul_matcheap.databinding.FragmentStoreListBinding import com.sandy.seoul_matcheap.extension.connectPagerWithTabLayout import com.sandy.seoul_matcheap.ui.LocationViewModel import com.sandy.seoul_matcheap.ui.BaseFragment import com.sandy.seoul_matcheap.adapters.PagerAdapter import com.sandy.seoul_matcheap.adapters.StoreListAdapter import com.sandy.seoul_matcheap.util.constants.* import dagger.hilt.android.AndroidEntryPoint import showProgressView @AndroidEntryPoint class StoreListFragment : BaseFragment<FragmentStoreListBinding>(R.layout.fragment_store_list) { private val storeViewModel: StoreViewModel by viewModels() private val args: StoreListFragmentArgs by navArgs() private val locationViewModel: LocationViewModel by activityViewModels() private val location: Location by lazy { locationViewModel.getCurLocation() } override fun setupBinding(): FragmentStoreListBinding = binding.apply { fragment = this@StoreListFragment lifecycleOwner = viewLifecycleOwner viewModel = storeViewModel } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.progressView.showProgressView() super.onViewCreated(view, savedInstanceState) } private var pagerAdapter: PagerAdapter<StoreListAdapter>? = null override fun initGlobalVariables() { pagerAdapter = PagerAdapter(StoreListAdapter()).apply { setOnScrollChangeListener { binding.btnTop.visibility = if(it > DEFAULT_POSITION) View.VISIBLE else View.GONE } } } override fun initView() = binding.run { val type = args.type val category = args.category pager.init(type, category, tabLayout, progressView) tvTitle.text = if(type == TYPE_CATEGORY) TYPE_CATEGORY_NAME else category tvGps.text = args.address } private fun ViewPager2.init(type: Int, category: String, tabLayout: TabLayout, progressView: FrameLayout,) { adapter = pagerAdapter connectPagerWithTabLayout(tabLayout, progressView, requireContext()) val defaultPosition = if(type == TYPE_CATEGORY) category.toInt() else DEFAULT_POSITION setCurrentItem(defaultPosition, false) setPagerPosition(type, category, defaultPosition) setOnPageChangeListener(type, category, defaultPosition) } private fun setPagerPosition(type: Int, category: String, position: Int) { pagerAdapter!!.adapter[position]?.setOnItemClickListener { navigateToStoreDetails(it) } storeViewModel.updateStoreCount(type, category, position, location) binding.btnTop.setOnClickListener { pagerAdapter!!.initScroll(position, TYPE_SMOOTH_SCROLL) } } private fun ViewPager2.setOnPageChangeListener(type: Int, category: String, defaultPosition: Int) { val onPageChangeCallback = object : ViewPager2.OnPageChangeCallback() { var oldPosition = defaultPosition override fun onPageSelected(newPosition: Int) { super.onPageSelected(newPosition) // because current state of old page is recycled, have to be restored old page to default scroll state. // whenever page change, old page have to is scrolled to top. pagerAdapter!!.initScroll(oldPosition, TYPE_NORMAL_SCROLL) oldPosition = newPosition setPagerPosition(type, category, newPosition) } } registerOnPageChangeCallback(onPageChangeCallback) } override fun subscribeToObservers() { storeViewModel.getStoreList(args.type, args.category, location).observe(viewLifecycleOwner) { handleStoreListData(it) } } //why submit data to all of pagerAdapter is because thinking of swipe handling of viewpager. //when swiping, both sides of current page have to already be generated. private fun handleStoreListData(storePagingData: PagingData<StoreItem>) { repeat(CATEGORY_SIZE) { position -> pagerAdapter?.run { adapter[position]!!.submitData(lifecycle, filteredStoreList(position, storePagingData)) } } } private fun filteredStoreList(position: Int, stores: PagingData<StoreItem>) = when (position) { DEFAULT_POSITION -> stores else -> stores.filter { it.code == "$position" } } override fun destroyGlobalVariables() { pagerAdapter = null } private companion object { private const val TYPE_CATEGORY_NAME = "우리 동네 착한가격업소" } }
0
Kotlin
0
0
3b84686b3d409bf7cbbc3044798d73b8dc54cd5b
5,104
Project_SeoulMatcheap2.0
Apache License 2.0
Matcheap/app/src/main/java/com/sandy/seoul_matcheap/ui/store/StoreListFragment.kt
SANDY-9
677,761,441
false
{"Kotlin": 217577, "Java": 2281}
package com.sandy.seoul_matcheap.ui.store import android.location.Location import android.os.Bundle import android.view.* import android.widget.* import androidx.fragment.app.* import androidx.navigation.fragment.navArgs import androidx.paging.PagingData import androidx.paging.filter import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.tabs.TabLayout import com.sandy.seoul_matcheap.R import com.sandy.seoul_matcheap.data.store.dao.StoreItem import com.sandy.seoul_matcheap.databinding.FragmentStoreListBinding import com.sandy.seoul_matcheap.extension.connectPagerWithTabLayout import com.sandy.seoul_matcheap.ui.LocationViewModel import com.sandy.seoul_matcheap.ui.BaseFragment import com.sandy.seoul_matcheap.adapters.PagerAdapter import com.sandy.seoul_matcheap.adapters.StoreListAdapter import com.sandy.seoul_matcheap.util.constants.* import dagger.hilt.android.AndroidEntryPoint import showProgressView @AndroidEntryPoint class StoreListFragment : BaseFragment<FragmentStoreListBinding>(R.layout.fragment_store_list) { private val storeViewModel: StoreViewModel by viewModels() private val args: StoreListFragmentArgs by navArgs() private val locationViewModel: LocationViewModel by activityViewModels() private val location: Location by lazy { locationViewModel.getCurLocation() } override fun setupBinding(): FragmentStoreListBinding = binding.apply { fragment = this@StoreListFragment lifecycleOwner = viewLifecycleOwner viewModel = storeViewModel } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.progressView.showProgressView() super.onViewCreated(view, savedInstanceState) } private var pagerAdapter: PagerAdapter<StoreListAdapter>? = null override fun initGlobalVariables() { pagerAdapter = PagerAdapter(StoreListAdapter()).apply { setOnScrollChangeListener { binding.btnTop.visibility = if(it > DEFAULT_POSITION) View.VISIBLE else View.GONE } } } override fun initView() = binding.run { val type = args.type val category = args.category pager.init(type, category, tabLayout, progressView) tvTitle.text = if(type == TYPE_CATEGORY) TYPE_CATEGORY_NAME else category tvGps.text = args.address } private fun ViewPager2.init(type: Int, category: String, tabLayout: TabLayout, progressView: FrameLayout,) { adapter = pagerAdapter connectPagerWithTabLayout(tabLayout, progressView, requireContext()) val defaultPosition = if(type == TYPE_CATEGORY) category.toInt() else DEFAULT_POSITION setCurrentItem(defaultPosition, false) setPagerPosition(type, category, defaultPosition) setOnPageChangeListener(type, category, defaultPosition) } private fun setPagerPosition(type: Int, category: String, position: Int) { pagerAdapter!!.adapter[position]?.setOnItemClickListener { navigateToStoreDetails(it) } storeViewModel.updateStoreCount(type, category, position, location) binding.btnTop.setOnClickListener { pagerAdapter!!.initScroll(position, TYPE_SMOOTH_SCROLL) } } private fun ViewPager2.setOnPageChangeListener(type: Int, category: String, defaultPosition: Int) { val onPageChangeCallback = object : ViewPager2.OnPageChangeCallback() { var oldPosition = defaultPosition override fun onPageSelected(newPosition: Int) { super.onPageSelected(newPosition) // because current state of old page is recycled, have to be restored old page to default scroll state. // whenever page change, old page have to is scrolled to top. pagerAdapter!!.initScroll(oldPosition, TYPE_NORMAL_SCROLL) oldPosition = newPosition setPagerPosition(type, category, newPosition) } } registerOnPageChangeCallback(onPageChangeCallback) } override fun subscribeToObservers() { storeViewModel.getStoreList(args.type, args.category, location).observe(viewLifecycleOwner) { handleStoreListData(it) } } //why submit data to all of pagerAdapter is because thinking of swipe handling of viewpager. //when swiping, both sides of current page have to already be generated. private fun handleStoreListData(storePagingData: PagingData<StoreItem>) { repeat(CATEGORY_SIZE) { position -> pagerAdapter?.run { adapter[position]!!.submitData(lifecycle, filteredStoreList(position, storePagingData)) } } } private fun filteredStoreList(position: Int, stores: PagingData<StoreItem>) = when (position) { DEFAULT_POSITION -> stores else -> stores.filter { it.code == "$position" } } override fun destroyGlobalVariables() { pagerAdapter = null } private companion object { private const val TYPE_CATEGORY_NAME = "우리 동네 착한가격업소" } }
0
Kotlin
0
0
3b84686b3d409bf7cbbc3044798d73b8dc54cd5b
5,104
Project_SeoulMatcheap2.0
Apache License 2.0
chat-app-common/src/ktor/chat/messages/MessageInput.kt
bjhham
838,751,258
false
{"Kotlin": 72979}
package ktor.chat.messages import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.Send import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.isShiftPressed import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onKeyEvent import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch @Composable fun MessageInput(send: suspend (String) -> Unit) { val coroutineScope = rememberCoroutineScope() var message by remember { mutableStateOf("") } // TODO loading feedback fun sendMessage() { val messageToSend = message coroutineScope.launch { send(messageToSend.trim()) } message = "" } Spacer(Modifier.height(10.dp)) Box { TextField( value = message, placeholder = { Text("Type a message...") }, onValueChange = { message = it }, modifier = Modifier.fillMaxWidth().onKeyEvent { e -> when (e.key.keyCode) { Key.Enter.keyCode -> { if (!e.isShiftPressed) sendMessage() true } else -> false } } ) IconButton( onClick = { sendMessage() }, modifier = Modifier.align(Alignment.CenterEnd) ) { Icon( Icons.AutoMirrored.Rounded.Send, contentDescription = "Send message" ) } } }
0
Kotlin
0
2
466b71b2f7c6827bd1ed59982eecc1d1b5e8002f
2,074
ktor-chat
Apache License 2.0
app/src/main/java/ar/com/wolox/android/cookbook/netowork/GraphQlService.kt
Wolox
151,121,373
false
null
package ar.com.wolox.android.cookbook.netowork import com.apollographql.apollo.ApolloCall import com.apollographql.apollo.ApolloClient import com.wolox.queries.GetOrdersQuery import okhttp3.OkHttpClient object GraphQlService { const val SERVER_URL = "https://graphql-training-wolox.herokuapp.com/graphql/" private val apolloClient = ApolloClient.builder() .serverUrl(SERVER_URL) .okHttpClient(OkHttpClient.Builder().build()) .build() fun getOrders(page: Int, limit: Int): ApolloCall<GetOrdersQuery.Data> { return apolloClient.query( GetOrdersQuery .builder() .page(page) .limit(limit) .build()) } }
3
Kotlin
8
9
10c61b24b6c8812aa039441bfea709bfac29668c
776
wolmo-cookbook-android
MIT License