repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/dashuai009/dashuai009.github.io
https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/028.typ
typst
#let date = datetime( year: 2022, month: 6, day: 10, ) #metadata(( title: "rust过程宏", subtitle: [rust], author: "dashuai009", description: "使用过程宏自定义一个struct format。", pubDate: date.display(), ))<frontmatter> #import "../__template/style.typ": conf #show: conf 我们有这样一个结构体 ```rust struct TestStruct{ a:String, b:String } ``` 我们希望自定义一个Display。针对`TestStruct{a:String::from("aaa"),b:String::from("bbb")}`形式化输出`a:aaa;b:bbb;` 利用过程宏可以做到这一点,编译时生成`std::fmt::Display`的trait。 #quote[ 刚开始学习过程宏,简单记录自己怎么实现的和一些坑 ] 直接上代码 ```rust extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, Data, DeriveInput, Fields, Ident}; #[proc_macro_derive(format)] pub fn derive_format(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let struct_name = input.ident; let struct_str = Ident::new("struct_str", struct_name.span()); let expended = if let Data::Struct(r#struct) = input.data { if let Fields::Named(ref fields_name) = r#struct.fields { let get_selfs: Vec<_> = fields_name .named .iter() .map(|field| { let f = field.ident.as_ref().unwrap(); quote! { stringify!(#f),&self.#f } }) .collect(); let format_string = "{}:{};".repeat(get_selfs.len()); let format_literal = proc_macro2::Literal::string(format_string.as_str()); let struct_fields = quote! { #(#get_selfs),* }; quote! { impl std::fmt::Display for #struct_name{ fn fmt(&self,f:&mut std::fmt::Formatter)->std::fmt::Result{ write!(f , #format_literal , #struct_fields) } } } } else { panic!("sorry, may it's a complicated struct.") } } else { panic!("sorry, Show is not implemented for union or enum type.") }; expended.into() } ``` 难点有两个: 1. `proc_macro2::Literal` `format!("{}",str);`语句中格式控制字符串`"{}"`是一个字面量`literal`。 quote内部使用的第三方库`proc_macro2`,quote语法`#ident`只接受`proc_macro2`的`{TokenStream,Ident,....}`。 在上边代码中,我们需要将一个String变量转为一个字面量。这个一定要用`proc_macro2::Literal`,用默认库`proc_macro::Literal`,会报错#strong[mismatches types];。#strike[要了命了才看出来这么个事] 2. `#(#get_selfs),*` quote的语法糖 `write!(f , #format_literal , #struct_fields)` 写出`write!(f , "{:?}" , (#(#get_selfs),*))`这样可以过编译,最后这个参数会生成一个元组,这又没法自定义格式了。 写成`write!(f , #format_literal , #(#get_selfs),*)`又过不了编译。 所以用`let struct_fields = quote!{#(#get_selfs),*}`套了一层。
https://github.com/darkMatter781x/OverUnderNotebook
https://raw.githubusercontent.com/darkMatter781x/OverUnderNotebook/main/entries/auton/auto-util.typ
typst
#import "/packages.typ": notebookinator, gentle-clues #import notebookinator: * #import themes.radial.components: * #import gentle-clues: * #import "/util.typ": qrlink #let auton( title, date, filename, description, directory: "src/auton/autons/", body, ) = { show: create-body-entry.with( title: "Auton: " + title, type: "program", date: date, author: "<NAME>", ) grid( columns: 2, gutter: 2mm, { heading(title) description }, { set align(horizon) figure( qrlink( "https://github.com/meiszwflz/OverUnder781X/tree/master/" + dictionary + filename, width: 9em, ), caption: "Source Code on Github", ) }, ) body }
https://github.com/Quaternijkon/Typst_BIT
https://raw.githubusercontent.com/Quaternijkon/Typst_BIT/main/README.md
markdown
vscode中打开,插件搜索typst,把下载量高的几个装上就行了。(Typst LSP, Typst Preview, Tinymist Typst, Typst Sync)
https://github.com/YunkaiZhang233/a-level-further-maths-topic-questions-david-game
https://raw.githubusercontent.com/YunkaiZhang233/a-level-further-maths-topic-questions-david-game/main/fs1/pgf.typ
typst
#import "../template.typ": * #import "../shortcut.typ": * #prob( [Cambridge Pre-U 9795/02, June 2022, Q2], [ (a) The random variable $U$ has the distribution of Po($lambda$). Show that the probability generating function of $U$ is $e^(lambda(t-1))$. #marks(4) (b) The random variable $V$ has probability generating function $G(t)$. It is given that $E(V) = 3$ and $"Var"(V) = 6.75$. - (i) Find the values of $G(1)$, $G'(1)$, and $G''(1)$. #marks(4) - (ii) Find the mean and variance of the random variable with probability generating function $[G(t)]^4$. #marks(2) ] ) #prob( [CAIE 9321/42 FM Paper 4, June 2022 (v2), Q2], [ The probability generating function, $G_Y (t)$, of the random variable $Y$ is given by $ G_Y (t) = 0.04+0.2t+0.37t^2 +0.3t^3 +0.09t^4 $ (a) Find $"Var"(Y)$. #marks(4) The random variable $Y$ is the sum of two independent observations of the random variable $X$. (b) Find the probability generating function of $X$, giving your answer as a polynomial in $t$. ] ) #prob( [Cambridge Pre-U 9795/02, Specimen Paper 2, Q1], [ The discrete random variable X has probability generating function $G_X (t)$ given by $ G_X (t) = a t(t + 1 / t)^3 $ where $a$ is a constant. (a) Find, in either order, the value of $a$ and the set of values that $X$ can take. #marks(4) (b) Find the value of $E(X)$. #marks(2) ] ) #prob( [CAIE 9321/43 FM Paper 4, Nov 2020 (v3), Q5], [ Keira has two unbiased coins. She tosses both coins. The number of heads obtained by Keira is denoted by $X$. (a) Find the probability generating function $G_X (t)$ of $X$. #marks(1) Hassan has three coins, two of which are biased so that the probability of obtaining a head when the coin is tossed is 13. The corresponding probability for the third coin is 14. The number of heads obtained by Hassan when he tosses these three coins is denoted by $Y$. (b) Find the probability generating function $G_Y (t)$ of $Y$. #marks(3) The random variable $Z$ is the total number of heads obtained by Keira and Hassan. (c) Find the probability generating function of $Z$, expressing your answer as a polynomial. #marks(3) (d) Use the probability generating function of $Z$ to find $E(Z)$. #marks(2) (e) Use the probability generating function of $Z$ to find the most probable value of $Z$. #marks(1) ] )
https://github.com/augustebaum/epfl-thesis-typst
https://raw.githubusercontent.com/augustebaum/epfl-thesis-typst/main/example/head/dedication.typ
typst
MIT License
#align(right + horizon)[ Wings are a constraint that makes\ it possible to fly.\ --- <NAME> ] #v(4cm) #align(center + horizon)[ To my parents... ]
https://github.com/crdevio/typst-themes
https://raw.githubusercontent.com/crdevio/typst-themes/main/typing-course%20template/theme.typ
typst
#let cpt_def = counter("cpt_def") #let cpt_prop = counter("cpt_prop") #let cpt_thm = counter("cpt_thm") #let cpt_part = counter("cpt_part") #let wedge = sym.and #let equiv = sym.ident // Size of the left "margin" (note area) #let margin-size = 15% // Spacer so that main content and notes don't rub up against each other #let margin-space = 0.1in #let imp(cont) ={ text(fill: blue.darken(50%),cont,weight: "semibold",size: 1em) } #let def( description, title: none, ) = { cpt_def.step() set align(center) box( rect( width:100%, fill:blue.lighten(99%), radius:( left:5pt, right:5pt ), stroke: ( left:blue, right: blue, top: black, bottom: black ) )[ #align(left)[ #box( polygon( stroke: blue.lighten(99%), fill: blue, (-5%, 0.55em), (0%,-0.25em), (45%,-0.25em), (90%,-0.25em), (90%,1.15em), (45%,1.15em), (0%,1.15em), (-5%,0.55em) ) + place(top+left)[#text(white,underline(smallcaps("Définition " + cpt_part.display("1") + "-" + cpt_def.display())),size:1.1em,weight: "medium") #text(white,"(" + title + ")",size:1em,weight: "semibold") ] ) ] #align(left)[ #text(black,description,size:1em) ] ] ) } #let prop( description, title: none ) = { set align(center) cpt_prop.step() box( rect( width:100%, fill:blue.lighten(99%), radius:( left:5pt, right:5pt ), stroke: ( left:blue.darken(20%), right: blue.darken(20%), top: black, bottom: black ) )[ #align(left)[ #box( polygon( stroke: blue.lighten(99%), fill: blue.darken(20%), (-5%, 0.55em), (0%,-0.25em), (45%,-0.25em), (90%,-0.25em), (90%,1.15em), (45%,1.15em), (0%,1.15em), (-5%,0.55em) ) + place(top+left)[#text(white,underline(smallcaps("Proposition " + cpt_part.display() + "-" + cpt_prop.display())),size:1.1em,weight: "medium") #text(white,"(" + title + ")",size:1em,weight: "semibold") ] ) ] #align(left)[ #text(black,description,size:1em) ] ] ) } #let cb(cont,title: "titre") ={ set align(left) box( rect( width:100%, fill:blue.lighten(99%), radius:( left:5pt, right:5pt ), stroke: ( left:blue.darken(20%), right: blue.darken(20%), top: black, bottom: black ) )[ #align(left)[ #box( polygon( stroke: blue.lighten(99%), fill: blue.darken(20%), (-5%, 0.55em), (0%,-0.25em), (45%,-0.25em), (90%,-0.25em), (90%,1.15em), (45%,1.15em), (0%,1.15em), (-5%,0.55em) ) + place(top+left)[#text(white,underline(smallcaps("Code")),size:1.1em,weight: "medium") #text(white,"(" + title + ")",size:1em,weight: "semibold") ] ) ] #align(left)[ #cont ] ] ) } #let th( description, title: none ) = { set align(center) cpt_thm.step() box( rect( width:100%, fill:blue.lighten(70%), radius:( left:5pt, right:5pt ), stroke: ( left:blue.darken(50%), right: blue.darken(50%), top: black, bottom: black ) )[ #align(left)[ #box( polygon( fill: blue.darken(50%), (-5%, 0.55em), (0%,-0.25em), (45%,-0.25em), (90%,-0.25em), (90%,1.15em), (45%,1.15em), (0%,1.15em), (-5%,0.55em) ) + place(top+left)[#text(white,underline(smallcaps("Théorème "+ cpt_part.display() + "-" + cpt_thm.display())),size:1.1em,weight: "medium") #text(white,"(" + title + ")",size:1em,weight: "semibold") ] ) ] #align(center)[ #text(black,description,size:1em) ] ] ) } #let rem( content )={ text(black,underline(smallcaps("Remarque"))) + ": " + content } #let reset_cpt()={ cpt_def.update(0) cpt_prop.update(0) cpt_thm.update(0) } #let dem( content ) ={ set align(left) box( rect( width:100%, fill:blue.lighten(99%), radius:( left:5pt, right:5pt ), stroke: ( left:blue.darken(20%), ) )[ #align(left)[ #box( place(top+left)[#text(black,underline(smallcaps("Démonstration")),size:1.1em,weight: "medium") ] ) ] #align(left)[ \ #content ] ] ) } #let enonce( content ) ={ set align(center) box( rect( width:100%, fill:blue.lighten(70%), radius:( left:5pt, right:5pt ), stroke: ( left:blue.darken(50%), right: blue.darken(50%), top: black, bottom: black ) )[ #align(left)[ #box( polygon( fill: blue.darken(80%), (-5%, 0.55em), (0%,-0.25em), (45%,-0.25em), (90%,-0.25em), (90%,1.15em), (45%,1.15em), (0%,1.15em), (-5%,0.55em) ) + place(top+left)[#text(white,underline(smallcaps("Enoncé" )),size:1.1em,weight: "medium") ] ) ] #align(center)[ #text(black,content,size:1em) ] ] ) } #let margin-note(dy: -1em, content) = { place( right, dx: margin-size + margin-space, dy: dy, block(width: margin-size, rect( width:100%, fill:blue.lighten(99%), radius:( left:1pt, right:1pt ), stroke: ( left:blue.darken(20%), top:blue.darken(40%) ) )[ #set text(size: 0.75em) #set align(left) #content ] )) } #let document( title: none, doc ) ={ show heading.where( level: 1 ): it => block(width: 100%)[ #reset_cpt() #cpt_part.step() #set align(left) #set text(1.1em, weight: "regular") #imp(counter(heading).display()) #underline(smallcaps(it.body)) ] show heading.where( level: 2 ): it => block(width: 100%)[ #set align(left) #set text(1.1em, weight: "regular") #imp(counter(heading).display()) #smallcaps(it.body)) ] show heading.where( level: 3 ): it => block(width: 100%)[ #set align(left) #set text(1em, weight: "regular") #imp(counter(heading).display()) #smallcaps(it.body)) ] show heading.where( level: 4 ): it => block(width: 100%)[ #set align(left) #set text(1em, weight: "regular") #imp(counter(heading).display()) #smallcaps(it.body) ] set page( paper: "us-letter", header : align(center)[your author name], numbering : "1/1", ) set heading(numbering: "I.1.a -") set text(font: "DejaVu",size: 1em) set align(center) text(2em,smallcaps(title)) set align(left) set par(justify: true) grid( columns:(100%-margin-size, margin-size), doc, ) }
https://github.com/jamesrswift/springer-spaniel
https://raw.githubusercontent.com/jamesrswift/springer-spaniel/main/README.md
markdown
The Unlicense
# The `springer-spaniel` Package <div align="center">Version 0.1.1</div> This is an loose recreation of the _Springer Contributed Chapter_ LaTeX template on Overleaf. It aims to provide template-level support for commonly used packages so you don't have to choose between style and features. ## Media <p align="center"> <img alt="Light" src="./thumbnails/1.png" width="32%"> <img alt="Dark" src="./thumbnails/2.png" width="32%"> <img alt="Light" src="./thumbnails/3.png" width="32%"> </p> ## Getting Started These instructions will get you a copy of the project up and running on the typst web app. Perhaps a short code example on importing the package and a very simple teaser usage. ```typ #import "@preview/springer-spaniel:0.1.1" #import springer-spaniel.ctheorems: * // provides "proof", "theorem", "lemma" #show: springer-spaniel.template( title: [Contribution Title], authors: ( ( name: "<NAME>", institute: "Name", address: "Address of Institute", email: "<EMAIL>" ), // ... and so on ), abstract: lorem(75), // debug: true, // Highlights structural elements and links // frame: 1pt, // A border around the page for white on white display // printer-test: true, // Suitably placed CMYK printer tests ) = Section Heading == Subsection Heading === Subsubsection Heading ==== Paragraph Heading ===== Subparagraph Heading ``` ### Local Installation To install this project locally, follow the steps below; + Install Just + Clone repository + In a bash compatible shell, `just install-preview`
https://github.com/jw2476/cslog
https://raw.githubusercontent.com/jw2476/cslog/master/devlogs/client_server_data_representation/mod.typ
typst
== 2023-08-02 - Client Server Representation With gathering and a basic inventory implemented on the client-side, I ran a brief playtest sending an executable and IP address to a few friends who are interested in the project. The resounding feedback was that were was no persistence, if they logged off and logged back in, their items would have been lost, this is because at the moment the server has no concept of an inventory or gathering, I was planning to move on to crafting and revisit this later but with the feedback recieved I decided to prioritise this issue. The first issue was going to be where to store the game data, below is a table evaluating the #table( columns: (auto, auto, auto), inset: 10pt, align: horizon, [*Option*], [*Advantages*], [*Disadvantages*], [Client-side storage], [ - Minimises server load - No need to sync data with server ], [ - Easy to tamper with data - Client is not always online ], [Server-side storage], [ - Very difficult to tamper with data - Data is all in one place - Data is always accessible ], [ - Increased server load - Clients need to tell server about all data changes ] ) Since this system would be used to store inventory data it must be tamper-proof, otherwise it would be too easy for players to cheat items into the game, and any sort of economy would be impossible. Because of this I decided the server would have to store the data in some sort of central database. The server load issue this creates can be minimised using client prediction which I'll get to later in this devlog. The choice to store data on the server then presents another issue, the same objects will often be represented differently on the client and server, for example here the client and server `Player` struct: ```pretty-rs struct Player { player: RenderObject, jump_t: f32, light: Light } ``` ```pretty-rs struct Player { position: Vec3, username: String, inventory: Inventory, } ``` The data is completely different, the server `Player` contains a username and inventory, whereas on the client these are separate systems. This is an example of a struct that should be kept separate between server and client, however there are structs with more in common between server and client such as the `Item` enum which contains a list of all items in the game, at this point I moved these more common data structures into a common crate which can be used by both the client and server crates. So far the network protocol had been manually encoding data into bytes which lead to a lot of bugs and errors along the way. Luckily someone has made an amazing crate called `serde` which allows automatic encoding and decoding of data structures. In addition to `serde`, I needed a crate that encodes data into a tightly packet binary stream, I took a while to look through the option and it seemed like `postcard` was the best option. Refactoring to use `serde` and `postcard` took the network code from ```pretty-rs #[derive(FromPrimitive, ToPrimitive)] pub enum ServerboundOpcode { Login, Move, Heartbeat, Disconnect, } pub struct ServerboundPacket { pub opcode: ServerboundOpcode, pub payload: Vec<u8>, } #[derive(FromPrimitive, ToPrimitive)] pub enum ClientboundOpcode { SpawnPlayer, Move, DespawnPlayer, NotifyDisconnection, Kick, } pub struct ClientboundPacket { pub opcode: ClientboundOpcode, pub payload: Vec<u8>, } impl ClientboundPacket { pub fn to_bytes(&self) -> Vec<u8> { let mut data = Vec::new(); data.extend(&self.opcode.to_u32().unwrap().to_be_bytes()); data.extend(&self.payload.clone()); let mut packet = data.len().to_be_bytes().to_vec(); packet.append(&mut data); packet } } impl ServerboundPacket { pub fn to_bytes(&self) -> Vec<u8> { let mut data = Vec::new(); data.extend(&self.opcode.to_u32().unwrap().to_be_bytes()); data.extend(&self.payload.clone()); let mut packet = data.len().to_be_bytes().to_vec(); packet.append(&mut data); packet } } ``` to ```pretty-rs pub mod server { use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Login { pub username: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Move { pub position: glam::Vec3, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum Packet { Login(Login), Move(Move), Heartbeat, Disconnect, } } pub mod client { use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct SpawnPlayer { pub username: String, pub position: glam::Vec3, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct DespawnPlayer { pub username: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Move { pub username: String, pub position: glam::Vec3, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct NotifyDisconnection { pub reason: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum Packet { SpawnPlayer(SpawnPlayer), DespawnPlayer(DespawnPlayer), Move(Move), NotifyDisconnection(NotifyDisconnection), } } ``` Here's an example of where it simplified the most code, this is server side decoding before and after this change: ```pretty-rs let packet_size = if let Some(array) = buf.get(0..8).and_then(|bytes| bytes.try_into().ok()) { u64::from_be_bytes(array) } else { warn!("Failed to read packet due to underflow"); continue; }; let Some(packet) = buf.get(8..(packet_size as usize + 8)) else { warn!("Failed to read packet due to underflow"); continue }; let opcode = if let Some(array) = packet.get(0..4).and_then(|bytes| bytes.try_into().ok()) { u32::from_be_bytes(array) } else { warn!("Packet of size {} is too short", packet.len()); continue; }; let Some(opcode) = ServerboundOpcode::from_u32(opcode) else { warn!("Invalid opcode: {}", opcode); continue }; let Some(payload) = packet.get(4..).map(<[u8]>::to_vec) else { warn!("Failed to read packet body"); continue }; let packet = ServerboundPacket { opcode, payload }; ``` to just: ```pretty-rs let packet = match postcard::from_bytes(&buf) { Ok(packet) => packet, Err(e) => { warn!("Failed to decode packet due to {}", e); continue; } }; if let Err(e) = handle_packet(&mut server, &packet, addr) { warn!("Handling packet failed with {e}"); continue; } ``` It also made using the packet payloads a lot easier since the handlers don't have to worry about decoding the binary, for example: ```pretty-rs let username = match String::from_utf8(packet.payload.clone()) { Ok(str) => str.trim().to_owned(), Err(e) => { warn!("Failed to parse username: {}", e); if let Err(e) = disconnect(server, addr, Some("Invalid username".to_owned())) { warn!("Failed to disconnect client due to {}", e); } return; } }; let client = Client { username, player_translation: Vec3::new(0.0, 0.0, 0.0), last_heartbeat: Instant::now(), }; ``` became just: ```pretty-rs let client = Client { username: packet.username.clone(), player_translation: Vec3::new(0.0, 0.0, 0.0), last_heartbeat: Instant::now(), }; ``` While testing all server functionality I found the player would jitter when moving and peers positions would not update, looking at client logs when client A would move, client A would recieve a packet updating its position, client B wouldn't. Must be a server bug, issue was when sending the movement update packets, taking a look at the server-side `handle_move` function: ```pretty-rs fn handle_move(server: &mut Server, packet: &net::server::Move, addr: SocketAddr) { // Find client, early returning if not found let Some(client) = server .connections .get_mut(&addr) else { warn!("Cannot find client for addr {}", addr); return; }; client.player_translation = packet.position; info!( "Updated position for {} to {:?}", client.username, client.player_translation ); // Have to refetch to drop the mutable reference let Some(client) = server .connections .get(&addr) else { warn!("Cannot find client for addr {}", addr); return; }; for peer_addr in server.connections.keys() { if *peer_addr == addr { // Don't want to send to itself, will cause jitter continue; } // Prepare packet let packet = net::client::Packet::Move(net::client::Move { username: client.username.clone(), position: client.player_translation }); if let Err(e) = server.send(addr, &packet) { warn!( "Failed to notify {} of {} moving due to {}", peer_addr, client.username, e ); continue; } } } ``` The issue was with the destination address of the packet, I was sending them to `addr` which was the address of the client that sent the packet. I should have been sending them to the peer's address, stored in `peer_addr`, here are the changes I made to fix it: ```pretty-rs if let Err(e) = server.send(addr, &packet) { warn!( "Failed to notify {} of {} moving due to {}", peer_addr, client.username, e ); continue; } ``` needed to be: ```pretty-rs if let Err(e) = server.send(*peer_addr, &packet) { warn!( "Failed to notify {} of {} moving due to {}", peer_addr, client.username, e ); continue; } ``` The dereference was needed as the `peer_addr` was borrowed from the hashmap of clients. After testing again I found another issue, the first client would connect fine, second client would connect and the first would crash due to 'Unknown peer', this meant there was an issue with the `handle_login` function and it wasn't notifying peers about a new connection. ```pretty-rs fn handle_login(server: &mut Server, packet: &net::server::Login, addr: SocketAddr) { let client = Client { username: packet.username.clone(), player_translation: Vec3::new(0.0, 0.0, 0.0), last_heartbeat: Instant::now(), }; // Notify peers about new client for peer_addr in server.connections.keys() { let packet = net::client::Packet::SpawnPlayer(net::client::SpawnPlayer { username: client.username.clone(), position: client.player_translation, }); if let Err(e) = server.send(addr, &packet) { warn!("Failed to notify {} of new player due to {}", peer_addr, e); } } // Notify client about existing peers for (peer_addr, peer_client) in &server.connections { let packet = net::client::Packet::SpawnPlayer(net::client::SpawnPlayer { username: peer_client.username.clone(), position: peer_client.player_translation, }); if let Err(e) = server.send(addr, &packet) { warn!( "Failed to notify new player {} of player {} due to {}", addr, peer_addr, e ); } } info!("Added {} to connection list", client.username); server.connections.insert(addr, client); } ``` Taking a look it was the same bug as before, now on line 14, the first client was complaining about unknown peers because it wasn't being notified, the newly connected client was as `addr` was being used instead of `peer_addr`. This can be fixed with a quick change: ```pretty-rs // Notify peers about new client for peer_addr in server.connections.keys() { let packet = net::client::Packet::SpawnPlayer(net::client::SpawnPlayer { username: client.username.clone(), position: client.player_translation, }); if let Err(e) = server.send(addr, &packet) { warn!("Failed to notify {} of new player due to {}", peer_addr, e); } } ``` should have been: ```pretty-rs // Notify peers about new client for peer_addr in server.connections.keys() { let packet = net::client::Packet::SpawnPlayer(net::client::SpawnPlayer { username: client.username.clone(), position: client.player_translation, }); if let Err(e) = server.send(*peer_addr, &packet) { warn!("Failed to notify {} of new player due to {}", peer_addr, e); } } ``` And with that everything was working again, now the server and client both had access to the item data and networking was refactored I finally moved onto inventory syncing. I chose the simplest approach, the client notifes the server about a new item, this approach has a few issues, mainly that it would be very easy to spawn items in since there can be no validation. Eventually I'd want to make the client tell the server about an action such as gathering or crafting, and then the server validates the action and calculates the resulting effects such as modifying the player's inventory, and then notifies the client of the effects, however since the server currently has no knowledge of the game world, and I said before there's little point until I start working on a static/procedurally generated world, it can't validate these actions so this simple approach is all that's possible. Firstly I designed the packet `ModifyInventory`, it needed to both add and remove item stacks (I chose item stacks over indiviual items to reduce the number of packets being sent to the server), the struct for the packet looked like this, I could simplify adding and removing stacks by just making the server respond by setting the stack quantity to the amount in the packet. So if the client sent a packet with a stack containing `(Wood, 4)`, the server would set that player's quantity of wood to 4. If its set to 0, its treated as deleting the stack. ```pretty-rs #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ModifyInventory { stack: ItemStack } ``` Now I had to hook into `Inventory` struct's `add` method, and whenever it is called dispatch a `ModifyInventory` packet to the server. With the current system with `Inventory` in the common crate, this was very difficult as whatever changes were made would affect both the server and client, I needed a way of specifying behaviour specific to the client or the server, so far I had only done this with data. Here are a couple solutions I came up with and evalutated: #table( columns: (auto, auto, auto), inset: 10pt, align: horizon, [*Option*], [*Advantages*], [*Disadvantages*], [Inject middleware closures that are called when the method is called], [ - Function signatures remain the same as the closures will capture any side specific state - Adding middleware capabilities could be automated with a macro ], [ - Adds a layer of indirection when you call a function, unknown side-effects, could lead to accidental deadlocks or performance issues - Makes constructors a lot more complicated ], [Move the struct from the common crate into seperate server and client structs], [ - Easy to do - No complex constructors ], [ - Data and code could be duplicated, possibly causing a data desync - Common crate has no knowledge of this system ], [Swap the struct for a trait which then the side specific structs implement aka dependency injection], [ - Useful if the common crate needs to use the system as it can be passed as a `&dyn Trait` - Easy to do ], [ - Data and code could be duplicated, possibly causing a data desync, however this can be reduced using default implementations - Boilerplate ], [Use features to disable certain functions], [ - Easy to do - Useful if the common crate needs to use the system as it can be passed as a `&dyn Trait` ], [ - Code has to be written in the common crate, so it can't use any client/server specific bits ], [Wrap the struct with a new struct in the side specific crates], [ - Allows for the use of code in side specific crates ], [ - Common crate can't use the specialised methods - Results in a bit of boilerplate ], [Observables], [ - Observers can be registered from either side to watch the changes and respond ], [ - Can add a little boilerplate ] ) I don't think there's a one size fits all solution to this senario, but in the case of the Inventory struct I decided to keep the `Inventory` struct split and have different structs and code on the client and server sides, I was leaning towards observables but working out whats changed can be very complicated and easy to introduce bugs. The client side inventory needed to store a reference to the socket so it could send packets, so the struct looked like: ```pretty-rs use common::ItemStack; struct Inventory { inventory: Vec<ItemStack>, socket: Arc<Socket> } ``` and on the server to socket wasn't needed so the struct looked like: ```pretty-rs use common::ItemStack; struct Inventory { inventory: Vec<ItemStack> } ``` I may choose to replace the `Vec<ItemStack>` with some sort of indexed map in future to bring lookups from O(n) to O(1), but for now the vector is fine. With that done, I moved onto implementation, the server implementation was just the same as the existing client implementation so I copied that over before modifying the client implementation to include sockets. The only changes needed for the client was taking the socket reference in the constructor and sending the packet when either `add` or `set` were called. I chose to add a new private method called `update` that sent the ModifyInventory packet to the server. ```pretty-rs impl Inventory { pub fn new(socket: Arc<Socket>) -> Self { Self { inventory: Vec::new(), socket } } fn update(&self, item: Item) { let Some(stack) = self.inventory.iter().find(|s| s.item == item) else { warn!("Tried to update stack {:?} that doesn't exist", item); return; }; let packet = net::server::Packet::ModifyInventory(net::server::ModifyInventory { stack: stack.clone() }); if let Err(e) = self.socket.send(&packet) { warn!("Failed to update stack {:?} due to {}", item, e); return; } } pub fn add(&mut self, stack: ItemStack) { if let Some(existing) = self.inventory.iter_mut().find(|s| s.item == stack.item) { existing.amount += stack.amount; } else { self.inventory.push(stack); } self.update(stack.item); } pub fn set(&mut self, stack: ItemStack) { if let Some(existing) = self.inventory.iter_mut().find(|s| s.item == stack.item) { existing.amount = stack.amount; } else { self.inventory.push(stack); } self.update(stack.item); } pub fn get_items(&self) -> &[ItemStack] { &self.inventory } } ``` I handled the socket errors in the update function which is bad practice but I didn't want to be bubbling up Results everywhere, eventually there may be a wrapper around the socket that attempts to retry sending packets to recover from temporary losses of connection but that's a problem to solve in the future With ModifyInventory packets being sent to the server, I now to handle them by updating the server-side inventory for the player. Firstly I updated the `Connection` struct to include an inventory: ```pretty-rs struct Connection { player_translation: Vec3, username: String, last_heartbeat: Instant, inventory: Inventory // New } ``` Next I needed the logic to update the item stacks on a `ModifyInventory` packet, I put this code in a new function called `handle_modify_inventory`: ```pretty-rs fn handle_modify_inventory(server: &mut Server, packet: &net::server::ModifyInventory, addr: SocketAddr) { // Get connection let Some(connection) = server .connections .get_mut(&addr) else { warn!("Cannot find connection for addr {}", addr); return; }; // Update inventory connection.inventory.set(packet.stack); } ``` Now the server was keeping track of the players' inventories, however when the connection was lost, the `Connection` structs were dropped out of the HashMap, loosing the inventories in the process. I needed to store player data separately from connection info so the data can be reused by multiple connections. I came up with a couple ways of doing this: #table( columns: (auto, auto, auto), inset: 10pt, align: horizon, [*Option*], [*Advantages*], [*Disadvantages*], [Store a list of players and a list of connections, with each connection storing the player's username so the player can be searched for], [ - Simple to store ], [ - Lots of Options to handle due to searching for players ], [Store a list of players and a list of connections, with each connection having a reference to a player], [ - Easy to index ], [ - Raw references result in lifetime nightmare - Shared ownership i.e. Mutex, RwLock needs locking, lots of Results to handle ], [Store a list of offline players, and a list of online connection, on login the player is moved out of the list and into a connection object which is put into the online connections list, undo on disconnect], [ - No references, so no Results - No searches, so no Options ], [ - Puts a bit more logic into connection and disconnection, need to be careful not to drop player info ] ) I decided to go with storing a list of offline players and a list of online connections because it didn't need any error handling so the code would be simpler. At this point I decided to implement that indexed map I talked about earlier, its a wrapper around a HashMap where the keys can be derived from the value, for players that's their username (I'll probably replace this with UUIDs at some point), for connections that's their socket address, here's the code for the IndexedMap and the Unique trait which I use to implement how to go from the value to the key: ```pretty-rs trait Unique { type Key: Eq + PartialEq + Hash; fn get_unique_key(&self) -> Self::Key; } struct IndexedMap<T> where T: Unique, { inner: HashMap<T::Key, T>, } impl<T> IndexedMap<T> where T: Unique + Clone, { fn new() -> Self { Self::default() } fn get(&self, key: &T::Key) -> Option<&T> { self.inner.get(key) } fn get_mut(&mut self, key: &T::Key) -> Option<&mut T> { self.inner.get_mut(key) } fn insert(&mut self, value: T) { self.inner.insert(value.get_unique_key(), value); } fn remove(&mut self, key: &T::Key) { self.inner.remove(key); } fn values<'a>(&'a self) -> Values<'a, T::Key, T> { self.inner.values() } fn keys<'a>(&'a self) -> Keys<'a, T::Key, T> { self.inner.keys() } fn take(&mut self, key: &T::Key) -> Option<T> { let value = self.get(key).cloned(); self.remove(key); value } } impl<T> Default for IndexedMap<T> where T: Unique, { fn default() -> Self { Self { inner: HashMap::new(), } } } ``` With the IndexedMap implemented I moved onto updating the Player, Connection and Server structs to fit the specification above: ```pretty-rs struct Player { position: Vec3, inventory: Inventory } struct Connection { last_heartbeat: Instant, addr: SocketAddr, player: Player } struct Server { socket: UdpSocket, offline: IndexedMap<Player>, online: IndexedMap<Connection> } ``` For IndexedMap to work with players and connections, they need to implement the Unique trait which I've done below: ```pretty-rs impl Unique for Player { type Key = String; fn get_unique_key(&self) -> Self::Key { self.username.clone() } } impl Unique for Connection { type Key = SocketAddr; fn get_unique_key(&self) -> Self::Key { self.addr } } ``` I also implemented Deref and DerefMut for Connection so the Player instance within can be easily accessed: ```pretty-rs impl Deref for Connection { type Target = Player; fn deref(&self) -> &Self::Target { &self.player } } impl DerefMut for Connection { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.player } } ``` Next was to change `handle_login` to take the player out of the offline map, wrap it in a Connection and insert it into the online map ```pretty-rs fn handle_login(server: &mut Server, packet: &net::server::Login, addr: SocketAddr) { let player = server.offline.take(&packet.username).unwrap_or(Player { position: Vec3::ZERO, username: packet.username.clone(), inventory: Inventory::new() }); server.online.insert(Connection { last_heartbeat: Instant::now(), addr, player }); let connection = server.online.get(&addr).expect("Failed to get connection that was just inserted, this is very bad"); ... ``` and then do the opposite when the client disconnects: ```pretty-rs fn disconnect(server: &mut Server, addr: SocketAddr, reason: Option<String>) -> Result<()> { let Some(connection) = server.online .get(&addr) else { warn!("Cannot find client for addr {}", addr); return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "Client not found").into()); }; info!("{} is disconnecting", connection.player.username); ... // Peers are notified, if it was a forced disconnection, reason is sent to the client server.offline.insert(connection.player.clone()); server.online.remove(&connection.get_unique_key()); } ``` At this point the server was running and I did some testing, I logged on, harvested some trees, login out and back in again and my items didn't reappear, but in the server logs my items were found from my previous session, I wasn't setting the client's inventory when they logged in. I repurposed the ModifyInventory packet and made it common to both the server and client protocols, then on the server I needed to send a ModifyInventory packet for every item stack in that player's inventory, and on the client I needed to handle these packets by setting those item stacks to the inventory. ```pretty-rs fn handle_login(server: &mut Server, packet: &net::server::Login, addr: SocketAddr) { ... // Login and insert connection for stack in connection.player.inventory.get_items() { let packet = net::client::Packet::ModifyInventory(net::client::ModifyInventory { stack: *stack }); if let Err(e) = server.send(connection, &packet) { warn!( "Failed to update player {}'s inventory stack {:?} due to {}", connection.player.username, stack, e ); continue; } info!( "Updating player {}'s stack {:?}", connection.player.username, stack ); } } ``` and the client-side is as simple as calling `Inventory::set` in the network handling function: ```pretty-rs ... net::client::Packet::ModifyInventory(packet) => { info!("Setting {:?} to {}", packet.stack.item, packet.stack.amount); inventory.set(packet.stack); } ... ``` And with that I did another round of testing, this was a big server refactor, so I did a full networking test trying to break the server by making it handle lots of clients at once, and everything passed. Inventories were persisting through sessions, and were being updated nearly instantly on login. With this set of features done I did a round of testing with my friends over the internet, to test latency and different computers, and also to gather some feedback before deciding what to implement next.
https://github.com/k0tran/typst
https://raw.githubusercontent.com/k0tran/typst/sisyphus/vendor/biblatex/README.md
markdown
# BibLaTeX [![Build status](https://github.com/typst/biblatex/workflows/Continuous%20integration/badge.svg)](https://github.com/typst/biblatex/actions) [![Current crates.io release](https://img.shields.io/crates/v/biblatex)](https://crates.io/crates/biblatex) [![Documentation](https://img.shields.io/badge/docs.rs-biblatex-66c2a5?labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpb<KEY>z<KEY>)](https://docs.rs/biblatex/) A Rust crate for parsing and writing BibTeX and BibLaTeX files. BibLaTeX can help you to parse `.bib` bibliography files. As opposed to other available crates, this crate attempts to parse the data within the fields into easily usable structs and enums like `Person` and `Date` for downstream consumption. ## Usage Add this to your `Cargo.toml`: ```toml [dependencies] biblatex = "0.9" ``` Parsing a bibliography and getting the author of an item is as simple as: ```rust let src = "@book{tolkien1937, author = {<NAME>}}"; let bibliography = Bibliography::parse(src).unwrap(); let entry = bibliography.get("tolkien1937").unwrap(); let author = entry.author().unwrap(); assert_eq!(author[0].name, "Tolkien"); ``` This library operates on a `Bibliography` struct, which is a collection of _entries_ (the items in your `.bib` file that start with an `@` and are wrapped in curly braces). The entries may hold multiple fields. Entries have getter methods for each of the possible fields in a Bib(La)TeX file which handle possible field aliases, composition and type conversion automatically. Refer to the [WikiBook section on LaTeX bibliography management](https://en.wikibooks.org/wiki/LaTeX/Bibliography_Management) and the [BibLaTeX package manual](http://ctan.ebinger.cc/tex-archive/macros/latex/contrib/biblatex/doc/biblatex.pdf) to learn more about the intended meaning of each of the fields. The generated documentation more specifically describes the selection and behavior of the getters but generally, they follow the convention of being the snake-case name of the corresponding field (such that the getter for `booktitleaddon` is named `book_title_addon`). ## Limitations This library attempts to provide fairly comprehensive coverage of the BibLaTeX spec with which most of the `.bib` files in circulation can be processed. However, the crate currently has some limitations: - There is no explicit support for entry sets, although it is easy to account for them by manually getting the `entryset` field and calling `parse::<Vec<String>>()` on it
https://github.com/lrmrct/CADMO-Template
https://raw.githubusercontent.com/lrmrct/CADMO-Template/main/template/abstract.typ
typst
#let abstract( abstract: [], doc ) = { page(numbering: "i")[ #counter(page).update(1) #line(length: 100%, stroke: 0.5pt) #align(center)[ #strong("Abstract") #linebreak() ] #abstract ] doc }
https://github.com/mrtz-j/typst-thesis-template
https://raw.githubusercontent.com/mrtz-j/typst-thesis-template/main/template/utils/todo.typ
typst
MIT License
// Utility to highlight TODOs to easily find them in the PDF #let TODO(body, color: yellow, title: "TODO") = { rect( width: 100%, radius: 3pt, stroke: 0.5pt, fill: color, )[ #text(weight: 700)[#title]: #body ] }
https://github.com/ivaquero/lang-romanic
https://raw.githubusercontent.com/ivaquero/lang-romanic/main/fr-2-num+noun.typ
typst
#import "@local/scibook:0.1.0": * #show: doc => conf( title: "数词与名词", author: ("github@ivaquero"), footer-cap: "github@ivaquero", header-cap: "音速法语", outline-on: false, doc, ) = 代词 == 人称代词 #let data = csv("fr/fr-pron.csv") #figure( ktable(data, 3), caption: "人称代词", supplement: [表], kind: table, ) = 提问 == 一般疑问句 一般疑问句中,主谓倒置,并在词之间加横杠,表示愿意。如 - Est-il ici aujourd'hui? (Is he here today?) - Parles-tu français avec tes amis? (Do you speak French with your friends?) == 特殊疑问句 === 特殊疑问词 #let data = csv("fr/fr-ask.csv") #figure( ktable(data, 2), caption: "特殊疑问词", supplement: [表], kind: table, ) === 例子 - Comment vas-tu? (How are you?) - Comment tu manges? (What do you eat?) - Où est-il? (Where is it?) - Pourquoi aimes-tu Paris? (Why do you like Paris?) - Quand travaillent-ils? (When do they work?) - Avec qui es-tu? (Who are you with?) = 数词 == 1-10 #let data = csv("fr/fr-num.csv") #figure( ktable(data, 3, inset: 0.4em), caption: "1-10", supplement: [表], kind: table, ) == 11-101 #let data = csv("fr/fr-num2.csv") #figure( ktable(data, 3), caption: "11-101", supplement: [表], kind: table, ) = 介词 == 冠词缩合 #let data = csv("fr/fr-prep-coal.csv") #figure( ktable(data, 3, inset: .4em), caption: "", supplement: [表], kind: table, ) == 方位介词 - à 和 en - à 用于地方和城市(小范围地理概念) - en 用于国家和大洲(大范围地理概念) = 限定词 - ce/cette/ces: this/that/these/those - des: some
https://github.com/han0126/MCM-test
https://raw.githubusercontent.com/han0126/MCM-test/main/2024亚太杯typst/chapter/chapter8.typ
typst
= 模型评价 == 模型优点 在问题二中,我们采用$K-m e a n s$聚类算法将洪水概率分成三类,这类算法简单、易于实现且时间复杂度$cal(O)(t k m n)$适中,在处理大量数据时又较好的伸缩性。在后续预警预测模型中,采用$X G B o o s t$算法,该算法作为一种经过优化的分布式梯度提升库,有较高的可移植性,且对缺失数据有较高的预测能力。 在问题三中,采用了$"MLP"$神经网络模型,可通过多个隐藏层和非线性激活函数,学习到复杂的数据特征,从而提高模型的表达能力,且能逼近任何连续函数,且该模型提供丰富的参数设置,可根据模型需求进行灵活调控,从而优化模型性能。 == 模型缺点 在模型建立过程中,存在大量假设,使得该预测模型在实践生活使用过程中,存在一顶模型预测的偏差;并且,所采用的模型,对数据初始值比较敏感,不具有较强的泛用性,故对极端天气或人为导致的洪水灾害无法进行准确预测。
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/enum-numbering_04.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test numbering with closure and nested lists. #set text(font: "New Computer Modern") #set enum(numbering: (..args) => math.mat(args.pos()), full: true) + A + B + C + D + E + F
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/SA/project_documentation/content/meeting_minutes/week_01.typ
typst
= Project Meeting 20.09.2023 08:15 - 09:00 (MS Teams) == Participants - Prof. Dr. <NAME> - <NAME> - <NAME> == Agenda - Finalization of SA task description - Questions: - How detailed does the project documentation have to be? -> as we see fit - Are there formatting requirements for documentation? -> no - Do we have to grant access to Jira, GitHub & Figma? -> yes
https://github.com/akagiyuu/math-document
https://raw.githubusercontent.com/akagiyuu/math-document/main/function/prime_test.typ
typst
#set text(size: 20pt) $ cos^2(((n-1)! + 1)/n pi) = cases(1 "if" n "is prime", 0 "otherwise")$
https://github.com/RossSmyth/resume
https://raw.githubusercontent.com/RossSmyth/resume/main/smyth_resume.typ
typst
Other
#set par(justify: true) #set text(font: "Arial", size: 10pt, fallback: false) #set page(paper: "us-letter", header: text(12pt)[ *<NAME>* #h(1fr) *Résumé* ], numbering: "p. 1 of 1") // Headers for the left column of the page #let col_hed(cont) = heading(outlined: true, bookmarked: true)[ #text(11pt, weight: "regular")[#smallcaps[#cont]] ] // Lists of stuff #let stuff_list(..stuff) = list(indent: 1em, ..stuff) #grid( columns: 2, gutter: 0.5cm, col_hed[Contact\ Information], grid( columns: 2, gutter: 1fr, [ <NAME> \ 16006 Black Sheep Lane \ Manchester, MI 48158 USA ], [ Cell: #link("tel:1+734-657-5853") \ Email: #link("mailto:<EMAIL>") \ GitHub: #link("https://github.com/RossSmyth")[GitHub.com/RossSmyth] \ LinkedIn: #link("https://www.linkedin.com/in/rosssmyth")[LinkedIn.com/in/rosssmyth] ], ), col_hed[Overview], [Software developer], col_hed[Education], [ #link("https://www.mtu.edu/")[*Michigan Technological University*], Houghton, MI \ B.S. Mechanical Engineering, May 2021 #h(1fr) GPA: 3.57 (4.0 scale) #stuff_list( [Specialization in signals, systems, and control (focus on space systems)], [Minor in Aerospace Engineering], ) ], col_hed[Experience], [ #link("https://www.electrocraft.com/")[*ElectroCraft*], Saline, MI #h(1fr) February 2023 to Present \ #underline[Embedded Software Engineer] #h(1fr) February 2023 to Present \ #stuff_list( [Developed firmware for two products in C], [Developed customer-facing desktop software in Rust], ) #link("https://orbionspace.com/")[*Orbion Space Technology*], Houghton, MI #h(1fr) May 2019 to February 2023 \ #underline[Lead Test Software Engineer] #h(1fr) June 2021 to February 2023 \ #stuff_list( [Developed & maintained data processing software], [Architect and author of new software suite for testing company's product], ) ], col_hed[Skills], box(height: 6em, columns(3, gutter: 3pt)[ - Python - Data visualization - Numpy, SciPy, Pandas - Matlab - Simulink - Rust - .NET - C - git - GitHub - Some Docker ]), col_hed[Leadership], [ *ADC Systems Engineer*, #link("https://aerospace.mtu.edu/enterprise/")[MTU Aerospace Enterprise] #h(1fr) December 2018 to April 2021 \ #par( first-line-indent: 1em, hanging-indent: 1em, )[Technical lead of a team of 5-10 student engineers responsible for designing, architecting, and testing the attitude determination and control subsystem of small spacecraft.] *Eagle Scount*, Troop 425 ], col_hed[Work History], [ - *Intern*, Orbion Space Technology #h(1fr) May 2019 to June 2021 - *Intern*, Keweenaw Research Center #h(1fr) May 2018 to April 2019 ], )
https://github.com/Lypsilonx/Game-of-Intrigue
https://raw.githubusercontent.com/Lypsilonx/Game-of-Intrigue/main/data.typ
typst
#let version = "1.2.1" // Game settings #let colors = ( red, orange, yellow, green, blue, purple, ) #let color_to_string(color) = { if color == blue { "Blue" } else if color == green { "Green" } else if color == red { "Red" } else if color == yellow { "Yellow" } else if color == purple { "Purple" } else if color == orange { "Orange" } else { "Unknown" } } #let player_count = colors.len() #let settings_json = json("game_settings.json") #let hand_card_amount = settings_json.hand_card_amount #let standing_card_amount = settings_json.standing_card_amount #let standing_card_value = settings_json.standing_card_value #let asset_copy_amount = settings_json.asset_copy_amount #let asset_value_range = (settings_json.asset_value_range.at(0), settings_json.asset_value_range.at(1)) #let influence_copy_amount = settings_json.influence_copy_amount #let influence_value_range = (settings_json.influence_value_range.at(0), settings_json.influence_value_range.at(1)) #let testimony_copy_amount = settings_json.testimony_copy_amount #let testimony_values = settings_json.testimony_values #let rebrand_copy_amount = settings_json.rebrand_copy_amount #let rebrand_values = settings_json.rebrand_values #let defence_copy_amount = settings_json.defence_copy_amount #let defence_value = settings_json.defence_value #let social_cards = settings_json.social_cards // Design settings #let card_width = 2.5in #let card_height = 3.5in #let card_radius = 3.5mm #let card_cut_radius = 0mm #let skew_angle = 6deg #let display_supertitle = settings_json.display_supertitle #let descriptions = ( "Token": "Represents you as the [C] player.", "Standing": "If you loose all of these cards, you are eliminated.", "Pact": "Symbolizes a pact with the [C] player. Removed from the game when discarded.", "Asset": "Worth [X] (Value)", "Influence": "Make someone trade with you in the trade phase.", "Favour": "Announce to ask the [C] player for [X] card_s. (excluding Standing and Roles)", "Hook": "Announce to make the [C] player discard 1 Standing.", "Threat": "Announce to make the [C] player pay a fine to you.", "Secret": "Announce to force the [C] player to tell everyone how many illegal cards they have.", "Testimony": "When announced you can discard [X] illegal card_s from your hand.", "Rebrand": "When announced you can discard [X] legal card_s from your hand.", "Defence": "When announced you are immune to all Social cards.", ) #let goal_hand_size = hand_card_amount - 2 #let role_descriptions = ( "Millionaire": "[Goal]Hold cards worth more or equal to " + str(calc.floor(int(goal_hand_size * ((asset_value_range.at(1) + asset_value_range.at(0)) / 2) / 10) * 10)) + ". (excluding Standing)", "Mafioso": "[Goal]Hold more or equal to " + str(goal_hand_size) + " illegal cards, but only illegal cards. (excluding Standing and cards of your Color)", "Broker": "[Goal]Hold " + str(goal_hand_size + 1) + " cards with ascending values.", "Hoarder": "[Goal]Hold " + str(calc.ceil(asset_copy_amount * 0.6)) + " Assets with the same value.", "Snitch": "[Goal]Hold " + str(calc.floor(hand_card_amount * 1.5)) + " Cards. (excluding Standing)", "Isolationist": "[Goal]Hold only cards with less than 2 value. (including Standing)", "Tyrant": "[Goal]Hold an evil Social card\n(Threat |Hook )\nfor all other players.\n(3 Players: Hold 2)", "Politician": "[Goal]Hold a calm Social card\n(Favour |Secret )\nfor all other players.\n(3 Players: Hold 2)", "Lobbyist": "[Perk]If you trade this card to another player, they have to discard all their Standing.", "Leach": "[Perk]If someone you have a Pact with wins, you win too. When you loose, you can try to sneak this card out of the game, to win later.", "Undead": "[Perk]When you loose, take " + str((standing_card_amount - 1)) + " Standing cards from the draw pile and shuffle it again, then remove this card from the game.", "Liar": "[Perk]You only loose when being accused during a trade, while having no Standing. You cannot win without Standing.", // TODO: Figure out how to handle this discretely "Officer": "[Perk]Announce to force everyone to give you all their illegal cards.", "Speculator": "[Perk]At the end of the game each of your Asset cards is worth 5+1d4. (Throw a dice with 4 sides and add 5)", "Salesperson": "[Perk]Announce to discard all your cards (excluding Standing and Roles)", "Banker": "[Perk]Announce to force everyone to give you all their Assets.", ) #let role_card_amount = role_descriptions.len() #let colored_card_count = player_count * (social_cards.len() + 1) #let non_colored_card_count = asset_copy_amount * (asset_value_range.at(1) - asset_value_range.at(0) + 1) + influence_copy_amount * (influence_value_range.at(1) - influence_value_range.at(0) + 1) + testimony_copy_amount * testimony_values.len() + rebrand_copy_amount * rebrand_values.len() + defence_copy_amount #let card_count = colored_card_count + non_colored_card_count + player_count + role_card_amount + standing_card_amount * player_count #let symbols = ( "Token": "token.svg", "Standing": "standing.svg", "Pact": "pact.svg", "Asset": "asset.svg", "Influence": "influence.svg", "Social": "social.svg", "Favour": "favour.svg", "Hook": "hook.svg", "Threat": "threat.svg", "Secret": "secret.svg", "Speech": "speech.svg", "Testimony": "testimony.svg", "Rebrand": "rebrand.svg", "Defence": "defence.svg", "Role": "role.svg", ) // Functions #let skew(angle, vscale: 1, body) = { let (a,b,c,d)= (1,vscale*calc.tan(angle),0,vscale) let E = (a + d)/2 let F = (a - d)/2 let G = (b + c)/2 let H = (c - b)/2 let Q = calc.sqrt(E*E + H*H) let R = calc.sqrt(F*F + G*G) let sx = Q + R let sy = Q - R let a1 = calc.atan2(F,G) let a2 = calc.atan2(E,H) let theta = (a2 - a1) /2 let phi = (a2 + a1)/2 set rotate(origin: bottom+center) set scale(origin: bottom+center) rotate(phi,scale(x: sx*100%, y: sy*100%,rotate(theta,body))) } #let icon(name, color: none, color2: black, width: 1.2em, height: 1.2em, side_distance: 0.4em) = [ #h(side_distance/2)#box( inset: -0.3em, image.decode( width: width, height: height, read("icons/" + symbols.at(name)) .replace( "rgb(254,255,254)", if color == none { gray } else { color }.to-hex() ) .replace( "rgb(0,0,0)", color2.to-hex() ) ) )#h(side_distance) ] #let logo_text(color: white) = [ #text( weight: "extrabold", size: 5em, fill: color )[ GAME #text( weight: "bold", size: 0.8em )[ #h(-0.2em) of\ ] INTRIGUE ]\ ] #let icon_banner = [ #box( width: 150% )[ #grid( rows: 1, columns: (1fr) * 7, fill: white, )[ #icon("Pact", width: 5em, height: 5em, color: red) #icon("Asset", width: 5em, height: 5em, color: orange) #icon("Influence", width: 5em, height: 5em, color: yellow) #icon("Social", width: 5em, height: 5em, color: green) #icon("Speech", width: 5em, height: 5em, color: blue) #icon("Role", width: 5em, height: 5em, color: purple) ] ] ] #let logo(subtitle: true, banner: false) = [ #rotate(-skew_angle)[ #skew(-skew_angle)[ #logo_text() #if subtitle [ #text( weight: "extrabold", size: 2em, fill: white )[ a game about\ being an asshole ] ] #if banner [ #v(2em) #icon_banner ] ] ] ] #let outline_text = [ In the Game of Intrigue, you compete against at least two other players. You draw cards and trade them with other players to gain an advantage. Everyone has their own Goal that wins them the game, but the most important cards are the Standing cards. If you loose all your Standing cards you are eliminated. You can play it safe, scheme to fulfill your personal Goal or take risks and try to eliminate other players. When everyone except two players are eliminated. The player with the most valueable cards wins. But beware! After players draw their Perk cards they get powerfull abilities. ]
https://github.com/zadigus/math
https://raw.githubusercontent.com/zadigus/math/main/number-theory/page-9/main.typ
typst
#import "template.typ": * #show: project.with( title: "test", authors: ( "zadigus", ), ) #lemma[ $o(1) eq O(1)$ ] #proof[ On the one hand, $ o(1) <=> f -> 0, $ on the other hand, $ O(1) <=> abs(f) lt A. $ Now, if $f->0$, then $abs(f) lt A$, whence $ o(1) eq O(1). $ ] #lemma[ $O(1) eq.not o(1)$ ] #proof[ $ O(1) eq.not o(1) <=> abs(f) lt A arrow.r.double.not f arrow 0 $ That's indeed the case if $f = B < A$. ] #lemma[ $O(1) eq o(x)$ ] #proof[ That means $ abs(f) < A arrow.r.double f/x arrow.r 0 $ which is trivially true. ] #pagebreak() #lemma[ $ f tilde phi arrow.r.l.double f = phi (1 + o(1)) $ ] #proof[ $ f tilde phi &arrow.r.l.double f/phi arrow 1 arrow.r.l.double f/phi - 1 arrow.r 0 arrow.r.l.double (f-phi)/phi arrow.r 0 arrow.r.l.double^"defn" f - phi = o(phi) arrow.r.l.double f = phi + o(phi) arrow.r.l.double f - phi = phi o(1) $ because $ g = o(phi) arrow.r.l.double g / phi arrow.r 0 arrow.r.l.double g / phi = o(1) arrow.r.l.double g = phi o(1) $ ]
https://github.com/enseignantePC/2023-24
https://raw.githubusercontent.com/enseignantePC/2023-24/master/chapter_template.typ
typst
#import "detect.typ": detect #import "style.typ": doc // #let doc = doc.with(breakable : false) #let minititle(it) = box( inset: (top: 2pt, bottom: 2pt, x: 5pt), text(18pt, hyphenate: false)[_#it _], ) #let introduction(title: [Introduction], it) = { rect( stroke: (left: 1.8pt), fill: blue.lighten(80%), inset: (bottom: 10pt, x: 10pt), )[ #minititle(title) #it ] } #let chapitre( title: none, number: none, objectifs: none, columnized : true, body, ) = [ #set page( paper: "a4", margin: (x: 1.2cm, top: 2cm, bottom: 1cm), footer: align( center, counter(page).display("1 / 1", both: true), ), header: [ #place( dy: 10pt, line(stroke: .5pt, length: 100%), ) #h(1fr) 2023-24 #h(1fr) <NAME> #line( stroke: .5pt, length: 100%, start: (0pt, -0.7em), ) ], ) // #set par(linebreaks: "optimized") #set par(justify: true, linebreaks: "optimized") #set text(size: 13pt) #set heading(numbering: "A)") #show heading.where(level: 1): it => [ #v(1em, weak: true) #set align(center) #minititle[#it] ] #v(-5.5pt) #align(center)[#rect( width: 90%, radius: 130pt, fill: gray, stroke: 4pt + gray, inset: 10pt, )[ #layout(size => align(center)[#rect( inset: 18pt, width: 95% * size.width, fill: white, radius: 6pt, )[ #set text(size: 26pt) #set text(hyphenate: false) *Chapitre #number: #title* ]]) ]] // #set align(center) #assert( type(objectifs) == "array", message: "objectifs must be of type array", ) *_#stack( dir: ltr, [Objectifs: #h(7pt)], list(marker: [-], ..objectifs), ) _* #let columns = if columnized {columns} else {(_,y) => y} #columns(2)[ #body ] ] #chapitre( title: [Titre du chapitre], number: 1, objectifs: ([Réussir], [Devenir fort]), )[ ]
https://github.com/danilasar/conspectuses-3sem
https://raw.githubusercontent.com/danilasar/conspectuses-3sem/master/Основы_теории_изучаемого_языка/240911_Члены_предложения.typ
typst
= Члены предложения Главные члены: - Главные - Подлежащее - Сказуемое - Второстепенные == Подлежащее / Подлежащее: --- главный *член* двусоставного предложения, обощначающий предмет или лицо --- носитель признака, выраженного сказуемым. Подлежащее может быть выражеоно существительным в форме общего падежа, местоимением, герундием, инфинитивом. Например, #quote(block: true, [ The _man_ was right. \ _He_ didn't know the truth. \ _Eating_ is a pleasure. \ _To see_ is to believe. _To err_ is human, _to forgive_ --- divine. ]) / Сложное полежащее (Complex Subject): представляет сочетание существительного в общем падеже или местоимения и инфинитива. Например, #quote([_He_ is known _to go_ to Siberia]). Сочетание формального компонента, выраженного личным местоимением it, и придаточного предложения. Например, #quote([_It_ was known by everyone (that) _he had travelled the world_]). / Составное подлжежащее: состоит из одного или более существительного. Например, #quote([The _man_ and the _woman_ talked over to the telephone]). == Сказуемое / Сказуемое: --- главный член предложения, выражающий признак лица или предмета --- подлежащего. В английском языке в отличие от русского в состав сказуемого всегда входит глагол в личной форме. За сказуемым закреплено место после подлежащего. Разделяется на 3 подгруппы: - Простое глагольное сказуемое - Составное глагольное сказуемое - Составное именное сказуемое / Составное глагольное сказуемое (Compound Verbal Predicate): включает модальный глагол или глагол с модальным значением и неличную форму глагола: - #quote([I _can't wait_ so long.]) - #quote([I _began to laugh_.]) Составное глагольное сказуемое представляет собой сочетания: + Модального глагола (can, may, must и др.) с инфинитивом + Инфинитива или герундия с глаголами, выражающими: + начало, продолжение или конец действия (to begin, to start, to continue, to end). \ #quote[He began to cry] + Отношение подлежащего к действию, выражаемому инфинитивом или герундием \ #quote[He decided to go to Moscow] + случайность, неожиданность совершения действия (to happen, to turn out, to prove и др.). \ #quote[They happened to meet at the conference.] + видимость или что-то кажущееся (to seem, to appear и др.) \ #quote[He scemed not to know about it.] Казалось, он не знал об этом. / Составное именное сказуемое (Compound Nominal Predicate): включает глагол _to be_ в нужной форме и прилагательное, существительное или причасте II: #quote[I _am_ very _comfortable_ here]. Составное именное сказуемое состоит из глагола-связки (чаще to be) и именной части сказуемого. Именная часть может быть выражена: + Существительным + Прилагательным + Местоимением + Числителем + Инфинитивом, причастием, герундием, т. е. целевыми формами глаголами + Наречием Кроме глагола to be глаголом-связкой могут быть глаголы to become, to grow, to get, to turn в значении "становиться", to seem --- "казаться", to look --- выглядеть, to remain --- оставаться, to keep, to go on и другие. == Второстепенные члены предложения Среди них: - Дополнение - Определение - Обстоятельство / Дополнение: --- второстепеннй член предложения, поясняющий слово со значением действия или признака и обозначающий лицо или предмет, на который направлено действие, или по отношению к которому проявляется признак. Дополнение может быть выражено существительным в общем падеже, местоимением, инфинитивом, герундием: \ #quote[ I met _her_ this morning. \ She bought the _dress_. \ I remembered _to eat_. \ He needs _taking care of_. ] / Простое дополнение: состоит из одного элемента. Например, #quote[I met _him_ this evening]. / Сложное дополнение (Complex Object): состоит из существительного в общем падеже или личного местоимения в оюъективной позици и инфинитива или причастия: \ #quote[I didn't see _John leave the house_.] \ #quote[I saw _him crossing the street_.] \ #quote[I want you to _do smth_.] Сочетание формального дополнения it и знаменательного дополнения, выраженного инфинитивом или придаточным предложением: \ #quote[I find _it_ strange that _he didn't come_.] \ #quote[I find _it_ neccessary _to wait_ for a few days.]
https://github.com/topdeoo/Course-Slides
https://raw.githubusercontent.com/topdeoo/Course-Slides/master/Courses/Thesis/main.typ
typst
#import "../../theme/iTalk.typ": * #import "@preview/algo:0.3.3": algo, i, d, comment, code // TODO fill all "TODO" with your information #show: nenu-theme.with( short-title: "SparrOS", short-date: "2024-05-08", short-author: "凌典" ) #let argmax = math.op("arg max", limits: true) #let argmin = math.op("arg min", limits: true) #title-slide( title: "SparrOS", subtitle: "面向 RISC-V 的 POSIX 操作系统内核设计与实现", authors: ( ( name: "答辩学生:凌典", email: "<EMAIL>" ), ( name: "指导老师:胡书丽", email: "<EMAIL>" ) ), logo: image("../../Seminar/template/fig/nenu-logo-title.png", width: 30%), institution: "Northeast Normal University", date: "2024-05-08" ) #toc-slide() #slide( session: "选题背景", title: "选题背景" )[ // TODO 选题背景主要从操作系统的教学入手,主要说明两点: // 1. 国内操作系统教学的问题所在 // 2. 工业级别操作系统的复杂性 纵观计算机系统的历史,已经有过太多操作系统的出现, - IBM 的 OS/360 - MIT 的 CTSS - Unix#footnote[Ritchie, <NAME>. and <NAME>. “The UNIX time-sharing system.” The Bell System Technical Journal 57 (1974): 1905-1929.],Minix#footnote[Tanenbaum, Andrew S.. “Operating systems: design and implementation.” Prentice-Hall software series (1987)] - Linux#footnote[Linux, https://kernel.org/],Windows,MacOS,Open Harmony#footnote[⁴OpenHarmony: https://www.openharmony.cn/mainPlay] 这些操作系统的架构各有差异,但都是工业级别的操作系统,由于需要兼容各 类硬件,其代码行数高达十几万行,对于初学者而言难度太大。 ] #slide( title: "选题背景" )[ 对于教学级别的操作系统而言,例如 - MIT 的 xv6#footnote[xv6: https://pdos.csail.mit.edu/6.S081/2023/xv6/book-riscv-rev3.pdf] - 清华大学的 uCore, rCore - UCB 的 PintOS#footnote[Pfaff, Ben, <NAME> and <NAME>. “The pintos instructional operating system kernel.” Technical Symposium on Computer Science Education (2009).] 其实现均为 C 语言,但 C 语言需要谨慎和经验才能安全使用,即便如此,低级错误也屡见不鲜。 而南京大学的 Mosaic#footnote[<NAME>. “The Hitchhiker’s Guide to Operating Systems.” USENIX Annual Technical Conference (2023).],其只关注了操作系统的抽象,而屏蔽了底层的太多细节 ] // #slide( // session: "论文综述", // title: "论文综述" // )[ // ] #slide( session: "设计与实现", title: "研究目标" )[ 本文旨在提出一种由高级语言重构的 POSIX 操作系统内核,此内核面向简洁的 RISC-V 架构,且能够兼容部分 POSIX.1 标准。 ] #slide( title: "总体架构" )[ #figure( image("fig/sparros-arch.png"), ) ] #slide( title: "虚拟化" )[ = 内存虚拟化 = CPU 虚拟化 = 文件系统虚拟化 ] #slide( title: "内存虚拟化" )[ 我们通过 sv39 页表机制来实现内存虚拟化,其转化机制如下图所示: #set align(center) #image("fig/sv39-pte.png", fit: "contain", height: 80%) ] #slide( title: "内存虚拟化" )[ 并通过 TLSF 算法来进行空闲内存的管理与分配,其管理的数据结构如下: #set align(center) #image("fig/tlsf-demo.png", fit: "contain", height: 80%) ] #slide( title: "CPU 虚拟化" )[ CPU 虚拟化的核心在于对进程的抽象,在 SparrOS 中,我们定义进程如下: #code()[ ```rust pub struct Proc { pub kstack: KVAddr, // Virtual address of kernel stack pub sz: usize, // Size of process memory (bytes) pub uvm: Option<Uvm>, // User Memory Page Table pub context: Context, // swtch() here to run process pub pid: PId, // Process ID pub state: ProcState, // Process state pub VRunTime: usize, // Virtual running time // ... } ``` ] ] #slide( title: "CPU 虚拟化" )[ 我们通过 CFS 来实现进程的调度,以实现 CPU 的虚拟化,我们为每一个 CPU 都建立了一个进程队列 `rq`,其结构如下图所示: #set align(center) #image("fig/cfs-demo.png", fit: "contain", height: 75%) ] #slide( title: "持久化" )[ SparrOS 的文件系统实现参考了 rCore 的 easy-fs 与 xv6 的文件系统,我们将磁盘分为以下几个部分: #figure( image("fig/easy-fs.png"), ) ] #slide( title: "文件系统虚拟化" )[ 我们通过上述的 `inode` 层进行虚拟化,将对文件的操作封装为统一的接口,例如 `open`, `write`, `read` 等系统调用。 ] #slide( title: "设备管理" )[ 我们通过设备树进行管理,在 QEMU 中模拟的 virt 设备,其设备树部分如下: #figure( image("fig/device_tree.png", fit: "contain", height: 80%), ) ] #slide( title: "设备管理" )[ 我们实现了 `virtio` ,`rtc` 与 `serial` 的驱动程序,`rtc` 的驱动程序如下所示: #code()[ ```rs impl RTCDriver for GoldfishRTC { fn get_time(&self) -> TimeStramp { unsafe { let time_low = read_volatile((self.base + TIMER_TIME_LOW as usize) as *const u32); let time_high = read_volatile((self.base + TIMER_TIME_HIGH as usize) as *const u32); let time = ((time_high as u64) << 32) | (time_low as u64); TimeStramp::new(sec, NSEC_PER_SEC) } } } ``` ] ] #slide( title: "并发" )[ 在并发方面,我们主要聚焦于实现进程的同步与互斥问题,SparrOS 中实现了包括: + `spinlock` + `sleeplock` + `condvar` ] #slide( title: "并发" )[ 通过条件变量实现了“生产者与消费者”问题(场景为 `UART` 驱动),如下所示: #figure( image("fig/buffer-limit.png", fit: "contain", height: 80%) ) ] #slide( session: "实验与结果", title: "实验环境" )[ #set align(center + horizon) #figure( table( columns: 3, stroke: (x: none), row-gutter: (2.2pt, auto), table.header[环境条目][宿主机配置][版本], [操作系统], [Manjaro-Linux], [6.1.84-1], [CPU 架构], [Intel x86-64], [i5-13500H], [虚拟机版本], [QEMU], [8.2.2], [代码编辑器], [VS Code], [1.88.1], [调试工具], [gdb-multiarch], [12.1], [交叉编译工具 (1)], [Rust], [nightly-1.79.0], [交叉编译工具 (2)], [LLVM], [18.1.2], [运行内存], [16G], [], [磁盘空间], [NVMe], [512G], ), ) ] #slide( title: "实验结果" )[ 我们通过编写用户程序并写入文件系统来测试内核的正确性: + shell + ls (list) + 并行素数筛 ] #slide( title: "并行素数筛" )[ 这里我们展示素数筛的工作流程及其实验结果,其主要使用 `pipe`,将多个进程连接为一个流水线,从而达到并行的效果,效果图如下所示: #figure( image("fig/sieve.gif") ) ] #slide( title: "并行素数筛" )[ 测试结果如下图所示: #figure( image("fig/primer.png", fit: "contain", height: 80%), ) ] #slide( session: "总结与展望", title: "工作总结" )[ + 设计并实现了一个兼容部分 POSIX.1 标准的操作系统。 + 设计各类模块时注重了现代化这一特点,采用了 TLSF 分配算法,CFS 调度算法以及设备树等现代操作系统使用的特性。 + 使用了 Rust 这种高级程序语言进行开发,虽然损失了一定的程序性能,但高级语言的抽象可以极大提高程序的可读性与可维护性。 ] #slide( title: "未来展望" )[ + 在完成了操作系统基本功能的基础上,继续完善网络模块,例如增加 TCP/IP 协议栈。 + 将文件系统升级,改为ext4 文件系统从而能够与 Unix-like 的 OS 兼容,并增加更多的虚拟文件系统,例如 procfs 与 devfs。 + 将操作系统烧录到开发版上运行,并实现开发板的设备驱动。 + 升级操作系统支持的硬件架构,例如 LoongArch 等 RISC 指令集架构。 ] #focus-slide[ #set align(center + horizon) Q & A ] #focus-slide[ #set align(center + horizon) 恳请老师批评指正 ]
https://github.com/hongjr03/shiroa-page
https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DIP/chapters/4频率域图像增强.typ
typst
#import "../template.typ": * #import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge #import fletcher.shapes: house, hexagon, ellipse #import "@preview/pinit:0.1.4": * #import "@preview/cetz:0.2.2" #import "/book.typ": book-page #show: book-page.with(title: "数字图像处理基础 | DIP") = 频率域图像增强 Image Enhancement in the Frequency Domain 二维离散傅里叶变换(2D DFT): $ F(u, v) = 1 / (M N) sum_(x=0)^(M-1) sum_(y=0)^(N-1) f(x, y) e^(-j 2 pi((u x)/M + (v y)/N)) $ 含义就是将 $(x, y)$ 空间转换到 $(u, v)$ 空间,$F(u, v)$ 是频率域的图像,$f(x, y)$ 是空间域的图像。 二维离散傅里叶逆变换(2D IDFT): $ f(x, y) = sum_(u=0)^(M-1) sum_(v=0)^(N-1) F(u, v) e^(j 2 pi((u x)/M + (v y)/N)) $ *例*: #note_block[ 下图是一幅二值图像($256 times 256$),每条黑色条纹和白条纹都是 2 个像素宽,求此图像的傅里叶谱(将 $(0,0)$ 点移到中心上)中亮点的位置和亮度值。 #figure( [ #image("../assets/2024-06-22-11-36-20.png") // #let repeater(times) = range(times).map(i => 2pt) // #grid( // columns: repeater(128), // rows: repeater(128), // // gutter: pt, // align: center + horizon, // fill: (x, _) => if calc.even(x) { // black // } else { // white // }, // ) ], caption: "二值图像", kind: { image }, ) 分析:$y$ 方向没有变化,所以 $v = 0$;$x$ 方向上,每个黑白条纹都是 2 个像素宽,所以频率就是最大频率的一半。在图像上就是 $(-64, 0)$ 和 $(64, 0)$ 两个点,直流分量为 $(0, 0)$ 点。直流分量强度是图像强度的均值,也就是一半;剩下两个点强度相等,为原图像的 $1/4$。 ] == 频率域图像滤波 Filtering in the Frequency Domain #definition[ *卷积定理*:在频率域中,卷积变成了乘法。 ] 即 $ f(x, y) * h(x, y) = F(u, v) H(u, v) $ 如果希望通过先做频域乘积、再对结果进行DFT反变换,来实现空域卷积,则需要保证信号无缠绕。可通过将原始数字信号通过补零延拓其矩阵大小。*要让卷积定理和直接卷积一致,需要0填充。* 比如,$f(x)$有$A$个样本、$g(x)$有$B$个样本,那么卷积前就需要分别对样本后面补 $0$,使其长度为 $P$。缠绕错误可以避免,如果 $ P >= A + B - 1 $。对于二维图像卷积,就要让长宽的最小值都大于原图像+滤波器的长宽$-1$。 #grid( columns: (1fr, 1fr), )[#image("../assets/2024-06-21-23-09-26.png")][#image("../assets/2024-06-21-23-10-06.png")] === 频率域滤波流程 + 给定一副大小为 $M times N$ 的输入图像 $f(x,y)$ ,选择填充参数 $P$ 和 $Q$。典型地,我们选择 $P=2M$ 和 $Q=2N$。 + 对 $f(x,y)$ 添加必要数量的 $0$,形成大小为 $P times Q$ 的填充后图像 $f_p(x,y)$。 + 用 $(-1)^(x+y)$ 乘以 $f_p(x,y)$ 移到其变换的中心。 + 计算来自步骤3的图像的DFT,得到 $F(u,v)$。 + 生成一个实对称滤波器函数 $H(u,v)$,大小为 $P times Q$,且中心位于 $(P/2, Q/2)$。用阵列相乘形成乘积 $G(u,v) = H(u,v)F(u,v)$。 + 得到处理后的图像 $g_p(x,y) = {"real"[cal(F)^(-1)(G(u,v))]}bold((-1)^(x+y))$。注意 $(-1)^(x+y)$ 用来移动 $g_p(x,y)$ 的中心。 - 这里本应该只有实部,但是由于计算机的误差,可能会有虚部,所以取实部。 + 通过从 $g_p(x,y)$ 的左上角提取 $M times N$ 区域来得到 $g(x,y)$。 == 频率域平滑滤波器 Smoothing Frequency Domain Filters === 理想低通滤波器 Ideal Lowpass Filters 直接截断频率,不考虑过渡带。 $ H(u, v) = cases( 1 ",当" D(u, v) <= D_0, 0 ",当" D(u, v) > D_0 ), D(u, v) = sqrt((u-M/2)^2 + (v-N/2)^2) $ 缺点:*明显的振铃效应* === 巴特沃斯低通滤波器 Butterworth Lowpass Filters $ H(u, v) = 1 / (1 + (D(u, v) slash D_0)^(2n)) $ #figure( [ #set text(size: 9pt) #set par(leading: 1em) #cetz.canvas({ import cetz.draw: * import cetz.plot import cetz.palette: * plot.plot( size: (10, 5), x-tick-step: none, y-tick-step: none, x-label: [频率 $D(u, v)$], y-label: [增益 $H(u, v)$], name: "Butterworth", { let Butterworth1(x) = { 1 / (1 + calc.pow(x / 100, 1)) } let Butterworth2(x) = { 1 / (1 + calc.pow(x / 100, 2)) } let Butterworth3(x) = { 1 / (1 + calc.pow(x / 100, 3)) } let Butterworth4(x) = { 1 / (1 + calc.pow(x / 100, 4)) } plot.add(domain: (0, 400), Butterworth1) plot.add-anchor("pt1", (20, 0.84)) plot.add(domain: (0, 400), Butterworth2) plot.add-anchor("pt2", (40, 0.87)) plot.add(domain: (0, 400), Butterworth3) plot.add-anchor("pt3", (60, 0.83)) plot.add(domain: (0, 400), Butterworth4) plot.add-anchor("pt4", (80, 0.73)) }, ) line("Butterworth.pt1", ((), "|-", (0, 2.5)), mark: (start: ">"), name: "line") content("line.end", $n=1$, anchor: "north", padding: .1) line("Butterworth.pt2", ((), "|-", (0, 2)), mark: (start: ">"), name: "line") content("line.end", $n=2$, anchor: "north", padding: .1) line("Butterworth.pt3", ((), "|-", (0, 1.5)), mark: (start: ">"), name: "line") content("line.end", $n=3$, anchor: "north", padding: .1) line("Butterworth.pt4", ((), "|-", (0, 1)), mark: (start: ">"), name: "line") content("line.end", $n=4$, anchor: "north", padding: .1) })], caption: "不同阶数的巴特沃斯低通滤波器", ) 显然,阶数越低,过渡越平滑。所以阶数高的时候还是会有振铃效应。 === 高斯低通滤波器 Gaussian Lowpass Filters $ H(u, v) = e^(-D(u, v)^2 / (2D_0^2)) $ #figure( [ #set text(size: 9pt) #set par(leading: 1em) #cetz.canvas({ import cetz.draw: * import cetz.plot import cetz.palette: * plot.plot( size: (10, 5), x-tick-step: none, y-tick-step: none, x-label: [频率 $D(u, v)$], y-label: [增益 $H(u, v)$], name: "Gaussian", { let Gaussian1(x) = { calc.exp(-calc.pow(x, 2) / (2 * 10 * 10)) } let Gaussian2(x) = { calc.exp(-calc.pow(x, 2) / (2 * 20 * 20)) } let Gaussian3(x) = { calc.exp(-calc.pow(x, 2) / (2 * 40 * 40)) } let Gaussian4(x) = { calc.exp(-calc.pow(x, 2) / (2 * 100 * 100)) } plot.add(domain: (0, 300), Gaussian1) plot.add-anchor("pt1", (7, 0.8)) plot.add(domain: (0, 300), Gaussian2) plot.add-anchor("pt2", (19, 0.6)) plot.add(domain: (0, 300), Gaussian3) plot.add-anchor("pt3", (54, 0.4)) plot.add(domain: (0, 300), Gaussian4) plot.add-anchor("pt4", (180, 0.2)) }, ) line("Gaussian.pt1", ((4, 0), "|-", ()), mark: (start: ">"), name: "line") content("line.end", $n=1$, anchor: "west", padding: .1) line("Gaussian.pt2", ((5, 0), "|-", ()), mark: (start: ">"), name: "line") content("line.end", $n=2$, anchor: "west", padding: .1) line("Gaussian.pt3", ((6, 0), "|-", ()), mark: (start: ">"), name: "line") content("line.end", $n=3$, anchor: "west", padding: .1) line("Gaussian.pt4", ((7, 0), "|-", ()), mark: (start: ">"), name: "line") content("line.end", $n=4$, anchor: "west", padding: .1) })], caption: "不同方差的高斯低通滤波器", ) 显然,方差越大,过渡越平滑。但无论如何,高斯低通滤波器都*不会有振铃效应*。 == 锐化频率域滤波器 Sharpening Frequency Domain Filters 对于理想高通滤波器、巴特沃斯高通滤波器和高斯高通滤波器,直接将低通滤波器的增益函数取反即可。 即 $ H(u, v) = 1 - H_("lp")(u, v) $ === 同态滤波器 Homomorphic Filters 照射-反射模型:$ I(x, y) = R(x, y) * L(x, y), 0 < R(x, y) < 1, L(x, y) > 0 $ 其中,$I(x, y)$ 为图像,$R(x, y)$ 为反射分量,$L(x, y)$ 为照射分量。取对数后有:$ z(x, y) = log(I(x, y)) = log(R(x, y)) + log(L(x, y)) $ 对 $z(x, y)$ 进行傅里叶变换,有:$ cal(F)(z(x, y)) = cal(F)(log(R(x, y))) + cal(F)(log(L(x, y))) $ 即:$ Z(u, v) = F_i(u, v) + F_r(u, v) $ 再对 $Z(u, v)$ 进行滤波,有:$ S(u, v) &= H(u, v)Z(u, v)\ &= H(u, v)F_i(u, v) + H(u, v)F_r(u, v) $ 对 $S(u, v)$ 进行逆傅里叶变换,有:$ s(x, y) &= cal(F)^(-1)(S(u, v))\ &= i'(x, y) + r'(x, y) $ 而需要的增强图像 $g(x,y)$ 为:$ g(x, y) = e^(s(x, y)) = e^(i'(x, y))e^(r'(x, y)) $ 照射分量较为稳定,反射分量差异较大。所以一般认为照度分量 $L(x, y)$ 是低频分量,反射分量 $R(x, y)$ 是高频分量。这样,设计特定的 $H(u, v)$ 就可以实现对图像的照度和反射的分别增强。 #figure(image("../assets/2024-06-22-00-11-58.png")) == 选择性滤波 同上,也是基本的那三种。只是 $D_0$ 变成了距离 $D - D_0$。
https://github.com/julyfun/jfmfoi
https://raw.githubusercontent.com/julyfun/jfmfoi/main/240828-最短路/main.typ
typst
#import "@preview/touying:0.4.2": * #import "@preview/cetz:0.2.2" #import "@preview/ctheorems:1.1.2": * #import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge, shapes // cetz and fletcher bindings for touying #let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true)) #let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide) // Register university theme // You can replace it with other themes and it can still work normally #let s = themes.university.register(aspect-ratio: "16-9") // Set the numbering of section and subsection #let s = (s.methods.numbering)(self: s, section: "1.", "1.1") // Set the speaker notes configuration // #let s = (s.methods.show-notes-on-second-screen)(self: s, right) // [my] #set text( font: ("New Computer Modern", "Songti SC") ) #show strong: set text(weight: 900) // Songti SC 700 不够粗 // Global information configuration #let s = (s.methods.info)( self: s, title: [CSP2021初赛和最短路专题], subtitle: [], author: [方俊杰.SJTU], date: datetime.today(), institution: [交附闵分 OI], ) // Pdfpc configuration // typst query --root . ./example.typ --field value --one "<pdfpc-file>" > ./example.pdfpc #let s = (s.methods.append-preamble)(self: s, pdfpc.config( duration-minutes: 30, start-time: datetime(hour: 14, minute: 10, second: 0), end-time: datetime(hour: 14, minute: 40, second: 0), last-minutes: 5, note-font-size: 12, disable-markdown: false, default-transition: ( type: "push", duration-seconds: 2, angle: ltr, alignment: "vertical", direction: "inward", ), )) // Theorems configuration by ctheorems #show: thmrules.with(qed-symbol: $square$) #let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee")) #let corollary = thmplain( "corollary", "Corollary", base: "theorem", titlefmt: strong ) #let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em)) #let example = thmplain("example", "Example").with(numbering: none) #let proof = thmproof("proof", "Proof") // Extract methods #let (init, slides, touying-outline, alert, speaker-note) = utils.methods(s) #show: init #show strong: alert // Extract slide functions #let (slide, empty-slide) = utils.slides(s) // --- 以下为正文 #show raw.where(lang: "cpp"): it => { set text(12pt) it } #set text(20pt) #show: slides = 初赛 #slide[ #image("image copy 5.png") ][ #image("image copy 6.png") ] == T2 #slide[ #image("image copy 7.png") ][ #image("image copy 8.png") ] == con'd #image("image copy 9.png") == T3 #slide[ #image("image copy 10.png") ][ #image("image copy 11.png") ] == con'd #image("image copy 12.png") == T4 #image("image copy 14.png") == con'd #slide[ #image("image copy 13.png") ][ #image("image copy 15.png") ] == P3371 【模板】单源最短路径(弱化版) #slide[ === 问题是什么? #image("image copy.png", height: 50%) ][ === 数据长啥样? ``` 4 6 1 1 2 2 2 3 2 2 4 1 1 3 5 3 4 3 1 4 4 ``` ] == con'd #slide[ === 思路 #image("image copy 2.png") 这个算法叫做 dijkstra ][ #image("image copy.png", height: 50%) ] == con'd #slide[ === 伪代码 ```cpp 初始化 dis 数组为极大值 起点的 dis 设置为 0 执行 n 次: 遍历每一个点,求出未被拓展过的距离最近的点 u 将 u 标记为拓展过了 遍历 u 的所有邻接点 v: 若从 u 走到 v 可以缩短 v 的距离,则更新 dis[v] ``` ][ === 代码 #image("image copy 4.png") 复杂度: $O(n^2)$ ] == 多源最短路: P2910 [USACO08OPEN] Clear And Present Danger S #slide[ 给出带权有向图和序列 $A_n$,求 $A_1$ 到 $A_2$ 最短路,$A_2$ 到 $A_3$ 最短路,...,$A_{n-1}$ 到 $A_n$ 最短路的和。 要是能直接先求出任意两点之间的最短路,就很方便了。 ][ === 样例 ``` 3 4 1 2 1 3 0 5 1 5 0 2 1 2 0 ``` 输出 7 ] == con'd 直接以每个点为起点做 Dijsktra 也可以,复杂度 $O(n^3)$ 这里要讲一个新做法,Floyd 用 $f[x][y]$ 表示从 $x$ 到 $y$ 的最短路。一开始把直接连边的 $f[x][y]$ 初始化为边权,不连边的 $f[x][y]$ 初始化为无穷大。 随后考虑以每个点 $k$ 作为中继点,更新 $i$ 到 $j$ 的最短路。若 $i$ 到 $k$ 有一条路,$k$ 到 $j$ 有一条路,那么试图用 $f[i][k] + f[k][j]$ 来更新 $f[i][j]$。 做完了! == con'd #slide[ ```cpp for (k = 1; k <= n; k++) for (x = 1; x <= n; x++) for (y = 1; y <= n; y++) f[x][y] = min(f[x][y], f[x][k] + f[k][y]); ``` 时间复杂度: $O(n^3)$ 空间复杂度: $O(n^2)$ 正确性:当考虑了前 $k$ 个点时,所有以前 $k$ 个点作为中继点的最短路都一定已经被找到了。考虑任意两点 $x$ $y$ 的最短路如何被依次求解的... ] == P1629 邮递员送信 求 1 到所有点和所有点到 1 的最短路. floyd 复杂度爆炸。 如何求后者?从 $x$ 到 $1$ 的路径,可以看作从 $1$ 到 $x$ 沿着反向边的走的路径。 对全图建反向边,再跑一次 dijkstra 即可。
https://github.com/kyanbasu/pwr-typst
https://raw.githubusercontent.com/kyanbasu/pwr-typst/main/polylux/pwr.typ
typst
MIT License
#import "@preview/polylux:0.3.1": logic #let pwr-author = state("pwr-author", none) #let pwr-date = state("pwr-date", none) #let pwr-footer = state("pwr-footer", []) #let pwr-lang = state("pwr-lang", none) #let title_bg = "images/image1_p2_pl.png" #let secondary_bg = "images/image2_p2_pl.png" #let pwr-theme( footer: [\u{0}], author: none, date: none, lang: "pl", background: white, foreground: black, body ) = { set page( paper: "presentation-4-3", margin: 2em, header: none, footer: none, fill: background, ) set text(fill: foreground, size: 25pt) set text(lang: lang) show footnote.entry: set text(size: .6em) show heading.where(level: 2): set block(below: 2em) set outline(target: heading.where(level: 1), title: none, fill: none) show outline.entry: it => it.body show outline: it => block(inset: (x: 1em), it) show heading: it => [ #set text(fill: gradient.linear(red, red.darken(50%))) #block(it.body) ] //description above figure is polish thing show figure.where( kind: table ): set figure.caption(position: top) pwr-footer.update(footer) pwr-author.update(author) pwr-date.update(date) pwr-lang.update(lang) body } #let title-slide(title: "", subtitle: none) = { logic.polylux-slide({ place(dx:-7.5%, dy:-10%, image(title_bg, fit: "stretch", width: 120%, height: 120%)) set text(fill: black) v(15%) align( center, box(inset: (x: 2em), text(size: 46pt, fill: gradient.linear(red, red.darken(60%)), weight: 600, title)), ) if (subtitle != none) { align( center, box(inset: (x: 2em), text(size: 30pt, subtitle)), ) } align( center, box(inset: (x: 2em), text(size: 24pt, pwr-author.display())), ) align( center, box(inset: (x: 2em), text(size: 22pt, pwr-date.display())), ) }) } #let centered-slide(body) = { let deco-format(it) = text(size: .6em, fill: gray, it) set page( footer: deco-format({ place(bottom + left, dy: -20pt, dx: -30pt, logic.logical-slide.display()); place(bottom + center, dy: -20pt, pwr-footer.display()); }), footer-descent: 1em, header-ascent: 1em, ) logic.polylux-slide({place(dx:-7.5%, dy:-10%, image(secondary_bg, fit: "stretch", width: 120%, height: 120%)); align(center + horizon, body)}) } #let slide(body) = { let body = pad(x: 1em, y: .1em, body) let deco-format(it) = text(size: .6em, fill: gray, it) set page( footer: deco-format({ place(bottom + left, dy: -20pt, dx: -30pt, logic.logical-slide.display()); place(bottom + center, dy: -20pt, pwr-footer.display()); }), footer-descent: 1em, header-ascent: 1em, ) logic.polylux-slide({place(dx:-7.5%, dy:-10%, image(secondary_bg, fit: "stretch", width: 120%, height: 120%)); body}) }
https://github.com/htwr-aachen/exams
https://raw.githubusercontent.com/htwr-aachen/exams/main/template/template.typ
typst
MIT License
#import "../exam.typ": conf, task, blank #show: conf.with( title: "Klausurprotokoll", shortTitle: "HTWR", lang: "de", chair: "RWTH Chair", chairLogo: "assets/htwr.png", date: datetime(day: 01, month: 01, year: 2024), notices: ( custom: false, time: 120, points: 100, minPoints: 50, other: [ - Am Ende der Klausur sind die Klausurblätter und evtl. zusätzlich ausgehändigte Blätter abzugeben. - Es sind *keine Hilfsmittel* erlaubt. Mobiltelefone sind auszuschalten. Smartwatches sind für die Dauer der Klausur bei der Aufsicht abzugeben. - Bitte verwenden Sie keinen roten oder grünen Stift. - Legen Sie Ihren Studierendenausweis bereit. ]) ) #task(title: "Titel der Aufgabe", points: (5)) == a) (5 Punkte) Erläutern Sie ob Klausurprotokolle wie dieses hier eine Urheberrechtsverletzung darstellt. #blank(height: 80%, solution: [ Keine Ahnung aber es ist allemal besser als die blank abzukopieren. Das BMBF schreibt nur: #quote(block: true)[ Ja. Klausuraufgaben (auch Multiple-Choice-Aufgaben) sind in der Regel urheberrechtlich geschützt. Bei Multiple-Choice-Aufgaben liegt die schöpferische Leistung häufig in der Auswahl der falschen Alternativantworten. ] Weitergehend schreibt es auf die Frage ob für das Studium Aufsätze oder Lehrbücher kopiert werden dürfen: #quote(block: true)[ <NAME> (auch Gasthörerinnen und Gasthörer), Lehrende und Prüfer dürfen bis zu 15 Prozent aus urheberrechtlich geschützten Werken wie Lehrbüchern, Monografien, Tages- und Publikumszeitschriften etc. nutzen. Vergriffene Werke, wissenschaftliche Zeitschriftenartikel und Werke mit geringem Umfang dürfen sogar vollständig genutzt werden ] Ich denke nicht das Klausuren als geringerem Umpfang gelten. Wichtig ist hierbei. #quote(block: true)[Bloße Ideen oder Gedanken sind damit nicht urheberrechtlich geschützt] Also... Definitions Antworten sind Definitionen und somit per se nicht urheberrechtlich relevant (aus meiner Sicht). Multiple Choice Alternativantworten umformulieren oder hinzufügen hilft. Wenn möglich oder egal eigene Zahlen einfügen und Sätze umschreiben. Ich würde denken bei keinen exakten Kopien ist das ganze schon deutlich weniger Anfällig auf Urheberrechtliche Konsequenzen. ]) #pagebreak() #task(title: "Signale", points: (1.5,1.5,0.5, 1.5, 2,5)) a) (1.5 Punkte) Was bedeutet der Begriff _Latenz_? Geben Sie _zwei Faktoren_ an die eine höhere Latenz zur Folge haben. - Erklärung: #blank(lines: 3, solution: [ Latenz ist die Verzögerung zwischen dem Senden eines Signals auf das Medium vom Sender bis zum Empfangen beim Empfänger. ]) - Faktor 1: #blank(lines: 1, solution: [Niedrige Signalgeschwindigkeit]) - Faktor 2: #blank(lines: 1, solution: [Große Distanzen]) == b) (1.5 Punkte) Benennen Sie die drei grundlegenden _Modulationsarten_ im _Breitbandverfahren_ #blank(lines:3, solution: [ Amplituden-, Frequenz- und Phasenmodulation *0.5 Punkte pro korrekter Modulationsart. 0.5 Punkte Abzug für falsche Angaben* ]) == c) (0.5 Punkte) Haben und wenn ja welche Nachteile haben Leitungscodes mit 100% Effizienz #blank(lines: 2, solution: [Nicht selbsttaktend, nicht Gleichstromfrei])
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/inline_math/inline_math_updated.typ
typst
$Q = abs(A v + C)$ $A^2 + B^2 = C^2$
https://github.com/flavio20002/cyrcuits
https://raw.githubusercontent.com/flavio20002/cyrcuits/main/tests/current-source/test.typ
typst
Other
#import "../../lib.typ": * #set page(width: auto, height: auto, margin: 0.5cm) #show: doc => cyrcuits( scale: 1, doc, ) ```circuitkz \begin{circuitikz} \draw (0,0) to[R=$R_1$] ++ (0,2) to[battery1,l=$E$] ++ (0,2) to[short,-*] ++ (2,0) node[anchor=north-east]{$A quad$} coordinate (aux1) to[isource=$I_G$,invert] ++ (0,-4) node[anchor=south-east]{$B quad$} to[short,*-] ++ (-2,0); \draw (aux1) to[R=$R_2$] ++ (2,0) to[nos,l=$T$] ++ (1,0) coordinate (aux2) to[R=$R_3$] ++ (0,-2) to[L,l_=$L$,v^=$v_L$,f>_=$i_L$] ++ (0,-2) to[short] ++ (-3,0); \end{circuitikz} ```
https://github.com/Rhinemann/mage-hack
https://raw.githubusercontent.com/Rhinemann/mage-hack/main/src/chapters/Skills.typ
typst
#import "../templates/interior_template.typ": * #show: chapter.with(chapter_name: "Skills") = Skills #show: columns.with(2, gutter: 1em) Skills represent natural talent, training, or experience of a character. #block(breakable: false)[ == Using Skills Skills are the third PC's three primary trait sets, so they are to be used in almost every conceivable roll, and their usage is straightforward, flowing from the description of an action pretty obviously. ] #block(breakable: false)[ == Rating Skills Every PC has at least a #spec_c.d4 in each skill, which represents being untrained. Proficiency and expertise are represented by ratings between #spec_c.d6 and #spec_c.d12. ] / #spec_c.d4 Untrained: You have no idea what you're doing, and you're likely to create trouble when you try it, but who knows. / #spec_c.d6 Competent: Sufficient training to get by. You're comfortable doing this. / #spec_c.d8 Expert: Able to do this for a living. This is second nature to you. / #spec_c.d10 Master: One of the best in the field. Likely known to others who possess the skill. / #spec_c.d12 Grandmaster: One of the best in the world. Known even to those outside the field. #block(breakable: false)[ == Specialties A specialty is a narrow area of concentration or focus. It provides a bonus #spec_c.d6 to any roll that falls into that narrow area. Specialties are attached to a skill the governs them, but can be used with a different skill if an appropriate narrative case can be made. ] There is no set list of specialties, but the skill list that follows provides suggested specialties for every skill #block(breakable: false)[ == Skill List Similarly to Attributes, Skills are divided into Mental, Physical, and Social categories. ] #block(breakable: false)[ === Mental Skills ==== Academics Higher education and knowledge of the arts and humanities. It covers language, history, law, economics, and related fields. Many magi develop aptitude in Academics to further their research into the Mysteries. ] *Suggested Specialties:* Anthropology, Art History, English, History, Law, Literature, Religion, Research, Translation. #block(breakable: false)[ ==== Awareness You've got uncanny perceptions. While alert folks spot everyday clues, your instincts cue in on the so-called supernatural side of life. Perhaps you've simply got that feeling about things -- some people do, even if they're not Awakened as such. More likely, you've spent enough time around the magical world to sense its effects in your presence. ] At lower levels, this Skill grants a nebulous perception of uncanny phenomena; higher ratings in the Trait reveal auras, expose the secretive Night-Folk, and open your eyes to the spiritual Periphery. *Suggested Specialties:* Omens, Auras, Resonance, Weird Feelings, Mystic Instincts, Hidden Magic, Spiritual Vidare. #block(breakable: false)[ ==== Computer Advanced ability with computing. While most characters in the World of Darkness are expected to know the basics, the Computer Skill allows your character to program computers, to crack into systems, to diagnose major problems, and to investigate data. This Skill reflects advanced techniques and tricks; most people in the modern world can operate a computer for email and basic Internet searches. ] *Suggested Specialties:* Data Retrieval, Graphics, Hacking, Internet, Programming, Security, Social Media. #block(breakable: false)[ ==== Crafts Knack with creating and repairing things. From creating works of art, to fixing an automobile, Crafts is the Skill to use. ] *Suggested Specialties:* Automotive, Cosmetics, Fashion, Forging, Graffiti, Jury-Rigging, Painting, Perfumery, Repair, Sculpting. #block(breakable: false)[ ==== Esoterica Esoteric knowledge comes in many forms: astrology, angelography, fortune-telling, yoga, herbalism, demonology, the lore of stones, even the secret code languages of occult societies. For centuries, such mysteries were the province of selected initiates; these days, it's relatively easy to find the basics in any decent bookstore or website. Even so, the deeper levels remain obscure to all but the most devoted students of the art. Anyone can take a yoga class in the modern world, but the more arcane applications of that art demand years of practice, study, and devotion. ] Esoterica Knowledge reflects your pursuit of esoteric disciplines and, by extension, provides instruments for your magickal focus. The Skill's overall rating reflects your general knowledge of arcane subjects, whereas each specialty reflects your expertise within a certain field. Unlike the Occult -- which reflects an understanding of “secret history” and shadow-cultures -- Esoterica represents the practical application of unusual fields. Occult can teach your character who <NAME> was, while Esoterica helps them understand what Crowley did... and to use those principles themselves. Given an opportunity to study and practice an art, any character can learn Esoterica. Although such disciplines don't give magickal powers to unAwakened characters, the Knowledge lets them use mundane applications -- teaching yoga classes, doing horoscopes, deciphering alchemical texts and so forth. Understanding the principles of bakemono-jutsu -- the ninja “ghost technique” -- won't make you invisible, for instance, but a specialty in that esoteric technique would let you add it to your Stealth Skill rolls. *Suggested Specialties:* Yoga, Tantra, Herbalism, Kabbalah, Fortune-Telling, Hypnosis, Astrology, Celestiography, Demonology, Sacred Geometry, Gematria, Goetia, Prophecies, Omens, T'ai Chi, I Ching, Stone Lore, Alchemy, Symbolism, Transhumanist Theory, Esoteric Musicology, Bakemono-Jutsu, Iconology, Numerology, Voodoo, Crystalmancy, Tarot, specific arcane languages (Enochian, In-o-Musubi, the Language of Flowers, etc.). #block(breakable: false)[ ==== Investigation Skill with solving mysteries and putting together puzzles. It reflects the ability to draw conclusions, to find meaning out of confusion, and to use lateral thinking to find information where others could not. ] *Suggested Specialties:* Artifacts, Autopsy, Body Language, Crime Scenes, Cryptography, Dreams, Lab Work, Riddles. #block(breakable: false)[ ==== Medicine Knowledge of the human body, and of how to bring it to and keep it in working order. Characters with Medicine can make efforts to stem life-threatening wounds and illnesses. ] *Suggested Specialties:* First Aid, Pathology, Pharmaceuticals, Physical Therapy, Surgery. #block(breakable: false)[ ==== Occult Knowledge of things hidden in the dark, legends, and lore. While the supernatural is unpredictable and often unique, the Occult Skill allows your character to pick out facts from rumor. Almost all magi develop at least some aptitude in Occult, to further their studies of the Mysteries. ] *Suggested Specialties:* Neopaganism, Occult History, Conspiracy Theories, Secret Societies, New Age, Alternative Sciences, Mystic Lore, Folk Magic, Moral Panic, Urban Legends, Satanic Folklore, Pop-Culture Satanism, Actual Satanism, any specific occult discipline or field (Freemasonry, Voodoo, Stage Magic, etc.). #block(breakable: false)[ ==== Politics General knowledge of political structures and methodologies, but more practically shows your character's ability to navigate those systems and make them work the way they intend. With Politics, they know the right person to ask to get something done. ] *Suggested Specialties:* Bureaucracy, Church, Consilium, Democratic, Local, Order, Organized Crime, Scandals. #block(breakable: false)[ ==== Science Knowledge and understanding of the physical and natural sciences, such as biology, chemistry, geology, meteorology, and physics. ] *Suggested Specialties:* Almost any hard scientific field. #block(breakable: false)[ ===== Scientific Specialties Common “respectable” Science variations practiced by Awakened characters include, but are not limited to, the following potential specialties: ] / Aeronautics: Design, construction, and operation of aircraft and other flying machines. / Astronomy: Study of stellar bodies, celestial mechanics, and outer space. / Biology: Research into the mysteries within Earth's organic life forms. / Biopsychology: Tracing (and often altering) the interplay between a living being's physical state and its psychological state. / Chemistry: Deciphering and manipulating the chemical codes within Earthly substances. / Computer Science: IT system languages, logistics, theory, advancement, and implementation. / Cybernetics: Research, development, and implementation of interconnected organic matter and machines. / Electronics: Harnessing and exploring the potential of electronic energies and devices. / Engineering: Design, research, and construction of essential structures. Engineering has many variations; if there's a structure involved in a project, then there's an engineering discipline involved in creating and maintaining that structure. / Forensic Pathology: Reconstructing evidence from scattered and fragmented clues. / Genetics: Research, analysis, and manipulation involving the literal “building blocks of life.”consider this a soft science, those who manipulate identity, memory, and behavior find it extremely useful. / Geology: Study of earthly formations, materials, and phenomena. / Psychology: Study of human consciousness and behavior, and their related therapies. / Hypermathematics: Esoteric, arcane, theoretical, and sometimes absurd applications of advanced mathematical principles, often tied to the links between science, faith, and magick. / Psychopharmacology: Research, development, and applications dealing with the interplay between psychoactive substances and human/humanoid consciousness, perceptions, and behavior. / Mathematics: Study of equations, numbers, patterns, and the interplay between them. / Psychoprojection: Research into the multiple disciplines and effects of extraphysical consciousness co- and re-location. In plain English, the study of astral projection, multiple selves, and travel into the Digital Web. / Metallurgy: Research, refinement, and implementation involving the properties and functions of various metallic substances, alloys, and compounds... though not, unfortunately, musicians. / Paraphysics: “Proper” name for Dimensional Science, also known as the interrelationship between Earthly reality and the Otherworlds. / Phylogeny: Study of transition and transformation, their effects, and the potential uses of both. / Physics: Observations and research regarding the interrelationships between matter and energy. Theoretical physics deals with potential but currently unproven models of physics, whereas practical physics deals with known applications of established physics. / Psychodynamics: Study and application of human and humanoid mental processes -- specifically the relationships between emotional responses, mental health, physical state, and outward behavior. Although some Technocrats. / Sociobiology: Observation and manipulation of societies as extended organisms -- composed of individual beings -- that nurture, protect, and reproduce themselves. By researching the tendencies of such organisms, sociobiologists strive to understand and influence societies... and the individuals within them. / Xenobiology: Study, analysis and understanding of alien organisms: monsters, spirits, mythic beasts, and other things conventional science does not currently accept as real. Radical scientists -- Etherites, Ecstatics, Virtual Adepts, and even some maverick Technocrats, among others -- have dozens, perhaps hundreds, of other disciplines, ranging from Etherdynamics to Chaos Math to Coprophrenology (don't ask...). Naturally, such sciences are not generally accepted by the community at large; this, of course, just inspires their proponents to prove how true their theories really are... #block(breakable: false)[ === Physical ==== Athletics A broad category of physical training and ability. It covers sports, and basic physical tasks such as running, jumping, dodging threats, and climbing. It also determines a character's ability with thrown weapons. ] *Suggested Specialties:* Acrobatics, Archery, Climbing, Jumping, Parkour, Swimming, Throwing. #block(breakable: false)[ ==== Brawl Ability to tussle and fight without weapons. This includes old-fashioned bar brawls as well as complex martial arts. Almost every member of the Akashiana, and many other magi, train in at least basic self-defense. ] *Suggested Specialties:* Biting, Boxing, Claws, Dirty Fighting, Grappling, Martial Arts, Threats, Throws. #block(breakable: false)[ ==== Drive Skill to control and maneuver automobiles, motorcycles, boats, and even airplanes. The Skill relates to moments of high stress, such as a high-speed chase or trying to elude a tail. As well, Drive can reflect your character's skill with horseback riding, if appropriate to their history. ] *Suggested Specialties:* Defensive Driving, Evasion, Off-Road Driving, Motorcycles, Pursuit, Stunts. #block(breakable: false)[ ==== Firearms Ability to identify, maintain, and otherwise use guns. This Skill covers everything from small pistols, to shotguns, to assault rifles, and anything else related. ] *Suggested Specialties:* Handguns, Rifles, Shotguns, Trick Shots. #block(breakable: false)[ ==== Larceny Intrusion, lockpicking, theft, pickpocketing, and other (generally considered) criminal activities. This Skill is typically learned on the streets, outside of formal methods. However, stage magicians and other entertainers learn these skills as part of their repertoire. ] *Suggested Specialties:* Breaking and Entering, Concealment, Lockpicking, Pickpocketing, Safecracking, Security Systems, Sleight of Hand. #block(breakable: false)[ ==== Stealth Ability to move unnoticed and unheard, or to blend into a crowd. Every character approaches Stealth differently; some use distraction, some disguise, some are just hard to keep an eye on. ] *Suggested Specialties:* Camouflage, Crowds, In Plain Sight, Rural, Shadowing, Stakeout, Staying Motionless. #block(breakable: false)[ ==== Survival Ability to “live off the land.” This means finding shelter, finding food, and otherwise procuring the necessities for existence. This could be in a rural or urban environment. This skill also covers the ability to hunt for animals. ] *Suggested Specialties:* Foraging, Hunting, Navigation, Shelter, Weather. #block(breakable: false)[ ==== Weaponry Ability to fight with hand-to-hand weapons: from swords, to knives, to baseball bats, to chainsaws. If the intent is to strike another and harm them, Weaponry is the Skill. ] *Suggested Specialties:* Chains, Clubs, Improvised Weapons, Spears, Swords. #block(breakable: false)[ === Social ==== Animal Ken Ability to train and understand animals. With Animal Ken, your character can cow beasts or rile them to violence under the right circumstances. ] *Suggested Specialties:* Canines, Felines, Reptiles, Soothing, Threatening, Training. #block(breakable: false)[ ==== Empathy Ability to read and understand others' feelings and motivations. This helps discern moods, or read deceptive behavior in discussion. It is not inherently sympathetic; one can understand another's positions without agreeing with them. ] *Suggested Specialties:* Calming, Emotion, Lies, Motives, Personalities. #block(breakable: false)[ ==== Expression Ability to communicate. This Skill covers written and spoken forms of communication, journalism, acting, music, and dance. ] *Suggested Specialties:* Dance, Drama, Journalism, Musical Instrument, Performance Art, Singing, Speeches. #block(breakable: false)[ ==== Intimidation Ability to influence others' behavior through threats and fear. It could mean direct physical threats, interrogation, or veiled implications of things to come. ] *Suggested Specialties:* Direct Threats, Interrogation, Stare Down, Torture, Veiled Threats. #block(breakable: false)[ ==== Persuasion Ability to change minds and influence behaviors through logic, fast-talking, or appealing to desire. It relies on the force of your character's personality to sway the listener. ] *Suggested Specialties:* Confidence Scam, Fast Talking, Inspiring, Sales Pitch, Seduction, Sermon. #block(breakable: false)[ ==== Socialize Ability to present themselves well and interact with groups of people. It reflects proper (and setting-appropriate) etiquette, customs, sensitivity, and warmth. A character with a high Socialize is the life of the party. ] *Suggested Specialties:* Bar Hopping, Church Lock-in, Dress Balls, Formal Events, Frat Parties, Political Fundraisers, The Club. #block(breakable: false)[ ==== Streetwise Knowledge of life on the streets. It tells them how to navigate the city, how to get information from unlikely sources, and where they'll be (relatively) safe. If they want to get something on the black market, Streetwise is how. ] *Suggested Specialties:* Black Market, Gangs, Navigation, Rumors, Undercover. #block(breakable: false)[ ==== Subterfuge Ability to deceive. With Subterfuge, your character can lie convincingly, project hidden messages in what they say, hide motivations, and notice deception in others. ] *Suggested Specialties:* Detecting Lies, Doublespeak, Hiding Emotion, Little White Lies, Misdirection. // #colbreak(weak: true) #sidebar()[ #block(breakable: false)[ == Optional Rule: Roles Instead of the menagerie of skills you may use roles. Each of the five roles -- #smallcaps[Scholar], #smallcaps[Scoundrel], #smallcaps[Scout], #smallcaps[Soldier], and #smallcaps[Speaker] -- represents a thematic grouping of training, skill, and experience. Your largest-rated role is usually how you best contribute to a group, whereas for smaller-rated roles, you're usually better off relying on more proficient allies. ] #smallcaps[Scholar] is your academic knowledge, including education, lore, the sciences, deduction, and research. #smallcaps[Scoundrel] is your aptitude for trickery, crime, spying, sleight of hand, defeating security measures like traps or alarms. #smallcaps[Scout] is your facility for exploration, perception, and survival, including tracking, navigation, animal handling, climbing, and simply noticing things. #smallcaps[Soldier] is your skill and experience when it comes to wielding weapons, enduring hardship, providing security, and fighting in general. #smallcaps[Speaker] is your affinity for communication, group dynamics, leadership, empathy, and various forms of self-expression, such as oratory, performance, and art. Sometimes more than one role might apply. Sneak up on a poacher with #smallcaps[Scout] or #smallcaps[Scoundrel]? Give battlefield orders with SOLDIER or SPEAKER? In those cases, choose the one your character favors. === Roles And Specialties Specialties are no different when used with roles. For example, you might use #smallcaps[Soldier] to display your general prowess with weapons, but you might also have a specialty that you add when using certain types of weapons, such as #smallcaps[Swordplay] #spec_c.d6, #smallcaps[Shotguns] #spec_c.d6, or #smallcaps[Plasma Rifles] #spec_c.d8. When you follow a trail through a dense forest, your dice pool might not only include #smallcaps[Scout] but also an extra die for your #smallcaps[Tracking] specialty. === Roles At Character Creation Assign the following die ratings to your five roles, in any order: #spec_c.d10, #spec_c.d8, #spec_c.d6, #spec_c.d6, #spec_c.d4. ]
https://github.com/optimizerfeb/MathScience
https://raw.githubusercontent.com/optimizerfeb/MathScience/main/퍼셉트론과 진화 알고리즘을 이용한 게임 인공지능.typ
typst
#set text(font: "NanumMyeongjo") #align(center, text(size: 20pt)[ *퍼셉트론과 진화 알고리즘을 이용한 게임 인공지능* ]) #align(right, [ 한남대학교 수학과 20172581 김남훈 ]) = 1. 퍼셉트론 소개 #h(5pt)퍼셉트론은 인공지능을 구현하기 위한 고전적인 방법 중 하나로, 입력받은 벡터에 선형변환과 활성화 함수라고 부르는 Component-Wise 한 비선형 함수를 번갈아 적용하며 출력 벡터를 만드는 알고리즘이다. #figure( image("images/Perceptron.svg"), caption: [하나의 은닉층을 갖는 퍼셉트론을 나타낸 그림] ) #h(5pt)방향 그래프의 각 변은 선형변환, 즉 행렬의 각 성분에 대응한다. 또한 각 정점은 벡터의 성분에 대응한다. 방향 그래프의 각 변에 대응하는 실수를 가중치, 정점에 대응하는 실수를 신호라고 한다. $ D = mat(d_1; d_2), E = mat(e_1; e_2; e_3), F = mat(f_1; f_2) \ W = mat(w_(11), w_(12); w_(21), w_(22); w_(31), w_(32)), V = mat(v_(11), v_(12), v_(13); v_(21), v_(22), v_(23)) $ 로 놓고, 이 퍼셉트론의 활성화 함수를 $"Activ"$ 라고 하면 $ E &=& "Activ"(W D) \ F &=& "Activ"(V E) $ 가 된다. 다음은 활성화 함수로 이용되는 대표적인 세 함수이다. $ "RELU"(d) &= max(0, d) \ "Sigmoid"(d) &= frac(e^d, e^d + 1) \ "Sign"(d) &= cases(-1 &"if" d lt.eq 0, 1 &"if" d gt 0) $ #h(5pt)활성화 함수가 필요한 이유는, 선형변환의 합성은 반드시 선형변환이므로 활성화함수 없이는 선형적이지 않은 문제를 풀 수 없기 때문이다. = 2. 진화 알고리즘과 퍼셉트론 #h(5pt)퍼셉트론이 주어진 문제를 풀 수 있는지는 가중치가 잘 설정되었느냐에 따라 갈린다는 것을 위의 내용으로부터 예상할 수 있다. 가중치는 사람이 직접 설정해줄 수도 있지만 각 층의 차원에 커지면 가중치의 수가 차원의 제곱으로 증가하기 때문에 사실상 불가능하다. 실제로 쓰이는 방법은 적당한 알고리즘을 이용해 랜덤한 초기값을 설정한 뒤 기계학습 알고리즘에 의해 가중치가 자동으로 조정되도록 하는 것이다. #h(5pt)퍼셉트론의 가중치를 설정하는 대표적인 방법으로는 역전파 알고리즘과 진화 알고리즘이 있는데, 여기서는 진화 알고리즘에 대해 알아볼 것이다. 정답이 존재하여 그 정답에 가능한 한 가깝게 접근하는 것이 목적인 상용 인공지능과 달리 게임 속 인공지능의 목적은 게이머에게 재미를 선사하는 것이므로 보다 예측 불가능하고 다양한 행동 패턴을 갖기를 원하기 때문이다. #h(5pt)단순한 형태의 진화 알고리즘은 다음과 같이 구현할 수 있다. 다음은 주어진 퍼셉트론의 가중치 중 일부를 임의로 선택해 $-0.1$ 에서 $0.1$ 사이의 임의의 실수를 더해 얻어진 퍼셉트론을 반환하는 함수이다. #block( fill:luma(230), inset: 8pt, text(font:"D2Coding", size:10pt,[ def generate_child(self):\ #h(20pt)weights = $[w_(11), w_(12), dots, w_(32), v_(11), dots, v_(23)]$ \/\/ 기존 퍼셉트론의 가중치를 성분으로 갖는 벡터\ #h(20pt)n = randint(1, 12) \/\/ $1$ 에서 $12$(벡터 weights 의 길이) 사이의 임의의 정수\ #h(20pt)selected = weights.select(n) \/\/ $1$ 에서 $12$ 사이의 정수 $n$ 개를 임의로 선택\ \ #h(20pt)for i in selected:\ #h(40pt)multiplier = randomfloat(-0.1, 0.1) \/\/ $-0.1$ 에서 $0.1$ 사이의 임의의 실수\ #h(40pt)weights[i] = weights[i] + multiplier\ \ #h(20pt)return Perceptron(weights) \/\/ weights 의 각 성분을 가중치로 갖는 퍼셉트론을 반환 ]) ) #h(5pt)위 코드를 통해 기존의 퍼셉트론에서 약간 변형된 퍼셉트론을 얻을 수 있다. 이것을 기존 퍼셉트론의 *자손* 이라고 부르는데, 적게는 수십, 많게는 수백개의 자손을 생성한 뒤 그 중 정답에 가장 근접한 자손을 선택하여 다음 세대의 부모로 삼아 앞의 과정을 다시 수행한다. 이 때, $n$ 번째 반복에서 생성된 자손들을 $n$ *세대* 라고 한다. 진화 알고리즘은 이러한 과정을 사용자가 원하는 만큼 정답에 근접한 퍼셉트론이 등장할 때까지, 적게는 $10$ 세대, 많게는 수백 세대에 걸쳐 위의 과정을 반복한다. = 3. 진화 알고리즘과 게임 #h(5pt)선형대수학을 수강한 학생들은 주어진 문제의 정답이 속한 공간의 차원이 증가할수록 각 세대가 지날 때마다 정답에 더 근접하기 위해 생성해야 하는 자손의 수가 지수적으로 증가함을 짐작할 수 있을 것이다. 그러므로, 진화 알고리즘은 비교적 단순한 문제에 유효하다. 위에서 언급한 *역전파 알고리즘* 은 그보다 복잡한, 차원이 높은 문제에 유효하다. 게임 NPC 의 행동은 차원이 낮은 문제에 속하므로, 진화 알고리즘을 통한 학습이 적절하다. === 진화 알고리즘을 이용해 인공지능에게 운전을 가르치는 예시 https://youtu.be/Aut32pR5PQA\ 여기에서는 두 개의 은닉층을 갖는 퍼셉트론을 사용하였다. 매 순간의 행동은 $2$ 차원 공간의 벡터로 주어진다. === 진화 알고리즘을 이용해 인공지능에게 뱀 게임을 가르치는 예시 https://youtu.be/C4WH5b-EidU\ https://github.com/kairess/genetic_snake\ 소스 코드가 공개되어 있다. 매 순간의 행동은 $3$ 차원 공간의 벡터로 주어진다. = 참고문헌 #align(left, text(size: 10pt,[ <NAME>. (2005). Artificial intelligence: a guide to intelligent systems. Pearson education.\ Goodfellow, I., <NAME>., & <NAME>. (2016). Deep learning. MIT press. ]) )
https://github.com/OverflowCat/astro-typst
https://raw.githubusercontent.com/OverflowCat/astro-typst/master/src/pages/_included.typ
typst
This is an included file. $ H = n overline(u) y = n^' overline(u)^' y^' $ This is an included file. Include changed to:
https://github.com/hargoniX/bachelor
https://raw.githubusercontent.com/hargoniX/bachelor/main/present-short/presentation.typ
typst
#import "@preview/polylux:0.3.1": * #import "@preview/codelst:1.0.0": sourcecode #import "@preview/bytefield:0.0.2": bytefield, bit, bits, bytes, flagtext #let bfield(..args) = [ #set text(18pt); #bytefield(msb_first: true, ..args); ] #import "theme.typ" : * #show: genua-theme.with() #set text(font: "Fira Sans", weight: "light", size: 20pt) #set strong(delta: 100) #set par(justify: true) #title-slide( author: [<NAME>], title: "VeRix: A Verified Rust ix(4) driver", date: "15.01.2024", extra: "Thesis Defense", logo_company: "figures/genua.svg", logo_institution: "figures/hm.svg", logo_size: 45%, ) #slide(title: "Table of contents")[ #genua-outline ] #new-section-slide("Goals") #slide(title: "Goals")[ Verify interactions of drivers with hardware by: 1. enabling driver development in Rust on L4.Fiasco 2. developing a driver framework for real-world hardware and formal verification 3. developing an Intel 82599 driver on top of it 4. verifying that this driver: - doesn't panic (safety) - doesn't put the hardware into an undefined state (safety) - receives all packets that are received by the hardware (correctness) - correctly instructs the hardware to send packets (correctness) ] #new-section-slide("Formal Verification in Rust") #slide(title: "Tools")[ #figure( table( columns: (auto, auto, auto, auto), [*Feature*], [*Kani*], [*Creusot*], [*Prusti*], [Core], [#sym.checkmark], [#sym.checkmark], [#sym.checkmark], [Generics], [#sym.checkmark], [#sym.checkmark], [#sym.checkmark], [Traits], [#sym.checkmark], [#sym.checkmark], [#sym.checkmark], [`unsafe`], [#sym.checkmark], [-], [-], [`RefCell`], [#sym.checkmark], [#sym.checkmark], [#sym.checkmark], ), caption: [Capabilities of formal verification tools for Rust], ) <requirements> ] #slide(title: "Kani guarantees")[ Guarantees provided by Kani: - memory safety, that is: - pointer type safety - the absence of invalid pointer indexing - the absence of out-of-bounds accesses - the absence of mathematical errors like arithmetic overflow - the absence of runtime panics - the absence of violations of user-added assertions ] #slide(title: "Kani Basics")[ ```rust fn get_wrapped(a: &[u32], i: usize) -> u32 { return a[i % a.len()]; } #[kani::proof] fn check_get_wrapped() { let size: usize = kani::any(); kani::assume(size < 128); let index: usize = kani::any(); let array: Vec<u32> = vec![0; size]; get_wrapped(&array, index); } ``` ] #slide(title: "Kani counter examples")[ ```rust #[test] fn kani_concrete_playback_check_get_wrapped_10606138830414890630() { let concrete_vals: Vec<Vec<u8>> = vec![ // 0ul vec![0, 0, 0, 0, 0, 0, 0, 0], // 18446744073709551615ul vec![255, 255, 255, 255, 255, 255, 255, 255], ]; kani::concrete_playback_run(concrete_vals, check_get_wrapped); } ``` ] #slide(title: "Kani cover")[ ```rust fn complicated() -> usize { kani::any() } #[kani::proof] fn check_get_wrapped() { let size: usize = kani::any(); kani::assume(size < 128); let array: Vec<u32> = vec![0; size]; let index = complicated(); kani::cover(index >= array.len(), "Out of bounds indexing possible"); get_wrapped(&array, index); } ``` ] #slide(title: "Kani loops")[ ```rust fn zeroize(buffer: &mut [u8]) { for i in 0..buffer.len() { buffer[i] = 0; } } #[kani::unwind(32)] // <== HERE! #[kani::proof] fn check_zeroize() { let size: usize = kani::any_where(|&size| size > 0 && size < 32); let mut buffer: Vec<u8> = vec![10; size]; zeroize(&mut buffer); let index: usize = kani::any_where(|&index| index < buffer.len()); assert!(buffer[index] == 0); } ``` ] #slide(title: "Kani stubs")[ ```rust fn interaction() { thread::sleep(Duration::from_secs(1)); rate_limited_functionality(); } #[kani::stub(thread::sleep, mock_sleep)] // <== HERE! #[kani::proof] fn check_interaction() { interaction(); } ``` ] #new-section-slide("verix") #slide(title: "Architecture")[ #figure( image("figures/drawio/verix-arch.drawio.pdf.svg", width: 80%), caption: [Architecture] ) <arch> ] #slide(title: [`pc-hal`])[ `embedded-hal` style library, providing traits for: - DMA mappings - PCI bus - PCI config space - raw pointer-based MMIO interfaces (`svd2rust` style) ] #slide(title: [`ixy` Register Access])[ ```rust pub const IXGBE_CTRL: u32 = 0x00000; pub const IXGBE_CTRL_LNK_RST: u32 = 0x00000008; pub const IXGBE_CTRL_RST: u32 = 0x04000000; pub const IXGBE_CTRL_RST_MASK: u32 = IXGBE_CTRL_LNK_RST | IXGBE_CTRL_RST; fn set_reg32(&self, reg: u32, value: u32) { unsafe { ptr::write_volatile( (self.addr as usize + reg as usize) as *mut u32, value ); } } self.set_reg32(IXGBE_CTRL, IXGBE_CTRL_RST_MASK); ``` ] #slide(title: [`pc-hal` Register Access])[ ```rust mm2types! { Intel82599 Bit32 { Bar0 { ctrl @ 0x000000 RW { // Other fields lrst @ 3, rst @ 26, } } } } bar0.ctrl().modify(|_, w| w.lrst(1).rst(1)); ``` ] #slide(title: "verix")[ Driver performs three steps: 1. Initialization through PCI config space 2. Initialization through MMIO config space 3. Packet processing through DMA queues ] #slide(title: "Verifying packet receiving")[ 1. prove that the RX queue state after configuration is valid (Kani checked) 2. prove that if the queue state is valid and `rx()` is called the state remains valid (Kani checked) 3. This constitutes an induction proof that shows we always remain in a valid state (meta) 4. For all valid queue states (and thus for all reachable states): - prove that if the queue has a packet and we call `rx()` we get it (Kani checked) - prove that if the queue is empty and we call `rx()` we get nothing (Kani checked) ] #new-section-slide("Evaluation") #slide(title: "Verification")[ - entire verification effort consumed approximately 150 man-hours - two limitations: 1. `Drop` functionality DMA allocator could not be verified 2. queue size is limited to 16 elements ] #slide(title: "SAT Limitation")[ #figure( table( columns: (auto, auto, auto, auto), [*Solver*], [*Queue Size*], [*Time (hh:mm:ss)*], [*RAM (GB)*], [Minisat], [16], [Timeout], [-], [CaDiCal], [16], [$05:04:39$], [46], [CaDiCal], [32], [-], [OOM], [Kissat], [16], [$03:53:56$], [18], [Kissat], [32], [-], [OOM], [Glucose], [16], [$05:42:35$], [19], [Glucose], [32], [-], [OOM], ), caption: [Resource Consumption of different SAT solvers], ) <satres> ] #slide(title: "SMT Limitation")[ #figure( table( columns: (auto, auto, auto), [*Solver*], [*Queue Size*], [*Result*], [Z3], [16], [Crashed CBMC], [CVC4], [16], [Crashed CVC4], [CVC5], [16], [Crashed CBMC], ), caption: [Resource Consumption of different SMT solvers], ) <smtres> ] #slide(title: "Performance")[ #figure( table( columns: (auto, auto, auto, auto, auto), [*Implementation*], [*CPU Freq (GHz)*], [*Absolute (Mpps)*], [*Max (Mpps)*], [*Max\%*], [ixy C], [3.3], [27.4], [29.76], [92.07], [ixy.rs], [3.3], [27.4], [29.76], [92.07], [verix], [2.4], [11.9], [14.88], [79.97], [ixy C], [1.7], [17.2], [29.76], [57.80], [ixy.rs], [1.7], [17.2], [29.76], [57.80], ), caption: [Performance of ixy vs verix at a batch size of 64] ) <perf-packets> ] #new-section-slide("Conclusion") #slide(title: "Conclusion")[ We thus conclude that we: - ported ixy to L4 at a, most likely, comparable performance - successfully applied our model-based proof strategy to a real world problem - verified the desired properties at a small but not irrelevant scale #pause Three extensions of our work seem interesting: - extend `pc-hal` to an `embedded-hal` style library - integrate verix with the rest of L4 - improve the maximum verified queue size ] #focus-slide[ Questions? ]
https://github.com/Nenuial/fnchJury
https://raw.githubusercontent.com/Nenuial/fnchJury/main/_extensions/nenuial/se-doc/typst-show.typ
typst
// Typst custom formats typically consist of a 'typst-template.typ' (which is // the source code for a typst template) and a 'typst-show.typ' which calls the // template's function (forwarding Pandoc metadata values as required) // // This is an example 'typst-show.typ' file (based on the default template // that ships with Quarto). It calls the typst function named 'article' which // is defined in the 'typst-template.typ' file. // // If you are creating or packaging a custom typst template you will likely // want to replace this file and 'typst-template.typ' entirely. You can find // documentation on creating typst templates here and some examples here: // - https://typst.app/docs/tutorial/making-a-template/ // - https://github.com/typst/templates #show: doc => article( logo: "$logo$", $if(title)$ title: [$title$], $endif$ $if(subtitle)$ subtitle: [$subtitle$], $endif$ $if(by-author)$ authors: ( $for(by-author)$ $if(it.name.literal)$ ( name: [$it.name.literal$], affiliation: [$for(it.affiliations)$$it.name$$sep$, $endfor$], email: [$it.email$] ), $endif$ $endfor$ ), $endif$ $if(date)$ date: [$date$], $endif$ $if(lang)$ lang: "$lang$", $endif$ $if(region)$ region: "$region$", $endif$ $if(abstract)$ abstract: [$abstract$], abstract-title: "$labels.abstract$", $endif$ $if(margin)$ margin: ($for(margin/pairs)$$margin.key$: $margin.value$,$endfor$), $endif$ $if(papersize)$ paper: "$papersize$", $endif$ $if(flipped)$ flipped: $flipped$, $endif$ $if(mainfont)$ font: ("$mainfont$",), $endif$ $if(fontsize)$ fontsize: $fontsize$, $endif$ $if(section-numbering)$ sectionnumbering: "$section-numbering$", $endif$ $if(toc)$ toc: $toc$, $endif$ $if(toc-title)$ toc_title: [$toc-title$], $endif$ $if(toc-indent)$ toc_indent: $toc-indent$, $endif$ toc_depth: $toc-depth$, cols: $if(columns)$$columns$$else$1$endif$, doc, )
https://github.com/UntimelyCreation/typst-neat-cv
https://raw.githubusercontent.com/UntimelyCreation/typst-neat-cv/main/src/content/en/languages.typ
typst
MIT License
#import "../../template.typ": * #cvSection("Languages") #cvLanguage( name: "English", info: "Native Language", ) #cvLanguage( name: "French", info: "Native Language", ) #cvLanguage( name: "German", info: "B2, Deutsches Sprachdiplom I", ) #cvLanguage( name: "Japanese", info: "B1", )
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/079.%20die.html.typ
typst
die.html How Not to Die Want to start a startup? Get funded by Y Combinator. August 2007(This is a talk I gave at the last Y Combinator dinner of the summer. Usually we don't have a speaker at the last dinner; it's more of a party. But it seemed worth spoiling the atmosphere if I could save some of the startups from preventable deaths. So at the last minute I cooked up this rather grim talk. I didn't mean this as an essay; I wrote it down because I only had two hours before dinner and think fastest while writing.) A couple days ago I told a reporter that we expected about a third of the companies we funded to succeed. Actually I was being conservative. I'm hoping it might be as much as a half. Wouldn't it be amazing if we could achieve a 50% success rate?Another way of saying that is that half of you are going to die. Phrased that way, it doesn't sound good at all. In fact, it's kind of weird when you think about it, because our definition of success is that the founders get rich. If half the startups we fund succeed, then half of you are going to get rich and the other half are going to get nothing.If you can just avoid dying, you get rich. That sounds like a joke, but it's actually a pretty good description of what happens in a typical startup. It certainly describes what happened in Viaweb. We avoided dying till we got rich.It was really close, too. When we were visiting Yahoo to talk about being acquired, we had to interrupt everything and borrow one of their conference rooms to talk down an investor who was about to back out of a new funding round we needed to stay alive. So even in the middle of getting rich we were fighting off the grim reaper.You may have heard that quote about luck consisting of opportunity meeting preparation. You've now done the preparation. The work you've done so far has, in effect, put you in a position to get lucky: you can now get rich by not letting your company die. That's more than most people have. So let's talk about how not to die.We've done this five times now, and we've seen a bunch of startups die. About 10 of them so far. We don't know exactly what happens when they die, because they generally don't die loudly and heroically. Mostly they crawl off somewhere and die.For us the main indication of impending doom is when we don't hear from you. When we haven't heard from, or about, a startup for a couple months, that's a bad sign. If we send them an email asking what's up, and they don't reply, that's a really bad sign. So far that is a 100% accurate predictor of death.Whereas if a startup regularly does new deals and releases and either sends us mail or shows up at YC events, they're probably going to live.I realize this will sound naive, but maybe the linkage works in both directions. Maybe if you can arrange that we keep hearing from you, you won't die.That may not be so naive as it sounds. You've probably noticed that having dinners every Tuesday with us and the other founders causes you to get more done than you would otherwise, because every dinner is a mini Demo Day. Every dinner is a kind of a deadline. So the mere constraint of staying in regular contact with us will push you to make things happen, because otherwise you'll be embarrassed to tell us that you haven't done anything new since the last time we talked.If this works, it would be an amazing hack. It would be pretty cool if merely by staying in regular contact with us you could get rich. It sounds crazy, but there's a good chance that would work.A variant is to stay in touch with other YC-funded startups. There is now a whole neighborhood of them in San Francisco. If you move there, the peer pressure that made you work harder all summer will continue to operate.When startups die, the official cause of death is always either running out of money or a critical founder bailing. Often the two occur simultaneously. But I think the underlying cause is usually that they've become demoralized. You rarely hear of a startup that's working around the clock doing deals and pumping out new features, and dies because they can't pay their bills and their ISP unplugs their server.Startups rarely die in mid keystroke. So keep typing!If so many startups get demoralized and fail when merely by hanging on they could get rich, you have to assume that running a startup can be demoralizing. That is certainly true. I've been there, and that's why I've never done another startup. The low points in a startup are just unbelievably low. I bet even Google had moments where things seemed hopeless.Knowing that should help. If you know it's going to feel terrible sometimes, then when it feels terrible you won't think "ouch, this feels terrible, I give up." It feels that way for everyone. And if you just hang on, things will probably get better. The metaphor people use to describe the way a startup feels is at least a roller coaster and not drowning. You don't just sink and sink; there are ups after the downs.Another feeling that seems alarming but is in fact normal in a startup is the feeling that what you're doing isn't working. The reason you can expect to feel this is that what you do probably won't work. Startups almost never get it right the first time. Much more commonly you launch something, and no one cares. Don't assume when this happens that you've failed. That's normal for startups. But don't sit around doing nothing. Iterate.I like <NAME>'s suggestion of trying to make something that at least someone really loves. As long as you've made something that a few users are ecstatic about, you're on the right track. It will be good for your morale to have even a handful of users who really love you, and startups run on morale. But also it will tell you what to focus on. What is it about you that they love? Can you do more of that? Where can you find more people who love that sort of thing? As long as you have some core of users who love you, all you have to do is expand it. It may take a while, but as long as you keep plugging away, you'll win in the end. Both Blogger and Delicious did that. Both took years to succeed. But both began with a core of fanatically devoted users, and all Evan and Joshua had to do was grow that core incrementally. Wufoo is on the same trajectory now.So when you release something and it seems like no one cares, look more closely. Are there zero users who really love you, or is there at least some little group that does? It's quite possible there will be zero. In that case, tweak your product and try again. Every one of you is working on a space that contains at least one winning permutation somewhere in it. If you just keep trying, you'll find it.Let me mention some things not to do. The number one thing not to do is other things. If you find yourself saying a sentence that ends with "but we're going to keep working on the startup," you are in big trouble. Bob's going to grad school, but we're going to keep working on the startup. We're moving back to Minnesota, but we're going to keep working on the startup. We're taking on some consulting projects, but we're going to keep working on the startup. You may as well just translate these to "we're giving up on the startup, but we're not willing to admit that to ourselves," because that's what it means most of the time. A startup is so hard that working on it can't be preceded by "but."In particular, don't go to graduate school, and don't start other projects. Distraction is fatal to startups. Going to (or back to) school is a huge predictor of death because in addition to the distraction it gives you something to say you're doing. If you're only doing a startup, then if the startup fails, you fail. If you're in grad school and your startup fails, you can say later "Oh yeah, we had this startup on the side when I was in grad school, but it didn't go anywhere."You can't use euphemisms like "didn't go anywhere" for something that's your only occupation. People won't let you.One of the most interesting things we've discovered from working on Y Combinator is that founders are more motivated by the fear of looking bad than by the hope of getting millions of dollars. So if you want to get millions of dollars, put yourself in a position where failure will be public and humiliating.When we first met the founders of Octopart, they seemed very smart, but not a great bet to succeed, because they didn't seem especially committed. One of the two founders was still in grad school. It was the usual story: he'd drop out if it looked like the startup was taking off. Since then he has not only dropped out of grad school, but appeared full length in Newsweek with the word "Billionaire" printed across his chest. He just cannot fail now. Everyone he knows has seen that picture. Girls who dissed him in high school have seen it. His mom probably has it on the fridge. It would be unthinkably humiliating to fail now. At this point he is committed to fight to the death.I wish every startup we funded could appear in a Newsweek article describing them as the next generation of billionaires, because then none of them would be able to give up. The success rate would be 90%. I'm not kidding.When we first knew the Octoparts they were lighthearted, cheery guys. Now when we talk to them they seem grimly determined. The electronic parts distributors are trying to squash them to keep their monopoly pricing. (If it strikes you as odd that people still order electronic parts out of thick paper catalogs in 2007, there's a reason for that. The distributors want to prevent the transparency that comes from having prices online.) I feel kind of bad that we've transformed these guys from lighthearted to grimly determined. But that comes with the territory. If a startup succeeds, you get millions of dollars, and you don't get that kind of money just by asking for it. You have to assume it takes some amount of pain.And however tough things get for the Octoparts, I predict they'll succeed. They may have to morph themselves into something totally different, but they won't just crawl off and die. They're smart; they're working in a promising field; and they just cannot give up.All of you guys already have the first two. You're all smart and working on promising ideas. Whether you end up among the living or the dead comes down to the third ingredient, not giving up.So I'll tell you now: bad shit is coming. It always is in a startup. The odds of getting from launch to liquidity without some kind of disaster happening are one in a thousand. So don't get demoralized. When the disaster strikes, just say to yourself, ok, this was what Paul was talking about. What did he say to do? Oh, yeah. Don't give up.Japanese TranslationArabic Translation
https://github.com/coalg/notebook
https://raw.githubusercontent.com/coalg/notebook/main/documentation/intro-to-typst/hello.typ
typst
#import "@preview/tablex:0.0.8": tablex, colspanx, rowspanx #set par(justify: true) #let meta = yaml("hello.yaml") #align(center, text(17pt)[ *#meta.title* ]) #set align(left) #text(15pt)[ #meta.company ] #text(11pt)[ #meta.department ] #text(11pt)[ #meta.payer 様 ] #set align(right) #meta.addres 請求日: #meta.charge-date #let sum = 0 #set align(left) = 詳細 #tablex( columns: (auto, auto, 1fr, auto), // 4 columns rows: auto, // at least 1 row of auto size header-row: red, align: center + horizon, stroke: black, auto-vlines: false, [*番号*], [*注文日*], [*品目*], [*価格*], ..for charge in meta.charges { (charge.at("no"), charge.at("date"), charge.at("description"), "¥" + str(charge.at("price"))) sum += charge.at("price") } ) #set align(right) #tablex( columns: (auto, 50pt), align: center + horizon, auto-vlines: false, [小計], "¥" + str(sum), [消費税], "¥" + str(sum * 0.08), [総計], "¥" + str(calc.floor(sum * 1.08)) )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/ouset/0.1.0/ouset.typ
typst
Apache License 2.0
/// clip param c ∈ {0,1,2,3} ≜ {no clip, left clip, right clip, both clip}, #let overset(s, t, c: 0) = style(sty => { let sw = measure(s, sty).width let tw = measure(math.script(t), sty).width let dw = calc.max(tw - sw, 0pt) if calc.odd(c) { h(-dw/2) } // left clip for e.g. &= pad($attach(#s, t: #t, tr: "")$, right: dw) if c > 1 { h(-dw/2) } // right clip for e.g. =& }) /// clip param c ∈ {0,1,2,3} ≜ {no clip, left clip, right clip, both clip}, #let underset(s, b, c: 0) = style(sty => { let sw = measure(s, sty).width let bw = measure(math.script(b), sty).width let dw = calc.max(bw - sw, 0pt) if calc.odd(c) { h(-dw/2) } // left clip for e.g. &= pad($attach(#s, b: #b, br: "")$, right: dw) if c > 1 { h(-dw/2) } // right clip for e.g. =& }) /// clip param c ∈ {0,1,2,3} ≜ {no clip, left clip, right clip, both clip}, #let overunderset(s, t, b, c: 0) = style(sty => { let sw = measure(s, sty).width let tw = measure(math.script(t), sty).width let bw = measure(math.script(b), sty).width let dw = calc.max(calc.max(tw, bw) - sw, 0pt) if calc.odd(c) { h(-dw/2) } // left clip for e.g. &= pad($attach(#s, t: #t, tr: "", b: #b, br: "")$, right: dw) if c > 1 { h(-dw/2) } // right clip for e.g. =& })
https://github.com/r8vnhill/apunte-bibliotecas-de-software
https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit2/operator_overloading.typ
typst
== Sobrecarga de Operadores La sobrecarga de operadores es una funcionalidad de algunos lenguajes de programación que permite a lxs desarrolladorxs definir implementaciones personalizadas para los operadores estándar como `+`, `-`, `*`, `/`, entre otros. En Kotlin, esto se logra mediante el uso de la palabra clave `operator` seguido de `fun`, indicando que se está definiendo una función que actúa como un operador. === Cómo Funciona Para sobrecargar un operador, se declara una función miembro o una función de extensión con el prefijo `operator`. El nombre de la función debe corresponder a una de las funciones de operador predefinidas en Kotlin, como `plus`, `minus`, `times`, etc. === Ejemplo Práctico Consideremos un ejemplo con un tipo de dato definido por el usuario, `Complex`, que representa un número complejo. Queremos permitir que estos números complejos se puedan sumar utilizando el operador `+`. Aquí está cómo podríamos implementar esto: ```kotlin class Complex(val real: Double, val imaginary: Double) { operator fun plus(other: Complex) = Complex(real + other.real, imaginary + other.imaginary) } ``` En este ejemplo: - `Complex` es una clase que almacena dos propiedades: `real` e `imaginary`. - `plus` es una función miembro que sobrecarga el operador `+`. Toma otro objeto `Complex` como parámetro y devuelve un nuevo objeto `Complex` cuyo valor real e imaginario es la suma de los valores correspondientes de los dos números complejos. === Uso Gracias a la sobrecarga de operadores, podemos usar el operador `+` de forma natural con instancias de `Complex`: ```kotlin val number1 = Complex(1.0, 2.0) val number2 = Complex(3.0, 4.0) val sum = number1 + number2 println("Sum: (${sum.real}, ${sum.imaginary})") ``` === Consideraciones Al diseñar clases que sobrecarguen operadores, es importante mantener el comportamiento intuitivo y esperado. Por ejemplo, asegurarse de que la operación sea conmutativa si eso tiene sentido para el tipo de datos, como es el caso de la suma de números complejos.
https://github.com/voXrey/cours-informatique
https://raw.githubusercontent.com/voXrey/cours-informatique/main/typst/21-programmation-dynamique.typ
typst
#import "@preview/codly:0.2.1": * #show: codly-init.with() #set text(font: "Roboto Serif") = Programmation Dynamique <programmation-dynamique> == I - Introduction <i---introduction> ==== 1. Exemple du problème du Sac à dos <exemple-du-problème-du-sac-à-dos> Écrivons un algorithme qui résout le problème par backtracking #codly() ```ocaml (* obj : (int*int) array : tablau de poids/valeur *) let knapsack obj poids_max = (* On souhaite calculer la valeur optimale sans conserver la façon de remplir x *) (* p : poids_max courant *) let rec aux i p = if i = 0 || p = 0 then 0 else begin if fst obj.(i-1) > p then aux (i-1) p else max (aux (i-1) p) (snd obj.(i-1) + aux (i-1) (p-(fst obj.(i-1)))) end in aux (Array.length obj) poids_max;; ``` $==>$ On fait apparaître la notion de sous-problèmes. La valeur renvoyée par `aux i p` est la valeur optimale du sac avec les objets $o b j lr([0 : i])$ et le poids max p. Prenons un exemple : $"obj" = [|(1 , 3); (3, 10); (5, 7); (8, 12)|]$ et $"poids_max(max)" = 10$ On dessine l'arbre des appels récursifs à la fonction aux. #codly(enable-numbers: false) ```toml aux 4 10 ├── oui │ └── aux 3 2 │ └── non │ └── aux 2 2 │ └── non │ └── aux 1 2 └── non └── aux 3 10 ├── oui │ └── aux 2 5 │ ├── oui │ │ └── aux 1 2 │ └── non │ └── ... └── non └── aux 2 10 └── ... ``` $==>$ Le calcul `aux 1 2` va être effectué 2 fois ! ==== 2. Mémoïsation <mémoïsation> La mémoïsation est une "technique" en informatique qui consiste à mémoriser (stocker en mémoire) des résultats de "calculs" qui risquent d'être réutilisés plus tard. De manière générale, on peut mémoïser une fonction $f : prime a arrow.r prime b$ $arrow.r.double$ On utilise un dictionnaire dont les clés sont les arguments de f (de type 'a) et les valeurs associées sont les images de f : ${ x : f lr((x)) , . . . }$ Appliquons cette idée : #codly(enable-numbers: true) ```ocaml let knapsack obj poids_max = (* Création de la table *) let d = Hashtbl.create () in (* Cas de base *) for i = 0 to Array.length obj do Hashtbl.add d (i,0) 0 done; for p = 0 to poids_max do Hashtbl.add d (0,p) 0 done; (* Fonction aux *) let rec aux i p = match Hashtbl.find_opt d (i,p) with | None -> if fst obj.(i-1) > p then begin let v = aux (i-1) p in Hashtbl.add d (i,p) v; v end else begin let v = max (aux (i-1) p) (snd obj.(i-1) (p- fst obj.(i-1))) in Hashtbl.add d (i,p) v; v | Some v -> v in aux (Array.length obj) poids_max;; ``` Exemple tiré de wikipédia ```ocaml let memo f = let h = Hashtbl.create 97 in fun x -> try Hashtbl.find h x with Not_found -> let y = f x in Hashtbl.add h x y ; y ;; let ma_fonction_efficace = memo ma_fonction;; ``` ```ocaml (* Pour une fonction récursive comme la suite de Fibonacci *) let memo_rec yf = let h = Hashtbl.create 97 in let rec f x = try Hashtbl.find h x with Not_found -> let y = yf f x in Hashtbl.add h x y ; y in f ;; let fib = memo_rec (fun fib n -> if n<2 then n else fib (n-1)+fib (n-2));; ``` == II - Principe de la programmation Dynamique C'est un concept aux contours assez flous. A notre niveau, les exercices liés à la programmation dynamique auront (presque) toujours la forme suivante : 1. Établir une équation de récurrence qui décrit le problème concret : $u_n = u_(n . . . , p . . .) + m a x { u_(n . . . , p . . .) }$ 2. Écrire un programme qui calcule $u_(n , p)$ (sans refaire 2 fois le même calcul). Reprise de l'exemple du sac à dos : $arrow.r.double.long$ On pose $v_(i , p)$ la valeur optimale du sac à dos pour le sous-problème $o b j lr([0 : i])$ aux poids maximal p.~ $forall i in [0,n], v_(i,0) = 0, forall p in [0, "poids"_("max")] , v_(0, p) = 0$ $v_(i,p) = v_(i-1,p) "si fst obj".(i-1) > p $ $v_(i,p) = max(v_(i-1,p), "snd obj".(i-1)+v_(i-1)+v_(i-1),p-"fst obj".(i-1)) "sinon"$ Les suites récurrentes qui décrivent le problème correspondent souvent à découper le problème en sous-problèmes. Pour expliquer que certains sous-problèmes seront considérés plusieurs fois dans l'arbre des appels récursifs on dit que les sous-problèmes se chevauchent. == III - Première étape, un exemple <iii---première-étape-un-exemple> Vous êtes consultant pour une entreprise qui vend des barres de fer. Une étude de marché vient fixer des prix pour chaque longueur de barre de fer : #figure( align( center, )[#table( columns: 8, align: (col, row) => (auto, auto, auto, auto, auto, auto, auto, auto,).at(col), inset: 6pt, [Longueur], [0], [1], [2], [3], [4], […], [K], [prix], [0], [5], [8], [16], [16], […], [Prices\[K\]], )], ) Pour accéder au prix de la barre de longueur K on écrit $"prices"[K]$. #quote( block: true, )[ Problème : l'usine livre une barre de taille N. Quel est le découpage optimal de la barre, c'est-à-dire celui qui maximise le prix de vente. ] On note pour $K in [0 , N] , p_K$ le prix de vente optimal d'une barre de longueur K. ~Établir une équation de récurrence sur $p_K$ : - $p_0 = 0$ - Pour $K > 0 , p_K = max_(l in [1 , K]) ("prices"[l] + p_(K - l))$ Preuve $"prices"[k]$ : prix d'une barre de longueur k $p_0 = 0$ $p_K = m a x_(l in [1 , K]) ("prices"[l] + p_(K - l))$ On montre par récurrence sur K que p\_K est le prix de vente maximal d'une barre de longueur K. #strong[Initialisation] : Trivial #strong[Hérédité] : Soit $K > 0$ tel que l'hypothèse de récurrence HR soit vrai pour tout i Soit $l in [1 , K]$, par HR $p_(K - l)$ est le prix de vente optimal d'une barre de longueur K-l, donc il existe un découpage $K - l = n_0 + . . . + n_P$ tel que $sum_(i = 0)^p "prices"lr([n_i]) = p_(K - l)$. Alors clairement le découpage $K = l + n_0 + . . . + n_P$ réalise le prix de vente $"prices"lr([l]) + p_(K - l)$. Donc $p_K lt.eq p r i x_(o p t i)$ pour K. Réciproquement, soit $K = n_0 + . . . + n_P$ un découpage optimal pour une barre de longueur K (existe car possibilités finies). Alors le découpage $K - n_0 = n_1 + . . . n_P$ est optimal. Si ce n'était pas le cas, en prenant un meilleur découpage $K - n_0 = n_1 prime + . . . + n_P prime$ on obtient un meilleur découpage pour K. Donc $sum_(i = 1)^P "prices"[n_i] = p_K - n_0$. Donc $p r i x_(o p t i) = "prices"[n_0] + p_K - n_0 lt.eq p_K$. #strong[Mot-clé] : Propriété de sous-problème optimal = une solution qui se construit en combinant des solutions optimales pour des sous-problèmes. == IV - Seconde étape <iv---seconde-étape> ==== 1. Version Descendante <version-descendante> Il s'agit de la version récursive, c'est la mémoïsation. Illustration sur la vente de barres de fer : L'équation de récurrence est donc connue. ```ocaml open Hastbl;; let price_opti prices n = (* 1. Création de la table *) let t = create () in (* 2. Cas de base *) add t 0 0; (* 3. Fonction aux *) let rec aux K = (* aux K = pK *) match find_opt t K with | None -> let p = max_list (List.init K (fun l->prices.(l+1) + aux (K-l-1))) in add t K p; p | Some p -> p in (* 4. On retourne la valeur souhaitée *) aux n;; let max_list = List.fold_left max 0;; ``` ```ocaml let rec fold_left op acc = function | [] -> acc | h :: t -> fold_left op (op acc h) t ``` La fonction `fold_left` permet d'abréger toute fonction de cette forme : ```ocaml let s = ref e in for i = 0 to Array.length a - 1 do s := s f a[i];; ``` <NAME> #quote(block: true)[ Écrit en `python`, traduit du `camlython` ] ```python def version_desc(arg): # 1. On crée la table T = dict() # 2. Cas de base T[cas_de_base] = ... # 3. Fonction aux def aux (arg_sspb): if arg_sspb in T: return T[arg_sspb] else res = equation_de_recurrence(arg_sspb) T[arg_sspb] = res return res # 4. Valeur souhaitée aux (arg) ``` Variantes : - Type de table : dictionnaire ou tableau de dimension N. - Cas de base : Si table de dimension N \> 1, il y a plusieurs cas de base. - Possibilité de traiter tous les cas de base dans la fonction aux. ==== 2. Version Ascendante = Impérative <version-ascendante-impérative> Au lieu de vérifier si un calcul a déjà été mené (/sous-problème déjà résolu), on remplit toute la table dans le bon ordre systématiquement. Le bon ordre est celui qui assure que pour remplir la case courante, on a déjà remplit les cases utilisées dans l'équation de récurrence. On reprend l'exemple des barres de fer une fois de plus : ```ocaml let barre_de_fer prices n = (* 1. Création de la table *) let t = Array.make (n+1) 0 in (* 2. Cas de base *) t.(0) <- 0; (* 3. On remplit la table dans l'ordre montant *) for k = 1 to n do t.(k) <- max_list (List.init (fun l -> prices.(l+1) + t.(k-l-1))) done; (* 4 Valeur souhaitée *) t.(n);; ``` #quote(block: true)[ desc : $p_k -> "aux" k$\ asc : $p_k -> t.(k)$ ] Squelette Générique ```ocaml let version_asc arg = (* 1. Création de la table *) let t = Array.make_matrix .... in (* 2. Cas de base *) t.(cas_de_base) <- val_init; (* 3. On remplit dans le bon ordre ascendant *) for i = 1 to .... do for j = 1 to .... do t.(i).(j) <- ....t.(k).(l).... done done (* 4. Valeur souhaitée *) t.(arg);; ``` Difficultés : - Taille de la table : souvent (n+1) (p+1) à n et p sont les variables du problèmes - Les cas de base : ne pas en oublier - Trouver le bon ordre : $t . lr((k)) . lr((l))$ doit avoir déjà été remplit lorsqu'il est utilisé. Version ascendante ```ocaml let knapsack obj poids_max = let n = Array.length obj in (* Création de la table *) let t = Hashtbl.create () in (* Cas de base *) for i = 0 to n do for p = 0 to poids_max do Hashtbl.add t (i,p) 0 done; done; let rec aux i p = match Hashtbl.find_opt t (i,p) with | None -> let res = max (Hashtbl.find t (i-1,p)) (snd obj.(i-1) + (Hashtbl.find (i-1) (p-(fst obj.(i-1))))); in Hashtbl.add t res; res; | Some v -> v ``` == V - Optimisations Mémoires <v---optimisations-mémoires> ==== 1. Fibonacci <fibonacci> $u_0 = u_1 = 1$ $u_(n + 2) = u_(n + 1) - u_n$ Version descendante ```python def fibo(n): T = {} T[0] = 1 T[1] = 1 def aux(k): if k not in T: T[k] = aux(k-1) - aux(k-2) return T[k] return aux(n) ``` Ici on remplit le dictionnaire à la demande, on ne remplit que ce dont on a besoin. Version ascendante ```python def fibo(n): T = [0]*(n+1) T[0] = 1 T[1] = 1 for i in range(2, n+1): T[i] = T[i-1] - T[i-2] return T[n] ``` On remarque qu'on aurait pu utiliser 2 variables au lieu de toute une liste. ```python def fibo(n): u_prec = 1 u = 1 for i in range(2, n+1): tmp = u_prec u_prec = u u = u + tmp return u ``` On a ainsi l'invariant suivant : $u = f i b o lr((i - 1))$ et $u p r e c = f i b o lr((i - 2))$. On a ainsi un coût d'espace constant bien que l'on reste on coût temporel linéaire. $arrow.r.double$ La version ascendante peut permettre de gagner en espace. ==== 2. Sac à dos <sac-à-dos> #strong[Version impératif TODO] Sur un exemple : ${ lr((1 , 5)) , lr((3 , 5)) , lr((5 , 8)) , lr((8 , 12)) }$ avec $p_(m a x) = 10$ Table des $v_(i , p)$ #figure( align( center, )[#table( columns: 6, align: (col, row) => (center, center, center, center, center, center,).at(col), inset: 6pt, [p 0], [1], [2], [3], [4], [], [#strong[0]], [X], [X], [X], [X], [X], [#strong[1]], [0], [], [], [], [], [#strong[2]], [0], [5], [5], [5], [], [#strong[3]], [X], [], [], [], [], [#strong[4]], [0], [], [], [], [], [#strong[5]], [0], [5], [10], [], [], [#strong[6]], [0], [], [], [], [], [#strong[7]], [0], [5], [], [], [], [#strong[8]], [1], [], [], [], [], [#strong[9]], [0], [], [], [], [], [#strong[10]], [0], [5], [10], [18], [18], )], ) Version ascendante : On remplit $lr((p o i d s_(m a x) + 1)) times lr((n + 1))$ cases Version descendante : Potentiellement beaucoup moins $arrow.r.double$ gain en temps (difficile à mesurer dans le pire des cas) $arrow.r.double$ gain en espace ?? $->$ Cela dépend de l'implémentation des dictionnaires, ce n'est pas si évident. == VI - Reconstruction de la Solution <vi---reconstruction-de-la-solution> Les programmes écrits pour le problème du sac à dos donnent la valeur optimale du sac à dos mais pas comment l'atteindre. L'arbre de décision se lit dans la table obtenue à la fin de l'algorithme. Pour reconstruire la solution on conserve la table et on la parcourt "à l'envers". #quote( block: true, )[ Ici le "18" de la case $t . lr((10)) . lr((4))$ a été obtenu comme $m a x lr((t . lr((10)) . lr((3)) , t . lr((2)) . lr((3)) + 12))$. Comme c'est $t . lr((10)) . lr((3))$ qui donne sa valeur au max, l'objet 4 n'est pas choisi dans la solution. Puis on continue. ] == VII - TD <vii---td> ==== 1. Optimisation mémoire <optimisation-mémoire> $ binom(n + 1, k + 1) = binom(n, k) + binom(n, k + 1) $ Version ascendante triangle de Pascal ```ocaml let pascal k n = let t = Hashtbl.create 1 in let rec aux k n = if k > n || n < 0 then 0 if k = 0 then 1 if k = 1 then n match Hashtbl.find_opt t (k,n) with | Some v -> v | None -> begin let res = (aux (n-1) (k-1)) + (aux (n-1) k) in Hashtbl.add t (k,n) res; res end; in aux k n;; ``` Version ascendante Un transforme notre parallélogramme en rectangle : $m i , j = m_(i lr((j - 1))) + m_(lr((i - 1)) , j)$ $m_(0 , j) = m_(i , 0) = 1$ ```ocaml let pascal k n = let t = Array.make_matrix (k+1) (n-k) 0 in for i = 0 to n do t.(0).(i) <- 1 ``` On peut ainsi se ramener à un problème plus classique que nous savons déjà implémenter. Amélioration de la version ascendante pour être en O\(k) On applique l'algorithme sur un tableau de taille k. ```ocaml let pascal k n = let t = Array.make (k+1) 1 in (* Cas de base déjà fait *) for i = 0 to n-1 do (* Lignes *) (* Invariant: t.(j) = j parmi i pour j dans [0,i] *) for j = min k (i-1) downto 1 do t.(j) <- t.(j) + t.(j-1) done; done; t.(k);; ``` Pour le sac à dos La même astuce permet d'obtenir un coût linéaire de mémoire. ==== 2. Trouver et Prouver des Formules de Récurrences <trouver-et-prouver-des-formules-de-récurrences> ===== 2.1 Vente de Barres de Fer <vente-de-barres-de-fer> Preuve dans la partie #strong[III] de cours. ===== 2.2 Distance d'édition : Levenshtein <distance-dédition-levenshtein> Formule de récurrence $d_(i , 0) = i$ $d_(0 , j) = j$ $d_(i , j) = d_(i - 1 , j - 1)$ si $t 1 lr([i - 1]) = t 2 lr([j - 1])$ $d_(i , j) = m i n lr((d_(i - 1 , j) + 1 , 1 + d_(i , j - 1))) = 1 + m i n lr((d_(i - 1 , j) , d_(i , j - 1)))$ sinon Le minimum fait intervenir d'un côté la suppression du caractère suivi de l'application de l'algorithme avec le reste du mot. De l'autre côté il fait intervenir l'ajout du caractère avant de continuer. Avec remplacement $d_(i , j) = 1 + m i n lr((d_(i - 1 , j) , d_(i , j - 1) , d_(i - 1 , j - 1)))$
https://github.com/EpicEricEE/typst-plugins
https://raw.githubusercontent.com/EpicEricEE/typst-plugins/master/outex/assets/example.typ
typst
#import "../src/lib.typ": outex #set text(size: 14pt) #set heading(numbering: "1.1 i") #set page( width: 10cm, height: auto, margin: 1em, background: box( width: 100%, height: 100%, radius: 4pt, fill: white, stroke: white.darken(10%), ), ) #show heading: set block(below: 1em) #show: outex #outline(title: "Table of Contents") #set page(height: 2cm) = Introduction = Background == The Problem == The Solution = Implementation == The Algorithm == The Code === The Parser === The Compiler == The Tests = Conclusion #heading(numbering: none, [References])
https://github.com/oravard/typst-dataframes
https://raw.githubusercontent.com/oravard/typst-dataframes/main/lib.typ
typst
MIT License
#import "@preview/tabut:1.0.1" as _tabut_ #import "@preview/cetz:0.2.1" as _cetz_ #let verify-consistency(df) = { let n = -1 for key in df.keys() { if n > 0 { assert(n==df.at(key).len(), message: "Columns do not have the same length") } n = df.at(key).len() } } #let row(df,i) = { let r = (:) for (key,values) in df.pairs() { r.insert(key,values.at(i)) } r } // returns the number of rows of a dataframe #let nb-rows(df) = { let df-keys = df.keys() if df-keys.len()==0 { return 0 } else { return df.at(df-keys.first()).len() } } // returns the number of columns of a dataframe #let nb-cols(df) = { df.keys().len() } #let size(df) = { (nb-rows(df), nb-cols(df)) } #let to-array(df) = { if type(df)==dictionary { let keys = df.keys() let res = () let n = df.at(keys.at(0)).len() for i in range(0,n,step: 1) { let elt = (:) for key in keys { elt.insert(key,df.at(key).at(i)) } res.push(elt) } res } else if type(df)==array { df } else { panic("Cannot convert an object of type "+repr(type(df))+" to array.") } } #let array-to-dataframe(df) = { if type(df)==dictionary { return df } else if type(df)==array { if df.len()==0 { return (:) } let new_df = (:) for key in df.at(0).keys() { new_df.insert(key, df.map(r=>r.at(key))) } new_df } else { panic("Cannot convert an object of type "+repr(type(df))+" to dictionary") } } #let transpose(df, key-name:"Col") = { let new-df = (:) new-df.insert(key-name,df.keys()) let adf = to-array(df) for (i,row) in adf.enumerate() { new-df.insert(repr(i),row.values()) } new-df } #let slice(df, row-start:0, row-end:none, row-count:-1, col-start:0, col-end:none, col-count:-1) = { let new_df = (:) let df-keys = df.keys() if col-count < 0 {col-count=nb-cols(df) - col-start} if row-count < 0 {row-count=nb-rows(df) - row-start} for key in df-keys.slice(col-start, col-end, count:col-count) { new_df.insert(key,df.at(key).slice(row-start,row-end,count:row-count)) } return new_df } #let add-cols(df, ..kw) = { for (key,values) in kw.named() { if type(values)==array { df.insert(key,values) } else { df.insert(key,(values,)) } } verify-consistency(df) df } // equivalent to add-cols #let hcat = add-cols #let dataframe(..kw) = { if kw.named().len()>0 { let df = (:) df = add-cols(df, ..kw) df } else if kw.pos().len()==1 { array-to-dataframe(kw.pos().at(0)) } } #let add-rows(df, ..kw, missing:none) = { if df == none { df = kw.named() if df.len()==0 {df = kw.pos()} for key in df.keys() { if type(df.at(key)) != array { df.insert(key,(df.at(key),)) } } } else { let df-keys = df.keys() if kw.named().len()==0 { kw=kw.pos() } else { kw = kw.named() } kw = array-to-dataframe(kw) // transform all elements of kw to an array if it is not for key in kw.keys() { if type(kw.at(key)) != array { kw.insert(key,(kw.at(key),)) } } // add missing elements to df for keys in kw which are not in df let len-df = df.at(df-keys.first()).len() for key in kw.keys() { if key not in df-keys { df-keys.push(key) df.insert(key, (missing,) * len-df) } } // add missing elements to kw for keys in df which are not in kw let len-kw = kw.at(kw.keys().first()).len() for key in df-keys { if key not in kw.keys() { kw.insert(key, (missing,) * len-kw) } df.insert(key, df.at(key) + kw.at(key)) } } verify-consistency(df) df } // equivalent to add-rows #let vcat = add-rows #let concat(df, other) = { let other-keys = other.keys() let df-keys = df.keys() if other-keys.filter(r=>r not in df-keys).len()==0 { add-rows(df, ..other) } else { assert(other-keys.filter(r=>r in df-keys).len()==0, message:"Cannot concat this two dataframes. Try add-rows and add-cols separately.") add-cols(df, ..other) } } #let j0 = datetime(year:1970,month:1,day:1, hour:0, minute:0, second:0) #let j0d = datetime(year:1970,month:1,day:1) #let datetime_to_julian_date(date) = { let f(r) = { if r.second()==none { return int((r - j0d).seconds()) } else { return int((r - j0).seconds()) } } if type(date)==array { return date.map(f) } else { return f(date) } } #let julian_date_to_datetime(julian_date) = { let f(r) = { if r.hour()==0 and r.minute()==0 and r.second()==0 { datetime(year:r.year(), month:r.month(), day:r.day()) } else { r } } if type(julian_date)==array { let res = julian_date.map(r=>j0 + duration(seconds:r)) return res.map(f) } else { return f(j0 + duration(seconds:int(julian_date)) ) } } #let tabut-cells(df, ..kw) = _tabut_.tabut-cells(to-array(df), ..kw) #let auto-type(input) = { if type(input)==type("") { let date-format = input.match(regex("(\d{4})-(\d{2})-(\d{2})[T| ](\d{2}):(\d{2}):(\d{2})")) if date-format != none { let year = int(date-format.captures.at(0)) let month = int(date-format.captures.at(1)) let day = int(date-format.captures.at(2)) let hour = int(date-format.captures.at(3)) let minute = int(date-format.captures.at(4)) let second = int(date-format.captures.at(5)) return datetime(year:year, month:month, day:day, hour:hour, minute:minute, second:second) } let date-format = input.match(regex("(\d{4})-(\d{2})-(\d{2})")) if date-format != none { let year = int(date-format.captures.at(0)) let month = int(date-format.captures.at(1)) let day = int(date-format.captures.at(2)) return datetime(year:year, month:month, day:day) } } input } #let dataframe-from-csv(input) = { let data = _tabut_.records-from-csv(input) data = data.map( r => { let new-record = (:); for (k, v) in r.pairs() { new-record.insert(k, auto-type(v)); } new-record }) return array-to-dataframe(data) } #let select(df, cols:auto, rows:auto) = { if rows != auto and df.len()>0 { df = to-array(df) df = df.filter(rows) df = array-to-dataframe(df) } let new_df = (:) if cols==auto { cols = df.keys() } else if type(cols)==function { cols = df.keys().filter(cols) } else if type(cols)==type("") { cols = (cols,) } let keys = df.keys() for key in cols { if key in keys { new_df.insert(key, df.at(key)) } } return new_df } // apply the func of a dataframe df with : // - a scalar: each element of the dataframe apply the func with the scalar // - an "other" dataframe: // - if the number of columns of other is 1, each // columns of df apply the func term by term with other. // - if the number of columns of other is equal to the number // of columns of df each column of df apply the func // term by term by each column of other. // - if df column names are the same asother column names, each // columns of df apply the func term by term by the column // of other with the same name. #let apply(df, other, func:(r1,r2)=>(r1+r2)) = { if type(other)!=array and type(other)!=dictionary { for key in df.keys() { df.insert(key, df.at(key).map(r=>func(r,other))) } } else if type(other)==array { assert(other.len()==nb-rows(df), message: "Array should have the same size than dataframe") for key in df.keys() { df.insert(key, df.at(key).zip(other).map(r=>func(r.at(0),r.at(1)))) } } else if type(other)==dictionary { let other-keys = other.keys() if other-keys.len() == 1 { other = other.at(other-keys.first()) for key in df.keys() { df.insert(key, df.at(key).zip(other).map(r=>func(r.at(0),r.at(1)))) } } else if other-keys.len() == df.keys().len() { let df-keys = df.keys() for i in range(0,other-keys.len()) { let key = df-keys.at(i) df.insert(key, df.at(key).zip(other.at(other-keys.at(i))).map(r=>func(r.at(0),r.at(1)))) } } else { panic("multiply dataframe with another needs nb-cols==1 or nb-cols==dataframe nb-cols") } } df } // returns the product of a dataframe df with : // - a scalar: each element of df is multiplied by the scalar // - an "other" dataframe: // - if the number of columns of other is 1, each // columns of df is multiplied term by term by other. // - if the number of columns of other is equal to the number // of columns of df, each column of df is // multipled term by term by each column of other. // - if df column names are the same as other column names, each // columns of df is multiplied term by term by the column // of other with the same name. #let mult(df,other) = apply(df,other,func:(r1,r2)=>r1*r2) #let add(df,other) = apply(df,other,func:(r1,r2)=>r1+r2) #let div(df,other) = apply(df,other,func:(r1,r2)=>r1 / r2) #let substract(df,other) = apply(df,other,func:(r1,r2)=>r1 - r2) // unary operator functions: // the unary operator is applied to all elements of dataframe #let apply-unary(df, func:r=>calc.abs(r)) = { for (key,values) in df.pairs() { df.insert(key, values.map(func)) } df } #let abs(df) = {apply-unary(df)} #let round(df, digits:0) = {apply-unary(df,func:r=>{ if type(r)==float { calc.round(r, digits: digits) } else { r } })} #let ceil(df) = {apply-unary(df,func:r=>calc.ceil(r))} #let floor(df) = {apply-unary(df,func:r=>calc.floor(r))} #let exp(df) = {apply-unary(df,func:r=>calc.exp(r))} #let log(df) = {apply-unary(df,func:r=>calc.log(r))} #let cos(df) = {apply-unary(df,func:r=>calc.cos(r))} #let sin(df) = {apply-unary(df,func:r=>calc.sin(r))} // vector to vector functions // given a vector, returns a vector of the same size. // missing elements can appear. #let vec-func(v, init:0, func:(r1,r2)=>r1+r2) = { let s = init let new-v = () for i in range(0,v.len()) { s = func(s, v.at(i)) new-v.push(s) } new-v } #let vec-cumsum(v) = vec-func(v) #let vec-cumprod(v) = vec-func(v, func:(r1,r2)=>r1*r2, init:1) #let cum-func(df, axis:1, func:vec-cumsum) = { if axis==1 { for (key,values) in df.pairs() { df.insert(key, func(values)) } } else { let temp-df = cum-func(slice(transpose(df), col-start:1), axis:1, func:func) temp-df = slice(transpose(temp-df), col-start:1) for (key,temp-key) in df.keys().zip(temp-df.keys()) { df.insert(key, temp-df.at(temp-key)) } } df } #let cumsum(df,axis:1) = cum-func(df,axis:axis) #let cumprod(df,axis:1) = cum-func(df, axis:axis, func:vec-cumprod) #let sorted(df, x, rev:false) = { let adf = to-array(df) adf = adf.sorted(key:r=>r.at(x)) if rev { adf = adf.rev() } return array-to-dataframe(adf) } // vector to scalar functions: functions which takes a vector as input // and returns a scalar #let vec-sum(v) = {v.sum()} #let vec-product(v) = {v.product()} #let vec-min(v) = {v.fold(1e99, (r1,r2)=>calc.min(r1,r2))} #let vec-max(v) = {v.fold(-1e99, (r1,r2)=>calc.max(r1,r2))} #let vec-mean(v) = {v.sum()/v.len()} // folding function: folds all items into a single value along the given // axis using an accumulator function #let fold(df, axis:1, func:vec-sum) = { if axis==1 { let new-df = (:) for key in df.keys() { new-df.insert(key, func(df.at(key))) } new-df } else { let adf = to-array(df) adf.map(r=>func(r.values())) } } #let sum(df, axis:1) = {fold(df,axis:axis)} #let product(df, axis:1) = {fold(df,axis:axis,func:vec-product)} #let min(df,axis:1) = {fold(df,axis:axis,func:vec-min)} #let max(df,axis:1) = {fold(df,axis:axis,func:vec-max)} #let mean(df,axis:1) = {fold(df,axis:axis, func:vec-mean)} #let diff(df, axis:1) = { let new-row = mult(dataframe(..row(df,0)),0) let df1 = concat(new-row,df) let df2 = concat(df, new-row) slice(substract(df2,df1), row-end:-1) } #let tbl(df, ..kw) = { let adf = to-array(df) let keys = df.keys() let cols = () set text(weight: "bold") for key in keys { if type(df.at(key).at(0))==datetime { cols.push((header:align(center, [#set text(weight: "bold") #key.replace("_"," ")]), func:r=>align(center,r.at(key).display()) )) } else { cols.push((header:align(center, [#set text(weight: "bold") #key.replace("_"," ")]), func:r=>align(center,[#r.at(key)]) )) } } let tab = _tabut_.tabut( adf, cols, ..kw ) return tab } #let curve(data:none, label:"", mark:none, mark-size:0.15, color:blue, thickness:0.5pt, dash:none, ..kw) = { _cetz_.plot.add( data, label:{set text(size:9pt);label}, mark:mark, mark-size:mark-size, mark-style:(fill:color, stroke:black+thickness), style:(stroke:(dash:dash,paint:color,thickness:thickness), fill:color), ..kw ) } #let plot(df, x:none, y:none, x-label:none, y-label:none, y2-label:none, label-text-size:1em, tick-text-size:0.8em, x-tick-step:auto, y-tick-step:auto, y2-tick-step:auto, x-tick-rotate:0deg, x-tick-anchor:"north", y-tick-rotate:0deg, y-tick-anchor:"east", y2-tick-rotate:0deg, y2-tick-anchor:"west", x-minor-tick-step:auto, y-minor-tick-step:auto, y2-minor-tick-step:auto, x-min:none, y-min:none, x-max:none, y-max:none, x-axis-padding:2%, y-axis-padding:2%, axis-style:"scientific", grid:false, width:80%, aspect-ratio:50%, style:(:), legend-default-position:"legend.inner-south-east", legend-padding:0.15, legend-spacing:0.3, legend-item-spacing:0.15, legend-item-preview-height:0.2, legend-item-preview-width:0.6, ..kw) = { if y==none { y=df.keys() if x!= none { y = y.filter(r=>r!=x) } } let x-datetime-format = false let x-string-format = false let orig-x = none if x==none or type(df.at(x).first())==type("") { if x!=none and type(df.at(x).first())==type("") { x-string-format = true orig-x = df.at(x) x-tick-step=1.0 } x = range(0,df.at(df.keys().at(0)).len()) } else { assert(x in df.keys(), message: "x should be in dataframe column names") if x-label == none { x-label = x.replace("_"," ") } x = df.at(x) if type(x.at(0))==datetime { x = datetime_to_julian_date(x) x-datetime-format = true } } let curves = () let yM = -1e99 let ym = 1e99 let xM = -1e99 let xm = 1e99 let i = 0 for key in y { let y_ = df.at(key) if type(y_.at(0))==datetime { y_ = datetime_to_julian_date(y_) } let data = x.zip(y_) let curve-style = ( color : _cetz_.palette.rainbow(i).fill, thickness : 0.5pt, mark : none, mark-size : 0.15, dash : none, label:key.replace("_"," "), axes:("x","y") ) curve-style = curve-style + style.at(key,default:(:)) let c = curve(data:data, ..curve-style).at(0) if curve-style.axes.at(1)=="y" { let cy_data = c.data.map(r=>r.at(1)) yM=calc.max(yM,..cy_data) ym=calc.min(ym,..cy_data) } if curve-style.axes.at(0)=="x" { let cx_data = c.data.map(r=>r.at(0)) xM=calc.max(xM,..cx_data) xm=calc.min(xm,..cx_data) } curves.push(c) i = i+1 } if x-min==none { x-min = xm - (xM - xm) * x-axis-padding/100% } if y-min==none { y-min = ym - (yM - ym) * y-axis-padding/100% } if x-max==none { x-max = xM + (xM - xm) * x-axis-padding/100% } if y-max==none { y-max = yM + (yM - ym) * y-axis-padding/100% } let x-format(r) = { if x-datetime-format { text(size:tick-text-size)[#julian_date_to_datetime(r).display()] } else if x-string-format { let i=int(r) if i>=0 and i < orig-x.len() { text(size:tick-text-size)[#orig-x.at(int(r))] } else {[]} } else { text(size:tick-text-size)[#r] } } let y-format(r) = { text(size:tick-text-size)[#r] } let y2-format(r) = { text(size:tick-text-size)[#r] } if type(x-tick-step)==duration { x-tick-step = x-tick-step.seconds() } if type(x-min)==datetime { x-min = datetime_to_julian_date(x-min) } if type(x-max)==datetime { x-max = datetime_to_julian_date(x-max) } let pl = _cetz_.plot.plot( size: (10,10*aspect-ratio/100%), y-tick-step: y-tick-step, y2-tick-step: y2-tick-step, x-tick-step:x-tick-step, x-minor-tick-step:x-minor-tick-step, y-minor-tick-step:y-minor-tick-step, y2-minor-tick-step:y2-minor-tick-step, x-label:{set text(size:label-text-size);x-label}, y-label:{set text(size:label-text-size);y-label}, y2-label:{set text(size:label-text-size);y2-label}, y-max:y-max, y-min:y-min, x-min:x-min, x-max: x-max, x-grid:grid, y-grid:grid, x-format:x-format, y-format:y-format, y2-format:y2-format, axis-style:axis-style, legend:auto, legend-style:(default-position:legend-default-position, padding:legend-padding, item:(spacing:legend-item-spacing, preview:(height:legend-item-preview-height, width:legend-item-preview-width)), orientation:ttb, spacing:legend-spacing ), curves, ..kw ) // set text(size:tick-text-size) if type(width)==ratio { layout(size=>{_cetz_.canvas( { _cetz_.draw.set-style(axes: ( bottom: (tick:(label:(angle:x-tick-rotate, anchor:x-tick-anchor))), left: (tick:(label:(angle:y-tick-rotate, anchor:y-tick-anchor))), right: (tick:(label:(angle:y2-tick-rotate, anchor:y2-tick-anchor))) )) pl }, length:size.width/10*width, background:none)}) } else { _cetz_.canvas({ _cetz_.draw.set-style(axes: ( bottom: (tick:(label:(angle:x-tick-rotate, anchor:x-tick-anchor))), left: (tick:(label:(angle:y-tick-rotate, anchor:y-tick-anchor))), right: (tick:(label:(angle:y2-tick-rotate, anchor:y2-tick-anchor))) )) pl }, length:width/10, background:none) } }
https://github.com/EtoDemerzel0427/resume.typst
https://raw.githubusercontent.com/EtoDemerzel0427/resume.typst/main/main.typ
typst
#import "fontawesome.typ": * #import "simplecv.typ": template, education_entry, work_entry, skill_entry // Change the theme color of the cv. #let color = black // Change to your name. #let name = "<NAME>" // Change the shown contact data. You can also change the order of the elements so that they will show up in a different order. Currently, only these five elements are available with icons, but you can add new ones by editing the template. #let contact_data = ( ( "service":fa[#linkedin], "display": "johndoe", "link": "https://www.linkedin.com/in/johndoe/" ), ( "service": fa[#envelope], "display": "<EMAIL>", "link": "mailto://<EMAIL>" ), ( "service": fa[#phone], "display": "+1 xxx-xxx-xxxx", "link": "tel:+1 xxx xxx xxxx" ), ( "service": fa[#github], "display": "johndoe-git", "link": "https://github.com/johndoe-git" ), ( "service": fa[#globe], "display": "johndoe.club", "link": "https://johndoe.club" ), ) #show: doc => template(name, contact_data, color, doc) // Starting from here, you can add as much content as you want. This represents the main content of the cv. = Education #education_entry("Computer Science", "Stanford University", degree_title: "M.S.", start_date: "Jan 2022", end_date: "May 2024 (Expected)", description: "GPA: 4.0/4,0", location: "Stanford, California", details: ( [Teaching Assistant of CS149: Parallel Computing (Fall 2022)], [Teaching Assistant of CS224n: Natural Language Processing with Deep Learning (Spring 2023)], )) #education_entry("Computer Science", "Tsinghua University", degree_title: "B.Eng.", start_date: "Sep 2016", end_date: "Jun 2020", description: "rank: 25/315", location: "Beijing, China" ) = Experience #work_entry("Software Development Intern", "Google", start_date: "Aug 2023", end_date: "Nov 2023", location: "Bay Area, California", tasks: ( lorem(18), lorem(25) ) ) #work_entry("Haskell Development Intern", "Jane Street Capital", start_date: "Jun 2023", end_date: "Aug 2023", location: "New York City, New York", tasks: ( lorem(32), lorem(15) ) ) #work_entry("Research Intern", "ByteDance", start_date: "Oct 2019", end_date: "Nov 2019", tasks: ( lorem(18), [some random text to show how you can input text], "You can also use quotes." ), location: "Beijing, China") = Projects *Project-A: Some descriptive text*. - #lorem(18) - #lorem(17) - #lorem(19) *Typst: A new markup-based typesetting system*. #link("https://github.com/typst/typst")[#fa[#github]] - #lorem(22) - #lorem(25) *Project-C: #lorem(10)* - #lorem(40) = Skills // Ratings won't be displayed in this template. - *Languages*: C/C++, Python, Golang, Java, Rust, CUDA, JavaScript/TypeScript, Bash, SQL, MATLAB - *Technologies/Frameworks*: Flask, Docker, Git, WebGL, ReactJS, Pytorch, TensorFlow, Horovod, MPI, MySQL, gRPC, Typst, Apache Beam, Slurm, VTune = Publications - (C-1) #underline[<NAME>], <NAME>, <NAME>, and <NAME>, "Deep Residual Learning for Image Recognition," #emph[CoRR, Volume abs/1512.03385], 2015. - (J-1) <NAME>, <NAME>, <NAME>, and #underline[D. Miller], "Efficient Natural Language Processing with Transformer Models," #emph[Journal of Artificial Intelligence Research (JAIR), Volume 58, Issue 3, pp. 627-645], 2023.
https://github.com/olligobber/Matrixst
https://raw.githubusercontent.com/olligobber/Matrixst/master/main.typ
typst
#set page(width: auto, height:auto) #import "matrix.typ": * //demonstration of transpose = Matrix Transpose #let a = ( (1,2,3), (4,5,6) ) $ #render(a)^top = #render(transpose(a)) $ #pagebreak() // demonstration of minor = Matrix Minors #let a = ( (1,2,3), (4,5,6), (7,8,9) ) If $ a = #render(a) $ then the minor at $(3,1)$ is $ #render(minor(a,3,1)), $ the minor at $(2,2)$ is $ #render(minor(a,2,2)), $ and the minor at $(1,3)$ is $ #render(minor(a,1,3)). $ #pagebreak() // demonstration of determinant = Matrix Determinant #let a = ( (1,2,3), (0,2,-1), (-1,3,-1) ) $ "det"#render(a) = #determinant(a) $ #pagebreak() // demonstartion of inverses = Matrix Inverse #let a = ( (1,2,0), (0,2,3), (1,3,1) ) #let a-inverse = invert(a) #show_power(a,-1) #show_multiply(a,a-inverse) #show_multiply(a-inverse,a) #pagebreak() = This Matrix Has Interesting Powers // demonstration showing powers of a when a^3 is the identity #let a = ( (1,0,0), (0,0,1), (0,-1,-1), ) #{ for i in range(-3,5) { show_power(a,i) } } #pagebreak() = Matrices Act On Column Vectors // demonstration showing a e_i is the ith column of a #let b = ( (1,2,3), (4,5,6), (7,8,9), ) #{ for i in range(1,4) { show_multiply(b, column_basis(3,i)) } } #pagebreak() = Matrices Act On Row Vectors // demonstration showing e_i^T a is the ith row of a #{ for i in range(1,4) { show_multiply(row_basis(3,i), b) } } #pagebreak() = Matrices Don't Commute // demonstration of two matrices that don't commute #let c = ( (1,1), (0,0), ) #let d = ( (1,0), (1,0), ) #show_multiply(c,d) #show_multiply(d,c) #pagebreak() = Invertible Matrices Don't Commute // demonstration showing matrix multiplication isn't commutative even when the matrices are invertible #let a = ( (1,1), (1,0) ) #let b = ( (0,1), (1,1) ) #show_multiply(a,invert(a)) #show_multiply(b,invert(b)) #show_multiply(a,b) #show_multiply(b,a) #pagebreak() // demonstration showing multiplying more than two matrices of different dimensions = #[Multiplying Multiple Matrices \ with Many Measurements] #let e = ( (3,0), (-1,5) ) #let f = ( (4,-2,1), (0,2,3) ) #let g = ( (1,2), (3,4), (5,6) ) #show_multiply(e,f,g) #pagebreak() = Building a Matrix out of Column Vectors #let v1 = column_vector(1,2,3,4) #let v2 = column_vector(1,-1,2,1) #let v3 = column_vector(0,0,1,0) #let v4 = column_vector(-1,0,1,-1) #let vs = (v1,v2,v3,v4) #v(1em) #align(center, range(4) .map(i => $bold(v)_#{i+1} = #render(vs.at(i))$) .join([,] + h(1em)) ) #let bars = ($|$,) * 4 #let names = range(1,5).map(x => $bold(v)_#x$) $ #math.mat(..(bars,names,bars)) = #render(horizontal_cat(..vs)) $ #pagebreak() = Building a Matrix out of Row Vectors #let v1 = row_vector(1,5,2,-1) #let v2 = row_vector(1,-1,0,0.5) #let v3 = row_vector(0,2,1,1) #let v4 = row_vector(6,0,1,-1) #let vs = (v1,v2,v3,v4) #{ for i in range(4) { $ bold(v)_#{i+1} = #render(vs.at(i)) $ } } #let namerows = range(1,5).map(x => ($-$,$bold(v)_#x$,$-$)) $ #math.mat(..namerows) = #render(vertical_cat(..vs)) $
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-算法/贪心算法/找字符串拼接的最大值.typ
typst
#import "../../../../lib.typ":* === #Title( title: [找字符串拼接的最大值], reflink: "https://leetcode.cn/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/description/", level: 2, )<找字符串拼接的最大值> #note( title: [ 破解闯关密码 ], description: [ 闯关游戏需要破解一组密码,闯关组给出的有关密码的线索是: - 一个拥有密码所有元素的非负整数数组 password - 密码是 password 中所有元素拼接后得到的最小的一个数 请编写一个程序返回这个密码。 ], examples: ([ 输入: password = [15, 8, 7] 输出: "1578" ],[ 输入: password = [0, 3, 30, 34, 5, 9] 输出: "03033459" ] ), tips: [ 0 < password.length <= 100 输出结果可能非常大,所以你需要返回一个字符串而不是整数 拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0 ], solutions: ( ( name:[快速排序], text:[ 此题求拼接起来的最小数字,本质上是一个排序问题。设数组 password 中任意两数字的字符串为 x 和 y ,则规定 排序判断规则 为: - 若拼接字符串 $x+y > y+x$ ,则 x “大于” y ; - 反之,若 $x+y < y+x$ ,则 x “小于” y ; x “小于” y 代表:排序完成后,数组中 x 应在 y 左边;“大于” 则反之。 根据以上规则,套用任何排序方法对 password 执行排序即可。 #align(center)[ #image("img/solution1.png") ] 1. 初始化: 字符串列表 strs ,保存各数字的字符串格式; 2. 列表排序: 应用以上 “排序判断规则” ,对 strs 执行排序; 3. 返回值: 拼接 strs 中的所有字符串,并返回。 需修改快速排序函数中的排序判断规则。字符串大小(字典序)对比的实现方法: - 在 Python 和 C++ 中可直接用 `<` , `>`; - 在 Java 中使用函数 A.compareTo(B); ],code:[ ```cpp class Solution { public: string crackPassword(vector<int>& password) { vector<string> strs; for(int i = 0; i < password.size(); i++) strs.push_back(to_string(password[i])); quickSort(strs, 0, strs.size() - 1); string res; for(string s : strs) res.append(s); return res; } private: void quickSort(vector<string>& strs, int l, int r) { if(l >= r) return; int i = l, j = r; while(i < j) { while(strs[j] + strs[l] >= strs[l] + strs[j] && i < j) j--; while(strs[i] + strs[l] <= strs[l] + strs[i] && i < j) i++; swap(strs[i], strs[j]); } swap(strs[i], strs[l]); quickSort(strs, l, i - 1); quickSort(strs, i + 1, r); } }; ``` ]),( name:[内置函数], text:[ 需定义排序规则: - Python 定义在函数 `sort_rule(x, y)` 中; - Java 定义为 `(x, y) -> (x + y).compareTo(y + x)` ; - C++ 定义为`(string& x, string& y){ return x + y < y + x; }` ; ], code:[ ```cpp class Solution { public: string crackPassword(vector<int>& password) { vector<string> strs; string res; for(int i = 0; i < password.size(); i++) strs.push_back(to_string(password[i])); sort(strs.begin(), strs.end(), [](string& x, string& y){ return x + y < y + x; }); for(int i = 0; i < strs.size(); i++) res.append(strs[i]); return res; } }; ``` ] ) ), gain:none, )
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/grid-4.typ
typst
Apache License 2.0
// Test relative sizing inside grids. --- // Test that auto and relative columns use the correct base. #grid( columns: (auto, 60%), rows: (auto, auto), rect(width: 50%, height: 0.5cm, fill: conifer), rect(width: 100%, height: 0.5cm, fill: eastern), rect(width: 50%, height: 0.5cm, fill: forest), ) --- // Test that fr columns use the correct base. #grid( columns: (1fr,) * 4, rows: (1cm,), rect(width: 50%, fill: conifer), rect(width: 50%, fill: forest), rect(width: 50%, fill: conifer), rect(width: 50%, fill: forest), ) --- // Test that all three kinds of rows use the correct bases. #set page(height: 4cm, margin: 0cm) #grid( rows: (1cm, 1fr, 1fr, auto), rect(height: 50%, width: 100%, fill: conifer), rect(height: 50%, width: 100%, fill: forest), rect(height: 50%, width: 100%, fill: conifer), rect(height: 25%, width: 100%, fill: forest), )
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/036%20-%20Guilds%20of%20Ravnica/004_Death's%20Precious%20Moments.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Death's Precious Moments", set_name: "Guilds of Ravnica", story_date: datetime(day: 07, month: 11, year: 2018), author: "<NAME>", doc ) I thrust my staff into spongy soil, bracing myself as I examine the delicate upturned caps of the bird's nest fungus—the most coveted mushroom among Golgari shamans this season. Only three rot farms have managed to cultivate them, and ours was the first. Even the most lackluster specimens fetch up to a zino each. This one boasts an impressive golden-bronze hue and holds a half-dozen turquoise spheres inside that resemble eggs, but it is not destined to adorn the elaborate gowns worn in the Undercity. I'm claiming this fungus for my own collection. I remove a vial from my harvester's satchel and swirl the moss-green elixir around until it glows in the moonlight. I turn it over and let a single drop fall from the dispenser onto the mushroom cap. It sits there for a moment, like a perfect dew drop, then a web of white tendrils grows out, encasing the fungus in a magical cocoon that will preserve it for next season's plantings. I test the casing's hardness with a quick tap of my pincers, then add it to a carefully marked compartment in my satchel. Insect song echoes off the crumbling canal walls that border our farmstead, opening up into the night sky high above. A symphony of crickets, cicadas, and katydids sing in chorus with the deep throaty bellows of a deadbridge goliath in the distance. Even a few of my siblings join in. I hear the melodic trill of Razi's wings rising above them all. She's the best singer in our family. Mother's favorite from the day we hatched, though she would never admit this out loud. Suddenly, the music on the wind changes, gone from the warbling calls for late-night romance on the fringes of Golgari territory to the hard, fast chirps of news from the Undercity—a new lich has been named. I look up over the vast expanse of our farmstead, and all my siblings have stopped their work as well, straining to hear what we all hope in our hearts—that the new lich is kraul. Like us. But no, it's another elf. My siblings go back to work, but I can't tear myself away from the rest of the message: the lich is seeking an apprentice with a proficiency in mushroom identification and a keen interest in necromancy. "Why do you want to work for an elf?" Razi says later that night after the fields have all been tended and we've returned to Mother's safe embrace. "They wear bits and pieces of us in their hair, paint eyes on their faces so they look like insects, and yet when it comes time to lead~who do they choose again and again?" "What about Mazirek?" #figure(image("004_Death's Precious Moments/01.jpg", width: 100%), caption: [Mazirek, Kraul Death Priest | Art by: <NAME>], supplement: none, numbering: none) "What about him? He's one kraul priest out of dozens of gorgons and hundreds of Devkarin elves." I wring my wings together, producing a sour note of displeasure. I know Razi doesn't mean that about Mazirek. She's just upset about the thought of me leaving our farmstead. I'd be mad, too, if she'd told me she was going off to sing for Vraska's court. "You're the best at singing," I say. "I can barely hold a tune. Ellin is the best at flying," I flex my wings, one of them malformed. "I can't even get airborne. I know a lot about mushrooms, but that's only because Kuurik is a great teacher. Necromancy could be that special thing that I do with my life. A profession that would make Mother proud of me." "She's proud of you. She's proud of all of us. You can see it in her eyes." I look up into the deep, dark sockets where our mother's eyes had once been, but I don't see the pride, only the emptiness. We keep her iridescent exoskeleton polished to a high shine, a beacon visible from one side of our farmstead to the other. She is our family anchor. Our everything. As soon as we'd erupted from our egg sacs, we'd fed upon her internal organs—meat sweet and nourishing, making our little larval bodies grow. Then we'd punctured through her carapace and made our cocoons upon her underside, and for weeks, she'd selflessly deterred predators with her pincers. Finally, we emerged and gorged upon what was left of her, all hundred and seven of us, until her exoskeleton was picked clean and we were strong enough to fend for ourselves. Now her giant carapace is our shelter during the daylight hours, just enough nooks and hollowed-out crannies for each of us to find a place to call our own. Mother sacrificed everything for us. How could I not want to make her proud? "Just think it over, Bozak. Please? We'll all talk about it tomorrow evening." Riza yawns, stretched out in the sloping curve of one of Mother's mandibles. "Till death, dearest brother." "Till death," I say, bidding her not only a good sleep, but a fond farewell. As soon as the noon sun shines upon the murky depths of our canal, I pack my maps, my journals, my vials, and my harvester's satchel and sneak away while my siblings lie dreaming. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The majesty of the Undercity is overwhelming, with vast stone tunnels shrouded in mist and giant circular entryways, like open maws begging to swallow us whole. My fellow competitors have come wearing their finest robes ribbed with mushroom gills in oranges and teals and bejeweled in shiny pieces of carapace that had once belonged to my brethren. I clench my staff close, feeling inadequately dressed in a bronzed head plate, a modest decorative chest plate, and nothing more. The lich appraises each of us, a deathly pall spread across his skin. His eyes have gone milky, including the moodmark enchantments on his forehead. His gown is a work of art, flowing black webbing with thirty-one different species of fungus worked into a mosaic pattern that compliments his slender, nearly skeletal frame. There are twenty-six of us brave (or foolish) enough to attempt to identify and retrieve four of the most dangerous mushrooms in all of Ravnica. I stand tall, keep my antenna erect, all my knees locked~ready to be the first one back with all four specimens. I packed extra elixirs to seal them in, since exposure to some of the spores can lead to paralysis, asphyxiation, death, or worse. "Only one of you will be deemed skillful enough to serve as my apprentice," the lich says. "You must be thorough, cunning, and quick. If you should perish, take comfort that your body will give life to generations of decomposers whose spawn will rot the bodies of the Undercity for millennia to come." Then he drops a kerchief woven from the finest spider's silk to signal the start of the competition. This is my first time away from the farmstead, and I'm unfamiliar with the layout of the Undercity, but the lich has graciously provided us with a map. Most of the other competitors hustle off, but a moment spent surveying the lay of the land will save two moments lost in the swamps. As I plot my course, an elf shoulder checks me as he passes, causing the brittle parchment to split in two. "Watch where you're going!" I scream out and strum a kraul cuss on my wings. He glances back at me, barely able to see over the bulk of the mushroom cap shoulder pads adorning his gaudy blue robes. His mouth is obscured from view, but from the smirk his moodmarks are projecting, I'm sure he bumped me on purpose. Never mind. Locating the zombie fungus is easy. It's deadly, yes, but not exactly uncommon. They prefer to grow under the shade of mangroves, and the map says there's one not far from here. I sprint through brackish waters, ducking under vines, trailing toward the rear of the pack. We exit through a concrete portcullis and into an open marsh. The mangrove~it's haunting to say the least. Thick knobby trunks are upheld by stilted roots, twisted canopies that look more like green locks than leaves. Most of the competitors are already scouring the tree's roots—the perfect spot for zombie fungus to grow. I run to join them before the specimens are picked clean, then notice something is off. The moss on the trees~it's on the wrong side. And those roots, I think I saw one of them twitch. "Woodwraiths!" I scream, drawing the attention of the gorgon running past me. We both stop, turn, and start running in the opposite direction, warning off the two elves and another kraul coming up behind us. We hear the creaking of old branches and the suck of roots pulling up from waterlogged soil. Then screaming. Lots and lots of screaming. Then quiet. The five of us don't stop running until we're on the other side of the marsh and through several tunnels too narrow to accommodate a woodwraith's girth. Finally, we settle, winded and terrified. "Well, we definitely can't trust the map," the gorgon says. Her hair is riled up, but I risk a glance in her direction, just to see who I'm dealing with. She's young, skin a deep olive green. Eyes wise like someone three times her age. "I can't believe the lich would set us up like that," I say. "Devkarin elves are jerks like that," the other kraul says. The two elves with us balk, probably unused to finding themselves outnumbered. They sulk off with a few cusses and angry moodmarks. "Don't worry about them," the kraul says. "Zegodonis was the only elf in this competition who was worth anything, and his bones are picking the flesh out of a woodwraith's teeth right about now. Complete ass. Even for an elf." "Zegodonis?" I ask. "With the gaudy blue robe and huge shoulder pads? About twenty insect legs in his hair?" The elf who'd torn my map. "That's the one. From death, life," he says, spitting into the marsh. "From death, life," I repeat the Golgari mantra, trying to soothe my nerves. But I can't stop thinking about all those people~dead. It happened so fast. If I hadn't taken that moment to look the map over, my bones would be at the bottom of that bog, too. "Hey, what's your name?" the kraul says to me. "Bozak," I say, with a strum of my wings. #figure(image("004_Death's Precious Moments/02.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "I'm Limin." He grins. He's got the most amazing gossamer wings, but they barely twitch when he speaks. Without them, his words sound so flat. So elven. He must sense my unease and offers up an explanation. "I grew up in the heart of the Undercity. There, you have to fit in to survive." "I get it," I say, even though I don't. If I had wings like his, I'd be strumming them all day long. "You?" I ask the gorgon. "Kata," she says, unimpressed by either of us. She looks away from me like I'm the one who's got the face that'll turn flesh to stone. "Oh, look. Zombie fungus." But she's right, not twenty feet away, a small patch of the fungus grows up against a sewer grate. We each carefully collect a specimen and douse it with a casing elixir. Once the cocoon has hardened, I douse my specimen again, just to be safe. "You saved our lives," Kata says to me when she's done. "I'm grateful, but don't get any ideas that we're working together. Only one of us is going to win this competition." She runs off, leaving Limin and me alone. "She has a point. But that doesn't mean we can't make a temporary truce. If we share information and resources, we can all but guarantee a kraul will win. What do you say?" He sticks his hand out, the way elves do to seal a deal. I hold back my grimace as I press my hand into his. Where I'm from, a deal between kraul is sealed with the touching of mandibles. Maybe this makes him feel like he's fitting in, but it leaves me feeling like a stranger in my own body. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Together, we harvest young death caps, barely emerged from their veils, and pull firmly ahead of Kata and one of the elves. The other is not too far ahead. He looks back, tries to run faster, but he trips over a raised tree root and falls flat on his satchel. "Help, I'm hurt," he cries out. "Limin~come on, we're friends, right? We practically grew up together." "He punctured his zombie fungus specimen," I whisper to Limin. The spores are puffing up into the elf's face, but he doesn't notice. "We need to double back." "Should we tell him?" Limin asks. "Maybe he can—" "It's too late." He's stopped moaning already. He stands up, and we see the stick impaled through his canvas bag, leading right into his chest cavity. He looks up, admiring the trees around him as blood drips down his robes. It's like the pain doesn't even bother him. "Which of these trees looks the highest to you?" he says, speech slurred. There are several varieties of the zombie fungus, but this one is the most aggressive and the quickest acting. It's already rewiring his brain, programming him to do the mushroom's bidding. His body is now an involuntary host to the next generation. The elf chooses a tree and scales it like his body had been built for this sole purpose. He goes right to the very tip, then clamps down. A few hours from now, mushrooms will erupt from his eyes, nostrils, ears~feeding slowly upon his body tissue until they're ready to rain down spores upon the marshlands. I don't feel sorry for him. It's the way of life~not much different than how my siblings and I came to our mother. She was the one who'd nurtured us, who'd given of herself, but she wasn't our biological mother. We never knew her. She'd deposited her eggs into the giant beetle and spared not a single thought toward us again. I know that Mother's mind had been compromised, whispers of the invaders there prompting her to defend us. I know her screams were not really lullabies, but she loves us. And we love her. No family is perfect. I'm so caught up in the memories of home that Limin has to drag me away. We work together to get the wolf's fang fungus growing from a rotting stump perched up high on a treacherous cliff face in Selesnyan territory. Limin's wings glisten as he flies up effortlessly to retrieve them while I pitch stones at the adolescent wurm trying to make a snack of him. Finally, we come to the last specimen on the list. We're back in the belly of the Undercity, my legs covered knee-high in brilliant green moss. I press deeper through the marsh, slowing down now as the insect song goes quiet, a warning from my kin that something dangerous is afoot. There's a mossdog den ahead, entrance covered in vines, bioluminescent lichen, and the devouring angel mushrooms we seek. A quick dip under the water, and I've hidden my scent from the dogs. I motion to Limin to do the same. If they're sleeping, we'll have a chance. The caps are white along the top and feathered like angels' wings with rubbery black rims beneath. They're not poisonous like the death cap and wolf's fang. These cause severe hallucinations that drive you to kill everyone in sight, and then you snap to an hour later, feeling perfectly fine, no side effects except the blood of twenty-eight people on your hands. I peek into the cave entrance, and sure enough, three mossdogs are curled together deep in the shadows, paws twitching in a state of dreaming—sharp obsidian claws dragging through imagined flesh, muffled barks coming from those fanged mouths. Carefully, quietly, I reach up to snag the devouring angels. "Psst, Bozak!" Limin whispers, "Are you sure that's not griffin's paw fungus?" One of the mossdog's tentacles shifts, and I instantly stop what I'm doing. I hold my breath until the tentacle settles. Limin's buzzing overhead, right outside the cave, gossamer wings glistening, but all I can think about is how he's spreading his scent around and any second the mossdogs are going to notice. "I'm sure," I whisper back. Griffin's paw looks so similar to devouring angel that even some seasoned spore druids have trouble telling them apart, but my brother had taught me to spot the slight difference in the shape of their caps. I collect the devouring angel mushrooms and carefully wrap them. I tuck my sample into my satchel and hand Limin his. Limin lands in the marsh, right next to me. I try to push past him, but he shuffles into my way. "What's the matter, Bozak? Afraid you can't outrun a little mossdog?" He squints into the cave. "Oh, come on. They're nearly pups." "Mmm-hmm. Easy to say for someone like you." Someone who can fly, I mean. "Now if you'll excuse me, we're on our own from here on out." I hear more footsteps on the way. I look up to see a silhouette with hair waving like a nest of snakes. Kata's caught up with us. Gorgons are stiff competition. Literally. And I don't intend to catch a case of petrification. "Till death and beyond!" Limin shouts, stashing his mushroom, then tossing a rock into the mossdog den. It lands in the middle of one dog's forehead, and all those glassy black eyes become alert. Its head lifts. Muzzle draws back into a growl. Then the other two dogs are awake and growling right behind it. "What did you do, Limin?" I ask, but he's already flying away. The mossdogs stare down at me, timidly stepping forth. I turn and take off sprinting, and that's all the invitation they need to give chase. "Mossdogs," I shout at Kata, and then we're both running, shoulder to shoulder, and the mossdogs are gaining on us. "I can petrify them~" she says to me, panting and nearly out of breath. "~if you can buy me a few seconds to cast the spell." "I thought you didn't want to work together," I say. "Bozak, are you seriously going to be that petty while mossdogs are trying to eat us alive?" "Fine," I say. "I'll distract them." "Give me half a minute, then loop them back around my way." I nod, then flutter my wings in an irresistible hum, and as the dogs give chase, I veer around a copse of vines, then circle back around to Kata, all the tendrils on her head aggravated and waving. She releases her spell, and two of the mossdogs slow down, then freeze, mouths caught open in vicious growls. Flesh turns to stone, an inch at a time, but there's no time to gawk. I've got one more dog headed my way, and Kata is trying to cast again, but nothing's happening. Suddenly the dog is upon her. I can't lie~my first instinct is to leave her there and go after victory, but what would Mother think of that? I rip my wings together, putting together a beautiful song. Insects flock to me, a swarm of silver-backed locusts. I sic them on the mossdog, who stops tearing at Kata, and starts trying to gnash away at the bugs. "Go, get away!" I yell at Kata, but she's got another idea. Her hair is flaring again. "No!" I scream, but it's too late. The third mossdog turns into a statue, and with it, nearly a hundred locusts. They fall to the ground like pebbles. "What? They're just bugs," she says, when she notices me glaring at her. I get ready to tell her that they're more than bugs, they're my kin, but then I notice her hair is still agitated. I'm just a bug to her as well. "Only one can win, Bozak. And it's going to be me." She fixes me with her stare. Her pupils dilate until her eyes are entirely black, then light starts glowing around the edges. I stand there a moment, frozen from shock, from the ache of broken trust~but then my staff pulses in my hand. Its point is sharp enough to pierce flesh, maybe. I move fast, thrust the staff forward. It catches the gorgon in the stomach. The light in her eyes fades, the spell releases, and the stiffness building in my joints eases away. She lies there, clutching the staff at the entry wound, coughing up blood. My staff glints and almost seems to have come alive with magic. My mind shifts~and I grab the shaft, running my hand along the pearlescent outer curve and the ribbed blackness of the inner curve. I'd carved it myself from one of Mother's legs. Whatever bit of magic it had contained is gone now, her last gift to me. Her encouragement spears me on, my mind set on one thing. Winning. With all of the mushrooms safely tucked away in my satchel, all I need to do is get back to the lich before Limin does. I may not be able to fly, but I don't need to when I've got insects on my side. I brush my wings together and hum deeply, imitating the mating call of the deadbridge goliath. The ground thunders, then I see it, a giant beetle running right toward me. He's confused seeing me and not his potential mate, but I grab onto his leg and hold on for dear life and he trudges forward, making up valuable time. I see Limin ahead, and I'm catching up, but then the beast veers and I'm forced to bail. Still, I'm close enough that I'll have a chance. #figure(image("004_Death's Precious Moments/03.jpg", width: 100%), caption: [Deadbridge Goliath | Art by: Chase Stone], supplement: none, numbering: none) Then out of the swamp, a moss-covered figure rises, staff held in both hands. He batters Limin as he passes, breaking off two legs and part of a wing. Limin tumbles into the boggy water, screaming as the mossy figure snatches his satchel. The assailant then looks up at me~elven ears and moodmarks showing through the green grit upon his skin. Half his face is covered in splinters, and his gaudy blue robe is shredded to pieces. Zegodonis. He'd somehow survived the woodwraith attack. We race, I'm going as fast as I can, and he's limping behind. He curses at me, calling me every kraul slur he can think of, but I keep my eye on the prize. The lich is standing there, not far. I reach him first, and instantly I'm filled with accomplishment. I've done it! "Congratulations," the lich says, the dead in his voice a perfect match for the rest of him. He examines my specimens twice over before Zegodonis hobbles up to us. "Congratulations to you, too." He takes Zegodonis's bag, glances inside. "Both of you have met the challenge. And both of you shall serve under me." The lich's eyes brighten when he looks at Zegodonis, something I would have thought impossible from the look he'd given me. There was supposed to be one winner, but I don't dare confront them about it. Instead, I choose to savor this moment and focus on becoming the best necromancer I can be. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "Not here. Over there!" I scream at the fungus drudge for the fifth time. He moans at me, limbs covered in soft, white fuzz and a grouping of long-stalked mushrooms sprouting from his shoulders and head. His body is held together with death magic and fungal rhizomes that animate bones that hadn't felt flesh for the past century. Drudges are nearly impossible to work with. The Erstwhile zombies, they're decent at taking instructions, though the lich hasn't put me in charge of any of those. But I enjoy watching how they march to the beat of a bygone era, dressed in dusty fineries with lots of scallops, frill, and innumerable cloth buttons sewed upon their bodices. The fungal drudge, I call him Benzi, places the corpse he's carrying onto the pile in the corner of the lich's sanctum, then turns to me. Eye sockets trained on me, he waits eagerly for my next command. I sigh. "Sorry, Benzi," I say. I shouldn't have screamed. I get frustrated and take it out on the zombies sometimes. This isn't exactly how I'd envisioned being apprentice to a lich—tending to the undead instead of learning to raise them. The lich is out consulting at Korozda, the Golgari guildhall, and he's taken Zegodonis with him. Again. There's been a fungal attack on Sunhome. Three high-ranking Boros officers were exposed to the same type of zombie fungus we had been asked to gather. They'd climbed the towers of their guildhall, and one actually made it to the top. Vraska, our guildmaster, is worried the Boros will use this as another excuse to infiltrate the Undercity and has summoned the liches to confer on how best to proceed. They'll be gone for hours. The lich doesn't like me in his sanctum, and he reprimands me if I linger too long when dropping off bodies, so most of what I've learned about spells has come from eavesdropping at the door. But now I can thoroughly explore without the risk of getting caught. There are shelves upon shelves of skulls: Rakdos devils with thick curling horns and eye sockets that glow a deep emerald green when the lights are low, long-snouted viashinos, minotaurs, giants~all the way up to a dragon's skull that now serves as the lich's lectern. The mushroom specimens lining his walls put my own collection to shame. There must be thousands of them. The rot is so thick in the air, so rich and decadent, that I'm tempted to try a death spell of my own. I practice the movements I've seen the lich do, and I prickle all over as mana rushes through me, coursing over my skin like hundreds of marching ants. I fight the urge to shake them off, and instead relax, letting the mana flow down my arm, the soft green light pooling into the palm of my hand. I channel a bit onto the not-so-fresh rat corpse I'd found while cleaning behind the Erstwhile's crypts. Then I watch. The rat's back leg twitches, but nothing more. I'm certain with the lich's instruction, I'd be able to do it by now. Zegodonis has learned several spells already. I'd hoped that necromancy would be my calling, but maybe it's time to admit that cleaning cobwebs out of crypts and bossing fungal drudges around is what I'll be doing with the rest of my life. I hear voices down the hall. The lich. He's back already. I can't let him catch me in here. I duck into the nook in the back of the sanctum, then look out at Benzi who's still staring at me, ready to give me away. "Come!" I command him. He shuffles over to me. "Faster!" The yelling never speeds things up. I run out and push him into the nook. He moans. "Shhh," I tell him. "Play dead." Benzi obeys, a little trick I'd taught him in our spare time. He slumps over, head leaned against the cold, gray stone wall. The lich enters from his private door, two Boros soldiers following him. They hold themselves tight and proud, but the way their puffy eyes are darting around in their sockets, I can tell they are scared to be here. The lich goes to the vials of mushroom specimens and chooses the ones we'd retrieved from the mossdog cave. "Devouring angel. Perhaps the deadliest mushroom in all of Ravnica. It won't kill you, but it'll make everyone who inhales its spores embrace their rage. You remember the Tin Street massacre?" "Yeah," says one of the soldiers. "We arrested a couple of Gruul raiders for that. You're saying we got the wrong criminals?" The lich arches a thin, sickly eyebrow. "I've already planted a neutralized specimen on the gown Vraska will be wearing for her address to the Krunstraz this evening at the Hanging Keep. Exhume the bodies from the massacre and analyze the spores. The evidence will show that the attack came from the same plant. Boros will have no choice but to charge Vraska with murder. It will stick this time, I promise you." #figure(image("004_Death's Precious Moments/04.jpg", width: 100%), caption: [Underrealm Lich | Art by: <NAME>], supplement: none, numbering: none) "Come on, we've got a party to crash," the Boros soldier says. "Indeed," the lich says, his bony fingers pitched into a steeple. "And I do hope that when it comes time for Boros to back a new candidate for guildmaster, they take into consideration the help I've been to you today." "Oh, we think we know the right Devkarin for the job," they laugh. The lich smiles, a harrowing stretch of desiccated lips revealing an endless expanse of ash-gray teeth. "Zegodonis!" he yells. Zegodonis comes running in. "Show these fine soldiers out, will you?" "Yes, my lich," Zegodonis says with a deep bow. The lich examines his pile of corpses, then starts his reanimation spells. I peek around the corner, watching as he casts, and one by one, life fills their bodies. I wait, nervous. I've got to warn Vraska. I look down and realize I'm still clutching the dead rat in my hand, just what I need to cause a distraction. If I can get the lich to look the other way, I can sneak out of here. I stare at the rat and cast the spell as I saw the lich just do it. The green light fills my palm again, thicker now, more like syrup than water. I pour it over the rat. Whiskers flicker. Tail twitches. Four little paws paddle at the air. I pull a boar's tail mushroom sample from my satchel, cheesy and soft. I feed it to the rat. It nibbles, stuffing its mouth. Pieces of chewed mushroom tumble out of the hole worn through its abdomen, but it doesn't seem to notice. I carefully toss a couple of mushroom chunks at the lich's feet, then put the rat on the floor. It skitters across the tile, eats both pieces, then takes a chomp on the lich's ankle. He enrages, his flailing arm knocks a spell book off his lectern. Old parchment goes flying everywhere. In the chaos, I stick to the shadows and slip out the door. Then I'm running as fast as I can to the Hanging Keep. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) I feel hundreds of eyes upon me as I approach the Hanging Keep. I crane my neck, looking up at the fortress clinging to the ceiling like a wasp's nest. Even from down here, I can hear the buzzing and clicking of my fellow kraul, riled up from the excitement of a visit from the guildmaster. "I need to see Vraska," I say to the guards. I expect them to ask for my credentials, or at least explain why I'm here, but the guard just eyes me up and down like I couldn't possibly pose a threat. "Standing room only. Go ahead up," he mumbles, motioning to the bottom entrance of the Keep. "Actually, could I get a lift?" He glances at my crooked wing, then whistles over to a winged guard who whisks me up and into the first level of the Keep. Overhead is a grand atrium, jewel-colored moss draping from the overhangs. The royal guard, overwhelmingly kraul, crowds every level, and I can feel the collective buzz through my exoskeleton. Seven stories up, Vraska is leaning over the railing and waving at her devoted followers. I squint. I think that's Vraska. From here, she's the size of an ant. The crowd is so thick, I'll never be able to reach her in time. The Boros officers may already be on their way, so whatever I do, I have to do it now. I push my way through the swarm until I reach one of the Keep's windows, a handy shortcut to Vraska. I make the mistake of looking down, dizziness clouding my thoughts. All I need to do is scale seven stories, and I know exactly how I can climb them without a lick of fear. #figure(image("004_Death's Precious Moments/05.jpg", width: 100%), caption: [K<NAME> | Art by: <NAME>], supplement: none, numbering: none) I pull a zombie fungus sample from my satchel and place it on my tongue. The cocoon melts away. Minutes pass, and with it, my fear of heights. I can't think of anything I'd love more than to reach the very top of the Hanging Keep. I squeeze out of the window, sink leg after leg into the outside of the structure. I climb seven stories, and then force my thoughts against those of my fungal invaders. I must stop climbing. #emph[Higher] , the fungus tells me. #emph[Higher] . #emph[Higher] . It beats like my heart. But I have to go inside. I work my way through a series of back chambers until I find the atrium. Vraska is standing there with her back facing me, giving an impassioned speech to the Krunstraz, her hair waving wildly. A dozen mushroom species adorn her gown. I look for the devouring angel fungus. I see golden parasols on her shoulders, scarlet elf caps on her bodice, club coral fungi, shaggy mane~then there, tucked among the griffin's paw fungus trailing down the webbing of the gown's train, I spot where the lich had hidden the devouring angel mushroom, its cap bulging up ever-so-slightly higher than its non-lethal neighbors. I creep forward, one step at a time. Her guards and advisors are with her, but they've all got their eyes trained on the crowd gathered below. One of her advisors turns and sees me. He excuses himself and starts coming for me. It takes my brain a moment to identify him as kraul. Then his face becomes obvious. It's Mazirek. "You!" he says. I try to compose myself so I can tell him about my lich, and the Boros, and the devouring angel fungus, and the plot against Vraska, but the fungus has crowded out nearly every function that doesn't involve climbing and all that comes out is an incomprehensible grumble. #emph[Higher] . A guard grabs me by the arm and wrenches it tight. It should hurt the way he's bending it, but it doesn't. "Get him out of here," Mazirek says. The guard shoves me forward, but I focus my thoughts. If the fungus has dulled my sense of pain, I can use that in my favor. I wrench hard against his grip, once, twice, violently enough to dislodge my arm from the socket. There's a dull throb where it has broken free, but it doesn't bother me. The guard is left there holding my arm while I make a run for Vraska. I grab the devouring angel mushroom on her gown and swallow it whole. I can't let it be found here. I can't let the Boros sink their grips further into the Swarm, just when we're starting to recover from the internal chaos of the change in leadership. I run to the window. Looking down is still scary, but I do what I must do. I flap my wings and jump. Maybe what's great about me is that there are so many things I can do well enough. I can sing a mating call well enough to fool a deadbridge goliath. I can throw a stone accurately enough to hit a wurm in the eye from fifty feet. And I can spread my wings and fly far enough~#emph[fall] far enough from the Keep, ensuring that Vraska won't be implicated in the Tin Street massacre. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) I twitch in the shallow water of an Undercity marsh. I hadn't expected to survive the fall, but maybe my wings had slowed me down just enough. My body throbs all over, not quite pain, but an uncomfortable pressure, like I've been holding my breath too long. The urge to climb is gone. I thought maybe I'd be raging from the devouring angel fungus by now, but perhaps the lich really did neutralize it completely? I should go somewhere far away from people, just to be safe. I try to sit up, but two of my legs are broken and there's a crack in my carapace running end to end. Something else is wrong with me—a fungus stirs within that's powerful, precise, and sits watch over my thoughts. I move my remaining arm, but it is not the automatic movement I am used to. It's more like a combined effort, like the time my siblings and I had hoisted Mother away from the riverbank during our first flood season. My other senses come slowly as well, like they're processed and filtered through a hundred different minds before they get to me. "Take. Time," comes a voice from beside me. There were a lot more words than that spoken, but I'm only able to understand those. In a coordinated effort, I twist my neck. My muscles slither more than move. #figure(image("004_Death's Precious Moments/06.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) My vision is blurry, pressure from fungal matter taking root behind my eyes. A few of the mushrooms have sprouted through, and they wreck my peripheral vision. I touch them, feeling upturned caps and tiny egg-like spheres within. Bird's nest fungus. Had my samples ruptured from their casings in the fall? They're not the fastest growing mushrooms, and I start to wonder how long I'd been unconscious. "Careful," the voice says. I focus hard on the person and see kraul features. "Razi?" I call out my sister's name, but my voice is a rasp, and when I'd tried to strum my wings, I couldn't feel either of them. I panic, reach around to my back. I feel stumps covered in soft fuzz. "Wings. Lost. Fall." The face behind the words starts to congeal. It takes a long, long moment, but I recognize it. "Mazirek?" I'm drawn to him, not just from years of admiration, but physically drawn to him. I'm looking at him how the fungus drudges look at me, eagerly awaiting his command. Maybe I hadn't survived the fall after all. But there are worse places to end up than bound to the most powerful kraul in the Swarm. I wrench my facial features up into a smile, completely humbled, and ready and willing to serve him as best I can. That moment it takes for everything to sink in—#emph[that's] the moment of death—not when you take your last breath, or your heart beats its last beat. It's the moment when you realize you've got your whole death in front of you, and the possibilities are endless.
https://github.com/mumblingdrunkard/mscs-thesis
https://raw.githubusercontent.com/mumblingdrunkard/mscs-thesis/master/src/utils/acronyms.typ
typst
#let acronyms = ( // Assembly: ("(A|a)ssembly", "Human-readable form of machine language"), AGU: ("AGUs?" , "Address generation unit" ), ALU: ("ALUs?" , "Arithmetic-logic unit" ), ARF: ("ARFs?" , "Architectural register file" ), BOOM: ("BOOM" , "Berkeley out-of-order machine" ), CPI: ("CPI" , "Cycles per instruction" ), CPU: ("CPUs?" , "Central processing unit" ), CSR: ("CSRs?" , "Control and status registers" ), DAG: ("DAGs?" , "Directed acyclic graph" ), DCPT: ("DCPT" , "Delta-correlating prediction tables" ), DoM: ("DoM" , "Delay-on-miss" ), DRAM: ("DRAM" , "Dynamic Random Access Memory" ), DSL: ("DSLs?" , "Domain-specific language" ), FU: ("FUs?" , "Functional unit" ), HDL: ("HDLs?" , "Hardware description language" ), ILP: ("ILP" , "Instruction-level parallelism" ), IPC: ("IPC" , "Instructions per cycle" ), IPS: ("IPS" , "Instructions per second" ), IQ: ("IQs?" , "Issue queue" ), ISA: ("ISAs?" , "Instruction set architecture" ), InO: ("InO" , "In-order" ), JAL: ("JALs?" , "Jump-and link" ), L1: ("L1s?" , "First-level cache" ), L1d: ("L1ds?" , "First-level data cache" ), L1i: ("L1is?" , "First-level instruction cache" ), L2: ("L2s?" , "Second-level cache" ), L3: ("L3s?" , "Third-level cache" ), LDQ: ("LDQs?" , "Load queue" ), LLC: ("LLCs?" , "Last-level cache" ), LSU: ("LSUs?" , "Load-store unit" ), MIPS: ("MIPS" , "Millions of instructions per second" ), MLP: ("MLP" , "Memory-level parallelism" ), MSHR: ("MSHRs?" , "Miss status holding register" ), NDA: ("NDA" , "Non-speculative data access" ), OS: ("OSs?" , "Operating system" ), OSS: ("OSS" , "Open source software" ), OoO: ("OoO" , "Out-of-order" ), PC: ("PCs?" , "Program counter" ), PRF: ("PRFs?" , "Physical register file" ), RAM: ("RAM" , "Random access memory" ), RAW: ("RAWs?" , "Read-after-write" ), RFP: ("RFPs?" , "Register file prefetching" ), RISC: ("RISCs?" , "Reduced instruction set computer" ), ROB: ("ROBs?" , "Re-order buffer" ), RR: ("RR" , "Register renaming" ), RTL: ("RTL" , "Register-transfer level" ), SRAM: ("SRAMs?" , "Static random access memory" ), STQ: ("STQs?" , "Store queue" ), STT: ("STT" , "Speculative taint tracking" ), TSO: ("TSO" , "Total store order" ), TVM: ("TVMs?" , "Test virtual machine" ), UCB: ("UC(B| Berkeley)", "University of California, Berkeley" ), VHDL: ("VHDL" , "VHSIC hardware description language" ), VHSIC: ("VHSIC" , "Very high speed integrated circuit" ), VLIW: ("VLIWs?" , "Very long instruction word" ), VP: ("VPs?" , "Value prediction" ), WAR: ("WARs?" , "Write-after-read" ), WAW: ("WAWs?" , "Write-after-write" ), eDSL: ("eDSLs?" , "Embedded domain-specific language" ), uOP: ("uOPs?" , "Micro-operation" ), ) #let usedAcronyms = state("used", (:)) #let listOfAcronyms = () => locate(loc => { grid(columns: (auto, 1fr), align: (left, left), inset: 5pt, ..usedAcronyms.final().pairs().sorted().map(((acr, uses)) => { ( [*#acr*], [#acronyms.at(acr).at(1) #label("acronyms:" + acr) #box(repeat(" ."), width: 1fr) #box(width: 5pt) #uses.dedup(key: use => use).map(use => { link(use)[#use.page()] }).join(", ")], ) }).flatten() ) } ) #let enableAcronyms(body) = { for (acr, (expr, desc)) in acronyms { body = { let match = "\b" + expr + "\b" show regex(match): (it) => { locate(loc => { usedAcronyms.update(used => { if used.keys().contains(acr) { if used.at(acr).last().page() != loc.page() { used.at(acr).push(loc) } } else { used.insert(acr, (loc,)) } used }) link(label("acronyms:" + acr), it) }) } body } } body }
https://github.com/typst-jp/typst-jp.github.io
https://raw.githubusercontent.com/typst-jp/typst-jp.github.io/main/docs/changelog/0.7.0.md
markdown
Apache License 2.0
--- title: 0.7.0 description: Changes in Typst 0.7.0 --- # Version 0.7.0 (August 7, 2023) ## Text and Layout - Added support for floating figures through the [`placement`]($figure.placement) argument on the figure function - Added support for arbitrary floating content through the [`float`]($place.float) argument on the place function - Added support for loading `.sublime-syntax` files as highlighting [syntaxes]($raw.syntaxes) for raw blocks - Added support for loading `.tmTheme` files as highlighting [themes]($raw.theme) for raw blocks - Added _bounds_ option to [`top-edge`]($text.top-edge) and [`bottom-edge`]($text.bottom-edge) arguments of text function for tight bounding boxes - Removed nonsensical top- and bottom-edge options, e.g. _ascender_ for the bottom edge **(Breaking change)** - Added [`script`]($text.script) argument to text function - Added [`alternative`]($smartquote.alternative) argument to smart quote function - Added basic i18n for Japanese - Added hyphenation support for `nb` and `nn` language codes in addition to `no` - Fixed positioning of [placed elements]($place) in containers - Fixed overflowing containers due to optimized line breaks ## Export - Greatly improved export of SVG images to PDF. Many thanks to [@LaurenzV](https://github.com/LaurenzV) for their work on this. - Added support for the alpha channel of RGBA colors in PDF export - Fixed a bug with PPI (pixels per inch) for PNG export ## Math - Improved layout of primes (e.g. in `[$a'_1$]`) - Improved display of multi-primes (e.g. in `[$a''$]`) - Improved layout of [roots]($math.root) - Changed relations to show attachments as [limits]($math.limits) by default (e.g. in `[$a ->^x b$]`) - Large operators and delimiters are now always vertically centered - [Boxes]($box) in equations now sit on the baseline instead of being vertically centered by default. Notably, this does not affect [blocks]($block) because they are not inline elements. - Added support for [weak spacing]($h.weak) - Added support for OpenType character variants - Added support for customizing the [math class]($math.class) of content - Fixed spacing around `.`, `\/`, and `...` - Fixed spacing between closing delimiters and large operators - Fixed a bug with math font weight selection - Symbols and Operators **(Breaking changes)** - Added `id`, `im`, and `tr` text [operators]($math.op) - Renamed `ident` to `equiv` with alias `eq.triple` and removed `ident.strict` in favor of `eq.quad` - Renamed `ast.sq` to `ast.square` and `integral.sq` to `integral.square` - Renamed `.eqq` modifier to `.equiv` (and `.neqq` to `.nequiv`) for `tilde`, `gt`, `lt`, `prec`, and `succ` - Added `emptyset` as alias for `nothing` - Added `lt.curly` and `gt.curly` as aliases for `prec` and `succ` - Added `aleph`, `beth`, and `gimmel` as alias for `alef`, `bet`, and `gimel` ## Scripting - Fields - Added `abs` and `em` field to [lengths]($length) - Added `ratio` and `length` field to [relative lengths]($relative) - Added `x` and `y` field to [2d alignments]($align.alignment) - Added `paint`, `thickness`, `cap`, `join`, `dash`, and `miter-limit` field to [strokes]($stroke) - Accessor and utility methods - Added [`dedup`]($array.dedup) method to arrays - Added `pt`, `mm`, `cm`, and `inches` method to [lengths]($length) - Added `deg` and `rad` method to [angles]($angle) - Added `kind`, `hex`, `rgba`, `cmyk`, and `luma` method to [colors]($color) - Added `axis`, `start`, `end`, and `inv` method to [directions]($stack.dir) - Added `axis` and `inv` method to [alignments]($align.alignment) - Added `inv` method to [2d alignments]($align.alignment) - Added `start` argument to [`enumerate`]($array.enumerate) method on arrays - Added [`color.mix`]($color.mix) function - Added `mode` and `scope` arguments to [`eval`] function - Added [`bytes`] type for holding large byte buffers - Added [`encoding`]($read.encoding) argument to read function to read a file as bytes instead of a string - Added [`image.decode`]($image.decode) function for decoding an image directly from a string or bytes - Added [`bytes`] function for converting a string or an array of integers to bytes - Added [`array`] function for converting bytes to an array of integers - Added support for converting bytes to a string with the [`str`] function ## Tooling and Diagnostics - Added support for compiler warnings - Added warning when compilation does not converge within five attempts due to intense use of introspection features - Added warnings for empty emphasis (`__` and `**`) - Improved error message for invalid field assignments - Improved error message after single `#` - Improved error message when a keyword is used where an identifier is expected - Fixed parameter autocompletion for functions that are in modules - Import autocompletion now only shows the latest package version until a colon is typed - Fixed autocompletion for dictionary key containing a space - Fixed autocompletion for `for` loops ## Command line interface - Added `typst query` subcommand to execute a [query]($reference/introspection/query/#command-line-queries) on the command line - The `--root` and `--font-paths` arguments cannot appear in front of the command anymore **(Breaking change)** - Local and cached packages are now stored in directories of the form `[{namespace}/{name}/{version}]` instead of `[{namespace}/{name}-{version}]` **(Breaking change)** - Now prioritizes explicitly given fonts (via `--font-paths`) over system and embedded fonts when both exist - Fixed `typst watch` not working with some text editors - Fixed displayed compilation time (now includes export) ## Miscellaneous Improvements - Added [`bookmarked`]($heading.bookmarked) argument to heading to control whether a heading becomes part of the PDF outline - Added [`caption-pos`]($figure.caption.position) argument to control the position of a figure's caption - Added [`metadata`] function for exposing an arbitrary value to the introspection system - Fixed that a [`state`] was identified by the pair `(key, init)` instead of just its `key` - Improved indent logic of [enumerations]($enum). Instead of requiring at least as much indent as the end of the marker, they now require only one more space indent than the start of the marker. As a result, even long markers like `12.` work with just 2 spaces of indent. - Fixed bug with indent logic of [`raw`] blocks - Fixed a parsing bug with dictionaries ## Development - Extracted parser and syntax tree into `typst-syntax` crate - The `World::today` implementation of Typst dependents may need fixing if they have the same [bug](https://github.com/typst/typst/issues/1842) that the CLI world had ## Contributors <contributors from="v0.6.0" to="v0.7.0" />
https://github.com/xingjian-zhang/typst2img
https://raw.githubusercontent.com/xingjian-zhang/typst2img/main/README.md
markdown
# Typst Formula Renderer A customization-allowed fast script to render your Typst formulas to svg or png. ## Usage Command line: ```bash python render_typ.py '$y = A x + b$' -o output.svg ``` In Jupyter Notebook (recommended): ```python from render_typ import FormulaRenderer formulas = [ r'$ A = pi r^2 $', r'$ "area" = pi dot "radius"^2 $', r'$ cal(A) := { x in RR | x "is natural" } $', r'$ x < y => x gt.eq.not y $', r'$ mat(1, 2; 3, 4) $', r'''$ sum_(k=0)^n k &= 1 + ... + n \ &= (n(n+1)) / 2 $''', ] # Render in-line in a notebook. basic_renderer = FormulaRenderer() for f in formulas: basic_renderer.render(f) # Save to file. named_formulas = { "mass_energy_equivalence": r'$ E = m c^2 $', "euler_identity": r'$ e^(i pi) + 1 = 0 $', "general_relativity": r'$ G_(mu nu) + Lambda g_(mu nu) = kappa T_(mu nu) $', } for k, v in named_formulas.items(): basic_renderer.render(v, name=k) ``` See [`example.ipynb`](example.ipynb) for more examples. ## Installation ```bash pip install -r requirements.txt ``` ## Convert to PNG You can convert the SVG files to PNG using [ImageMagick `convert`](https://imagemagick.org/script/download.php). This feature is only tested on MacOS. ```bash $ make all convert -density 1000 output/euler_identity.svg output/euler_identity.png convert -density 1000 output/general_relativity.svg output/general_relativity.png convert -density 1000 output/mass_energy_equivalence.svg output/mass_energy_equivalence.png ``` ## Examples ### Euler Identity ![Euler Identity](output/euler_identity.svg) ### General Relativity ![General Relativity](output/general_relativity.svg) ### Mass Energy Equivalence ![Mass Energy Equivalence](output/mass_energy_equivalence.svg)
https://github.com/UBOdin/data_structures_book
https://raw.githubusercontent.com/UBOdin/data_structures_book/main/book.typ
typst
#set page(width: 8.5in, height: 11in) #set heading(numbering: "1.") #show figure.caption: strong #show heading: set text(navy) #show heading.where(level: 1): it => [ #set text(navy) #set align(center) #pagebreak() #underline[ Chapter #counter(heading).display() #emph(it.body) ] ] #set document(title: "CSE 250: Data Structures") #align(center + horizon)[ #text(size: 40pt)[CSE 250: Data Structures] #text(size: 20pt)[Course Reference] ] #outline() #include "chapters/1-introduction.typ" #include "chapters/2-math.typ" #include "chapters/3-asymptotic.typ" #include "chapters/4-lists.typ" #include "chapters/5-recursion.typ" // Chapter 6: The Stacks and Queue ADTs // Chapter 7: The Graph ADT and Graph Traversal // Chapter 7: The Priority Queue ADT // Chapter 8: Binary Search Trees // Chapter 9: Hash Tables // Chapter 10: Spatial Indexing // Chapter 11: On-Disk Data Structures
https://github.com/lbsekr/provadis-typst-template
https://raw.githubusercontent.com/lbsekr/provadis-typst-template/main/README.md
markdown
# Provadis Typst Template Das hier ist ein [Typst](https://typst.app) Template für wissenschaftliche Arbeiten an der Provadis Hochschule. Es orientiert sich an der offiziellen Word Vorlage (aber keine Garantie auf Vollständigkeit). ## Nutzung Verwende nur getaggte [Versionen](https://github.com/lbsekr/provadis-typst-template/tags). Ungetaggte Versionen sind als Entwicklungsversionen anzusehen und möglicherweise nicht benutzbar. ### 1. Binde das Template ein Entweder über einen Download oder als Git-Submodule, falls du ohnehin Git nutzt um deine wissenschaftliche Arbeit zu verwalten (`git submodule add https://github.com/lbsekr/provadis-typst-template.git`) ``` thesis/ ├─ provadis-typst-template/ <- this repository ├─ main.typ ``` Wenn du Git verwendest, solltest du noch eine getaggte Version auschecken. ``` cd provadis-typst-template git checkout <tag_or_commit_sha> ``` ### 2. Binde das Template in deine `main.typ` Datei ein ```{typst} #import "template.typ": Template ``` ### 3. Initialisiere das Template mit deinen eigenen Werten Für die Referenz der ganzen Werte schaue bitte in der `template.typst` Datei nach. Hier folgt ein Beispiel: ``` #show: Template.with( title: "Evaluierung der Nutzung von Typst in einer Bachelor-Arbeit", authors: ( ( name: "<NAME>", email: "<EMAIL>", postal: "Hauptstraße 10, D-10341 Superstadt", matrikel: "X420" ), ), bib: arguments("literatur.bib", style: "frontiers"), first_appraiser: "Dr. Prof. <NAME>", supervisor: "<NAME>, Infraserv GmbH", location: "Frankfurt (Oder)", deadline: "11.09.2001", ) ``` **Liste von Argumenten** | Argument | Typ | Standardwert | Verwendungszweck | |------------------------------|--------------------|--------------------------------------|-------------------------------------------------------------------------------------------| | language | String | "de" | Definiert die Sprache des Dokuments. Momentan nur Deutsch und English unterstützt. | | title | Liste von Strings | ["Textvorlage für wissenschaftliche Arbeiten\n\nTitel und Untertitel der Arbeit"] | Gibt den Titel und Untertitel des Dokuments an. | | authors | Tupel von Tupeln ( name: string \| content, email: string \| content, postal: string \| content, matrikel: string \| content), | [(name: "<NAME>", email: "<EMAIL>", postal: "Hauptstraße 10, D-10341 Hauptstadt",matrikel: "XXXX")] | Enthält Informationen über die Autoren des Dokuments. | | logo | Bild | image("img/t-systems.png", width: 180pt, height: 2.06cm, fit: "contain") | 2tes optionales Logo. | | abstract | String | lorem(100) | Enthält das Abstract des Dokuments. | | preface | String | lorem(100) | Enthält das Vorwort oder die Einleitung des Dokuments. | | acknowledgement | String | "Für meine Brudis" | Danksagung an Personen oder Gruppen für ihre Unterstützung. | | document-type | String | "Wiss. Kurzbericht / WAB / Bachelorarbeit / Masterarbeit" | Spezifiziert den Typ des Dokuments (z.B. Bachelorarbeit, Masterarbeit). | | reason | Liste von Strings | Siehe Template | Beschreibt den Grund für die Erstellung des Dokuments, z.B. für Erlangung akademische Grade. | | submitted_to | Liste von Strings | Siehe Template | Gibt an, wo das Dokument eingereicht wird (z.B. Universitätsabteilung). | | first_appraiser | String | "<NAME>" | Name des ersten Gutachters oder Prüfers des Dokuments. | | second_appraiser | String | "Dr. Kunze" | Name des zweiten Gutachters oder Prüfers des Dokuments. | | supervisor | String | "Dr. Peter" | Name des Betreuers oder Beraters, der das Dokument überwacht. | | bib | String oder NoneType| none | Gibt den Stil für das Literaturverzeichnis an oder zeigt an, dass kein Literaturverzeichnis vorhanden ist (none). | | appendix | Liste von Content | () | Enthält Anhänge oder zusätzliches Material, das dem Dokument angehängt ist. | | location | String | "Berlin" | Gibt den Ort an, an dem das Dokument erstellt wird. | | deadline | String | "15.03.2024" | Setzt die Abgabefrist für das Dokument. | | declaration_of_independence | Boolean | true | Gibt an, ob das Dokument eine Unabhängigkeitserklärung enthält. | | confidential_clause | Boolean | false | Spezifiziert, ob das Dokument eine Vertraulichkeitsklausel enthält. | | glossary_entries | Liste von ( key: String \| Content, short: String \| Content, long: String \| Content ) | () | Enthält Einträge für ein Glossar der im Dokument verwendeten Begriffe. | | abbreviation_entries | Liste von ( key: String \| Content, short: String \| Content, long: String \| Content ) | () | Enthält Einträge für Abkürzungen, die im Dokument verwendet werden. | | show_lists_after_content | Boolean | false | Bestimmt, ob Listen (z.B. Abbildungsverzeichnis) nach dem Hauptinhaltverzeichnis angezeigt werden sollen. | | ai_entries | Liste von (String \| Content, String \| Content) | () | Enthält Einträge für verwendete künstliche Intelligenz im Dokument. | ### 4. Optional: Konfiguriere die Github Action In diesem Repository befindet sich eine [GitHub Action](./.github/workflows/main.yml), die du zum Bauen deines Dokumentes verwenden kannst. Mit dieser GitHub Action wird dein Dokument bei jedem Push (Commit oder Tag) gebaut und als Artefakt hochgeladen. Optional kannst du dieses auch über eine Discord Webhook in einen Discord Channel schicken lassen. Kopiere hierfür einfach den .github Ordner dieses Projekts in dein Eigenes. Du kannst zusätzlich folgende Variablen als Action Variablen konfigurieren. | Variable | Default | Beschreibung | |------------------|---------|--------------------------------------------------------| | FILE_NAME_PREFIX | main_ | Präfix der vor der Versionsinfo angehangen werden soll | | DISCORD_WEBHOOK | | Discord Webhook URL zum Hochladen des PDFs | ## Weitere praktische Tipps - Praktisches Package für TODO-Notizen oder allgemein Anmerkungen am Seitenrand: [package/drafting](https://typst.app/universe/package/drafting) ... werden hier ergänzt falls wir etwas finden 🫡 ## Known Issuses Am Ende des Dokuments wird eine leere Seite angehängt. Das ist ein bekannter [Fehler](https://github.com/typst/typst/issues/2326#issuecomment-2019132332) im Typst-Compiler. Es muss auf einen Fix gewartet werden.
https://github.com/yy01zz02/profile-template
https://raw.githubusercontent.com/yy01zz02/profile-template/main/template/template.typ
typst
MIT License
#import "icons.typ": *; #let template(doc) = { set page( margin: (x: 0.9cm, y: 1.3cm), paper: "a4", ) set text( size: 11pt, font:("Source Han Serif SC") ) show link: text set par( justify: true, ) doc } #let init( name:lorem(3), pic_path: "", ) = { set document( title: name + "'s Resume", author: name, ) set align ( center, ) if pic_path == ""{ text( style: "normal", weight: "extrabold", size: 20pt, )[#name] } else { // insert picture table( columns: (83%, 17%), rows: 1em, align: (x, y) => { (center, right).at(x); }, stroke: none, text( style: "normal", weight: "extrabold", size: 22pt, )[#name], image( pic_path, width: 2.5cm, height: 3.33cm, ) ) } // v(1em) set align(left) } #let info( color: rgb(0, 0, 0), ..infos ) = { set text( fill: color, // size: 10pt, ) set align( center, ) infos.pos().map(dir => { box( height: 1em, { if "icon" in dir { if (type(dir.icon) == "string") { icon(dir.icon) } else { dir.icon } } h(0.15em) if "link" in dir { link(dir.link, dir.content) } else { dir.content } }) }).join(h(0.5em) + "·" + h(0.5em)) v(0.5em) } #let chiline() = {v(-3pt); line(length: 100%); v(-5pt)} #let resume_section(title) = { [== #title] chiline() } #let resume_item(proj_title, proj_time, proj_postion, proj_rule) = { [*#proj_title*] h(1fr) if proj_time != none { [#proj_time] } if proj_postion != none or proj_rule != none { linebreak() } if proj_postion != none { [#proj_postion] } h(1fr) if(proj_rule != none) { [#proj_rule] } linebreak() } #let resume_desc(l, r) = { [- *#l*: #r] }
https://github.com/bennyhandball/PA1_LoB_Finance
https://raw.githubusercontent.com/bennyhandball/PA1_LoB_Finance/main/PA/supercharged-dhbw/2.1.0/README.md
markdown
# Supercharged DHBW Unofficial [Typst](https://typst.app/) template for DHBW students. You can see an example PDF [here](https://github.com/DannySeidel/typst-dhbw-template/blob/main/example.pdf). ## Usage You can use this template in the Typst web app by clicking "Start from template" on the dashboard and searching for `supercharged-dhbw`. Alternatively, you can use the CLI to kick this project off using the command ```shell typst init @preview/supercharged-dhbw ``` Typst will create a new directory with all the files needed to get you started. ## Fonts This template uses the following fonts: - [Montserrat](https://fonts.google.com/specimen/Montserrat) - [Open Sans](https://fonts.google.com/specimen/Open+Sans) If you want to use typst locally, you can download the fonts from the links above and install them on your system. Otherwise, when using the web version add the fonts to your project. For further information on how to add fonts to your project, please refer to the [Typst documentation](https://typst.app/docs/reference/text/text/#parameters-font). ## Used Packages This template uses the following packages: - [codelst](https://typst.app/universe/package/codelst): To create code snippets A more detailed explanation of the features can be found in the `main.typ` file. ## Configuration This template exports the `supercharged-dhbw` function with the following named arguments: `title (str*)`: Title of the document `authors (dictionary*)`: List of authors with the following named arguments (max. 6 authors when in the company or 8 authors when at DHBW): - name (str*): Name of the author - student-id (str*): Student ID of the author - course (str*): Course of the author - course-of-studies (str*): Course of studies of the author - company (dictionary): Company of the author (only needed when `at-university` is `false`) with the following named arguments: - name (str*): Name of the company - post-code (str): Post code of the company - city (str*): City of the company - country (str): Country of the company `abstract (content)`: Content of the abstract, it is recommended that you pass a variable containing the content or a function that returns the content `acronym-spacing (length)`: Spacing between the acronym and its long form (check the [Typst documentation](https://typst.app/docs/reference/layout/length/) for examples on how to provide parameters of type length), default is `5em` `acronyms (dictionary)`: Pass a dictionary containing the acronyms and their long forms (See the example in the `acronyms.typ` file) `appendix (content)`: Content of the appendix, it is recommended that you pass a variable containing the content or a function that returns the content `at-university* (bool)`: Whether the document is written at university or not, default is `false` `bibliography (content)`: Path to the bibliography file `bib-style (str)`: Style of the bibliography, default is `ieee` `city (str)`: City of the author (only needed when `at-university` is `true`) `confidentiality-marker: (dict)`: Configure the confidentially marker (red or green circle) on the title page (using this option reduces the maximum number of authors by 2 to 4 authors when in the company or 6 authors when at DHBW) - display (bool*): Whether the confidentiality marker should be shown, default is `false` - offset-x (length): Horizontal offset of the confidentiality marker, default is `0pt` - offset-y (length): Vertical offset of the confidentiality marker, default is `0pt` - size (length): Size of the confidentiality marker, default is `7em` - title-spacing (length): Adds space below the title to make room for the confidentiality marker, default is `2em` `confidentiality-statement-content (content)`: Provide a custom confidentiality statement `date (datetime* | array*)`: Provide a datetime object to display one date (e.g. submission date) or a array containing two datetime objects to display a date range (e.g. start and end date of the project), default is `datetime.today()` `date-format (str)`: Format of the displayed dates, default is `"[day].[month].[year]"` (for more information on possible formats check the [Typst documentation](https://typst.app/docs/reference/foundations/datetime/#format)) `language (str*)`: Language of the document which is either `en` or `de`, default is `en` `logo-left (content)`: Path to the logo on the left side of the title page (usage: image("path/to/image.png")), default is the `DHBW logo` `logo-right (content)`: Path to the logo on the right side of the title page (usage: image("path/to/image.png")), default is `no logo` `logo-size-ratio (str)`: Ratio between the right logo and the left logo height (left-logo:right-logo), default is `"1:1"` `numbering-alignment (alignment)`: Alignment of the page numbering (for possible options check the [Typst documentation](https://typst.app/docs/reference/layout/alignment/)), default is `center` `show-abstract (bool)`: Whether the abstract should be shown, default is `true` `show-acronyms (bool)`: Whether the list of acronyms should be shown, default is `true` `show-appendix (bool)`: Whether the appendix should be shown, default is `false` `show-code-snippets (bool)`: Whether the code snippets should be shown, default is `true` `show-confidentiality-statement (bool)`: Whether the confidentiality statement should be shown, default is `true` `show-declaration-of-authorship (bool)`: Whether the declaration of authorship should be shown, default is `true` `show-header (bool)`: Whether the header should be shown, default is `true` `show-header-divider (bool)`: Whether the header divider should be shown, default is `true` `show-list-of-figures (bool)`: Whether the list of figures should be shown, default is `true` `show-list-of-tables (bool)`: Whether the list of tables should be shown, default is `true` `show-left-logo-in-header (bool)`: Whether the left logo should be shown in the header, default is `true` `show-right-logo-in-header (bool)`: Whether the right logo should be shown in the header, default is `true` `show-table-of-contents (bool)`: Whether the table of contents should be shown, default is `true` `show-title-in-header (bool)`: Whether the title should be shown in the header, default is `true` `supervisor (dict*)`: Name of the supervisor at the university and/or company (e.g. supervisor: (company: "<NAME>", university: "<NAME>")) - company (str): Name of the supervisor at the company (note while the argument is optional at least one of the two arguments must be provided) - university (str): Name of the supervisor at the university (note while the argument is optional at least one of the two arguments must be provided) `toc-depth (int)`: Depth of the table of contents, default is `3` `type-of-thesis (str)`: Type of the thesis, default is `none` (using this option reduces the maximum number of authors by 2 to 4 authors when in the company or 6 authors when at DHBW) `type-of-degree (str)`: Type of the degree, default is `none` (using this option reduces the maximum number of authors by 2 to 4 authors when in the company or 6 authors when at DHBW) `university (str*)`: Name of the university `university-location (str*)`: Campus or city of the university Behind the arguments the type of the value is given in parentheses. All arguments marked with `*` are required. ## Acronyms ### Functions This template provides the following functions to reference acronyms: `acr`: Reference an acronym in the text `acrpl`: Reference an acronym in the text in plural form `acrs`: Reference an acronym in the text in short form (e.g. `acr("API")` -> `API`) `acrspl`: Reference an acronym in the text in short form in plural form (e.g. `acrpl("API")` -> `APIs`) `acrl`: Reference an acronym in the text in long form (e.g. `acrl("API")` -> `Application Programming Interface`) `acrlpl`: Reference an acronym in the text in long form in plural form (e.g. `acrlpl("API")` -> `Application Programming Interfaces`) `acrf`: Reference an acronym in the text in full form (e.g. `acrf("API")` -> `Application Programming Interface (API)`) `acrfpl`: Reference an acronym in the text in full form in plural form (e.g. `acrfpl("API")` -> `Application Programming Interfaces (API)`) ### Definition To define acronyms use a dictionary and pass it to the acronyms attribute of the template. The dictionary should contain the acronyms as keys and their long forms as values. ```typst #let acronyms = ( API: "Application Programming Interface", HTTP: "Hypertext Transfer Protocol", REST: "Representational State Transfer", ) ``` To define the plural form of an acronym use a array as value with the first element being the singular form and the second element being the plural form. If you don't define the plural form, the template will automatically add an "s" to the singular form. ```typst #let acronyms = ( API: ("Application Programming Interface", "Application Programming Interfaces"), HTTP: ("Hypertext Transfer Protocol", "Hypertext Transfer Protocols"), REST: ("Representational State Transfer", "Representational State Transfers"), ) ``` ## Example If you want to change an existing project to use this template, you can add a show rule like this at the top of your file: ```typst #import "@preview/supercharged-dhbw:2.1.0": * #show: supercharged-dhbw.with( title: "Exploration of Typst for the Composition of a University Thesis", authors: ( (name: "<NAME>", student-id: "7654321", course: "TIS21", course-of-studies: "IT-Security", company: ( (name: "YXZ GmbH", post-code: "70435", city: "Stuttgart") )), (name: "<NAME>", student-id: "1234567", course: "TIM21", course-of-studies: "Mobile Computer Science", company: ( (name: "ABC S.L.", post-code: "08005", city: "Barcelona", country: "Spain") )), ), acronyms: acronyms, // displays the acronyms defined in the acronyms dictionary at-university: false, // if true the company name on the title page and the confidentiality statement are hidden bibliography: bibliography("sources.bib"), date: datetime.today(), language: "en", // en, de supervisor: (company: "<NAME>"), university: "Cooperative State University Baden-Württemberg", university-location: "Ravensburg Campus Friedrichshafen", // for more options check the package documentation (https://typst.app/universe/package/supercharged-dhbw) ) // Your content goes here ```
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/lemmify/0.1.0/src/styles.typ
typst
Apache License 2.0
#import "util.typ": * // Numbering function which combines // heading number and theorem number // with a dot: 1.1 and 2 -> 1.1.2 #let thm-numbering-heading(fig) = { if fig.numbering != none { display-heading-counter-at(fig.location()) "." numbering(fig.numbering, ..fig.counter.at(fig.location())) } } // Numbering function which only // returns the theorem number. #let thm-numbering-linear(fig) = { if fig.numbering != none { numbering(fig.numbering, ..fig.counter.at(fig.location())) } } // Numbering function which takes // the theorem number of the last // theorem, but does not return it. #let thm-numbering-proof(fig) = { if fig.numbering != none { fig.counter.update(n => n - 1) } } // Simple theorem style: // thm-type n (name) body #let thm-style-simple( thm-type, name, number, body ) = block[#{ strong(thm-type) + " " if number != none { strong(number) + " " } if name != none { emph[(#name)] + " " } " " + body }] // Reversed theorem style: // n thm-type (name) body #let thm-style-reversed( thm-type, name, number, body ) = block[#{ if number != none { strong(number) + " " } strong(thm-type) + " " if name != none { emph[(#name)] + " " } " " + body }] // Simple proof style: // thm-type n (name) body □ #let thm-style-proof( thm-type, name, number, body ) = block[#{ strong(thm-type) + " " if number != none { strong(number) + " " } if name != none { emph[(#name)] + " " } " " + body + h(1fr) + $square$ }] // Basic theorem reference style: // @thm -> thm-type n // @thm[X] -> X n // where n is the numbering specified // by the numbering function #let thm-ref-style-simple( thm-type, thm-numbering, ref ) = link(ref.target, box[#{ assert( ref.element.numbering != none, message: "cannot reference theorem without numbering" ) if ref.citation.supplement != none { ref.citation.supplement } else { thm-type } " " + thm-numbering(ref.element) }])
https://github.com/eratio08/learn-typst
https://raw.githubusercontent.com/eratio08/learn-typst/main/template.typ
typst
#import "conf.typ": conf #show: doc => conf( title: [Towards Improved Modelling], authors: ( ( name: "<NAME>", affiliation: "Artos Institute", email: "<EMAIL>", ), ( name: "<NAME>", affiliation: "Honduras State", email: "<EMAIL>", ), ), abstract: lorem(80), doc, ) = Introduction #lorem(90) == Motivation #lorem(140) == Problem Statement #lorem(50) = Related Work #lorem(200)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/skyzh-cv/main.typ
typst
Apache License 2.0
// https://github.com/skyzh/typst-cv-template/blob/master/cv.typ #show heading: set text(font: "Linux Biolinum") #let style_color = rgb("#000000") #set text(fill: style_color) #show link: it => underline(stroke: style_color, it) #set page( margin: (x: 0.9cm, y: 1.3cm), ) #set par(justify: true) #let chiline() = {v(-3pt); line(length: 100%, stroke: style_color); v(-5pt)} = <NAME> <EMAIL> | #link("https://github.com/skyzh")[github.com/skyzh] | #link("https://skyzh.dev")[skyzh.dev] == Education #chiline() *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(10) *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(10) == Work Experience #chiline() *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(20) - #lorem(30) - #lorem(40) *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(20) - #lorem(30) - #lorem(40) == Projects #chiline() *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(20) - #lorem(30) - #lorem(40) *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(20) - #lorem(30) - #lorem(40)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/link-01.typ
typst
Other
// Test that the period is trimmed. #show link: underline https://a.b.?q=%10#. \ Wahttp://link \ Nohttps:\//link \ Nohttp\://comment
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/guide/renderer/ts-lib.typ
typst
Apache License 2.0
#import "/docs/cookery/book.typ": * #import "/docs/cookery/term.typ" as term #show: book-page.with(title: "JavaScript/TypeScript Library") #let renderer-source = "https://github.com/Myriad-Dreamin/typst.ts/blob/main/packages/typst.ts/src/renderer.mts" #let renderer-lib = link(renderer-source)[`renderer.mts`] = JavaScript/TypeScript Library Use #link("https://www.npmjs.com/package/@myriaddreamin/typst.ts")[`@myriaddreamin/typst.ts`]. It is also runnable in node.js, but we recommend using the #cross-link("/guide/all-in-one-node.typ")[Node.js Library] whenever. Ideally, we can wrap node.js into `@myriaddreamin/typst.ts`, but we still don't have concrete idea. Please let us know if you're interested. == Use simplified APIs One may use simplified apis: ```typescript import { $typst } from '@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs'; const mainContent = 'Hello, typst!'; console.log(await $typst.svg({ mainContent })); ``` Specify correct path to the wasm modules if it complains. ```typescript $typst.setCompilerInitOptions({ getModule: ... }); $typst.setRendererInitOptions({ getModule: ... }); ``` The path option is likely required in browser but not in node.js. See #link("https://myriad-dreamin.github.io/typst.ts/cookery/guide/all-in-one.html")[All-in-one (Simplified) JavaScript Library] for more details. == Use one-shot APIs See #renderer-lib for more details. === Example: render a precompiled document inside of some `<div/>` element Full example: #link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/packages/typst.ts/index.html")[single-file] First, initialize the renderer inside browser: ```js let m = window.TypstRenderModule; let plugin = m.createTypstRenderer(); plugin .init({ getModule: () => '/path/to/typst_ts_renderer_bg.wasm', }) ``` Please ensure that `/path/to/typst_ts_renderer_bg.wasm` is accessible to your frontend. Next, load the artifact in #term.vector-format from somewhere. For example, load it by the `fetch` api: ```ts const artifactContent: Uint8Array = await fetch('/main.white.artifact.sir.in') .then(response => response.arrayBuffer()) .then(buffer => new Uint8Array(buffer)); ``` #include "get-artifact.typ" Finally, call the `render` api to trigger rendering: ```js await plugin.init(args); const artifactContent = await loadData(args); // <div id="typst-app" /> const container = document.getElementById('typst-app'); await plugin.renderToCanvas({ artifactContent, container, backgroundColor: '#343541', pixelPerPt: 4.5, }); ``` See the sample application #link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/packages/typst.ts/index.html")[single-file] for more details. == Use `RenderSession` APIs Full exmaple: #link("https://github.com/Enter-tainer/typst-preview/tree/110c031d21e74f747f78fbf78934140d23fec267/addons/frontend")[typst-preview-frontend] See #renderer-lib for more details.
https://github.com/v411e/optimal-ovgu-thesis
https://raw.githubusercontent.com/v411e/optimal-ovgu-thesis/main/template/expose.typ
typst
MIT License
#import "metadata.typ": title, author, lang, document-type, city, date, organisation #import "@local/optimal-ovgu-thesis:0.1.0": oot-expose #oot-expose( title: title, author: author, lang: lang, document-type: document-type, city: city, date: date, organisation: [], )[ #include "chapter/01-Einleitung.typ" #pagebreak() #text(weight: "semibold", "Bibliography") #bibliography("thesis.bib") ]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/let-23.typ
typst
Other
// Error: 10-13 expected identifier, found string // Error: 18-19 expected identifier, found integer #let (a: "a", b: 2) = (a: 1, b: 2)
https://github.com/linxuanm/math-notes
https://raw.githubusercontent.com/linxuanm/math-notes/master/real-analysis/main.typ
typst
#align(center, text(17pt)[Real Analysis Lecture Notes]) #grid( columns: (1fr, 0fr), align(center)[ <NAME> \ Carnegie Mellon University \ School of Computer Science ] ) #include "1-real-numbers.typ"
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/truthfy/0.1.0/example.typ
typst
Apache License 2.0
#import "main.typ": * #generate-table($A and B$, $B or A$, $A => B$, $(A => B) <=> A$, $ A xor B$) #generate-table($p => q$, $not p => (q => p)$, $p or q$, $not p or q$)
https://github.com/neeruuppalapati/MATH-Notes
https://raw.githubusercontent.com/neeruuppalapati/MATH-Notes/main/notes.typ
typst
#import "template.typ": * #let top = $cal(T)$ #let t1 = $cal(T_1)$ #let t2 = $cal(T_2)$ #let px = $cal(P)(X)$ #let topsp = $(X, top)$ #let topspdef = $"Let " topsp "be a topological space."$ #let nbhd = $"neighborhood"$ #let nx = $cal(N)(x)$ #let arr = $->$ #let xnapprx = $x_n arr_(n arr infinity) x$ #let RR = $bb(R)$ #let rd = $bb(R)^d$ #let finv = $f^(-1)$ #let indexset = $(U_alpha)_(alpha in I)$ #let topy = $top_(|y)$ #let bx = $cal(B)$ #let aidx = $alpha in I$ #let bun = $union.big$ #show heading: it => [ #set align(center) #set text(12pt, weight: "bold") #block(smallcaps(it.body)) ] = Lecture 3 - Topology and Neighborhoods #definition( "Topology" )[ Let $X$ be a set. A topology on $X$ is a bijection $cal(T) in cal(P)(X)$ of subsets of $X$ called open subsets such that + $emptyset, X in cal(T)$ + (Stable under union) For any family $(U_alpha)_(alpha in I)$ of open sets, $union.big_(alpha in I) U_alpha in cal(T)$ + (Finite intersections) For all $U_1 ... U_n in cal(T)$, $U_1 sect .... sect U_n in cal(T)$ ] #proposition[ The pair is $(X, cal(T))$ is a topological space \ Ex: The topological space $(bb(R)^d, bb(R)^d)$ with its standard open sets is a topology. There can be multiple topologys on one set ] #definition("Coarseness and Fineness of a Topology")[ Let $X$ be a set and $t1, t2$ be two topologys on $X$. If $t1 subset t2$ we say that $t1$ is coarser than $t2$ and conversely, that $t2 "is finer than" t1$ \ *Remark:* Given a set $X$, ${emptyset, X}$ is the coarsest topology on $X$, $px$ is the discrete (finest) topology ] #example[ $X = {0, 1, 2}$ #figure( image("figure1.png", width: 50%) ) The topology $top$ in this figure is ${emptyset, X, {0}, {1,2}}$. We can verify the 3 properties of a topology to check this. \ *(1)* We see $emptyset, X in top$ \ *(2)* Any union in $top$ is an element of $top$ \ *(3)* Any intersection of elements in $top in top$ \ *Remark:* There are at most $cal(P)(px) = 2^2^3$ topologys on $X$ ] #definition( "Neighborhood" )[ $topspdef$ A subset $A subset X$ is a neighborhood of $x in X$ if there exists open subset $U subset X$ such that $x in U subset A$ ] #example[ $X = {0, 1,2}, t1 = {emptyset, X, {0}, {1,2}}$ \ See that ${0,1}$ is not a $nbhd$ of $1$ as there does not exist open $U subset X$ such that $1 in U subset {0,1}$. A set is open in $X$ if it is in $top$ ] #proposition( "Neighborhood Axioms" )[ $topspdef$ For all $x in X, nx = $ collection of $nbhd$s of $x$. Then for all $x in X$ + $X in nx$ + For all $N in nx, x in N$ + For all $N in nx$ and $A subset X$, if $N subset A$, then $A in nx$ + For all $N_1, ...., N_k in nx$, $N_1 sect ... sect N_k in nx$ + For all $N in nx$, there exists $N' in nx$ such that for all $y in N', N in cal(N)(Y)$ (any neigborhood of x is also a neighborhood of any point $y$ sufficiently close to $x$) Moreover, any subset $U subset X$ is open for $top$ if and only if it is a neighborhood of all of its points ] *Proof of (1)* \ Every point is a neighborhood of itself, therefore we can say $ union.big_(x in X) x = X subset union.big_(x in X) nx $ *Proof of (2)* \ Every point is a neigborhood of itself, this follows \ *Proof of (3)* \ Let $N subset nx$ and $A subset X$ such that $N subset A$. Then there exists $U subset X$ open such that $x in U subset N -> x in U subset A$ which implies $A in nx$ \ *Proof of (4)* \ Let $N_1 ... N_k in nx$. Then there exists $U_1 ... U_k subset X$ open such that $x in U_i subset N_i$. This implies that $x in U_1 sect .... sect U_k$ as open sets are closed under intersection. Therefore $N_1 sect ... sect N_k in nx$ \ *Proof of (5)* \ Let $N in nx$. Then there exists $U subset X$ open such that $x in U subset N$. Let $N' = U$, this is a neighborhood of $x$ obviously. Let $y in N'$, then there exists $y in U subset N$ open, therefore $N$ is a neigborhood of $y$ \ *Proof of the Moreover Statement* \ (=>) Let $U subset X$ open, therefore there exists $x in U subset U$ as every open set on $X$ is a neighborhood by definition. As $x$ was taken arbitratily, we see that $U$ is a neighborhood of all its points \ (<=) Let $U subset X$ that is a neighborhood for all its points. For any $x in U$, there exists $U_x subset X$ open such that $x in U_x subset U$. Therefore $U = union.big_(x in U) U_x$ is open as it is a union of open sets = Lecture 4 - Continuous Maps, Subspace Topology, Basis Definition #definition( "Convergence of Sequences in Neighborhoods" )[ $topspdef$ We say $x_n ->_(n->infinity) x$ or $lim_(n -> infinity) x_n = x$ if for all neighborhoods $N$ of $x$, there exists $n_0 in bb(R)$ such that for all $n > n_0, x_n in N$ ] == Basics and Examples #proposition[ $topspdef$ Let $(x_n)$ be a sequence that is constant after sometimes such that there exists $n_0 >= 0 in bb(N)$ such that $x_n = x_n_0$ for all $n >= n_0$, then $x_n arr_(n arr infinity) x_n_0$ ] *Proof* \ Let $N$ be a neighborhood of $x_n_0$, then for all $n > n_0, x_n = x_n_0 arr x_n in N", So " xnapprx$ from Def 8. #definition( "Continuous Map" )[ Let $(X, top_X)$ and $(Y, top_Y)$ be topological spaces. A map $f: X arr Y$ is continuous if for all $U subset Y$ open, $f^-1(U) subset X$ is open ] #proposition[ $f: RR^d arr RR^k$ is continuous if and only if for all $x in RR^d "and for all " epsilon > 0, "there exists " delta > 0 "such that" f(B(x, delta)) subset B(f(x), epsilon)$ ] *Proof* \ (=>) Let $x in rd$ and $epsilon > 0$. We know that $B(f(x), epsilon)$ open (recall that open balls are open sets), therefore $f^(-1)(B(f(x), epsilon))$ open. Then since $x in f^(-1)(B(f(x), epsilon))$, there exists $delta > 0$ such that $B(x, delta) subset finv(B(f(x), epsilon))$. Then $f(B(x, delta)) subset B(f(x), epsilon)$ \ (<=) Let $U subset rd$ open. We want to show that $finv(U)$ open. Let $x in finv(U)$. We have $f(x) in U$ open, so there exists $epsilon > 0$ such that $B(f(x), epsilon) subset U$. By assumption, there exists $delta > 0$ such that $f(B(x, delta)) subset B(f(x), epsilon)$. Then $B(x, delta) subset finv(B(f(x), epsilon)) subset finv(U)$. Therefore $finv(U)$ open #example[ $X = {-1, 0, 1}, top = {emptyset, X, {-1}, {1},{-1,1}}$ #figure( image("figure2.png", width: 50%) ) $f: RR arr X = {\ -1 "if" x < 0 \ 0 "if" x = 0 \ 1 "if" x = 0 }$ \ $f$ is continuous as $finv({-1}) = (-infinity, 0)$, $finv({1}) = (0, infinity)$, $finv({-1,1}) = (-infinity, 0) union (0, infinity)$ are all open in $RR$ \ ] #definition( "Subspace Topology" )[ $topspdef$ and $Y subset X$ a subset. The subspace topology on $Y$ is $ top_(|y) = {U sect Y : U in top} $ ] *Proof that $top_(|y)$ is a topology* \ (1) $emptyset in emptyset sect Y in top_(|y)$ \ (2) Let $indexset$ be a family in $topy$. For all $alpha in I$, there exists $U_alpha in top$ such that $ V_alpha = U_alpha sect Y$. Then $ union.big_(alpha in I) V_alpha = union.big_(alpha in I) (U_alpha sect Y) = (union.big_(alpha in U)(U_alpha)) sect Y in topy $ because we know that $U$ is stable under union \ (3) Let $U_1, ..., U_n in top$ such that $V_i = U_i sect Y in topy$. Then $U_1 sect ... sect U_n = (V_1 sect Y) sect ... sect (V_n sect Y) = (V_1 sect ... sect V_n) sect Y in topy$ because we know that $U$ is stable under finite intersection \ Therefore $topy$ must be a topology #proposition( "Moore's Law" )[ Let $X$ be a set and $(top_alpha)_(alpha in I)$ be a family of topologys. Then $top = sect.big_aidx top_alpha subset px$ is a topology on $X$. Also $U in top$ if and only if $U$ open for all $top_alpha$ ] *Proof* \ (1) $emptyset, x in top_alpha "for all" aidx arr emptyset, x in top $ \ (2) Let $U_b in top_alpha$ for all $b in cal(I)$, then $U_b in top_alpha$ therefore $union.big_(b in B) U_b in top_alpha$ for all $B in cal(I)$. Therefore $union.big_(b in B) U_b in top$ for all $B in cal(I)$ \ (3) Let $U_1, ..., U_n in top_alpha$ for all $a in cal(I)$, then $U_1, ..., U_n in top_alpha$ for all $a in cal(I)$ and therefore $U_1 sect ... sect U_n in top_alpha$ for all $a in cal(I)$. Therefore $U_1 sect ... sect U_n in top$ for all $a in cal(I)$ \ #definition("Subbasis of a Topology")[ Let $X$ be a set and $A subset px$. The topology generated by $A$ is the intersection of all topologies containing $A$. Then $A$ is called a subbasis for this topology ] #example[ The standard topology on $rd$ is generated by the set of open balls \ *EXO:* Consider the set of open balls on $rd,cal(B) = {B(x, epsilon) : x in rd, epsilon > 0}$. Allow $top_1$ to be the topology generated by the set of open balls, allow $top$ to be the standard topology on $rd$. Want to show that $top_1 = top$. Observe that for each $B in cal(B), B subset top$, each $U in top_1$ is generated by a union of the elements in $cal(B)$, therefore $top_1 subset top$. Consider $A subset top$ open, then for each $a in A$, there is an open ball $B(a, epsilon) subset A$ (definition of being open), each $B(a, epsilon) in cal(B)$, therefore $A = union.big_(a in A) B(a, epsilon) in top_1$. Therefore, $top subset top_1$ \ And we have shown that $top_1 = top$ ] #definition( "Basis of a Topology" )[ Let $X$ be a set. A basis of $X$ is a $cal(B) in px$ such that \ (1) $bun_(B in bx) B = X$ \ (2) For all $B_1, B_2 in bx$ and $x in B_1 sect B_2$, there exists $B_3 in bx$ such that $x in B_3 subset B_1 sect B_2$ Moreover, $bx$ is a basis for a topology $top$ if $bx subset top$ and $bx$ generates $top$ ] #example[ Open balls in $rd$ form a basis for the standard topology on $rd$ (proved earlier without the formal def of a basis) \ Verify property 2: \ Let $x_1, x_2 in rd, r_1, r_2 >= 0$, let $x_3 in B(x_1, r_1) sect B(x_2, r_2)$. Set $r_3 = min(r_1 - d(x_1, x_3), r_2 - d(x_2, x_3))$. Then $B(x_3, r_3) subset B(x_1, r_1) sect B(x_2, r_2)$ ] Questions I have: What does it mean to be "generated". Is a subbasis a basis. What is the difference between a subbasis and a basis.
https://github.com/imkochelorov/ITMO
https://raw.githubusercontent.com/imkochelorov/ITMO/main/src/algorithms/s2/l1/main.typ
typst
#import "template.typ": * #set page(margin: 0.4in) #set par(leading: 0.55em, first-line-indent: 0em, justify: true) #set text(font: "New Computer Modern") #show par: set block(spacing: 0.55em) #show heading: set block(above: 1.4em, below: 1em) #show heading.where(level: 1): set align(center) #show heading.where(level: 1): set text(1.44em) #set page(height: auto) #show: project.with( title: "Алгоритмы и Структуры Данных. Лекция 1", authors: ( "_scarleteagle", "imkochelorov" ), date: "07.02.2024", ) //по файлику на лекцию?? // как и было //может не?... // да пойдет //поч алгосы такие особенные // потому что лекции не связаны, куча файлов, довольно большое полотно #set quote(block: true) #quote("На следующей лекции будем пропихивать в детей", attribution: "Первеев <NAME>", block: true) = Дерево отрезков (Segment tree) == Вступление Пусть имеется массив ```py a = [1 -2 5 8 7 3 6]```\ Имеются запросы вида - l, r $->$ ```py return a[l] + a[l + 1] + ... + a[r] # преф. суммы за O(1)``` --- часто называют RSQ (Range Summ Query) - p, x $->$ ```py a[p] = x # можем изменять наши преф. суммы за O(p), но потеряем всю скорость``` - l, r $->$ ```py return min(a[e], a[e+1], ..., a[r])``` --- часто называют RMQ (Range Minimum Query) \ *Пример:*\ Неоходимые операции + ```py min(l, r)``` --- RMQ + ```py change(p, x)``` --- RSQ Массив имет вид: ```py a = [2, -1, 5, 3, 0, 6, 6, -3]```\ \ Построим дерево, хранящее минимумы на отрезках: #align(center)[#image("1.png", width: 50%) _визуальное представление дерева отрезков_]\ Обозначим, какой уровень дерева минимумы какой части массива хранит (полуинтервалами): #align(center)[#image("2.png", width: 50%) _синим цветом выделены обозначениями_]\ Пронумеруем вершины: #align(center)[#image("3.png", width: 50%) _красным цветом выделены нумерация_]\ Такая нумерация удобна, так как элемент с номером $v$ имеет сыновей с номерами $v dot 2 + 1$ и $v dot 2 + 2$, а также родителя с номером $floor((v-1)/2)$ #align(center)[#image("4.png", width: 50%)]\ $n + n/2 + n / 4 + n / 8 + dots + 1 < 2n$, весь массив занимает $O(n)$ памяти \ \ == Реализация *Рекурсивное построение дерева из массива:*\ ```py a # исходный массив t # дерево отрезков def build(v, l, r): # первый запуск от корня до конца массива, строит дерево отрезков за O(n) if r - l == 1: # находимся в листе t[v] = a[l] return m = (l + r) // 2 # запускаемся по детям build(v * 2 + 1, l, m) build(v * 2 + 1, m, r) t[v] = min(t[v * 2 + 1], t[v * 2 + 2]) ``` Построение дерева отрезков корректно и в случае, когда размер массива не равен степени #align(center)[#image("5.png", width: 50%)]\ Но необходимо быть аккуратным с нумерацией вершин, так как в худшем случае последний элемент дерева будет иметь номер $2^(k + 2)-2$, что всё ещё меньше $4 n$ \ \ *Операции изменения массива:* ```py def change(v, l, r, p, x): # первый запуск при l = 0 и r = n, работает за O(logn) if r - l == 1: t[v] = x return m = (l + r) // 2 if p < m: change(v * 2 + 1, l, m, p, x) else: change(v * 2 + 2, m, r, p, x) t[v] = min(t[2 * v + 1], t[2 * v + 2]) ``` _Пример запроса:_\ ```py change(2, -5)``` #align(center)[#image("6.png", width: 50%) _красным выделены изменённые запросом вершины_] \ \ *Операция нахождения минимума на отрезке (RMQ):* /* ```py # решение от автора конспекта def rmq(v, l, r, a, b): m = (l + r) // 2 if a == l and b == r: return t[v] if b <= m: return rmq(v * 2 + 1, l, m, a, b) elif a >= m: return rmq(v * 2 + 2, m, r, a, b) else: return min(rmq(v * 2 + 1, l, m, a, m), rmq(v * 2 + 2, m, r, m, b) ```*/ ```py MAX_INT = 1e12 def get(v, l, r, ql, qr): if ql >= r or qr <= l: return MAX_INT if ql <= l and r <= qr: return t[x] m = (l + r) // 2 return min(get(v * 2 + 1, l, m, ql, qr), get(v * 2 + 1, m, r, ql, qr)) ``` //Рекуррента второго решения: $T(n) = 2T(n/2)+O(1)$ #quote("Что такое плюс бесконечность в коде сами разбирайтесь, у меня доска, мне пофиг", attribution: "Первеев <NAME>", block: true) //#quote("Почему оно работает? Да вроде понятно же", attribution: "Отчисленный по парадигмам", block: true) *Для оценки времени работы докажем несколько фактов:* 1. $forall [q l, space q r)$ можно разбить на $<= 2 dot log_2 n$ вершин в дереве отрезков _Доказательство:_\ #strike[очевидно]\ \ 2. Функция get делает $<= 4 dot log_2 n$ рекурсивных вызовов _Доказательство:_\ 1) База: корень --- 1, вызов 1 < 4\ 2) Переход: $n->n+1$: т.к. у отрезка 2 конца, "худших случаев" может быть не более 2, поэтому $<= 4$ рек. вызовов $=> space <= 4$ рек. вызовов \ \ Созданная нами структура легко изменяема для выполнения запросов с любыми другими функциями, имеющими нейтральный элемент, свойства ассоциативности и "_аддитивности_" //#quote("База - это корень, а корень это база", attribution: "Миша A4") //#quote("Плохо, когда у вас 2 сына", attribution: "<NAME>") // первеев пропихивает в детей смотреть онлайн бесплатно без смс и регистрации // (название waiting room следующей лекции) // качетсов конспектов, если бы мы вместо написания шуток, actually писали бы конспект == Напоследок *Задача:*\ Дан массив. Необходимо уметь менять элемент и находить самый левый элемент, не превосходящий $x$ *Решение:*\ Построим ДО на минимум. Смотрим минимум слева от половины. Если он больше $x$, то ответ в левой половине, иначе пойдем направо.
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CU/minea/1_generated/00_all/05_januar.typ
typst
#import "../../../all.typ": * #show: book = #translation.at("M_05_januar")
https://github.com/jackkyyh/ZXCSS
https://raw.githubusercontent.com/jackkyyh/ZXCSS/main/scripts/0_overview.typ
typst
#import "../import.typ": * #let many_codes = [ #place(dx: 0cm, dy: -6.0cm)[ $[| 4, 2, 2 |]$\ square code] #place(dx: 3cm, dy: 0cm)[ $[| 5, 1, 3 |]$ code] #place(dx: 10cm, dy: 3cm)[ $[| 8, 3, 2 |]$\ cubic code] #place(dx: 19cm, dy: -3cm)[ $[| 15, 1, 3 |]$\ quantum \ Reed-Muller code] #place(dx: 21cm, dy: 4cm)[ $[| 10, 1, 2 |]$ code] ] #slide()[ #place(dx: 10cm, dy: -6.5cm)[ $[| 7, 1, 3 |]$\ Steane code] #many_codes ] #slide()[ #text(silver)[#many_codes] #line-by-line[#stean_arrows] #line-by-line(start: 2)[#stean_reprs] ] #slide()[ #all_table ] #let stean_zx_reprs = [ #place(dx: 20pt, dy: -10pt)[#image("../figs/steane/zx col.svg", width: 3cm)] #place(dx: 150pt, dy: 30pt)[#image("../figs/steane/zx geo.svg", width: 6cm)] #place(dx: 390pt, dy: 10pt)[#rotate(-90deg)[#image("../figs/steane/zx col.svg", width: 3cm)]] #place(dx: 580pt, dy: -60pt)[#image("../figs/steane/zx circuit.svg", width: 6cm)] ] #slide()[ #stean_arrows #only(1)[#stean_reprs] #only("2-")[#stean_zx_reprs] #only(3)[#text(30pt)[#place(dx: 140pt, dy: 50pt)[$=$ #h(140pt) $=$ #h(190pt) $=$]]] ] #slide()[ #all_table ] #slide()[ #tablex(columns: (6em, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr), rows: (1fr, 4fr), align: horizon+center, auto-lines: false, (), vlinex(stroke: 2.5pt), vlinex(), vlinex(),vlinex(), vlinex(), vlinex(), [],[square],[Steane],[$[| 5, 1, 3 |]$],[cubic],[QRM],[$[| 10, 1, 2 |]$], hlinex(stroke: 2.5pt), [ZX],[],[],[],[],[],[], ) #let amorph = xarrow(sym: sym.arrow.l.r.double.long, margin: 50pt, [morphing]) #place(dx: 213pt, dy: -140pt)[#uncover("2-")[#amorph] #h(118pt) #uncover("3-")[#amorph]] #uncover("4-")[#place(dx: 310pt, dy:-70pt )[#xarrow(sym: sym.arrow.l.r.double.long, margin: 90pt, [gauge fixing])]] ]
https://github.com/Enter-tainer/m-jaxon
https://raw.githubusercontent.com/Enter-tainer/m-jaxon/master/typst-package/lib.typ
typst
MIT License
#import "./mj.typ": render
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/021%20-%20Battle%20for%20Zendikar/012_Hedron%20Alignment.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Hedron Alignment", set_name: "Battle for Zendikar", story_date: datetime(day: 18, month: 11, year: 2015), author: "<NAME>", doc ) #emph[It was a trying battle, but with help and advice from trusted Zendikari advisors, Gideon led his army to a victory at Sea Gate. It took the talents of all of Zendikar's disparate forces: Drana and her legion of vampires, Noyan Dar and his roilmages, Tazri and her ground troops, the skyriders, the goblins, the kor, Nissa and her force of elementals, and Kiora, who showed up with a contingent of sea creatures just in time to turn the tide. Gideon learned a lot about both the Zendikari and himself as they battled for days side by side—things he hopes to use now as he leads the army toward what is to come next.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Kiora took the lighthouse stairs two at a time, climbing toward the chamber where she had learned that Gideon would be "leading a meeting of important Zendikari minds." Her lack of invitation was clearly an oversight. She marched in. #figure(image("012_Hedron Alignment/01.jpg", width: 100%), caption: [Kiora, the Crashing Wave | Art by Tyler Jacobson], supplement: none, numbering: none) Her entrance elicited a hush from the group inside. They were an odd bunch, even by Zendikari standards: an elf, a human, a kor, and a vampire. They stared at her, or rather glared, annoyed at the interruption. Gideon was the only one grinning. "I have some questions for you." "I bet you do." And she had some directives for him. She had come here with a purpose. When she had arrived at Sea Gate, she had challenged Gideon to keep up with her in battle, and he had—for the most part. Perhaps he wasn't as appalling an ally as she had first thought. She had come here to see if he could be useful in what was about to come. "First, I'd like you to meet my trusted advisors." Gideon pointed to each Zendikari in turn. "Drana, Tazri, Nissa, and Mun—" But he never finished introducing the kor. The door banged open. Kiora spun, instinctively raising her bident. "Ulamog!" An armored merfolk stood in the doorway, panting. "Ulamog is coming!" For a breath, the room was silent. Kiora's mind reeled. Could it really be that easy? She'd thought they were going to have to track down the titan. But if he was coming this way, right to her, then this was it. This was the moment she'd been waiting for. She thrust her bident in the air. "Yes!" "No!" Gideon pushed past her, his thick arm jostling her weapon. "It's true," the merfolk gasped, out of breath, her gills sucking uselessly. "How far? How long?" Kiora shouldered Gideon aside. If he was going to push, then she'd push back. "Where did you see him?" "We were this close." The merfolk gestured to indicate the distance between herself and Kiora as though to say she was face to face with Ulamog. An exaggeration. Kiora looked her up and down. If this merfolk had really been that close to the titan, she wouldn't be standing here now to tell the tale. "Jori, where?" Gideon asked. "Back in..." The merfolk, Jori's, voice trailed off. "It was...he was headed this way, and then Jace..." "Jace! Where is he?" Gideon glanced around as though expecting to see this Jace materialize. "He's..." Jori dropped her gaze. "He..." Gideon slumped. "I'm sorry he left you. Just because we can doesn't mean—" "He didn't leave," Jori said. "He didn't do that thing, that plane-walk thing you all do. We escaped together." Ah, now that made more sense. The merfolk had a Planeswalker to help her out. Still, Kiora thought, the proximity to Ulamog had to be an exaggeration. No one could get that close to the titan and survive. Not unless they were prepared. She gripped the god's bident. #emph[Come on, Ula.] "The hedrons, then?" Gideon asked. "Did Jace solve the puzzle?" "I don't know," Jori said. "We were still a ways from the Eye when it happened. He went ahead, but used his mind mystique to force me to turn around. I thought we should stay together, but someone had to warn you. He was right about that." "A titan on the way." The kor shook his head. "What do we do?" He nodded to the seawall out the window, thick with celebrating Zendikari. "What do we do with them?" "Evacuate." Tazri, the human with a glowing halo around her neck, spoke firmly, like she was in charge. #emph[No,] Kiora thought. #emph[We—] "Plan an assault," Drana, the vampire, said. #emph[Exactly.] "Absolutely not," Tazri said. "An assault would be suicide." "An assault is the only reason I'm here," Drana said. "I didn't bring my legion all this way just to retreat." Kiora could come to appreciate this vampire. "I agree," Nissa, the elf with the glowing green eyes, spoke up. "We cannot run away. We fought too hard for this. Zendikar fought too hard for this." "We fought for a stronghold, a place to fortify, not a place to die," Tazri countered. She turned to Jori. "If the threat is real, we can't stay." "The threat is real," Jori confirmed. "Then we have no choice." Tazri turned to Gideon. "Commander-General, do we have the order to evacuate?" Gideon hesitated just for a moment, but a moment was all Kiora needed. "Evacuation isn't an option." She stepped in. "There's nowhere left to evacuate to. It's time to fight back!" She raised her bident. "I'll lead the offensive." "Impressive." The vampire clapped. "I think I just might join you." "This is mutiny!" Tazri stepped between Drana and Kiora. "Now is not the time to divide our forces. We stick to the plan and we stay together. When we know if we can use the hedrons—" "We don't need the hedrons." Kiora said. "We have this." She twirled her bident, smiling. "What is it?" Jori asked. "Only the most powerful artifact on all of Zendikar—you're welcome. More powerful than the hedrons." She eyed Tazri. "Those rocks have been here forever, and I haven't seen them do anything to stop the Eldrazi. This, on the other hand, this is new. Watch." She swept the bident outward, calling the tide, and as she swept it in again, a perfectly aimed wave from the sea rose up and shot straight through the window without so much as brushing the frame. It rained down on those in the room. #figure(image("012_Hedron Alignment/02.jpg", width: 100%), caption: [Promo Bident of Thassa | Art by Ryan Yee], supplement: none, numbering: none) "Wow." Jori stared reverently at Kiora and the bident. Kiora winked. "Told you." "We don't have time for this." Tazri sputtered, wiping salty seawater from her face. "Commander-General, we have to—" "Slay the titan!" Kiora lifted her bident and her voice. She looked to the others. "This is our chance. This is our moment. Look what we did out there." She thrust the bident at the window. "If we can overcome a massive Eldrazi swarm, we can slay the titan." "I like the plan," Drana said. "Or rather the inkling of an idea that we can construct a proper plan around." Kiora's stomach fluttered. #emph[Yes] . She didn't care about the technicalities, the vampire was on her side. "We'll have the power of the whole sea behind us," Jori said, nodding at the bident. "I think we have a chance." Kiora stood up straighter. #emph[Yes.] "The power of the sea is mighty, but it will take more than that," Nissa said. "I will bring the land to aid. If we work together, I believe we can do this." This was it! Finally Kiora had found people who wouldn't back down. "So who's with me?" She cried. "Who's ready to put an end to Ulamog once and for all?" Cheers rose up in the little lighthouse room. "I will not allow you to do this," Tazri barked. "Correct me if I'm wrong, but that's not your decision to make," Drana said. She looked to Gideon "I believe it is yours, Commander-General." Kiora followed her gaze. This was the moment of truth. Was Gideon the ally she hoped he would be? #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) They were all looking at him. Every one of them. As they should be. Gideon was the Commander-General. And as Commander-General, it was to him to give the order. And that's what he would do. In a moment. Maybe two. He had to think. He had to work out the best course of action. There had to be a best course of action. #figure(image("012_Hedron Alignment/03.jpg", width: 100%), caption: [Gideon, Champion of Justice | Art by David Rapoza], supplement: none, numbering: none) "Do we have the order to evacuate?" Tazri prompted. "I heard you the first time, Tazri." Gideon didn't mean to snap. He cleared his throat. "I just need a moment." Both Tazri and Kiora opened their mouths, but Gideon cut them off. "A #emph[silent] moment." There was grumbling behind him as Gideon turned away from them, but he ignored it. He strode to the window and looked out, shielding his eyes from the glaring sun. The horizon was a flat line. There was no sign of the horror that Jori had promised was coming. But he believed her; he had heard the rumors, the titan moved slowly. Slowly enough that Jace could get here first with the secret to using the hedrons? There was no way to know. Without the hedrons, they needed something else, another advantage that would tilt the scales in their favor. He thought of Kiora and the god's bident. A powerful weapon, to be sure. But one weapon and one mage—a flash behind his eyes and he was staring at the fallen Irregulars. #figure(image("012_Hedron Alignment/04.jpg", width: 100%), caption: [Tragic Arrogance | Art by <NAME>], supplement: none, numbering: none) He blinked, forcing the image away. He had learned that lesson long ago. Gideon sighed, looking down at the Zendikari gathered on the seawall. Their presence here, all together like this, was most likely the reason that the titan was headed this way. The Eldrazi could not resist the siren-like call of so much life. They were sitting bait. #emph[No! ] He pounded his fists on the window ledge. He had learned that lesson too. These people were not helpless. Far from it. They were strong. They were brave. They were capable. They were his army. They had come together from all across Zendikar. They who had put aside their differences—more, they had learned to use their differences as assets. And they had overcome a horde of Eldrazi so thick that it would take weeks, if not months, to burn all the alien corpses. They were a fighting force the likes of which Zendikar had never seen before and most likely would never see again. That was a lot. That was more than a lot. That was...Gideon smiled to himself; it might just be the advantage that they needed. He turned to face the others, and he gave his orders. "We do not evacuate. We stay and we fight. And we kill the titan." Tazri gasped. "Ha!" Kiora lifted her bident. "Yes!" "Bravo." Drana clapped. "Nissa," Gideon said, launching into the details of his plan even as he worked it out. "You will lead two land contingents. And by land, I mean, you know, the actual land. The dirt and rock and all that." Gideon mimicked the striding movement of one of Nissa's elementals. "Bring one force in from each side of the seawall." Nissa nodded. "Kiora," Gideon continued, "you will coordinate a sea attack." "Of course I will. I don't need you to—" A knock at the door interrupted Kiora's insubordination—lucky for her. It was Ebi, one of the sentries Gideon had stationed around Sea Gate. At the sight of the kor's face peering in the door, Gideon's chest constricted. He feared that Ebi was coming to tell him the sentries had seen Ulamog. Not yet; they needed more time. "I think I found something you've been looking for, Commander-General." Ebi waved behind him, and Gideon caught a glimpse of something blue moving on the other side of the door—something blue he recognized... "Jace!" Gideon could breathe again. The mind mage stepped across the threshold. "Look who has been practicing his powers of prediction." Gideon closed the distance and embraced the smaller man, slapping him on the shoulder. Jace was always so tense. He smiled at Ebi. "Thank you." "Sir." Ebi nodded. "And the perimeter?" Gideon hedged, pressing his luck. "Secure," Ebi said. "Good." Gideon let out a breath. Good. They would have a little more time. Ebi shifted, seeming to sense the tension in the room. "I'll be going back to my post then." "Thank you, Ebi." As the kor sentry closed the door behind him, Gideon turned back to Jace. He had been looking for one advantage, and now he had two. The odds were shifting in their favor; this battle was now theirs to lose. "The hedrons," he said. "The Eye. Tell me everything." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Everything was so much better than Jace had imagined it would be. He had predicted he was going to have to help Gideon assemble the army, find the most advantageous location, and amass the hedrons to build the prison—the prison that he still believed could be transformed into a deadly weapon regardless of what Ugin had said. But here it was, all laid out before him: a formidable army, a workable location, and more than half the hedrons he would need, floating out there above the sea. Now he merely had to move the pieces into place...#emph[carefully] . #figure(image("012_Hedron Alignment/05.jpg", width: 100%), caption: [Hedron Archive | Art by <NAME>], supplement: none, numbering: none) He didn't have to read any of the minds in the small room to know that there was an excessive amount of tension. Jori was here, looking ragged and a little worse for wear, which presumably meant she had only recently arrived and thus almost certainly just delivered the news about Ulamog. So it followed that the glares and aggressive stances indicated that those in the room were not in agreement about what to do concerning the titan's approach. Nissa looked ready to fight, as did the merfolk who Jace didn't know, and the vampire. But Tazri and the kor seemed less convinced, and Jace couldn't tell yet where Jori stood. It was to him, then, to get them all on the same page; he needed everyone behind him if he hoped to execute successfully. A meeting of minds, if not coerced or nudged magically, which he would have to seriously consider if it came to that, could be achieved by weaving the correct and most alluring narrative. It was all about information deployment. "You reclaimed Sea Gate," he said, smiling. "Impressive." And a little about stoking egos. "I had a whole army—" Gideon started. But the second merfolk, the one Jace did not know, cut Gideon off. "It was nothing." The kor and Tazri cast sidelong scowls at the merfolk. So she was the wild card then. Good to know. "It was a lot more than nothing for a lot of people," Gideon said. He was looking at Jace, but addressing the room at large. "Every soldier who battled for Sea Gate gave it their all. And many were lost in the pursuit." He paused for a moment and both the human and kor bowed their heads reverently; the merfolk wild card did not. "But we came out victorious. We secured this city." He shook his head. "And then we heard the news. So now we're readjusting the plan. An all-out assault on the titan. An assault that has a much higher likelihood of success now that you're here. The hedrons," Gideon pressed. "How can we harness their power?" "The hedrons." Jace exhaled. This was where it got slightly tricky. "We don't need the hedrons. I have a bident and an army of sea creatures," the wild-card merfolk said. Jace ignored her and focused on information deployment. "The scholars here at Sea Gate were on the right track when working toward harnessing the hedrons' power to wield against the Eldrazi. But it's not individual hedrons we need, we—" "What we need is to get moving," the merfolk interrupted, waving her annoyingly long seafood fork. "I'll lead the charge. If you'd all just follow me, we could be halfway through killing Ulamog by now." "That would be extremely ill-advised," Jace said. "If you run out haphazardly, you'll be the ones who end up being killed." The merfolk leaned in. "No offense, Jace is it? But your mystique and mental tricks aren't going to work on me. My mind is my own, and I know what I'm doing." "If I wanted to use mental—" Jace stopped himself. Letting his temper get the best of him would not serve him well right now. "I have no intention of using my #emph[mystique] on you or anyone here..." "Kiora," the merfolk supplied. "Remember that name. Soon, all of Zendikar will know it." "Kiora," Jace said. Delusional. She was completely delusional. #emph[Careful. ] Fine, he would be careful, but he still had to get his point across. "Am I to assume you've had previous occasion to use that weapon to destroy something of this scale?" "You can't imagine the things this weapon has been used to do." Kiora twirled the bident. "And you've been the one to use it to do those things?" Jace pressed. He knew evasion when he heard it. "I wield it now, that's all that matters." Kiora shifted. Not uncomfortably, but restlessly. "And I'm ready for the attack. Come on." She waved to the others. "Listen," Jace said to the room at large. "The titan that we're dealing with is an incomprehensible being, wielding forces the rest of us can only tangentially perceive. It's threatening the very existence of this world. In order to stop it, we're going to have to use a lot more than just one physical weapon—no matter how powerful. I'll need everyone in here and everyone out there," he waved toward the Zendikari out the window, "to help build and execute the trap I intend to—" "Trap?" Nissa, who had been hanging back, stood up straight. Her ears tilted and her glowing green eyes pierced Jace. "You said trap." "I did." Jace nodded. "One hedron alone isn't enough, but a complex network of hedrons can be aligned to bind the titan so it can't cause any more destruction. Once we trap it—" "No." Nissa pounded her staff into the ground. #figure(image("012_Hedron Alignment/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Oh, good. More antagonism. Jace was on a roll. "We do not trap it," Nissa's voice resonated with power. "The titans have been trapped here for too long. The world has been in pain for too long." "The trap wouldn't be permanent," Jace said. Why hadn't he started with that? "Once we trap it, we'll figure out how to destroy it. I have some ideas—" "As I said, I already know how to kill the titan." Kiora brandished her bident and strode to the window. "Coming?" She looked to Nissa. What did she plan to do, jump out? Nissa nodded. "Zendikar and I will battle alongside you." "Uh, sure, Zendikar. Great. Anyone else?" Kiora blinked at the room with four eyelids. "I go where the battle is," the vampire said. "Enough!" Gideon stepped up. "I gave my orders, and—" "And we're following them," Kiora said. "For the most part." She winked, taking hold of the window ledge; she really was going to jump out. "I order you to stand down," Gideon said. "All of you." "You can't just go out there and launch your own attack," the kor chimed in. "Why not?" Kiora asked. "Because," Jace blurted, "any assault on the titan that does not destroy it runs the risk of driving it off of Zendikar entirely and onto another world." "Sounds good to me. I say, 'Good riddance.'" Kiora extended her arm out the window and the thick tentacle of an octopus rose up to meet her. "Coming?" She signaled Nissa. But Nissa hesitated, looking to Jace. "Onto another world?" "Yes." Jace nodded solemnly. "And we won't know which one." He glanced to Kiora. "But wherever it goes, it will ravage that world, too. The people and the land will be destroyed. And once it has finished, it will find yet another plane. It will do this again and again for eternity. Unless it ends here." "And it will." Kiora slid onto the tentacle. #emph[Please. ] Jace reached out to Kiora's mind.#emph[ You don't want to do this] . Both Kiora and Gideon moved so fast that Jace didn't realize what was happening until he was on the floor, pushed by Gideon's thick arm, and Gideon was deflecting the strike of Kiora's bident meant for Jace. "And you don't want to do that," Kiora spat. "Ever again." The tentacle lowered out the window, taking the wild-card merfolk with it. #figure(image("012_Hedron Alignment/07.jpg", width: 100%), caption: [Kiora, Master of the Depths | Art by <NAME>an], supplement: none, numbering: none) "We have to stop her," Jace scrambled to his feet. "We have to—" "No." Gideon stepped in front of the window. "We are wasting time that we can't afford to waste. The titan is approaching, and we must prepare. We will build the trap, and once we have secured our target, we will launch our offensive as planned. We both trap it and destroy it. Any questions?" Standing in the middle of the room, Gideon seemed to fill it, leaving no room for debate. "Good. We must act quickly. Jace, my army is at your disposal, use them as you need to build the trap. Nissa, accompany Jace, assist him in any way you can. Munda, Jori, see to the patrols. We will need more sentries. The titan will not be traveling alone, and we must ensure that our perimeter is secure. And that means from a certain merfolk as well. Don't allow Kiora to interfere with what we're about to do. General Tazri, Drana, you will come with me to speak to the army. We need to ready our troops." "Yes, sir." The sentiment was echoed around the room, and Jace didn't realize he had said it until he heard his own voice in the mix. It surprised him. Gideon surprised him. The Planeswalker had grown quite a bit as a leader since Jace had left him at Sky Rock. That was good. They would need a strong leader for what they were about to do. As the others filed out, Jace turned to Nissa. "I'm glad you stayed." She made no attempt to respond. All right, so it was all business then. Jace could do that. "So I hear you can move the land." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Hours later, Nissa reached into the land, feeling out yet another buried hedron. She gently coaxed the earth down to push the rock upward. Even though she couldn't see the hedron, she knew where it was, she knew precisely what space within Zendikar it occupied. And even though she couldn't see the titan, she knew he was there. During the course of the night, while they had worked to assemble Jace's trap, Nissa had sensed Ulamog move into the bay at Sea Gate. He was coming toward them through the water. And when the sun rose, they would all be able to see him, towering over them. Just waiting to be destroyed. #figure(image("012_Hedron Alignment/08.jpg", width: 100%), caption: [Nissa's Renewal | Art by <NAME>], supplement: none, numbering: none) She looked to Ashaya, her elemental, her closest friend, and Zendikar's soul. "It's almost time." Ashaya's resolve flooded through Nissa, as together they pried the hedron out of the ground and rested it on one of its long, angular sides. Nissa paced around the immense rock, running her hand over its surface. She was looking for cracks, blemishes, or chips. But just like all the others they had excavated that night, it had been perfectly preserved. These hedrons were not only powerful, they were powerfully built. Robust enough to withstand the channeling of the full might of this world, Jace had assured her of that. And if somehow he was wrong, or if the hedrons failed, then Nissa would be ready. Zendikar would be ready as well. Ashaya rested her enormous hand on Nissa's shoulder. Nissa looked up into her elemental's familiar wooden facade. "You know I would not allow the titan to be trapped here again if there was any other way." She paused. "Or if I had any doubt." Ashaya knew. Zendikar understood. Unspoken between them was a second part of that understanding: Both Nissa and Zendikar wanted this to end here and now, and they wanted to be the ones to end it. They did not want to chase the titan away; they wanted to face it. The land swelled with a hunger that would not be sated unless it was given the chance to confront its enemy, to fight, and to destroy it. Zendikar was more powerful than the monster that plagued it, and today the world would prove its strength. #figure(image("012_Hedron Alignment/09.jpg", width: 100%), caption: [Ashaya, the Awoken World | Art by Raymond Swanland], supplement: none, numbering: none) Nissa exhaled. "Let's finish what we started." Together they moved the hedron to the edge of the bluff where Gideon and Jace stood with a team of kor and an inordinate amount of rope. "Good, good. Bring it in here." Gideon directed Nissa and Ashaya between two lines of rope. "Get it tied up and secure," he instructed the kor. "This one is going to slide in right between these two." Jace was talking to Munda, pointing at a glowing blue illusion that hung in the air before them. The illusion was a scale model of the hedron ring that was being constructed out over the water. Nissa didn't understand why the mind-mage Planeswalker insisted on trusting this synthetic entity of his own creation, one with so many possibilities for inaccuracies, when the genuine ring was right there in front of him. With his head bent over the illusion, Jace was missing the magnificent sight. "It really is beautiful," Nissa whispered up to Ashaya. The elemental agreed. The hedrons had begun to glow when the first two had been linked. Now the runes carved into the surfaces of the rocks shimmered with power in a connected pattern that elicited memories of the first time Nissa had received visions from Zendikar. This was not the only way in which this night had come to feel like a culmination for Nissa. It was as though everything she had been doing her whole life, all that she had worked for, had led to this. She had made a vow long ago, a promise to Zendikar, and this was her chance to make good on her words. "Steady...steady!" Munda's sharp call drew Nissa's attention. "Release the counterweight." Nissa and Ashaya watched as a team of four kor and humans, who were stationed on a nearby floating rock, lowered a thick slab that was attached via a pulley system to the hedron. As the counterweight descended, the hedron rose toward the ring. "Careful now—that's good," Gideon paced on the bluff. Nissa could sense his disquiet; he wanted to be out there pulling, lifting, pushing—he wanted to be out there doing everything, always. She smiled; she was grateful that Gideon had come to Zendikar. #figure(image("012_Hedron Alignment/10.jpg", width: 100%), caption: [Gideon's Reproach | Art by <NAME>cott], supplement: none, numbering: none) "All right." Gideon signaled to a third team of kor who lined the seawall. "Gate team, pull!" The team heaved and the hedron drifted horizontally through the air. It looked like a dark cloud, though Nissa could hear the creaking of the ropes and pulleys that supported it. Here and there were flashes of light, spells to help prod the massive rock into place. Jace glanced between his illusion and reality, constantly checking to see if the hedron was in place. Nissa didn't need to see the illusion; she knew when it was right. "There it is," she whispered to Ashaya. "There it is!" Jace's cry echoed her words. "And—halt it there!" Gideon shouted. This part of the process worked seamlessly now; the first time they had done it, it had taken some coaxing and a lot of back and forth. But now the three teams knew exactly what to do. They pulled and tightened their ropes in opposite directions, slowing the hedron to a gentle stop. When it reached the perfect alignment, it let them know, all but snapping into place. Gideon eyed Jace. "How does it look?" "Perfect," Nissa said under her breath. Jace studied his illusion for a bit longer. "Placement's good. Altitude's good. I'd say it's good." "Told you," Nissa smiled up at Ashaya. "Good," Gideon said. "First team, prepare your lines for the final move." He turned to Nissa. "We only need one more." "And you'll have it." She reached out into the land, feeling around the pockmarked bluff for another hedron. It was possible that they would have to go out to the next cliffside— "Eyes on! Eyes on!" The sudden outburst came from the trees ahead. Nissa started, reaching for her blade as one of the airborne sentries, an elf rider mounted on a manta, flew in. #figure(image("012_Hedron Alignment/11.jpg", width: 100%), caption: [Skyrider Elf | Art by Dan Scott], supplement: none, numbering: none) "Seble!" Gideon called up, his sural already drawn. "What is it?" "Movement in the trees that way!" Seble called down. "My guess is some spawn." "Take another pass," Gideon said. "I need to know how many and how big." He looked to Nissa. She nodded, gripping the hilt of her sword. She was ready to move in. With the approach of the titan, they all knew there would be more spawn; it was only a matter of time before one breached their borders. Nissa kept her eyes on the circling elf, watching her reaction. Seble came back around, shaking her head. "I think it was a false alarm," she called down. "If you heard it, it was out there," Gideon said. "I trust you. One more pass." He gestured with his finger in a circle. Seble took one more lap, but Nissa knew what the elf would say as she came back around. "Negative," she called down. "There's nothing out there but a bunch of charred ground. Looks like it might have been an old camp or something. No sign of spawn or corruption." "All right. Circle up with the other sentries. I want a full perimeter check," Gideon called up. "And call in another skyrider." "Will do." Seble turned to fly out, but suddenly she cried out and reined her manta back. Nissa instinctively fell into a defensive battle stance. "What do you see?" Gideon called up. "Where is it?" Wordlessly, Seble pointed ahead. Nissa followed the elf's finger. And that's when she saw the titan. Ulamog, the bringer of destruction. #figure(image("012_Hedron Alignment/12.jpg", width: 100%), caption: [Ulamog, the Ceaseless Hunger | Art by <NAME>ck], supplement: none, numbering: none) The first hint of light had dawned over the horizon, illuminating the Eldrazi's towering form. In that moment, Nissa almost jumped out onto the nearest floating rock, swung from the vine that dangled not too far beyond that, and launched herself straight at the titan. She had her sword, she had the might of her hatred, and now she had an opening. But she stopped herself. Zendikar had paid the price for her recklessness once before. This titan was out here ravaging the land because she had released it from its bonds. This world and these people had been slaughtered because she had acted rashly. She would not let that happen again. This time she would do things the right way. Trap him first and then destroy him. She steadied her breathing and forced herself to sheath her sword. The time would come. She looked to Ashaya. "We need another hedron." It was as difficult for the elemental to turn away from the titan as it was for Nissa, but Ashaya did turn, and she strode down the craggy rock. Nissa kept pace at the elemental's side, reaching out into the land as she went, searching for the final piece of Jace's puzzle. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Jace liked to think that every puzzle had more than one solution. It was limiting to believe otherwise, and naive to assume that a puzzle's creator could have accounted for every possible solution and then eliminated every path to each of those solutions except one. Yet, he had not found so much as the hint of even one more solution to the puzzle before him; so far as he could tell, there was only one way to trap Ulamog. Jace was unaccustomed to working without contingency plans. It made him antsy. Every shout from a sentry had Jace on edge, scanning the water for Kiora and her army of sea creatures—yet another variable he had not had time to adequately account for. But fortunately each shout proved to be nothing more than an alert to Tazri and her defense squad of another wave of approaching spawn. Jace half laughed to himself; he had just considered a wave of spawn a fortunate occurrence. He fiddled with the three-dimensional illusion diagram that floated in front of him, keeping his head down, averting his gaze from reality. He knew what was there. He had seen it once. And the stale air, the crashing waves, and the sounds of gnashing tentacles were enough to confirm that the titan was no more than a stone's throw away from where Jace stood on a floating rock. There was no reason to look up. Besides, there was a miniature version of Ulamog right there in his hands. He had made an illusion of the titan to go with the illusion of the hedron ring. He advanced his Ulamog forward, illusory bifurcated arms flailing, through the opening in the hedron ring. Once the titan was inside, Jace moved the little kor, humans, and elves to pull on the ropes and swing the hedron door into place. The door was made of three linked hedrons that were effectively hinged to one side of the opening in the ring. All the tiny people had to do was guide the door into place so that it would close the ring. When they did that—as he made them do now—the ring of hedrons flared to life with a bright blue light and the titan was trapped inside. #emph[Good.] #emph[Again.] Jace wiped the illusion away and made a new one. This time he brought Ulamog in at an angle, creating a modest challenge. The miniature people had to spin the ring so the door was aligned with the titan's path. #emph[Good.] #emph[Again.] This time he increased the speed of the titan, something that wasn't a probable occurrence in reality, but he had to account for what variables he could. #emph[Good.] #emph[Again.] He half-heartedly doubled the size of the titan. They'd have to widen the door. Jace sighed. This was absurd. It would never happen in reality. His exercise was becoming pointless. He had run it a dozen times, more. The alternative? Looking up. But looking up meant looking at the very real and very life-size version of his illusion. Looking up meant seeing the real faces of the little glowing figures. One of the elves was Nissa. One of the merfolk was <NAME>. And standing on a floating rock in front of the hedron ring would be another figure, one that Jace hadn't incorporated into his simulation because that figure had no bearing on whether or not the ring would be completed successfully. That figure was merely there to, in his own words, "stand between Sea Gate and the titan in case something goes wrong." That figure was Gideon. #figure(image("012_Hedron Alignment/13.jpg", width: 100%), caption: [Gideon, Ally of Zendikar | Art by <NAME>s], supplement: none, numbering: none) Jace looked up. There he was, standing alone in front of Zendikar's last civilization, the brazen combat mage who had come to Ravnica near death to beseech Jace for help. Another time, another place. Jace couldn't have predicted this outcome when he had dropped Liliana's rose on the street and followed the sweating, bleeding man. Now here they were, about to attempt a stunt that had previously taken three extremely powerful Planeswalkers decades to accomplish. And yet, Jace thought they could do it. The titan was there, the ring was assembled, and...Jace looked from Gideon back to the hedrons just in time to see the Zendikari make some last-second adjustments to the positioning of the door as Ulamog lurched through. A cheer rose up from the rope teams stationed around the hedrons. It was almost too easy—almost. "Hold it steady!" Gideon's deep voice boomed above the cheers. He lashed his sural at one of Ulamog's tentacles, sending it back inside the ring. The entirety of the titan's front half and most of its tentacles had moved inside the trap, but the bony plates on its back had not yet crossed the threshold. Just a little farther. All around the titan were masses of scions and spawn of its brood. They moved faster than their sire and had descended on Sea Gate first. But Gideon's army had been there to head them off, and the Zendikari forces were still staunchly battling now. The fortified seawall remained untouched. Jace had to admit that he was impressed by the force Gideon had assembled. And he was impressed by the Zendikari themselves. None of them had chosen to evacuate even after seeing Ulamog on the horizon, not one. #figure(image("012_Hedron Alignment/14.jpg", width: 100%), caption: [Goblin War Paint | Art by Karl Kopinski], supplement: none, numbering: none) They were a capable army, and Gideon was an adept leader. Which didn't mean that he wasn't also a fool. Nothing but a foolhardy notion could have precipitated his decision to stand there on that rock mere feet from the titan's bony faceplate. "In! He's in!" The cry was audible even above the cacophony of crashing waves, snapping bones, and slicing weapons. Jace confirmed the assertion; yes, the titan had moved into place. "Let's close it up!" Munda, the kor who often fought at Gideon's side, was the one who had shouted the order. "Hatch team, heave!" The team, which included Nissa and Jori, pulled on their ropes and cast their spells, easing the hedron door into place. But it moved so slowly! Jace's hands fluttered around his illusion, flicking the illusory door closed and open, closed and open. Each time the ring lit up and the miniature Ulamog was trapped. "Come on. Come on." He looked to Gideon, who was now face to face with the titan. What did the other man expect to accomplish up there? He had to know that he wouldn't be able to stop Ulamog alone. If the plan failed, if the trap didn't work, then Gideon would just be the first of the army to be reduced to dust. Ulamog lurched closer, bifurcated arms thrashing, reaching toward Gideon. Gideon wielded his sural, slashing one knobby blue arm back and then another. He did not once step back; rather he moved forward on the rock, closer to the titan. What must he be thinking right now, staring straight at Ulamog's blank faceplate, seeing the monster that didn't see him? What must that feel like? Jace was not at all tempted to actually find out. Unable to watch any longer, he traced the line of hedrons back around to the door. The team had almost completed the ring. Finally! He compared it to his illusion. Just a few more inches... "Yes! There!" Nissa cried from her position dangling from a hanging vine. Her declaration surprised Jace. Was she right? He glanced between the illusion and the actual ring, studying the two, comparing the placement. It appeared the elf was correct. But without the diagram, how... "Jace!" Gideon called. "Are we good?" His voice wasn't at all strained, an auditory contradiction to the strain on his face as he pushed against Ulamog's bony chin extension. "Can they lock it in?" Right. They were supposed to wait for Jace to tell them the assembly matched the diagram. "Yes! That's it. Lock it in!" "Lock it in!" Munda echoed Jace's call. In response, three kor rappelled down the side of the hedron that had temporarily acted as a doorframe and secured the final connection. As the kor cinched their ropes into place, Nissa provided a spell to nudge the hedron into perfect alignment, and...Jace held his breath. The light. Where was the light? The ring didn't flare to life like it was supposed to. And the titan wasn't contained within its bounds. Gideon ducked under another of Ulamog's swinging tentacles. "Are we there yet?" "Why isn't it glowing?" Munda called. Jace blinked down to the simulation still floating above his palm. He opened and closed the illusory door. His ring glowed. He looked between the illusion and the real ring. Why wasn't it glowing? He bounced on the balls of his feet. What was he missing? "Something is out of place!" Nissa called down to him. She was running her hands along the hedron closest to her. She pressed her cheek to the side of the massive rock. "There's a misalignment." Was she right? Based on her demonstrated capabilities, which Jace admittedly did not fully understand, should he just assume she was right? At the very least, he should eliminate her possibility before moving on. He had nothing better to go on. His eyes tracked from his diagram to the ring, marking off one hedron at a time. #emph[Yes...yes...yes...] Each one was where it was supposed to be—and yet. "I think it's coming from over there!" Nissa pointed toward the hedrons nearest Sea Gate. How did—Jace twisted the illusion around 90 degrees. What did she see that he didn't? He had done all the calculations. He had measured the alignment. "Jace!" Gideon cried. "What can you tell me?" The massive man bobbed under Ulamog's arm and slashed at the titan's bony chest plate. Jace ran his hand through his hair. This was on him. Gideon's life. The fate of Zendikar. This was the puzzle he had come here to solve, but he didn't have the solution. He had no idea which hedron it was, or if it even was a hedron that was out of place. He sent the illusion spinning. And Nissa caught it as she landed on the floating rock next to him. "What—" Jace staggered back. "I can tell it is coming from that side," she said. She had to yell above the sounds of water and war even though they were standing right next to each other. "I cannot tell which one it is, though, not from this distance. I would have to see the whole assembly at once, all of the connections. I would have to go up there onto the bluff, but—" "There's no time for that," Jace finished for her. "Correct." Nissa's glowing green eyes bored into him. "But I think there is another way. A more expedient way." She pointed to the illusion. "This synthetic energy diagram will allow us to see." "What do you mean?" "How confident are you that there are no inaccuracies?" "In my illusion?" "May I see it?" She touched her head. "From in here." Was she inviting him into her mind? A cry from over her shoulder, and Jace glanced up in time to see a kor struck by one of Ulamog's rear tentacles and sent plummeting. Nissa didn't turn around. She rested her hand on Jace's shoulder, drawing his gaze back to her magnetic eyes. "If there is a way to identify the misalignment, we must act quickly. If you do not allow me to do this, then I will have no choice but to confront the titan and attempt to destroy him without the trap. I don't want to have do that." Jace shook his head. "And I don't want you to have to do that either." "Then we agree," Nissa said. All right then. Into the elf's mind. Jace exhaled and looked into Nissa's wild, green eyes...and then out of them. It was as though the whole world was afire—if fire was green. At first Jace thought the hedron ring had finally lit up, but then he realized that it wasn't the circle itself that was glowing. It was the web of leylines that ran between each pair of hedrons. The lines crisscrossed in an intricate pattern too complex to reduce to a simple equation—or to an equation at all... The pattern lit up the space above the sea, but the hedrons were not the only things that were glowing, far from it. Everything. Everything was connected to something else by a line of power. The Zendikari holding the ropes, Gideon widening his stance before the titan, the skyrider's manta beating its wings overhead, the tree to his right, the rock at his feet. There was too much to process, too much to parse. Jace's mind spun. He lost his grip and began to fall out of Nissa's mind. He tried to hold on, but how was he supposed to know what to hold on to? #emph[Hold on here. ] It was Nissa's voice, and with it came what felt like a cradle of support. How was she doing this? Jace gripped the invisible hand and he did not fall out. #emph[Focus] , #emph[s] he said. #emph[Focus on one thing at a time.] She directed his attention down to his illusory diagram. Jace breathed deeply, concentrating on that one thing, just the illusion. He could still see the chaos of the leylines in his periphery, but he ignored it. #emph[Good] , Nissa said. She reached out to touch the illusion. #emph[May I?] Why not? They had come this far. #emph[Yes.] Nissa pinched two sides of the hedron circle and picked up the illusion. Jace allowed her mind to guide it while his maintained the form. She pulled outward, opening her arms and stretching the illusion, widening the ring and growing the hedrons. #emph[You've made all the calculations? ] she said. #emph[You are relatively confident it is correct?] #emph[Yes] , Jace said. #emph[I'm very confident that everything is where it should be, but—] #emph[Then this will work. ] Nissa launched the illusion out over the sea, expanding it as she did, sending it toward the real ring of hedrons. Her control of it was shaky and awkward, but Jace understood immediately what she was trying to do. His heart leapt. Brilliant. He took control, deftly directing the illusion into place, expertly growing it until it was life-size, making each of the illusory hedrons as large as its stone counterpart. Nissa didn't know how to line them up, but he did. Each of them found its match—except one. #emph[There. ] Nissa said, noting it at the same time that Jace did. The hedron was tilted; it must have shifted sometime after being carefully locked into place. #emph[We have to—] Jace began, but Nissa was already gone, leaping toward the out-of-place hedron. She released his mind as she sprang off the rock—she released his mind, not the other way around. She didn't exactly kick him out, but he didn't think he could have stayed if he had wanted to. That was a powerful thing. This elf was powerful. Jace staggered on his own two feet, looking out of his own two eyes at a dull world. The web was gone, the connections had vanished. The chaos had faded away. It was as much a relief as a disappointment. It was an odd feeling to know that there was so little—of the leylines, of the world—that he could actually see. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The only thing Gideon could see was jagged, white bone: Ulamog's thick faceplate. The titan was too close; the trap should have stopped him by now, he should have been contained. But something had gone wrong. Gideon had been preparing himself for this moment since the first time he had heard Jace explain the plan. He had believed it would work, he had trusted the mind mage—and he still did—but he had always known that there was a possibility that something would go wrong. Jace had known it too. That's why Gideon had stationed himself here on this rock. He was the last line of defense. He stood between Sea Gate and Ulamog, and he would hold his position for as long as it took them to set the trap. And if they couldn't set it, if it came to it, then Gideon would call for an evacuation. And he would hold the titan back until his army could get to safety. But it wasn't time for that yet. He could hold out a little longer. They just needed a little longer... One of Ulamog's tentacles soared through the air, aimed right at Gideon. Whorls of invulnerability erupted over his skin in anticipation of the collision. Gideon absorbed the blow, gritting his teeth under the weight of it. A second tentacle hurtled his way from the other side. He shifted the focus of his protection. How much longer should he wait? He slashed back Ulamog's reaching fingers. Just a little longer... The titan leaned forward, bearing down toward Gideon. Gideon dug his feet into the rock and stared straight into where he imagined the titan's eyes would be. "You're not getting past me." He turned his shoulder to meet Ulamog's chest, focusing all of his power into that single point, the point of impact. He grounded himself, clenching every muscle in his body, pushing back. It was as though the weight of an entire world was being driven against him. He felt his feet begin to slip. Was it time? He opened his mouth to give the order, but then closed it. He could hold out just a little longer. They needed just a little longer... Gideon squeezed his eyes shut, exhaling a roaring cry with the effort. He was losing ground. Then suddenly a blue flash lit up the inside of his eyelids, and the pressure on his shoulder vanished. Gideon stumbled forward with the momentum stored up from the force he had been exerting on the titan. He caught himself just before he tumbled off the front of the floating rock...which meant there was nothing else in front of him to stop his fall. He was no longer standing face-to-face with the titan. Ulamog had been pulled within the bounds of the hedron prison—and the prison was glowing, glowing a brilliant blue. The gleam flooded Sea Gate, drowning out the shadow of the great Eldrazi. #figure(image("012_Hedron Alignment/15.jpg", width: 100%), caption: [Aligned Hedron Network | Art by <NAME>right], supplement: none, numbering: none) "Ha!" Gideon thrust his sural in the air. They had done it. Ulamog was trapped. A cheer rose up from behind him as Nissa landed gracefully on the rock next to him, letting a dangling vine recoil behind her. "We did it," she said. "We did it," Gideon agreed, his eyes connecting with Jace's across the sea. "We did it." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) From his station atop a cliffside, Ebi whooped a cheer. They had done it. The titan. Ulamog. Trapped. Ebi staggered back, tears in his eyes. There was still hope. There was still a chance to save this world. A cry echoed up from the Zendikari below, and Ebi lent his voice to theirs. "For Zendikar!" As he raised his fist in the air, a shadow fell over him. Before he could look up, a demon landed on the rock in front of him. Ebi swung his weapon, but the demon caught his arm in midair. "It's unfortunate, but it seems that you're in the wrong place at the wrong time." The demon pushed Ebi up against the rock face behind him, its thick black hand around Ebi's neck. Ebi tried to call out. He had to warn the others. He was a sentry. Gideon was counting on him. #figure(image("012_Hedron Alignment/16.jpg", width: 100%), caption: [Demon's Grasp | Art by David Gaillet], supplement: none, numbering: none) "Shhh." The demon squeezed. Ebi could feel his life draining away. "Take what solace you can in the knowledge that you will not be here to witness Zendikar's demise." The world went black.
https://github.com/jujimeizuo/ZJSU-typst-template
https://raw.githubusercontent.com/jujimeizuo/ZJSU-typst-template/master/contents/context.typ
typst
Apache License 2.0
= 绪论 == typst 介绍 typst 是最新最热的标记文本语言,定位与 LaTeX 类似,具有极强的排版能力,通过一定的语法写文档,然后生成 pdf 文件。与 LaTeX 相比有以下的优势: 1. 编译巨快:因为提供增量编译的功能所以在修改后基本能在一秒内编译出 pdf 文件,typst 提供了监听修改自动编译的功能,可以像 Markdown 一样边写边看效果。 2. 环境搭建简单:原生支持中日韩等非拉丁语言,不用再大量折腾字符兼容问题以及下载好几个 G 的环境。只需要下载命令行程序就能开始编译生成 pdf。 3. 语法友好:对于普通的排版需求,上手难度跟 Markdown 相当,同时文本源码阅读性高:不会再充斥一堆反斜杠跟花括号 个人观点:跟 Markdown 一样好用,跟 LaTeX 一样强大 是吗 == 基本语法 === 代码执行 正文可以像前面那样直接写出来,隔行相当于分段。 个人理解:typst 有两种环境,代码和内容,在代码的环境中会按代码去执行,在内容环境中会解析成普通的文本,代码环境用{}表示,内容环境用[]表示,在 content 中以 \# 开头来接上一段代码,比如\#set rule,而在花括号包裹的块中调用代码就不需要 \#。 === 标题 类似 Markdown 里用 \# 表示标题,typst 里用 = 表示标题,一级标题用一个 =,二级标题用两个 =,以此类推。 间距、字体等我都排版好了。但是要注意下每个段落后需要加12pt!!! #pagebreak() = 模版简介 == 模板概述 本项目是使用 Typst 语言重新编写而成,旨在帮助浙江工商大学大学的本科生更方便地撰写自己的毕业论文。该模板基于 Typst 系统创建,相较于 Latex@tex1989, 是一种语法更加简易的排版软件,可以用于制作高质量的科技论文和出版物。该项目目前已经包括论文的封面、摘要、正文、参考文献等,用户可以根据自己的需要进行修改和定制。 == 引用文献 这里参考了开源社区 Latex 模板中的参考文献@tex1989 @nikiforov2014 @algebra2000 @LuMan2016:Small-Spectral-Radius @HuQiShao2013:Cored-Hypergraphs @LinZhou2016:Distance-Spectral @KangNikiforov2014:Extremal-Problems @Qi2014:H-Plus-Eigenvalues @Nikiforov2017:Symmetric-Spectrum @BuFanZhou2016:Z-eigenvalues @impagliazzo2001complexity @impagliazzo2001problems @elffers2014scheduling @chrobak2017greedy @paturi1997satisfiability @book1980michael @papadimitriou1998combinatorial,可以点击序号跳转文末查看引用格式。 #pagebreak() = 图表样例 == 图表样例 // 新增了对图的引用参考 如@fig-acm 所示是一个图片样例。 #figure( image("../template/images/zjgsu_logo.png", width: 50%), caption: [ "hhhhh" ], ) <fig-acm> == 表格样例 @tab-acmer 展示了一些大佬的博客。 #figure( table( columns: (auto, auto, auto,auto), [怎么称呼], [所在院系], [来句介绍], [甩个链接], [Mauve], [2018计科], [阿里人], [https://hukeqing.github.io], [jujimeizuo], [2019计科], [菜鸡], [http://www.jujimeizuo.cn], [kaka], [2019计科], [杭电研], [https://ricar0.github.io], [lx_tyin], [2020计科], [金牌爷], [lxtyin.ac.cn] ), caption : [ ZJGSU ACMer ] ) <tab-acmer> 表格跟图片差不多,但是表格的输入要复杂一点,建议去 typst 官网学习一下,自由度特别高,定制化很强。 #v(10em) 看看@tbl1,没有字段的一律是单元格里的内容(每一个被[])包起来的内容,在 align 为水平时横向排列,排完换行。 #figure( table( columns: (100pt, 100pt, 100pt), inset: 10pt, stroke: 0.7pt, align: horizon, [], [*Area*], [*Parameters*], image("../images/avatar.jpeg", height: 10%), $ pi h (D^2 - d^2) / 4 $, [ $h$: height \ $D$: outer radius \ $d$: inner radius ], image("../images/avatar.jpeg", height: 10%), $ sqrt(2) / 12 a^3 $, [$a$: 边长] ), caption: "芝士样表" ) <tbl1> #pagebreak() = 公式样例 公式用两个\$包裹,但是语法跟 LaTeX 并不一样,如果有大量公式需求那先建议看官网教程,不过typst还比较早期,不排除以后会加入兼容语法的可能。 == 行内公式 行内公式 $a^2 + b^2 = c^2$ 行内公式。 == 独立公式 独立公式,如@eq-1 所示。 $ sum_(i=1)^(n) F_i(x) = F_1(x) + F_2(x) + ... + F_n(x) $ <eq-1> 独立公式,如@eq-2 所示。 $ F_1(x) + F_2(x) + ... + F_n(x) = sum_(i=1)^(n) F_i(x) $ <eq-2> #pagebreak() = 列表样例 == 无序列表 - 无序列表1: 1 - 无序列表2: 2 == 有序列表 1. 有序列表1 2. 有序列表2 想自己定义可以自己set numbering,建议用 \#[] 包起来保证只在该作用域内生效: #[ #set enum(numbering: "1.a)") + 自定义列表1 + 自定义列表1.1 + 自定义列表2 + 自定义列表2.1 ] #pagebreak() = 这是一章占位的 == 占位的二级标题 1 == 占位的二级标题 2 == 占位的二级标题 3 == 占位的二级标题 4 === 占位的三级标题 1 === 占位的三级标题 2 ==== 占位的四级标题 1 ==== 占位的四级标题 2 == 占位的二级标题 5 == 占位的二级标题 6
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/sweet-graduate-resume/0.1.0/template.typ
typst
Apache License 2.0
#import "lib_fontawesome.typ": * #let preamble(doc) = { set page( paper: "a4", margin: (x: 0.5cm, y: 0.5cm), ) set text( font: "DejaVu Sans", size: 8pt, ) set par(justify: true) show link: name => { set text(blue) name } set block(spacing: 0.5em) set align(left) doc } #let header(author, roll, school, urls) = { set text(17pt, weight: "bold") set block(spacing: 0.3em) [ #author | #roll #set text(13pt) #box( width: 1fr, inset: (bottom: 5pt), stroke: (bottom: (1pt + black)), )[#school] ] set text(7pt) for value in urls { let img = if value.fa { if value.brand { fa-icon(value.svg) } else { fa-icon(value.svg, solid: value.solid) } } else { value.svg } link(value.url)[ #value.name #box(height: 1em, baseline: 20%)[#img] ] + if value == urls.last() { "" } else { "|" } } } #let section-header(head) = { box( inset: (top: 0.3em, left: 0.4em, bottom: 0.3em), width: 1fr, fill: rgb(120, 230, 230), )[#set text(weight: "black"); #head] } #let education(rows) = { table( stroke: none, columns: (1fr, 1fr, auto), inset: 5pt, align: horizon, table.hline(), table.header( [*Program*], [*Institution*], [#set align(right); *Grade*], ), table.hline(), table.vline(x: 0), ..rows.map(r => ( r.prog, r.school, [#set align(right); #r.grade], )).flatten(), table.vline(), table.hline(), ) } #let points(arr) = { list(..arr) } #let dual(arr) = { columns(2, gutter: 11pt)[ #let i = 0 #let first-half = (); #while i < arr.len() / 2 { first-half.push(arr.at(i)) i += 1 } #list(..first-half) #colbreak() #let second-half = (); #while i < arr.len() { second-half.push(arr.at(i)) i += 1 } #list(..second-half) ] } #let dated-section( title, subtitle, date-start: none, date-end: none, ongoing: false, points: array, ) = { [ #box( width: 1fr, inset: (bottom: 3pt), stroke: (bottom: (1pt + black)), )[#text(9.5pt)[*⊚ #title*] #h(1fr) #text(7pt)[_#subtitle #if date-start != none {[(#date-start]} #if date-end != none {[\- #date-end)]} else if ongoing {[\- Ongoing)]} else if date-start != none {[)]}_]] #list(..points) ] }
https://github.com/mrtz-j/typst-thesis-template
https://raw.githubusercontent.com/mrtz-j/typst-thesis-template/main/lib.typ
typst
MIT License
#import "@preview/subpar:0.1.1" #import "@preview/physica:0.9.3": * #import "@preview/outrageous:0.2.0" #import "@preview/glossarium:0.5.0": make-glossary, register-glossary #import "@preview/codly:1.0.0": * #import "modules/frontpage.typ": frontpage #import "modules/backpage.typ": backpage #import "modules/supervisors.typ": supervisors-page #import "modules/epigraph.typ": epigraph-page #import "modules/abstract.typ": abstract-page #import "modules/acknowledgements.typ": acknowledgements-page #import "modules/abbreviations.typ": abbreviations-page // Workaround for the lack of an `std` scope. #let std-bibliography = bibliography #let std-smallcaps = smallcaps #let std-upper = upper #let std-pagebreak = pagebreak // Overwrite the default `smallcaps` and `upper` functions with increased spacing between // characters. Default tracking is 0pt. #let smallcaps(body) = std-smallcaps(text(tracking: 0.6pt, body)) #let upper(body) = std-upper(text(tracking: 0.6pt, body)) // Colors used across the template. #let stroke-color = luma(200) #let fill-color = luma(250) #let uit-teal-color = rgb("#0095b6") #let uit-gray-color = rgb("#48545e") // Helper to display two pieces of content with space between. #let fill-line(left-text, right-text) = [#left-text #h(1fr) #right-text] // Helper to display external codeblocks. // Based on https://github.com/typst/typst/issues/1494 #let code-block(filename, content) = raw( content, block: true, lang: filename.split(".").at(-1), ) // Helper to display CSV tables. #let csv-table( tabledata: "", columns: 1, header-row: rgb(255, 231, 230), even-row: rgb(255, 255, 255), odd-row: rgb(228, 234, 250), ) = { let tableheadings = tabledata.first() let data = tabledata.slice(1).flatten() table( columns: columns, fill: (_, row) => if row == 0 { header-row // color for header row } else if calc.odd(row) { odd-row // each other row colored } else { even-row }, align: (col, row) => if row == 0 { center } else { left }, ..tableheadings.map(x => [*#x*]), // bold headings ..data, ) } // `in-appendix` is for custom styling in the appendix section #let in-appendix = state("in-appendix", false) // The `in-outline` mechanism is for showing a short caption in the list of figures // See https://sitandr.github.io/typst-examples-book/book/snippets/chapters/outlines.html#long-and-short-captions-for-the-outline #let in-outline = state("in-outline", false) // -- Styling rules for Front-Main-Back matter -- // Common styles for front matter #let front-matter(body) = { set page(numbering: "i") counter(page).update(1) set heading(numbering: none) show heading.where(level: 1): it => { it v(6%, weak: true) } body } // Common styles for main matter #let main-matter(body) = { set page(numbering: "1", // Only show numbering in footer when no chapter header is present footer: context { let chapters = heading.where(level: 1) if query(chapters).any(it => it.location().page() == here().page()) { align(center, counter(page).display()) } else { none } } ) counter(page).update(1) counter(heading).update(0) set heading(numbering: "1.1") show heading.where(level: 1): it => { it v(12%, weak: true) } body } // Common styles for back matter #let back-matter(body) = { // TODO: Should not outline bibliography, but maybe appendix? set heading(numbering: "A", supplement: [Appendix], outlined: false) // Make sure headings start with 'A' counter(heading.where(level: 1)).update(0) counter(heading).update(0) body } // -- Template entrypoint -- // This function gets your whole document as its `body` and formats it #let thesis( // The title for your work. title: [Your Title], // Subtitle for your work. subtitle: none, // Author. author: "Author", // The supervisor(s) for your work. Takes an array of "Title", "Name", [Affiliation] supervisors: ( (title: "Your Supervisor", name: "<NAME>", affiliation: [UiT The Arctic University of Norway, \ Faculty of Science and Technology, \ Department of Computer Science]) ), // The paper size to use. paper-size: "a4", // The degree you are working towards degree: "INF-3983 Capstone", // What field you are majoring in major: "Computer Science", // The faculty and department at which you are working faculty: "Faculty of Science and Technology", department: "Department of Computer Science", // Date that will be displayed on cover page. // The value needs to be of the 'datetime' type. // More info: https://typst.app/docs/reference/foundations/datetime/ // Example: datetime(year: 2024, month: 03, day: 17) date: datetime.today(), // The date that you are submitting your work. submission-date: datetime.today(), // Format in which the date will be displayed on cover page. // More info: https://typst.app/docs/reference/foundations/datetime/#format date-format: "[month repr:long] [day padding:zero], [year repr:full]", // The contents for the epigraph page. This will be displayed after the acknowledgements. // Can be omitted if you don't have one epigraph: none, // An abstract for your work. Can be omitted if you don't have one. abstract: none, // The contents for the acknowledgements page. This will be displayed after the // abstract. Can be omitted if you don't have one. acknowledgements: none, // The contents for the preface page. This will be displayed after the cover page. Can // be omitted if you don't have one. preface: none, // The result of a call to the `bibliography` function or `none`. // Example: bibliography("refs.bib", title: "Bibliography", style: "ieee") // More info: https://typst.app/docs/reference/model/bibliography/ bibliography: none, // Display an index of figures (images). figure-index: true, // Display an index of tables table-index: true, // Display an index of listings (code blocks). listing-index: true, // List of abbreviations abbreviations: none, // The content of your work. body, ) = { // Set the document's metadata. set document( title: title, author: author, date: if date != none { date } else { auto }, ) // Required init for packages show: make-glossary register-glossary(abbreviations) show: codly-init // Optimize numbers with superscript // especially nice for bibliography entries show regex("\d?\dth"): w => { // 26th, ... let b = w.text.split(regex("th")).join() [#b#super([th])] } show regex("\d?\dst"): w => { // 1st let b = w.text.split(regex("st")).join() [#b#super([st])] } show regex("\d?\d[nr]d"): w => { // 2nd, 3rd, ... let s = w.text.split(regex("\d")).last() let b = w.text.split(regex("[nr]d")).join() [#b#super(s)] } // If we find in bibentries some ISBN, we add link to it show "https://doi.org/": w => { // handle DOIs [DOI:] + str.from-unicode(160) // 160 A0 nbsp } show regex("ISBN \d+"): w => { let s = w.text.split().last() link( "https://isbnsearch.org/isbn/" + s, w, ) // https://isbnsearch.org/isbn/1-891562-35-5 } // Hanging indent for footnote show footnote.entry: set par(hanging-indent: 1.5em) // Set the body font. // Default is Charter at 11pt set text(font: "Charter", size: 11pt) // Set raw text font. // Default is JetBrains Mono at 9tp with DejaVu Sans Mono as fallback show raw: set text(font: ("JetBrains Mono", "Fira Code"), size: 9pt) // Configure page size and margins. set page( paper: "a4", margin: ( bottom: 5cm, top: 4cm, inside: 26.2mm, outside: 37mm, ), numbering: "1", number-align: center, ) // Configure paragraph properties. // Default leading is 0.7em. // Default spacing is 1.35em. set par( leading: 0.7em, justify: true, linebreaks: "optimized", spacing: 1.35em, ) // Add some vertical spacing for all headings show heading: it => { let body = if it.level > 1 { box(width: 12pt * it.level, counter(heading).display()) it.body } else { it } v(2.5em, weak: true) body v(1.5em, weak: true) } // Style chapter headings show heading.where(level: 1): it => { set text(font: ("Open Sans", "Noto Sans"), weight: "bold", size: 24pt) // FIXME: Has no effect, still shows "Section" set heading(supplement: [Chapter]) let heading-number = if heading.numbering == none { [] } else { text(counter(heading.where(level: 1)).display(), size: 62pt) } // Reset figure numbering on every chapter start for kind in (image, table, raw) { counter(figure.where(kind: kind)).update(0) // Also reset equation numbering counter(math.equation).update(0) } // Start chapter headings on a new page pagebreak(weak: true) v(16%) if heading.numbering != none { stack( dir: ltr, move( dy: 54pt, polygon( fill: uit-teal-color, stroke: uit-teal-color, (0pt, 0pt), (5pt, 0pt), (40pt, -90pt), (35pt, -90pt), ), ), heading-number, ) v(1.0em) it.body v(-1.5em) } else { it.body } } // Configure heading numbering. set heading(numbering: "1.1") // Do not hyphenate headings. show heading: set text( font: ("Open Sans", "Noto Sans"), weight: "bold", features: ("sc", "si", "scit"), hyphenate: false, ) set page( // Set page header header-ascent: 30%, header: context { // Get current page number let page-number = here().page() // If the current page is the start of a chapter, don't show a header let chapters = heading.where(level: 1) if query(chapters).any(it => it.location().page() == page-number) { return [] } // Find the chapter of the section we are currently in let chapters-before = query(chapters.before(here())) if chapters-before.len() > 0 { let current-chapter = chapters-before.last() // If a new subsecion starts on this page, select that subsection. // Otherwise, select the last subsection let current-subsection = { let subsections = heading.where(level: 2) let subsections-after = query(subsections.after(here())) if subsections-after.len() > 0 { let next-subsection = subsections-after.first() if next-subsection.location().page() == page-number { (next-subsection) } else { let subsections-before = query(subsections.before(here())) if subsections-before.len() > 0 { (subsections-before.last()) } else { // No subsections in this chapter (none) } } } } let colored-slash = text(fill: uit-teal-color, "/") let spacing = h(3pt) // Content to display subsection count and heading let subsection-text = if current-subsection != none { let subsection-numbering = current-subsection.numbering let location = current-subsection.location() let subsection-count = numbering(subsection-numbering,..counter(heading).at(location)) [#subsection-count #spacing #colored-slash #spacing #current-subsection.body] } else { // No subsections in chapter, display nothing [] } // Content to display chapter count and heading let chapter-text = { let chapter-title = current-chapter.body let chapter-number = counter(heading.where(level: 1)).display() [CHAPTER #chapter-number #spacing #colored-slash #spacing #chapter-title] } if current-chapter.numbering != none { // Show current chapter on odd pages, current subsection on even let (left-text, right-text) = if calc.odd(page-number) { (counter(page).display(), chapter-text) } else { ( subsection-text, counter(page).display(), ) } text( weight: "thin", font: ("Open Sans", "Noto Sans"), size: 8pt, fill: uit-gray-color, // FIXME: Seems to have no effect // features: ("sc", "si", "scit"), fill-line(upper(left-text), upper(right-text)), ) } } }, ) // -- Equations -- // Configure equation numbering. set math.equation(numbering: n => { let h1 = counter(heading).get().first() numbering("(1.1)", h1, n) }) show math.equation.where(block: true): it => { set align(center) // Indent pad(left: 2em, it) } // -- Figures -- // Set figure numbering to follow chapter set figure(numbering: n => { let h1 = counter(heading).get().first() numbering("1.1", h1, n) }) set figure.caption(separator: [ -- ]) // Place table captions above table show figure.where(kind: table): it => { set figure.caption(position: top) // Break large tables across pages. set block(breakable: true) it } // -- Tables -- // Use lighter gray color for table stroke set table( inset: 7pt, stroke: (0.5pt + stroke-color), ) // Show table header in small caps show table.cell.where(y: 0): smallcaps // Display inline code in a small box that retains the correct baseline. show raw.where(block: false): box.with( fill: fill-color.darken(2%), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) // -- Links -- // Show a small maroon circle next to external links. show link: it => { // Workaround for ctheorems package so that its labels keep the default link styling. if type(it.dest) == label { return it } it h(1.6pt) super( box(height: 3.8pt, circle(radius: 1.2pt, stroke: 0.7pt + rgb("#993333"))), ) } // -- Front matter -- // Display front page frontpage( title: title, subtitle: subtitle, author: author, degree: degree, faculty: faculty, department: department, major: major, submission-date: submission-date, ) // Use front matter stylings show: front-matter // List of Supervisors supervisors-page(supervisors) // Epigraph epigraph-page()[#epigraph] // Abstract abstract-page()[#abstract] // Acknowledgements acknowledgements-page()[#acknowledgements] // -- Outlines -- // Display outlines (table of content, table of figures, etc...) context { // Helper to target figure kinds let fig-t(kind) = figure.where(kind: kind) // The `in-outline` is for showing a short caption in the list of figures // See https://sitandr.github.io/typst-examples-book/book/snippets/chapters/outlines.html#long-and-short-captions-for-the-outline show outline: it => { in-outline.update(true) // Show table of contents, list of figures, list of tables, etc. in the table of contents set heading(outlined: true) it in-outline.update(false) } // Increase distance between dots on all outline fill set outline(fill: box(width: 1fr, repeat([#h(2.5pt) . #h(2.5pt)]))) pagebreak() // Common padding to use on outline entries let entry-padding = 0.5em // Styling for ToC // NOTE: When/if setting fill dependent on the depth becomes easily possible // in typst itself, we can remove the 'outrageous' package [ #show outline.entry: outrageous.show-entry.with( ..outrageous.presets.typst, font-weight: ("bold", auto), fill: (none, auto), font: ("Charter", "Charter"), vspace: (1.5em, 0.5em), // Manually add indent and spacing body-transform: (lvl, body) => { let indent = (lvl - 1) * 1.5em // Entries with (number, text, page) should have more spacing between number and text let spaced-entry = if "children" in body.fields() { let (number, space, ..text) = body.children [#number #h(entry-padding) #text.join()] } else { body } [#h(indent) #spaced-entry] }, // Manually add spacing between fill and page number page-transform: (lvl, page) => { if lvl > 1 { [#h(entry-padding) #page] } else { page } } ) #outline(title: "Contents") ] // Styling for remaining outlines show outline.entry: outrageous .show-entry .with( ..outrageous.presets.typst, // Don't display 'figure' or 'table' before each entry body-transform: (_lvl, body) => { if "children" in body.fields() { let (fig-type, space, number, colon, ..text) = body.children [#number #h(entry-padding) #text.join()] } else { body } }, // Manually add spacing between fill and page number page-transform: (_lvl, page) => { [#h(entry-padding) #page] } ) // Remaining outlines are all optional if figure-index { outline(title: "List of Figures", target: fig-t(image)) } if table-index { outline(title: "List of Tables", target: fig-t(table)) } if listing-index { outline(title: "List of Listings", target: fig-t(raw)) } } // List of Abbreviations if abbreviations != none { abbreviations-page(abbreviations) } // -- Main matter -- // Use main matter stylings show: main-matter // Thesis content body // -- Back matter -- // Use back matter stylings show: back-matter // Style bibliography if bibliography != none { pagebreak() // show std-bibliography: set text(0.95em) show std-bibliography: set text(12pt) // Use default paragraph properties for bibliography. show std-bibliography: set par( leading: 0.65em, justify: false, linebreaks: auto, ) bibliography } // Display back page backpage() }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/if-01.typ
typst
Other
// Braced condition. #if {true} [ One. ] // Content block in condition. #if [] != none [ Two. ] // Multi-line condition with parens. #if ( 1 + 1 == 1 ) [ Nope. ] else { "Three." } // Multiline. #if false [ Bad. ] else { let point = "." "Four" + point } // Content block can be argument or body depending on whitespace. #{ if "content" == type[b] [Fi] else [Nope] if "content" == type [Nope] else [ve.] } #let i = 3 #if i < 2 [ Five. ] else if i < 4 [ Six. ] else [ Seven. ]
https://github.com/MattiaOldani/Informatica-Teorica
https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/00_introduzione.typ
typst
#set heading(numbering: none) #import "alias.typ": * = Introduzione L'*informatica teorica* è la branca dell'informatica che si "contrappone" all'informatica applicata: in quest'ultima, l'informatica è usata solo come uno _strumento_ per gestire l'oggetto del discorso, mentre nella prima l'informatica diventa l'_oggetto_ del discorso, di cui ne vengono studiati i fondamenti. Analizziamo i due aspetti fondamentali che caratterizzano ogni materia: + il *cosa*: l'informatica è la scienza che studia l'informazione e la sua elaborazione automatica mediante un sistema di calcolo. Ogni volta che ho un _problema_ cerco di risolverlo _automaticamente_ scrivendo un programma. _Posso farlo per ogni problema? Esistono problemi che non sono risolubili?_ \ Possiamo chiamare questo primo aspetto con il nome di *teoria della calcolabilità*, quella branca che studia cosa è calcolabile e cosa non lo è, a prescindere dal costo in termini di risorse che ne deriva. In questa parte utilizzeremo una caratterizzazione molto rigorosa e una definizione di problema il più generale possibile, così che l'analisi non dipenda da fattori tecnologici, storici, ... + il *come*: è relazionato alla *teoria della complessità*, quella branca che studia la quantità di risorse computazionali richieste nella soluzione automatica di un problema. Con _risorsa computazionale_ si intende qualsiasi cosa venga consumata durante l'esecuzione di un programma. \ In questa parte daremo una definizione rigorosa di tempo, spazio e di problema efficientemente risolubile in tempo e spazio, oltre che uno sguardo al famoso problema $P = NP$. In ordine, nella teoria della calcolabilità andremo a fare uno studio *qualitativo* dei problemi, nel quale individueremo quali sono quelli calcolabili, mentre nella teoria della complessità questi ultimi verranno studiati in modo *quantitativo*.
https://github.com/Brndan/formalettre
https://raw.githubusercontent.com/Brndan/formalettre/main/src/lib.typ
typst
BSD 3-Clause "New" or "Revised" License
#let expediteur = ( nom: [], prenom: [], voie: [], complement_adresse: [], code_postal: [], commune: [], telephone: [], email: [], signature: false, ) #let destinataire = ( titre: [], voie: [], complement_adresse: [], code_postal: [], commune: [], sc: [], ) #let lettre( expediteur: expediteur, destinataire: destinataire, objet: [], date: [], lieu: [], pj: [], doc, ) = { [ #expediteur.prenom #smallcaps[#expediteur.nom] \ #expediteur.voie #h(1fr) #lieu, #date \ ] if expediteur.complement_adresse != "" { [ #expediteur.complement_adresse #linebreak() ] } [ #expediteur.code_postal #expediteur.commune ] if expediteur.telephone != "" { [ #linebreak() tél. : #raw(expediteur.telephone) ] } if expediteur.email != "" { [ #linebreak() email: #link("mailto:" + expediteur.email)[#raw(expediteur.email)] ] } v(1cm) grid( columns: (1fr, 5cm), grid.cell(""), [ #destinataire.titre \ #destinataire.voie \ #if destinataire.complement_adresse != "" { [ #destinataire.complement_adresse \ ] } #destinataire.code_postal #destinataire.commune #if destinataire.sc != "" { [ #v(1cm) s/c de #destinataire.sc \ ] } ], ) v(1.7cm) [*Objet : objet*] v(0.7cm) set par(justify: true) doc if pj != "" { [ #v(1cm) P. j. : #pj ] } set align(right + horizon) if expediteur.signature == true { v(-3cm) } [ #expediteur.prenom #smallcaps[#expediteur.nom] ] }
https://github.com/ufodauge/master_thesis
https://raw.githubusercontent.com/ufodauge/master_thesis/main/src/template/components/intro-section/toc.typ
typst
MIT License
#import "../../constants/page.typ": * #import "../common/page.typ" : Page // #let #let TocPage() = locate(loc => [ #let headings = query(heading.where(outlined: true), loc) #let lines = headings.fold(( lines: (), options: ( latest_chapter: none ) ), (( lines, options ), head) => [ #let head_loc = head.location() #let head_numbers = counter(heading).at(head_loc) #let head_numbering = head.at("numbering") #let head_level = head.at("level") #let chapter_number = head_numbers.first() #if lines.len() > 0 and head_level == 1 { lines.push(v(13pt)) } #let indent = if head_level == 1 { 0pt } else if head_level == 2 { 18pt } else { 46pt } #let chapter_name = [ #let chapter = if head_numbering != none { numbering( head_numbering, ..head_numbers ) + h(1em) } else { none } #let chapter_body = [ #chapter #head.body ] #if head_level == 1 { strong(chapter_body) } else { chapter_body } ] #let chapter_body = if head_level != 1 { box(width: 1fr, repeat(box(inset: (x: 0.25em), "."))) } #let is_before_main_section = query( heading .where(level: 1) .after(head_loc), head_loc ).any(x => x.body == [表目次]) #let page_numbering = if is_before_main_section { PAGE_NUMBERING_INTRO } else { PAGE_NUMBERING_MAIN } #let page_number = counter(page).at(head_loc).first() #let page_name = numbering( page_numbering, page_number ) #lines.push( grid( columns: (indent, 1fr, 10pt, 18pt), none, [ #chapter_name #h(1em) #chapter_body ], none, align(right)[ #page_name ] ) ) #return (lines, options) ]).first() #Page[ #set heading(outlined: false) = 目次 #for line in lines [ #line ] ] ])
https://github.com/Wint3rmute/cv
https://raw.githubusercontent.com/Wint3rmute/cv/master/README.md
markdown
MIT License
# My Curriculum Vitae The CV is made in [typst](https://typst.app/), forked from [Alta Typst](https://github.com/GeorgeHoneywood/alta-typst) and further modified to fit my aesthetic preferences. The compiled PDF is available [here](./cv.pdf). ## Usage ### On [typst.app](https://typst.app/) Upload the `.typ` and `.svg` files to your Typst project, then see `cv.typ`. ### With [Typst CLI](https://github.com/typst/typst) Fork and clone this repo, then run `typst watch cv.typ`. ### Icons Add extra icons by uploading more `.svg` files — the existing ones are free icons from [Font Awsome](https://fontawesome.com/search?o=r&m=free). You can then reference these as `name` values in the links array. ## Licence [MIT](./LICENSE) Icons are from Font Awesome, subject to [their terms](https://github.com/FortAwesome/Font-Awesome/blob/6.x/LICENSE.txt).
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/emphasis_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 6-7 unclosed delimiter // #box[_Scoped] to body.
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/references/cross_module_absolute.typ
typst
Apache License 2.0
// path: /out/main.typ #import "/out/base.typ": x #x ----- // path: /out/base.typ #let /* ident after */ x = 1;
https://github.com/SkiFire13/fmcps-assignment2
https://raw.githubusercontent.com/SkiFire13/fmcps-assignment2/master/automata.typ
typst
#import "@preview/cetz:0.1.1" #import "@preview/finite:0.3.0" #import "defs.typ": * // Set this to `true` to avoid rendering many labels and speed up compilation. #let no-labels = false #let position(i) = v(2em) + cetz.canvas({ import finite.draw: * let (xmin, xmax, ymin, ymax) = (1, 5, 1, 3) let n(x, y) = "X" + str(x) + "Y" + str(y) let transition(s, e, l, curve: 0.2, anchor: top) = finite.draw.transition( s, e, label: text(size: 10pt, l), curve: curve, anchor: anchor) for x in range(xmin, xmax+1) { for y in range(ymin, ymax+1) { let initial = false if (i, x, y) == (1, 1, 1) { initial = (text: "", anchor: alignment.left) } if (i, x, y) == (2, 4, 2) { initial = (text: "", anchor: top + alignment.left) } state( (3.5 * x, -3.5 * y), n(x, y), label: box(width: 1.6em, align(center, n(x, y))), radius: 0.7, initial: initial, final: initial != false ) } } transition(n(2, 2), n(1, 2), $uleft #i$) transition(n(2, 2), n(3, 2), $uright #i$) transition(n(2, 2), n(2, 1), $uup #i$) transition(n(2, 2), n(2, 3), $udown #i$) for x in range(xmin, xmax+1) { for y in range(ymin, ymax+1) { if (x, y) == (2, 2) { continue } if x != xmin { transition(n(x, y), n(x - 1, y), $left #i$) } if x != xmax { transition(n(x, y), n(x + 1, y), $right #i$) } if y != ymin { transition(n(x, y), n(x, y - 1), $up #i$) } if y != ymax { transition(n(x, y), n(x, y + 1), $down #i$) } } } loop(n(1, 1), label: $charge #i$, curve: 0.5) let label = (text: text(size: 10pt, $charge #i$), angle: 45deg) finite.draw.loop(n(4, 2), label: label, curve: 1, anchor: bottom + alignment.left) }) #let battery(i) = v(2em) + cetz.canvas({ import finite.draw: * state((-2.8 * 2.5, -3), "L6", initial: (text: "", anchor: bottom), final: true) for l in range(0, 6) { state((-2.8*l, 0), "L" + str(l)) } let label_text = align(center, text(size: 10pt)[ $left #i$ \ $right #i$ \ $up #i$ \ $down #i$ \ $uleft #i$ \ $uright #i$ \ $uup #i$ \ $udown #i$ ]) for l in range(1, 6) { let label = (text: label_text, dist: 2) transition("L" + str(l), "L" + str(l - 1), label: label, curve: 0.5) } let label = (text: label_text, angle: -66deg, dist: 0.6) transition("L6", "L5", label: label, curve: 1.05) transition("L5", "L6", label: text(size: 10pt, $charge #i$), curve: -0.3) transition("L4", "L6", label: text(size: 10pt, $charge #i$), curve: -0.1) transition("L3", "L6", label: text(size: 10pt, $charge #i$), curve: -0.1) transition("L2", "L6", label: text(size: 10pt, $charge #i$), curve: 0.1) transition("L1", "L6", label: text(size: 10pt, $charge #i$), curve: 0.5) transition("L0", "L6", label: text(size: 10pt, $charge #i$), curve: 1) }) #let r2-alternate = v(1em) + cetz.canvas({ import finite.draw: * let mklabel(name) = box(width: 1.6em, align(center, text(size: 10pt, name))) let state_style = (radius: 0.7, final: true) state((0, 0), "I", label: mklabel($I$), initial: "", ..state_style) state((3, 1.5), "N2", label: mklabel($N2$), ..state_style) state((3, -1.5), "N1", label: mklabel($N1$), ..state_style) let chargei(j) = align(center, text(size: 9pt)[ $charge{i}$ \ at station #j ]) transition("I", "N1", label: (text: chargei(2), dist: -0.5), curve: -0.85) transition("I", "N2", label: (text: chargei(1), dist: 0.5), curve: 0.85) transition("N1", "N2", label: (text: chargei(1), dist: 0.5)) transition("N2", "N1", label: (text: chargei(2), dist: 0.5, angle: 90deg)) }) #let r2(i) = v(1em) + cetz.canvas({ import finite.draw: * let scale = 1.7 let (xmin, xmax, ymin, ymax) = (1, 5, 1, 3) let n(x, y, suf) = "X" + str(x) + "Y" + str(y) + suf let transition(s, e, l, curve: 0.12) = { let label = (text: text(size: 5pt, l), dist: 0.15) if no-labels { label = none } finite.draw.transition(s, e, curve: curve, label: label) } let pos(bx, by, suf) = { for x in range(xmin, xmax+1) { for y in range(ymin, ymax+1) { let initial = false if (suf, i, x, y) == ("I", 1, 1, 1) or (suf, i, x, y) == ("I", 2, 4, 2) { let anchor = if i == 1 { alignment.left } else { top + alignment.left } initial = (text: "", anchor: anchor) } state( (bx + scale * x, by + -scale * y), n(x, y, suf), label: box(width: 1em, align(center, text(size: 5.5pt, n(x, y, suf)))), radius: 0.5, initial: initial, final: true ) } } transition(n(2, 2, suf), n(1, 2, suf), $uleft #i$) transition(n(2, 2, suf), n(3, 2, suf), $uright #i$) transition(n(2, 2, suf), n(2, 1, suf), $uup #i$) transition(n(2, 2, suf), n(2, 3, suf), $udown #i$) for x in range(xmin, xmax+1) { for y in range(ymin, ymax+1) { if (x, y) == (2, 2) { continue } if x != xmin { transition(n(x, y, suf), n(x - 1, y, suf), $left #i$) } if x != xmax { transition(n(x, y, suf), n(x + 1, y, suf), $right #i$) } if y != ymin { transition(n(x, y, suf), n(x, y - 1, suf), $up #i$) } if y != ymax { transition(n(x, y, suf), n(x, y + 1, suf), $down #i$) } } } } pos(0, scale*1.5, "I") pos(scale*5, 0, "N1") pos(scale*5, scale*3, "N2") transition(n(1, 1, "I"), n(1, 1, "N2"), $charge #i$, curve: 1) transition(n(4, 2, "I"), n(4, 2, "N1"), $charge #i$, curve: -0.3) transition(n(1, 1, "N1"), n(1, 1, "N2"), $charge #i$, curve: 0.75) transition(n(4, 2, "N2"), n(4, 2, "N1"), $charge #i$, curve: 0.6) }) #let r2-compact(i) = v(1em) + cetz.canvas({ import finite.draw: * let mklabel(name) = box(width: 1.6em, align(center, name)) for y in range(1, 3+1) { let name = "Y" + str(y) + "I" let initial = if y == i { "" } else { false } state((0, -3 * y), name, label: mklabel(name), initial: initial, final: true) for (i, n) in ("N1", "N2").enumerate() { let name = "Y" + str(y) + n state((4 * (i + 1), -3 * y), name, label: mklabel(name), final: true) } } for n in ("I", "N1", "N2") { for y in (1, 2) { let label1 = (text: align(center)[ $up #i$ \ $uup #i$ ], dist: 0.6) let label2 = (text: align(center)[ $down #i$ \ $udown #i$ ], dist: 0.6) transition("Y" + str(y + 1) + n, "Y" + str(y) + n, curve: 0.5, label: label1) transition("Y" + str(y) + n, "Y" + str(y + 1) + n, curve: 0.5, label: label2) } } transition("Y1I", "Y1N2", label: $charge #i$, curve: 1) transition("Y2I", "Y2N1", label: $charge #i$, curve: 0.01) transition("Y1N1", "Y1N2", label: $charge #i$, curve: 0) transition("Y2N2", "Y2N1", label: $charge #i$, curve: 0) }) #let r3 = cetz.canvas({ import finite.draw: * let mklabel(name) = box(width: 1.6em, align(center, text(size: 9.5pt, name))) let xstates = ("L4", "L3", "L2", "L1", "SX", "R1", "R2", "R3", "R4") let ystates = ("U2", "U1", "SY", "D1", "D2") let label(l) = align(center, text(size: 2pt, l)) let l1 = label[ $right 1$ \ $uright 1$ \ $left 2$ \ $uleft 2$ ] let l2 = label[ $left 1$ \ $uleft 1$ \ $right 2$ \ $uright 2$ ] let l3 = label[ $down 1$ \ $udown 1$ \ $up 2$ \ $uup 2$ ] let l4 = label[ $up 1$ \ $uup 1$ \ $down 2$ \ $udown 2$ ] if no-labels { (l1, l2, l3, l4) = ("", "", "", "") } for (x, xs) in xstates.enumerate() { for (y, ys) in ystates.enumerate() { if (xs, ys) == ("SX", "SY") { continue } let initial = (label: "", anchor: top + alignment.left) let initial = if (xs, ys) == ("L3", "U1") { initial } else { false } let style = (label: mklabel(var(xs + ys)), initial: initial, final: true) state((1.8 * x, -1.8 * y), xs + ys, ..style) } } for y in ystates { for (x1, x2) in xstates.zip(xstates.slice(1)) { if y == "SY" and (x1 == "SX" or x2 == "SX") { continue } transition(x1 + y, x2 + y, label: l1, curve: 0.1) transition(x2 + y, x1 + y, label: l2, curve: 0.1) } } for x in xstates { for (y1, y2) in ystates.zip(ystates.slice(1)) { if x == "SX" and (y1 == "SY" or y2 == "SY") { continue } transition(x + y1, x + y2, label: l3, curve: 0.1) transition(x + y2, x + y1, label: l4, curve: 0.1) } } }) #let r3-sametile = cetz.canvas({ import finite.draw: * let mklabel(name) = box(width: 1.6em, align(center, text(size: 11pt, name))) let valid_style = (initial: "", final: true) state((0, 0), "Valid", radius: 0.8, label: mklabel($Valid$), ..valid_style) state((4, 0), "Invalid", radius: 0.8, label: mklabel($Invalid$)) transition("Valid", "Invalid", label: $sametile$, curve: 0.01) }) #let r3-xy(states, si, sc, l1, l2) = cetz.canvas({ import finite.draw: * for (i, s) in states.enumerate() { let initial = if s == si { (label: "", anchor: top) } else { false } state((1.8 * i, 0), s, label: var(s), initial: initial, final: true) } for (s1, s2) in states.zip(states.slice(1)) { transition(s1, s2, label: (text: align(center, text(size: 10pt, l1)), dist: 0.9)) transition(s2, s1, label: (text: align(center, text(size: 10pt, l2)), dist: 0.9)) } loop(sc, label: (text: text(size: 10pt, $sametile$), angle: 90deg, dist: 0.8)) }) #let r3-x = r3-xy( ("L4", "L3", "L2", "L1", "SX", "R1", "R2", "R3", "R4"), "L3", "SX", [ $right 1$ \ $uright 1$ \ $left 2$ \ $uleft 2$ ], [ $left 1$ \ $uleft 1$ \ $right 2$ \ $uright 2$ ], ) #let r3-y = r3-xy( ("U2", "U1", "SY", "D1", "D2"), "U1", "SY", [ $down 1$ \ $udown 1$ \ $up 2$ \ $uup 2$ ], [ $up 1$ \ $uup 1$ \ $down 2$ \ $udown 2$ ], ) #let r3-compact = v(1em) + r3-sametile + r3-x + r3-y
https://github.com/lcharleux/LCharleux_Teaching_Typst
https://raw.githubusercontent.com/lcharleux/LCharleux_Teaching_Typst/main/src/templates/conf.typ
typst
MIT License
#import "@preview/chic-hdr:0.4.0": * // UTILITY FUNCTIONS #let todo = what => rect(fill: rgb("#f2726da1"), stroke: black)[*To do*: #what] #let comment = what => rect( fill: rgb("#50b56aa1"), stroke: black, )[*Comment*: #what] #let idea = what => rect(fill: rgb("#4346aba1"), stroke: black)[*Ideas*: #what] #let note = what => rect(fill: rgb("#bdb541a1"), stroke: black)[*Note*: #what] #let important(what) = { rect(fill: rgb("#a44444a1"), stroke: black)[*Important*: #what] } // MATH FUNCTIONS #let conf( course: none, block: none, section: none, teacher: none, email: none, doc, ) = { show figure.caption: set text(10pt) // set text(font: "PT Sans", size: 10pt) set text(font: "Linux Libertine", size: 11pt) set par(justify: true) set heading(numbering: "1.a") show bibliography: set heading(numbering: "1") show bibliography: it => { set text(size: 10pt) show heading: set text(size: 12pt) it } show table.cell.where(x: 1): set text(weight: "medium") show table.cell.where(y: 0): set text(weight: "bold") // See the strokes section for details on this! let frame(stroke) = ( (x, y) => ( left: if x > 0 { 0pt } else { stroke }, right: stroke, top: if y < 2 { stroke } else { 0pt }, bottom: stroke, ) ) set table(fill: (rgb("EAF2F5"), none), stroke: frame(rgb("21222C"))) // set page(footer: context [ // *<NAME> #sym.bar.h #course #sym.bar.h #block * // #h(1fr) // #counter(page).display("1/1", both: true) // ]) place(top + left, image("pac.png", height: 1cm, fit: "contain")) place(top + right, image("USMB_logo.svg", height: 1cm, fit: "contain")) // align(center)[ // #text(12pt, luma(100))[ // <NAME>\ // #section // ] // ] // box( // stroke: black, // inset: 1em, // width: 1fr, // )[ // #text(10pt)[ // *Cours : #course* \ // *Bloc: #block* \ // *Enseignant : #teacher* // ] // ] align( center + horizon, [ #text(17pt)[*#course*] \ #text(15pt)[#block] \ #text(13pt)[#section] #align(center)[ #teacher \ #link("mailto:" + email, email) \ <NAME> \ ] #outline(title: "Plan du cours", depth:2, indent:auto) ], ) show link: this => { let show-type = "box" // "box" or "filled", see below let label-color = green let default-color = rgb("#6694ff") if show-type == "box" { if type(this.dest) == label { // Make the box bound the entire text: set text(bottom-edge: "bounds", top-edge: "bounds") box(this, stroke: label-color + 1pt) } else { set text(bottom-edge: "bounds", top-edge: "bounds") box(this, stroke: default-color + 1pt) } } else if show-type == "filled" { if type(this.dest) == label { text(this, fill: label-color) } else { text(this, fill: default-color) } } else { this } } show: chic.with( chic-footer( left-side: strong( link("mailto:" + email, email), ), right-side: chic-page-number(), ), chic-header( left-side: emph(chic-heading-name(fill: true)), right-side: smallcaps([#course]), ), chic-separator(1pt), chic-offset(7pt), chic-height(1.5cm), ) doc }
https://github.com/andreinonea/introduction-to-fuzzy-logic-control
https://raw.githubusercontent.com/andreinonea/introduction-to-fuzzy-logic-control/master/fuzzy-logic.typ
typst
#set page(paper: "presentation-4-3") #image( "src/01_Introduction+to+Fuzzy+Logic+Control.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/02_Overview+Outline+to+the+left+in+green+Current+topic+in+yellow.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/03_References+References.+Introduction.+Crisp+Variables.+Fuzzy+Sets.+Linguistic+Variables.+Membership+Functions..jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/04_Introduction+Fuzzy+logic_.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/05_Crisp+(Traditional)+Variables.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/06_Fuzzy+Sets+What+if+Richard+is+only+somewhat+greedy.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/07_Fuzzy+Linguistic+Variables.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/08_Membership+Functions+Temp_+{Freezing,+Cool,+Warm,+Hot}.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/09_Membership+Functions+How+cool+is+36+F°+References+Introduction.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/10_Membership+Functions+How+cool+is+36+F°.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/11_Fuzzy+Logic+References.+Introduction.+Crisp+Variables.+Fuzzy+Sets.+Linguistic+Variables.+Membership+Functions..jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/12_Fuzzy+Disjunction+AB+max(A,+B).jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/13_Fuzzy+Conjunction+AB+min(A,+B).jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/14_Example_+Fuzzy+Conjunction.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/15_Example_+Fuzzy+Conjunction (1).jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/16_Example_+Fuzzy+Conjunction (2).jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/17_Example_+Fuzzy+Conjunction (3).jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/18_Example_+Fuzzy+Conjunction (4).jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/19_Fuzzy+Control+References.+Introduction.+Crisp+Variables.+Fuzzy+Sets.+Linguistic+Variables.+Membership+Functions..jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/20_Inputs_+Temperature+Temp_+{Freezing,+Cool,+Warm,+Hot}+References.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/21_Inputs_+Temperature,+Cloud+Cover.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/22_Output_+Speed+Speed_+{Slow,+Fast}+References+Introduction.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/23_Rules+If+it+s+Sunny+and+Warm,+drive+Fast.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/24_Example+Speed+Calculation.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/25_Fuzzification_+Calculate+Input+Membership+Levels.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/26_Fuzzification_+Calculate+Input+Membership+Levels (1).jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/27_Calculating...+If+it+s+Sunny+and+Warm,+drive+Fast.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/28_Defuzzification_+Constructing+the+Output.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/29_Defuzzification_+Constructing+the+Output (1).jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/30_Defuzzification_+Constructing+the+Output (2).jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/31_Defuzzification_+Constructing+the+Output (3).jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/32_Notes_+Follow-up+Points.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/33_Notes_+Drawbacks+to+Fuzzy+logic.jpg", width: 100%, height: 100%, fit: "cover", ) #pagebreak() #image( "src/34_Summary+References.+Introduction.+Crisp+Variables.+Fuzzy+Sets.+Linguistic+Variables.+Membership+Functions..jpg", width: 100%, height: 100%, fit: "cover", )
https://github.com/lkndl/typst-bioinfo-thesis
https://raw.githubusercontent.com/lkndl/typst-bioinfo-thesis/main/modules/styles.typ
typst
#let quantum = 8pt #let page-num-width = 2em #let space = 2.2cm #let raw-style = (font: "IBM Plex Mono", size: 1.2em) // the default font size in the doc defines what 1em is, and this always looked a bit too small, therefore scale it // use a state to manage whether the caption title or the full thing is displayed at different places in the do // https://github.com/typst/typst/issues/1295#issuecomment-1853762154 #let in-outline = state("in-outline", false) #let flex-caption(title, rest) = locate(loc => if in-outline.at(loc) { title } else { title + rest } ) // set in typewriter, blue against a gray background #let ibm(it) = { h(1pt, weak:false) box(fill: luma(250), outset: 2pt, radius: 2pt, //it) text(..raw-style, size: 1em, fill: rgb("#1A68AD"), it)) // use default size 1em here again h(1pt, weak:false) } // refer to the page of a labeled element in the doc #let ref-page(label, supplement: "page") = { locate(loc => { let match = query(label, loc) if match == none { panic() } match = match.first().location() link(match, box([#supplement #counter(page).at(match).first()])) }) } #let empty-page() = { page([], header: [], footer: []) } // citation shorthand #let citeprose(label) = cite(label, form: "prose") #let citeauthor(label) = cite(label, form: "author") // fix reference styles: level 1 headings are chapter, not Section #let supplements(it, lang) = { if "level" not in it.fields() { return none } else if lang == "en" { // per default "Section", "Section", ... return ([chapter], [section], [subsection]).at(it.level - 1, default: [subsection]) } else { // i just made these up: return ([Kapitel], [Abschnitt], [Absatz]).at(it.level - 1, default: [Absatz]) } } #let headingspaced(it) = { block(above: 2 * space, below: space / 2, [#v(space)#text(size: 20pt, it)]) } #let heading-styles(lang, numbering-depth, body) = { // define the section numbering set heading( //numbering: "1.1", numbering: (..nums) => { let nums = nums.pos() if nums.len() <= numbering-depth { numbering("1.1", ..nums) }}, outlined: true, supplement: it => supplements(it, lang)) // add space above chapters, later enforce a pagebreak show heading.where(level: 1): it => headingspaced(it) show heading.where(level: 2): it => [ #block(above: 11mm, below: 6mm)[#it] ] // show heading.where(level: 3): it => [ // #block(above: 11mm, below: 6mm)[#it.body] ] // hide the numbering body } #let break-before-chapter(on: true, body) = { // turning this on and off is a fix until https://github.com/typst/typst/issues/2841 is resolved if on { show heading.where(level: 1): it => pagebreak(weak: true) + headingspaced(it) } else { show heading.where(level: 1): it => headingspaced(it) } body } #let continue-page-counter-from(label, shift: none) = { // shift: if it's broken don't fret - just fix it. Life is more than LaTeX or Typst locate(loc => { let i = { if shift != none { shift } else { -int(calc.odd(loc.page())) } } let toc-end = query(label, loc) let restart-at = { if toc-end.len() == 0 { 1 } else { toc-end.first().location().page() } } // locate can only return content, therefore update the page counter here instead counter(page).update(restart-at + i) }) } // Pure typst re-implementation of flawed typst-native `repeat` // by EpicEricEE from here: https://github.com/typst/typst/issues/2713#issue-2000578599 // // Repeat the given content to fill the full space. // // Parameters: // - gap: The gap between repeated items. (Default: none) // - justify: Whether to increase the gap to justify the items. (Default: false) // // Returns: The repeated content. #let typst-repeat( gap: none, justify: false, body ) = layout(size => style(styles => { let pt(length) = measure(h(length), styles).width let width = measure(body, styles).width let amount = calc.floor(pt(size.width + gap) / pt(width + gap)) let gap = if not justify { gap } else { (size.width - amount * width) / (amount - 1) } let items = ((box(body),) * amount) if type(gap) == length and gap != 0pt { items = items.intersperse(h(gap)) } items.join() }))
https://github.com/DaavidT/CV-2023
https://raw.githubusercontent.com/DaavidT/CV-2023/main/modules/skills.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Skills") #cvSkill( type: [Idiomas], info: [Español #hBar() Inglés (B2)] ) #cvSkill( type: [Lenguajes de Programación], info: [ JavaScript #hBar() TypeScript #hBar() Python #hBar() C++ #hBar() C #hBar() PHP #hBar() SQL #hBar() HTML #hBar() CSS] ) #cvSkill( type: [Competencias], info: [Liderazgo #hBar() Trabajo en equipo #hBar() Habilidades Sociales ] ) #cvSkill( type: [Tegnologías], info: [React #hBar() Node #hBar() Oracle SQL #hBar() Git #hBar() Docker #hBar() AWS #hBar() Linux #hBar() Windows #hBar() Mac OS] ) #cvSkill( type: [Intereses Personales], info: [Natación #hBar() Fotografía #hBar() Videojuegos #hBar() Ciclismo] )
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/049.%20ideas.html.typ
typst
ideas.html Ideas for Startups Want to start a startup? Get funded by Y Combinator. October 2005(This essay is derived from a talk at the 2005 Startup School.)How do you get good ideas for startups? That's probably the number one question people ask me.I'd like to reply with another question: why do people think it's hard to come up with ideas for startups?That might seem a stupid thing to ask. Why do they think it's hard? If people can't do it, then it is hard, at least for them. Right?Well, maybe not. What people usually say is not that they can't think of ideas, but that they don't have any. That's not quite the same thing. It could be the reason they don't have any is that they haven't tried to generate them.I think this is often the case. I think people believe that coming up with ideas for startups is very hard-- that it must be very hard-- and so they don't try do to it. They assume ideas are like miracles: they either pop into your head or they don't.I also have a theory about why people think this. They overvalue ideas. They think creating a startup is just a matter of implementing some fabulous initial idea. And since a successful startup is worth millions of dollars, a good idea is therefore a million dollar idea.If coming up with an idea for a startup equals coming up with a million dollar idea, then of course it's going to seem hard. Too hard to bother trying. Our instincts tell us something so valuable would not be just lying around for anyone to discover.Actually, startup ideas are not million dollar ideas, and here's an experiment you can try to prove it: just try to sell one. Nothing evolves faster than markets. The fact that there's no market for startup ideas suggests there's no demand. Which means, in the narrow sense of the word, that startup ideas are worthless.QuestionsThe fact is, most startups end up nothing like the initial idea. It would be closer to the truth to say the main value of your initial idea is that, in the process of discovering it's broken, you'll come up with your real idea.The initial idea is just a starting point-- not a blueprint, but a question. It might help if they were expressed that way. Instead of saying that your idea is to make a collaborative, web-based spreadsheet, say: could one make a collaborative, web-based spreadsheet? A few grammatical tweaks, and a woefully incomplete idea becomes a promising question to explore.There's a real difference, because an assertion provokes objections in a way a question doesn't. If you say: I'm going to build a web-based spreadsheet, then critics-- the most dangerous of which are in your own head-- will immediately reply that you'd be competing with Microsoft, that you couldn't give people the kind of UI they expect, that users wouldn't want to have their data on your servers, and so on.A question doesn't seem so challenging. It becomes: let's try making a web-based spreadsheet and see how far we get. And everyone knows that if you tried this you'd be able to make something useful. Maybe what you'd end up with wouldn't even be a spreadsheet. Maybe it would be some kind of new spreasheet-like collaboration tool that doesn't even have a name yet. You wouldn't have thought of something like that except by implementing your way toward it.Treating a startup idea as a question changes what you're looking for. If an idea is a blueprint, it has to be right. But if it's a question, it can be wrong, so long as it's wrong in a way that leads to more ideas.One valuable way for an idea to be wrong is to be only a partial solution. When someone's working on a problem that seems too big, I always ask: is there some way to bite off some subset of the problem, then gradually expand from there? That will generally work unless you get trapped on a local maximum, like 1980s-style AI, or C.UpwindSo far, we've reduced the problem from thinking of a million dollar idea to thinking of a mistaken question. That doesn't seem so hard, does it?To generate such questions you need two things: to be familiar with promising new technologies, and to have the right kind of friends. New technologies are the ingredients startup ideas are made of, and conversations with friends are the kitchen they're cooked in.Universities have both, and that's why so many startups grow out of them. They're filled with new technologies, because they're trying to produce research, and only things that are new count as research. And they're full of exactly the right kind of people to have ideas with: the other students, who will be not only smart but elastic-minded to a fault.The opposite extreme would be a well-paying but boring job at a big company. Big companies are biased against new technologies, and the people you'd meet there would be wrong too.In an essay I wrote for high school students, I said a good rule of thumb was to stay upwind-- to work on things that maximize your future options. The principle applies for adults too, though perhaps it has to be modified to: stay upwind for as long as you can, then cash in the potential energy you've accumulated when you need to pay for kids.I don't think people consciously realize this, but one reason downwind jobs like churning out Java for a bank pay so well is precisely that they are downwind. The market price for that kind of work is higher because it gives you fewer options for the future. A job that lets you work on exciting new stuff will tend to pay less, because part of the compensation is in the form of the new skills you'll learn.Grad school is the other end of the spectrum from a coding job at a big company: the pay's low but you spend most of your time working on new stuff. And of course, it's called "school," which makes that clear to everyone, though in fact all jobs are some percentage school.The right environment for having startup ideas need not be a university per se. It just has to be a situation with a large percentage of school.It's obvious why you want exposure to new technology, but why do you need other people? Can't you just think of new ideas yourself? The empirical answer is: no. Even Einstein needed people to bounce ideas off. Ideas get developed in the process of explaining them to the right kind of person. You need that resistance, just as a carver needs the resistance of the wood.This is one reason Y Combinator has a rule against investing in startups with only one founder. Practically every successful company has at least two. And because startup founders work under great pressure, it's critical they be friends.I didn't realize it till I was writing this, but that may help explain why there are so few female startup founders. I read on the Internet (so it must be true) that only 1.7% of VC-backed startups are founded by women. The percentage of female hackers is small, but not that small. So why the discrepancy?When you realize that successful startups tend to have multiple founders who were already friends, a possible explanation emerges. People's best friends are likely to be of the same sex, and if one group is a minority in some population, pairs of them will be a minority squared. [1]DoodlingWhat these groups of co-founders do together is more complicated than just sitting down and trying to think of ideas. I suspect the most productive setup is a kind of together-alone-together sandwich. Together you talk about some hard problem, probably getting nowhere. Then, the next morning, one of you has an idea in the shower about how to solve it. He runs eagerly to to tell the others, and together they work out the kinks.What happens in that shower? It seems to me that ideas just pop into my head. But can we say more than that?Taking a shower is like a form of meditation. You're alert, but there's nothing to distract you. It's in a situation like this, where your mind is free to roam, that it bumps into new ideas.What happens when your mind wanders? It may be like doodling. Most people have characteristic ways of doodling. This habit is unconscious, but not random: I found my doodles changed after I started studying painting. I started to make the kind of gestures I'd make if I were drawing from life. They were atoms of drawing, but arranged randomly. [2]Perhaps letting your mind wander is like doodling with ideas. You have certain mental gestures you've learned in your work, and when you're not paying attention, you keep making these same gestures, but somewhat randomly. In effect, you call the same functions on random arguments. That's what a metaphor is: a function applied to an argument of the wrong type.Conveniently, as I was writing this, my mind wandered: would it be useful to have metaphors in a programming language? I don't know; I don't have time to think about this. But it's convenient because this is an example of what I mean by habits of mind. I spend a lot of time thinking about language design, and my habit of always asking "would x be useful in a programming language" just got invoked.If new ideas arise like doodles, this would explain why you have to work at something for a while before you have any. It's not just that you can't judge ideas till you're an expert in a field. You won't even generate ideas, because you won't have any habits of mind to invoke.Of course the habits of mind you invoke on some field don't have to be derived from working in that field. In fact, it's often better if they're not. You're not just looking for good ideas, but for good new ideas, and you have a better chance of generating those if you combine stuff from distant fields. As hackers, one of our habits of mind is to ask, could one open-source x? For example, what if you made an open-source operating system? A fine idea, but not very novel. Whereas if you ask, could you make an open-source play? you might be onto something.Are some kinds of work better sources of habits of mind than others? I suspect harder fields may be better sources, because to attack hard problems you need powerful solvents. I find math is a good source of metaphors-- good enough that it's worth studying just for that. Related fields are also good sources, especially when they're related in unexpected ways. Everyone knows computer science and electrical engineering are related, but precisely because everyone knows it, importing ideas from one to the other doesn't yield great profits. It's like importing something from Wisconsin to Michigan. Whereas (I claim) hacking and painting are also related, in the sense that hackers and painters are both makers, and this source of new ideas is practically virgin territory.ProblemsIn theory you could stick together ideas at random and see what you came up with. What if you built a peer-to-peer dating site? Would it be useful to have an automatic book? Could you turn theorems into a commodity? When you assemble ideas at random like this, they may not be just stupid, but semantically ill-formed. What would it even mean to make theorems a commodity? You got me. I didn't think of that idea, just its name.You might come up with something useful this way, but I never have. It's like knowing a fabulous sculpture is hidden inside a block of marble, and all you have to do is remove the marble that isn't part of it. It's an encouraging thought, because it reminds you there is an answer, but it's not much use in practice because the search space is too big.I find that to have good ideas I need to be working on some problem. You can't start with randomness. You have to start with a problem, then let your mind wander just far enough for new ideas to form.In a way, it's harder to see problems than their solutions. Most people prefer to remain in denial about problems. It's obvious why: problems are irritating. They're problems! Imagine if people in 1700 saw their lives the way we'd see them. It would have been unbearable. This denial is such a powerful force that, even when presented with possible solutions, people often prefer to believe they wouldn't work.I saw this phenomenon when I worked on spam filters. In 2002, most people preferred to ignore spam, and most of those who didn't preferred to believe the heuristic filters then available were the best you could do.I found spam intolerable, and I felt it had to be possible to recognize it statistically. And it turns out that was all you needed to solve the problem. The algorithm I used was ridiculously simple. Anyone who'd really tried to solve the problem would have found it. It was just that no one had really tried to solve the problem. [3]Let me repeat that recipe: finding the problem intolerable and feeling it must be possible to solve it. Simple as it seems, that's the recipe for a lot of startup ideas.WealthSo far most of what I've said applies to ideas in general. What's special about startup ideas? Startup ideas are ideas for companies, and companies have to make money. And the way to make money is to make something people want.Wealth is what people want. I don't mean that as some kind of philosophical statement; I mean it as a tautology.So an idea for a startup is an idea for something people want. Wouldn't any good idea be something people want? Unfortunately not. I think new theorems are a fine thing to create, but there is no great demand for them. Whereas there appears to be great demand for celebrity gossip magazines. Wealth is defined democratically. Good ideas and valuable ideas are not quite the same thing; the difference is individual tastes.But valuable ideas are very close to good ideas, especially in technology. I think they're so close that you can get away with working as if the goal were to discover good ideas, so long as, in the final stage, you stop and ask: will people actually pay for this? Only a few ideas are likely to make it that far and then get shot down; RPN calculators might be one example.One way to make something people want is to look at stuff people use now that's broken. Dating sites are a prime example. They have millions of users, so they must be promising something people want. And yet they work horribly. Just ask anyone who uses them. It's as if they used the worse-is-better approach but stopped after the first stage and handed the thing over to marketers.Of course, the most obvious breakage in the average computer user's life is Windows itself. But this is a special case: you can't defeat a monopoly by a frontal attack. Windows can and will be overthrown, but not by giving people a better desktop OS. The way to kill it is to redefine the problem as a superset of the current one. The problem is not, what operating system should people use on desktop computers? but how should people use applications? There are answers to that question that don't even involve desktop computers.Everyone thinks Google is going to solve this problem, but it is a very subtle one, so subtle that a company as big as Google might well get it wrong. I think the odds are better than 50-50 that the Windows killer-- or more accurately, Windows transcender-- will come from some little startup.Another classic way to make something people want is to take a luxury and make it into a commmodity. People must want something if they pay a lot for it. And it is a very rare product that can't be made dramatically cheaper if you try.This was <NAME>'s plan. He made cars, which had been a luxury item, into a commodity. But the idea is much older than <NAME>. Water mills transformed mechanical power from a luxury into a commodity, and they were used in the Roman empire. Arguably pastoralism transformed a luxury into a commodity.When you make something cheaper you can sell more of them. But if you make something dramatically cheaper you often get qualitative changes, because people start to use it in different ways. For example, once computers get so cheap that most people can have one of their own, you can use them as communication devices.Often to make something dramatically cheaper you have to redefine the problem. The Model T didn't have all the features previous cars did. It only came in black, for example. But it solved the problem people cared most about, which was getting from place to place.One of the most useful mental habits I know I learned from Michael Rabin: that the best way to solve a problem is often to redefine it. A lot of people use this technique without being consciously aware of it, but Rabin was spectacularly explicit. You need a big prime number? Those are pretty expensive. How about if I give you a big number that only has a 10 to the minus 100 chance of not being prime? Would that do? Well, probably; I mean, that's probably smaller than the chance that I'm imagining all this anyway.Redefining the problem is a particularly juicy heuristic when you have competitors, because it's so hard for rigid-minded people to follow. You can work in plain sight and they don't realize the danger. Don't worry about us. We're just working on search. Do one thing and do it well, that's our motto.Making things cheaper is actually a subset of a more general technique: making things easier. For a long time it was most of making things easier, but now that the things we build are so complicated, there's another rapidly growing subset: making things easier to use.This is an area where there's great room for improvement. What you want to be able to say about technology is: it just works. How often do you say that now?Simplicity takes effort-- genius, even. The average programmer seems to produce UI designs that are almost willfully bad. I was trying to use the stove at my mother's house a couple weeks ago. It was a new one, and instead of physical knobs it had buttons and an LED display. I tried pressing some buttons I thought would cause it to get hot, and you know what it said? "Err." Not even "Error." "Err." You can't just say "Err" to the user of a stove. You should design the UI so that errors are impossible. And the boneheads who designed this stove even had an example of such a UI to work from: the old one. You turn one knob to set the temperature and another to set the timer. What was wrong with that? It just worked.It seems that, for the average engineer, more options just means more rope to hang yourself. So if you want to start a startup, you can take almost any existing technology produced by a big company, and assume you could build something way easier to use.Design for ExitSuccess for a startup approximately equals getting bought. You need some kind of exit strategy, because you can't get the smartest people to work for you without giving them options likely to be worth something. Which means you either have to get bought or go public, and the number of startups that go public is very small.If success probably means getting bought, should you make that a conscious goal? The old answer was no: you were supposed to pretend that you wanted to create a giant, public company, and act surprised when someone made you an offer. Really, you want to buy us? Well, I suppose we'd consider it, for the right price.I think things are changing. If 98% of the time success means getting bought, why not be open about it? If 98% of the time you're doing product development on spec for some big company, why not think of that as your task? One advantage of this approach is that it gives you another source of ideas: look at big companies, think what they should be doing, and do it yourself. Even if they already know it, you'll probably be done faster.Just be sure to make something multiple acquirers will want. Don't fix Windows, because the only potential acquirer is Microsoft, and when there's only one acquirer, they don't have to hurry. They can take their time and copy you instead of buying you. If you want to get market price, work on something where there's competition.If an increasing number of startups are created to do product development on spec, it will be a natural counterweight to monopolies. Once some type of technology is captured by a monopoly, it will only evolve at big company rates instead of startup rates, whereas alternatives will evolve with especial speed. A free market interprets monopoly as damage and routes around it.The Woz RouteThe most productive way to generate startup ideas is also the most unlikely-sounding: by accident. If you look at how famous startups got started, a lot of them weren't initially supposed to be startups. Lotus began with a program <NAME> wrote for a friend. Apple got started because <NAME> wanted to build microcomputers, and his employer, Hewlett-Packard, wouldn't let him do it at work. Yahoo began as <NAME>'s personal collection of links.This is not the only way to start startups. You can sit down and consciously come up with an idea for a company; we did. But measured in total market cap, the build-stuff-for-yourself model might be more fruitful. It certainly has to be the most fun way to come up with startup ideas. And since a startup ought to have multiple founders who were already friends before they decided to start a company, the rather surprising conclusion is that the best way to generate startup ideas is to do what hackers do for fun: cook up amusing hacks with your friends.It seems like it violates some kind of conservation law, but there it is: the best way to get a "million dollar idea" is just to do what hackers enjoy doing anyway. Notes[1] This phenomenon may account for a number of discrepancies currently blamed on various forbidden isms. Never attribute to malice what can be explained by math.[2] A lot of classic abstract expressionism is doodling of this type: artists trained to paint from life using the same gestures but without using them to represent anything. This explains why such paintings are (slightly) more interesting than random marks would be.[3] <NAME> had solved the problem, but he got there by another path. He made a general-purpose file classifier so good that it also worked for spam.One Specific IdeaRomanian TranslationJapanese TranslationTraditional Chinese TranslationRussian TranslationArabic Translation
https://github.com/QRWells/uni-theme
https://raw.githubusercontent.com/QRWells/uni-theme/main/sample-en.typ
typst
MIT License
#import "@preview/tablex:0.0.8": tablex, rowspanx, colspanx #import "@preview/polylux:0.3.1": * #import "uni-theme-en.typ": * // define theme colors #let color-a = rgb("04364A"); #let color-b = rgb("176B87"); #let color-c = rgb("448C95"); #show: uni-theme.with( short-author: "Author 1", short-title: "Example Title of the Presentation", date: datetime(year:2024, month: 2, day:2), color-a: color-a, color-b: color-b, color-c: color-c, ) #title-slide( authors: ("Author 1", "Author 2"), title: "Example Title of the Presentation", subtitle: "Approach to solving the problem", lab-name: "XXX", institution-name: "YYY University", ) #slide(title: [Outline], sub-title: [What is the problem?], new-section: [Content])[ == Motivation - What is the problem? == Contribution A new approach to solving the problem. - How does it work? - What are the results? ] #slide(title: [Example], new-section: [Content])[ Reference to the table: @madje2022programmable ```rust enum { A { a: u8 }, } ``` ] #slide(title: [Bibliography], new-section: [])[ #set text(size: 15pt) #bibliography(title:none, style: "the-institution-of-engineering-and-technology","ref.bib") ]
https://github.com/daskol/typst-templates
https://raw.githubusercontent.com/daskol/typst-templates/main/jmlr/format.typ
typst
MIT License
#import "/jmlr.typ": jmlr #import "/logo.typ": LaTeX #let affls = ( one: ( department: "Artificial Intelligence Laboratory", institution: "Massachusetts Institute of Technology", address: "545 Technology Square", location: "Cambridge, MA 02139", country: "USA"), two: ( institution: "Burning Glass Technologies", address: "Burning Glass Technologies", location: "Pittsburgh, PA 15213", country: "USA"), ) #let authors = ( (name: "<NAME>", affl: "one", email: "<EMAIL>"), (name: "<NAME>", affl: "two", email: "<EMAIL>"), ) #show: jmlr.with( title: [Instructions for Formatting JMLR Articles], authors: (authors, affls), abstract: [ This document, which is based on an earlier document by @minton1999, describes the required formatting of JMLR papers, including margins, fonts, citation styles, and figure placement. It describes how authors can obtain and use a #LaTeX style file that will ease adherence to the requirements. It also contains a section on avoiding formatting errors that frequently appear in JMLR submissions. While the format requirements are only compulsory for final submissions, we encourage authors to adopt and adhere to its recommendations throughout the submission process. ], keywords: ("keyword one", "keyword two", "keyword three"), bibliography: bibliography("format.bib"), appendix: include "format-appendix.typ", pubdata: ( id: "21-0000", editor: "My editor", volume: 23, submitted-at: datetime(year: 2021, month: 1, day: 1), revised-at: datetime(year: 2022, month: 5, day: 1), published-at: datetime(year: 2022, month: 9, day: 1), ), ) #let href = it => link(it, raw(it)) = Introduction To ensure that all articles published in the journal have a uniform appearance, authors must produce a PostScript or PDF document that meets the formatting specifications outlined here. The document will be used for both the hardcopy and electronic versions of the journal. This document briefly describes and illustrates the JMLR format. It draws very heavily from an earlier document by @minton1999. Your article should look as similar as possible to the JMLR sample article which can be found at #href("https://github.com/JmlrOrg/jmlr-style-file"). Below we outline the basic specifications, including font sizes, margins, etc. However, the point is to have your articles look similar to the sample, and when in doubt you should use the sample as your guide. Please feel free to contact the editor of JMLR if you have any questions. The remainder of this document is organized as follows. Section 2 describes the style and formatting requirements for JMLR papers. Section 3 describes how to obtain the formatting templates that should simplify following the requirements, and Section 4 describes common formatting errors that should be avoided. = Style and Format Papers must be printed in the single column format as shown in the enclosed sample. Margins should be $1 1/4$ inch left and right. Headers should be $1/2$ inch from top and footer should be $1$ inch from bottom of page. Title should start $1 1/2$ inches from the top of the page. == Fonts You should use Times Roman style fonts. Please be very careful not to use nonstandard or unusual fonts in the paper. Including such fonts will cause problems for many printers. Headers and Footers should be in 9pt type. The title of the paper should be in 14pt bold type. The abstract title should be in 11pt bold type, and the abstract itself should be in 10pt type. First headings should be in 12 point bold type and second headings should be in 11 point bold type. The text and body of the paper should be in 11 point type. == Title and Authors The title appears near the top of the first page, centered. Authors' names should appear in designated areas below the title of the paper in twelve point bold type. Authors' affiliations and complete addresses should be in italics, and their electronic addresses should be in small capitals (see sample article). == Abstract The abstract appears at the beginning of the paper, indented $1/4$ of an inch from the left and right margins. The title "Abstract" should appear in bold face 11 point type, centered above the body of the abstract. The abstract body should be in 10 point type. == Headings and Sections When necessary, headings should be used to separate major sections of your paper. First-level headings should be in 12 point bold type and second-level headings should be in 11 point bold type. Do not skip a line between paragraphs. Third-level headings should also be in 11 point bold type. All headings should be capitalized. After a heading, the first sentence should not be indented. References to sections (as well as figures, tables, theorems and so on), should be capitalized, as in "In Section 4, we show that...". === Appendices Appendices, if included, follow the acknowledgments. Each appendix should be lettered, e.g., "Appendix A". If online appendices are submitted, they should not be included in the final manuscript (see below), although they may be referred to in the manuscript. They will be published online in separate files. The online appendices should be numbered and referred to as Online Appendix 1, Online Appendix 2, etc. === Acknowledgements and Disclosure of Funding All acknowledgements go at the end of the paper before appendices and references. Moreover, you are required to declare funding (financial activities supporting the submitted work) and competing interests (related financial activities outside the submitted work). == Figures and Tables Figures and tables should be inserted in proper places throughout the text. Do not group them together at the beginning of a page, nor at the bottom of the paper. Number figures sequentially, e.g., Figure 1, and so on. The figure or table number and the caption should appear under the illustration. Leave a margin of one-quarter inch around the area covered by the figure and caption. Captions, labels, and other text in illustrations must be at least nine-point type. At present, some types of illustrations in your manuscript may cause problems for some printers/previewers. Although this is gradually becoming less of an issue, we encourage authors to use "reliable" programs for producing figures. Before your paper can be accepted, we must verify that all your figures print successfully on our printers and may be viewed with Adobe Acrobat Reader or Ghostview. == Headers and Footers The first page of your article should include the journal name, volume number, year and page numbers in the upper left corner, the submission date and publication date in the upper right corner, and the copyright notice in the lower left corner. The editor will let you know the volume number, year, pages, submission date and publication date. On the even numbered pages, the header of the page should be the authors' names. On the odd pages, starting with page 3, the header should be the title of the paper (shortened if necessary, as in the sample). === Page Numbering and Publication Date Leave the page number starting at one. The Production Editor will change the page numbers according to the actual order of publication, and will insert the proper page numbers in the heading of your article. For submission dates, please do the following. If the paper was accepted with no revisions the first time just include the submission date (month and year) as the fourth argument to the `\jmlrheading` command. For example, for a paper submitted February 12, 2005, the fourth argument should be ```tex 2/05 ``` If your paper was returned for revisions, please insert the original date of submission followed by the text "; Revised " and then the date the revision was submitted, like this (for a paper originally submitted Feb, 2005 and resubmitted in April of 2005): ``` 2/05; Revised 4/05 ``` You may leave the publication date (the fifth argument to `\jmlrheading`) blank and it will be filled in by the Production Editor. === Footnotes We encourage authors to use footnotes sparingly, especially since they may be difficult to read online. Footnotes should be numbered sequentially and should appear at the bottom of the page, as shown below.#footnote[A footnote should appear like this. Please ensure that your footnotes are complete, fully punctuated sentences.] == References The reference section should be labeled "References" and should appear at the end of the paper in natbib format. A sample list of references is given in Appendix A. Poorly prepared, incomplete or sloppy references reflect badly on the quality of your scholarship. Please prepare complete and accurate citations. Citations within the text should include the author's last name and year, for example (Cheeseman, 1992). Append lower-case letters to the year in cases of ambiguity, as in (Cheeseman, 1993a). Multiple authors should be treated as follows: (Cheeseman & Englemore 1988) or (Englemore, <NAME>, 1992). In the case of three or more authors, the citation can be shortened by referring only the first author, followed by "et al.", as in (Clancey et al., 1991). Multiple citations should be separated by a semi-colon, as in (Cheeseman, 1993a; Buntine, 1992). If two works have the same author or authors, the appropriate format is as follows: (Drummond 1990, 1991). If the authors' names are mentioned in the text, the citation need only refer to the year, as in "Cheeseman and Englemore (1988) showed that...". In general, you shouldn't have parenthetical statements embedded in parenthetical statements. Therefore, citations within parenthetical statements should not be embedded in parentheses. Use commas as separators instead. For instance, rather than "(as shown by Bresina (1992))" you should write "(as shown by Bresina, 1992)". Similarly, "(e.g., (Bresina, 1992))" should be "(e.g., Bresina, 1992). Note that the natbib style file supports the inclusion of prefixes in citations. = Formatting Templates To ready your work for publication, please typeset it using software such LATEX that produces PostScript or PDF output (LATEX is preferred.) A LATEX style file is available at #href("https://raw.githubusercontent.com/JmlrOrg/jmlr-style-file/master/jmlr2e.sty"). We hope to eventually have macros/samples for other document preparation systems as well. We recommend working from the LATEX source of the sample article (at #href("https://raw.githubusercontent.com/JmlrOrg/jmlr-style-file/master/sample.tex")), which has been annotated to simplify use of the macros in the style file. If you must use a document preparation system other than LATEX, please discuss this with the editor prior to submitting your final document. If you do not have the software necessary to produce acceptable PostScript or PDF files, the editor will recommend a professional service for formatting your article. (Authors will be responsible for paying for this service). == Using `jmlr2e.sty` The #LaTeX source for the sample paper, at #href("http://www.jmlr.org/format/sample.tex"), details the use of most of the macros in `jmlr2e`; we describe a few of the macros here for illustration. The paper should begin with a specification of the document class and JMLR style file: ```tex \documentclass[twoside,11pt]{article} \usepackage{jmlr2e} ``` The following command can be used in the LaTex version of your paper to set the first page header: ```tex # dates/pages from editor \jmlrheading{1}{2000}{1-48}{4/00}{10/00}{00-000}{author list} ``` To set your title and authors for headings: ```tex \ShortHeadings{short title}{short authors} ``` For example: ```tex \ShortHeadings{Minimizing Conflicts}{Minton et al.} ``` To set your page numbers: ```tex \firstpageno{?} the pagenumber you are assigned to start with by the editor. ``` Authors are specified with the `author` macro: ```tex \author{\name Author One \email author-one-email\\ \addr Author One address line one\\ Author One address line two\\ Author One address line three... \AND \name Author Two \email author-two-email\\ \addr Author Two address line one\\ Author Two address line two\\ Author Two address line three...} ``` If multiple authors share an affiliation, it may be appended to the group by specifying: ```tex \author{\name Author One \email author-one-email\\ \name Author Two \email author-two-email\\ \addr Authors' address line one\\ Authors' address line two\\ Authors' address line three...} ``` == Citations using `natbib` The recommended citation style file, natbib, is included in `jmlr2e.sty`. It supports the citation styles described in Section 2.7 with macros such as `\citep{}` and `\citet{}`. The basic uses of `\citep{}` and `\citet{}` are as follows: ``` \citet{jon90} => Jones et al. (1990) \citet[chap.~2]{jon90} => Jones et al. (1990, chap. 2) \citep{jon90} => (Jones et al., 1990) \citep[chap.~2]{jon90} => (Jones et al., 1990, chap. 2) \citep[see][]{jon90} => (see Jones et al., 1990) \citep[see][chap.~2]{jon90} => (see Jones et al., 1990, chap. 2) \citet*{jon90} => Jones, Baker, and Williams (1990) \citep*{jon90} => (Jones, Baker, and Williams, 1990) ``` For details on making citations with natbib macros, see the natbib documentation @daly1997, a copy of which is available at #href("http://www.jmlr.org/format/natbib.pdf"). = Avoiding Common Errors As we do the final editing passes on JMLR papers, we find a fairly consistent set of problems repeated over and over. Here's a list of them. JMLR won't enforce conformity with these rules, but it would certainly please the editors if you followed them. == Dashes Dashes should be used --- with care --- to set off interjections in a sentence. They should be long and there should not be spaces between them and the preceding and following words. Thus, in LaTeX, the input should look like this: ```tex Dashes should be used---with care---to set off ... ``` == Lower case names The names of fields, algorithms, methods, etc., should be in lower case: cognitive science, reinforcement learning, principal components analysis. Exceptions are when they are in names of organizational entities, like Cognitive Science Department, or when they include proper names, such as Markov decision processes or Gaussian densities, or Bayes' rule. == Latin abbrevs. Scientists seem to like to use the Latin abbreviations i.e. and e.g. First, I'd like to encourage you to try to do without them. If you can't, then use the English equivalents ("that is" instead of i.e. and "for example" instead of e.g.) If you really love the Latin (then you're a Latin lover?) you should at least do it right. There should be a period after each letter (because they're abbreviations), and there should be a comma after the expression. If you're addicted to these things, I encourage you to define and use LaTeX macros like ```tex \newcommand{\ie}{i.e.} ``` == Equation numbers Only number equations that are actually referred to later in the text. == Citations Citations are not nouns. It is not correct to say "Using the method of (Smith, 1999), we ..." Instead, say "Using the method of Smith (1999), we ..." or "Using the method of partial discombobulation (Smith, 1999), we ....". See the section on references (Section 2.7) for more details on correct and incorrect citation forms. == Punctuate math Sentences with mathematical statements in them are still sentences, subject to the usual rules of grammar and punctuation. As @knuth1989 say,#footnote[I recommend this book highly to anyone who likes to think about technical writing. While we're on the subject, I also highly recommend the (sadly, out of print) Handbook for Scholars by @leunen1992.] you should test this by reading out your paper with things like "snort" and "grunt" substituted in for the mathematics and listening to see whether it's grammatically correct. Never put a footnote directly after a mathematical expression; it is too easily confused with an exponent. == Hyphenating compound nouns When you have a long string of nouns together, they often need hyphenation to make the meaning clear (and to make your editor happy). Here are some examples of correct expressions: - reinforcement learning - reinforcement-learning algorithm - delayed-reinforcement learning (learning from delayed reinforcement) - delayed reinforcement learning (reinforcement learning that is delayed) What are the rules? Here's a simple view: by default, modifiers bind to the phrase to their right. If you want to override that, then you need to use a hyphen. Consider the string of words "country chicken pump dispenser" (seen in an actual catalog). A "pump dispenser" is either something that dispenses pumps or that dispenses by pumping. A "chicken pump dispenser" is, perhaps, a pump dispenser in the shape of a chicken. But a "chicken-pump dispenser" is something that dispenses chicken pumps. The object in the catalog was a soap dispenser in the shape of a country chicken (as opposed to a city chicken, I guess) with a pump. So, probably, it should have been a "country-chicken pump dispenser", since "pump" modifies "dispenser," "country" modifies "chicken," and the phrase "country chicken" modifies "pump dispenser." Whew. Many people think it's bad form to use such long strings of nouns anyway. == Don't use "utilize." == Don't start a section with a subsection A section heading should never immediately follow another section heading without intervening text. So don't do this: ```tex 5. Experimental Results 5.1 Results on a Simulated Domain ``` Instead, do this: ```tex 5. Experimental Results In this section, we first describe blah, blah, blah... 5.1 Results on a Simulated Domain ```
https://github.com/chendaohan/bevy_tutorials_typ
https://raw.githubusercontent.com/chendaohan/bevy_tutorials_typ/main/19_playing_sounds/playing_sounds.typ
typst
#set page(fill: rgb(35, 35, 38, 255), height: auto, paper: "a3") #set text(fill: color.hsv(0deg, 0%, 90%, 100%), size: 22pt, font: "Microsoft YaHei") #set raw(theme: "themes/Material-Theme.tmTheme") = 1. 播放音频 我们可以通过生成 AudioBundle 的实体来播放声音。通过 PlaybackSettings 组件控制播放次数。 ```rust fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(AudioBundle { source: asset_server.load("19_playing_sounds/Windless Slopes.ogg"), settings: PlaybackSettings::LOOP, }); } ``` 可以使用 GlobalVolume 资源来控制全局音量。注意,更改此值不会影响已经播放的音频。 ```rust insert_resource(GlobalVolume::new(2.)) ``` Bevy 会将 AudioSink 组件添加到我们刚刚添加的 AudioBundle 实体中,以控制播放。 = 2. 控制播放 为了控制音频播放,我们可以使用 AudioSink 组件的方法。set_volume() 设置音量,set_speed() 设置速度,pause() 暂停,play() 播放,stop() 停止,toggle() 切换播放暂停。 ```rs fn control_audio(audio: Query<&AudioSink>, keyboard: Res<ButtonInput<KeyCode>>) { let Ok(sink) = audio.get_single() else { return; }; if keyboard.just_pressed(KeyCode::ArrowUp) { sink.set_volume(sink.volume() + 1.); } if keyboard.just_pressed(KeyCode::ArrowDown) { sink.set_volume(sink.volume() - 1.); } if keyboard.just_pressed(KeyCode::KeyW) { sink.set_speed(sink.speed() + 1.); } if keyboard.just_pressed(KeyCode::KeyS) { sink.set_speed(sink.speed() - 1.); } if keyboard.just_pressed(KeyCode::KeyP) { sink.pause(); } if keyboard.just_pressed(KeyCode::KeyL) { sink.play(); } if keyboard.just_pressed(KeyCode::KeyO) { sink.stop(); } if keyboard.just_pressed(KeyCode::KeyT) { sink.toggle(); } } ```
https://github.com/tingerrr/masters-thesis
https://raw.githubusercontent.com/tingerrr/masters-thesis/main/src/figures/figures.typ
typst
#import "util.typ": * // // linked lists // #let list-new = fdiag({ instance((0, 0), `l`) edge("-|>") node((0.5, 0), `A`) edge("-|>") node((1, 0), `B`) edge("-|>") node((1.5, 0), `C`) }) #let list-copy = fdiag({ instance((0, 0), `l`) edge("-|>") node((0.5, 0), `A`, stroke: green) edge("-|>") node((1, 0), `B`, stroke: green) edge("-|>") node((1.5, 0), `C`, stroke: green) instance((0, 0.5), `m`) edge((0.5, 0), "-|>") }) #let list-pop = fdiag({ instance((0, 0), `l`) edge("-|>") node((0.5, 0), `A`) edge("-|>") node((1, 0), `B`, stroke: green) edge("-|>") node((1.5, 0), `C`, stroke: green) instance((0, 0.5), `n`) edge((1, 0), "-|>") }) #let list-push = fdiag({ instance((0, 0), `l`) edge("-|>") node((0.5, 0), `A`) edge("-|>") node((1, 0), `B`, stroke: green) edge("-|>") node((1.5, 0), `C`, stroke: green) instance((0, 0.5), `o`) edge("-|>") node((0.5, 0.5), `D`) edge((1, 0), "-|>") }) // // t4gl arrays // #let t4gl-layers-new = fdiag({ instance((0, 0), `a`, name: <i>) edge("-|>") instance((0, 0.5), `storage`, name: <s>) edge("-|>") node((0, 1), `buffer`, name: <b>) }) #let t4gl-layers-shallow = fdiag({ instance((-0.5, 0), `a`, name: <i_a>) edge("-|>") instance((0, 0.5), `shared storage`, name: <s>, stroke: green) edge("-|>") node((0, 1), `buffer`, name: <b>, stroke: green) instance((0.5, 0), `b`, name: <i_b>) edge(<i_b>, <s>, "-|>") }) #let t4gl-layers-deep-new = fdiag({ instance((-0.5, 0), `a`, name: <i_a>) instance((0.5, 0), `c`, name: <i_c>) instance((-0.5, 0.5), `storage a`, name: <s_a>) instance((0.5, 0.5), `storage c`, name: <s_c>, stroke: red) node((0, 1), `shared buffer`, name: <b>, stroke: green) edge(<i_a>, <s_a>, "-|>") edge(<i_c>, <s_c>, "-|>") edge(<s_c>, <b>, "-|>") edge(<s_a>, <b>, "-|>") }) #let t4gl-layers-deep-mut = fdiag({ instance((-0.5, 0), `a`, name: <i_a>) instance((0.5, 0), `c`, name: <i_c>) instance((-0.5, 0.5), `storage a`, name: <s_a>) instance((0.5, 0.5), `storage c`, name: <s_c>) node((-0.5, 1), `buffer a`, name: <b_a>) node((0.5, 1), `buffer c`, name: <b_c>, stroke: red) edge(<i_a>, <s_a>, "-|>") edge(<i_c>, <s_c>, "-|>") edge(<s_a>, <b_a>, "-|>") edge(<s_c>, <b_c>, "-|>") }) // // vector // #let vector-repr = cetz.canvas({ import cetz.draw: * rotate(x: 180deg) rect((-0.1, -0.1), (1.1, 3.1)) grid((0, 0), (1, 3)) content((0.5, 0.5), `ptr`) content((0.5, 1.5), `len`) content((0.5, 2.5), `cap`) grid((3, 0), (4, 4), stroke: gray) content((3.5, 0.5), `e1`) content((3.5, 1.5), `e2`) content((3.5, 2.5), `e3`) content((3.5, 3.5), `...`) line((1, 0.5), (3, 0.5), mark: (end: (symbol: ">", fill: black))) }) // // trees // #let tree-new = fdiag({ instance((0, 0), `t`, name: <root>) node((0, 0.5), `A`, name: <A>) node((-0.5, 1), `B`, name: <B>) node((0.5, 1), `C`, name: <C>) node((-1, 1.5), `D`, name: <D>) node((0, 1.5), `E`, name: <E>) node((1, 1.5), `X`, name: <X>, stroke: dstroke(gray)) edge(<root>, <A>, "-|>") edge(<A>, <B>, "-|>") edge(<A>, <C>, "-|>") edge(<B>, <D>, "-|>") edge(<B>, <E>, "-|>") edge(<C>, <X>, "-|>", stroke: dstroke(gray)) }) #let tree-shared = fdiag({ instance((0, 0), `t`, name: <t-root>) node((0, 0.5), `A`, name: <t-A>) node((-0.5, 1), `B`, name: <B>, stroke: green) node((0.5, 1), `C`, name: <t-C>) node((-1, 1.5), `D`, name: <D>, stroke: green) node((0, 1.5), `E`, name: <E>, stroke: green) edge(<t-root>, <t-A>, "-|>") edge(<t-A>, <B>, "-|>") edge(<t-A>, <t-C>, "-|>") edge(<B>, <D>, "-|>") edge(<B>, <E>, "-|>") instance((1, 0), `u`, name: <u-root>) node((1, 0.5), `A`, name: <u-A>, stroke: red) node((1.5, 1), `C`, name: <u-C>, stroke: red) node((2, 1.5), `X`, name: <X>) edge(<u-A>, <B>, "-|>") edge(<u-root>, <u-A>, "-|>") edge(<u-A>, <u-C>, "-|>") edge(<u-C>, <X>, "-|>") }) // // b-tree // #let b-tree-node = cetz.canvas({ import cetz.draw: * rotate(x: 180deg) grid((0, 0), (3, 1)) content((0.5, 0.5), $s_1$) content((1.5, 0.5), $s_2$) content((2.5, 0.5), $s_3$) line((-1, 2), (0, 1), name: "l1") line((0.5, 2), (1, 1), name: "l2") line((2.5, 2), (2, 1), name: "l3") line((4, 2), (3, 1), name: "l4") for l in range(1, 5) { content( ("l" + str(l) + ".start", 50%, "l" + str(l) + ".end"), box( fill: white, outset: (bottom: 0.4em, x: 0.2em), $k_#l$ ), ) } }) // // finger-tree // #let finger-tree-ranges = [ #let (kmin, kmax) = (2, 3) #let (dmin, dmax) = (1, 4) #let fmins(t) = calc.pow(kmin, t - 1) #let fmin(t) = 2 * dmin * calc.pow(kmin, t - 1) #let fmax(t) = 2 * dmax * calc.pow(kmax, t - 1) #let fcummin(t) = range(1, t + 1).map(fmin).fold(0, (acc, it) => acc + it) #let fcummins(t) = fmins(t) + fcummin(t - 1) #let fcummax(t) = range(1, t + 1).map(fmax).fold(0, (acc, it) => acc + it) #let ranges(t) = { let individual = range(2, t + 1).map(t => ( t: t, mins: fmins(t), min: fmin(t), max: fmax(t), )) individual } #let cum-ranges(t) = { let cummulative = range(1, t + 1).map(t => ( t: t, mins: fcummins(t), min: fcummin(t), max: fcummax(t), )) cummulative } #let count = 8 #let cum-ranges = cum-ranges(count) #let mmax = cum-ranges.last().max #let base = 2 #let sqr = calc.pow.with(base) #let lg = calc.log.with(base: base) #let tick-max = int(calc.round(lg(mmax))) #let tick-args = ( x-tick-step: none, x-ticks: range(tick-max + 1).map(x => (x, sqr(x))), ) // comment out to make linear scale plot // #let sqr = x => x // #let lg = x => x // #let tick-max = int(lg(mmax)) // #let tick-args = () #import "@preview/cetz:0.2.2" #cetz.canvas({ cetz.draw.set-style(axes: (bottom: (tick: (label: (angle: 45deg, anchor: "north-east"))))) cetz.plot.plot( size: (9, 6), x-label: $n$, y-label: $t$, y-tick-step: none, y-ticks: range(1, count + 1), plot-style: cetz.palette.pink, ..tick-args, { let intersections(n) = { cetz.plot.add-vline( style: (stroke: (paint: gray.lighten(70%), dash: "dashed")), lg(n), ) cetz.plot.add( label: box(inset: 0.2em)[$n' = #n$], style: (stroke: none), mark-style: cetz.palette.new( colors: color.map.crest.chunks(32).map(array.first) ).with(stroke: true), mark: "x", cum-ranges.filter(r => r.mins <= n and n <= r.max).map(r => (lg(n), r.t)) ) } // force the plot domain cetz.plot.add( style: (stroke: none), ((-1, 0), (tick-max + 1, count + 1)), ) for t in cum-ranges { cetz.plot.add( label: if t.t == 1 { box(inset: 0.2em)[$n'(t)$] }, domain: (0, lg(mmax)), style: cetz.palette.blue.with(stroke: true), mark-style: cetz.palette.blue.with(stroke: true), mark: "|", ( (lg(t.mins), t.t), (lg(t.max), t.t), ) ) } intersections(9) intersections(27) intersections(250) }, ) }) // #table( // columns: 6, // align: right, // table.header[$t$], // ..cum-ranges.map(t => (t.t, t.mins, $<=$, $n$, $<=$, t.max)).flatten().map(x => $#x$) // ) ] #let finger-tree = fdiag({ let elem = node.with(radius: 7.5pt) let spine = node.with(radius: 7.5pt, fill: blue.lighten(75%)) let node = node.with(radius: 5pt, fill: gray.lighten(50%)) let elems(coord, data, parent: none, ..args) = { let parent = if parent != none { parent } else { label(str(data.first()) + "-" + str(data.last())) } let (x, y) = coord let deltas = range(0, data.len()).map(dx => dx * 0.3) let deltas = deltas.map(dx => dx - deltas.last() / 2) for (e, dx) in data.zip(deltas) { let l = label(str(e)) elem((x + dx, y), raw(str(e)), name: l, ..args) edge(parent, l, "-|>") } } let fill-digit-elem = gradient.linear(angle: 45deg, teal.lighten(50%), white).sharp(2) let fill-digit-node = gradient.linear(angle: 45deg, teal.lighten(50%), gray).sharp(2) instance((0, -0.5), `t`) edge("-|>") spine((0, 0), name: <l1>) edge("-|>") spine((0, 0.5), name: <l2>) edge("-|>") spine((0, 1), name: <l3>) elems((-3.15, 1.25), (1, 2, 3), parent: <l1>, fill: fill-digit-elem) elems((2.15, 1.25), (20, 21), parent: <l1>, fill: fill-digit-elem) node((-2.45, 1.25), name: <4-5>, fill: fill-digit-node) node((-1.7, 1.25), name: <6-8>, fill: fill-digit-node) node((1.7, 1.25), name: <18-19>, fill: fill-digit-node) elems((-2.45, 1.75), (4, 5)) elems((-1.7, 1.75), (6, 7, 8)) elems((1.7, 1.75), (18, 19)) edge(<l2>, <4-5>, "-|>") edge(<l2>, <6-8>, "-|>") edge(<l2>, <18-19>, "-|>") node((-0.725, 1.25), name: <9-12>, fill: fill-digit-node) node((0.725, 1.25), name: <13-17>, fill: fill-digit-node) node((-1.1, 1.75), name: <9-10>) node((-0.35, 1.75), name: <11-12>) node((0.35, 1.75), name: <13-14>) node((1.1, 1.75), name: <15-17>) elems((-1.1, 2.25), (9, 10)) elems((-0.35, 2.25), (11, 12)) elems((0.35, 2.25), (13, 14)) elems((1.1, 2.25), (15, 16, 17)) edge(<l3>, <9-12>, "-|>") edge(<9-12>, <9-10>, "-|>") edge(<9-12>, <11-12>, "-|>") edge(<l3>, <13-17>, "-|>") edge(<13-17>, <13-14>, "-|>") edge(<13-17>, <15-17>, "-|>") }) // // srb tree // #let srb-tree = fdiag({ let arraybox(..args, leaf: false, hl: (0,)) = { let items = args.pos() grid( inset: 5pt, stroke: 1pt, fill: (x, y) => if x in hl { teal.lighten(50%) }, columns: if leaf { int(items.len() / 2) } else { items.len() }, rows: 1.5em, ..items.map(i => [#i]) ) } let node = node.with(inset: 0pt, stroke: none) instance((0, -0.5), `t`, name: <t>) edge("-|>") node((0, 0), arraybox(0, [...], 15, hl: (0, 2)), name: <l1>) node((-0.5, 0.5), arraybox(0, [...], 15), name: <l2-1>) node((0.5, 0.5), arraybox(0, [...], 15, hl: (2,)), name: <l2-2>) edge(<l1>, <l2-1>, "-|>") edge(<l1>, <l2-2>, "-|>") node((-1, 1), arraybox(0, 1, [...], 15, hl: (0, 1)), name: <l3-1>) node((1, 1), arraybox(0, 1, [...], 14, 15, hl: (1, 3)), name: <l3-2>) edge(<l2-1>, <l3-1>, "-|>", shift: -2pt) edge(<l2-2>, <l3-2>, "-|>") node((-1.5, 1.75), arraybox(leaf: true, 0, [...], 15, 0, [...], 15), name: <l4-1>) node((-0.5, 1.75), arraybox(leaf: true, 0, [...], 15, 16, [...], 31), name: <l4-2>) node((0.5, 1.75), arraybox(leaf: true, 0, [...], 15, 65296, [...], 65311), name: <l4-3>) node((1.5, 1.75), arraybox(leaf: true, 0, [...], 15, 65504, [...], 65519, hl: (2,)), name: <l4-4>) edge(<l3-1>, <l4-1>, "-|>", shift: -10pt) edge((rel: (-30pt, 0pt), to: <l3-1>), <l4-2>, "-|>") edge(<l3-2>, <l4-3>, "-|>", shift: -4pt) edge(<l3-2>, <l4-4>, "-|>", shift: -2pt) })
https://github.com/ShapeLayer/ucpc-solutions__typst
https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/tests/ucpc/test.typ
typst
Other
#import "/lib/lib.typ" as ucpc /* * (temp) Disabled: `ucpc.ucpc.with` changes font, and occurs test failed. #show: ucpc.ucpc.with( title: "Contest Name", authors: ("Solutions Commentary Editorial", ), ) */
https://github.com/MultisampledNight/flow
https://raw.githubusercontent.com/MultisampledNight/flow/main/src/tyck.typ
typst
MIT License
// Utils for building schemas and verifying whether or not they are kept. // Note: Even though some functions here are prefixed with underscores, // that's just so they don't conflict with built-in functions and types. // Ordered sequence of elements of type `ty`. #let _array(ty) = (array: (ty: ty)) // Key-value mapping ordered by insertion timepoint. // Technically the key check is redundant // since in Typst, dict keys are guaranteed to be strings // but eh, it fits my mental model better to specify it explicitly. #let _dict(key, value) = { if key != str { panic("typst doesn't support non-string dictionary keys") } (dict: (key: key, value: value)) } // Key-value mapping with specifically defined keys. // May contain more keys than specified which are ignored. // Effectively a very lenient product type. #let _attrs(..args) = (attrs: args.named()) // If any of the specified types match, the value is valid, // regardless of any other matching. #let _any(..args) = (any: args.pos()) #let fmt(schema) = { let (prefix, parts) = if type(schema) == dictionary { if "array" in schema { ("array", (fmt(schema.array.ty),)) } else if "dict" in schema { ("dictionary", ( fmt(schema.dict.key), fmt(schema.dict.value), )) } else if "any" in schema { ("any", schema.any.map(fmt)) } else if "attrs" in schema { ( "dictionary", schema .attrs .pairs() .map(((key, value)) => fmt(key) + ":" + fmt(value) ), ) } else { (repr(schema), ()) } } else { (repr(schema), ()) } prefix if parts.len() == 0 { return } "<" parts .intersperse(", ") .join() ">" } // Checks if the given value adheres to the given expected type schema. // The type schema needs to be constructed using the functions above. // For collections, you should use the functions above. // For primitives like `int` and `str`, you can just specify the types directly. // (You can also specify `dictionary` for example, but that does not put any restrictions on the keys or values.) // // This is more specific than just comparing `type` // since it also allows specifying the types of elements in collections. // Returns a dictionary with the keys `expected`, `found` // and optionally `key` // if the typecheck fails, // otherwise returns none. #let check(value, expected) = { // to have the typecheck work with nested collections, // we just rely on recursion // i despise the Go-ish error handling but there are no usable alternatives here let actual = type(value) // handling direct type specifications if actual == expected { return none } // handling _any if type(expected) == dictionary and "any" in expected { for expected in expected.any { let err = check(value, expected) if err == none { return none } } return ( expected: expected, found: value, ) } // handling _array if actual == array { if type(expected) != dictionary or "array" not in expected { return (expected: expected, found: value) } for ele in value { let err = check(ele, expected.array.ty) if err != none { return ( expected: expected.array.ty, found: ele, ) } } } else if actual == dictionary { // was `expected` constructed using the functions above? if type(expected) != dictionary { return (expected: expected, found: value) } // handling _attrs if "attrs" in expected { for (key, value) in value { let expected = expected.attrs.at(key, default: none) if expected == none { continue } let err = check(value, expected) if err != none { return ( expected: expected, found: value, key: key, ) } } } else if "dict" in expected { // handling _dict for (key, value) in value { let err = check(value, expected.dict.value) if err != none { return ( expected: expected.dict.value, found: value, key: key, ) } } } } else { return ( expected: expected, found: value, ) } } // Panics if known fields do not contain their known types. #let validate(it, schema) = { let err = check(it, schema) if err == none { return } panic( "failed typecheck" + if "key" in err { " at key `" + err.key + "`" } else { "" } + ". " + "expected: `" + _fmt-schema(err.expected) + "`, " + "actual: `" + repr(type(err.found)) + "`" ) }
https://github.com/elpekenin/access_kb
https://raw.githubusercontent.com/elpekenin/access_kb/main/typst/content/parts/summary.typ
typst
En la actualidad es cada vez más la gente que pasa varias horas al día delante de un ordenador, nuestra principal herramienta para controlarlos es el teclado y, sin embargo, su diseño apenas ha avanzado desde su aparición. Este diseño arcaico supone problemas de salud, falta de accesibilidad y reduce la productividad. Por esto, en el presente documento se estudian los avances y variaciones que ha realizado la comunidad de aficionados en los últimos años y se detalla el diseño y construcción de un teclado más acorde al mundo actual que solventa los problemas recién citados, así como permitiendo una gran capacidad de personalización gracias a su diseño hardware que permite cambiar componentes fácilmente y el desarrollo de un firmware y software _open source_ fácilmente editables.
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/ziele_und_aufgaben/main.typ
typst
Other
#import "/src/template.typ": * = Ziele und Aufgaben des Philosophieunterrichts #author[<NAME>] #include "ziele_philosophieunterricht.typ" #include "anforderungsbereiche.typ" #include "kompetenzen.typ" #include "ziele_aufgabenstellungen.typ"
https://github.com/Jeomhps/datify
https://raw.githubusercontent.com/Jeomhps/datify/main/src/utils.typ
typst
MIT License
#let first-letter-to-upper = (s) => { upper(s.first()) + s.slice(1) } // Take a number as an input and a length, // if number is not as big as length, return the number // with 0 padding in front, like 9 with length 2 // will return 09 #let pad = (number, length, pad_char: "0") => { let str_num = str(number) let padding = "" while str_num.len() + padding.len() < length { padding += pad_char } return padding + str_num } #let safe-slice = (s, length) => { let result = "" for ch in s { if result.len() < length { result += ch } else { break } } result }
https://github.com/StanleyDINNE/php-devops-tp
https://raw.githubusercontent.com/StanleyDINNE/php-devops-tp/main/documents/Rapport/Documentation%20CI-CD.typ
typst
#import "Typst/Template_default.typ": set_config #import "Typst/Constants.typ": document_data, line_separator, figures_folder #import "Typst/Util.typ": file_folder, import_csv_filter_categories, insert_code-snippet, insert_figure as i_f, to_string, todo, transpose #show: document => set_config( title: [Documentation du pipeline CI/CD dans\ _CircleCI_ pour une #link("https://github.com/StanleyDINNE/php-devops-tp")[Application Web PHP]], title_prefix: none, authors: (document_data.author.reb, document_data.author.stan, document_data.author.raf).join("\n"), context: "Security & Privacy 3.0", date: datetime.today().display(), image_banner: align(center, image("Typst/logo_Polytech_Nice_X_UCA.png", width: 60%)), header_logo: align(center, image("Typst/logo_Polytech_Nice_X_UCA.png", width: 40%)), )[#document] #let insert_figure(title, width: 100%, border: true) = { i_f(title, folder: "../" + figures_folder + "/Documentation", width: width, border: border) } #outline(title: "Sommaire", indent: 1em, depth: 3) <table_of_contents> #pagebreak() Tips : pour l'édition du fichier de configuration #file_folder(".circleci/config.yml"), utiliser des extensions (comme par exemple #link("https://open-vsx.org/extension/redhat/vscode-yaml")[_redhat.vscode-yaml_]) qui vont garantir l'intégrité de la syntaxe _YAML_, et ansi éviter une configuration cassée et un rejet par _CircleCI_ comme sur la capture ci-dessous. #insert_figure("Fichier de configuration YAML syntaxiquement invalide, non lisible par CircleCI", width: 50%) = Configuration de base du pipeline dans #file_folder(".circleci/config.yml") Le fichier #file_folder(".circleci/config.yml") est présent à la racine du projet, configuration standard pour que _CircleCI_ le voit. + Création d'un compte _CircleCI_ avec GitHub, de manière à pouvoir lier directement le dépôt à CircleCI + Définition d'un workflow `main_workflow` avec des jobs de base : + `debug-info` : qui sert à afficher des variables d'environnement, le contexte d'exécution, etc. + `build-setup` : job parent à tous les jobs de tests, metrics, lint, security checks, etc. + `test-phpunit` : job de test pour assurer que le code est toujours test-compliant Il faut ensuite définir une politque de contribution, à l'aide de pull-requests, contribution dans des branches comme `develop*` premièrement, puis intégration du code de releases dans des branches `release/*`, et quand on veut Ainsi, à partir de ça, on peut définir les filtres de branches ou tag qui vont déclencher la construction d'une image docker du projet, et le déploiement sur les serveurs. = Configuration de _CircleCI_ == Dans les Paramètres du projet > Variables d'environnement #insert_figure("Configuration des variables d'environnement", width: 70%) == Dans les Paramètres du projet > Clefs SSH #insert_figure("Ajout des clefs SSH des utilisateurs updater_agent sur les serveurs de staging et prodution", width: 70%) == Dans les Paramètres d'organisation > Contextes #insert_figure("Définition des tokens dans les Contextes", width: 70%) Injection du contexte dans un job avec la directive `context`. À noter que tous les tokens sauf celui d'Infisical peuvent être déplacés dans Infisical, et injectés en ligne de commande dans le pipeline avec la CLI d'Infisical. = Ajout de jobs de metrics et lint Ajouter de tels jobs pour avoir une meilleure visibilité sur le code, notamment au travers des rapports, trouvable dans la section _Artifacts_ de chaque job. = Ajout du jobs de containerisation Le job qui construit l'image suit les étapes suivantes : + Reconstruction du nom du projet avec les variables d'environnement + Construction du tag avec le nom de branche et la date, ou le tag git + Connexion au stockage d'artifacts _GitHub Container Registry_ - Utilisation des credentials stockés dans le contexte CircleCI des tokens + Construction de l'image docker à partir du code source du dépôt GitHub récupéré et injection des variables d'environnement adéquates + Tag de l'image + Stockage de l'image sur _GHCR_ = Ajout des jobs de déploiement == Serveur staging Avec le serveur configuré. Connexion ssh avec injection de l'ensemble des commandes ci-dessous + Actualisation "sans-échec"/"multirisque" du dépôt en local - Changements locaux ignorés - Modifications divergentes ignorées en local : priorité au remote/orign + Mise à jour des dépendances avec `composer` + Overwrite du contenu du dossier du service #file_folder("/var/www/html") + Rechargement de FPM-PHP == Server production Connexion ssh avec injection de l'ensemble des commandes ci-dessous + Reconstruction du nom de l'image + Arrêt de suppression du container en cours d'exécution + Récupération de l'image distante en denière version + Instanciation du container = Si AWS tombe + On a restart et reconfiguré les machines + Récupération des addresses IPv4 publiques + Aller dans CircleCI > Projects > php-devops-tp > Project settings > SSH keys - Redéfinir (réutiliser) les clefs privées des deux serveurs, en remplaçant les hostnames par les IP copiées + Aller dans CircleCI > Projects > php-devops-tp > Project settings > Environment Variables - Mettre à jour de la même façon les IP pour les clefs `STAGING_SSH_HOST` et `PRODUCTION_SSH_HOST`
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/flow/invisibles.typ
typst
// Test out-of-flow items (place, counter updates, etc.) at the // beginning of a block not creating a frame just for them. --- flow-first-region-no-item --- // No item in the first region. #set page(height: 5cm, margin: 1cm) No item in the first region. #block(breakable: true, stroke: 1pt, inset: 0.5cm)[ #rect(height: 2cm, fill: gray) ] --- flow-first-region-counter-update --- // Counter update in the first region. #set page(height: 5cm, margin: 1cm) Counter update. #block(breakable: true, stroke: 1pt, inset: 0.5cm)[ #counter("dummy").step() #rect(height: 2cm, fill: gray) ] --- flow-first-region-placed --- // Placed item in the first region. #set page(height: 5cm, margin: 1cm) Placed item in the first region. #block(breakable: true, above: 1cm, stroke: 1pt, inset: 0.5cm)[ #place(dx: -0.5cm, dy: -0.75cm, box(width: 200%)[OOF]) #rect(height: 2cm, fill: gray) ] --- flow-first-region-zero-sized-item --- // In-flow item with size zero in the first region. #set page(height: 5cm, margin: 1cm) In-flow, zero-sized item. #block(breakable: true, stroke: 1pt, inset: 0.4cm)[ #set block(spacing: 0pt) #line(length: 0pt) #rect(height: 2cm, fill: gray) #line(length: 100%) ] --- flow-first-region-counter-update-and-placed --- // Counter update and placed item in the first region. #set page(height: 5cm, margin: 1cm) Counter update + place. #block(breakable: true, above: 1cm, stroke: 1pt, inset: 0.5cm)[ #counter("dummy").step() #place(dx: -0.5cm, dy: -0.75cm, box([OOF])) #rect(height: 2cm, fill: gray) ] --- flow-first-region-counter-update-placed-and-line --- // Mix-and-match all the previous ones. #set page(height: 5cm, margin: 1cm) Mix-and-match all the previous tests. #block(breakable: true, above: 1cm, stroke: 1pt, inset: 0.5cm)[ #counter("dummy").step() #place(dx: -0.5cm, dy: -0.75cm, box(width: 200%)[OOF]) #line(length: 100%) #place(dy: 0.2em)[OOF] #rect(height: 2cm, fill: gray) ]
https://github.com/MobtgZhang/sues-thesis-typst
https://raw.githubusercontent.com/MobtgZhang/sues-thesis-typst/main/paper/chapters/symbols.typ
typst
MIT License
#import "../thesis.typ":fontstypedict,fontsizedict,autoFakeBold_pt,matter_state #import "@preview/tablex:0.0.6": tablex,hlinex #matter_state.update(matter => "none") #v(1em) #align( center, text("符号和缩略词说明",font:fontstypedict.黑体,size:fontsizedict.三号,stroke:autoFakeBold_pt) ) 对文中所用符号缩略词所表示的意义以及单位(或者量纲)的说明。在目录中不出现,若不需要说明,则删除此页面。 这里使用三线表举个例子。这里的符号描述可以使用三线表描述一些符号和缩略词,在学术文章当中经常使用到一种表格。插入表格,一般最上面线和最下面线宽度为1.5pt,中间线条宽度为0.75pt。下面的三线表是一个最为简单的例子: #figure( tablex( auto-lines:false, align: center + horizon, columns: (1fr, 1fr), size:fontsizedict.三号, hlinex(y: 0,stroke: 1.5pt,expand:-50pt), hlinex(y: 1,stroke: 0.75pt,expand:-50pt), [符号表示],[符号意义], [$e$],[数学自然对数], [$pi$],[数学圆周率], [$epsilon$],[介电值常数], [$G$],[万有引力常数], [$k$],[波尔兹曼常数], hlinex(stroke: 1.5pt,expand:-50pt),), caption:"一个三线表的示例" )
https://github.com/EpicEricEE/typst-plugins
https://raw.githubusercontent.com/EpicEricEE/typst-plugins/master/hash/README.md
markdown
# hash A package that implements the following hashing algorithms (based on [`RustCrypto`](https://github.com/RustCrypto/hashes)'s crates): - BLAKE2 - BLAKE2s - MD5 - SHA-1 - SHA-224 - SHA-256 - SHA-384 - SHA-512 - SHA-3 ## Methods ### `hash` method Hashes the given data using the given algorithm. ```typ hash.hash( string, string | array | bytes, ) -> bytes ``` #### `algorithm` parameter The algorithm to use for hashing. There also exist convenience methods for each algorithm that only take the data to hash. - `"blake2"` - `"blake2s"` - `"md5"` - `"sha1"` - `"sha224"` - `"sha256"` - `"sha384"` - `"sha512"` - `"sha3"` #### `data` parameter The data to hash. --- ### `hex` method Converts a given bytes object to a hexadecimal string. ```typ hash.hex(bytes) -> string ``` #### `bytes` parameter The bytes object to convert. --- ### `blake2` method Hashes the given data using the BLAKE2 algorithm. ```typ hash.blake2(string | array | bytes) -> bytes ``` #### `data` parameter The data to hash. --- ### `blake2s` method Hashes the given data using the BLAKE2s algorithm. ```typ hash.blake2s(string | array | bytes) -> bytes ``` #### `data` parameter The data to hash. --- ### `md5` method Hashes the given data using the MD5 algorithm. ```typ hash.md5(string | array | bytes) -> bytes ``` #### `data` parameter The data to hash. --- ### `sha1` method Hashes the given data using the SHA-1 algorithm. ```typ hash.sha1(string | array | bytes) -> bytes ``` #### `data` parameter The data to hash. --- ### `sha224` method Hashes the given data using the SHA-224 algorithm. ```typ hash.sha224(string | array | bytes) -> bytes ``` #### `data` parameter The data to hash. --- ### `sha256` method Hashes the given data using the SHA-256 algorithm. ```typ hash.sha256(string | array | bytes) -> bytes ``` #### `data` parameter The data to hash. --- ### `sha384` method Hashes the given data using the SHA-384 algorithm. ```typ hash.sha384(string | array | bytes) -> bytes ``` #### `data` parameter The data to hash. --- ### `sha512` method Hashes the given data using the SHA-512 algorithm. ```typ hash.sha512(string | array | bytes) -> bytes ``` #### `data` parameter The data to hash. --- ### `sha3` method Hashes the given data using the SHA-3 algorithm. ```typ hash.sha3(string | array | bytes) -> bytes ``` #### `data` parameter The data to hash. ## Example ```typ #import "@local/hash:0.1.0": hash, hex, md5, sha256, sha3 #table( columns: 2, table.header[*Digest*][*Hash*], [BLAKE2], hex(hash("blake2", "Hello world!")), [BLAKE2s], hex(hash("blake2s", "Hello world!")), [MD5], hex(md5("Hello world!")), [SHA-1], hex(hash("sha1", "Hello world!")), [SHA-224], hex(hash("sha224", "Hello world!")), [SHA-256], hex(sha256("Hello world!")), [SHA-384], hex(hash("sha384", "Hello world!")), [SHA-512], hex(hash("sha512", "Hello world!")), [SHA-3], hex(sha3("Hello world!")), ) ``` ![Result](assets/example.svg)
https://github.com/TempContainer/typnotes
https://raw.githubusercontent.com/TempContainer/typnotes/main/book.typ
typst
#import "@preview/shiroa:0.1.1": * #show: book #book-meta( title: "Temp Notes", summary: [ #prefix-chapter("sample-page.typ")[Home] = Structure and Interpretation of Classical Mechanics - #chapter("sicm/lag_mech.typ")[Lagrangian Mechanics] = Optimization - #chapter("opti/con_set.typ", section: "1")[Convex Sets] ] ) // re-export page template #import "/templates/page.typ": project #let book-page = project
https://github.com/rabotaem-incorporated/algebra-conspect-1course
https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/config.typ
typst
Other
#let enable-chapters-from-sem1 = true #let enable-chapters-from-sem2 = true #let enable-ticket-references = true #let monochrome = false
https://github.com/EpicEricEE/typst-droplet
https://raw.githubusercontent.com/EpicEricEE/typst-droplet/master/tests/breaks/test.typ
typst
MIT License
#import "/src/lib.typ": dropcap #set page(width: 6cm, height: auto, margin: 1em) // Test correct splitting with trailing line- and paragraph breaks. #dropcap[This ends\ with a line break.\ But there is more!] #dropcap[This ends\ with two line breaks.\ \ But there is more!] #dropcap[ This ends\ with a paragraph break. But there is more! ]