text
stringlengths
14
100k
source
stringclasses
1 value
repo
stringclasses
810 values
language
stringclasses
13 values
<|fim_prefix|>// Copyright (c) 2016- University of Oxford (Atilim Gunes Baydin <gunes@robots.ox.ac.uk>) // and other contributors, see LICENSE in root of repository. // // BSD 2-Clause License. See<|fim_suffix|> let _ = dsharp.randn([batchSize; inFeatures]) --> net net.state <- dsharp.load(fileName) ...
fim
DiffSharp/DiffSharp
fsharp
<|fim_prefix|>// Copyright (c) 2016- University of Oxford (Atilim Gunes Baydin <gunes@robots.ox.ac.uk>) // and other contributors, see LICENSE in root of repo<|fim_suffix|>, lr=dsharp.tensor(lr)) let target = dsharp.randn([batchSize; seqLen; dout]) let output = input --> rnn let mutable loss...
fim
DiffSharp/DiffSharp
fsharp
<|fim_suffix|>Linear(1, 2) let m2 = Linear(2, 3) let m3 = Linear(3, 4) let net = Sequential([m1;m2;m3]) let fileName = System.IO.Path.GetTempFileName() dsharp.save(net.state, fileName) let _ = dsharp.randn([batchSize; inFeatures]) --> net net.state <- dsharp.load...
fim
DiffSharp/DiffSharp
fsharp
<|fim_suffix|> n = 8, 4, 16 let net = VAEMLP(xdim*xdim, zdim) let fileName = System.IO.Path.GetTempFileName() dsharp.save(net.state, fileName) // Save pre-use let _ = dsharp.randn([n; xdim*xdim]) --> net // Use net.state <- dsharp.load(fileName) // Load after-use Assert...
fim
DiffSharp/DiffSharp
fsharp
<|fim_suffix|> let y2 = x --> net2 Assert.CheckEqual(y1, y2) [<Test>] member _.TestModelSaveLoad () = let net1 = ModelStyle1WithParamBuffer() let p1 = net1.stateVector let fileName = System.IO.Path.GetTempFileName() dsharp.save(net1, fileName) let net2:M...
fim
DiffSharp/DiffSharp
fsharp
<|fim_prefix|>// Copyright (c) 2016- University of Oxford (Atilim Gunes Baydin <gunes@robots.ox.ac.uk>) // and other contributors, see LICENSE in root of repository. // // BSD 2-Clause License. See LICENSE in root of repository. namespace Tests open NUnit.Framework open DiffSharp [<TestFixture>] type TestTenso...
fim
DiffSharp/DiffSharp
fsharp
// Copyright (c) 2016- University of Oxford (Atilim Gunes Baydin <gunes@robots.ox.ac.uk>) // and other contributors, see LICENSE in root of repository. // // BSD 2-Clause License. See LICENSE in root of repository. namespace Tests open NUnit.Framework open DiffSharp [<TestFixture>] type TestTensorBMM () = [...
fim
DiffSharp/DiffSharp
fsharp
<|fim_prefix|>// Copyright (c) 2016- University of Oxford (Atilim Gunes Baydin <gunes@robots.ox.ac.uk>) // and other contributor<|fim_suffix|> [[-2.0709, 0.2865], [ 1.0892, 0.5796]]]) let fwdx = fwdx.forwardDiff(combo.tensor([[[ 2.2755, -1.2585],...
fim
DiffSharp/DiffSharp
fsharp
<|fim_suffix|> [ 2.0147, -16.4717]]]) Assert.True(t4x2x2InvCorrect.allclose(t4x2x2Inv, 0.01)) [<TestFixture>] type TestDerivativesInv () = [<Test>] member _.TestDerivativeInv () = for combo in Combos.FloatingPointExcept16s do let fwdx = com...
fim
DiffSharp/DiffSharp
fsharp
<|fim_suffix|> let nOtherDim0Correct = combo.tensor([11.3016, 16.0621, 8.6211, 16.2887]) let nOtherDim1Correct = combo.tensor([ 6.2108, 17.4708, 16.4092]) let nOtherDim0KeepDimCorrect = combo.tensor([[11.3016, 16.0621, 8.6211, 16.2887]]) let nOtherDim1KeepDimCorrect = co...
fim
DiffSharp/DiffSharp
fsharp
<|fim_prefix|>// Copyright (c) 2016- <|fim_suffix|>sorOuter () = for combo in Combos.FloatingPointExcept16s do let a1 = combo.tensor([ 1.7865, 1.2723, 0.2065, -0.4601, 0.3218]) let b1 = combo.tensor([ 2.1136, 1.0551, -0.4575]) let a1outerb1 = a1.outer(b1) let...
fim
DiffSharp/DiffSharp
fsharp
<|fim_prefix|>// Copyright (c) 2016- University of Oxford (Atilim Gunes Baydin <gunes@robots.ox.ac.uk>) // and other contributors, see LICENSE in root of repository. // // BSD 2-Clause License. See LICENSE in root of repository. namespace Tests open NUnit.Framework open DiffSharp [<TestFixture>] type TestTensor...
fim
DiffSharp/DiffSharp
fsharp
// Copyright (c) 2016- University of Oxford (Atilim Gunes Baydin <gunes@robots.ox.ac.uk>) // and other contributors, see LICENSE in root of repository. // // BSD 2-Clause License. See LICENSE in root of repository. namespace Tests open NUnit.Framework open DiffSharp open DiffSharp.Compose open DiffSharp.Model ope...
fim
DiffSharp/DiffSharp
fsharp
<|fim_prefix|>// Copyright (c) 2016- University of Oxford (Atilim Gunes Baydin <gunes@robots.ox.ac.uk>) // and other contributors, see LICENSE in root of repository. // // BSD 2-Clause License. See LICENSE in root of repository. namespace Tests open NUnit.Framework open DiffSharp.Util [<TestFixture>] type TestRa...
fim
DiffSharp/DiffSharp
fsharp
<|fim_suffix|> [0.3855, 1.4428, 0.6534]], [[1.4250, 1.7200, 1.8228], [1.2607, 0.6599, 1.8958], [0.6304, 1.5875, 0.4057]]]]) let tk3p1i = co...
fim
DiffSharp/DiffSharp
fsharp
<|fim_prefix|>// Copyright (c) 2016- University of Oxford (Atilim Gunes Baydin <gunes@robots.ox.ac.uk>) // and other contributors, see LICENSE in root of reposito<|fim_suffix|>re the same type static member CheckEqual (expected: 'T, actual: 'T) = Assert.AreEqual(box expected, box actual) type dsharp wi...
fim
DiffSharp/DiffSharp
fsharp
<|fim_prefix|>def generate(num_dims, fixed_dims): str = '[<System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage>]' str += '\nmember t.GetSlice(' prefix = '' for i in range(num_dims): if fixed_dims[i]: str += '{}i{}:int'.format(prefix, i) else: str += '{}i{}min:...
fim
DiffSharp/DiffSharp
python
<|fim_suffix|> } } } } } } } } } } <|fim_prefix|>use dioxus::prelude::*; fn main() { dioxus::launch(app) } fn app() -> Element { let mut scan = use_action(|| async...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> val.set("0".into()); } }, if val.cloned().is_empty() { "C" } else { "AC" } } button { ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> } } fn perform_operation(&mut self) { if let Some(op) = &self.operator { let rhs = self.display_value.parse::<f64>().unwrap(); let new_val = match op { Operator::Add => self.cur_val + rhs, Operator::Sub => self.cur_val - rhs, ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! A simple counters example that stores a list of items in a vec and then iterates over them. use dioxus::prelude::*; const STYLE: Asset = asset!("/examples/assets/counter.css"); fn main() { dioxus::launch(app); } fn app() -> Element { // Store the counters in a signal let mut counters =...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Tiny CRM - A simple CRM app using the Router component and global signals //! //! This shows how to use the `Router` component to manage different views in your app. It also shows how to use global //! signals to manage state across the entire app. //! //! We could simply pass the state as a prop to e...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>or throw errors let breed_list = use_loader(move || async move { #[derive(Deserialize, Serialize, Debug, PartialEq, Clone)] struct ListBreeds { message: HashMap<String, Vec<String>>, } reqwest::get("https://dog.ceo/api/breeds/list/all") .await? ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use dioxus::prelude::Result; use serde::{Deserialize, Serialize}; use std::fmt::Display; // Cache up to 100 requests, invalidating them after 60 seconds pub(crate) async fn fetch_product(product_id: usize) -> Result<Product> { Ok( reqwest::get(format!("https://fakestoreapi.com/products/{produ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use diox<|fim_suffix|> } } } } } <|fim_middle|>us::prelude::*; #[component] pub fn error_page() -> Element { rsx! { section { class: "py-20", div { class: "container mx-auto px-4", div { class: "flex flex-wrap -mx-4 mb-24 text-center"...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>sistent websocket connection. use crate::{ api::{Sort, fetch_products}, components::nav::Nav, components::product_item::ProductItem, }; use dioxus::prelude::*; pub(crate) fn Home() -> Element { let products = use_loader(|| fetch_products(10, Sort::Ascending))?; rsx! { Nav {}...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use dioxus::prelude::*; #[component] pub(crate) fn ChildrenOrLoading(children: Element) -> Element { rsx! { Stylesheet { href: asset!("/public/loading.css") } Suspen<|fim_suffix|>dren} } } } <|fim_middle|>seBoundary { fallback: |_| rsx! { div { class: "spinner"...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use dioxus::prelude::*; #[component] pub fn Nav() -> Element { rsx! { section { class: "relative", nav { class: "flex justify-between border-b", div { class: "px-12 py-8 flex w-full items-center", a { class: "hidden xl:block mr-16", ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>g flex flex-row place-items-center hover:ring-4 hover:shadow-2xl transition-all duration-200", img { class: "object-scale-down w-1/6 h-full", src: "{image}", } div { class: "pl-4 text-left text-ellipsis", a { ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>r for Size { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { use Size::*; match s.to_lowercase().as_str() { "small" => Ok(Small), "medium" => Ok(Medium), "large" => Ok(Large), _ => Err(()), } } } mod ico...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>#![allow(non_snake_case)] use components::home::Home; use components::loading::ChildrenOrLoading; use dioxus::prelude::*; mod components { pub mod error; pub mod home; pub mod loading; pub mod nav; pub mod product_item; pub mod product_page; } mod api; fn main() { dioxus::la...
fim
DioxusLabs/dioxus
rust
//! Example: File Explorer //! //! This is a fun little desktop application that lets you explore the file system. //! //! This example is interesting because it's mixing filesystem operations and GUI, which is typically hard for UI to do. //! We store the state entirely in a single signal, making the explorer logic fa...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! A simple Dioxus app demonstrating how to build a native plugin using manganis. //! //! This example shows how to use the `#[manganis::ffi]` macro to automatically generate //! FFI bindings between Rust and native platforms (Swift/Kotlin). //! //! It also demonstrates how to use the widget!() macro to ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use serde::{Serialize, ser::Serializer}; pub type R<|fim_suffix|>e(String), /// Location unavailable #[error("Location unavailable: {0}")] LocationUna...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>#![allow(non_snake_case)] // Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT //! Dioxus Geolocation Plugin //! //! This plugin provides APIs for getting and tracking the device's current position //! on Android and ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apac<|fim_suffix|>) and Precise location (ACCESS_FINE_LOCATION). /// /// On iOS it will have the same value as the `location` alias. pub coarse_location: PermissionState, } #[derive(Debug, Clone,...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>#![allow(non_snake_case, unused)] use dioxus::prelude::*; // Define the Hackernews API and types use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::{ fmt::{Display, Formatter}, num::ParseIntError, str::FromStr, }; use svg_attributes::to; fn main() { LaunchBuilder::...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! The simplest example of a Dioxus app. //! //! In this example we: //! - import a number of important items from the prelude (launch, Element, rsx, div, etc.) //! - define a main function<|fim_suffix|>kes a function that returns an Element. This function //! calls "launch" on the currently-configured r...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>std::sync::LazyLock<rusqlite::Connection> = std::sync::LazyLock::new(|| { let conn = rusqlite::Connection::open(":memory:").expect("Failed to open database"); conn.execute_batch( "CREATE TABLE IF NOT EXISTS dogs ( id INTEGER PRIMARY KEY, url TEX...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> id: "skip", onclick: move |_| img_src.restart(), "skip" } button { id: "save", onclick: move |_| async move { _ = save_dog(img_src()).await }, "save!" } } } } <|fim_prefi...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>:set_server_url("https://hot-dog.fly.dev"); dioxus::launch(app); } fn app() -> Element { rsx! { Stylesheet { href: asset!("/assets/main.css") } Router::<Route> {} } } <|fim_prefix|>mod backend; mod frontend; use dioxus::prelude::*; use frontend::*; #[derive(Routable, Partia...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> placeholder: "MAX 1000 Dgts", r#type: "text", value:"{prompt}", oninput: move |evt| prompt.set(evt.value()) } input { class: "input is-primary mt-4", r#...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>Five counter: {count}" } button { onclick: move |_| count += 1, "Up high!" } button { onclick: move |_| count -= 1, "Down low!" } } } <|fim_prefix|>//! The example from the readme! //! //! This example demonstrates how to create a simple counter app with dioxus. The `Signal` type wraps...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>Entry component so it can access the todo from the todos signal. // Since we store the todos in a signal too, we also need to send down the todo list ul { class: "todo-list", for id in filtered_todos() { TodoEntry { key: "{id}", i...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>= 0 } label { r#for: "toggle-all" } } // Render the todos using the filtered_todos memo // We pass the ID along with the hashmap into the TodoEntry component so it can access the todo from the todos store. ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>#![allow(non_snake_case)] use dioxus::{fullstack::Loading, prelude::*}; use serde::{Deserialize, Serialize}; use std::fmt::Display; fn main() { dioxus::launch(app); } fn app() -> Element { let country = use_signal(|| WeatherLocation { name: "Berlin".to_string(), country: "German...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! A websocket chat demo using Dioxus' built-in websocket support. //! //! We setup an endpoint at `/api/chat` that accepts a `name` and `user_id` query parameter. //! Each client connects to that endpoint, and we use a `tokio::broadcast` channel //! to send messages to all connected clients. //! //! In ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Checkboxes and radio groups. //! //! Checkboxes expose their checked state through the FormEvent — read `evt.checked()`. //! Radio groups share a `name` attribute so only one option can be selected at a time; //! the selected value comes through `evt.value()`. use dioxus::prelude::*; fn main() { ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Accepting children on a component. //! //! Any component can take a `children: Element` prop. Anything nested inside the component //! in `rsx!` is passed in as `children`. This is how you build reusable layout and container //! components like cards, modals, or page shells. use dioxus::prelude::*; ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Defining and using components. //! //! A component is just a function annotat<|fim_suffix|>ovelace", role: "Mathematician" } UserCard { name: "Grace Hopper", role: "Computer Scientist" } } } // Components must start with an uppercase letter. // Props are taken as named arguments — `name` ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>), "Ready" } button { onclick: move |_| status.set(Status::Error), "Error" } // `if` without an `else` is also valid — nothing renders when false if logged_in() && status() == Status::Ready { p { "You are logged in and the app is ready." } } } } <|fim_prefi...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! The classic counter — the "hello world" of reactive UI. //! //! `us<|fim_suffix|> -= 1, "Decrement" } button { onclick: move |_| count.set(0), "Reset" } } } <|fim_middle|>e_signal` creates a reactive value. Whenever the signal changes, any part of the UI //! that reads it will re-render au...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> { onclick: move |_| disabled.toggle(), "click to " if disabled() { "enable" } else { "disable" } " the lower button" } button { disabled, "lower button" } } } } <|fim_prefix|>//! A simple demonstratio<|fim...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>, "Smaller" } } } const STYLE: &str = r#" .btn { padding: 6px 12px; border: 1px solid #888; border-radius: 4px; } .btn.active { background: #4CAF50; color: white; border-color: #2E7D32; } .box { padding: 12px; margin-top: 12px; border: 1px dashed #999; } .box.highlight { background: #fff3cd; border-c...
fim
DioxusLabs/dioxus
rust
//! Passing event handlers as props. //! //! Components can accept callbacks using `EventHandler<T>`, which is Dioxus's equivalent //! of React's `onClick` prop or a closure. Call the handler with `.call(value)` from the //! child; the parent decides what happens when the event fires. use dioxus::prelude::*; fn main(...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Handling form submission and deserializing into a struct. //! //! `evt.parsed_values::<T>()` takes the form's named inputs and deserializes them straight //! into your own type via serde. This skips the chore of pulling each field out of the //! values map by hand — just define a struct whose fields m...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! C<|fim_suffix|> to a signal makes the input //! "controlled" — the signal is the single source of truth, so clearing it clears the input. use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { let mut name = use_signal(String::new); let mut message = use_signal...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Rendering lists. //! //! Use a `for` loop inside <|fim_suffix|>can also use iterator adapters with .map() for anything more complex than a for loop p { "Uppercased:" } ul { {items.iter().map(|item| rsx! { li { "{item.to_uppercase()}" } })} } } } <|fim_middle|>`r...
fim
DioxusLabs/dioxus
rust
//! Nested Listeners //! //! This example showcases how to control event bubbling from child to parents. //! //! Both web and desktop support bubbling and bubble cancellation. use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { rsx! { div { onclick: move |_| p...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Thanks to @japsu and their project https://github.com/japsu/jatsi for the example! //! //! This example shows how to create a simple dice rolling app using SVG and Dioxus. //! The `svg` element and its children have a custom namespace, and are attached using different methods than regular //! HTML ele...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>OtherStyles; rsx! { div { class: Styles::container, div { class: OtherStyles::test, "Hello, world!" } div { class: OtherStyles::highlight, "This is highlighted" } div { class: Styles::global_class, "This uses a global class (no hash)" } } } } <|...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>lazily loaded using platform-specific APIs. use dioxus::prelude::*; static ASSET_PATH: Asset = asset!("/examples/assets/logo.png"); fn main() { dioxus::launch(app); } fn app() -> Element { rsx! { div { h1 { "This should show an image:" } img { src: ASSET_PATH } ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Setting the page title. //! //! The `Title` component renders a `<title>` tag into the document head. On the web it //! sets the browser tab title; on desktop it becomes the window title. Because it's a //! regular component, its contents can be driven by signals and u<|fim_suffix|>all read" } } }...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> request made by the webview //! and respond with your own data. You could use this to load in custom videos, streams, stylesheets, images, //! or any asset that isn't known at compile time. use dioxus::desktop::{use_asset_handler, wry::http::Response}; use dioxus::prelude::*; const STYLE: Asset = asset...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> transform: if rotated() { "rotate(45deg)" } else { "rotate(0deg)" }, margin: "20px 0", } div { label { "Hue: {hue:.0}" } input { r#type: "range", min: "0", max: "360", value: "{hue}"...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>png." } } } <|fim_prefix|>//! Setting a favicon. //! //! Use `document::Link` with `rel: "icon"` to point the browser at a favicon. Combined with //! `asset!`, the favicon is bundled into the app and served with the same path-mangling //! and cache-busting as any other asset. use <|fim_middle|>dioxus...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Loading fonts — from a CDN and bundled with the app. //! //! Two common ways to get a custom typeface onto the page: //! //! 1. Point `Stylesheet` at a hosted CSS file like Google Fonts — the browser fetches the //! font files on demand. //! 2. Bundle a font file into the app with `asset!`, then de...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>rgin: "4px", background_color: "hsl({i * 60}, 70%, 55%)", } } } } <|fim_prefix|>//! Inline styles. //! //! For quick one-off styling, every CSS property is available as an attribute on HTML //! elements — use snake_case in Rust (`background_color`) for the kebab-cas...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! This example shows how to add metadata to the pa<|fim_suffix|>Site is a site", } } } <|fim_middle|>ge with the Meta component use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { rsx! { // You can use the Meta component to render a meta tag in...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>-confetti@1.9.3/dist/confetti.browser.min.js", defer: true } h1 { "Script example" } p { "Open your browser's console to see the inline script's output." } button { onclick: move |_| { // Call out to the confetti library loaded above do...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Linking a CSS stylesheet. //!<|fim_suffix|>const STYLE: Asset = asset!("/examples/assets/stylesheet.css"); fn main() { dioxus::launch(app); } fn app() -> Element { rsx! { // Placing the Stylesheet anywhere in the tree is fine — it's collected into <head> Stylesheet { href: ST...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>::<Signal<Theme>>() .expect("Theme context not found. Ensure <App> is the root component.") } <|fim_prefix|>//! Demonstra<|fim_middle|>tes cross-component state sharing using Dioxus' Context API //! //! Features: //! - Context provider initialization //! - Nested component consumption //! - Reacti...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>; }); (name, set_name, reverse) } <|fim_prefix|>//! Writing your own hook. //! //! A hook is just a function that calls other hooks. By convention it starts with `use_` //! and returns whatever state handle the caller needs. Extracting hooks is how you reuse //! stateful logic across components —...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! This example showcases how to use the ErrorBoundary component to handle errors in your app. //! //! The ErrorBoundary component is a special component that can be used to catch panics and other errors that occur. //! By default, Dioxus will catch panics during re<|fim_suffix|> #[component] fn Compone...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>our app and are accessible from anywhere. To access a //! global signal, simply use its methods like a regular signal. Calls to `read` and `write` will be forwarded to the //! signal at the root of your app using the `static`'s address. use dioxus::prelude::*; const STYLE: Asset = asset!("/examples/asse...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Sharing state between sibling components by lifting it up. //! //! When two components need to read or edit the same value, put the signal in their //! common parent and pass it down as a prop. This keeps the data flow obvious: the parent //! owns the state, the children receive a `Signal<T>` handle, ...
fim
DioxusLabs/dioxus
rust
//! This example shows how you can chain memos together to create a tree of memoized values. //! //! Memos will also pause when their parent component pauses, so if you have a memo that depends on a signal, and the //! signal pauses, the memo will pause too. use dioxus::prelude::*; fn main() { dioxus::launch(app)...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>t } Display { label: "Doubled", value: doubled } // You can also pass a plain value — it'll be wrapped automatically Display { label: "Constant", value: 42 } } } // Taking `ReadSignal<i32>` means the child can subscribe but can't mutate the source #[component] fn Display(labe...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>ayerAction { Pause, Play, } #[derive(Clone)] struct PlayerState { is_playing: bool, } impl PlayerState { fn reduce(&mut self, action: PlayerAction) { match action { PlayerAction::Pause => self.is_playing = false, PlayerAction::Play => self.is_playing = tru...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>hange use_effect(move || println!("Count changed to {count}")); // We can do early returns and conditional rendering which will pause all futures that haven't been polled if count() > 30 { return rsx! { h1 { "Count is too high!" } button { onclick: move |_| cou...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! A signal that holds a struct. //! //! Signals don't care what they hold — you can put any `'static` type inside. To mutate //! a field on a struct signal, call `.write()` and the guard derefs to the inner value. //! Any read of the signal in the UI will re-render when you drop the write guard. use di...
fim
DioxusLabs/dioxus
rust
//! Running side effects when state changes. //! //! `use_effect` runs a closure after every render where one of the signals it reads has //! changed. It's the escape hatch for talking to code outside of Dioxus — logging, syncing //! to `localStorage`, updating the `document.title`, tweaking imperative APIs, and so on....
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>| w.chars().next()) .collect::<String>() }); rsx! { h1 { "{full_name}" } p { "Initials: {initials}" } label { "First: " } input { value: "{first}", oninput: move |e| first.set(e.value()) } label { "Last: " } input { value: "{last}", on...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>der: "New todo...", value: "{draft}", oninput: move |evt| draft.set(evt.value()), } button { onclick: move |_| { if !draft.read().is_empty() { todos.push(draft()); draft.set(String::new()); ...
fim
DioxusLabs/dioxus
rust
//! Backgrounded futures example //! //! This showcases how use_future, use_memo, and use_effect will stop running if the component returns early. //! Generally you should avoid using early returns around hooks since most hooks are not properly designed to //! handle early returns. However, use_future *does* pause the ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! A simple little clock that updates the time every few milliseconds. use async_std::task::sleep; use dioxus::prelude::*; use web_time::Instant; fn main() { dioxus::launch(app); } fn app() -> Elem<|fim_suffix|>_millis() as i64); } }); // Format the time as a string // This is...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! A simple example that shows how to use the use_future hook to run a background task. //! //! use_future won't return a value, analogous to use_effect. //! If you want to return a value from a future, use use_resource instead. use async_std::task::sleep; use dioxus::prelude::*; fn main() { dioxus...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Handle async streams using use_future and awaiting the next value. use async_std::task::sleep; use dioxus::prelude::*; use futures_util::{Stream, StreamExt, future, stream}; fn main() { dioxus::launch(app); } fn app() -> Element { let mut count = use_signal(|| 10); use<|fim_suffix|>c m...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//<|fim_suffix|>ader(move || async move { #[derive(serde::Deserialize, serde::Serialize, PartialEq)] struct DogApi { message: String, } reqwest::get("https://dog.ceo/api/breeds/image/random/") .await? .json::<DogApi>() .await...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>h1 { "Settings" } p { "Settings are consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." } ) } <|fim_prefix|>//! This example shows how to use the `Router` component to create a simple navigation system. //! The more complex router example uses all o...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! This example shows how to use the hash segment to store state in the url. //! //! You can set up two way data binding between the url hash and signals. //! //! Run this example on desktop with //! ```sh //! dx serve --example hash_fragment_state --features=ciborium,base64 //! ``` //! Or on web with ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> #[component] fn DefaultLinks() -> Element { rsx! { // Just some default links div { id: "external-links", // This link will open in a webbrowser a { href: "http://dioxuslabs.com/", "Default link - links outside of your app" } // This link will do ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! This example shows how to access and use query segments present in an url on the web. //! //! The enum router makes it easy to use your route as state in your app. This example shows how to use the router to encode search text into the url and decode it back into a string. //! //! Run this example on ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> h2 { "{name}" } p { "{contents}" } } } #[component] fn PageNotFound(route: Vec<String>) -> Element { rsx! { h1 { "Page not found" } p { "We are terribly sorry, but the page you requested doesn't exist." } pre { color: "red", "log:\nattempted to navigate to: ...
fim
DioxusLabs/dioxus
rust
//! Example: Updating components with use_resource //! ----------------- //! //! This example shows how to use ReadSignal to make props reactive //! when linking to it from the same component, when using use_resource use dioxus::prelude::*; #[derive(Clone, Routable, Debug, PartialEq)] enum Route { #[route("/")] ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> .unwrap(); } }); rsx! { div { height: "300px", overflow_y: "auto", border: "1px solid black", onmounted: move |event| element.set(Some(event.data())), onscroll: move |_| async move { if let Som...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>the Routable derive will use the name of the variant as the route /// You can also specify a specific component by adding the Component name to the `#[route]` attribute #[rustfmt::skip] #[derive(Routable, Clone, PartialEq)] enum Route { // Wrap the app in a Nav layout #[layout(Nav)] #[rout...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>E user_id = $1;", ) .bind(userid) .fetch_all(db) .await .unwrap(); Ok(User { id: sqluser.id, anonymous: sqluser.anonymous, username: sqluser.username, permissions: sql_user_perms.into_iter().map(|x| x.token).c...
fim
DioxusLabs/dioxus
rust
//! This example showcases how to use the `axum-session-auth` crate with Dioxus fullstack. //! We add the `auth::Session` extractor to our server functions to get access to the current user session. //! //! To initialize the axum router, we use `dioxus::serve` to spawn a custom axum server that creates //! our database...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! This example demonstrates how to use `dioxus::serve` with a custom Axum router. //! //! By default, `dioxus::launch` takes over the main thread and runs the Dioxus application. //! However, if you want to integrate Dioxus into an existing web server or use a custom router, //! you can use `dioxus::ser...
fim
DioxusLabs/dioxus
rust