Skip to content

Instantly share code, notes, and snippets.

@davidchall
Last active September 29, 2024 15:22
Show Gist options
  • Save davidchall/697a9f02c3c000de6ae4b10ac1e725eb to your computer and use it in GitHub Desktop.
Save davidchall/697a9f02c3c000de6ae4b10ac1e725eb to your computer and use it in GitHub Desktop.
Cat food calculator
# Editor: https://shinylive.io/py/editor/#gist=697a9f02c3c000de6ae4b10ac1e725eb
# App: https://shinylive.io/py/app/#gist=697a9f02c3c000de6ae4b10ac1e725eb
from pathlib import Path
from shiny import ui, render, App, Inputs, Outputs, Session
calories_target = 200
app_ui = ui.page_fluid(
ui.panel_title("Cat food calculator"),
ui.tags.p(f"Specify daily intake for 1 cat (target intake is {calories_target} kcal)."),
ui.row(
ui.column(6, ui.panel_well(
ui.tags.h4("Wet food"),
ui.input_numeric("calories_per_can", "Calories per can [kcal]:", 177),
ui.input_numeric("n_cans", "Number of cans:", 0.5)
)),
ui.column(6, ui.panel_well(
ui.tags.h4("Dry food"),
ui.input_numeric("calories_per_gram", "Calories per gram [kcal]:", 3.99),
ui.tags.b("Calculated meal size:", style="color:green"),
ui.output_text("result")
))
)
)
def check_positive_number(x, msg):
if x is None or x <= 0:
raise ValueError(msg)
def server(input: Inputs, output: Outputs, session: Session):
@output
@render.text
def result():
check_positive_number(input.calories_per_can(), "Invalid calories per can")
check_positive_number(input.n_cans(), "Invalid number of cans")
check_positive_number(input.calories_per_gram(), "Invalid calories per gram")
calories_wet = input.n_cans() * input.calories_per_can()
calories_dry = calories_target - calories_wet
grams_dry = calories_dry / input.calories_per_gram()
return f"{grams_dry:.0f} g"
app = App(app_ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment