repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/Walker-00/cs-eik
https://raw.githubusercontent.com/Walker-00/cs-eik/rust/README.md
markdown
Do What The F*ck You Want To Public License
# cs-eik A project to write a book for everything I know (eik) about computer science with typst. ## မိတ်ဆက် ဒီ project လေးကတော့ ကျွန်တော်နဲ့ contributor တွေသိသလောက် Computer Science နဲ့ ပတ်သက်တဲ့ အကြောင်းအရာတွေကို မြန်မာလူငယ်တွေ အလကား လေ့လာလို့ရအောင် စုစည်းပြီး ရေးထားတာပါ။ ကျွန်တော်တို့ သိတာတွေပေါင်းရေးတာဖြစ်တဲ့အတွက် မပြည့်စုံတာ မမှန်ကန်တာတွေလည်း ပါနိုင်ပါတယ်။ ဒီအတွက် အမှားပြင်ချင်တာတို့ ကိုယ်တိုင် ဝင်ရောက် ရေးချင်တာတို့ ဆိုရင် issue ဖွင့်တာဖြစ်ဖြစ် pull request တင်တာဖြစ်ဖြစ် လုပ်ပြီး Speical Thanks ဒါမှမဟုတ် Co-Author နေရာမှာ credit ရယူလို့ရပါတယ်။ <br> ## ဒီစာအုပ်ကို လိုက်လုပ်ဖို့ဘာတွေလိုအပ်လဲ ဘာမှမလိုပါဘူး ကျွန်တော်တို့က တော့အတတ်နိုင်ဆုံး ဘာမှနားမလည် တဲ့သူကို နားလည်အောင် ရှင်းပြသလိုမျိုး ရေးထားမှာဖြစ်တဲ့အတွက်၊ ဘာ backgroud မှ မရှိ ဘာ သချာ် ဘာ အဂ်လိပ် စာမှမရလဲ လိုက်လုပ်လေ့လာလို့ရအောင် သေချာပြင်ဆင်ပေးထားပါမယ်။ သေချာနားလည်အောင်ရှင်းပြပြီး အလကားရဖို့က ကျွန်တော့တာဝန်ထားပါ သေချာလိုက်လုပ် ရမှာကတော့ ဖတ်တဲ့သူတာဝန်ပါ။ <br> ## License And Warning Lincese ကတော့ `WTFPL` ကို သုံးထားတယ်ဆိုပေမဲ့။ ကိုယ်ကျိုးအတွက် ပြန်လည်ရောင်းချတာမျိုးကို ခွင့်မပြုပါဘူး။ ခွင့်မပြုလည်း ဘာလုပ်ရတုန်းမေးရင် ဘာမှလုပ်မရပေမဲ့ ကျွန်တော့ရဲ့ အဓိကအိမ်မက်က ပညာရေးတိုင်းကို လူတိုင်း အလကား လေ့လာနိုင်စေချင်တာပါ။ ပြန်ရှဲတာမျိုး Hard Copy စာအုပ်တွေကို Non-Profit ရောင်းတာမျိုး လူထုအကျိုးပြု နေရာတွေ အဖွဲ့အစည်းတွေ အတွက် funding သဘောမျိုး ရောင်းချတာမျိုး ကတော့ ခွင့်ပြုချက်မလိုပဲလုပ်ဆောင်လို့ရပါတယ်။
https://github.com/unb3rechenbar/TypstPackages
https://raw.githubusercontent.com/unb3rechenbar/TypstPackages/main/environments/boxdef/0.1.0/src/lib.typ
typst
#let beweisbox( fill: luma(250), width: 100%, height: auto, stroke: (left: 2pt + rgb("#002fa7")), inset: (left: 10pt, right: 10pt, bottom: 10pt, top: 10pt), content ) = block( fill: fill, width: width, height: height, stroke: stroke, inset: inset, breakable: true, [ #block( below: -6pt, width: 100%, [*Beweis.*] + content ) #align(right)[ #move(dy: 2pt, square(size: 8pt, stroke: (thickness: 0.5pt, paint: rgb("#002fa7")), fill: white) ) ] ] ) #let defcount = counter("defcount") #let definitionsbox( fill: white, width: 100%, height: auto, stroke: black + 0.5pt, inset: (left: 20pt, right: 20pt, bottom: 20pt, top: 17pt), title, content ) = block[ #defcount.step() #box( fill: fill, width: width, height: height, stroke: stroke, inset: inset, [ *Definition #counter(heading).display()#defcount.display().* #title. #content ] ) ] #let satcount = counter("satcount") #let satzbox( fill: luma(225), width: 100%, height: auto, stroke: black + 0.5pt, inset: (left: 20pt, right: 20pt, bottom: 20pt, top: 17pt), title, content ) = block[ #satcount.step() #box( fill: fill, width: width, height: height, stroke: stroke, inset: inset, [ *Satz #counter(heading).display()#satcount.display().* #title. #content ] ) ] #let corcount = counter("corcount") #let korollarbox( fill: luma(240), width: 100%, height: auto, stroke: black + 0.5pt, inset: (left: 20pt, right: 20pt, bottom: 20pt, top: 17pt), title, content ) = block[ #corcount.step() #box( fill: fill, width: width, height: height, stroke: stroke, inset: inset, [ *Korollar #counter(heading).display()#corcount.display().* #title. #content ] ) ] // 9PKGLxW/2>OWl2|4 #let lemcount = counter("lemcount") #let lemmabox( fill: luma(240), width: 100%, height: auto, inset: (left: 20pt, right: 20pt, bottom: 20pt, top: 17pt), title, content ) = block[ #lemcount.step() #box( fill: fill, width: width, height: height, inset: inset, radius: 5pt, [ *Lemma #counter(heading).display()#lemcount.display().* #title. #content ] ) ] #let aufgabenbox( width: 100%, height: auto, stroke: (top: (paint: black, dash: "loosely-dotted"), bottom: (paint: black, dash: "loosely-dotted")), inset: (left: 5pt, right: 10pt, bottom: 10pt, top: 10pt), content ) = box( width: width, height: height, stroke: stroke, inset: inset, par(leading: 0.65em, linebreaks: "optimized", text(size: 10pt, content)) )
https://github.com/EpicEricEE/typst-marge
https://raw.githubusercontent.com/EpicEricEE/typst-marge/main/tests/integration/todo/test.typ
typst
MIT License
#import "/src/lib.typ": sidenote #set par(justify: true) #set page(width: 9cm, height: auto, margin: (outside: 4cm, rest: 5mm)) #let todo(color: red, body) = sidenote( padding: (inside: 2em, outside: 1em), numbering: none, format: it => { // Add line to source location. let dx = it.source.position().x - here().position().x let dy = it.source.position().y - here().position().y let offset = 0.175em let start-y = 0em let start-x = if it.side == left { it.margin - it.padding.values().sum() } else { 0pt } let padding = if it.side == left { it.padding.right } else { -it.padding.left } place(path( stroke: (paint: color, join: "round", cap: "round"), (start-x, start-y), (start-x + padding / 2, start-y), (start-x + padding / 2, dy + offset), (dx, dy + offset), )) place(dx: dx, dy: dy + offset, { place(center + horizon, circle(radius: 1pt, fill: color)) }) // Add original note in a colorful box. box( width: 100%, fill: color.lighten(75%), stroke: ((repr(it.side.inv())): color), radius: 0.5pt, inset: (x: 0.5em), outset: (y: 0.5em), it.default ) }, body ) Lorem ipsum dolor sit amet, consectetur #todo["consectetur" is a weird word] adipiscing elit, sed do eiusmod #todo(color: blue)[so is "eiusmod"] tempor incididunt ut labore et dolore magnam aliquam quaerat. #pagebreak() Lorem ipsum dolor sit amet, consectetur #todo(color: orange)[same as before] adipiscing elit, sed do eiusmod #todo(color: green)[last one] tempor incididunt ut labore et dolore magnam aliquam quaerat.
https://github.com/jakobjpeters/Typstry.jl
https://raw.githubusercontent.com/jakobjpeters/Typstry.jl/main/docs/source/references/package_extensions.md
markdown
MIT License
# Package Extensions This reference documents the lazily-loaded implementations of [`show_typst`](@ref) for types defined in external packages. ## LaTeXStrings.jl ```@docs show_typst(::Any, ::LaTeXStrings.LaTeXString) ``` ## Markdown.jl ```@docs show_typst(::Any, ::Markdown.MD) ```
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/visualize/gradient-text.typ
typst
Apache License 2.0
// Test that gradient fills on text. // The solid bar gradients are used to make sure that all transforms are // correct: if you can see the text through the bar, then the gradient is // misaligned to its reference container. // Ref: true --- // Ref: false // Make sure they don't work when `relative: "self"`. // Hint: 17-61 make sure to set `relative: auto` on your text fill // Error: 17-61 gradients on text must be relative to the parent #set text(fill: gradient.linear(red, blue, relative: "self")) --- // Test that gradient fills on text work for globally defined gradients. #set page(width: 200pt, height: auto, margin: 10pt, background: { rect(width: 100%, height: 30pt, fill: gradient.linear(red, blue)) }) #set par(justify: true) #set text(fill: gradient.linear(red, blue)) #lorem(30) --- // Sanity check that the direction works on text. #set page(width: 200pt, height: auto, margin: 10pt, background: { rect(height: 100%, width: 30pt, fill: gradient.linear(dir: btt, red, blue)) }) #set par(justify: true) #set text(fill: gradient.linear(dir: btt, red, blue)) #lorem(30) --- // Test that gradient fills on text work for locally defined gradients. #set page(width: auto, height: auto, margin: 10pt) #show box: set text(fill: gradient.linear(..color.map.rainbow)) Hello, #box[World]! --- // Test that gradients fills on text work with transforms. #set page(width: auto, height: auto, margin: 10pt) #show box: set text(fill: gradient.linear(..color.map.rainbow)) #rotate(45deg, box[World])
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/note-me/0.1.0/README.md
markdown
Apache License 2.0
# GitHub Admonition for Typst > [!NOTE] > Add GitHub style admonitions (also known as alerts) to Typst. ## Usage Import this package, and ```typ #note[ Highlights information that users should take into account, even when skimming. ] #tip[ Optional information to help a user be more successful. ] #important[ Crucial information necessary for users to succeed. ] #warning[ Critical content demanding immediate user attention due to potential risks. ] #caution[ Negative potential consequences of an action. ] #admonition( icon: "icons/stop.svg", color: color.fuchsia, title: "Custom Title", )[ The icon, color and title are customizable. ] ``` ![note-me](https://github.com/FlandiaYingman/note-me/assets/9929037/639a62fa-f2f7-4d70-b922-29dc72372f46) Further Reading: - https://github.com/orgs/community/discussions/16925 - https://docs.asciidoctor.org/asciidoc/latest/blocks/admonitions/ ## Style It borrows the style of GitHub's admonition. > [!NOTE] > Highlights information that users should take into account, even when skimming. > [!TIP] > Optional information to help a user be more successful. > [!IMPORTANT] > Crucial information necessary for users to succeed. > [!WARNING] > Critical content demanding immediate user attention due to potential risks. > [!CAUTION] > Negative potential consequences of an action. ## Credits The admonition icons are from [Octicons](https://github.com/primer/octicons).
https://github.com/SkytAsul/INSA-Typst-Template
https://raw.githubusercontent.com/SkytAsul/INSA-Typst-Template/main/exemples/exemple-rapport-stage.typ
typst
MIT License
#import "../insa-template/document-template.typ" : * #set document(date: datetime(year: 2024, month: 08, day: 16), keywords: ("VR", "Physics Simulation", "Soft body")) #show: doc => insa-stage( "<NAME>", "INFO", "2023-2024", "Real-time virtual interaction with deformable structure", "Sapienza University of Rome", image("logo-example.png"), "<NAME>", "<NAME>", [ Résumé du stage en français. ], [ Summary of the internship in english. ], thanks-page: [ Merci aux clients fidèles. ], student-suffix: "(e)", lang: "fr", insa: "rennes", doc ) = Introduction Présentation de l'entreprise, tout ça tout ça. #pagebreak() = Travail réalisé == Première partie Blabla == Seconde partie Bleble #pagebreak() = Conclusion Conclusion random #pagebreak() = Annexes
https://github.com/typst-community/mantodea
https://raw.githubusercontent.com/typst-community/mantodea/main/assets/examples/thumbnail.typ
typst
MIT License
#import "/src/component/title-page.typ": make-title-page #make-title-page()
https://github.com/Enter-tainer/typst-preview
https://raw.githubusercontent.com/Enter-tainer/typst-preview/main/docs/arch.typ
typst
MIT License
#import "./book.typ": book-page #import "./templates/gh-page.typ": page-width, is-dark-theme #import "@preview/fontawesome:0.1.0": * #import "@preview/colorful-boxes:1.1.0": * #import "@preview/cetz:0.1.0" #show: book-page.with(title: "Typst-Preview Architecture") #show link: underline #let natural-image(img) = style(styles => { let (width, height) = measure(img, styles) layout(page => { let width_scale = 0.8 * page.width / width block(width: width_scale * width, height: width_scale * height)[ #scale(x: width_scale * 100%, y: width_scale * 100%, origin: center+top)[#img] ] }) }) = Architecture Typst preview consists of three parts: 1. The first one is the typst preview server, which watches events, recompiles the document and sends it to client. This part is written in rust and is the core of typst preview. 2. The second one is the typst preview client, which is a web client that renders the preview pages. This part is written in typescript and wasm. 3. The third one is the typst preview extension for VSCode. This part is written in typescript and is responsible for starting the server and sending/receive events to the server. These three parts communicate with each other through websockets. The server sends the compiled document to the client, and the client renders it. #let img = { set text(size: 8pt) cetz.canvas({ import cetz.draw: * rect((0, 0), (7, 6), name: "binary", stroke: (dash: "dashed")) rect((8, 0), (13, 2.5), name: "webview", stroke: (dash: "dashed")) rect((8, 3), (13, 6), name: "vscode", stroke: (dash: "dashed")) circle((1.7, 4.3), radius: 1, name: "typst-actor") circle((1.9, 1.5), radius: 1, fill: white) circle((1.8, 1.4), radius: 1, fill: white) circle((1.7, 1.3), radius: 1, fill: white, name: "render-actor") rect((4.2, 0.7), (6.7, 2.2), fill: white) rect((4.1, 0.6), (6.6, 2.1), fill: white) rect((4, 0.5), (6.5, 2), fill: white, name: "webview-actor") rect((4, 3.75), (6.7, 5.25), name: "editor-actor") line("editor-actor.right", "vscode.left", mark: (start: ">", end: ">")) line("webview-actor.right", "webview.left", mark: (start: ">", end: ">")) line("webview-actor.left", "typst-actor.right", mark: (start: ">", end: ">")) line("editor-actor.left", "typst-actor.right", mark: (start: ">", end: ">")) line("typst-actor.bottom", "render-actor.top", mark: (start: ">", end: ">")) line("render-actor.right", "webview-actor.left", mark: (start: ">", end: ">")) line("render-actor.right", "editor-actor.left", mark: (start: ">", end: ">")) content("binary.top-left", anchor: "top-left", padding: 0.3)[Typst Preview's Server(Rust)] content("webview.top-left", anchor: "top-left", padding: 0.3)[ Webview(Typescript+Wasm)\ #set text(size: 6pt) Incremental rendering based on VDOM are used\ to achieve high performance. Interact with the server using websockets. ] content("vscode.top-left", anchor: "top-left", padding: 0.3)[ VSCode(Typescript(Node.js))\ #set text(size: 6pt) The VSCode extension starts the server and send\ events like file update to the server. Interact with the server using websockets. ] content("typst-actor")[Typst Actor] content("render-actor")[Render Actor] content("webview-actor.top-left", anchor: "top-left", padding: 0.2)[ Webview Actor\ #set text(size: 6pt) There can be multiple\ webview actors\ in the system. ] content("editor-actor.top-left", anchor: "top-left", padding: 0.2)[ Editor Actor\ #set text(size: 6pt) Communicate with\ VSCode using websocket\ and forward events. ] }) } #figure( natural-image(img), caption: [Typst Preview Architecture], ) == Rust Part of Typst Preview === Actors The architecture of typst preview mainly follows the actor model. To be more specific, there are four actors in the system: + _Typst Actor_: The typst actor is the main actor of the system. It is responsible for watching the file system, compiling the document and resolving cross jump requests. Basically everything related to typst's `World` is handled by this actor. There is exactly one typst actor in the system. + _Render Actor_: The render actor is responsible for rendering the document. It receives the compiled document from the typst actor and renders it. There can be multiple render actors in the system. The number of render actors is equal to the number of clients connected to the server. + _Editor Actor_: This actor listens to the events from the editor. It is responsible for sending the events to the typst actor. There is exactly one editor actor in the system. When the editor is closed, the editor actor will shutdown the whole program otherwise the program will keep running, resulting in process leak. + _Webview Actor_: Webview actor is responsible for communicating with the webview client. It receives the events from the webview client and sends them to relevant actors. The number of webview actors is equal to the number of render actors. We can see that the first two actors are CPU heavy, while the last two actors are IO heavy. Therefore we use different runtimes for them. For each CPU heavy actor, we create a thread and run the actor on it. For each IO heavy actor, we create a tokio task and run the actor on it. These actors can send messages to each other using `tokio::sync::mpsc`. A dedicated thread for the first two actor is necessary because typst use #link("https://github.com/typst/comemo")[comemo] under the hood, which use thread local storage to cache intermediate results. If we run the first two actors on tokio tasks, the thread local storage will not work, resulting in unstable performance. === Renderer To achieve incremental and high performance rendering, we use #link("https://github.com/Myriad-Dreamin/typst.ts")[typst.ts] to render document. To be specific, we use the `IncrementalSvgExporter`. The `IncrementalSvgExporter` will only output the changed part of the document. The result is serialized to using #link("https://github.com/rkyv/rkyv")[rkyv]. The serialized result is then sent to the client. == Client Part of Typst Preview The client part of typst preview is written in typescript and wasm. It is responsible for rendering the document. It receives the serialized document from the server, deserializes it using rkyv and apply the changes to the VDOM to get the latest document. This is done by #link("https://github.com/Myriad-Dreamin/typst.ts/tree/main/packages/renderer")[typst-ts-renderer]. For optimization, we maintains the visible rectangle of the document in the client. When the document is updated, we only re-render the visible part of the document.
https://github.com/DrakeAxelrod/cvss.typ
https://raw.githubusercontent.com/DrakeAxelrod/cvss.typ/main/bak/cvss40.typ
typst
MIT License
#let test-string = "CVSS:4.0/AV:A/AC:H/AT:P/PR:L/UI:P/VC:L/VI:L/VA:L/SC:L/SI:L/SA:L/E:A/CR:L/IR:L/AR:L/MAV:N/MAC:L/MAT:N/MPR:N/MUI:N/MVC:H/MVI:H/MVA:H/MSC:L/MSI:L/MSA:L/S:N/AU:N/R:A/V:D/RE:L/U:Clear" // Attack Vector (AV): // Attack Complexity (AC): // Attack Requirements (AT): // Privileges Required (PR): // User Interaction (UI): // Vulnerable System Impact Metrics // Confidentiality (VC): // Integrity (VI): // Availability (VA): // Subsequent System Impact Metrics // Confidentiality (SC): // Integrity (SI): // Availability (SA): // Supplemental Metrics ? // Safety (S): // Automatable (AU): // Recovery (R): // Value Density (V): // Vulnerability Response Effort (RE): // Provider Urgency (U): // Environmental (Modified Base Metrics) ? // Exploitability Metrics // Attack Vector (MAV): // Attack Complexity (MAC): // Attack Requirements (MAT): // Privileges Required (MPR): // User Interaction (MUI): // Vulnerable System Impact Metrics // Confidentiality (MVC): // Integrity (MVI): // Availability (MVA): // Subsequent System Impact Metrics // Confidentiality (MSC): // Integrity (MSI): // Availability (MSA): // Environmental (Security Requirements) ? // Confidentiality Requirements (CR): // Integrity Requirements (IR): // Availability Requirements (AR): // Threat Metrics ? // Exploit Maturity (E): #let header = "CVSS\:4\.0" // #let metric = "[\/]([A-Z]{1,3})\:" #let re-metric(key, vals) = { "[/]?(" + key + ":[" + vals + "])?" } // #let verify(s) = { // let re = regex("CVSS\:4\.0" // // Base Metrics // + re-metric("AV", "N|A|L|P|Network|Adjacent|Local|Physical") // + re-metric("AC", "H|L|High|Low") // + re-metric("AT", "N|P|None|Present") // + re-metric("PR", "N|L|H|None|Low|High") // + re-metric("UI", "N|R|A|None|Required|All") // // Vulnerable System Impact Metrics // + re-metric("VC", "N|L|H|None|Low|High") // + re-metric("VI", "N|L|H|None|Low|High") // + re-metric("VA", "N|L|H|None|Low|High") // // Subsequent System Impact Metrics // + re-metric("SC", "N|L|H|None|Low|High") // + re-metric("SI", "N|L|H|None|Low|High") // + re-metric("SA", "N|L|H|None|Low|High") // ) // s.matches(re) // } // #verify(test-string) #let re = regex("CVSS:4.0([/?[A-Za-z]{1,3}:[A-Za-z]]+)") // #let res = test-string.match(regex("CVSS:4.0([/?[A-Za-z]{1,3}:[A-Za-z]]+)")) // #res.captures.at(0).split("/").fold((:), (acc, x) => { // if x == "" { return acc } // let kv = x.split(":") // acc + ((kv.at(0)): kv.at(1)) // }) #let metrics(s) = { let re = regex("CVSS:4.0([/?[A-Za-z]{1,3}:[A-Za-z]]+)") let res = s.match(re) res.captures.at(0).split("/").fold((:), (acc, x) => { if x == "" { return acc } let kv = x.split(":") acc + ((kv.at(0)): kv.at(1)) }) } #metrics(test-string)
https://github.com/cadojo/correspondence
https://raw.githubusercontent.com/cadojo/correspondence/main/src/hermes/src/article.typ
typst
MIT License
// // Article Formats // #import "../../options/options.typ": * #import "../../rolo/rolo.typ": * #let builtin-columns = columns #let builtin-outline = outline #let article( title: none, subtitle: none, abstract: none, author: author(), date: datetime.today().display("[month repr:long] [day], [year]"), theme: black, columns: 2, header: none, footer: none, margin: 0.75in, font: "New Computer Modern", mono: "New Computer Modern Mono", outline: true, content, ) = { set text(11pt, font: font) show raw: set text(font: mono) set par(justify: true) set heading(numbering: "1.1 ") show heading: h => align( center, pad(bottom: 0.25em, text(theme, smallcaps(h))) ) set page( paper: "us-letter", header: header, margin: margin, footer: if some(footer) { footer } else { set text(rgb(75,75,75)) place(left, align(left, title)) place(right, align(right, counter(page).display("1 / 1", both: true))) }, ) let titleblock = { align(center, text(theme, size: 22pt, weight: "bold", smallcaps(title))) if some(subtitle) { align(center, text(black, size: 14pt, weight: "semibold", subtitle)) } if some(author) { set align(center) pad( 1em, if type(author) == "array" { stack(dir: ltr, ..author.map(authorblock)) } else if type(author) == "string" { author } else { authorblock(author) } ) } } titleblock builtin-columns(columns)[ #if some(abstract) { heading(level: 1, numbering: none, outlined: false, smallcaps("abstract")) abstract // pad(top: 1em, bottom: 1em, left: (25% / 2), right: (25% / 2), abstract) } #if outline { builtin-outline(title: "Table of Contents", indent: auto, depth: 2) } #content ] }
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/074.%20guidetoinvestors.html.typ
typst
guidetoinvestors.html The Hacker's Guide to Investors April 2007(This essay is derived from a keynote talk at the 2007 ASES Summit at Stanford.)The world of investors is a foreign one to most hackers—partly because investors are so unlike hackers, and partly because they tend to operate in secret. I've been dealing with this world for many years, both as a founder and an investor, and I still don't fully understand it.In this essay I'm going to list some of the more surprising things I've learned about investors. Some I only learned in the past year.Teaching hackers how to deal with investors is probably the second most important thing we do at Y Combinator. The most important thing for a startup is to make something good. But everyone knows that's important. The dangerous thing about investors is that hackers don't know how little they know about this strange world.1. The investors are what make a startup hub.About a year ago I tried to figure out what you'd need to reproduce Silicon Valley. I decided the critical ingredients were rich people and nerds—investors and founders. People are all you need to make technology, and all the other people will move.If I had to narrow that down, I'd say investors are the limiting factor. Not because they contribute more to the startup, but simply because they're least willing to move. They're rich. They're not going to move to Albuquerque just because there are some smart hackers there they could invest in. Whereas hackers will move to the Bay Area to find investors.2. Angel investors are the most critical.There are several types of investors. The two main categories are angels and VCs: VCs invest other people's money, and angels invest their own.Though they're less well known, the angel investors are probably the more critical ingredient in creating a silicon valley. Most companies that VCs invest in would never have made it that far if angels hadn't invested first. VCs say between half and three quarters of companies that raise series A rounds have taken some outside investment already. [1]Angels are willing to fund riskier projects than VCs. They also give valuable advice, because (unlike VCs) many have been startup founders themselves.Google's story shows the key role angels play. A lot of people know Google raised money from Kleiner and Sequoia. What most don't realize is how late. That VC round was a series B round; the premoney valuation was $75 million. Google was already a successful company at that point. Really, Google was funded with angel money.It may seem odd that the canonical Silicon Valley startup was funded by angels, but this is not so surprising. Risk is always proportionate to reward. So the most successful startup of all is likely to have seemed an extremely risky bet at first, and that is exactly the kind VCs won't touch.Where do angel investors come from? From other startups. So startup hubs like Silicon Valley benefit from something like the marketplace effect, but shifted in time: startups are there because startups were there.3. Angels don't like publicity.If angels are so important, why do we hear more about VCs? Because VCs like publicity. They need to market themselves to the investors who are their "customers"—the endowments and pension funds and rich families whose money they invest—and also to founders who might come to them for funding.Angels don't need to market themselves to investors because they invest their own money. Nor do they want to market themselves to founders: they don't want random people pestering them with business plans. Actually, neither do VCs. Both angels and VCs get deals almost exclusively through personal introductions. [2]The reason VCs want a strong brand is not to draw in more business plans over the transom, but so they win deals when competing against other VCs. Whereas angels are rarely in direct competition, because (a) they do fewer deals, (b) they're happy to split them, and (c) they invest at a point where the stream is broader.4. Most investors, especially VCs, are not like founders.Some angels are, or were, hackers. But most VCs are a different type of people: they're dealmakers.If you're a hacker, here's a thought experiment you can run to understand why there are basically no hacker VCs: How would you like a job where you never got to make anything, but instead spent all your time listening to other people pitch (mostly terrible) projects, deciding whether to fund them, and sitting on their boards if you did? That would not be fun for most hackers. Hackers like to make things. This would be like being an administrator.Because most VCs are a different species of people from founders, it's hard to know what they're thinking. If you're a hacker, the last time you had to deal with these guys was in high school. Maybe in college you walked past their fraternity on your way to the lab. But don't underestimate them. They're as expert in their world as you are in yours. What they're good at is reading people, and making deals work to their advantage. Think twice before you try to beat them at that.5. Most investors are momentum investors.Because most investors are dealmakers rather than technology people, they generally don't understand what you're doing. I knew as a founder that most VCs didn't get technology. I also knew some made a lot of money. And yet it never occurred to me till recently to put those two ideas together and ask "How can VCs make money by investing in stuff they don't understand?"The answer is that they're like momentum investors. You can (or could once) make a lot of money by noticing sudden changes in stock prices. When a stock jumps upward, you buy, and when it suddenly drops, you sell. In effect you're insider trading, without knowing what you know. You just know someone knows something, and that's making the stock move.This is how most venture investors operate. They don't try to look at something and predict whether it will take off. They win by noticing that something is taking off a little sooner than everyone else. That generates almost as good returns as actually being able to pick winners. They may have to pay a little more than they would if they got in at the very beginning, but only a little.Investors always say what they really care about is the team. Actually what they care most about is your traffic, then what other investors think, then the team. If you don't yet have any traffic, they fall back on number 2, what other investors think. And this, as you can imagine, produces wild oscillations in the "stock price" of a startup. One week everyone wants you, and they're begging not to be cut out of the deal. But all it takes is for one big investor to cool on you, and the next week no one will return your phone calls. We regularly have startups go from hot to cold or cold to hot in a matter of days, and literally nothing has changed.There are two ways to deal with this phenomenon. If you're feeling really confident, you can try to ride it. You can start by asking a comparatively lowly VC for a small amount of money, and then after generating interest there, ask more prestigious VCs for larger amounts, stirring up a crescendo of buzz, and then "sell" at the top. This is extremely risky, and takes months even if you succeed. I wouldn't try it myself. My advice is to err on the side of safety: when someone offers you a decent deal, just take it and get on with building the company. Startups win or lose based on the quality of their product, not the quality of their funding deals.6. Most investors are looking for big hits.Venture investors like companies that could go public. That's where the big returns are. They know the odds of any individual startup going public are small, but they want to invest in those that at least have a chance of going public.Currently the way VCs seem to operate is to invest in a bunch of companies, most of which fail, and one of which is Google. Those few big wins compensate for losses on their other investments. What this means is that most VCs will only invest in you if you're a potential Google. They don't care about companies that are a safe bet to be acquired for $20 million. There needs to be a chance, however small, of the company becoming really big.Angels are different in this respect. They're happy to invest in a company where the most likely outcome is a $20 million acquisition if they can do it at a low enough valuation. But of course they like companies that could go public too. So having an ambitious long-term plan pleases everyone.If you take VC money, you have to mean it, because the structure of VC deals prevents early acquisitions. If you take VC money, they won't let you sell early.7. VCs want to invest large amounts.The fact that they're running investment funds makes VCs want to invest large amounts. A typical VC fund is now hundreds of millions of dollars. If $400 million has to be invested by 10 partners, they have to invest $40 million each. VCs usually sit on the boards of companies they fund. If the average deal size was $1 million, each partner would have to sit on 40 boards, which would not be fun. So they prefer bigger deals, where they can put a lot of money to work at once.VCs don't regard you as a bargain if you don't need a lot of money. That may even make you less attractive, because it means their investment creates less of a barrier to entry for competitors.Angels are in a different position because they're investing their own money. They're happy to invest small amounts—sometimes as little as $20,000—as long as the potential returns look good enough. So if you're doing something inexpensive, go to angels.8. Valuations are fiction.VCs admit that valuations are an artifact. They decide how much money you need and how much of the company they want, and those two constraints yield a valuation.Valuations increase as the size of the investment does. A company that an angel is willing to put $50,000 into at a valuation of a million can't take $6 million from VCs at that valuation. That would leave the founders less than a seventh of the company between them (since the option pool would also come out of that seventh). Most VCs wouldn't want that, which is why you never hear of deals where a VC invests $6 million at a premoney valuation of $1 million.If valuations change depending on the amount invested, that shows how far they are from reflecting any kind of value of the company.Since valuations are made up, founders shouldn't care too much about them. That's not the part to focus on. In fact, a high valuation can be a bad thing. If you take funding at a premoney valuation of $10 million, you won't be selling the company for 20. You'll have to sell for over 50 for the VCs to get even a 5x return, which is low to them. More likely they'll want you to hold out for 100. But needing to get a high price decreases the chance of getting bought at all; many companies can buy you for $10 million, but only a handful for 100. And since a startup is like a pass/fail course for the founders, what you want to optimize is your chance of a good outcome, not the percentage of the company you keep.So why do founders chase high valuations? They're tricked by misplaced ambition. They feel they've achieved more if they get a higher valuation. They usually know other founders, and if they get a higher valuation they can say "mine is bigger than yours." But funding is not the real test. The real test is the final outcome for the founder, and getting too high a valuation may just make a good outcome less likely.The one advantage of a high valuation is that you get less dilution. But there is another less sexy way to achieve that: just take less money.9. Investors look for founders like the current stars.Ten years ago investors were looking for the next <NAME>. This was a mistake, because Microsoft was a very anomalous startup. They started almost as a contract programming operation, and the reason they became huge was that IBM happened to drop the PC standard in their lap.Now all the VCs are looking for the next Larry and Sergey. This is a good trend, because Larry and Sergey are closer to the ideal startup founders.Historically investors thought it was important for a founder to be an expert in business. So they were willing to fund teams of MBAs who planned to use the money to pay programmers to build their product for them. This is like funding <NAME> in the hope that the programmer he'll hire is <NAME>—kind of backward, as the events of the Bubble showed. Now most VCs know they should be funding technical guys. This is more pronounced among the very top funds; the lamer ones still want to fund MBAs.If you're a hacker, it's good news that investors are looking for Larry and Sergey. The bad news is, the only investors who can do it right are the ones who knew them when they were a couple of CS grad students, not the confident media stars they are today. What investors still don't get is how clueless and tentative great founders can seem at the very beginning.10. The contribution of investors tends to be underestimated.Investors do more for startups than give them money. They're helpful in doing deals and arranging introductions, and some of the smarter ones, particularly angels, can give good advice about the product.In fact, I'd say what separates the great investors from the mediocre ones is the quality of their advice. Most investors give advice, but the top ones give good advice.Whatever help investors give a startup tends to be underestimated. It's to everyone's advantage to let the world think the founders thought of everything. The goal of the investors is for the company to become valuable, and the company seems more valuable if it seems like all the good ideas came from within.This trend is compounded by the obsession that the press has with founders. In a company founded by two people, 10% of the ideas might come from the first guy they hire. Arguably they've done a bad job of hiring otherwise. And yet this guy will be almost entirely overlooked by the press.I say this as a founder: the contribution of founders is always overestimated. The danger here is that new founders, looking at existing founders, will think that they're supermen that one couldn't possibly equal oneself. Actually they have a hundred different types of support people just offscreen making the whole show possible. [3]11. VCs are afraid of looking bad.I've been very surprised to discover how timid most VCs are. They seem to be afraid of looking bad to their partners, and perhaps also to the limited partners—the people whose money they invest.You can measure this fear in how much less risk VCs are willing to take. You can tell they won't make investments for their fund that they might be willing to make themselves as angels. Though it's not quite accurate to say that VCs are less willing to take risks. They're less willing to do things that might look bad. That's not the same thing.For example, most VCs would be very reluctant to invest in a startup founded by a pair of 18 year old hackers, no matter how brilliant, because if the startup failed their partners could turn on them and say "What, you invested $x million of our money in a pair of 18 year olds?" Whereas if a VC invested in a startup founded by three former banking executives in their 40s who planned to outsource their product development—which to my mind is actually a lot riskier than investing in a pair of really smart 18 year olds—he couldn't be faulted, if it failed, for making such an apparently prudent investment.As a friend of mine said, "Most VCs can't do anything that would sound bad to the kind of doofuses who run pension funds." Angels can take greater risks because they don't have to answer to anyone.12. Being turned down by investors doesn't mean much.Some founders are quite dejected when they get turned down by investors. They shouldn't take it so much to heart. To start with, investors are often wrong. It's hard to think of a successful startup that wasn't turned down by investors at some point. Lots of VCs rejected Google. So obviously the reaction of investors is not a very meaningful test.Investors will often reject you for what seem to be superficial reasons. I read of one VC who turned down a startup simply because they'd given away so many little bits of stock that the deal required too many signatures to close. [4] The reason investors can get away with this is that they see so many deals. It doesn't matter if they underestimate you because of some surface imperfection, because the next best deal will be almost as good. Imagine picking out apples at a grocery store. You grab one with a little bruise. Maybe it's just a surface bruise, but why even bother checking when there are so many other unbruised apples to choose from?Investors would be the first to admit they're often wrong. So when you get rejected by investors, don't think "we suck," but instead ask "do we suck?" Rejection is a question, not an answer.13. Investors are emotional.I've been surprised to discover how emotional investors can be. You'd expect them to be cold and calculating, or at least businesslike, but often they're not. I'm not sure if it's their position of power that makes them this way, or the large sums of money involved, but investment negotiations can easily turn personal. If you offend investors, they'll leave in a huff.A while ago an eminent VC firm offered a series A round to a startup we'd seed funded. Then they heard a rival VC firm was also interested. They were so afraid that they'd be rejected in favor of this other firm that they gave the startup what's known as an "exploding termsheet." They had, I think, 24 hours to say yes or no, or the deal was off. Exploding termsheets are a somewhat dubious device, but not uncommon. What surprised me was their reaction when I called to talk about it. I asked if they'd still be interested in the startup if the rival VC didn't end up making an offer, and they said no. What rational basis could they have had for saying that? If they thought the startup was worth investing in, what difference should it make what some other VC thought? Surely it was their duty to their limited partners simply to invest in the best opportunities they found; they should be delighted if the other VC said no, because it would mean they'd overlooked a good opportunity. But of course there was no rational basis for their decision. They just couldn't stand the idea of taking this rival firm's rejects.In this case the exploding termsheet was not (or not only) a tactic to pressure the startup. It was more like the high school trick of breaking up with someone before they can break up with you. In an earlier essay I said that VCs were a lot like high school girls. A few VCs have joked about that characterization, but none have disputed it.14. The negotiation never stops till the closing.Most deals, for investment or acquisition, happen in two phases. There's an initial phase of negotiation about the big questions. If this succeeds you get a termsheet, so called because it outlines the key terms of a deal. A termsheet is not legally binding, but it is a definite step. It's supposed to mean that a deal is going to happen, once the lawyers work out all the details. In theory these details are minor ones; by definition all the important points are supposed to be covered in the termsheet.Inexperience and wishful thinking combine to make founders feel that when they have a termsheet, they have a deal. They want there to be a deal; everyone acts like they have a deal; so there must be a deal. But there isn't and may not be for several months. A lot can change for a startup in several months. It's not uncommon for investors and acquirers to get buyer's remorse. So you have to keep pushing, keep selling, all the way to the close. Otherwise all the "minor" details left unspecified in the termsheet will be interpreted to your disadvantage. The other side may even break the deal; if they do that, they'll usually seize on some technicality or claim you misled them, rather than admitting they changed their minds.It can be hard to keep the pressure on an investor or acquirer all the way to the closing, because the most effective pressure is competition from other investors or acquirers, and these tend to drop away when you get a termsheet. You should try to stay as close friends as you can with these rivals, but the most important thing is just to keep up the momentum in your startup. The investors or acquirers chose you because you seemed hot. Keep doing whatever made you seem hot. Keep releasing new features; keep getting new users; keep getting mentioned in the press and in blogs.15. Investors like to co-invest.I've been surprised how willing investors are to split deals. You might think that if they found a good deal they'd want it all to themselves, but they seem positively eager to syndicate. This is understandable with angels; they invest on a smaller scale and don't like to have too much money tied up in any one deal. But VCs also share deals a lot. Why?Partly I think this is an artifact of the rule I quoted earlier: after traffic, VCs care most what other VCs think. A deal that has multiple VCs interested in it is more likely to close, so of deals that close, more will have multiple investors.There is one rational reason to want multiple VCs in a deal: Any investor who co-invests with you is one less investor who could fund a competitor. Apparently Kleiner and Sequoia didn't like splitting the Google deal, but it did at least have the advantage, from each one's point of view, that there probably wouldn't be a competitor funded by the other. Splitting deals thus has similar advantages to confusing paternity.But I think the main reason VCs like splitting deals is the fear of looking bad. If another firm shares the deal, then in the event of failure it will seem to have been a prudent choice—a consensus decision, rather than just the whim of an individual partner.16. Investors collude.Investing is not covered by antitrust law. At least, it better not be, because investors regularly do things that would be illegal otherwise. I know personally of cases where one investor has talked another out of making a competitive offer, using the promise of sharing future deals.In principle investors are all competing for the same deals, but the spirit of cooperation is stronger than the spirit of competition. The reason, again, is that there are so many deals. Though a professional investor may have a closer relationship with a founder he invests in than with other investors, his relationship with the founder is only going to last a couple years, whereas his relationship with other firms will last his whole career. There isn't so much at stake in his interactions with other investors, but there will be a lot of them. Professional investors are constantly trading little favors.Another reason investors stick together is to preserve the power of investors as a whole. So you will not, as of this writing, be able to get investors into an auction for your series A round. They'd rather lose the deal than establish a precedent of VCs competitively bidding against one another. An efficient startup funding market may be coming in the distant future; things tend to move in that direction; but it's certainly not here now. 17. Large-scale investors care about their portfolio, not any individual company.The reason startups work so well is that everyone with power also has equity. The only way any of them can succeed is if they all do. This makes everyone naturally pull in the same direction, subject to differences of opinion about tactics.The problem is, larger scale investors don't have exactly the same motivation. Close, but not identical. They don't need any given startup to succeed, like founders do, just their portfolio as a whole to. So in borderline cases the rational thing for them to do is to sacrifice unpromising startups.Large-scale investors tend to put startups in three categories: successes, failures, and the "living dead"—companies that are plugging along but don't seem likely in the immediate future to get bought or go public. To the founders, "living dead" sounds harsh. These companies may be far from failures by ordinary standards. But they might as well be from a venture investor's point of view, and they suck up just as much time and attention as the successes. So if such a company has two possible strategies, a conservative one that's slightly more likely to work in the end, or a risky one that within a short time will either yield a giant success or kill the company, VCs will push for the kill-or-cure option. To them the company is already a write-off. Better to have resolution, one way or the other, as soon as possible.If a startup gets into real trouble, instead of trying to save it VCs may just sell it at a low price to another of their portfolio companies. <NAME> said in Founders at Work that Ars Digita's VCs did this to them.18. Investors have different risk profiles from founders.Most people would rather a 100% chance of $1 million than a 20% chance of $10 million. Investors are rich enough to be rational and prefer the latter. So they'll always tend to encourage founders to keep rolling the dice. If a company is doing well, investors will want founders to turn down most acquisition offers. And indeed, most startups that turn down acquisition offers ultimately do better. But it's still hair-raising for the founders, because they might end up with nothing. When someone's offering to buy you for a price at which your stock is worth $5 million, saying no is equivalent to having $5 million and betting it all on one spin of the roulette wheel.Investors will tell you the company is worth more. And they may be right. But that doesn't mean it's wrong to sell. Any financial advisor who put all his client's assets in the stock of a single, private company would probably lose his license for it.More and more, investors are letting founders cash out partially. That should correct the problem. Most founders have such low standards that they'll feel rich with a sum that doesn't seem huge to investors. But this custom is spreading too slowly, because VCs are afraid of seeming irresponsible. No one wants to be the first VC to give someone fuck-you money and then actually get told "fuck you." But until this does start to happen, we know VCs are being too conservative.19. Investors vary greatly.Back when I was a founder I used to think all VCs were the same. And in fact they do all look the same. They're all what hackers call "suits." But since I've been dealing with VCs more I've learned that some suits are smarter than others.They're also in a business where winners tend to keep winning and losers to keep losing. When a VC firm has been successful in the past, everyone wants funding from them, so they get the pick of all the new deals. The self-reinforcing nature of the venture funding market means that the top ten firms live in a completely different world from, say, the hundredth. As well as being smarter, they tend to be calmer and more upstanding; they don't need to do iffy things to get an edge, and don't want to because they have more brand to protect.There are only two kinds of VCs you want to take money from, if you have the luxury of choosing: the "top tier" VCs, meaning about the top 20 or so firms, plus a few new ones that are not among the top 20 only because they haven't been around long enough.It's particularly important to raise money from a top firm if you're a hacker, because they're more confident. That means they're less likely to stick you with a business guy as CEO, like VCs used to do in the 90s. If you seem smart and want to do it, they'll let you run the company.20. Investors don't realize how much it costs to raise money from them.Raising money is a huge time suck at just the point where startups can least afford it. It's not unusual for it to take five or six months to close a funding round. Six weeks is fast. And raising money is not just something you can leave running as a background process. When you're raising money, it's inevitably the main focus of the company. Which means building the product isn't.Suppose a Y Combinator company starts talking to VCs after demo day, and is successful in raising money from them, closing the deal after a comparatively short 8 weeks. Since demo day occurs after 10 weeks, the company is now 18 weeks old. Raising money, rather than working on the product, has been the company's main focus for 44% of its existence. And mind you, this an example where things turned out well.When a startup does return to working on the product after a funding round finally closes, it's as if they were returning to work after a months-long illness. They've lost most of their momentum.Investors have no idea how much they damage the companies they invest in by taking so long to do it. But companies do. So there is a big opportunity here for a new kind of venture fund that invests smaller amounts at lower valuations, but promises to either close or say no very quickly. If there were such a firm, I'd recommend it to startups in preference to any other, no matter how prestigious. Startups live on speed and momentum.21. Investors don't like to say no.The reason funding deals take so long to close is mainly that investors can't make up their minds. VCs are not big companies; they can do a deal in 24 hours if they need to. But they usually let the initial meetings stretch out over a couple weeks. The reason is the selection algorithm I mentioned earlier. Most don't try to predict whether a startup will win, but to notice quickly that it already is winning. They care what the market thinks of you and what other VCs think of you, and they can't judge those just from meeting you.Because they're investing in things that (a) change fast and (b) they don't understand, a lot of investors will reject you in a way that can later be claimed not to have been a rejection. Unless you know this world, you may not even realize you've been rejected. Here's a VC saying no: We're really excited about your project, and we want to keep in close touch as you develop it further. Translated into more straightforward language, this means: We're not investing in you, but we may change our minds if it looks like you're taking off. Sometimes they're more candid and say explicitly that they need to "see some traction." They'll invest in you if you start to get lots of users. But so would any VC. So all they're saying is that you're still at square 1.Here's a test for deciding whether a VC's response was yes or no. Look down at your hands. Are you holding a termsheet?22. You need investors.Some founders say "Who needs investors?" Empirically the answer seems to be: everyone who wants to succeed. Practically every successful startup takes outside investment at some point.Why? What the people who think they don't need investors forget is that they will have competitors. The question is not whether you need outside investment, but whether it could help you at all. If the answer is yes, and you don't take investment, then competitors who do will have an advantage over you. And in the startup world a little advantage can expand into a lot.<NAME> famously said that he invested in Yahoo because he thought they had a few weeks' lead over their competitors. That may not have mattered quite so much as he thought, because Google came along three years later and kicked Yahoo's ass. But there is something in what he said. Sometimes a small lead can grow into the yes half of a binary choice.Maybe as it gets cheaper to start a startup, it will start to be possible to succeed in a competitive market without outside funding. There are certainly costs to raising money. But as of this writing the empirical evidence says it's a net win.23. Investors like it when you don't need them.A lot of founders approach investors as if they needed their permission to start a company—as if it were like getting into college. But you don't need investors to start most companies; they just make it easier.And in fact, investors greatly prefer it if you don't need them. What excites them, both consciously and unconsciously, is the sort of startup that approaches them saying "the train's leaving the station; are you in or out?" not the one saying "please can we have some money to start a company?"Most investors are "bottoms" in the sense that the startups they like most are those that are rough with them. When Google stuck Kleiner and Sequoia with a $75 million premoney valuation, their reaction was probably "Ouch! That feels so good." And they were right, weren't they? That deal probably made them more than any other they've done.The thing is, VCs are pretty good at reading people. So don't try to act tough with them unless you really are the next Google, or they'll see through you in a second. Instead of acting tough, what most startups should do is simply always have a backup plan. Always have some alternative plan for getting started if any given investor says no. Having one is the best insurance against needing one.So you shouldn't start a startup that's expensive to start, because then you'll be at the mercy of investors. If you ultimately want to do something that will cost a lot, start by doing a cheaper subset of it, and expand your ambitions when and if you raise more money.Apparently the most likely animals to be left alive after a nuclear war are cockroaches, because they're so hard to kill. That's what you want to be as a startup, initially. Instead of a beautiful but fragile flower that needs to have its stem in a plastic tube to support itself, better to be small, ugly, and indestructible.Notes[1] I may be underestimating VCs. They may play some behind the scenes role in IPOs, which you ultimately need if you want to create a silicon valley.[2] A few VCs have an email address you can send your business plan to, but the number of startups that get funded this way is basically zero. You should always get a personal introduction—and to a partner, not an associate.[3] Several people have told us that the most valuable thing about startup school was that they got to see famous startup founders and realized they were just ordinary guys. Though we're happy to provide this service, this is not generally the way we pitch startup school to potential speakers.[4] Actually this sounds to me like a VC who got buyer's remorse, then used a technicality to get out of the deal. But it's telling that it even seemed a plausible excuse.Thanks to <NAME>, <NAME>, <NAME>, and Robert Morris for reading drafts of this, and to Kenneth King of ASES for inviting me to speak. Comment on this essay.
https://github.com/MatheSchool/typst-g-exam
https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/docs-shiroa/g-exam-doc/introduction.typ
typst
MIT License
#import "mod.typ": * #show: book-page.with(title: "Introduction") = Introduction Introducción a la documentación de g-exam. *Uno* prueba *Dos* Prueba // *shiroa* (_Shiro A_, or _The White_, or _云笺_) is a simple tool for creating modern online (cloud) books in pure typst. It has similar use cases as #link("https://rust-lang.github.io/mdBook/index.html")[mdBook], which is ideal for creating product or API documentation, tutorials, course materials or anything that requires a clean, easily navigable and customizable presentation. // *shiroa* is heavily inspired by mdBook, but it is considered to be more adapted to Typst style, hence no guarantee of compatibility with mdBook. Compared with mdBook, we utilizes typst's advantages to bring a more flexible writing experience, such as #link("https://typst.app/docs/reference/scripting/")[scripting] and #link("https://typst.app/docs/packages/")[package]. // = Not yet finished project // *shiroa* still have many items in todolist: // - User experience, which is transparent to writers: // - SEO optimization // - Faster font loading // - Reducing the size of theme bundle files and compiled svg artifacts // - Add prev/next buttons // - initialize a book project interactively // - Writer experience: // - Multimedia html elements // - Book specific helper functions // - Customize Favicon // - Developer experience: // - Continuous CI testing for `shiroa` // Hence you may meet many problems. We are active to receive questions and bugs in #link("https://github.com/Myriad-Dreamin/shiroa/issues")[Github Issues] and please feel free to open issues. If you'd like to contribute, please consider opening a #link("https://github.com/Myriad-Dreamin/shiroa/pulls")[pull request]. // = License // *shiroa* source and documentation are released under the #link("https://www.apache.org/licenses/LICENSE-2.0")[Apache License v2.0]. // The source and documentation in theme directory in `themes/mdbook` are released under the #link("https://www.mozilla.org/en-US/MPL/2.0/")[Mozilla Public License v2.0].
https://github.com/leeqh98/dict
https://raw.githubusercontent.com/leeqh98/dict/master/chapter01/noun.typ
typst
/ Ligature: A merged glyph. / Kerning: A spacing adjustment between two adjacent letter: / sabotage: / figuratively: / ubiquitously: / blunt: / riveting: / reinforce: / heighten:
https://github.com/r8vnhill/apunte-bibliotecas-de-software
https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit3/Publish.typ
typst
== Publicación de bibliotecas La publicación de bibliotecas es el proceso de distribuir un conjunto de funcionalidades empaquetadas en un archivo para que otrxs desarrolladorxs puedan utilizarlas en sus proyectos. Este proceso facilita la reutilización de código, promueve la colaboración y fomenta el desarrollo de software modular. === Beneficios - *No reinventar la rueda*: - Permite a los desarrolladores reutilizar funcionalidades ya implementadas, reduciendo el tiempo y esfuerzo necesarios para desarrollar nuevas aplicaciones. - *Mejora de la calidad del software*: - Utilizar bibliotecas probadas y mantenidas ayuda a mejorar la calidad del software, ya que se basan en soluciones robustas y bien documentadas. - *Facilitación de actualizaciones y mejoras centralizadas*: - Facilita la implementación de actualizaciones y mejoras de manera centralizada, asegurando que todos los proyectos que utilizan la biblioteca se beneficien de las mejoras y correcciones. === Proceso de Publicación 1. *Compilación de la biblioteca*: - Asegurarse de que el código fuente de la biblioteca se compila correctamente sin errores. 2. *Generación de artefactos*: - *JAR* en el caso de Java/Kotlin/Scala. - *Wheels* para Python. - *Static Library (lib)*, *Shared Library (dll/so/dylib)* en C++. - *RubyGems* con Ruby. 3. *Subida a un repositorio o plataforma de distribución*: - Por ejemplo, GitHub Releases, GitHub Packages, Maven Central. === Documentación Una biblioteca sin una documentación clara es “desechable”. Una buena documentación facilita el entendimiento y uso de la biblioteca por otrxs desarrolladorxs, ahorra tiempo y recursos al reducir la necesidad de soporte y consultas frecuentes, y mejora la adopción de la biblioteca, ya que los desarrolladores prefieren usar herramientas bien documentadas. ==== Documentación inadecuada - Lxs usuarixs pueden encontrar difícil entender cómo utilizar la biblioteca correctamente. - Incrementa los errores y malentendidos, lo que lleva a una percepción negativa de la biblioteca. - Reducción en la tasa de adopción, ya que lxs desarrolladorxs buscarán alternativas mejor documentadas. ==== Buena documentación - Proporciona una visión general de cómo instalar y comenzar a usar la biblioteca. - Incluye ejemplos de código que muestran cómo utilizar las funciones y características principales. - Documenta todas las funciones, clases y métodos disponibles en la biblioteca con descripciones detalladas. - Explica cómo la biblioteca puede resolver problemas específicos con ejemplos concretos. - Aborda preguntas comunes y problemas que los usuarios pueden encontrar. ==== Buenas prácticas - Mantén un estilo y formato consistente en toda la documentación. - Asegúrate de que la documentación se mantenga actualizada con las nuevas versiones de la biblioteca. - Evita el uso de jerga técnica innecesaria y sé claro y directo en las explicaciones. - Recoge y actúa sobre el feedback de los usuarios para mejorar la documentación. ==== Herramientas Herramientas como Javadoc (Java), KDoc y Dokka (Kotlin), Sphinx (Python), entre otros, pueden ayudar a generar documentación a partir del código fuente. Publica la documentación en plataformas accesibles como GitHub Pages, Read the Docs, o sitios web dedicados. ==== Documentación eficaz - Cómo instalar la biblioteca y un ejemplo simple de uso. - Ejemplos prácticos de diferentes funcionalidades de la biblioteca. - Detalles de todas las funciones, métodos y clases disponibles, con ejemplos de uso. - Respuestas a preguntas comunes y soluciones a problemas típicos. === Configuración del proyecto Utilizaremos la librería Echo de la sección anterior. Publicaremos la biblioteca como un _release_ en GitHub y como una dependencia en GitHub Packages. Lo primero que necesitamos es convertir nuestra librería en un proyecto de git. Luego, debemos crear un repositorio en GitHub para nuestro proyecto. NO haremos _push_ todavía, ya que necesitamos configurar algunas cosas antes de hacerlo. 1. *Inicializar un Repositorio Git*: - Abre tu terminal y navega hasta el directorio de tu proyecto. - Ejecuta `git init` para inicializar un nuevo repositorio git. 2. *Crear un Repositorio en GitHub*: - Ve a #link("https://github.com")[GitHub] y crea un nuevo repositorio. - Sigue las instrucciones para crear un nuevo repositorio. - Asegúrate de no inicializarlo con un README, ya que ya tienes archivos en tu proyecto local. Aquí tienes la versión mejorada y desarrollada usando la sintaxis de Typst: ==== Dokka Dokka es una herramienta de generación de documentación para proyectos Kotlin. Similar a Javadoc para Java, Dokka convierte comentarios de documentación en código Kotlin en HTML, Markdown y otros formatos de salida. ```properties # gradle.properties # ... dokka.version=1.9.20 ``` ```kotlin // settings.gradle.kts /* ... */ pluginManagement { /* ... */ plugins { /* ... */ id("org.jetbrains.dokka") version extra["dokka.version"] as String } } ``` ```kotlin // echoLib/build.gradle.kts import org.jetbrains.dokka.gradle.DokkaTask plugins { /* ... */ id("org.jetbrains.dokka") } val dokkaVersion = extra["dokka.version"] as String dependencies { dokkaHtmlPlugin("org.jetbrains.dokka:kotlin-as-java-plugin:$dokkaVersion") } val dokkaHtml by tasks.getting(DokkaTask::class) /* ... */ ``` ````kotlin /** * Returns the input string as it is. * * This function takes a string as input and returns the same string without any * modifications. * * ## Usage: * ``` * val text = "Hello, world!" * val result = id(text) * // result == "Hello, world!" * ``` * * @param text The input string to be returned. * @return The same input string. */ fun id(text: String) = text ```` Para generar la documentación, ejecuta el siguiente comando: ```powershell # Windows .\gradlew.bat :echoLib:dokkaHtml ``` ```bash # Unix ./gradlew :echoLib:dokkaHtml ``` #figure( image("../img/dokka_1.png", width: 25%), caption: [Documentación compilada por Dokka, con `index.html` como punto de entrada.] ) #figure( image("../img/dokka_2.png", width: 60%), caption: [Documentación de la función `id` generada por Dokka.] ) === Publicación en GitHub Puedes encontrar información sobre cómo publicar tu biblioteca usando GitHub en el siguiente enlace: https://ravenhill.pages.dev/ccxxxx/lessons/build-systems-iv
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fh-joanneum-iit-thesis/1.2.0/template/chapters/glossary.typ
typst
Apache License 2.0
#import "global.typ": * // Not listed in table of contents (the outline) // Not numbered #heading(outlined: false, numbering: none)[ Glossary ] // Add list of terms // Usage within text will then be #gls(<key>) or plurals #glspl(<key>) #print-glossary( ( ( key: "cow", short: "COW", long: "Copy on Write", desc: [Copy on Write is a memory allocation strategy where arrays are copied if they are to be modified.], ), ( key: "gc", short: "GC", long: "Garbage Collection", desc: [Garbage collection is the common name for the term automatic memory management.], ) ) )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/string-20.typ
typst
Other
// Test the `split` method. #test("abc".split(""), ("", "a", "b", "c", "")) #test("abc".split("b"), ("a", "c")) #test("a123c".split(regex("\d")), ("a", "", "", "c")) #test("a123c".split(regex("\d+")), ("a", "c"))
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/foundations-11.typ
typst
Other
// Test failing assertions. // Error: 11-57 inequality assertion failed: must be different from 11 #assert.ne(11, 11, message: "must be different from 11")
https://github.com/Student-Smart-Printing-Service-HCMUT/ssps-docs
https://raw.githubusercontent.com/Student-Smart-Printing-Service-HCMUT/ssps-docs/main/contents/categories/task5/5.2.typ
typst
Apache License 2.0
#pagebreak() == Kế hoạch kiểm tra hệ thống Nhóm thực hiện testplan trên 2 module chính đã thực thi là đăng nhập và upload file === Đăng nhập Nhóm thực thi sử dụng danh sách tài khoản hợp lệ và không hợp lệ để đăng nhập vào hệ thống để ghi lại hành vi của hệ thống. Tài khoản phải bao gồm ít nhất 5 kí tự và mật khẩu phải ít nhất 8 kí tự. #table( columns: (40pt, 120pt, 70pt, 120pt, auto), inset: 10pt, align: horizon, [*Test*], [*Tài khoản*], [*Mật khẩu*], [*Đặc điểm*], [*Kết quả*], "1", "dt", "12345678", "Tên tài khoản không đạt đủ 5 ký tự", image("../../images/testcase1.png"), "2", "duytan1711", "12345", "Mật khẩu không đạt đủ 8 ký tự", image("../../images/testcase2.png"), "3", "dt", "12345", "Cả tài khoản và mật khẩu đều không thỏa mãn về số ký tự tối thiểu", image("../../images/testcase3.png"), "4", "<EMAIL>", "1234567890", "Tài khoản hoặc mật khẩu không chính xác", image("../../images/testcase4.png"), "5", "<EMAIL>", "123456789", "Thỏa mãn điều kiện và đăng nhập vào hệ thống", image("../../images/testcase5.png") ) === Upload tài liệu Hệ thống chấp nhận những tài liệu với các định dạng *.doc, .docx, .xls, .xlsx, .ppt, .jpg, .png, .pdf* với kích thước file tối đa là 100MB nên chúng ta sẽ lần lượt thực hiện các testcase trên các định dạng file khác nhóm trên, file có kích thước lớn hơn 100MB và những file phù hợp để theo dõi phản hồi của hệ thống ==== File có định dạng khác trong những định dạng được chấp nhận Người dùng upload file có định dạng *.pkt* - *_2110527-NguyenHoangDuyTan-lab1c.pkt_*. Hệ thống sẽ không chuyển sang trang chỉnh sửa thông tin file. #figure( grid( columns: 2, gutter: 3mm, image("../../images/testcaseupload1.png"), image("../../images/testcaseupload2.png"), ), caption: "Phản hồi hệ thống khi người dùng upload file có định dạng không phù hợp" ) === File có định dạng phù hợp nhưng kích thước lớn. Người dùng upload file *_Giáo trình Lịch sử ĐCS VN.pdf_* với kích thước *16.8 MB* Người dùng chờ hệ thống một khoảng thời gian tương đối để phản hồi và chuyển sang trang chỉnh sửa thông tin. #figure( image("../../images/testcaseupload3.png"), caption: "Người dùng upload file với định dạng pdf với kích thước lớn" ) Sau khoảng thời gian tầm 5-7s, hệ thống sẽ chuyển sang trang chỉnh sửa thông tin #figure( image("../../images/testcaseupload4.png"), caption: "Hệ thống phản hồi sau một khoảng thời gian dài" ) === File có định dạng phù hợp với kích thước nhỏ Người dùng upload file *paypal.png* với kích thước *4 KB*. Hệ thống phản hồi ngay lập tức và chuyển sang trang chỉnh sửa thông tin. #figure( image("../../images/testcaseupload5.png"), caption: "Người dùng upload file với định dạng png với kích thước nhỏ" ) Hệ thống phản hồi ngay lập tức và chuyển sang trang chỉnh sửa thông tin #figure( image("../../images/testcaseupload6.png"), caption: "Hệ thống phản hồi ngay lập tức" )
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/introspection/counter.typ
typst
// Test counters. --- counter-basic-1 --- // Count with string key. #let mine = counter("mine!") Final: #context mine.final().at(0) \ #mine.step() First: #context mine.display() \ #mine.update(7) #context mine.display("1 of 1", both: true) \ #mine.step() #mine.step() Second: #context mine.display("I") #mine.update(n => n * 2) #mine.step() --- counter-basic-2 --- // Test `counter`. #let c = counter("heading") #c.update(2) #c.update(n => n + 2) #context test(c.get(), (4,)) #c.update(n => n - 3) #context test(c.at(here()), (1,)) --- counter-label --- // Count labels. #let label = <heya> #let count = context counter(label).display() #let elem(it) = [#box(it) #label] #elem[hey, there!] #count \ #elem[more here!] #count --- counter-heading --- // Count headings. #set heading(numbering: "1.a.") #show heading: set text(10pt) #counter(heading).step() = Alpha In #context counter(heading).display() == Beta #set heading(numbering: none) = Gamma #heading(numbering: "I.")[Delta] At Beta, it was #context { let it = query(heading).find(it => it.body == [Beta]) numbering(it.numbering, ..counter(heading).at(it.location())) } --- counter-page --- #set page(height: 50pt, margin: (bottom: 20pt, rest: 10pt)) #lines(4) #set page(numbering: "(i)") #lines(2) #pagebreak() #set page(numbering: "1 / 1") #counter(page).update(1) #lines(7) --- counter-page-footer-before-set-page --- #set page(numbering: "1", margin: (bottom: 20pt)) A #pagebreak() #counter(page).update(5) #set page(fill: aqua) B --- counter-page-header-before-set-page --- #set page(numbering: "1", number-align: top + center, margin: (top: 20pt)) A #counter(page).update(4) #set page(fill: aqua) B --- counter-page-between-pages --- // The update happens conceptually between the pages. #set page(numbering: "1", margin: (bottom: 20pt)) A #pagebreak() #counter(page).update(5) #set page(number-align: top + center, margin: (top: 20pt, bottom: 10pt)) B --- counter-page-header-only-update --- // Header should not be affected by default. // To affect it, put the counter update before the `set page`. #set page( numbering: "1", number-align: top + center, margin: (top: 20pt), ) #counter(page).update(5) --- counter-page-footer-only-update --- // Footer should be affected by default. #set page(numbering: "1 / 1", margin: (bottom: 20pt)) #counter(page).update(5) --- counter-figure --- // Count figures. #figure(numbering: "A", caption: [Four 'A's], kind: image, supplement: "Figure")[_AAAA!_] #figure(numbering: none, caption: [Four 'B's], kind: image, supplement: "Figure")[_BBBB!_] #figure(caption: [Four 'C's], kind: image, supplement: "Figure")[_CCCC!_] #counter(figure.where(kind: image)).update(n => n + 3) #figure(caption: [Four 'D's], kind: image, supplement: "Figure")[_DDDD!_] --- counter-at-no-context --- // Test `counter.at` outside of context. // Error: 2-28 can only be used when context is known // Hint: 2-28 try wrapping this in a `context` expression // Hint: 2-28 the `context` expression should wrap everything that depends on this function #counter("key").at(<label>) --- issue-2480-counter-reset --- #let q = counter("question") #let step-show = q.step() + context q.display("1") #let g = grid(step-show, step-show, gutter: 2pt) #g #pagebreak() #step-show #q.update(10) #g --- issue-2480-counter-reset-2 --- #set block(spacing: 3pt) #let c = counter("c") #let foo() = context { c.step() c.display("1") str(c.get().first()) } #foo() #block(foo()) #foo() #foo() #block(foo()) #block(foo()) #foo() --- issue-4626-counter-depth-skip --- // When we step and skip a level, the levels should be filled with zeros, not // with ones. #let c = counter("c") #context test(c.get(), (0,)) #c.step(level: 4) #context test(c.get(), (0, 0, 0, 1)) #c.step(level: 1) #context test(c.get(), (1,)) #c.step(level: 3) #context test(c.get(), (1, 0, 1))
https://github.com/leeqh98/dict
https://raw.githubusercontent.com/leeqh98/dict/master/readme.md
markdown
# intro This is a repository for dict, in Typst
https://github.com/dadn-dream-home/documents
https://raw.githubusercontent.com/dadn-dream-home/documents/main/metadata.typ
typst
#let meta = ( course-name: "<NAME>", course-id: "CO3109", title: "Phát triển hệ thống nhà thông minh Dream home", semester: 222, date: "06/2023", students: ( "2011364": "<NAME>", "2010206": "<NAME>", "2011128": "<NAME>", "2012945": "<NAME>", ), advisor: "<NAME>" )
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/Preventivo.typ
typst
MIT License
#import "../functions.typ": glossary = Preventivo Ogni membro del gruppo si impegna a lavorare con la modalità di intensità dichiarata (alta), offrendo una disponibilità di 95 ore produttive a testa. Questo preventivo è stato calcolato sulla base del costo orario per ruolo presente nel "Regolamento del Progetto Didattico" e sulla previsione di quante, delle 570 ore totali a disposizione, verranno utilizzate in ogni ruolo, durante i vari incrementi. Nelle seguenti sezioni viene illustrato come sarà articolato ogni incremento e quanto sarà il suo costo. La suddivisione dei ruoli è stata fatta nel modo più equo possibile, per dare a tutti i membri la possibilità di approfondire le mansioni rilevanti. Per praticità, verranno utilizzate le seguenti abbreviazioni: - *Re*: Responsabile; - *Am*: Amministratore; - *An*: Analista; - *Pt*: Progettista; - *Pr*: Programmatore; - *Ve*: Verificatore. Questa sezione vuole essere una proiezione finanziaria dettagliata dell'intero progetto, delineando chiaramente le risorse preventivate per ciascuno #glossary[sprint]. #include "PreventivoSprint/PrimaRevisione.typ" #include "PreventivoSprint/PrimoSprint.typ" #include "PreventivoSprint/SecondoSprint.typ" #include "PreventivoSprint/TerzoSprint.typ" #include "PreventivoSprint/QuartoSprint.typ" #include "PreventivoSprint/QuintoSprint.typ" #include "PreventivoSprint/SestoSprint.typ" #include "PreventivoSprint/SettimoSprint.typ" #include "PreventivoSprint/OttavoSprint.typ" #include "PreventivoSprint/SecondaRevisione.typ" #include "PreventivoSprint/NonoSprint.typ" #include "PreventivoSprint/DecimoSprint.typ" #include "PreventivoSprint/TerzaRevisione.typ"
https://github.com/AHaliq/DependentTypeTheoryReport
https://raw.githubusercontent.com/AHaliq/DependentTypeTheoryReport/main/preamble/dtt.typ
typst
#let Tm = $upright(bold("Tm"))$ #let Ty = $upright(bold("Ty"))$ #let Eq = $upright(bold("Eq"))$ #let Id = $upright(bold("Id"))$ #let Void = $upright(bold("Void"))$ #let absurd = $upright("absurd")$ #let Bool = $upright(bold("Bool"))$ #let tt = $upright("true")$ #let ff = $upright("false")$ #let inl = $upright("inl")$ #let inr = $upright("inr")$ #let zero = $upright("zero")$ #let succ = $upright("succ")$ #let hy= $tack.r$ #let type = $upright("type")$ #let sq = $upright(bold("q"))$ #let sp = $upright(bold("p"))$ #let Unit = $upright("Unit")$ #let El = $upright(bold("El"))$ #let code = $upright(bold("code"))$ #let UU = $upright(bold("U"))$ #let HProp = $upright(bold("HProp"))$ #let rec = $upright("rec")$ #let ind = $upright("ind")$ #let lift = $upright(bold("lift"))$ #let uni = $upright(bold("uni"))$ #let sym = $upright("sym")$ #let trans = $upright("trans")$ #let cong = $upright("cong")$ #let subst = $upright("subst")$ #let jrule = $upright(bold("J"))$ #let uniq = $upright("uniq")$ #let gap = $#h(0.3em)$ #let refl = $upright("refl")$ #let equiv = $tilde.eq$ #let idtoequiv = $upright("idtoequiv")$ #let isotoid = $upright("isotoid")$ #let ua = $upright("ua")$
https://github.com/StefanieJaeger/sa-docu
https://raw.githubusercontent.com/StefanieJaeger/sa-docu/main/main.typ
typst
#set heading(numbering: "1.") #include "glossary.typ" #include "is-state/is-state.typ"
https://github.com/justmejulian/typst-documentation-template
https://raw.githubusercontent.com/justmejulian/typst-documentation-template/main/sections/introduction.typ
typst
= Introduction #rect( width: 100%, radius: 10%, stroke: 0.5pt, fill: yellow, )[ Note: Introduce the topic of your thesis, e.g. with a little historical overview. ] == Problem #rect( width: 100%, radius: 10%, stroke: 0.5pt, fill: yellow, )[ Note: Describe the problem that you like to address in your thesis to show the importance of your work. Focus on the negative symptoms of the currently available solution. ] == Motivation #rect( width: 100%, radius: 10%, stroke: 0.5pt, fill: yellow, )[ Note: Motivate scientifically why solving this problem is necessary. What kind of benefits do we have by solving the problem? ] == Objectives #rect( width: 100%, radius: 10%, stroke: 0.5pt, fill: yellow, )[ Note: Describe the research goals and/or research questions and how you address them by summarizing what you want to achieve in your thesis, e.g. developing a system and then evaluating it. ] == Outline #rect( width: 100%, radius: 10%, stroke: 0.5pt, fill: yellow, )[ Note: Describe the outline of your thesis ]
https://github.com/kotfind/hse-se-2-notes
https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/prob/homeworks/to-2024-10-13.typ
typst
= ДЗ 5 == Задача 3 #figure( table( columns: 3, align: center, $x$, $a$, $-a$, $P$, $1/2$, $1/2$, ) ) $ M(x) = a dot 1/2 + (-a) dot 1/2 = 0 $ $ M(x^2) = a^2 dot 1/2 + (-a)^2 dot 1/2 = a^2 $ $ D(x) = M(x^2) - (M(x))^2 = a^2 - 0^2 = a^2 $ Ответ. Не верно == Задача 4 (в) #figure( table( columns: 6, align: center, $x$, $-0.5$, $0$, $0.5$, $1$, $1.5$, $P$, $0.1$, $0.4$, $0.1$, $0.3$, $0.1$, $2^x$, $0.707$, $1$, $1.414$, $2$, $2.828$, $(2^x)^2$, $0.5$, $1$, $2$, $4$, $8$, ) ) $ M(2^x) = 0.707 dot 0.1 + 1 dot 0.4 + 1.414 dot 0.1 + 2 dot 0.3 + 2.828 dot 0.1 = 1.495 $ $ M((2^x)^2) = 0.5 dot 0.1 + 1 dot 0.4 + 2 dot 0.1 + 4 dot 0.3 + 8 dot 0.1 = 2.65 $ $ D(2^x) = M((2^x)^2) - (M(2^x))^2 = 0.415 $ Ответ. $M(2^x) = 1.495, D(2^x) = 2.65$ == Задача 9 #figure(table( columns: 3, $X$, $-1$, $1$, $P$, $1/2$, $1/2$, )) $ F_X (1/2) = P(X <= 1/2) = P(-1) = 1/2 $ $ F_X (-1/2) = P(X <= -1/2) = P(-1) = 1/2 $ Ответ. $F_X (1/2) = F_X (-1/2) = 1/2$ == Задача 10 $ xi ~ "Bi"(1, 0.2) $ #figure(table( columns: 3, $xi$, $0$, $1$, $p$, $C_1^0 p^0 q^1 = 0.8$, $C_1^1 p^1 q^0 = 0.2$, $y = 1 - x^n$, $1 - 0^n = 1$, $1 - 1^n = 0$, )) Ответ. $y ~ "Bi"(1, 0.8)$ == Задача 11 $ X ~ "Bi"((1, 1/2))$ #figure(table( columns: 3, align: center, $x$, $0$, $1$, $p$, $1/2$, $1/2$, $x^2$, $0$, $1$, )) $ M(x) = 0 dot 1/2 + 1 dot 1/2 = 1/2 $ $ M(x^2) = 0 dot 1/2 + 1 dot 1/2 = 1/2 $ $ D(x) = M(x^2) - (M(x))^2 = 1/2 - 1/4 = 1/4 $ Ответ. равны == Задача 12 $ X ~ "Bi"(4, 0.1) $ $X$ принимает значения $0, 1, 2, 4$. $ F_X (-10) = P(X <= -10) = 0 $ Ответ. 0 == Задача 19 $ X ~ R(-1, 1) $ - (а) $ M(x) = (-1 + 1) / 2 = 0 $ $ P(x < M(x)) = F_x (M(x)) = F_x (0) = (0 - (-1)) / (1 - (-1)) = 1/2 $ $ P(x > M(x)) = 1 - F_x (M(x)) = 1/2 $ Ответ. $P(x < M(x)) = P(x > M(x)) = 1/2$ - (б) $ sqrt(D(x)) = sqrt((1 - (-1))^2 / 12) = 1/sqrt(3)$ $ abs(x - M(x)) = abs(x) ~ R(0, 1) $ $ P(abs(x) < 1/sqrt(3)) = F_abs(x) (1/sqrt(3)) = (1/sqrt(3) - 0) / (1 - 0) = 1/sqrt(3) = 0.577 $ Ответ. $1/sqrt(3) = 0.577$ == Задача 27 - Чтобы агент обратился к ровно $k (k <= 4)$ покупателям, $k - 1$ первых должны ему отказать, а $k$-ый должен согласиться. - Чтобы агент обратился к ровно пяти покупателям, 4 первых должны ему отказать #figure(caption: [Ряд распределения], table( columns: 6, $x$, $1$, $2$, $3$, $4$, $5$, $p$, $0.5$, $0.2$, $0.12$, $0.054$, $0.126$, )) $ M(x) = 1 dot 0.5 + 2 dot 0.2 + 3 dot 0.12 + 4 dot 0.054 + 5 dot 0.126 = 2.106 $ $ M(x^2) = 1 dot 0.5 + 4 dot 0.2 + 9 dot 0.12 + 16 dot 0.054 + 25 dot 0.126 = 6.394 $ $ D(x) = M(x^2) - (M(x))^2 = 1.959 $ Ответ. $M(x) = 2.106, D(x) = 1.959$ == Задача 28 $ x ~ "Bi"(200, 0.3) $ - (а) $ M(x) = n p = 200 dot 0.3 = 60 $ $ D(x) = n p q = 200 dot 0.3 dot 0.7 = 42 $ - (б) $ P(x = [M(x)]) = P(x = 60) = C_200^60 dot 0.3^60 dot 0.7^140 = 0.06146$ == Задача 29 (а) Вероятность, что некоторая карта совпадет равна $1/36$. Тогда $x ~ "Bi"(36, 1/36)$. $ M(x) = n p = 36 dot 1/36 = 1 $ == Задача 32 $ x ~ "Bi"(10'000, 0.2) $ $ M(x) = n p = 10'000 dot 0.2 = 2000 $ $ D(x) = n p q = 10'000 dot 0.2 dot 0.8 = 1600 $ $ sigma(x) = sqrt(D(x)) = 40 $
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/lib/mod.typ
typst
MIT License
#import "lib.typ": * #import "catppuccin.typ": * #import "colors.typ" #import "text-case.typ": * #import "unitfmt.typ": * #import "@preview/oxifmt:0.2.1": strfmt #import "note.typ" #import "params.typ" #import "crates.typ" #import "table.typ": * #import "statistics.typ": * #import "numbers.typ" #import "durationfmt.typ": * #import "@preview/wrap-it:0.1.0": wrap-content // #import "diff.typ": diffarray, diffdict #import "diff.typ": * #import "dict.typ": * #import "binary.typ": binary, popcount, hamming-distance #import "equation.typ" #import "nouns.typ": * #import "@preview/cetz:0.2.2" #import "@preview/funarray:0.4.0": * #import "marker.typ" #import "aos-soa.typ": aos, soa #import "seq.typ": fib #let cursor = line(length: 100%, stroke: 1em + red)
https://github.com/Mc-Zen/zero
https://raw.githubusercontent.com/Mc-Zen/zero/main/src/num.typ
typst
MIT License
#import "state.typ": num-state, group-state, round-state #import "formatting.typ": * #import "rounding.typ": * #import "assertations.typ": * #import "parsing.typ" #let update-state(state, args, name: none) = { state.update(s => { assert-settable-args(args, s, name: name) s + args.named() }) } #let set-num(..args) = update-state(num-state, args, name: "set-num") #let set-group(..args) = { num-state.update(s => { assert-settable-args(args, s.group, name: "set-group") s.group += args.named() s }) } #let set-round(..args) = { num-state.update(s => { assert-settable-args(args, s.round, name: "set-round") s.round += args.named() s }) } #let contextual-round(int, frac, pm, round-state) = { round( int, frac, mode: round-state.mode, precision: round-state.precision, direction: round-state.direction, pad: round-state.pad, pm: pm ) } #let show-num = it => { // Process input let info if type(it.number) == dictionary { info = it.number if "mantissa" in info { let mantissa = info.mantissa if type(mantissa) in (int, float) { mantissa = str(mantissa).replace(sym.minus, "-") } let (sign, int, frac) = parsing.decompose-signed-float-string(mantissa) info += (sign: sign, int: int, frac: frac) } if "sign" not in info {info.sign = "" } } else { let num-str = number-to-string(it.number) if num-str == none { assert(false, message: "Cannot parse the number `" + repr(it.number) + "`") } info = decompose-normalized-number-string(num-str) } /// Maybe shift exponent if it.fixed != none { let e = if info.e == none { 0 } else { int(info.e) } info.e = str(it.fixed).replace(sym.minus, "-") (info.int, info.frac) = utility.shift-decimal-left(info.int, info.frac, it.fixed - e) } /// Round number and uncertainty if it.round.mode != none { (info.int, info.frac, info.pm) = contextual-round(info.int, info.frac, info.pm, it.round) } let digits = if it.digits == auto { info.frac.len() } else { it.digits } if digits < 0 { assert(false, message: "`digits` needs to be positive, got " + str(digits)) } if info.pm != none { let pm = info.pm if type(pm.first()) != array { pm = (pm,) } digits = calc.max(digits, ..pm.map(array.last).map(str.len)) } // info.digits = digits it.digits = digits // Format number let components = show-num-impl(info + it) let collect = if it.math { make-equation } else { it => it.join() } if it.align == none { return collect(components.join()) } let (col-widths, col) = it.align let components = components.map(x => if x == () { none } else { collect(x) }) let widths = components.map(x => if x == none { 0pt } else { measure(x).width }) if col-widths != auto { for i in range(4) { let alignment = if i == 0 { right } else { left } let content = align(alignment, components.at(i)) components.at(i) = box(width: col-widths.at(i), content) } } [#components.join()#metadata((col,) + widths)<__pillar-num__>] } #let update-num-state(state, args) = { if "round" in args { state.round += args.round; args.remove("round") } if "group" in args { state.group += args.group; args.remove("group") } return state + args } #let num( number, align: none, state: auto, ..args ) = { if type(number) == array { let named = args.named() let num-state = if state == auto { num-state.get() } else { state } let round-state = if state == auto { round-state.get() } else { num-state.round } let group-state = if state == auto { group-state.get() } else { num-state.group } if "round" in named { round-state += named.round } if "group" in named { group-state += named.group } let it = num-state + ( align: align, ..args.named() ) it.round = round-state it.group = group-state return number.map(n => show-num(it + (number: n))) } if state != auto { let it = update-num-state(state, args.named()) + ( align: align, number: number ) return show-num(it) } context { let it = update-num-state(num-state.get(), args.named()) + ( align: align, number: number ) show-num(it) } } /* - Mantissa (value or uncertainty): Doesn't really need a show rule? - Power: A rule would be beneficial. Does the multiplier need to be included? Question: How to pass values on to the nested types #set num.power(base: [5]) and then #num(power: (base: [4]), "1.23e4") show num.power: it => { - it.exponent [2.3] - it.base [10] - it.multiplier [×] ?? math.attach([#it.base], t: [#it.exponent]) or ( box(), it.multiplier, math.attach([#it.base], t: [#it.exponent]) ) } show num.exponent: it => { - it.sign - it.integer - it.fractional it.sign + format-integer(it.integer) + format-fractional(it.fractional).join() } show num.uncertainty: it => { - it.value ([0.2, 0.4]) - it.mode - it.symmetric false if it.mode == ... if it.symmetric { return ( math.class("normal", none), math.class(if state.tight {"normal"} else {"binary"}, sym.plus.minus), it.value ) } else { math.attach(none, t: sym.plus + it.value.at(0), b: sym.minus + it.value.at(1)), } } show num.num: it => { } */
https://github.com/cetz-package/cetz-venn
https://raw.githubusercontent.com/cetz-package/cetz-venn/master/doc/example.typ
typst
Apache License 2.0
#import "/src/lib.typ" #import "@preview/cetz:0.2.2" // String that gets prefixed to every example code // for compilation only! #let example-preamble = "" #let example-scope = (cetz-venn: lib, cetz: cetz) /// Render an example from a string /// - source (string, raw): Example source code /// - args (arguments): Arguments passed down to the canvas /// - vertical (boolean): If true, show the code below the canvas #let example(source, ..args, vertical: false) = { if type(source) == content { source = source.text } let radius = .25cm let border = 1pt + gray let canvas-background = yellow.lighten(95%) let picture = eval(example-preamble + source, scope: example-scope) let source = box( raw( source, lang: "typc" ), width: 100% ) block( if vertical { align( center, stack( dir: ttb, spacing: 1em, block( width: 100%, clip: true, radius: radius, stroke: border, table( columns: 1, stroke: none, fill: (c,r) => (canvas-background, white).at(r), picture, align(left, source) ) ), ) ) } else { block( table( columns: 2, stroke: none, fill: (canvas-background, white), align: (center + horizon, left), picture, source ), width: 100%, radius: radius, clip: true, stroke: border ) }, breakable: false) }
https://github.com/justmejulian/typst-documentation-template
https://raw.githubusercontent.com/justmejulian/typst-documentation-template/main/metadata.typ
typst
// Enter your thesis data here: #let title = "(Title)" #let subtitle = "(Subtitle)" #let program = "MSE - Computer Science" #let school = "Zurich University of Applied Sciences" #let advisor = "(Advisor)" #let author = "(Author)" #let expert = "(Expert)" #let proofReader = "(Proof Reader)"
https://github.com/Functional-Bus-Description-Language/Specification
https://raw.githubusercontent.com/Functional-Bus-Description-Language/Specification/master/src/functionalities/irq.typ
typst
== Irq The irq functionality represents an interrupt handling. The irq functionality allows for automatic connection of the following interrupt producers (in-trigger) and consumers (out-trigger): #set enum(numbering: "1)") + edge producer and edge sensitive consumer, #set align(center) #image("../images/irq-edge-edge.svg", width: 80%) #set align(left) + edge producer and level sensitive consumer, #set align(center) #image("../images/irq-edge-level.svg", width: 80%) #set align(left) + level producer and edge sensitive consumer, #set align(center) #image("../images/irq-level-edge.svg", width: 80%) #set align(left) + level producer and level sensitive consumer, #set align(center) #image("../images/irq-level-level.svg", width: 80%) #set align(left) The irq functionality has following properties: *`add-enable`*` bool (false) {definitive}` #pad(left: 1em)[ The add-enable property defines whether an interrupt has associated enable bit in the interrupt enable register. The enable can be used to mask the interrupt. ] *`clear`*` string (`_`"Explicit"`_`) {definitive}` #pad(left: 1em)[ The clear property defines how particular interrupt flag is cleared. The clear property is valid only in case of level-triggered interrupt consumer. If clear property is set for edge-triggered interrupt consumer a compiler shall report an error. Valid values are _`"Explicit"`_ and _`"On Read"`_. The _`"Explicit"`_ clear requires compiler to generate a means that must be explicitly used to clear the interrupt flag. The _`"On Read"`_ clear requires the provider to clear the interrupt flag on each interrupt flag read. ] *`enable-init-value`*` bit string (uninitialized) {definitive}` #pad(left: 1em)[ The enable-init-value property defines the initial value of the enable bit in the interrupt enable register. The value must not exceed one bit. If add-enable is false and enable-init-value is set, then a compiler must report an error. ] *`enable-reset-value`*` bit string (uninitialized) {definitive}` #pad(left: 1em)[ The enable-reset-value property defines the value of the enable bit in the interrupt enable register after the reset. The value must not exceed one bit. If add-enable is false and enable-reset-value is set, then a compiler must report an error. If the enable-reset-value is set, but a bus or block containing the irq is not resettable (`reset = None`), then the compiler shall report an error. ] *`in-trigger`*` string (`_`"Level"`_`) {declarative}` #pad(left: 1em)[ The in-trigger property declares the interrupt producer type of trigger. Valid values are _`"Edge"`_ and _`"Level"`_. It is up to the user to make sure declared trigger is coherent with the actual producer behavior. A mismatch may lead to incorrect behavior. ] *`out-trigger`*` string (`_`"Level"`_`) {declarative}` #pad(left: 1em)[ The out-trigger property declares the interrupt consumer type of trigger. Valid values are _`"Edge"`_ and _`"Level"`_. It is up to the user to make sure declared trigger is coherent with the actual consumer requirement. A mismatch may lead to incorrect behavior. ]
https://github.com/dismint/docmint
https://raw.githubusercontent.com/dismint/docmint/main/comptheory/pset1.typ
typst
#import "template.typ": * #show: template.with( title: "PSET 1", subtitle: "18.404", pset: true, ) = Problem 1 == (a) #twocola( bimg("imgs/graph.png", width: 80%), [ We have five states, each representing the `mod 5` of the number we have accepted up until now. Notably the accept state and the start state are the same since we start with $0$ and can also accept the empty string as the value $0$ which is divisible by $5$ ] ) == (b) It is possible to construct a DFA for $"MFIVE"_d$ for any $d >= 2$ by using the following steps: + All such DFAs can be constructed with $5$ states, one for each possible remainder when divided by $5$ + The start state is the same as the accept state, since any number conceptually starts with a value of $0$ and the desired behavior is to accept numbers that are divisible by $5$, and the empty string is accepted as a value of $0$ + Draw transitions out of each state $q$. To do this, assume that the number so far has as remainder of $q$ when divided by $5$. Then, for each possible digit $x$ in the base $d$ that we are working with, you can calculate the new remainder with $ delta(q, x) = (d dot q + x) mod 5 = r $ Then draw a transition from state $q$ to state $r$ labeled with $x$. Conceptually, when we add a new digit the entire number shifts to the left, which can be thought of as as multiplication of the old number by the base $d$. + Repeat for all modularities and digits. It does not matter what order the transitions are drawn. = Problem 2 To show that the class of regular languages is closed under the $N_1$ operation, I will construct a NFA that recognizes it. Construct the NFA as follows: + Let $M$ be the NFA that recognizes $A$. We know this must exist since $A$ is regular. + Create a copy of $M$ called $M_2$. Keep all accept states for both $M$ and $M_2$ but remove the start states for $M_2$. Right now, this NFA recognizes $A$ since it is the same as $M$ and there is no way to get to $M_2$ + For every possible transition in $M$, add a new transition of the opposite type ($1 => 0, 0 => 1$) that starts at the same state in $M$, but instead points to the corresponding destination $r$ in $M_2$ instead. This new compound NFA recognizes $N_1(A)$ What I have done is constructed a NFA that recognizes the original language, but allows the automata to jump to an alternate version when it makes a singular 'mistake'. This is the one Hamming difference that the new language allows. Because a Hamming distance of $0$ is also allowed, it is important that we keep the original accept states in $M$ as accept states in the new NFA as well as the accept states in $M_2$. = Problem 3 Suppose that $D$ is regular. Then since regular languages are closed under the complement as shown in $1.14$ where we swapped the accept and reject states, we know that the regular language of *palindromes* is also regular. Now let us apply the Pumping Lemma and show that $D$ cannot be regular through a proof by contradiction. #define(title: "Pumping Lemma")[ + Let $p$ be the pumping length. + Consider the palindrome $0^p 1 0^p$ + Since $|x y| <= p$ it must be the case that $y$ contains all $0$s + Pumping $y$ will result in a string that is not a palindrome, since the central $1$ will be surrounded by a greater number of $0$s on the left side. Therefore, it cannot be the case that the regular language of palindromes is regular. ] Because the regular language of palindromes is not regular, we have a contradiction. Therefore, $D$ cannot be regular. = Problem 4 == (a) The language that $"TUT"$ accepts can actually easily be represented by the regular expression $Sigma^*$. This occurs because $t, u in Sigma^*$, meaning that *any* string can be accepted by the language $"TUT"$ since we can set $t = epsilon$ and set $u$ to the entire string itself. Thus, since we can find a regular expression for the language, it must be the case that the language $"TUT"$ is regular. == (b) To show that the language $"TUTU"$ is not regular, use the Pumping Lemma. #example(title: "Pumping Lemma")[ + Let $p$ be the pumping length. + Consider the string $0^p 1^p 0^p 1^p$ + Since $|x y| <= p$ it must be the case that $y$ contains all $0$s. + In the language $"TUTU"$, the right half and left half of the string must be the same ($t u$). It is also true that the corresponding halves of each half must also be the same, but that is not essential to this proof. + Pumping $y$ will result in a string that is not in the language $"TUTU"$, since the right half will always contain more $1$s than the left half because the pumped $0$s will push the rightmost $1$s on the left half to the right half, or will cause an odd length which cannot be in the language. Therefore, it cannot be the case that the language $"TUTU"$ is regular. ] = Problem 5 Let us try and find a way to represent the language of strings that $A$ `avoids` $B$ creates. We still want the language to recognize strings that are based in the language $A$ with the restriction they don't contain any substrings of $B$. Represent the language of all strings with a substring of $B$ as $Sigma^* B Sigma^*$. Then the language of strings that avoid any substring of $B$ is $not (Sigma^* B Sigma^*)$ (using $not$ as the complement) which we know is regular since regular languages are closed under the complement. Then, the language of strings in $A$ that avoid any substring of $B$ can be represented by $A sect (not Sigma^* B Sigma ^*)$. We know that either side of this operation contains a regular language, and regular languages are closed under the intersection operation, thus it must be the case that regular languages are closed under the `avoids` operation. = Problem 6 Let us create a new DFA $C$ that has states labeled with a pair of states from $A$ and $B$. $C$ will have $k_1 k_2$ states at most, since each state is simple a labeled pair between the original DFAs. Allow there to be labels that are "null" to represent potential cases where you can reach a position from one DFA but not the other. The start state of $C$ is the pair of the start states of $A$ and $B$. Draw transitions between the correct labeled pair when moving from one state to another. What we are doing is similar to the process of creating a DFA from a NFA, where there is a set of states and we transition out of them at unison into another set - only this time the set is always of size two. To draw the transitions, start at the start state of $C$ and attempt every transition in for each character in the language. If neither of the original DFAs can transition from the current state to another with this character then ignore it. If both can transition out, then draw the transition between the two states in $C$. If only *one* can transition out, then transition to the state with one null label. Once done, continue from all "discovered" states in the same fashion. In this new graph, label all states that contain an accept state from $A$ *or* an accept state from $B$ as accept states. Because the two languages define in the original DFAs are not the same, there must be one accept state in $C$ that contains null for one of the two original DFAs. This represents the string that is accepted by one DFA but not the other. The length of this string must be less than or equal to the number of states in $C$, which is $k_1 k_2$ since otherwise we should be revisiting a state by the Pigeonhole principle. Thus, it must be the case that there exists a string that is accepted by one DFA but not the other with length $<=k_1 k_2$
https://github.com/EpicEricEE/typst-droplet
https://raw.githubusercontent.com/EpicEricEE/typst-droplet/master/tests/basic/test.typ
typst
MIT License
#import "/src/lib.typ": dropcap #set page(width: 6cm, height: auto, margin: 1em) // Test basic use of dropcap. #dropcap(lorem(20))
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CU/postna_triod/1_generated/Tyzden-01/7_Nedela.typ
typst
#import "../../../all.typ": * #columns(2, gutter: 2pt, [ == #translation.at("Ne") // --------------------------------------- // VECIEREN V NEDELU VECER // --------------------------------------- === #translation.at("V") #header3([(#translation.at("Ne_V"))]) ==== #translation.at("HOSPODI_VOZVACH") #generateTable(( // HV Stich na 6 sText("6:"), gText("И҆зведѝ и҆з̾ темни́цы дꙋ́шꙋ мою̀, и҆сповѣ́датисѧ и҆́мени твоемꙋ̀."), "", jObj4("",2, "Є҆гда̀ ѿ дре́ва", "Воздержа́нїемъ тѣ́ло смири́ти всѝ потщи́мсѧ, бж҃е́ственное преходѧ́ще по́прище непоро́чнагѡ поста̀ и҆ мл҃твами и҆ слеза́ми гдⷭ҇а сп҃са́ющаго на́съ взы́щемъ, и҆ забве́нїе ѕло́бы всеконе́чное сотвори́мъ, вопїю́ще: согрѣши́хомъ тѝ, сп҃сѝ, ꙗ҆́коже дре́вле нїнеѵі́тѧны хрⷭ҇тѐ цр҃ю̀, и҆ ѻ҆́бщники ны̀ сотворѝ нбⷭ҇нагѡ црⷭ҇твїѧ бл҃гоꙋтро́бне."), // HV Stich na 5 sText("5:"), gText("Менѐ ждꙋ́тъ пра́вєдницы, до́ндеже возда́си мнѣ̀."), "", jObj4("",none, "", "Себѐ ѿчаѧва́ю, помышлѧ́ѧ дѣ́ла моѧ̑ гдⷭ҇и, всѧ́кагѡ мꙋче́нїѧ достѡ́йнаѧ: се́ бо презрѣ́въ чⷭ҇тны̑ѧ твоѧ̑ сп҃се за́пѡвѣди, блꙋ́днѡ моѐ житїѐ и҆жди́хъ. тѣ́мже молю́сѧ, тꙋ́чами покаѧ́нїѧ мѧ̀ ѡ҆чи́стивъ, посто́мъ и҆ моле́нїемъ ꙗ҆́кѡ є҆ди́нъ млⷭ҇тивый просвѣтѝ, и҆ не гнꙋша́йсѧ менѐ бл҃годѣ́телю всѣ́хъ, и҆ пребл҃гі́й."), // HV Stich na 4 sText("4:"), gText("И҆з̾ глꙋбины̀ воззва́хъ къ тебѣ̀ гдⷭ҇и, гдⷭ҇и, ᲂу҆слы́ши гла́съ мо́й."), "", jObj4("",none, "Па́че ᲂу҆ма̀ дарѡ́въ", "По́стное вре́мѧ свѣ́тлѡ начне́мъ, къ подвигѡ́мъ дꙋхѡ́внымъ себѐ подложи́вше, ѡ҆чи́стимъ дꙋ́шꙋ, ѡ҆чи́стимъ пло́ть, пости́мсѧ ꙗ҆́коже въ снѣ́дехъ ѿ всѧ́кїѧ стра́сти, добродѣ́тельми наслажда́ющесѧ дх҃а: въ ни́хже соверша́ющесѧ любо́вїю, да сподо́бимсѧ всѝ ви́дѣти всечⷭ҇тнꙋ́ю стрⷭ҇ть хрⷭ҇та̀ бг҃а и҆ ст҃ꙋ́ю па́схꙋ, дꙋхо́внѡ ра́дꙋющесѧ."), // Note 1: after HV cText[$#sym.ast.circle$], cText([Та́же въ мине́и ст҃о́мꙋ, подо́бны г҃. А҆́ще ли и҆́мать самогла́сенъ: Сла́ва, а҆́ще ли нѣ́сть, Сла́ва, и҆ ны́нѣ, бг҃оро́диченъ, въ то́йже гла́съ мине́и.]), )) ==== #translation.at("PROKIMEN") #generateTable(( // Prokimen sText($#sym.dot$), jObj4("",8, "", "Не ѿвратѝ лица̀ твоегѡ̀ ѿ ѻ҆́трока твоегѡ̀, ꙗ҆́кѡ скорблю̀, ско́рѡ ᲂу҆слы́ши мѧ̀: вонмѝ дꙋшѝ мое́й, и҆ и҆зба́ви ю҆̀."), // Stich 0 sText([#translation.at("ST")#super("1")]), jObj4("",none, "", "Сп҃се́нїе твоѐ бж҃е да прїи́метъ мѧ̀."), // Stich 1 sText([#translation.at("ST")#super("2")]), jObj4("",none, "", "Да ᲂу҆́зрѧтъ ни́щїи, и҆ возвеселѧ́тсѧ."), // Stich 2 sText([#translation.at("ST")#super("3")]), jObj4("",none, "", "Взыщи́те бг҃а, и҆ жива̀ бꙋ́детъ дꙋша̀ ва́ша."), )) ==== #translation.at("STICHOVNI") #generateTable(( // S Stich na 1 sText("1:"), jObj4("",4, "", "Возсїѧ̀ бл҃года́ть твоѧ̀ гдⷭ҇и, возсїѧ̀ просвѣще́нїе дꙋ́шъ на́шихъ. сѐ вре́мѧ бл҃гопрїѧ́тное, сѐ вре́мѧ покаѧ́нїѧ, ѿложи́мъ дѣла̀ тьмы̀, и҆ ѡ҆блече́мсѧ во ѻ҆рꙋ̑жїѧ свѣ́та: ꙗ҆́кѡ да преплы́вше поста̀ вели́кꙋю пꙋчи́нꙋ, въ тридне́вное воскрⷭ҇нїе дости́гнемъ, гдⷭ҇а и҆ сп҃са на́шегѡ і҆и҃са хрⷭ҇та̀, сп҃са́ющагѡ дꙋ́шы на́шѧ."), "", gText(jObj4("",none, "", "Къ тебѣ̀ возведо́хъ ѻ҆́чи моѝ, живꙋ́щемꙋ на нб҃сѝ. сѐ ꙗ҆́кѡ ѻ҆́чи ра̑бъ въ рꙋкꙋ̀ госпо́дїй свои́хъ, ꙗ҆́кѡ ѻ҆́чи рабы́ни въ рꙋкꙋ̀ госпожѝ своеѧ̀: та́кѡ ѻ҆́чи на́ши ко гдⷭ҇ꙋ бг҃ꙋ на́шемꙋ, до́ндеже ᲂу҆ще́дритъ ны̀.")), // S Stich na 2 sText("2:"), jObj4("",none, "", "Возсїѧ̀ бл҃года́ть твоѧ̀ ..."), "", gText(jObj4("",none, "", "Поми́лꙋй на́съ, гдⷭ҇и, поми́лꙋй на́съ, ꙗ҆́кѡ по мно́гꙋ и҆спо́лнихомсѧ ᲂу҆ничиже́нїѧ: наипа́че напо́лнисѧ дꙋша̀ на́ша поноше́нїѧ гобзꙋ́ющихъ, и҆ ᲂу҆ничиже́нїѧ го́рдыхъ.")), // S Stich na 3 sText("3:"), jObj4("Мч҃нченъ",none, "", "Прославлѧ́емый въ па́мѧтехъ ст҃ы́хъ твои́хъ хрⷭ҇тѐ бж҃е, ѿ ни́хъ ᲂу҆молѧ́емь, низпослѝ на́мъ ве́лїю млⷭ҇ть."), // Note 1: after S cText[$#sym.ast.circle$], cText([Сла́ва, самогла́сенъ въ мине́и, а҆́ще и҆́мать: И҆ ны́нѣ, бг҃оро́диченъ по гла́сꙋ мине́и. А҆́ще ли не и҆́мать, Сла́ва, и҆ ны́нѣ, бг҃оро́диченъ.]), // S:I: col2(gText(translation.at("SI"))), "", jObj4("Бг҃оро́диченъ",4, "Ꙗ҆́кѡ до́блѧ", "А҆́гг҃льстїи чи́ни тѧ̀ бг҃ома́ти прославлѧ́ютъ: бг҃а бо всечⷭ҇таѧ родила̀ є҆сѝ, ѻ҆ц҃ꙋ̀, и҆ дх҃а соприсносꙋ́щна, и҆ а҆́гг҃льскаѧ вѡ́инства ѿ не сꙋ́щагѡ хотѣ́нїемъ поста́вивша. є҆го́же молѝ ѿ тлѝ сп҃стѝ и҆ просвѣти́ти дꙋ́шы правосла́вныхъ, тѧ̀ воспѣва́ющихъ всечⷭ҇таѧ."), )) #colbreak() ])
https://github.com/HKFoggyU/hkust-thesis-typst
https://raw.githubusercontent.com/HKFoggyU/hkust-thesis-typst/main/README.md
markdown
LaTeX Project Public License v1.3c
# HKUST Thesis Typst A [Typst](https://typst.app/) HKUST thesis template. In development!
https://github.com/dark-flames/resume
https://raw.githubusercontent.com/dark-flames/resume/main/data/open_source.typ
typst
MIT License
#import "../libs.typ": * #import "../chicv.typ": * #let openSourceList = ( ( name: "<NAME>", link: iconlink("https://github.com/aya-prover/aya-dev", icon: github, text: "aya-dev"), intro: "Practical implementation of a dependent type system", content:[ - Overhauled records to support dependent types. - Helped with some bugs and refactorings in primitive definitions. ] ), ) #let openSource(env) = { multiLang(env, en: [== OpenSource Contributions], cn: [== 开源贡献]) let c = openSourceList.map(i => { cventry( tl: [*#i.name*, #i.intro], tr: i.link, )[#i.content] }).join() [#c] }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/004%20-%20Dragon's%20Maze/006_Life%20in%20the%20Ring.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Life in the Ring", set_name: "Dragon's Maze", story_date: datetime(day: 08, month: 05, year: 2013), author: "<NAME>", doc ) Strips of flaming banners whipped violently around the Carnarium stage, threatening to catch the rafters ablaze. A half dozen goblin stagehands struggled for breath underneath a collapsed girder. There were screams of joy and pain as a cannon, which had become unmoored, tumbled into the crowd. All in all, it was one of the most successful performances of #emph[The Aria of Hilrod] seen since the Decamillenial. #figure(image("006_Life in the Ring/01.jpg", width: 100%), caption: [], supplement: none, numbering: none) Rinni brushed himself off, stood up on the center of the stage, and took a bow. He raised back up and lifted his hands in the air. He was joined by Ginoria, who took her bow and pointed toward Nikori, who lay unconscious in the rubble. Nikori always had a problem with dismounts. Ginoria and Rinni stepped off the stage, hand in hand, into the crowd, whose members had braved their way past the still-smoking cannon to meet the performers. Rinni reached down to his leg, running his palm across a freshly opened gash. He held his hand up to the crowd, gesturing in the traditional manner to indicate, #emph[This, I give for you] . "Ginoria," the fat Orzhov priest Silar said as he bowed to kiss her hand. "You are looking splendid. I never see you in the church anymore." #figure(image("006_Life in the Ring/02.jpg", width: 100%), caption: [], supplement: none, numbering: none) "Debts, like compliments, are best paid by the dead," Ginoria said, smiling as she pulled her hand away. Rinni continued, running his bloody fingers across the open palms of the crowd, gracing them with his gift, but stopped as he reached a young girl holding up a piece of parchment. "Who is this pup?" Rinni asked Silar. "Did you bring this one?" Rinni wagged his finger at Silar and made a clicking noise with his tongue. "Try and trick me into signing into your debt again?" "I'm no pup," the girl said, bringing down the piece of paper. "I wish to join the revue." Rinni laughed. "Ginoria, could we use this one? Hardly a morsel for an ogre. You think she could fit in a cannon?" He reached down and picked her up by her shirt. "Hmmm, maybe just for the kindling, eh?" The girl struggled, spinning in the air and bringing her foot nearly to Rinni's face. "Let me go old man," she said. "I tried to do you a favor. Your revue is trash. The Juri will take me and it will be your loss." "Juri would eat you alive," Rinni said. "Go home pup, before you get yourself hurt." He dropped the girl, who rolled backwards into a somersault, launched to a standing position, raised an arm to the sky, then spit in Rinni's face. The priest drew back his hand, but the girl bolted into the crowd, grabbed onto the scaffolding, and flung herself up into the rafters of the Carnarium and out of sight. "Unguilded filth. No respect," Silar said, removing a cloth from the folds of his robe to wipe off Rinni's face. "She could be found, you know." Rinni waved him off. "No, no," he said, taking the cloth and dabbing the spittle away. "She has the fire. It is pleasure to see it in one so young." Rinni handed the cloth back to Silar, who returned it to his robe—which would no doubt soon become part of his collection. Rinni thanked him and made his way backstage to his dressing room. There, he collapsed into the broad chair in front of the mirror. Wincing, he peeled off the heavy padded leather of his costume, dropping it to the ground piece by piece. Sweat and blood had shrunk it half a size. The heavy padding added weight, making the performance harder, but he needed it. Each year, it became harder to bounce back from the blows and falls. His bruised and swollen hands fumbled over the bottles on his desk—Simic-made tonics for vitality and strength and an Izzet potion that glowed an unnatural blue and let off a just barely audible hum. He finally found and opened a jar of balm, cultivated by the Selesnya, that would soon soothe the pain and minimize any scarring. #figure(image("006_Life in the Ring/03.jpg", width: 100%), caption: [], supplement: none, numbering: none) After applying a second layer, Rinni made his way to the bed in the corner of his dressing room. Outside, he could still hear the roar of the crowd at the next act, spike jesters of no small skill. In his younger days, he would've watched from the sidelines, but the performance had taken too much out of him. For tonight, there was only sleep. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The Carnarium from above was not a sight Rinni had seen in some time. He sought the girl who had so succinctly put him in his place two nights before. He found her in the scaffolding near the Carnarium's roof, a height he himself had struggled to climb. Her feet were dangling over the ledge, and she was watching the great Minyuli perform. The act modeled itself after the simple parlor tricks of the street magicians who performed near New Prahv. Minyuli's goblin assistant bound him and tortured him, and Minyuli reveled in the pain to better concentrate his magic—a technique he billed as the Projection of Pain—and send a fireball at the goblin just as it thought it had finally outsmarted the mage. #figure(image("006_Life in the Ring/04.jpg", width: 100%), caption: [], supplement: none, numbering: none) The goblin, already wearing some bandages to cover up yet-to-heal burns, had tied and bound Minyuli to an inverted table, stuck pins in his feet and sides, and set up an elaborate pulley system to stretch him on a rack from halfway across the stage. To add to this, the goblin hunkered down in a barrel full of water to dodge the sure-to-follow fireball. As the goblin turned the crank to the fifth position, steam began to come up from the barrel. The goblin quickly jumped out of the barrel, whose contents had begun to boil over, and ran manically around the stage trying to shake itself dry from the boiling contents. When it ran face-first into a support beam, the girl let out a snort. "People without tickets get thrown to the hounds, you know," Rinni said. The girl looked back to see him, then turned forward and eyed the ground below. "Far enough to hurt, not far enough to kill," Rinni said. "But sit, stay, Little Pup. I did not come here to harm you." "You want to tell me to go home again?" she said, turning back to watch the stage. "You don't think I can handle myself in your circus?" "Oh no, of course you can," Rini said, slowly lowering himself onto the ledge. "I think Silar was perhaps lucky you chose flight instead of fight. Maybe even you would be of use in the ring someday. I just wonder if it is for the Rakdos or not. But it is very rude of me." He extended his hand. "I am Rinni." "I know who you are," the girl said. "I don't like to presume," he said. "Ten years ago, yes, Azorius arbiters themselves would tip me their hats, but fame hardly keeps to one like a cloak." Rinni paused for a second. "This is the part where you introduce yourself." "Lunicia," she said. "Lunicia the Tremendous. At least someday." "I was your age when I saw my first revue," Rinni said. "Younger, perhaps. #emph[Dance of the Nine Chains] ." Rinni chuckled. "The fulcrumist was incompetent. The first two pairs that came his way he launched directly into the crowd. They ate it up, of course—carnage is carnage—but the ringleader was none-too-pleased. The next pair came with razor wire instead of a chain. You should've seen the look on his face." Rinni made a face of exaggerated shock, holding his hands up to his face, fingers bent back to imitate stumps. "That's not funny," Lunicia said. "That was a person." "Oh, don't worry," Rinni said, "they put two or three of them back. He went on to have a fine career as a chainwalker. Short, true, but fine." #figure(image("006_Life in the Ring/05.jpg", width: 100%), caption: [], supplement: none, numbering: none) On the stage, a dancer swung between a series of poles and chains using two hooks, one mounted on each hand. She held her body rigid and straight, and gained momentum spinning around one pole only to release herself into the air, arc upwards, grab onto one chain and swing it to a separate pole, then instantaneously reversed direction and flung herself across the room in another direction. "I don't understand sometimes how you all can accomplish such acts of beauty in one breath," Lunicia said, "and such brutality in the next." "Funny thing about the Centralum," Rinni said. "The dancer takes years to prepare. The hooks are not fastened to her wrists, they are implanted. Each change in direction brings complete pain to the dancer." Lunicia ran her hands over her wrists. "That's horrible," she said. "There is no other way for her body to support the stress," he said. "It is an ugly thing to do, but a beautiful thing to behold." "I'm beginning to feel I'm safer without a guild," she said. "Ah, safe, yes. You want to be a safe acrobat? Perform in the streets. To be a Rakdos is more." The girl turned back to the stage. "So I can grow old like you?" she asked. "To perform until my body stops working?" "Rakdos performers do not grow old in the ring," Rinni said. "They go on exactly as long as they are meant to. They acquire skills. They acquire scars. Their movements may be hampered, they may slow down, but it is all part of the dance. They play the role they were meant to play. To make people laugh. To remind them how precious and how fleeting our lives are, no matter how harsh or short. Our lives are a gift." "You speak as if he is a god," Lunicia said. "Where is the glory in that?" "Our lives are fleeting but his is not," Rinni said. "The people need the entertainment, yes, but do not underestimate the Demon. The nine Paruns gave the Demon a guild to entertain him—to satiate his bloodlust. Only the Firemind remains who knows what the Demon is truly capable of. We Rakdos, we perform—we live and we die—to appease him, so that the Demon can return peacefully to his slumber." #figure(image("006_Life in the Ring/06.jpg", width: 100%), caption: [], supplement: none, numbering: none) He signed and dated the paper. "You watch the show tonight. If you never come back again, I could not blame you. You keep this paper to remember why. But I think maybe it intrigues you. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The performance began with Nikori on the high chains, walking with two torches in his hands. As he reached the center of the chain, he began to juggle the two torches, tossing them from one hand to the other. Rinni entered the stage with two torches of his own, which he juggled back and forth with Nikori, high above him. Just as it seemed as if neither could sustain the loop any longer, Ginoria entered the stage with two more torches, which she tossed one at a time to Rinni, who added them to the rotation. The torches moved faster and faster, until Rinni's hands erupted in fire. The torches fell to the ground as the flame in Rinni's hands grew, but not out of control. It flowed off of his hands like smoke off a thurible. Molding the fire into a sphere in his left hand, he played it with his right, encouraging jets to emerge like spires on the ball. Ginoria took a swig from a bottle, and black liquid oozed out of her fingertips, taking the shape of sticky tendrils winding across the stage. Rinni and Ginoria locked arms with each other and begun to spin impossibly fast around the stage. The ichor fanned out like spinning blades circling over the crowd's head until the flames caught it, lighting it ablaze and creating ribbons of fire that danced through the air. The scent in the air was one of burning sulfur. As quickly as it began, the flames from Rinni's hands and ichor from Ginoria's puttered out, and the two fell to the floor. The crowd hooted and hollered. Slowly making his way to his feet, Rinni took a bow, and then pointed to Ginoria and Nikori, who each took their bow in turn. Mustering what little strength he had left, Rinni raised himself up again for the final act. Every performance in his entire life was leading up to this one. This was his one unforgettable act, the one that nobody who was anybody would admit to have missed. This was the showstopper. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("006_Life in the Ring/07.jpg", width: 100%), caption: [], supplement: none, numbering: none) The low and rumbling chuckle of the Demon could be heard throughout the hall, which triggered the audience to erupt into throes of elation. It was a sound unlike anything Lunicia had heard before. The way it shook the hall was both terrifying and oddly comforting. Lunicia watched as spectators young and old wrestled for souvenirs of the event—something to remember it by, something to prove that they were there in the flesh when it happened. Within a week, a dozen other performers in other circuses would imitate the act—but these spectators knew they were there for the first run. Lunicia was filled with a sense of grief, but also excitement. She understood what Rinni had told her now. Making her way backstage amid the chaos, she sought out Rinni's dressing room to try and get a clue how he did it. There, she saw the balms, the salves, and the mostly empty but still somehow electric bottle with the prominent Izzet signet. It was then she knew that no matter how skilled she could become, her acrobatics would never be enough alone—she would need to acquire allies in other guilds. Lunicia grabbed what she could from Rinni's dressing room. She would go to the fat priest, Silar. Certainly he would buy her autograph of Rinni and some of these knick knacks. She would have coin in her pocket and a contact in the church. Allies who could supply her with the means to top not only Rinni, but every performer in every circus in Rakdos. It might take years, but she would bring the Demon to his feet—not to chuckle, but to hear him roar with pleasure. The cost was no object.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/metro/0.1.0/src/utils.typ
typst
Apache License 2.0
// Joins two dictionaries together by inserting `new` values into `old`. // When only-update is true, values will only be inserted if they keys exist in old. #let combine-dict(new, old, only-update: false) = { for (k, v) in new { if not only-update or k in old { old.insert(k, v) } } return old }
https://github.com/BeiyanYunyi/resume
https://raw.githubusercontent.com/BeiyanYunyi/resume/main/modules_zh/certificates.typ
typst
#import "../brilliant-CV/template.typ": * #cvSection("证书") #cvHonor( date: [2021], title: [英语六级], issuer: [中华人民共和国教育部], ) #cvHonor( date: [2021], title: [计算机二级], issuer: [中华人民共和国教育部], ) #cvHonor( date: [2020], title: [英语四级], issuer: [中华人民共和国教育部], )
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/design/design_iteration_2_decisions_sum_type_destruction.typ
typst
= Sum Type Destruction <sum-type-destruction-decision> #let load-drawio-svg(path, ..args) = image.decode(read(path).replace("Text is not SVG - cannot display", ""), ..args) Sum types consist of a set of constructors, each with a different type. The type of a sum type is the union of the types of its constructors. To work with a value of a sum type, it must be possible to destruct the value into its constructor and arguments. Since while developing one usually cannot know which constructor was used to create a value, all possible constructors must be handled. A common approach in functional languages is to use _pattern matching_. Pattern matching allows to match values against a set of patterns and execute user-provided code per pattern. Each code path needs to have the same return type, which will then be used as the type of the matching expression. One of the pattern types usually destructs sum type constructors. An example of pattern-matching in Haskell can be seen in @pattern-matching-example-haskell, which defines a sum type named `Expression` with two constructors, `Value` and `Addition`, and a function `calc` that pattern matches a value of type `Expression` against its constructors. #figure( ```hs data Expression where Value :: Int -> Expression Addition :: Expression -> Expression -> Expression calc :: Expression -> Int calc e = case e of Value v -> v Addition left right -> calc left + calc right ```, caption: "Example of pattern-matching in Haskell" )<pattern-matching-example-haskell> An easier way to implement sum type destruction is to generate a function that takes a function parameter per constructor of the sum type. These parameter functions take the type constructor arguments as input parameters and map them to a common output type. These kinds of functions are called destruction functions. @destruction-function-example-haskell shows what such a destruction function would look like for the abovementioned example. #figure( ```hs data Expression where Value :: Int -> Expression Addition :: Expression -> Expression -> Expression destruct :: Expression -> (Int -> b) -> (Expression -> Expression -> b) -> b destruct = -- implementation omitted calc :: Expression -> Int calc e = destruct e (\x -> x) (\l r -> calc l + calc r) ```, caption: "Example of a destruction function in Haskell" )<destruction-function-example-haskell> Unfortunately, such a destruction function is not as powerful as pattern-matching in a few ways: - It is not possible to specify multiple overlapping patterns, which are matched against in order of definition. - It is not possible to combine patterns into more complex patterns. - It is not possible to specify a default case. This list is not exhaustive, but it already shows how the lack of pattern-matching would make the import of Haskell code into VisualFP more difficult. How pattern-matching and destruction functions would look in VisualFP can be seen in @pattern-matching-example-visualfp and @destruction-function-example-visualfp. #figure( load-drawio-svg("../../static/design_specification_destruction.svg", width: 100%), caption: [Example of a destruction function in VisualFP])<pattern-matching-example-visualfp> #figure( load-drawio-svg("../../static/design_specification_pattern-matching.svg", width: 80%), caption: [Example of pattern-matching in VisualFP])<destruction-function-example-visualfp> The decision was made in favor of the destruction function since the pattern-matching approach does not translate as well into an exclusively visual language. The fact that it makes the import of Haskell code more difficult is unfortunate but acceptable since the primary goal of VisualFP is to be a visual language to introduce beginners to functional programming.
https://github.com/jamesrswift/typst-chem-par
https://raw.githubusercontent.com/jamesrswift/typst-chem-par/main/tests/state/test.typ
typst
MIT License
#import "/src/lib.typ": * #set page(width: 30em, height: auto) #show: chem-style The oxidation of n-butanol with K2Cr2O7 requires acidification with H2SO4 to yield butanoic acid. N,N-chemicolium. #line(length:100%,stroke: 0.55pt) #chem-toggle(false) The oxidation of n-butanol with K2Cr2O7 requires acidification with H2SO4 to yield butanoic acid. #line(length:100%,stroke: 0.55pt) #chem-toggle(true) The oxidation of n-butanol with K2Cr2O7 requires acidification with H2SO4 to yield butanoic acid.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/CATEGORIES.md
markdown
Apache License 2.0
# Typst Package Categories Categories help users explore packages, make finding the right one easier, and provide package authors with a reference for best-practices in similar packages. In addition to categories, packages can also specify a list of [disciplines] describing their target audience. Each package can declare itself a part of up to three categories. There are two kinds of package categories: Functional categories that describe what a package does on a technical level and publication categories that describe for which kind of deliverable a package may be used. Package authors are not required to pick a category from each of the two groups. Instead, they can omit one group completely if it is not applicable to their package, or use two categories for another group. Publication categories, for example, are of big relevance to template packages and less so to a general utility package that may apply to most publication kinds. ## Functional Categories - **`components`:** Building blocks for documents. This includes boxes, layout elements, marginals, icon packs, color palettes, and more. - **`visualization`:** Packages producing compelling visual representations of data, information, and models. - **`model`:** Tools for managing semantic information and references. Examples could be glossaries and bibliographic tools. - **`layout`:** Primitives and helpers to achieve advanced layouts and set up a page with headers, margins, and multiple content flows. - **`text`:** Packages that transform text and strings or are focused on fonts. - **`languages`:** Tools for localization and internationalization as well as dealing with different scripts and languages in the same document. - **`scripting`:** Packages/libraries focused on the programmatic aspect of Typst, useful for automating documents. - **`integration`:** Integrations with third-party tools and formats. In particular, this includes packages that embed a third-party binary as a plugin. - **`utility`:** Auxiliary packages/tools, for example for creating compatibility and authoring packages. - **`fun`:** Unique uses of Typst that are not necessarily practical, but always entertaining. ## Publication Categories - **`book`:** Long-form fiction and non-fiction books with multiple chapters. - **`report`:** A multipage informational or investigative document focused on a single topic. This category contains templates for tech reports, homework, proposals and more. - **`paper`:** A scientific treatment on a research question. Usually published in a journal or conference proceedings. - **`thesis`:** A final long-form deliverable concluding an academic degree. - **`poster`:** A large-scale graphics-heavy presentation of a topic. A poster is intended to give its reader a first overview over a topic at a glance. - **`flyer`:** Graphics-heavy, small leaflets intended for massive circulation and to inform or convince. - **`presentation`:** Slides for a projected, oral presentation. - **`cv`:** A résumé or curriculum vitæ presenting the author's professional achievements in a compelling manner. - **`office`:** Staples for the day-to-day in an office, such as a letter or an invoice. [disciplines]: https://github.com/typst/packages/blob/main/DISCIPLINES.md
https://github.com/TheHarrisButler/my-resume
https://raw.githubusercontent.com/TheHarrisButler/my-resume/main/resume/package.typ
typst
#let default-theme = ( margin: 22pt, font: "Roboto", font-size: 11pt, accent-color: black, body-color: rgb("222"), main-width: 5fr, main-gutter-width: 64pt, aside-width: 3fr, aside-gutter-width: 48pt, footer-width: 8fr, footer-gutter-width: 48pt, ) #let cv( title: "", subtitle: "", theme: (), aside: [], main: [], footer, ) = { // Function to pick a key from the theme, or a default if not provided. let th(key, default: none) = { return if key in theme and theme.at(key) != none { theme.at(key) } else if default != none and default in theme and theme.at(default) != none { theme.at(default) } else if default != none { default-theme.at(default) } else { default-theme.at(key) } } set page( margin: ( top: th("margin"), bottom: th("margin"), left: th("margin"), right: th("margin"), ), ) // Fix for https://github.com/typst/typst/discussions/2919 show heading.where(level: 1): set text(size: th("font-size")) show heading.where(level: 2): set text(size: th("font-size")) set text(font: th("font")) set text(size: th("font-size")) set par(linebreaks: "simple", leading: 0.4em) set block(above: 7pt, spacing: 10pt) { show heading.where(level: 1): set text(size: 2.3em) show heading.where(level: 2): set text(size: 1.1em, weight: "regular") show heading.where(level: 1): set text(fill: th("header-accent-color", default: "accent-color")) show heading.where(level: 2): set text(fill: th("header-body-color", default: "body-color").lighten(30%)) stack( spacing: 5pt, heading(level: 1, title), heading(level: 2, subtitle) ) } grid( columns: (th("main-width"), th("margin"), th("aside-width")), { set grid(columns: (th("main-gutter-width"), 1fr)) show heading.where(level: 1): set text(fill: th("main-accent-color", default: "accent-color").lighten(30%)) show heading.where(level: 2): set text(fill: th("main-body-color", default: "body-color")) set text(fill: th("main-body-color", default: "body-color").lighten(40%)) set rect(fill: th("main-accent-color", default: "accent-color")) main }, {}, { set grid(columns: (th("aside-gutter-width"), 1fr)) show heading.where(level: 1): set text(fill: th("aside-accent-color", default: "accent-color").lighten(30%)) show heading.where(level: 2): set text(fill: th("aside-body-color", default: "body-color")) set text(fill: th("aside-body-color", default: "body-color").lighten(40%)) set rect(fill: th("aside-accent-color", default: "accent-color")) aside }, ) grid( columns: (th("footer-width")), { set grid(columns: (th("footer-gutter-width"), 1fr)) show heading.where(level: 1): set text(fill: th("main-accent-color", default: "accent-color").lighten(30%)) show heading.where(level: 2): set text(fill: th("main-body-color", default: "body-color")) set text(fill: th("main-body-color", default: "body-color").lighten(40%)) set rect(fill: th("main-accent-color", default: "accent-color")) footer } ) } #let section( theme: (), title, body, ) = { set grid(columns: (theme.gutter-size, 1fr)) if "gutter-size" in theme show heading.where(level: 1): set text(fill: theme.accent-color) if "accent-color" in theme show heading.where(level: 2): set text(fill: theme.body-color) if "body-color" in theme set rect(fill: theme.accent-color.darken(40%)) if "accent-color" in theme set text(fill: theme.body-color) if "body-color" in theme v(6pt) heading(level: 1, title) rect(height: 2pt, width: 100%,) body } #let entry( theme: (), right: none, gutter, title, body, ) = { set grid(columns: (theme.gutter-size, 1fr)) if "gutter-size" in theme show heading.where(level: 2): set text(fill: theme.body-color) if "body-color" in theme set text(fill: theme.body-color) if "body-color" in theme grid( { set text(tracking: -0.5pt, style: "italic") context { set text(fill: text.fill.lighten(40%)) gutter } }, { let hasTitle = title != none let hasRight = right != none if hasTitle or hasRight { grid( columns: (1fr, auto), { heading( level: 2, context { set text(fill: text.fill.darken(40%)) title } ) }, context { set text(fill: text.fill.darken(40%)) right }, ) } if body != none { set block(below: 4pt) body } } ) }
https://github.com/sabitov-kirill/comp-arch-conspect
https://raw.githubusercontent.com/sabitov-kirill/comp-arch-conspect/master/commons.typ
typst
#let imagebox(imageName, label: none, width: none, height: none, alignMode: center) = { let size = (:) if width != none { size.insert("width", width) } if height != none { size.insert("height", height) } set text(size: 0.8em) align(alignMode)[ #stack[ #image("images/" + imageName, ..size)\ #emph(label) ] ] }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/deco_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #let redact = strike.with(stroke: 10pt, extent: 0.05em) #let highlight-custom = strike.with(stroke: 10pt + rgb("abcdef88"), extent: 0.05em) // Abuse thickness and transparency for redacting and highlighting stuff. Sometimes, we work #redact[in secret]. There might be #highlight-custom[redacted] things.
https://github.com/maucejo/presentation_touying
https://raw.githubusercontent.com/maucejo/presentation_touying/main/template/main.typ
typst
MIT License
#import "../src/presentation-template.typ": * #let colors = ( red: rgb("#c1002a") ) #let title = [Title #v(-0.5em) #line(length: 15%, stroke: 0.075em + colors.red) #v(-0.5em) #text(size: 0.8em, [Subtitle]) ] #let labo = [Laboratory ] #let authors = [#text(fill: colors.red, [Author A]) #h(1em) Author B] #show: presentation-theme.with( navigation: "mini-slides", config-info( title: title, short-title: [Short title], author: authors, institution: labo, // logo: (image("../src/resources/assets/logo_cnam_lmssc.png"), image("../src/resources/assets/logo_cnam_lmssc.png")), // logo: image("../src/resources/assets/logo_cnam_lmssc.png"), ), ) #title-slide #content-slide = First section == Slide title #emphbox[ $ bold(z)_(k + 1) = bold(A) bold(z)_k + bold(B) bold(u)_k + bold(w)_k \ bold(y)_k = bold(C) bold(z)_k + bold(v)_k $ ] - #lorem(20) = Second section == Slide title #info[#lorem(10)] #tip[#lorem(10)] #important[#lorem(10)] #question[#lorem(10)] = Third section == Code #lorem(10) #code(lang:"Julia")[ ```julia # A comment function squared(x) return x^2 end ``` ] #subtitle("A slide with a list") #focus-slide[ Thank you for your attention Questions ? ] #show: appendix = Appendices <touying:hidden> == A first appendix == A second appendix
https://github.com/falkaer/resume
https://raw.githubusercontent.com/falkaer/resume/main/README.md
markdown
MIT License
# My resume My personal resume, written with Typst.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-2100.typ
typst
Apache License 2.0
#let data = ( ("ACCOUNT OF", "So", 0), ("ADDRESSED TO THE SUBJECT", "So", 0), ("DOUBLE-STRUCK CAPITAL C", "Lu", 0), ("DEGREE CELSIUS", "So", 0), ("CENTRE LINE SYMBOL", "So", 0), ("CARE OF", "So", 0), ("CADA UNA", "So", 0), ("EULER CONSTANT", "Lu", 0), ("SCRUPLE", "So", 0), ("DEGREE FAHRENHEIT", "So", 0), ("SCRIPT SMALL G", "Ll", 0), ("SCRIPT CAPITAL H", "Lu", 0), ("BLACK-LETTER CAPITAL H", "Lu", 0), ("DOUBLE-STRUCK CAPITAL H", "Lu", 0), ("PLANCK CONSTANT", "Ll", 0), ("PLANCK CONSTANT OVER TWO PI", "Ll", 0), ("SCRIPT CAPITAL I", "Lu", 0), ("BLACK-LETTER CAPITAL I", "Lu", 0), ("SCRIPT CAPITAL L", "Lu", 0), ("SCRIPT SMALL L", "Ll", 0), ("L B BAR SYMBOL", "So", 0), ("DOUBLE-STRUCK CAPITAL N", "Lu", 0), ("NUMERO SIGN", "So", 0), ("SOUND RECORDING COPYRIGHT", "So", 0), ("SCRIPT CAPITAL P", "Sm", 0), ("DOUBLE-STRUCK CAPITAL P", "Lu", 0), ("DOUBLE-STRUCK CAPITAL Q", "Lu", 0), ("SCRIPT CAPITAL R", "Lu", 0), ("BLACK-LETTER CAPITAL R", "Lu", 0), ("DOUBLE-STRUCK CAPITAL R", "Lu", 0), ("PRESCRIPTION TAKE", "So", 0), ("RESPONSE", "So", 0), ("SERVICE MARK", "So", 0), ("TELEPHONE SIGN", "So", 0), ("TRADE MARK SIGN", "So", 0), ("VERSICLE", "So", 0), ("DOUBLE-STRUCK CAPITAL Z", "Lu", 0), ("OUNCE SIGN", "So", 0), ("OHM SIGN", "Lu", 0), ("INVERTED OHM SIGN", "So", 0), ("BLACK-LETTER CAPITAL Z", "Lu", 0), ("TURNED GREEK SMALL LETTER IOTA", "So", 0), ("KELVIN SIGN", "Lu", 0), ("ANGSTROM SIGN", "Lu", 0), ("SCRIPT CAPITAL B", "Lu", 0), ("BLACK-LETTER CAPITAL C", "Lu", 0), ("ESTIMATED SYMBOL", "So", 0), ("SCRIPT SMALL E", "Ll", 0), ("SCRIPT CAPITAL E", "Lu", 0), ("SCRIPT CAPITAL F", "Lu", 0), ("TURNED CAPITAL F", "Lu", 0), ("SCRIPT CAPITAL M", "Lu", 0), ("SCRIPT SMALL O", "Ll", 0), ("ALEF SYMBOL", "Lo", 0), ("BET SYMBOL", "Lo", 0), ("GIMEL SYMBOL", "Lo", 0), ("DALET SYMBOL", "Lo", 0), ("INFORMATION SOURCE", "Ll", 0), ("ROTATED CAPITAL Q", "So", 0), ("FACSIMILE SIGN", "So", 0), ("DOUBLE-STRUCK SMALL PI", "Ll", 0), ("DOUBLE-STRUCK SMALL GAMMA", "Ll", 0), ("DOUBLE-STRUCK CAPITAL GAMMA", "Lu", 0), ("DOUBLE-STRUCK CAPITAL PI", "Lu", 0), ("DOUBLE-STRUCK N-ARY SUMMATION", "Sm", 0), ("TURNED SANS-SERIF CAPITAL G", "Sm", 0), ("TURNED SANS-SERIF CAPITAL L", "Sm", 0), ("REVERSED SANS-SERIF CAPITAL L", "Sm", 0), ("TURNED SANS-SERIF CAPITAL Y", "Sm", 0), ("DOUBLE-STRUCK ITALIC CAPITAL D", "Lu", 0), ("DOUBLE-STRUCK ITALIC SMALL D", "Ll", 0), ("DOUBLE-STRUCK ITALIC SMALL E", "Ll", 0), ("DOUBLE-STRUCK ITALIC SMALL I", "Ll", 0), ("DOUBLE-STRUCK ITALIC SMALL J", "Ll", 0), ("PROPERTY LINE", "So", 0), ("TURNED AMPERSAND", "Sm", 0), ("PER SIGN", "So", 0), ("AKTIESELSKAB", "So", 0), ("TURNED SMALL F", "Ll", 0), ("SYMBOL FOR SAMARITAN SOURCE", "So", 0), )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/packages/typst.solid/demo/README.md
markdown
Apache License 2.0
# demo ## Usage in `typst.solid` directory: ``` pnpm i npx vite build ``` in this directory: ``` pnpm i pnpm dev ``` This may take a while for loading page since it downloading pre-compiled demo file from <https://myriad-dreamin.github.io/typst.ts/docs/readme.artifact.sir.in>.
https://github.com/lucifer1004/typst-poetry
https://raw.githubusercontent.com/lucifer1004/typst-poetry/main/poetry.typ
typst
#let poem( title: none, author: none, date: none, update: none, meta: ( date: ( prefix: "", suffix: "written", ), update: ( prefix: "", suffix: "modified", ), ), linenumber: (left: "1:1", right: none, current: false), ..parts ) = { set align(center) set par(justify: true, leading: 1em) heading(level: 1, title) v(1em) emph(author) v(1em) let linenumbering(lineidx, currentlineidx, pos) = { if type(linenumber) == "dictionary" and linenumber.at(pos) != none { let number = if linenumber.current { numbering(linenumber.at(pos), lineidx, currentlineidx) } else { numbering(linenumber.at(pos), lineidx) } if pos == "left" { align(right, number) } else { number } } } let partcnt = parts.pos().len() let contents = () for (partidx, body) in parts.pos().enumerate() { let currentline = () let parttitle = none if body.has("children") { for item in body.children { if "heading(body:" in repr(item) { parttitle = item.body break } } } if partcnt > 1 or parttitle != none { contents.push(none) contents.push({ if partidx > 0 { v(2em) } align(center, heading(level: 2)[ #if partcnt > 1 { numbering("I", partidx + 1) } #parttitle ]) }) contents.push(none) } if not body.has("children") { continue } let lineidx = 1 let currentlineidx = 1 let stanzaidx = 1 for item in body.children { if repr(item) == "[ ]" { continue } else if repr(item) != "linebreak()" and repr(item) != "parbreak()" and "heading(body:" not in repr(item) { currentline.push(item) } if repr(item) == "linebreak()" or repr(item) == "parbreak()" { if currentline.join() != none { contents.push(linenumbering(lineidx, currentlineidx, "left")) contents.push(currentline.join()) contents.push(linenumbering(lineidx, currentlineidx, "right")) } } if repr(item) == "linebreak()" { if currentline.join() != none { lineidx += 1 currentlineidx += 1 } currentline = () } if repr(item) == "parbreak()" { if currentline.join() != none { lineidx += 1 } currentlineidx = 1 stanzaidx += 1 currentline = () contents.push(none) contents.push(none) contents.push(none) } } if currentline.join() != none { contents.push(linenumbering(lineidx, currentlineidx, "left")) contents.push(currentline.join()) contents.push(linenumbering(lineidx, currentlineidx, "right")) } } grid( columns: (1fr, auto, 1fr), none, { set align(left) grid( columns: (auto, auto, auto), gutter: 1em, ..contents, ) }, none, ) if date != none { align(right, [ #meta.date.prefix #date #meta.date.suffix ]) if update != none { align(right, [ #meta.update.prefix #update #meta.update.suffix ]) } } }
https://github.com/Nerixyz/icu-typ
https://raw.githubusercontent.com/Nerixyz/icu-typ/main/docs/docs/locale-info.md
markdown
MIT License
# `locale-info` ```typst-code let locale-info(locale) ``` Gets information about ICU4X' understanding of the `locale`. ## Arguments ### `locale` The [Unicode Locale Identifier] to parse. ## Structure A [Unicode Locale Identifier] starts with a [Unicode **Language** Identifier](https://unicode.org/reports/tr35/tr35.html#unicode-language-identifier) and is optionally followed by extensions. Most of the time the language identifier is sufficient to get the desired output. The language identifier starts with a [language subtag] with an optional [script subtag] _or_ just a [script subtag]. Afterwards, the [region subtag] and [variant subtag] can be specified. In this library, only some of the [Unicode extensions](https://unicode.org/reports/tr35/tr35.html#Key_And_Type_Definitions_) (`-u-` extensions) are important. - `ca` can be used to specify the calendar for dates and datetimes ([calendar.xml](https://github.com/unicode-org/cldr/blob/main/common/bcp47/calendar.xml)) - `hc` can be used to specify the hour cycle for time formatters ([reference](https://unicode.org/reports/tr35/tr35.html#UnicodeHourCycleIdentifier)) ### Example The locale `zh-Hans-CN` specifies the [language subtag] as `zn` (Chinese), the [script subtag] as `Hans` (simplified Han), and the [region subtag] as `CN` (China). You can test your identifiers on [util.unicode.org/UnicodeJsps/languageid.jsp](https://util.unicode.org/UnicodeJsps/languageid.jsp?l=en). ## Examples ### Language Identifier Chinese, tranditional Han, Hong Kong ```typst +preview #locale-info("zh-Hant-HK") ``` ### Default Language The default "undefined" language. ```typst +preview #locale-info("und") ``` ### Full Unicode Locale Identifier A [Unicode Locale Identifier] specifying all extensions. ```typst +preview(vertical) #let language-id = "en-arab-DE-posix-macos" #let unicode-ext = "-u-foo-bar-hc-h12-ca-buddhist" #let transform-ext = "-t-en-latn-US-windows-rusty-h0-hybrid" #let private-ext = "-a-other-ext" #let other-ext = "-x-typst-wasm" #locale-info( language-id + unicode-ext + transform-ext + private-ext + other-ext ) ``` [Unicode Locale Identifier]: https://unicode.org/reports/tr35/tr35.html#Unicode_locale_identifier [language subtag]: https://unicode.org/reports/tr35/tr35.html#unicode_language_subtag_validity [script subtag]: https://unicode.org/reports/tr35/tr35.html#unicode_script_subtag_validity [region subtag]: https://unicode.org/reports/tr35/tr35.html#unicode_region_subtag_validity [variant subtag]: https://unicode.org/reports/tr35/tr35.html#unicode_variant_subtag_validity
https://github.com/ysthakur/PHYS121-Notes
https://raw.githubusercontent.com/ysthakur/PHYS121-Notes/main/Notes/Ch10.typ
typst
MIT License
#import "@preview/gentle-clues:0.3.0": important, note = Chapter 10: Energy and Work == The Basic Energy Model Every system has a total energy $E$ === Energy Transfers and Work Energy can be transferred between a system and its environment through work and heat / Work: Mechanical transfer of energy to or from a system by pushing or pulling on it / Heat: Nonmechanical transfer of energy between system and environment due to temperature difference between the two Work is change in total energy: $ W = Delta E $ Work is positive when energy transferred into system and negative when energy transferred out of system / Isolated system: No energy transferred into or out of system === Law of Conservation of Energy The total energy of an isolated system remains constant == Work Work is done on a system by *external forces* $ W = F d $ Work is a *scalar* even though force and displacement are vectors Units of work are $J$ (joules), same as energy A force does no work on an object if the object undergoes no displacement (or the force is perpendicular to the displacement) === Kinetic Energy / Translational kinetic energy: Energy of motion in a line $ K = 1/2 m v^2 $ / Rotational kinetic energy: Way of expressing sum of kinetic energy of all parts of a rotating object. Moment of inertia takes place of mass and angular velocity takes place of linear velocity. $ K_"rot" = 1/2 I omega^2 $ == Potential Energy / Conservative forces: Forces that can store useful energy, e.g. gravity, elastic forces / Nonconservative forces: Forces that can't store useful energy, e.g. friction === Gravitational Potential Energy $ U_upright(g) = m g h $ Only the height ($h$) matters, not the path the object took to get there === Elastic Potential Energy $ U_upright(s) = 1/2 k x^2 $ == Conservation of Energy In an isolated system, $W = 0$ Carefully choose an isolated system to solve problems in == Energy Diagrams *Energy diagrams* graph potential energy as a function of position - Free fall energy diagrams are linear graphs of gravitational potential energy - A spring's energy diagram is a parabola showing spring potential energy #align(center)[ #image("/Images/10-Energy-Diagrams.png", width: 45%) ] - The distance from the axis to the PE line is the potential energy - The distance from the PE line to the energy line E is the kinetic energy - The object cannot be at a position where the PE curve is above the E line (because E is total energy) - A position where the E line crosses the PE curve is a turning point where the object reverses direction - If the E line crosses the PE curve at two positions, the object will oscillate between those two positions - Speed will be at a maximum where the PE curve is a minimum (because that's where KE is at a maximum) == Power / Power: Rate at which energy is transformed or transferred (scalar), measured in watts (W) $ P = (Delta E) / (Delta t) = W / (Delta t) $ / Output power: A force doing work transfers energy, and the rate at which the force transfers energy is called output power $ P = F v $ where $P$ is $F$'s output power, and $v$ is the velocity of the object that $F$ is acting on
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/grid/extra-arg.typ
typst
Apache License 2.0
#grid( columns: 2, )[ abc ][ def ] #table( columns: (auto, 1fr, auto), gutter: 3pt, [Name], [Age], [Strength], [Hannes], [36], [Grace], [Irma], [50], [Resourcefulness], [Vikram], [49], [Perseverance], )[123][ 456 ][789]
https://github.com/fiit-community/base-typst-template
https://raw.githubusercontent.com/fiit-community/base-typst-template/main/src/lib.typ
typst
MIT License
#import "localization.typ": get_localization as _get_loc // zero vertical space #let _zv() = v(0pt) #let cover-page( title: none, subtitle: none, author: ( name: none, id: none, ), date: none, year: none, logo: none, assignment: ( subject: none, teacher: none, time: none, ), lang: "sk", font: "New Computer Modern", ) = body => { let _loc = _get_loc(lang) // Defaults let title = if title != none {title} else {text(red)[Write a title]} let subtitle = if subtitle != none {subtitle} else {text(red)[Write a subtitle]} let author = author // document-author is used in the header author.insert("document-author", if author.name != none {author.name} else {"Write a name"}) author.name = if author.name != none {author.name} else {text(red)[Write a name]} author.id = if author.id != none {author.id} else {text(red)[Write an ID]} let assignment = assignment assignment.subject = if assignment.subject != none {assignment.subject} else {text(red)[Write a subject]} assignment.teacher = if assignment.teacher != none {assignment.teacher} else {text(red)[Write a teacher]} assignment.time = if assignment.time != none {assignment.time} else {text(red)[Write a time]} let date = if date != none {date} else {datetime.today()} let logo = if logo != none {logo} else {(width: none) => {text(red, size: 5em)[No logo]}} let year = if year != none {year} else {text(red)[Write an academic year]} // End of defaults set document( author: author.document-author, title: title, date: date, ) set page(numbering: "1", number-align: right) set text(font: font, lang: lang) set heading(numbering: "1.1") set par(leading: 0.58em) set align(center) show par: set block(above: 0.75em, below: 0.75em) text(1.2em, weight: "bold", _loc.fiit); _zv() text(1.2em, _loc.stu) v(1fr) align(center, logo(width: 20%)) v(1fr) text(1.8em, weight: 700, title); _zv() text(1.6em, subtitle) v(1fr) align( center, grid( columns: 2, align: left, gutter: 8em, text[ *#_loc.cover-page.author-name:* #author.name \ *#_loc.cover-page.author-id*: #author.id \ ], text[ *#_loc.cover-page.subject:* #assignment.subject \ *#_loc.cover-page.teacher:* #assignment.teacher \ *#_loc.cover-page.time:* #assignment.time \ ] ) ) v(1fr) text(1.2em, [*#_loc.cover-page.academic-year:* #year]) pagebreak() set page( header: [ #set text(8pt) #smallcaps[#author.name] #h(1fr) #smallcaps[#title] ] ) set par(justify: true) set align(start) set align(alignment.top) outline( title: _loc.content.title, ) pagebreak() body }
https://github.com/Turkeymanc/notebook
https://raw.githubusercontent.com/Turkeymanc/notebook/main/packages.typ
typst
// this file allows us to only specify package versions once #import "@local/notebookinator:1.0.1": * // TODO: change to the installed version #import themes.radial: radial-theme, components // TODO: put more packages here
https://github.com/wenzlawski/typst-cv
https://raw.githubusercontent.com/wenzlawski/typst-cv/main/modules/professional.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Experience") #cvEntry( title: [IT & Digitisation Intern], society: [EWF Intertax GmbH Steuerberatungsgesellschaft], date: [06/2022 - 09/2022], location: [Chemnitz, Germany], description: list( [Designed and developed software to digitize and organize paper documents, resulting in a 30% increase in inbox processing speed.], [Implemented a new website (www.ewf-intertax.de), including a back-end database storage system and dynamic web pages.], [] ), tags: () ) #cvEntry( title: [Peer Mentor], society: [University of Manchester], date: [09/2021 - 06/2023], location: [Manchester, UK], description: list( [Tutored freshmen in math and computer science concepts], [Assist students with programming exercises and reinforced concepts], [] ) )
https://github.com/Arrata-TTRPG/Arrata-TTRPG
https://raw.githubusercontent.com/Arrata-TTRPG/Arrata-TTRPG/main/src/sections/introduction.typ
typst
Other
#import "../typst-boxes.typ": * = Introduction Arrata is a roleplaying system inspired by the work of more traditional roleplaying games with an emphasis on universality. The purpose of this system is to allow you to collaboratively write interesting, nuanced, and fun stories easily with multiple people - all through the guise of playing a game. Arrata comes with no setting; I believe it is better to create something of your own and flesh it out as you go along. That's characters, the world, and the context in which those all interact, you will be able to do things far more suited to your understanding than I ever could by building your own worlds and defining their rules (or #strike[stealing] borrowing them). Doing things is often far more valuable and teachable than observing or being told them. Part of the learning-by-doing process is that in order to learn, _you must fail_. This is natural, expected, and not something to be upset or sad about. You _will also succeed_, although rarely in the manner you may be expecting. The great thing about fictional worlds is that they have no physical consequence - they cannot and will not hurt you, so you are free to try the things you want to, and to fail and succeed in amazing and interesting ways. == Other Worlds In using this system, a fictional world is constructed by a _Game Master_ (GM). This world is populated with characters and given things like factions, peoples, places, and conflict; things that make the world alive and interactable. _Players_ take control of _Player Characters_ (PCs) who are built with _Quirks_ that define who they are as people, and _Stats_ that define what they are as beings in the world. Together, the players and GM create a story with the PCs as the protagonists; their actions being influenced by their Quirks and the outcomes of their decisions determined by their Stats. #slantedColorbox( title: "Etymology: Arrata", width: auto, radius: 0pt, color: black, )[ #set text(size: 8pt) _The word Arrata is a misspelling of errata, the plural of erratum; a list of mistakes in a written document. The word was chosen as it embodies the spirit of Arrata: *Change Through Purpose*. By failing; making mistakes and blunders, you will develop as a person and become better than before. I hope in some way this system will allow you to explore these ideas, and perhaps even learn how you can change yourself._ ] == Examples This book contains many examples of different systems and situations, and for your convenience, each example will be enclosed in a box with a title, and will look like this: #slantedColorbox( title: "Example Note: Gamma Function", width: auto, radius: 0pt, color: black, )[ #set text(size: 8pt) _Note: notes often describe intrinsic rules or behaviors._ This is an example. Have the Gamma function: $ Gamma(x) = integral_(0)^(infinity)t^(x-1)e^(-1) dif x $ ] == Game Masters Game Masters (GMs) are a critical part of any roleplaying system. Their job is to: - Understand the rules as thoroughly as possible. - Roleplay Non-Player Characters (NPCs). - Be courteous and fair to their Players. - Provide a story, conflict, and setting. - Arbitrate Player and gameplay conflicts. - Describe: - The outcomes of rolls. - The environment. - NPCs and their actions. - Reactions and consequences. The GM is the world engine, describing and defining what the world is, how it looks, smells, tastes, and sounds, and how it interacts with the Players' Characters and their actions. As a GM, you have the most responsibility; orchestrating sessions and campaigns, managing NPCs, handling disputes, etc. Your Players are counting on you to prepare and improvise as well as you can. If the responsibility required is too much for you to handle, I suggest being a Player. There isn't anything wrong with not being a GM, but having a bad GM is a million times worse than having a bad Player. Game Masters are to be afforded extra rights over the Players. They will have to make rulings and decisions for the Players, and should act as a mediator; thus these rulings are to be respected and treated as the new rule of law unless otherwise changed by the GM. However, it is important not to overstep your authority as the GM. Punishing Players unfairly or making nonsensical rulings are unacceptable. If you find yourself under a GM making such decisions, the best course of action is typically to discuss the issue with the other Players and GM. Mediation and communication are critical skills in roleplaying, but if you fail to solve your issues, it's usually best to leave the group altogether. == Players and their Characters Players are the people in charge of player characters (PCs); their job is to be the "soul" driving their character. Players are charged with the following responsibilities: - Roleplaying their character. - Being courteous to the Game Master and fellow players. - Knowing the rules. - Following the rules and decisions of the Game Master. - Being honest about rolls, outcomes, and and their character. PCs are the protagonists of any Arrata game. They exist to provide a player with a point of view on the collective story being told, and to allow that player to interact with the story. Their PC is the primary responsibility of the Player, and thus if a conflict arises regarding your PC, it is the duty of the Player to back up their PC and fight on their behalf. == Non-Player Characters Non-Player Characters (NPCs) are characters in the story created by the GM or players that act without player input. Instead, the GM acts as the "soul" of every NPC and treats one of many of their characters. GMs can generate hundreds or even thousands of NPCs throughout long campaigns, so NPCs that are underdeveloped or single-purpose are acceptable as long as they are not used in a derogatory or offensive manner. #pagebreak()
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/165.%20name.html.typ
typst
name.html Change Your Name August 2015If you have a US startup called X and you don't have x.com, you should probably change your name.The reason is not just that people can't find you. For companies with mobile apps, especially, having the right domain name is not as critical as it used to be for getting users. The problem with not having the .com of your name is that it signals weakness. Unless you're so big that your reputation precedes you, a marginal domain suggests you're a marginal company. Whereas (as Stripe shows) having x.com signals strength even if it has no relation to what you do.Even good founders can be in denial about this. Their denial derives from two very powerful forces: identity, and lack of imagination.X is what we are, founders think. There's no other name as good. Both of which are false.You can fix the first by stepping back from the problem. Imagine you'd called your company something else. If you had, surely you'd be just as attached to that name as you are to your current one. The idea of switching to your current name would seem repellent. [1]There's nothing intrinsically great about your current name. Nearly all your attachment to it comes from it being attached to you. [2]The way to neutralize the second source of denial, your inability to think of other potential names, is to acknowledge that you're bad at naming. Naming is a completely separate skill from those you need to be a good founder. You can be a great startup founder but hopeless at thinking of names for your company.Once you acknowledge that, you stop believing there is nothing else you could be called. There are lots of other potential names that are as good or better; you just can't think of them.How do you find them? One answer is the default way to solve problems you're bad at: find someone else who can think of names. But with company names there is another possible approach. It turns out almost any word or word pair that is not an obviously bad name is a sufficiently good one, and the number of such domains is so large that you can find plenty that are cheap or even untaken. So make a list and try to buy some. That's what Stripe did. (Their search also turned up parse.com, which their friends at Parse took.)The reason I know that naming companies is a distinct skill orthogonal to the others you need in a startup is that I happen to have it. Back when I was running YC and did more office hours with startups, I would often help them find new names. 80% of the time we could find at least one good name in a 20 minute office hour slot.Now when I do office hours I have to focus on more important questions, like what the company is doing. I tell them when they need to change their name. But I know the power of the forces that have them in their grip, so I know most won't listen. [3]There are of course examples of startups that have succeeded without having the .com of their name. There are startups that have succeeded despite any number of different mistakes. But this mistake is less excusable than most. It's something that can be fixed in a couple days if you have sufficient discipline to acknowledge the problem.100% of the top 20 YC companies by valuation have the .com of their name. 94% of the top 50 do. But only 66% of companies in the current batch have the .com of their name. Which suggests there are lessons ahead for most of the rest, one way or another. Notes[1] Incidentally, this thought experiment works for nationality and religion too.[2] The liking you have for a name that has become part of your identity manifests itself not directly, which would be easy to discount, but as a collection of specious beliefs about its intrinsic qualities. (This too is true of nationality and religion as well.)[3] Sometimes founders know it's a problem that they don't have the .com of their name, but delusion strikes a step later in the belief that they'll be able to buy it despite having no evidence it's for sale. Don't believe a domain is for sale unless the owner has already told you an asking price. Thanks to <NAME>, <NAME>, and <NAME> for reading drafts of this.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/rivet/0.1.0/manual.typ
typst
Apache License 2.0
#import "@preview/tidy:0.3.0" #import "@preview/codelst:2.0.1": sourcecode #import "@preview/showybox:2.0.1": showybox #import "src/lib.typ" #import "src/schema.typ" #import "docs/examples.typ" #set heading(numbering: (..num) => if num.pos().len() < 4 { numbering("1.1", ..num) }) #{ outline(indent: true, depth: 3) } #set page(numbering: "1/1", header: align(right)[rivet #sym.dash.em v#lib.version]) #let doc-ref(target, full: false, var: false) = { let (module, func) = target.split(".") let label-name = module + func let display-name = func if full { display-name = target } if not var { label-name += "()" display-name += "()" } link(label(label-name))[#display-name] } #let note(it) = showybox( title: "Note", title-style: ( color: white, weight: "bold" ), frame: ( title-color: blue.lighten(30%), border-color: blue.darken(40%) ), it ) #show link: set text(blue) = Introduction This package provides a way to make beautiful register diagrams using the CeTZ package. It can be used to document Assembly instructions or binary registers This is a port of the #link("https://git.kb28.ch/HEL/rivet")[homonymous Python script] for Typst. = Usage Simply import `schema` from #link("src/lib.typ") and call `schema.load` to parse a schema description. Then use `schema.render` to render it, et voilà ! #pad(left: 1em)[```typ #import "@preview/rivet:0.1.0": schema #let doc = schema.load("path/to/schema.yaml") #schema.render(doc) ```] = Format This section describes the structure of a schema definition. The examples given use the JSON syntax. For examples in different formats, see #link("https://git.kb28.ch/HEL/rivet-typst/src/branch/main/gallery/test.yaml")[test.yaml], #link("https://git.kb28.ch/HEL/rivet-typst/src/branch/main/gallery/test.json")[test.json] and #link("https://git.kb28.ch/HEL/rivet-typst/src/branch/main/gallery/test.xml")[test.xml]. You can also directly define a schema using Typst dictionaries and arrays. Since the XML format is quite different from the other, you might find it helpful to look at the examples on GitHub to get familiar with it. == Main layout A schema contains a dictionary of structures. The must be at least one defined structure named "main". It can also optionnaly contain a "colors" dictionary. More details about this in #link(<format-colors>)[Colors] #sourcecode[```json { "structures": { "main": { ... }, "struct1": { ... }, "struct2": { ... }, ... } } ```] #pagebreak(weak: true) == Structure <format-structure> A structure has a given number of bits and one or multiple ranges. Each range of bits can have a name, a description and / or values with special meaning (see #link(<format-range>)[Range]). A range's structure can also depend on another range's value (see #link(<format-dependencies>)[Dependencies]). The range name (or key) defines the left- and rightmost bits (e.g. `7-4` goes from bit 7 down to bit 4). Bits are displayed in big-endian, i.e. the leftmost bit has the highest value. #sourcecode[```json "main": { "bits": 8, "ranges": { "7-4": { ... }, "3-2": { ... }, "1": { ... }, "0": { ... } } } ```] == Range <format-range> A range represents a group of consecutive bits. It can have a name (displayed in the bit cells), a description (displayed under the structure) and / or values. For values depending on other ranges, see #link(<format-dependencies>)[Dependencies]. #note[ In YAML, make sure to wrap values in quotes because some values can be interpreted as octal notation (e.g. 010 #sym.arrow.r 8) ] #sourcecode[```json "3-2": { "name": "op", "description": "Logical operation", "values": { "00": "AND", "01": "OR", "10": "XOR", "11": "NAND" } } ```] #pagebreak(weak: true) == Dependencies <format-dependencies> The structure of one range may depend on the value of another. To represent this situation, first indicate on the child range the range on which it depends. Then, in its values, indicate which structure to use. A description can also be added (displayed above the horizontal dependency arrow) #sourcecode[```json "7-4": { ... "depends-on": "0", "values": { "0": { "description": "immediate value", "structure": "immediateValue" }, "1": { "description": "value in register", "structure": "registerValue" } } } ```] Finally, add the sub-structures to the structure dictionary: #sourcecode[```json { "structures": { "main": { ... }, "immediateValue": { "bits": 4, ... }, "registerValue": { "bits": 4, ... }, ... } } ```] #pagebreak(weak: true) == Colors <format-colors> You may want to highlight some ranges to make your diagram more readable. For this, you can use colors. Colors may be defined in a separate dictionary, at the same level as the "structures" dictionary: #sourcecode[```json { "structures": { ... }, "colors": { ... } } ```] It can contain color definitions for any number of ranges. For each range, you may then define a dictionary mapping bit ranges to a particular color: #sourcecode[```json "colors": { "main": { "31-28": "#ABCDEF", "27-20": "12,34,56" }, "registerValue": { "19-10": [12, 34, 56] } } ```] Valid color formats are: - hex string starting with `#`, e.g. `"#23fa78"` - array of three integers (only JSON, YAML and Typst), e.g. `[35, 250, 120]` - string of three comma-separated integers (useful for XML), e.g. `"35,250,120"` - a Typst color (only Typst), e.g. `colors.green` or `rgb(35, 250, 120)` #note[ The XML format implements colors a bit differently. Instead of having a "colors" dictionary, color definitions are directly put on the same level as structure definitions. For this, you can use a `color` node with the attributes "structure", "color", "start" and "end", like so: #sourcecode[```xml <schema> <structure id="main" bits="8"> ... </structure> ... <color structure="main" color="#FF0000" start="4" end="7" /> <color structure="main" color="255,0,0" start="0" end="3" /> </schema> ```] ] #pagebreak(weak: true) = Config presets Aside from the default config, some example presets are also provided: - #doc-ref("config.config", full: true): the default theme, black on white #examples.config-config - #doc-ref("config.dark", full: true): a dark theme, with white text and lines on a black background #examples.config-dark - #doc-ref("config.blueprint", full: true): a blueprint theme, with white text and lines on a blue background #examples.config-blueprint #pagebreak(weak: true) = Reference #let doc-config = tidy.parse-module( read("docs/config.typ"), name: "config", scope: ( doc-ref: doc-ref ) ) #tidy.show-module(doc-config, sort-functions: false) #pagebreak() #let doc-schema = tidy.parse-module( read("docs/schema.typ"), name: "schema", scope: ( schema: schema, doc-ref: doc-ref ) ) #tidy.show-module(doc-schema, sort-functions: false)
https://github.com/dashuai009/dashuai009.github.io
https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/003.typ
typst
#let date = datetime( year: 2024, month: 1, day: 1, ) #metadata(( "title": "modules 模块", "author": "dashuai009", description: "这是一种将C++更加现代的代码组织方式。 模块是一组源代码文件,独立于导入它们的翻译单元进行编译。", pubDate: date.display(), subtitle: [modules,模块], ))<frontmatter> #import "../__template/style.typ": conf #show: conf 这是一种将C++更加现代的代码组织方式。 模块是一组源代码文件,独立于导入它们的翻译单元进行编译。 = 模块试图解决的问题 - 头文件 - module几乎解决了头文件编译的难题,比如头文件的重复替换 (复杂项目中,如果一个底层头文件被修改,上层引用的头文件都会被重新编译)。 使用module之后,这种问题会得到极大的改善。 - 封装:对外接口的暴露 - 在模块中声明的宏、预处理器指令和未导出的名称在模块外部不可见。 它们对导入模块的翻译单元的编译没有影响。 您可以按任意顺序导入模块,而无需考虑宏重定义。导入翻译单元中的声明不参与导入模块中的重载解析或名称查找。 - 编译速度 - 模块编译一次后,结果将存储在描述所有导出的类型、函数和模板的二进制文件中。 编译器处理该文件的速度比头文件快得多。 而且,编译器可以在项目中导入模块的每个位置重用它。 = 实现细节 todo = 常见库支持状态 #link("https://arewemodulesyet.org/")["arewemodulesyet"] Nope! = 编译器支持状态 todo = 基本示例 假设我们现在有如下cpp ```cpp int square(int i); // 声明一个函数 class Square { private: int value; public: explicit Square(int i) : value{square(i)} {} int getValue() const { return value; } }; template <typename T> Square toSquare(const T &x) { return Square{x}; } int square(int i) { // 实现平方函数 return i * i; } ``` 只需要两步就可以转成一个模块单元: 1. 在第一行添加`export module Square;`,这相当于导出一个名为Square的模块。 2. 把想要导出的函数前面加上export关键字。 ```cpp /** modules/mod0/square.ixx **/ export module Square; // declare module Square int square(int i); export class Square { private: int value; public: explicit Square(int i) : value{square(i)} {} int getValue() const { return value; } }; export template <typename T> Square toSquare(const T &x) { return Square{x}; } int square(int i) { return i * i; } ``` 在主文件中,就可以愉快地`import Square`啦~。 ```cpp /*== mod0/main.cpp ==*/ import std; import Square; // import module `Square` int main() { Square x = toSquare(42); std::cout << x.getValue() << '\n'; } ``` = 我就喜欢写头文件?模块实现单元(module implementation unit)和模块声明单元(module interface unit) 像上边这个例子,属于实现和声明放在一起了,可以写的很pythonic。 模块由若干个模块单元(module units)组成。而且模块可以进行分区(partition),或分为子模块。模块单元是包含模块声明的翻译单元(源文件)。类似.h和.cpp,模块分为**接口单元**和**实现单元**。 有几种类型的模块单元: - 模块接口单元(module interface unit)包含关键词`export module`,用于导出模块名称和分区(partition)。和.h文件类似。 - 模块实现单元(implementation unit)是不导出模块名称、分区名称。顾名思义,它用于实现模块。和cpp文件类似。 - 主模块接口单元(primary module interface unit)是导出模块名称的模块接口单元。 模块中必须有一个且只能有一个主模块接口单元。上边这个例子里还没有模块分区,直接`export module Square`,算是主模块单元。 - 模块分区接口单元(partition interface unit)是导出模块分区名称的模块接口单元。 - 模块分区实现单元(partition implementation unit)是模块实现单元,其模块声明中具有模块分区名称,但没有export关键字。 `export`关键字仅在接口文件中使用。实现文件可以`import`另一个模块,但不能`export`任何名称。 实现文件可以具有任何扩展名(这一点编译器还有些特殊处理,好像标准里没有规定)。 = 模块和namespace 不像其它语言,模块不会自动添加一个namespace。 就像第一个例子,import Square之后,Square里导出的所有东西都被直接暴露。 有两种方法可以处理一下,让代码更加规范: 定义一个和模块同名的namespace, 1. 导出命名空间中需要的接口,则命名空间也会被隐式导出,但是命名空间中,没有被导出的接口则不会暴露 ```cpp export module Square; // declare module ”Square” namespace Square { int square(int i);// not exported export class Square { // bala bala ... }; export template<typename T> Square toSquare(const T& x) { // ... } int square(int i) { // not exported // ... } } ``` 1. 显式导出整个命名空间,则命名空间中的所有声明都会被导出。 ```cpp export module Square; // declare module ”Square” int square(int i); export namespace Square { class Square { // ... }; template<typename T> Square toSquare(const T& x) { // ... } } int square(int i) { // not exported // ... } ``` 这样,在主文件中都可以达到以下效果: ```cpp import Square;// 这个是模块名,需要和export匹配 int main(){ Square::Square x = Square::toSquare(42); // ::前Square是命名空间的名字,::Square是类名,这块搞清楚,之后写模块就简单了 std::cout << x.getValue() << '\n'; } ``` = 多文件 == 模块接口单元与模块实现单元 模块接口单元用于导出模块名、模块接口。按照模块分区(partition),分为主模块接口单元和分区模块接口单元。直观上,如果整个模块叫做mod1,则含有export module mod1;的文件就是主接口单元;其他文件不能导出mod1这个名字。如果其他文件导出了mod1的子模块export module mod1:submod;则该文件是分区接口单元。 先来说没有分区的模块接口单元: ```cpp export module Mod1; // module declaration import std; struct Order { int count; std::string name; double price; Order(int c, const std::string& n, double p) : count{c}, name{n}, price{p} { } }; export class Customer { private: std::string name; std::vector<Order> orders; public: Customer(const std::string& n) : name{n} { } void buy(const std::string& ordername, double price) { orders.push_back(Order{1, ordername, price}); } void buy(int num, const std::string& ordername, double price) { orders.push_back(Order{num, ordername, price}); } double sumPrice() const; double averagePrice() const; void print() const; }; ``` 第一行,定义并导出模块的名字: ```cpp export module Mod1; // module declaration ``` 第二行,导入标准模块std: ```cpp import std; ``` 之后就是常见的类型声明部分,声明一个订单结构体 struct Order,和一个顾客类。相比于普通头文件,唯一多的就是 class Customer前前面的export关键字,表示导出这个类。 ```cpp struct Order { // ... } export class Customer { // .... } ``` 简单来说,首先声明并导出一个模块,导入需要的模块,声明需要类型,导出必要的类型。 接下来,需要实现这些类型(或者函数),类似cpp文件,这里我们分成两个实现单元: 实现单元第一行,标明所属模块,`module Mod1;`表示该单元属于Mod1模块。接着,这个单元实现`void Customer::print() const{}`函数。具体用到了format函数,这也是c++20的新功能。 ```cpp module Mod1; // implementation unit of module Mod1 import std; void Customer::print() const { // print name: std::cout << name << ":\n"; // print order entries: for (const auto& od : orders) { std::cout << std::format("{:3} {:14} {:6.2f} {:6.2f}\n", od.count, od.name, od.price, od.count * od.price); } // print sum: std::cout << std::format("{:25} ------\n", ' '); std::cout << std::format("{:25} {:6.2f}\n", " Sum:", sumPrice()); } ``` 与上边这个类似,这是另一个实现单元:标明属于Mod1模块,实现了两个函数`double Customer::sumPrice() const {}` 和另一个函数`double Customer::averagePrice() const {}` ```cpp module Mod1; // implementation unit of module Mod1 double Customer::sumPrice() const { double sum = 0.0; for (const Order &od: orders) { sum += od.count * od.price; } return sum; } double Customer::averagePrice() const { if (orders.empty()) { return 0.0; } return sumPrice() / orders.size(); } ``` 实现单元和cpp文件类似。以上三个文件完整定义并实现了Mod1模块。 具体使用模块如下: ```cpp import std; import Mod1; int main() { Customer c1{"Kim"}; // Order b1(1, "buy", 590.0); // error Order并没有被导出。 c1.buy("table", 59.90); c1.buy(4, "chair", 9.20); c1.print(); std::cout << " Average: " << c1.averagePrice() << '\n'; } ``` 输出结果为 ```jsx ``` > 上边这种定义与实现分离的方式,cmake支持好像还不太好,没编译过去 > == 模块内部(internal)单元,模块分区 有接口和实现单元还不够,c++20的module特性还支持模块划分,每个模块还可以被划分为子模块。类似python中`import a.b.c;` 分区接口的开头如下: ```cpp export module Example:part1; ``` 分区实现单元的开头如下: ```cpp module Example:part1; ``` 若要访问另一个分区中的声明,分区必须导入它,但它只能使用分区名称,而不是模块名称: ```cpp module Example:part2; import :part1;// 额外注意:这里不能带模块名,Example:part1不行。 ``` 主接口单元必须导入并重新导出模块的所有接口分区文件,如下所示: ```cpp export module Example; // export import :part1; // 如果part1不被export,则part1的所有内容对外不可见(包括export的接口) export import :part2;// 所有part2导出的接口,都会被导出到Example中。 ``` 主接口单元可以导入分区实现文件,但无法导出它们。 不允许这些文件导出任何名称。 这一限制使模块能够在模块内部保留实现详细信息。 > 具体的例子看modules/mod2 > = 子模块submodule 标准里面没有子模块的规定,但是模块名支持`.` ,他在模块名中没有特殊含义,但是可以从逻辑上划分模块之间的关系。 ```cpp export module a; // export import a.c; 没有被export,如果只import a是看不到a.c的。 export import a.b.c; ``` = 模块和include **While in theory modules could replace all traditional header files with all their flaws, in practice this will never happen**. === global module fragment 现在,我们可以确定,有export module xxx的就是模块接口单元,没有export关键字,但是有module xxx都是模块实现单元。 c++为了和旧代码兼容(~~为了留住用户~~),特地兼容了普通的头文件。用到了 全局模块片段(global module fragment) ```cpp module; // start module unit with global module fragment #include <string> #include <vector> export module Mod1; // module declaration // bula bula bula ``` 前面三行就是全局模块片段,不看前三行,和前面说过的模块单元是一样的。但是 - include进来的 指令 (`#define` and `#include`)可以正常使用和被看到。 - 不会导出任何东西(包括macros, declarations, definitions) == importable header 可被导入的头文件。 比如 ```cpp import <vector>; import "myheader.h"; ``` > include头文件和import模块之间的主要区别在于:头文件中的任何预处理器定义在语句之后的导入程序中都可见。 > = 其他 - 模块的使用可以提高代码的可读性和可维护性,解决了头文件编译的难题,同时也提高了编译速度。 - 模块分为接口单元和实现单元,可以通过定义同名的命名空间来更加规范地使用模块。 - 全局模块片段和可导入的头文件也是模块的一部分,可以提高代码的兼容性和可读性。
https://github.com/huyufeifei/grad
https://raw.githubusercontent.com/huyufeifei/grad/master/docs/paper/src/template/util.typ
typst
#let empty_par = par(h(1em)+v(-1em))
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10280.typ
typst
Apache License 2.0
#let data = ( ("LYCIAN LETTER A", "Lo", 0), ("LYCIAN LETTER E", "Lo", 0), ("LYCIAN LETTER B", "Lo", 0), ("LYCIAN LETTER BH", "Lo", 0), ("LYCIAN LETTER G", "Lo", 0), ("LYCIAN LETTER D", "Lo", 0), ("LYCIAN LETTER I", "Lo", 0), ("LYCIAN LETTER W", "Lo", 0), ("LYCIAN LETTER Z", "Lo", 0), ("LYCIAN LETTER TH", "Lo", 0), ("LYCIAN LETTER J", "Lo", 0), ("LYCIAN LETTER K", "Lo", 0), ("LYCIAN LETTER Q", "Lo", 0), ("LYCIAN LETTER L", "Lo", 0), ("LYCIAN LETTER M", "Lo", 0), ("LYCIAN LETTER N", "Lo", 0), ("LYCIAN LETTER MM", "Lo", 0), ("LYCIAN LETTER NN", "Lo", 0), ("LYCIAN LETTER U", "Lo", 0), ("LYCIAN LETTER P", "Lo", 0), ("LYCIAN LETTER KK", "Lo", 0), ("LYCIAN LETTER R", "Lo", 0), ("LYCIAN LETTER S", "Lo", 0), ("LYCIAN LETTER T", "Lo", 0), ("LYCIAN LETTER TT", "Lo", 0), ("LYCIAN LETTER AN", "Lo", 0), ("LYCIAN LETTER EN", "Lo", 0), ("LYCIAN LETTER H", "Lo", 0), ("LYCIAN LETTER X", "Lo", 0), )
https://github.com/AOx0/expo-nosql
https://raw.githubusercontent.com/AOx0/expo-nosql/main/main.typ
typst
MIT License
#import "slides.typ": * #import "tablex.typ": * #import "themes/bristol.typ": * #show: slides.with( authors: ("<NAME>"), short-authors: "<NAME>", title: "NoSQL", short-title: "NoSQL", subtitle: "Bases de Datos Avanzadas", date: datetime.today().display(), theme: bristol-theme(), ) #slide(theme-variant: "title slide") #new-section("Introducción") /* A data model determines how data is structured and accessed. Some key points about data models: - They determine the logical structure of a database independent of physical storage considerations - Different data models structure and organize data in different ways which impacts how it can be accessed and manipulated - Common data models include the hierarchical, network, relational, object-oriented, and dimensional models - The optimal data model depends on factors like the nature of the data, requirements for speed, reliability, maintainability and more */ #slide(title: "Escalabilidad", colwidths: (1.5fr, 1fr))[ - La capacidad de un sistema para manejar una carga cada vez mayor de datos y trabajo. - Ejemplo: Tienes un servidor, cuyo servicio ocupa el 80% ocupado del disco duro y 85% de RAM. ][ #image("assets/Resource.svg") ] #slide(theme-variant: "wake up")[ #text(size: 0.8 * 1em, weight: "light")[Quiz!!] ¿Cómo harían para tener más recursos para atender a los usuarios? ] #slide(title: "Horizontal vs Vertical", colwidths: (1fr, 1fr))[ #align(center)[ #image("assets/Resource3.svg") ] ][ #align(center)[ #image("assets/Resource2.svg") ] ] #slide(theme-variant: "wake up")[ #text(size: 0.8 * 1em, weight: "light")[Quiz!!] 10 millones de usuarios, ¿escalar horizontal o vertical? ] #slide(title: "Modelo de datos")[ - Describe cómo se estructuran los datos y cómo se accede a ellos. - El modelo de datos tiene implicaciones sobre las operaciones y representación de los datos - Un modelo implica formas distintas: - De relaciones - De entidades - De atributos ] #slide(title: "Modelo relacional", colwidths: (1.5fr, 1fr))[ - Propuesto por <NAME>. "Ted" Codd en 1970, de la IBM - Basado en tablas, formadas por columnas (atributos) y filas (entidades) - Se identifica las tuplas con llaves, y a la vez se usan para formar relaciones - Noten que el modelo esta orientado a entidades, las relaciones son secundarias - Las tablas deben ser pre definidas ][ #image("assets/Relational.svg") ] #slide(title: "\"SQL\"")[ - Desarrollado por <NAME> y <NAME>, de la IBM - Structured Query Language, antes Structured English Query Language (Sequel) - Lenguaje utilizado para el manejo de información en RDBMS. - Emplea algebra relacional y cálculo relacional de tuplas, muy innovador y sencillo - Utilizado con datos estructurados ] #slide(theme-variant: "wake up")[ #text(size: 0.8 * 1em, weight: "light")[Quiz!!] ¿Qué es una función hash? ] #slide(title: "RDBMS", colwidths: (1.5fr, 1fr))[ #align(horizon)[ - Sistema gestor de bases de datos relacionales - Usa SQL como lenguaje para manejar la información - Utiliza el modelo relacional - Fuerte enfoque en ACID (Accesibilidad, Consistencia, _Isolation_, Durabilidad), que verifica para cada transacción. ] ][ #image("assets/main_databases.jpg") ] #slide(title: "Sharding")[ #align(center)[ #image("assets/Shard.svg", height: 60%) ] ] #slide(theme-variant: "wake up")[ #text(size: 0.8 * 1em, weight: "light")[Quiz!!] 10 millones de usuarios, ¿cómo escalamos la base de datos? ] #slide(title: "Sharding")[ #align(center)[ #image("assets/Res1.svg", height: 65%) ] ] #slide(title: "CAP")[ Los sistemas pueden cubrir solo 2 características de entre: - Consistency: cómo se comporta el estado del sistema cuando se realiza una operación - Availability: Se puede continuar el servicio aunque existan fallas en hardware u otros nodos - Partition Tolerance: Cómo se desenvuelve el sistema cuando hay *islas* que no pueden conectarse entre si. Por ej, cuando agregamos/quitamos nodos ] #slide(theme-variant: "wake up")[ #text(size: 0.8 * 1em, weight: "light")[Quiz!!] ¿Qué es lo que sacrifican los RDBMS de CAP? ] #slide(title: "NoSQL")[ - En general, todo lo que no es _SQL_. Es decir, que no sigue el modelo de datos relacional. - Implica que no se use el mismo ANSI/ISO SQL - Si damos menor prioridad a las retricciones que pone ACID se puede lograr escalabilidad y rendimiento. - Menos consistencia e isolación para lograr disponibilidad y rendimiento. ] #slide(title: "NoSQL")[ Permite: - Manejo de datos estructurados y no estructurados - Facilita el desarrollo iterativo - Mejora la experiencia del desarrollador - Proporciona más herramientas para poder escalar mejor - Uso inteligente de índices, hashes, y cache ] #new-section("Modelos de Datos") #slide(title: "Key-Value")[ - La información se representa de la forma $(K,V)$ - Si queremos un valor, simplemente lo buscamos usando su llave - La llave $K$ es un nombre de archivo, texto plano, hash, URI, etc. - El valor $V$ es un _blob_ binario, puede almacenar lo que sea - El soporte de operaciones basado en el valor es limitado (p. ej buscar los usuarios que se llamen Daniel) - Multiples tipos: en memoria, en disco, híbrido - `Get(key)` ] #slide(theme-variant: "wake up")[ #text(size: 0.8 * 1em, weight: "light")[Quiz!!] ¿Cómo será que se particiona una base de datos _Key-Value_? ] #slide(title: "Wide-Column Stores")[ - Familia de columnas - Similar a _Key-Value_, se ve de la forma $(K, (C, C, C, C, ...))$ - Donde cada columna se ve de la forma $(K, V)$, es decir que se ve $(K, ((K_1, V_1), (K_2, V_2), ...))$ - Suelen dar soporte para almacenar versiones de columna con una tercera llave de tiempo `Get(key, col, time)` - Algunos (p. ej Cassandra) permiten tener _agregados_ (columnas anidadas en columnas) - Partición eficiente en vertical y horizontal - `Get(key, col)` ] #slide(title: "Document")[ - Similar a _Key-Value_ de la forma $(K, V)$ donde $V$ es JSON, XML, o BSON. - Permite cambios en la estructura de la información - Se puede agregar soporte para más tipos de valores. - Algunos (p. ej. MongoDB) permiten tener colecciones de documentos - Se puede obtener atributos especificos del documento sin cargarlo todo - Toda la información está contenida en el mismo documento - Se puede relacionar otros documentos usando su id ] #slide[ #text(size: 14pt)[ ```json { "_id": "123456789", "title": "Introduction to NoSQL Databases", "author": { "name": "<NAME>", "email": "<EMAIL>" }, "content": "NoSQL databases provide a flexible and scalable approach to data storage, allowing developers to...", "tags": ["NoSQL"], "date_published": "2023-01-15T08:00:00Z", "comments": [ { "user": "Alice", "comment_text": "Great article! I learned a lot." }, { "user": "Bob", "comment_text": "Could you elaborate on the sharding techniques mentioned?" } ] } ``` ] ] #slide(theme-variant: "wake up")[ #text(size: 0.8 * 1em, weight: "light")[Quiz!!] ¿En dónde usarían una base de datos con este modelo? ] #slide[ #align(center)[ #image(height: 75%, "assets/VS.svg") ] ] #slide(title: "Graph")[ - Utilizan teoría de grafos para almacenar los datos y representar relaciones. - Consiste en vértices que representan entidades y aristas que representan relaciones entre ellas - Brindan lenguajes de _consulta_ que facilitan el recorrido del grafo - Permiten hacer consultas complejas sin necesidad de joins - Por debajo usa los demás modelos para representar el grafo ] /* #slide(title: text(size: 0pt, "Representación"))[ #image("assets/Internal.png", height: 80%) ] */ #slide(theme-variant: "wake up")[ #text(size: 0.8 * 1em, weight: "light")[Ejemplo!!] Vamos a crear un _engine_ de recomendaciones, basado en las etiquetas de las publicaciones que hemos visto nosotros y lo usuarios que seguimos ] #slide[ #align(center + horizon)[ #image("assets/Problem.png", width: 75%) ] ] #slide[ #text(size: 18pt)[ ```sql BEGIN; LET $seen = SELECT VALUE id FROM (SELECT out.id as id FROM ($auth.id)->view GROUP BY id LIMIT 100 ); LET $seen_by_others = SELECT VALUE id FROM (SELECT out.id as id FROM ($auth.id)->follow->user->view GROUP BY id LIMIT 100); LET $seeng = array::union($seen, $seen_by_others); LET $a = SELECT * FROM $seeng->tagged->tag WHERE array::len(id) > 0; LET $tags = RETURN array::distinct(array::flatten($a)); RETURN SELECT *, fn::is_sus(id) FROM array::distinct(array::flatten((SELECT VALUE in.* FROM $tags<-tagged))); COMMIT; ``` ] ] #slide(title: "Publicaciones vistas")[ #align(horizon)[ #block[ ```sql LET $seen = SELECT VALUE id FROM ( SELECT out.id as id FROM ($auth.id)->view GROUP BY id LIMIT 100 ); LET $seen_by_others = SELECT VALUE id FROM ( SELECT out.id as id FROM ($auth.id)->follow->user->view GROUP BY id LIMIT 100 ); LET $seeng = array::union($seen, $seen_by_others); ``` ] ] ] #slide(title: "Etiquetas de pub")[ #align(horizon)[ #block[ ```sql LET $tags_por_pub = SELECT * FROM $seeng->tagged->tag WHERE array::len(id) > 0; LET $tags = RETURN array::distinct(array::flatten($tags_por_pub)); RETURN SELECT *, fn::is_sus(id) FROM array::distinct(array::flatten(( SELECT VALUE in.* FROM $tags<-tagged ))); ``` ] ] ] #new-section("Cierre") #slide(title: "Ventajas")[ - Pueden ofrecer mejor experiencia al desarrollar - El modelo de datos es más simple de entender - Flexibilidad con la información que se almacena - Facilidad para realizar análisis sobre información profundamente relacionada - Facilidad para escalar de forma horizontal ] #slide(title: "Desventajas")[ - Son menos confiables por ser menos estrictos con ACID en cada transacción - No hay un lenguaje de manipulación de datos estándard - Hay que aprender nuevos lenguajes conceptos y herramientas para utilizarlas - Pocas herramientas para trabajar con ellas, como plataformas para _hostear_ ] #slide(theme-variant: "wake up")[ Gracias! #set text(size: 12pt) #set enum(numbering: "[1]") + <NAME>, <NAME>, and <NAME>, "A Survey on NoSQL Stores," ACM Computing Surveys, vol. 51, no. 2. Association for Computing Machinery (ACM), pp. 1-43, Apr. 17, 2018. doi: 10.1145/3158661. + M. Besta et al., "Demystifying Graph Databases: Analysis and Taxonomy of Data Organization, System Designs, and Graph Queries." arXiv, 2019. doi: 10.48550/ARXIV.1910.09017. + <NAME>, <NAME>, <NAME>, and <NAME>, "Survey on NoSQL database," 2011 6th International Conference on Pervasive Computing and Applications. IEEE, Oct. 2011. doi: 10.1109/icpca.2011.6106531. + <NAME> and <NAME>, “Survey of graph database models,” ACM Computing Surveys, vol. 40, no. 1. Association for Computing Machinery (ACM), pp. 1-39, Feb. 2008. doi: 10.1145/1322432.1322433. + ComputerWorld. "The Story So Far". Consultado en Nov 2023 Disponible en https://www.computerworld.com/article/2588199/the-story-so-far.html + <NAME>. 2012. "A Survey on NoSQL Databases". (2012). ]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-selector-02.typ
typst
Other
// Error: 7-35 this selector cannot be used with show #show selector(heading).or(strong): none
https://github.com/lphoogenboom/typstThesisDCSC
https://raw.githubusercontent.com/lphoogenboom/typstThesisDCSC/master/chapters/preface.typ
typst
#import "../typFiles/specialChapter.typ": * #show: specialChapter.with(chapterTitle: "Preface", content: [ // Write your preface here #lorem(200) // lorem() function adds filler text ])
https://github.com/PetrusTryb/computer-networks
https://raw.githubusercontent.com/PetrusTryb/computer-networks/main/topics.typ
typst
#import "@preview/touying:0.4.2": * // Themes: default, simple, metropolis, dewdrop, university, aqua #let s = themes.metropolis.register(aspect-ratio: "4-3") #let occured(t) = text(fill: red, t) #let occnow = box(fill: yellow, inset: 0.2em, baseline: 0.2em, height: 1em, radius: 0.4em,text(fill: red, weight: "bold", "24/0")) #let s = (s.methods.info)( self: s, title: [Sieci Komputerowe], subtitle: [Heurystyka Edukacyjna], date: [Statystyki tematów uzupełnione o tegoroczną zerówkę #occnow], institution: [2023/2024], ) #let (init, slides, touying-outline, alert, speaker-note) = utils.methods(s) #show: init #show strong: alert #let (slide, empty-slide, title-slide, focus-slide) = utils.slides(s) #set text(size: 0.7em) #show: slides = Ranking tematów #table(columns: (2.5fr, 1.5fr), [Temat],[Wystąpienia (rok/termin)], [Tryby pracy przełączników, metody przełączania],[23/0,23/0',24/1',19/1,19/2,24/1"], [Porównanie koncentrator, przełącznik, router, brama],[23/0,23/0',17/1,18/1,24/1'], occured([Wady IPv4 wynikające z budowy nagłówka]),[23/0,23/0',18/1,24/1',19/1,#occnow], occured([Mechanizmy i algorytmy sterowania przepływem danych w IP]),[23/0,23/0',23/1,24/1',19/1,19/2,18/0,24/1",#occnow], occured([Zasady dostępu DCF i PCF w IEEE 802.11]),[23/0,17/1,18/1,19/1,24/1",#occnow], occured([VLAN - definicje, cel, sposoby określ. przynależności, 802.1Q]),[23/0',24/1',19/2,#occnow], occured([Synchronizacja w sieciach - def., cechy, standardy, w tym NTP]),[23/0',23/1,24/1',#occnow], [Zasady organizacji DNS],[17/1], [Tworzenie i modyfikacja tablic routingu],[17/1,18/1], [DHCP - co to, po co, zasada działania],[18/1,23/1,24/1"], [DNS - co to jest, jak działa, typy rekordów],[19/1,18/0,24/1"], [Przyczyny przejścia z adresacji klasowej na bezklasową],[18/1,19/1], [Dlaczego ramka Ethernet ma rozmiar >64B i \<2kB],[23/1,24/1\"], [Kodowanie xB/yB - zalety nad prostymi np. Manchester i opis],[23/1,19/2,18/0], [Kryteria wyboru przełączników],[23/1], [Różne typy adresów w ujęciu warstwowym],[19/2,18/0], [Porównanie ISO/OSI i TCP/IP, podst. założenia],[19/2], [Opis działania systemów pocztowych, w tym protokoły],[18/0], [Mechanizmy sieci WLAN, podwarstwa MAC, zróżn. strumienie],[18/0], occured([WiFi - Czułość odbiornika a parametramy emisyjne i propagacyjne]), occnow ) ' - EiT, " - IBM\ _Pominięto tematy wymagające znajomości literatury._\ *Pominięto tematy z zakr. wiedzy ogólnej, scalono podobne tematy (jako element heurystycznej strategii zaliczenia).* = Pewniaki == Tryby pracy przełączników, metody przełączania - Metody przełączania: - Store-and-forward: przesyłamy dane po otrzymaniu całej ramki i sprawdzeniu sumy kontrolnej - Zalety: nie zalewamy sieci nieprawidłowymi danymi, idealne przy aplikacjach wrażliwych na błędy w transmisji - Wady: opóźnienie proporcjonalne do długości ramki - Cut-Through: przesyłamy dane od razu po odczytaniu adresu docelowego - Zalety: o wiele szybciej, doskonałe do zastosowań niewrażliwych na przekłamania np. systemów multimedialnych - Wady: możemy zalewać sieć uszkodzonymi ramkami - Tryby pracy: - Transparent Bridging: dane rozgłoszeniowe przesyłane na wszystkie porty (oprócz źródłowego) - Zalety: brak konieczności konfiguracji przy zmianie podłączeń - Wady: możliwość wystąpienia sztormów rozgłoszeniowych, zalewanie sieci bardzo niekorzystne np. przy grach czy multimediach - Express Switching: dane rozgłoszeniowe przesyłane na wybrany port (ustalany przez supervisora) - Zalety: nie zalewamy sieci, pozwala uniknąć sztormów rozgłoszeniowych - Wady: konieczność ręcznej konfiguracji, jak przełączymy urządzenie do innego portu i nie zmienimy ustawień to nie działa *Dane rozgłoszeniowe = broadcast + ramki do urządzeń nieznajdujących się jeszcze w buforze LookUp* == Porównanie urządzeń sieciowych - Regenerator [warstwa fizyczna]: - Zamienia zniekształcony sygnał na "ładny" - Opóźnienia rzędu nanosekund (rozwiązanie sprzętowe analogowe) - Zastosowania: łączenie dwóch sieci tego samego typu (przedłużanie zasięgu medium) - Koncentrator [warstwa fizyczna]: - Rozgłasza otrzymany sygnał na wszystkie porty (oprócz źródłowego) - Opóźnienia kilkaset nanosekund (podobnie jak regenerator) - Do stosowania wyłącznie w sieciach o małym obciążeniu, np. centralek p-poż. i innych przemysłowych - Może wykrywać kolizje - Most [warstwa łącza danych]: - Urządzenie cyfrowe stosowane do łączenia ze sobą sieci heterogenicznych - Uczy się, w której sieci znajduje się stacja - Opóźnienia mikrosekundowe - Przełącznik [warstwa łącza danych i warstwa sieciowa]: - Podobnie jak most, uczy się lokalizacji stacji i przesyła dane, ale jednocześnie - Do momentu wypełnienia LookUp (albo jak go przepełnimy) table działa jak koncentrator - Dzieli domenę kolizyjną - Może posiadać zaawansowane mechanizmy filtracji wg. protokołu, MAC itp. - Może dzielić domenę rozgłoszeniową (VLANy) - Router [warstwa sieciowa]: - Dzieli domenę rozgłoszeniową - Opóźnienia rzędu kilku milisekund (nie nadużywać!) - Zaawansowane mechanizmy filtracji, firewalle, wydzielanie podsieci itp. - Routing wg. tablicy trasowania (statycznej od supervisora lub tworzonej dynamicznie) == Wady IPv4 wynikające z budowy nagłówka #occnow - Wersja protokołu - po co aż 4 bity jak może być tylko 4 lub 6?? - Typ usługi - ignorowane przez wiele urządzeń, może być tam kod klasy obsługi (ekspres, gwarantowana) ale i tak wtedy nieużywamy 2 bitów - Całkowita długość datagramu: 16 bitów to może być za mało - Identyfikacja: ponownie 16b to za mało na długie połączenia, ponadto narażenie prywatności (powiązanie wiadomość - IP) - Przesunięcie fragmentacji: sama idea fragmentacji wprowadza duże opóźnienia i możliwość zgubienia części danych, co zwykle skutkuje ponownym przesyłaniem całości - Czas życia (TTL): tylko 8 bitów, można tym manipulować i "ubijać" datagramy, ponadto każdy OS ustawia inaczej przez co można go zidentyfikować - Protokół: 8 bitów - stanowczo za mało, nieustandaryzowane - Suma kontrolna: po co skoro stopa błędów $10^(-12)$, zwłaszcza że dotyczy tylko nagłówka - Opcje nagłówka: rejestrowanie (i tak za małe pole 40B), wymuszanie trasy, zwykle ignorowane - *Adresy: 32b stanowczo za mało żeby zapewnić unikalność w skali świata* == Mechanizmy i algorytmy sterowania przepływem danych w IP #occnow - TCP Sliding Window Flow Control - Odbiorca określa ile danych może przyjąć, określając szerokość okna - Po otrzymaniu +ACK nadawca może wysłać kolejną porcję danych określoną przez rozmiar okna - Jeśli otrzyma -ACK lub nie otrzyma żadnej odpowiedzi w ustalonym czasie restransmituje dane - TCP Congestion Control *implementowany po stronie nadawczej* - Nadawca ma 2 parametry: - CWND - Congestion WiNDow - SSHTHRESH - Slow Start THRESHold - Tryb Slow Start - Początkowo CWND = 1 \* MSS (Max Segment Size) - Dla każdego +ACK zwiększamy CWND o 1 (wykładniczo, nawet gdy ACK potwierdza mniej niż 1MSS) - Jeżeli CWND>SSHTHRESH to przełączamy się w tryb Congestion Avoidance - Tryb Congestion Avoidance - Zwiększamy CWND dopiero gdy przyjdą wszystkie +ACK (liniowo) - Fast Retransmit *TCP TAHOE* - Jeśli odbierzemy >=3 zduplikowane ACK to znaczy że segment był stracony - Szybka retransmisja brakującego segmentu zanim nastąpi timeout - Procedura Slow Start - Fast Recovery *TCP RENO* - Duplikaty ACK oznaczają że coś tam się przesyła - Szybka retransmisja - SSHTHRESH = CWND/2 - CWND = SSHTHRESH+3 - Procedura Congestion Avoidance - Pozwala zwiększyć wydajność unikając procedury Slow Start po retransmisji == Zasady dostępu DCF i PCF w IEEE 802.11 #occnow - DCF (asynchroniczny) - Oparty o rywalizację, mogą istnieć kolizję ale staramy się ich unikać - Nadawca wysyła RTS (zawiera czas transmisji) - Odbiorca wysyła CTS (również zawiera planowany czas zajętości medium) - Inne stacje odkładają dane w swoich Network Allocation Vectorach - Nadawca wysyła dane - Po poprawnym odebraniu odbiorca wysyła ACK i kolejna rywalizacja - Występuje problem ukrytych stacji, które mogą wywołać kolizję nie wiedząc, że druga nadaje - PCF (synchroniczny) - Brak rywalizacji, brak kolizji, dostępem zarządza Point Coordinator (zwykle Access Point) - Jest stosowany przez wydzielony fragment czasu (podawany w beacon frame), obok DCF - W czasie PIFS PC odpytuje poszczególne stacje wysyłając POOL, wtedy wysyłają one swoje dane (muszą zdążyć zacząć w SIFS), reszta trzyma je w NAV #grid(columns: (1fr, 1fr), figure(caption: "DCF", image("DCF.png", width:20em)), figure(caption: "PCF", image("PCF.png", width:20em))) == VLAN - definicje, cel, sposoby określ. przynależności, 802.1Q #occnow - Pozwalają tworzyć wiele logicznych sieci w jednej fizycznej - Zalety: - Bezpieczeństwo - uniemożliwienie podsłuchiwania, skanowania urządzeń - Przeciwdziałanie sztormom rozgłoszeniowym, podział domeny rozgłoszeniowej bez routerów - Zmiany organizacji sieci za pomocą oprogramowania - Najpopularniejsze typy: - Segmentacja wirtualna - wydzielone nie nakładające się grupy, każda funkcjonuje jako oddzielna domena, pod jednym adresem. Najprostrzy sposób na tworzenie grup roboczych. - Podsieć wirtualna - ruch pakietów poddawany programowej kontroli, jedno urządzenie może należeć do wielu grup - Sposoby określania przynależności stacji - Grupy portów - segmentacja wirtualna, prawie każdy przełącznik to obsługuje - Adresy MAC - tabela asocjacyjna wewnątrz przełącznika, MAC->jedna/wiele podsieci - Adresy warstwy sieciowej (np. IP) - np. podział według masek podsieci - Reguły logiczne - kombinacja powyższych + protokoły, pola ramki itp. - Multicastowe adresy IP - stacje łączą się w grupy rejestrując specjalne adresy IP - Do ramki ethernet pomiędzy adresami a długością wpychane jest pole 802.1Q VLAN TAG (usuwa je potem ostatni switch na trasie) - Protocol ID - stała 0x8100 - User Priority Bits - priorytet QoS zakr. 0-7 - Canonical Format Indicator - 1 = brak zezwolenia na retransmisje przez porty bez wsparcia dla 802.1Q - VLAN ID - 12 bitów, chociaż często liczba ograniczona przez producenta VLAN może być jawny lub ukryty (wtedy klient nawet nie wie, że jest w VLANie)
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/references/label.typ
typst
Apache License 2.0
// compile: true #set heading(numbering: "1.") = Labeled <title_label> /* ident */ @title_label
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/draft-shsat-ws-1.typ
typst
#import "page-templates.typ" page-templates.test.with(fill: black) #let holder(..items) = { enum(..items) } #{ let num = 1 let top = { let expr = box([*Q17* -- *Kaplan Exam 2012*\ ]) expr h(1fr) box({ text(fill: blue, emph("percentages")) //rect(outset: 0pt, radius: 5pt, inset: 5pt, text(size: 8pt, "percentages")) }) v(-5pt) //line(length: 170pt) line(length: 100%) } let a = block({ lorem(60) }) let b = block({ let letters = "ABCD" set enum(numbering: (it) => { let x = letters.at(it - 1) + "." text(weight: "bold", x) }, spacing: 39pt, tight: false, body-indent: 10pt) enum( lorem(30), lorem(30), lorem(30), ) }) let val = block(breakable: false, fill: yellow.lighten(100%), grid(column-gutter: 19pt, columns: (170pt, 1fr), a, b)) set enum(full: false, numbering: (x) => { text(weight: "bold", str(x) + ".") }, tight: false, spacing: 40pt) //holder(val, val, val) // v(-30pt) [= Extra SHSAT Math Practice ] v(0pt) let name = [Michelle] let names = [<NAME> | Alvin | <NAME> Chen] let grouping = [ *Student Group*: #names ] style(styles => { let length = measure(grouping, styles).width //line(stroke: (dash: "loosely-dotted"), length: length) }) grouping v(40pt) rect(stroke: (dash: "dotted"), radius: 20pt, inset: 20pt, { top val }) } #let tabler(params) = { table( fill: (col, _) => if calc.odd(col) { luma(240) } else { white }, align: (col, row) => if row == 0 { center } else if col == 0 { left } else { right }, columns: 4, [], [*Q1*], [*Q2*], [*Q3*], [Revenue:], [1000 €], [2000 €], [3000 €], [Expenses:], [500 €], [1000 €], [1500 €], [Profit:], [500 €], [1000 €], [1500 €], ) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/ansi-render/0.4.0/CHANGELOG.md
markdown
Apache License 2.0
# Changelog 📝 ## [0.4.0] - 2023-09-13 ### Added * Added most options from [`block`]([https://](https://typst.app/docs/reference/layout/block/)) function * Added `vscode-light` theme ### Changed * Changed outmost layout from `rect` to `block` * Changed default theme to `VSCode Light` ## [0.3.0] - 2023-09-09 ### Added * Added `radius` option, default is `3pt` ### Changed * Changed default font size to `10pt` * Changed default font to `Cascadia Code` * Changed default theme to `Solarized Light` ## [0.2.0] 2023-08-05 ### Changed * Changed coding style to kebab-case and two spaces ## [0.1.0] 2023-07-02 first release
https://github.com/lvignoli/typst-action-example
https://raw.githubusercontent.com/lvignoli/typst-action-example/main/letter.typ
typst
Dear Santa, #for i in (12, 30, 40, 20, 10) { lorem(i) parbreak() }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz-plot/0.1.0/manual.typ
typst
Apache License 2.0
#import "/src/cetz.typ" #import "/doc/util.typ": * #import "/doc/example.typ": example #import "/doc/style.typ" as doc-style #import "/src/lib.typ": * #import "@preview/tidy:0.3.0" // Usage: // ```example // /* canvas drawing code */ // ``` #show raw.where(lang: "example"): example #show raw.where(lang: "example-vertical"): example.with(vertical: true) #make-title() #set terms(indent: 1em) #set par(justify: true) #set heading(numbering: (..num) => if num.pos().len() < 4 { numbering("1.1", ..num) }) #show link: set text(blue) // Outline #{ show heading: none columns(2, outline(indent: true, depth: 3)) pagebreak(weak: true) } #set page(numbering: "1/1", header: align(right)[CeTZ-Plot]) = Introduction CeTZ-Plot is a simple plotting library for use with CeTZ. = Usage This is the minimal starting point: #pad(left: 1em)[```typ #import "@preview/cetz:0.3.1" #import "@preview/cetz-plot:0.1.0" #cetz.canvas({ import cetz.draw: * import cetz-plot: * ... }) ```] Note that plot functions are imported inside the scope of the `canvas` block. All following example code is expected to be inside a `canvas` block, with the `plot` module imported into the namespace. = Plot #doc-style.parse-show-module("/src/plot.typ") #for m in ("line", "bar", "boxwhisker", "contour", "errorbar", "annotation", "formats", "violin") { doc-style.parse-show-module("/src/plot/" + m + ".typ") } = Chart #doc-style.parse-show-module("/src/chart.typ") #for m in ("barchart", "boxwhisker", "columnchart", "piechart") { doc-style.parse-show-module("/src/chart/" + m + ".typ") }
https://github.com/mem-courses/linear-algebra
https://raw.githubusercontent.com/mem-courses/linear-algebra/main/homework/linear-algebra-homework10.typ
typst
#import "../template.typ": * #show: project.with( title: "Linear Algebra Homework #10", authors: ( (name: "<NAME> (#95)", email: "<EMAIL>", phone: "3230104585"), ), date: "December 6, 2023", ) #let alpha = math.bold(math.alpha) #let beta = math.bold(math.beta) #let gamma = math.bold(math.gamma) #let theta = math.bold(math.theta) #let eta = math.bold(math.eta) #let nu = math.bold(math.nu) #let xi = math.bold(math.xi) #let ds = math.dots.c #let TT = math.upright("T") = P107 习题四 35 #ac #prob[ 问在 $PP^n$ 中,分别满足下列条件的全体 $n$ 元向量 $(x_1,x_2,dots.c,x_n)$ 的集合能否各自构成 $PP^n$ 的一个子空间. (1) $x_1+2x_2+dots.c+n x_n=0$. ] 设 $alpha=vecn(x,n),sp beta=vecn(y,n)$,有: $ (k x_1) + 2(k x_2) + dots.c + n(k x_n) = k (x_1+2x_2+dots.c+n x_n) = 0\ (x_1+y_1) + 2(x_2+y_2) + dots.c + n(x_n+y_n) = (x_1+2x_2+dots.c+n x_n) + (y_1+2y_2+dots.c+n y_n) = 0 $ 所以该线性空间是 $PP^n$ 的子空间. #prob[(2) $x_1x_2 dots.c x_n=0$.] 取 $n=2$,$alpha=display(vec(1,0)),sp beta=display(mat(0,1))$,则 $alpha+beta = display(vec(1,1))$ 不满足条件. 所以该线性空间不是 $PP^n$ 的子空间. #prob[(3) $x_(i+2) = x_(i+1) + 2 x_i, sp i=1,2,dots.c,n-2$.] $ (x_(i+2) + y_(i+2)) = x_(i+1) + 2x_i + y_(i+1) + 2y_i = (x_(i+1) + y_(i+1)) + 2(x_i + y_i)\ (k x_(i+2)) = k(x_(i+1) + 2 x_i) = (k x_(i+1)) + 2(k x_i)\ $ 所以该线性空间是 $PP^n$ 的子空间. = P107 习题四 36 #ac #prob[ 设 $alpha_1=display(mat(1,1,0,0))^TT$,$alpha_2=display(mat(1,0,1,1))^TT$,$beta_1=display(mat(2,-1,3,3))^TT$,$beta_2=display(mat(0,1,-1,-1))^TT$,证明 $L(alpha_1,alpha_2) = L(beta_1,beta_2)$. ] $ &beta_1 = -alpha_1 + 3 alpha_2 quad quad &&beta_2 = alpha_1 - alpha_2\ &alpha_1 = 1/2(beta_1 + 3beta_2) quad quad &&alpha_2 = 1/2(beta_1 + beta_2)\ $ 故向量组 $alpha_1,alpha_2$ 与向量组 $beta_1,beta_2$ 等价,故 $L(alpha_1,alpha_2) = L(beta_1,beta_2)$. = P107 习题四 40 #wa #prob[ 设 $bold(A) = display(mat(1,-2,1,3;9,-5,2,8))$.求一个 $4 times 2$ 矩阵 $bold(B)$,使 $bold(A B) = bold(O)$ 且 $r(bold(B)) = 2$. ] 相当于解齐次线性方程组 $bold(A X) = bold(O)$,对矩阵应用行等列变换得: $ mat( 1,-2,1,3,0; 9,-5,2,8,0; ) &-> mat( 1,-2,1,3,0; 0,13,-7,-19,0; ) -> mat( 1,-2,1,3,0; 0,1,-7/13,-19/13,0; )\ &-> mat( 1,0,-1/13,1/13,0; 0,1,-7/13,-19/13,0; ) $ 故 $display(bold(X)^TT = k_1 mat(1/13,7/13,1,0) + k_2 mat(-1/13,19/13,0,1) )$ 为齐次线性方程组的通解,为使 $r(bold(B))=2$,不妨取: $ bold(B) = mat( 1,7,13,0; -1,19,0,13; )^TT $ #warn[初等行变换算错了!!!] = P107 习题四 41 #ac #prob[ 设 $bold(A) = display(mat(alpha_1,alpha_2,alpha_3))$ 为三阶矩阵.若 $alpha_1,alpha_2$ 线性无关,且 $alpha_3 = -alpha_1 + 2 alpha_2$,求线性方程组 $bold(A X) = bold(O)$ 的通解. ] 设 $bold(X) = display(mat(x_1,x_2,x_3))^TT in PP^3$,则有: $ &x_1 alpha_1 + x_2 alpha_2 + x_3 (-alpha_1 + 2 alpha_2) = theta\ => &(x_1-x_3)alpha_1 + (x_2+ 2x_3) alpha_2 = theta $ 由于 $alpha_1$ 和 $alpha_2$ 线性无关,故只能有 $x_1-x_3=x_2+2x_3=0$,所以 $bold(X) = display(mat(t,-2t,t))^TT, sp t in RR$. = P107 习题四 43 #wa #prob[ 已知行列式 #set math.mat(delim: "|") $ D = mat( a_11,a_12,dots.c,a_(1 n); a_21,a_22,dots.c,a_(2 n); dots.v,dots.v,,dots.v; a_(n 1),a_(n 2),dots.c,a_(n n); ) != 0 $ #set math.mat(delim: "(") 证明 $display(mat(A_11,A_12,dots.c,A_(1 n))^TT)$ 是齐次线性方程组 $ cases( a_21 x_1 + a_22 x_2 + dots.c + a_(2 n) x_n &= 0, a_31 x_1 + a_32 x_2 + dots.c + a_(3 n) x_n &= 0, dots.c, a_(n 1) x_1 + a_(n 2) x_2 + dots.c + a_(n n) x_n &= 0, ) $ 的一个基础解系. ] 代入验证得 $display(mat(A_11,A_12,dots.c,A_(1 n))^TT)$ 是该线性方程组的一个解. 考虑到 $bold(A) in PP^(n times (n-1))$,$r(bold(A))<=n-1$;再由于 $D!=0$,故 $r(bold(A))>=n-1$.故 $r(bold(A))=n-1$. 设 $W$ 为该线性方程组的解空间,则 $dim W = n-r=1$.故 $display(mat(A_11,A_12,dots.c,A_(1 n))^TT)$ 就是该线性方程组的一个基础解系. = P108 习题四 44 #ac #prob[求一个齐次线性方程组,使它的基础解系为 $xi_1=display(mat(0,1,1,2))^TT,sp xi_2 = display(mat(2,1,1,0))^TT$.] 取 $eta_1=display(mat(2,1,1,0))^TT,sp eta_2=display(mat(-1,0,0,1))^TT$,则 $L(eta_1,eta_2) = L(xi_1,xi_2)$,故 $eta_1,eta_2$ 同样是该齐次线性方程组的基础解系.构造如下: $ cases( x_1-2x_3+x_4=0, x_2-x_3=0 ) $ = P108 习题四 49 #pc #prob[ 设 $bold(A) = display(mat(1,-2,3,-4;0,1,-1,1;1,2,0,-3))$,$bold(E)$ 为单位矩阵. (1) 求方程组 $bold(A X) = bold(O)$ 的一个基础解系. ] 对系数矩阵应用初等行变换得: $ mat(1,-2,3,-4;0,1,-1,1;1,2,0,-3) -> mat(1,0,0,1;0,1,0,-2;0,0,1,-3) $ 故其基础解向量为 $alpha=display(mat(-1,2,3,1))^TT$. #prob[(2) 求满足 $bold(A B) = bold(E)$ 的所有矩阵 $bold(B)$.] 设 $bold(B) = display(mat(beta_1,beta_2,beta_3))$,则: $ beta_1 = display((1,0,0,0))^TT + c_1 alpha\ beta_2 = display((0,1,0,0))^TT + c_2 alpha\ beta_3 = display((0,0,1,0))^TT + c_3 alpha\ $ 即: $ bold(B) = mat( 1-c_1,-c_2,-c_3; 2c_1,1+2c_2,2c_3; 3c_1,3c_2,1+3c_3; c_1,c_2,c_3 ) quad (c_1,c_2,c_3 in RR) $ #warn[ 应分别求出特解代入(不能想当然),并且基础解系的系数要相同. ] = P108 习题四 50 #ac #prob[ 已知非齐次线性方程组 $ cases( x_1+x_2+x_3+x_4=-1, 4x_1+3x_2+5x_3-x_4=-1, a x_1+x_2+3x_3+b x_4=1, ) $ 有三个线性无关的解. (1) 证明:方程组的系数矩阵 $bold(A)$ 的秩 $r(bold(A)) = 2$. ] 设 $r(bold(A)) = r$,依题意,应有 $r(bold(A)) = r(overline(bold(A))) = r$.由于其有三个线性无关的解,故解的形式应为: $ bold(X) = eta_0 + k_1 eta_1 + k_2 eta_2 $ 其中,$L(eta_1,eta_2)$ 是 $bold(A X) = bold(O)$ 的基础解系.即:$r(bold(A)) = 4-2 = 2$. #note[不太严谨?] #prob[ (2) 求 $a,b$ 的值及方程组的解. ] $ bold(A) -> mat( 1,1,1,1; 0,-1,1,-8; a-2,0,0,b+3; ) $ 由 (1) 知 $r(bold(A)) = 2$,故 $a=2,b=-3$.方程组的解为: $ bold(X) = mat(-3,2,0,0)^TT + k_1 mat(0,-2,1,0)^TT + k_2 mat(6,-8,0,1)^TT $ = P109 习题四 52 #ac #prob[ 设 $eta_0$ 是非齐次线性方程组的一个解,$eta_1,eta_2,dots.c,eta_t$ 是它的导出组的一个基础解系.令 $ nu_1=eta_0,sp nu_2=eta_1+eta_0,sp dots.c,sp nu_(t+1) = eta_t+eta_0 $ 证明:该线性方程组的任意一个解 $nu$ 都可以写成 $ nu = c_1 nu_1 + c_2 nu_2 + dots.c + c_(t+1) nu_(t+1) $ 其中 $c_1+c_2+dots.c+c_(t+1) = 1$. ] $ nu&=(c_1+c_2+dots.c+c_(t+1))eta_0 + (c_2+c_3+dots.c+c_(t+1))eta_1 + dots.c + (c_(t+1)) eta_t\ &=eta_0 + (c_2+c_3+dots.c+c_(t+1))eta_1 + dots.c + (c_(t+1)) eta_t $ 其中,由于矩阵 $display(mat(1,1,dots.c,1;0,1,dots.c,1;dots.v,dots.v,,dots.v;0,0,dots.c,1)_(n times n))$ 满秩,所以 $ L(seqn(eta,n)) = L(eta_1+eta_2+dots.c+eta_n,eta_2+eta_3+dots.c+eta_n,dots.c+eta_n) $ 即任意一个解都可以被写成上述形式. = P110 补充题四 2 #pc #prob[试证明:$PP^n$ 的任意一个子空间 $W$ 必是某一个 $n$ 元齐次线性方程组的解空间.] 设 $V$ 是 $PP^n$ 在数域 $PP$ 下的线性空间,则 $seqn(xi,n)$ 是其常用基. 设 $dim W = r$,则 $xi_(i_1),xi_(i_2),dots.c,xi_(i_r)$ 是其一组基. 考虑所以满足 $x_j=0\,quad&(j!=i_1 and j!=i_2 and dots.c and j!=i_r)$ 构成的 $n$ 元齐次线性方程组,$W$ 即是其解空间. #note[学习一下答案的做法.] = P175 补充题七 2 #wa #prob[ 设 $V$ 是数域 $PP$ 上的一个 $n$ 维线性空间,试证明:$PP^(n times n)$ 中的可逆矩阵和 $V$ 的基一一对应. ] 设 $seqn(xi,n)$ 是 $V$ 的一组基,取 $bold(A) = vecn(xi,n)$,则 $r(bold(A))=r{seqn(xi,n)}=n$,所以 $bold(A)$ 是可逆矩阵. TBD #note[*为了证明双射,可以分别证明单射和满射.*] #warn[后面的题目难度有点大,在习题课上听了一遍理解了点皮毛,就不具体纠错了.] = P176 补充题七 3 #prob[ 设 $lambda$ 为复数,通常称 $ bold(J) = mat( lambda,1,0,dots.c,0,0; 0,lambda,1,dots.c,0,0; 0,0,lambda,dots.c,0,0; dots.v,dots.v,dots.v,,dots.v,dots.v; 0,0,0,dots.c,lambda,1; 0,0,0,dots.c,0,lambda; )_(n times n) $ 为 $n$ 阶 Jordan 块. (1) 求出所有可与 $bold(J)$ 交换的复矩阵. ] #prob[ (2) 设 $W$ 为由所有可与 $bold(J)$ 交换的复矩阵构成的集合,证明 $W$ 是线性空间 $CC^(n times n)$ 的一个线性子空间,并求其维数. ] #prob[ (3) 证明:如果 $bold(A)$ 与 $bold(J)$ 可交换,那么存在复系数多项式 $f(x)$ 使得 $f(bold(J)) = bold(A)$. ] = P176 补充题七 4 #prob[ 设 $W$ 是 $PP^(n times n)$ 的全体形如 $bold(A B) - bold(B A) sp (A,B in PP^(n times n))$ 的矩阵所生成的子空间,证明:$dim W = n^2-1$. ] = P176 补充题七 6 #prob[ 设 $V_1,V_2,dots.c,V_m$ 均为线性空间 $V$ 的真子空间,证明:存在 $V$ 的一个基,使得其中任一个向量都不在集合 $display(op(union)_(i=1)^m V_i)$ 中. ]
https://github.com/Mouwrice/thesis-typst
https://raw.githubusercontent.com/Mouwrice/thesis-typst/main/jitter_noise/jitter_noise_method.typ
typst
== Method The method presented is based on the prediction of points in the image. The idea is to predict the position of the points in the image based on the previous positions. This prediction is then used to correct the pose estimation. Every incoming point is compared to the predicted position, based on distance. The distance is used to determine if the newly detected point is either caused by jitter or noise, or if it is just caused by the movement of the object. The method principle is best explained with a figure, @predicion-example. Points $A$ to $D$ are the previous positions of the points. Given the previous points, the predicted position $E$ is calculated. The current position $F$, the results returned from the pose estimation, is then compared to the predicted position $E$. If the distance between the predicted position $E$ and the current position $F$ is smaller than some threshold (e.g. the point $F$ would lie in the striped circle around $E$), the current position $F$ is considered to be caused by noise. On the other hand, if the distance is larger than some other threshold (e.g. the point $F$ lies outside the blue circle around $E$), the current position $F$ is considered to be caused by jitter. Only if the distance is between these two thresholds, the current position F is considered to be caused by the movement of the object. Based on this information, the current position $F$ is corrected. $F$ could be entirely discarded and replaced with the predicted position. However, this might lead to abrupt changes in positions. A smoother result is achieved by interposing between the predicted position $E$ and the current position $F$. #figure(caption: [Noise and Jitter reduction method principle. The horizontal axis is the time axis. The vertical axis is the value of the dots. Dots $A$ to $D$ are previous positions, $E$ is the predicted position, $F$ is the current position from MediaPipe.])[ #image("../images/prediction-example.svg") ] <predicion-example> === Prediction One aspect of the method is the prediction of the position of the points. The prediction is based on the previous positions of the points. Since we are dealing with points that are close together in time, a simple linear prediction is sufficient. To further clarify this: we are tracking the movement of a human, of which the movements are non-cyclic and non-deterministic. This means that the movement of the person is not predictable in the long term. However, in the short term (consecutive frames) the movement is somewhat predictable. We expect the movement to be similar for consecutive frames. The higher the framerate the more accurate the prediction can be. Advanced prediction methods are therefore not necessary. Every point has a timestamp $t$ and a value $y$. For every pair of consecutive points $P_1$ $(t_1, y_1)$ and $P_2$ $(t_2, y_2)$ a vector $arrow(v)$ can be computed. The vector $arrow(v)$ is the direction from $P_1$ to $P_2$ with the length of the vector indicating the velocity of the movement: $arrow(v) = (P_2 - P_1) / (t_2 - t_1)$. We divide by the time difference to get the change in value per time unit, which is the velocity. This is done because in a live stream setting, the time difference between frames can vary because of dropped frames, for example. When a new position $P_3$ $(t_3, y_3)$ is returned by MediaPipe, the predicted position $P'_3$ can be calculated by adding the vector $arrow(v)$ to the last known position $P_2$, multiplied by the time difference between $P_2$ and $P_3$: $ P'_3 = P_2 + arrow(v).(t_3 - t_2)$ The predicted position $P'_3$ is then compared to the actual position $P_3$ to determine if the point is caused by noise, jitter, or the movement of the object. The prediction requires keeping a memory of a given amount of previous points. The description above only considers the last 2 points. However, the method can be extended to consider more points. When considering more points, the vector $arrow(v)$ is calculated by averaging the $n$ vectors of all consecutive points stored in memory. This can be done to reduce the effect of noise and jitter in the prediction. However, when too many points are considered, the prediction might not be reactive enough to more sudden changes in the movement of the object. One might also opt for a weighted average, where the most recent points have a higher weight in the average, to give more importance to the most recent points. Using a weighted average has not been tested in this research. === Correction After the prediction has been made, the correction of the current position is done. The correction is based on the distance between the predicted position and the actual position. The distance is calculated using the Euclidean distance. The principle idea of correction has already been discussed above. Small differences in distance indicate noise, large differences indicate jitter. But, instead of discarding these positions, we interpolate between the predicted position and the actual position. Consider the interpolation function $f(x)$, with $x >= 0$ the distance between the predicted position and the actual position to a value between 0 and 1: $f(x): [0, infinity[ -> [0, 1]$. A value of 0 means that the predicted position is used, a value of 1 means that the actual position is used. Take $P$ to be the actual position, $P'$ the predicted position and an interpolation factor $b$. The corrected position is than: $hat(P) = (1 - b).P' + b.P$ . The chosen interpolation function is: $f(x) = e^(-(log_e (x))^2)$, @interpolation-function. Firstly, the function is smooth, to avoid abrupt changes in the corrected position. Secondly, this function is not picked randomly. It has some nice properties. The function remains close to zero for small values of $x$, meaning that the predicted position is mainly used when the distance is small. This is important because small distances indicate noise. The predicted values are assumed to be less noisy than the actual values, as they are based on the previous positions. This noise reduction is why the interpolation should not reach its maximum value of 1 for small distances. The long tail of the function ensures that large distances are not entirely discarded. Because we are not entirely sure if the large distances are caused by jitter or by the movement of the object, we want to keep some of the actual position. Only when the frame rate is higher, the average and expected distance between two consecutive points is smaller. In that case. the interpolation function can be more stringent and more precise at discarding outliers. #figure(caption: [Interpolation function. The horizontal axis is the distance between the predicted position and the actual position. The vertical axis is the interpolation factor. The blue line, $g(x) = x$, is purely a visual aid.])[ #image("../images/interpolation-function.svg") ] <interpolation-function> It is essential to understand the reasoning behind reaching a maximum value of 1. It is perfectly reasonable for the user to perform a movement that is not predicted by the method, without being an outlier. Consider a person who is standing still and suddenly starts walking. The method will predict the person to be standing still. This action by the user is not an outlier, but the method cannot predict the movement. The method should not discard the actual position in this case. Setting the maximum value of the interpolation function to 1 ensures that the actual position is not discarded in such cases. Two parameters are used to tune the parameter function. A first parameter determines the distance at which the interpolation function reaches its maximum value. Call this parameter $d$, the interpolation function becomes: $f(x) = e^(-(log_e (x / d))^2)$. The effect of this parameter is shown in @interpolation-function-d. Note that it not only changes the distance at which the interpolation function reaches its maximum value, but also the steepness of the function. By setting $d$ to a lower value, we lower the acceptable range of movement. This is particularly useful as we are working in the image frame where the positions are already normalized to be between 0 and 1. #footnote[ Remember the `Landmark` type of marker. The positions are normalized to be between 0 and 1. This means that the distance between two points will be, on average, a lot smaller than 1. ] #figure(caption: [Interpolation function with $d = 0.5$. The horizontal axis is the distance between the predicted position and the actual position. The vertical axis is the interpolation factor. The blue line, $g(x) = x$, is purely a visual aid.])[ #image("../images/interpolation-function-d.svg") ] <interpolation-function-d> A second parameter further controls the “tightness” of the interpolation around the maximum value. Call this parameter $s$, the interpolation function becomes: $f(x) = e^(-s.(log_e (x / d))^2)$ and is shown in @interpolation-function-s. The parameter $s$ controls the falloff of the function. A higher value of $s$ means that the function falls off more quickly on both sides of the maximum value. This means that the interpolation is stricter. #figure(caption: [Interpolation function with $d = 0.5$ and $s = 4$. The horizontal axis is the distance between the predicted position and the actual position. The vertical axis is the interpolation factor. The blue line, $g(x) = x$, is purely a visual aid..])[ #image("../images/interpolation-function-s.svg") ] <interpolation-function-s>
https://github.com/Ciolv/typst-template-bachelor-thesis
https://raw.githubusercontent.com/Ciolv/typst-template-bachelor-thesis/main/helper.typ
typst
// Get the page (counter value, not real page number) for a selector // e. g. #page_ref(<lst:hello-world>) #let page_ref(selector) = { locate(loc => { // Get the `location` of the element let element_location = query(selector, loc) .first() .location() // Get the page number, the location lies on link(element_location)[#counter(page).at(element_location).first()] }) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/features_09.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 26-28 stylistic set must be between 1 and 20 // #set text(stylistic-set: 25)
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/zalmy/Z085.typ
typst
Nakloň, Pane, svoj sluch a vyslyš ma, \* lebo som biedny a chudobný. Ochraňuj ma, lebo som ti oddaný; \* zachráň, Bože, svojho sluhu, ktorý dúfa v teba. Zmiluj sa, Pane, nado mnou, \* veď k tebe volám deň čo deň. Obveseľ, Pane, svojho sluhu, \* veď k tebe dvíham svoju dušu. Lebo ty, Pane, si dobrý a láskavý \* a veľmi milostivý voči všetkým, čo ťa vzývajú. Pane, počuj moju modlitbu, \* všimni si hlas mojej úpenlivej prosby. V deň svojho súženia volám k tebe, \* lebo ty ma vyslyšíš. Niet podobného tebe medzi bohmi, Pane, \* a nič sa nevyrovná tvojim dielam. Všetky národy, ktoré si stvoril, prídu k tebe \* a budú sa ti klaňať, Pane, a tvoje meno oslavovať. Lebo si veľký a robíš zázraky, \* iba ty si Boh. Ukáž mi, Pane, svoju cestu \* a budem kráčať v tvojej pravde. Daj, aby moje srdce bolo prosté \* a malo bázeň pred tvojím menom. Celým srdcom ťa chcem chváliť, Pane, Bože môj, \* a tvoje meno oslavovať naveky; Veď si bol ku mne veľmi milostivý \* a vytrhol si ma z najhlbšej priepasti. Bože, pyšní povstali proti mne a tlupa násilníkov mi čiahala na život; \* nechceli ťa mať pred očami. No ty, Pane, si Boh milosrdný a láskavý, \* zhovievavý, veľmi milostivý a verný. Pohliadni na mňa a zľutuj sa nado mnou; \* daj silu svojmu služobníkovi, zachráň syna svojej služobnice. Nech som dôkazom tvojej dobroty, \* aby moji nenávistníci s hanbou videli, že ty, Pane, si mi pomohol \* a že si ma potešil. A znova: Nech som dôkazom tvojej dobroty, \* aby moji nenávistníci s hanbou videli, že ty, Pane, si mi pomohol \* a že si ma potešil.
https://github.com/maucejo/cnam_templates
https://raw.githubusercontent.com/maucejo/cnam_templates/main/src/presentation/_pres-utils.typ
typst
MIT License
#import "@preview/touying:0.5.2": * #import "../common/_colors.typ": * #let _over-title(self: none, title, size) = { let box1 = { box(fill: white, stroke: 1pt + self.store.colors.box, inset: 8pt)[ #set text(size: size, font: "Crimson Pro", weight: "semibold", fill: self.store.colors.blue) #title.first() ] } let box2 = { box(fill: white, stroke: 1pt + self.store.colors.box, inset: 8pt)[ #set text(size: size, font: "Crimson Pro", weight: "semibold", fill: self.store.colors.blue) #title.last() ] } context{ let box1-size = measure(box1).width let box2-size = measure(box2).width box1 let dec = box1-size - box2-size/2.5 if dec < 0cm { dec = box1-size/3 } place(dx: dec, box2) } v(1em) } #let over-title(title, size: 16pt) = touying-fn-wrapper(_over-title.with(title, size)) #let _title-box(self: none, colors, title, subtitle, color-title) = { let title-logo-height = 6.5% let dy = -1.25cm if self.store.composante != "cnam" { title-logo-height= 12% dy = -1.75cm } set image(height: title-logo-height) place(top + right, dx: -1cm, dy: dy, self.store.logo) if type(colors) == color { box(fill: colors, width: 100%, height: 110%)[ #set align(center + horizon) #set text(fill: color-title) #v(-50pt) #title #linebreak() #subtitle ] } else { box[ #colors #let box-title = { box(fill: self.store.colors.primary.transparentize(29%), width: 87%, height: 70%)[ #set align(center + horizon) #set text(fill: color-title) #title #subtitle ] } #place(center + horizon, dy: 1.6cm, box-title) ] } } #let title-box(colors, title: none, subtitle: none, color-title: white) = touying-fn-wrapper(_title-box.with(colors, title, subtitle, color-title))
https://github.com/alex-touza/fractal-explorer
https://raw.githubusercontent.com/alex-touza/fractal-explorer/main/paper/cover.typ
typst
#import "meta.typ": * #set par(leading: 0.5em, justify: false) #align(horizon + center)[ #set par(spacing: 0.5em) #place(top)[ #box(stroke: (bottom: 2pt), inset: 16pt, width: 100%)[ #text(size: 24pt, weight: 900, meta.title, hyphenate: false) #text(size: 16pt, weight: 500, meta.subtitle, hyphenate: false) ] ] #box(outset: (y: 6em), height: 400pt)[ ] #set par(spacing: 1em) #place(bottom)[ #box(stroke: (top: 2pt), inset: 16pt, width: 100%)[ #text(size: 15pt)[ *À<NAME>* 2n <NAME> Institut <NAME> #sym.dash Curs 2024-2025 ] #v(0.5em) #text(size: 13pt)[ 25 d'octubre de 2024 Departament de Matemàtiques #sym.dash <NAME> ] ] ] ] #place(bottom + right, { if not FINISHED { text(size: 18pt, red)[ ESBORRANY #datetime.today().display() ] } else if not CHECKED { text(size: 18pt, orange)[ NO REVISAT #datetime.today().display() ] } v(15em) })
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10880.typ
typst
Apache License 2.0
#let data = ( ("NABATAEAN LETTER FINAL ALEPH", "Lo", 0), ("NABATAEAN LETTER ALEPH", "Lo", 0), ("NABATAEAN LETTER FINAL BETH", "Lo", 0), ("NABATAEAN LETTER BETH", "Lo", 0), ("NABATAEAN LETTER GIMEL", "Lo", 0), ("NABATAEAN LETTER DALETH", "Lo", 0), ("NABATAEAN LETTER FINAL HE", "Lo", 0), ("NABATAEAN LETTER HE", "Lo", 0), ("NABATAEAN LETTER WAW", "Lo", 0), ("NABATAEAN LETTER ZAYIN", "Lo", 0), ("NABATAEAN LETTER HETH", "Lo", 0), ("NABATAEAN LETTER TETH", "Lo", 0), ("NABATAEAN LETTER FINAL YODH", "Lo", 0), ("NABATAEAN LETTER YODH", "Lo", 0), ("NABATAEAN LETTER FINAL KAPH", "Lo", 0), ("NABATAEAN LETTER KAPH", "Lo", 0), ("NABATAEAN LETTER FINAL LAMEDH", "Lo", 0), ("NABATAEAN LETTER LAMEDH", "Lo", 0), ("NABATAEAN LETTER FINAL MEM", "Lo", 0), ("NABATAEAN LETTER MEM", "Lo", 0), ("NABATAEAN LETTER FINAL NUN", "Lo", 0), ("NABATAEAN LETTER NUN", "Lo", 0), ("NABATAEAN LETTER SAMEKH", "Lo", 0), ("NABATAEAN LETTER AYIN", "Lo", 0), ("NABATAEAN LETTER PE", "Lo", 0), ("NABATAEAN LETTER SADHE", "Lo", 0), ("NABATAEAN LETTER QOPH", "Lo", 0), ("NABATAEAN LETTER RESH", "Lo", 0), ("NABATAEAN LETTER FINAL SHIN", "Lo", 0), ("NABATAEAN LETTER SHIN", "Lo", 0), ("NABATAEAN LETTER TAW", "Lo", 0), (), (), (), (), (), (), (), (), ("NABATAEAN NUMBER ONE", "No", 0), ("NABATAEAN NUMBER TWO", "No", 0), ("NABATAEAN NUMBER THREE", "No", 0), ("NABATAEAN NUMBER FOUR", "No", 0), ("NABATAEAN CRUCIFORM NUMBER FOUR", "No", 0), ("NABATAEAN NUMBER FIVE", "No", 0), ("NABATAEAN NUMBER TEN", "No", 0), ("NABATAEAN NUMBER TWENTY", "No", 0), ("NABATAEAN NUMBER ONE HUNDRED", "No", 0), )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/footnote-refs_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Forward reference Usage @fn \ Definition #footnote[Hi]<fn>
https://github.com/buxx/cv
https://raw.githubusercontent.com/buxx/cv/master/src/utils.typ
typst
#let img(name, size: 10.0pt) = { box(width: size, image("../src/" + name + ".png")) }
https://github.com/augustebaum/epfl-thesis-typst
https://raw.githubusercontent.com/augustebaum/epfl-thesis-typst/main/example/tail/biblio.typ
typst
MIT License
// \cleardoublepage // \phantomsection // % ************* The working stuff ************* // % Print the bibliography just here #bibliography("references.bib", style: "apa") // \addcontentsline{toc}{chapter}{Bibliography}
https://github.com/typst-community/glossarium
https://raw.githubusercontent.com/typst-community/glossarium/master/README.md
markdown
MIT License
# Typst glossary > [!TIP] > Glossarium is based in great part of the work of [<NAME>](https://github.com/Dherse) from his master thesis available at: <https://github.com/Dherse/masterproef>. His glossary is available under the MIT license [here](https://github.com/Dherse/masterproef/blob/main/elems/acronyms.typ). Glossarium is a simple, easily customizable typst glossary inspired by [LaTeX glossaries package](https://www.ctan.org/pkg/glossaries) . You can see various examples showcasing the different features in the `examples` folder. ![Screenshot](.github/example.png) ## Manual ## Fast start ```typ #import "@preview/glossarium:0.5.0": make-glossary, register-glossary, print-glossary, gls, glspl #show: make-glossary #let entry-list = ( ( key: "kuleuven", short: "KU Leuven" long: "Katholieke Universiteit Leuven" description: "A university in Belgium." ), // Add more terms ) #register-glossary(entry-list) // Your document body #print-glossary( entry-list ) ``` ### Import and setup This manual assume you have a good enough understanding of typst markup and scripting. For Typst 0.6.0 or later import the package from the typst preview repository: ```typ #import "@preview/glossarium:0.5.0": make-glossary, register-glossary, print-glossary, gls, glspl ``` For Typst before 0.6.0 or to use **glossarium** as a local module, download the package files into your project folder and import `glossarium.typ`: ```typ #import "glossarium.typ": make-glossary, register-glossary, print-glossary, gls, glspl ``` After importing the package and before making any calls to `gls`,` print-glossary` or `glspl`, please ***MAKE SURE*** you add this line ```typ #show: make-glossary ``` > *WHY DO WE NEED THAT ?* : In order to be able to create references to the terms in your glossary using typst ref syntax `@key` glossarium needs to setup some [show rules](https://typst.app/docs/tutorial/advanced-styling/) before any references exist. This is due to the way typst works, there is no workaround. > >Therefore I recommend that you always put the `#show: ...` statement on the line just below the `#import` statement. ### Registering the glossary First we have to define the terms. A term is a [dictionary](https://typst.app/docs/reference/types/dictionary/) as follows: | Key | Type | Required/Optional | Description | | ------------- | ----------------- | ----------------- | -------------------------------------------------------------------------------------------- | | `key` | string | required | Case-sensitive, unique identifier used to reference the term. | | `short` | string | semi-optional | The short form of the term replacing the term citation. | | `long` | string or content | semi-optional | The long form of the term, displayed in the glossary and on the first citation of the term. | | `description` | string or content | optional | The description of the term. | | `plural` | string or content | optional | The pluralized short form of the term. | | `longplural` | string or content | optional | The pluralized long form of the term. | | `group` | string | optional | Case-sensitive group the term belongs to. The terms are displayed by groups in the glossary. | ```typ #let entry-list = ( // minimal term ( key: "kuleuven", short: "<NAME>" ), // a term with a long form and a group ( key: "unamur", short: "UNamur", long: "Namur University", group: "Universities" ), // a term with a markup description ( key: "oidc", short: "OIDC", long: "OpenID Connect", description: [ OpenID is an open standard and decentralized authentication protocol promoted by the non-profit #link("https://en.wikipedia.org/wiki/OpenID#OpenID_Foundation")[OpenID Foundation]. ], group: "Acronyms", ), // a term with a short plural ( key: "potato", short: "potato", // "plural" will be used when "short" should be pluralized plural: "potatoes", description: [#lorem(10)], ), // a term with a long plural ( key: "dm", short: "DM", long: "diagonal matrix", // "longplural" will be used when "long" should be pluralized longplural: "diagonal matrices", description: "Probably some math stuff idk", ), ) ``` Then the terms are passed as a list to `register-glossary` ```typ #register-glossary(entry-list) ``` ### Printing the glossary Now, you can display the glossary using the `print-glossary` function. ```typ #print-glossary(entry-list) ``` By default, the terms that are not referenced in the document are not shown in the glossary, you can force their appearance by setting the `show-all` argument to true. You can also disable the back-references by setting the parameter `disable-back-references` to `true`. By default, group breaks use `linebreaks`. This behaviour can be changed by setting the `user-group-break` parameter to `pagebreak()`, or `colbreak()`, or any other function that returns the `content` you want. You can call this function from anywhere in your document. ### Referencing terms. Referencing terms is done using the key of the terms using the `gls` function or the reference syntax. ```typ // referencing the OIDC term using gls #gls("oidc") // displaying the long form forcibly #gls("oidc", long: true) // referencing the OIDC term using the reference syntax @oidc ``` #### Handling plurals You can use the `glspl` function and the references supplements to pluralize terms. The `plural` key will be used when `short` should be pluralized and `longplural` will be used when `long` should be pluralized. If the `plural` key is missing then glossarium will add an 's' at the end of the short form as a fallback. ```typ #glspl("potato") ``` Please look at the examples regarding plurals. #### Overriding the text shown You can also override the text displayed by setting the `display` argument. ```typ #gls("oidc", display: "whatever you want") ``` ## Final tips I recommend setting a show rule for the links to that your readers understand that they can click on the references to go to the term in the glossary. ```typ #show link: set text(fill: blue.darken(60%)) // links are now blue ! ```
https://github.com/An-314/Note-of-Quantum_Mechanics
https://raw.githubusercontent.com/An-314/Note-of-Quantum_Mechanics/main/main.typ
typst
#import "@local/mytemplate:1.0.0": * #import "@preview/physica:0.9.2": * #show: project.with( template: "book", title: "量子力学", authors: ( "Anzreww", ), time: "甲辰春夏于清华园", contents: true, content_depth:3, ) #pagebreak(weak: true) #include "chap1.typ" #pagebreak(weak: true) #include "chap2.typ" #pagebreak(weak: true) #include "chap3.typ" #pagebreak(weak: true) #include "chap4.typ" #pagebreak(weak: true)
https://github.com/Doublonmousse/pandoc-typst-reproducer
https://raw.githubusercontent.com/Doublonmousse/pandoc-typst-reproducer/main/package_not_found/ctheorems.typ
typst
#import "@preview/ctheorems:1.1.2": * #show: thmrules
https://github.com/Dherse/typst-brrr
https://raw.githubusercontent.com/Dherse/typst-brrr/master/samples/CeTZ/main.typ
typst
#import "@preview/cetz:0.0.1" #set page(width: auto, height: auto) #show math.equation: block.with(fill: white, inset: 1pt) #cetz.canvas(length: 3cm, { import cetz.draw: * set-style( mark: (fill: black), stroke: (thickness: 0.4pt, cap: "round"), arc: ( radius: 0.3, mode: "PIE", fill: green.lighten(80%), stroke: (paint: green.darken(50%)) ), content: (padding: 1pt) ) grid((-1.5, -1.5), (1.4, 1.4), step: 0.5, stroke: gray + 0.2pt) circle((0,0), radius: 1) line((-1.5, 0), (1.5, 0), mark: (end: ">")) content((), $ x $, anchor: "left") line((0, -1.5), (0, 1.5), mark: (end: ">")) content((), $ y $, anchor: "bottom") for (x, ct) in ((-1, $ -1 $), (-0.5, $ -1/2 $), (1, $ 1 $)) { line((x, 3pt), (x, -3pt)) content((), anchor: "above", ct) } for (y, ct) in ((-1, $ -1 $), (-0.5, $ -1/2 $), (0.5, $ 1/2 $), (1, $ 1 $)) { line((3pt, y), (-3pt, y)) content((), anchor: "right", ct) } // Draw the green angle arc((0,0), start: 0deg, stop: 30deg, anchor: "origin", name: "arc") content((15deg + 4deg, 0.2), text(green)[#sym.alpha]) line((0,0), (1, calc.tan(30deg))) set-style(stroke: (thickness: 1.2pt)) line((30deg, 1), ((), "|-", (0,0)), stroke: (paint: red), name: "sin") content("sin", text(red)[$ sin alpha $], anchor: "right") line("sin.end", (0,0), stroke: (paint: blue), name: "cos") content("cos", text(blue)[$ cos alpha $], anchor: "top") line((1, 0), (1, calc.tan(30deg)), name: "tan", stroke: (paint: orange)) content("tan", $ text(#orange, tan alpha) = text(#red, sin alpha) / text(#blue, cos alpha) $, anchor: "left") }) #cetz.canvas({ import cetz.draw: * let chart(..values, name: none) = { let values = values.pos() let offset = 0 let total = values.fold(0, (s, v) => s + v.at(0)) let segment(from, to) = { merge-path(close: true, { line((0, 0), (rel: (-360deg * from, 1))) arc((), start: from * -360deg, stop: to * -360deg, radius: 1) }) } group(name: name, { stroke((paint: black, join: "round")) let i = 0 for v in values { fill(v.at(1)) let value = v.at(0) / total // Draw the segment segment(offset, offset + value) // Place an anchor for each segment anchor(v.at(2), (offset * -360deg + value * -180deg, .75)) offset += value } }) } // Draw the chart chart((10, red, "red"), (3, blue, "blue"), (1, green, "green"), name: "chart") set-style(mark: (fill: white, start: "o", stroke: black), content: (padding: .1)) // Draw annotations line("chart.red", ((), "-|", (2, 0))) content((), [Red], anchor: "left") line("chart.blue", (1, 1), ((), "-|", (2,0))) content((), [Blue], anchor: "left") line("chart.green", ((), "-|", (2,0))) content((), [Green], anchor: "left") })
https://github.com/Shedward/dnd-charbook
https://raw.githubusercontent.com/Shedward/dnd-charbook/main/dnd/game/spells.typ
typst
#import "../core/core.typ": * // Cast time #let action = [A] #let bonusAction = [B] #let reaction = [Re] // Durations #let instant = [Inst.] #let round(r) = str(r) + [r] #let minute(m) = str(m) + [m] #let hour(h) = str(h) + [h] #let always = sym.infinity // Cast type #let ritual = [R] #let concentration = [C] // School #let abjuration = "Abjuration" #let conjuration = "Conjuration" #let necromancy = "Necromancy" #let evocation = "Evocation" #let transmutation = "Transmutation" #let divination = "Divination" #let enchantment = "Enchantment" #let illusion = "Illusion" // Preparation #let alwaysPrepared = sym.infinity #let preparing = { box(circle(radius: paddings(1), stroke: strokes.thin)) } #let freePreparation(body, count: 1) = [ #body\ #spellCaption[#count free] ] // Range #let self = [Self] #let touch = [Touch] #let rangeDescr(range) = if (range == 0) [ #self ] else [ #(range)ft ] #let countDescr(count) = if (count>1) [#sym.times#count] else [] #let mile(m) = 5279 * m #let target(range, count: 1) = [#(rangeDescr(range))#icon("target")#countDescr(count)] #let point(range, count: 1) = [#(rangeDescr(range))#icon("point")#countDescr(count)] #let area(iconName) = (size, range: 0) => [#(rangeDescr(range))/#(size)ft#icon(iconName)] #let circle = area("circle") #let square = area("square") #let cube = area("cube") #let sphere = area("sphere") #let straightLine = area("arrow-right") #let volume(size) = [#(size)ft#icon("cube")] // Sources #let class = [Class] #let race = [Race] #let story = [Story] #let cantrip = ( name: subsection[Cantrip], slots: none ) #let spellSlots(count) = box(framed(checkboxes(count), stroke: strokes.normal)) #let spellLevel( level, slots: none ) = ( name: subsection[Level #level], slots: spellSlots(slots) ) #let spell( name, prep: none, school: none, castTime: action, castType: none, duration: none, range: none, components: none, source: class, body ) = ( prep: prep, name: name, school: school, castTime: castTime, castType: castType, duration: duration, range: range, components: components, source: source, body: body ) #let atHigherLevels(body) = emph[(Lvl~up:~#body)] #let required(body) = [ Req.: #underline(text(weight: "bold", body)) ]
https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst
https://raw.githubusercontent.com/TJ-CSCCG/tongji-undergrad-thesis-typst/main/.github/ISSUE_TEMPLATE/feat_request.md
markdown
MIT License
--- name: Feature 建议 about: 通过该 Issue 模板反馈向 tongji-undergrad-thesis-typst 提供需要新增的 feature 的具体信息 labels: 'type/feature' --- ### 新增特性类型 <!--点选下方的特性类型--> * [ ] 构建相关(如需要提供新的构建方法,现有构建方式需要迭代重构等) * [ ] 模板功能相关(如需要模板提供其他实用功能,适配新的模板样式等) * [ ] 文档相关(如更好展现该模板使用方法的想法) ### 特性描述 <!--在这里描述新增特性本身及其重要性。如果可能的话,还希望能够描述新增特性的实现方案--> ### 其他信息 <!--这里用于写有关于上述特性的其他想法-->
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-02.typ
typst
Other
// Error: 3-26 value is too large #(9223372036854775807 + 1)
https://github.com/flechonn/typst
https://raw.githubusercontent.com/flechonn/typst/main/data/doc2.typ
typst
= 1. Exercice : Résoudre une équation quadratique. Solution : $x = (-b ± √(b²-"4ac")) / 2a$ Niveau d'indice : Avancé = 2. Exercice : Calculer la dérivée d'une fonction polynomiale. Solution : $f'(x) = n*a*x^(n-1)$ Niveau d'indice : Intermédiaire
https://github.com/chamik/gympl-skripta
https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-dila/6-promena.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/helper.typ": dilo #dilo("Proměna", "promena", "Franz Kafka", "V. Kafka", "1. pol 20. st", "Praha/Rakousko", "1915", "epika", "povídka/novela") #columns(2, gutter: 1em)[ *Téma*\ Abusrdní situace Řehoře Samsy. *Motivy*\ beznaděj, smíření, absurdita, samota *Časoprostor*\ rodinný byt, doba autora *Postavy* \ _<NAME>_ -- obchodní cestující, brouk \ _Markéta_ -- řehořova sestra \ _řehořův otec a matka_ \ _Gréta_ -- posluhovačka *Kompozice* -- chronologická, tři kapitoly *Vypravěč* -- er-forma *Jazykové prostředky*\ spisovný jazyk, strohé (úřednické) vyjadřování, eufemismy #colbreak() *Obsah*\ <NAME> se jednoho dne probudí jako brouk, lol. Jeho první starotí je, jak se jako hmyz dostane do práce. Během celé doby nepropadá depresím a uvažuje racionálně. Otec musí znovu nastoupit do zaměstnání. Do jeho pokoje chodí jen jeho sestra, před kterou se schovává pod pohovkou. Při hádce o svůj oblíbený obraz ho spatří matka a omdlí, otec ho zraní vrhnutým jablkem. Jak se zhoršuje řehořův zdravotní stav, zhoršuje se i atmosféra a finanční situace rodiny. Markétka navrhuje se řehoře zbavit. Do bytu se nastěhují podnájemníci, kteří o Řehořovi neví. Podají ovšem okamžitou výpověď, když vyjde z pokoje ven, aby si poslechl, jak jeho sestra hraje na housle. Otcem je zahnán zpět do pokoje a nad ránem osamocený umírá. Najde ho posluhovačka, která ho sama odklidí. Rodině se uleví a vydávají se na výlet do města, probíraje nadějné plány do budoucna. *Literárně historický kontext*\ Přažská německá literatura. Vztah s jeho otcem byl velmi komplikovaný. ] #pagebreak() *Ukázka* Když se <NAME> jednou ráno probudil z nepokojných snů, shledal, že se v posteli proměnil v jakýsi nestvůrný hmyz. Ležel na hřbetě tvrdém jak pancíř, a když trochu nadzvedl hlavu, uviděl své vyklenuté, hnědé břicho rozdělené obloukovitými výztuhami, na jehož vrcholu se sotva ještě držela přikrývka a tak tak že úplně nesklouzla dolů. Jeho četné, vzhledem k ostatnímu objemu žalostně tenké nohy se mu bezmocně komíhaly před očima. Co se to se mnou stalo? pomyslel si. Nebyl to sen. Jeho pokoj, správný, jen trochu příliš malý lidský pokoj, spočíval klidně mezi čtyřmi dobře známými stěnami, Nad stolem, na němž byla rozložena vybalená kolekce vzorků soukenného zboží - Samsa byl obchodní cestující -, visel obrázek, který si nedávno vystřihl z jednoho ilustrovaného časopisu a zasadil do pěkného pozlaceného rámu. Představoval dámu, opatřenou kožešinovou čapkou a kožešinovým boa, jak vzpřímeně sedí a nastavuje divákovi těžký kožešinový rukávník, v němž se jí ztrácí celé předloktí. [...] "Rozuměli jste jediné slovo?" ptal se prokurista rodičů, "snad si z nás nedělá blázny?" "Proboha," zvolala už matka s pláčem, "třeba je těžce nemocen a my ho tu trápíme. Markétko! Markétko!" zvolala pak. "Co je, maminko?" volala sestra z druhé strany. Domlouvaly se přes Řehořův pokoj. "Musíš okamžitě k lékaři. Řehoř je nemocen. Honem pro lékaře. Slyšelas teď, jak Řehoř mluví?" "To byl zvířecí hlas," řekl prokurista nápadně tiše ve srovnání s matčiným křikem. "Anno! Anno!" volal otec skrz předsíň do kuchyně a zatleskal, "ihned běžte pro zámečníka!" A už proběhla obě děvčata s šustícími sukněmi předsíní - jak se dokázala sestra tak rychle ustrojit? - a vyrazila z bytu. Ani nebylo slyšet bouchnout dveře; snad je nechaly otevřené, jak to bývá v bytech, kde se stalo velké neštěstí. [...] "Tak," řekl Řehoř a dobře si uvědomoval, že je jediný, kdo zachoval klid, "ihned se obléknu, sbalím kolekci a pojedu. Chcete ještě, chcete ještě, abych jel? Tak vidíte, pane prokuristo, nejsem umíněný a pracuji rád; s cestováním je svízel, ale já bych bez cestování nemohl žít. Kampak jdete, pane prokuristo? Do obchodu? Ano? Povíte tam všechno podle pravdy? Může se stát, že člověk není momentálně schopen pracovat, ale to je zrovna pravá chvíle, aby se vzpomnělo na jeho dřívější výkony a uvážilo se, že později, až se překážky odstraní, bude jistě pracovat s tím větší pílí a soustředěním... " #pagebreak()
https://github.com/xrarch/books
https://raw.githubusercontent.com/xrarch/books/main/xrcomputerbook/chapintro.typ
typst
#import "@preview/tablex:0.0.6": tablex, cellx, colspanx, rowspanx = Overview == Introduction The XR/computer platform is a general hardware design that is shared by the XR/station uniprocessor desktop workstation, and the XR/MP multiprocessor deskside server. The platform is designed around the 32-bit XR/17032 RISC microprocessor, which itself is described in the _XR/17032 Architecture Handbook_. This document describes the platform as it is seen from the perspective of a system software writer; that is, details such as physical design and electrical characteristics are not discussed. The product range encompassed by the XR/computer platform consists of: #tablex( columns: (1fr, 1fr), auto-vlines: false, cellx([ #set text(fill: white) #set align(center) *XR/MP* ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *XR/station* ], fill: rgb(0,0,0,255)), [Deskside Server], [Desktop Workstation], [\$30K-120K], [\$8K-30K], [2-4 XR/17032 CPUs \@ 25 MHz], [1 XR/17032 CPU \@ 20 MHz], [8MB-128MB RAM], [4MB-64MB RAM], [1-8 200MB-1GB Hard Disks], [1-2 200MB-1GB Hard Disks], cellx([ #set align(center) 1024x768 \@ 8-bit Color ], colspan: 2), ) #set align(center) #image("xrcomputersabstract.png", width: 80%) #set align(left) #pagebreak(weak: true) == Machine Organization A simplified diagram of the XR/computer platform follows: #image("xrcomputer.svg") Note that this diagram shows a four-processor XR/MP 1500 model, the maximum extent of what an XR/computer based machine may contain. The actual models implement only a subset of this: 1. XR/station contains only one processor module, and entirely lacks an S-cache. There is only physical space for up to 4 hard disks. Finally, there are only two slots for memory sticks, limiting the machine to 64MB. 2. The XR/MP 1000 model contains only two processor modules, with a 128KB S-cache. The Kinnow framebuffer card is part of the default configuration of all models, and is therefore described in this document, but can be excluded by order if the customer only requires a headless machine (for a discount!). Note that since the XR/17032 architecture specifies accesses to physical addresses above 0xC0000000 (3GB) to be noncached, all memory mapped device registers are placed above this address by this platform. Additionally, the machine is entirely little-endian. #box([ == Memory There is a memory subsystem which contains up to 4 slots that may each hold one memory stick. A memory stick can have a capacity of 4MB, 8MB, 16MB, or 32MB. The slots are sequentially placed into the physical address space at offsets of 32MB starting at address zero, and the contents of a single stick are presented in a physically contiguous manner beginning at the base of the slot area. That is, the zeroth slot resides at 0x00000000, the first slot resides at 0x02000000, the second is at 0x04000000, etc. This creates a 128MB region in the low physical address space in which memory can be found. ]) Memory sticks need not be placed into the slots in a manner that is physically contiguous. For instance, it is possible to place a 4MB stick in slot 0 and another 4MB stick in slot 1, leaving a 28MB gap inbetween them in the physical address space. The system software will deal with this correctly. However, slot 0 must always contain some memory for use by the system ROM code. === Probing the Size of Memory Accesses to empty memory slots will produce bus error exceptions after a short timeout. Therefore, the size of the memory stick in each slot (or absence thereof) can be determined by probing along the slot area until either the end of the slot is reached or a bus error occurs. Note that the system PROM code will do this automatically, and should be consulted to acquire a map of physical memory at boot time if required. == System PROM The 128KB system PROM is placed into the final 128KB of the physical address space (starting at 0xFFFE0000) and contains the reset vector for the XR/17032 microprocessor. This is the first code that runs in the system during startup and is responsible for presenting a simple interface that allows the user to select a boot device, and for booting the operating system.#footnote([The _A4X_ boot firmware contained within the system PROM is described in the document _A4X Firmware Manual_.]) == NVRAM Beginning at 0xF8001000, there is a small 4KB battery-backed non-volatile RAM (NVRAM). This is used by the boot firmware to store certain persistent variables, such as the user's preferred boot device. == S-cache The secondary cache, or S-cache, is only found on multiprocessor XR/computer systems. It is a large cache of recently accessed memory, which is much faster to access than the main DRAM but is still significantly slower than the on-chip primary caches aboard the XR/17032 microprocessors (which can be accessed in a single cycle). It is also used as a single source of truth by the cache coherency protocol. There is no way to directly access the S-cache, and its existence is completely transparent to system software, as it is kept coherent with external device activity via a snooping write-update scheme. However, the primary caches are not kept coherent with the S-cache or with the rest of the system's autonomous activity (i.e. DMA) and must be manually invalidated by system software in certain situations. == Expansion Slots There are 7 slots for expansion cards which can be inserted into an XR/computer system to extend its functionality. Each slot is mapped sequentially into the physical address space at offsets of 128MB beginning at 0xC0000000, and accesses into these 128MB regions are serviced directly by the card. If a card is not present in a slot, an access will result in a short timeout followed by a bus error exception. This can be used to detect if a card is present in a slot or not. Each slot has only one interrupt line, whose IRQ number is 0x28 + N where N is the slot number from [0, 6]. The usage of this interrupt line is up to the logic on the card. Additionally, the layout and function of the slot space is completely the province of the hardware on the card, except that it must present the following read-only data structure starting at offset zero within its slot space: ``` STRUCT SlotInfo // The 32-bit magic number must read 0x0C007CA1. Magic : ULONG, // The 32-bit board ID number indicates the type of the board. BoardId : ULONG, // A 15-character, null-terminated string containing a human readable // name for the board. Name : UBYTE[16], // 232 reserved bytes for future expansion. Reserved : UBYTE[232], END ``` The following is a table of the currently defined board identifiers: #tablex( columns: (0.8fr, 1fr, 1fr), align: center, cellx([ ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *BoardId* ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *Name* ], fill: rgb(0,0,0,255)), [Kinnow Framebuffer], [0x4B494E36], [kinnowfb,8], ) == Reset Register Writing the magical 32-bit value 0xAABBCCDD into the "reset register" located at 0xF8800000 will assert the reset line on the bus for several cycles, inducing all devices to enter a quiescent (i.e. non-interrupting) state. Nothing else about the state of the devices may be assumed except that they will not produce an interrupt until again instructed that they may do so, in whatever device-specific manner. Expansion cards must be sure to respect this. Note that this is already done by the system PROM at startup time and need not be done again under normal circumstances. == Revision Register Reading from the "revision register" located at 0xF8000800 yields a 32-bit revision code for the motherboard which is divided into two 16-bit components. The upper 16 bits indicate the "major" revision, and the low 16 bits indicate the "minor" revision.
https://github.com/Wuvist/lcpc
https://raw.githubusercontent.com/Wuvist/lcpc/main/rental.typ
typst
#import "@preview/tablex:0.0.8": tablex, colspanx, rowspanx #let c(body) = { set text(font: "Microsoft YaHei") body } #figure( tablex( columns: 5, align: center + horizon, auto-vlines: false, [*#c("年度")*], [], [*#c("公屋")*], [*#c("居屋")*], [*#c("私人住宅")*], rowspanx(5)[2009\ / \ 2010], [#c("平均房租开支")], [1,116], [5,969], [9,573], [#c("月开支平均数")], [10,569], [19,288], [28,715], [#c("月收入中位数")], [10,550], [19,750], [24,250], [#c("支出 / 收入比")], [1.00], [0.98], [1.18], [#c("支出 / 收入比(不计房租)")], [0.90], [0.67], [0.80], rowspanx(5)[2014\ / \ 2015], [#c("平均房租开支")], [1,576], [8,982], [13,582], [#c("月开支平均数")], [13,275], [26,075], [36,728], [#c("月收入中位数")], [14,050], [25,000], [31,550], [#c("支出 / 收入比")], [0.94], [1.04], [1.16], [#c("支出 / 收入比(不计房租)")], [0.83], [0.68], [0.73], rowspanx(5)[2019\ / \ 2000], [#c("平均房租开支")], [1,701], [10,100], [15,218], [#c("月开支平均数")], [15,018], [27,631], [37,895], [#c("月收入中位数")], [18,250], [28,400], [38,900], [#c("支出 / 收入比")], [0.82], [0.97], [0.97], [#c("支出 / 收入比(不计房租)")], [0.72], [0.61], [0.58], ), kind: table, caption: c("香港不同住宅类型家庭月开支与收入一览") )
https://github.com/kazewong/lecture-notes
https://raw.githubusercontent.com/kazewong/lecture-notes/main/Engineering/SoftwareEngineeringForDataScience/lab/frontend.typ
typst
#set page( paper: "us-letter", header: align(center, text(17pt)[ *Frontend design* ]), numbering: "1", ) #import "./style.typ": style_template #show: doc => style_template(doc,) = Foreword In this session, we are going to learn about how to build a modern web app frontend with `Svelte`, a Javascript framework that is most beloved by the community during the time of writing. This is probably the most important part of this course. One reason is because the frontend is what your users see and interact with, so by extension it is what your user care. No matter how great your package is, if the user cannot use it or do not want to use it, it is not a good software. I am over commiting the term "frontend" here, because I am not only talking about the user interface, but also the user experience. The user interface is what the user see, while the user experience is how the user feel when they are using your software. A lot of scientific software do not aim to have a web frontend to it, and that is completely legitimate since the targeted users are other scientists and researchers who will look into their code. Nonetheless, a good user experience is not excusable even for the packages that do not require a web frontend. Another reason, perhaps a more legitimate reason, is because there are simply too many options to build your frontend. There are many javascript frameworks to choose from, `React`, `Angular`, `Vue` are the top three javascript frames, and I have dealt with all three of them. You can also write your frontend with `rust`, and there are frameworks like `yew`, `leptos`, `dioxus`. Recently `python` make a big splash in frontend development because of `FastHTML`. This list goes on and on. Then once your are done with choosing your javascript frameworks, it is time to choose your CSS framework. There are `Bootstrap`, `Tailwind`, `Material-UI` just to name a few. *Then*, you can choose your *metaframework* to handle routing and bundle your website, popular choices are `Next.js`, `Gatsby`, `Nuxt.js`, and here we go again. The point is, there are way too many choices, and I have spent so many hours just crawling through this holy war battlefield to try to build my frontend for some projects. In the end, it does not matter to the customer what framework you choose, as long as it works and it looks good, it is a good frontend. The reason I think this session is the most important one, it is because it has the biggest margin of time saving for you. Out of all the experience, I find `Svelte` to be the most fun to work with, and can convert what I think into what I see the most efficiently, so we are going to stick with the `Svelte` framework. = Key concept There are 3 main components in building a frontend: HTML, CSS, and Javascript. HTML defines the structure and content of the web page, CSS defines the style of the web page, and Javascript defines the interactivity of the web page. == Basic HTML HTML stands for Hyper Text Markup Language. It is where your content goes. You can just write in HTML and open it in your browser, and you will see your content. A minimal HTML file looks like this: ```html <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph.</p> </body> </html> ``` Trying opening this in your browser, you will see a heading and a paragraph. There are many tags in HTML and you can go very far with just HTML. You can find references of HTML tags in #link("https://www.w3schools.com/html/default.asp")[W3Schools], but these days it is probably easier to just ask ChatGPT. == Styling with tailwind CSS While HTML gives you the functionality of the webpage, it does not give you the style. Here is where CSS comes in. CSS stands for Cascading Style Sheets, and it defines the style of the webpage, which includes the color, the font, the size, the position of the elements, etc. A minimal CSS file looks like this: ```css body { background-color: lightblue; } h1 { color: white; text-align: center; } p { font-family: verdana; font-size: 20px; } ``` You can include this CSS file in your HTML file like this: ```html <!DOCTYPE html> <html> <head> <title>Page Title</title> <link rel="stylesheet" href="styles.css"> </head> <body> ... ``` However, keeping track of CSS in a separate file means you have to go back and fro to change the style of a particular element. To make this easier, people have made a number of CSS frameworks that helps the process. I personally uses `Tailwind CSS` because it is very easy to use and it keeps the style in the HTML file, so you can see the style of the element right next to the element. Here is an example of how you can use `Tailwind CSS` (Add `<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">` to the head of your HTML file): ```html <h1 class="text-4xl text-center text-blue-500">This is a Heading</h1> <p class="font-sans text-lg">This is a paragraph.</p> ``` == Javascript with Svelte Finally we arrive at Javascript, which is where the interactivity of the webpage comes from. You can add interactivity to our HTML example like this: ```html <!DOCTYPE html> <html> <head> <title>Page Title</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph.</p> <button onclick="myFunction()">Click me</button> <script> function myFunction() { alert("Hello World!"); } </script> </body> </html> ``` This will create a button that when clicked, will show an alert box with the message "Hello World!". Fundamentally Javascript is a language, but really when you hear about Javascript these days, it is more a discussion around which Javascript framework people are using. `React`, `Angular`, `Vue` are the big three in terms of popularity. I used to use `React` and `Vue` for my website, but I always felt like I don't like them as much as I want to, and there were something not quite right when I use them. Then I found `Svelte`, which is a Javascript framework that is most beloved by the community during the time of writing. `Svelte` is a compiler that takes your code and compiles it into vanilla Javascript, HTML, and CSS. So in a sense you are not strictly writing Javascript, but you are writing Svelte, and this can be seen as you will write file with `.svelte` extension instead of `.js` extension. A minimal Svelte file looks like this: ```html <script> let name = 'world'; </script> <h1>Hello {name}!</h1> ``` Isn't this simple? We will go through the basic of Svelte in the next section. = Buidling your website with SvelteKit == Setting up the project Make sure you have `node` and `npm` installed on your machine. You can check if you have them installed by running `node -v` and `npm -v` in your terminal. If you don't have them installed, you can download them from #link("https://nodejs.org/en/download/")[here]. Then you should be able to find the step by step guide for this tutorial on #link("https://github.com/KazeClasses/svelte_guide/tree/main")[this repository]. == Write a Hero page for yourself In this session, we are going to write a simple hero page for yourself. A hero page is the first page that the user sees when they visit your website. We are going to write a simple hero page that explores a number of svelte features following the steps below: === Defining and using a variable The first thing we are going to do is to checkout the basic of writing a svelte file such as defining variables and showing them to the user. Look at your `src/routes/+page.svelte` file, and you should see some bolier plate codes like: ```html <h1>Welcome to SvelteKit</h1> <p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p> ``` Replace them with the following code: ```html <script> let name = 'world'; </script> <h1>Hello {name}!</h1> ``` If you have `npm run dev` running in your terminal, you should see the changes in your browser. You should see a heading that says "Hello world!". You can change the value of `name` to anything you want, and the heading will change accordingly. === Importing components Sometimes you may find yourself reusing the same code in different places. In this case, you can create a component and reuse it. And you may find yourself wanting to pass some data to the component. In this case, you can use props. Let's create a component that takes a `name` prop and display it. Create a new file `src/components/Hello.svelte` and write the following code: ```html <script> export let name; </script> <h1>Hello {name}!</h1> ``` Then you can use this component in your `src/routes/+page.svelte` file like this: ```html <script> import Hello from '$lib/components/Hello.svelte'; </script> <Hello name="world" /> <Hello name="svelte" /> ``` === Logics In some situation you may want to display different content or style based on some condition. You can use `if` statement to do this. Let's say you want to display a different message based on the value of `name`. You can do this like this: ```html <script> let name = 'world'; </script> {#if name === 'world'} <h1>Hello {name}!</h1> {:else} <h1>I don't say hello to anyone else</h1> {/if} ``` Try changing this snippet to work with the `Hello` component we created earlier. There are more logics you can use in Svelte, such as `each`, `await`, `then`, `catch`, etc. You can find more information about them in the #link("https://svelte.dev/docs/logic-blocks")[Svelte documentation]. === Events and binding Now it is time to add a bit of interactivity to our page. Let's add a button that track the number of times it is clicked. You can do this like this: ```html <script> let count = 0; function handleClick() { count += 1; } </script> <button on:click={handleClick}> Clicked {count} {count === 1 ? 'time' : 'times'} </button> ``` This is a way to let data flow from the javascript to the html for display. However, sometimes you may want to go the other way around Another common use case is to bind the value of an input field to a variable. You can do this like this: ```html <script> let name = ''; </script> <input bind:value={name} placeholder="Enter your name" /> <p>Hello {name}!</p> ``` Now given the code above, try to make a page that says hello to the user when they enter their name in the input field, together with a poke button. If the poke button is poked more than 10 times, the page should say "You are annoying". == Setting up routes Often we want to have multiple pages in our website. This is usually done through the concept of route. A route is a path that the user can visit to see a different page. In SvelteKit, you can define routes in the `src/routes` folder. If you want to create a new page, you would create a new folder in the `src` folder, then add a `+page.svelte` file in it. To test this out, let's try to add a simple navigation bar to our website. === Creating a navigation bar Create a new file `src/components/Navbar.svelte` and write the following code: ```html <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> ``` Then you can include this component in your `src/routes/+page.svelte` file like this: ```html <script> import Navbar from '$lib/components/Navbar.svelte'; </script> <Navbar /> ``` Now you should see a navigation bar at the top of your page. If you click on the "About" link, you should see a 404 page. This is because we have not defined the route for the "About" page yet. Let's do that now. === Defining the About page Create a new folder `src/routes/about` and add a `+page.svelte` file in it. Write the following code in the `src/routes/about/+page.svelte` file: ```html <h1>About page</h1> <p>This is the about page</p> ``` Now if you click on the "About" link in the navigation bar, you should see the about page. In your browser, you should see the URL change to `http://localhost:5173/about`. == Layouts If you have navigate to the "About" page, you may notice that the navigation bar is missing. This is because the layout of the "About" page is different from the layout of the "Home" page. A layout file defines the layout of a page, such as the header, footer, and navigation bar. In SvelteKit, a layout file for a route can be defined with the `+layout.svelte` file in the route folder. And the layout file will be applied to all the child routes of the route folder. Let's create a layout file for our website. Let's move our navbar to the top level layout file. Create a new file `src/routes/+layout.svelte` and move the navbar code to it: ```html <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> <slot /> ``` The `<slot />` tag is where the content will be inserted. Now you can remove the navbar from the `src/routes/+page.svelte` file. If you navigate to the "About" page now, you should see the navigation bar at the top of the page. == Loading data == Forms
https://github.com/jens-hj/ds-exam-notes
https://raw.githubusercontent.com/jens-hj/ds-exam-notes/main/lib.typ
typst
#import "catppuccin.typ": * #import "@preview/gentle-clues:0.1.0": info, success, warning, error, abstract, attention, caution, done, failure, idea, note, remember, question, quote, hint #import "@preview/tablex:0.0.7": * #let maccent = math.accent #let accent = catppuccin.latte.lavender #let mainh = catppuccin.latte.maroon #let secondh = catppuccin.latte.green #let thirdh = catppuccin.latte.lavender #let rule = line.with(length: 100%) #let hr = rule() #let ivan = text(catppuccin.latte.mauve, link("https://pure.au.dk/portal/da/persons/ivan%40cs.au.dk",[<NAME>])) #let srikanth = text(catppuccin.latte.yellow, link("https://pure.au.dk/portal/en/persons/srikanth%40cs.au.dk", [<NAME>])) #let precision(f, n) = { let as-str = str(f) if str(f).contains(".") { let fract = str(calc.fract(f)).slice(2) // remove leading "0." let integral = calc.trunc(f) if n > fract.len() { panic("n is larger than the number of decimals in f") } [#integral.#fract.slice(0, n)] } else { f } } /// @param x integer|float /// @param n integer #let round(x, n) = { if type(x) == "integer" { return x } assert(type(x) == "float", message: "round(x, n) x is not of type `float`, but has type: " + type(x)) assert(type(n) == "integer", message: "n must have type `integer`, but has type: " + type(n)) assert(0 <= n, message: "0 <= n must hold, but n = " + str(n)) // @type integer|none let period-index = str(x).position(".") if period-index == none { // x is something like `3.` or `3.00` return x } // @type integer[] let fractional-part = str(x).slice(period-index + 1).split("").filter(it => it != "").map(int) // @type string let integer-part = str(x).slice(0, period-index) if n == fractional-part.len() { // nothing to round off return x } if n > fractional-part.len() { // append zeros, to have the fractional-part have n integers let appended-zeros = range(n - fractional-part.len()).map(it => 0) return float(integer-part + "." + (fractional-part + appended-zeros).map(str).join("")) } // typst uses 0-indexing for arrays, so .at(n) is the index we need to look at, that is to the right of the rounding boundary. if fractional-part.at(n) >= 5 { fractional-part.at(n - 1) = fractional-part.at(n - 1) + 1 } float(integer-part + "." + fractional-part.slice(0, n).map(str).join("")) } #let bra(..args) = { let left = [⟨] // U+27E8 let bar = [|] if args.pos().len() == 1 { let var = args.pos().at(0) $#left#var#bar$ } else { let coeffs = $italic(#args.pos().slice(0, -1).join(""))$ let var = args.pos().last() [#coeffs$#left#var|$] } } #let ket(..args) = { let right = [⟩] // U+27E9 if args.pos().len() == 1 { let var = args.pos().first() $|#var#right$ } else { let coeffs = $italic(#args.pos().slice(0, -1).join(""))$ let var = args.pos().last() [#coeffs$|#var#right$] } } #let to-content(it) = [#it] #let braket(..args) = { let left = [⟨] // U+27E8 let right = [⟩] // U+27E9 let bar = [|] let vars = args.pos() if vars.len() < 2 { panic("At least 2 arguments must be given") } else if vars.len() == 2 { let l = vars.first() let r = vars.last() [$#left#l#bar#r#right$] } else { let l = vars.first() let r = vars.last() let projections = vars.slice(1, -1).map(to-content).join(bar) [$#left#l#bar#projections#bar#r#right$] } } #let state = ( plus: $ket(#h(-0.1mm)#sym.plus)$, minus: $ket(#h(-0.1mm)#sym.minus)$, zero: $ket(0)$, one: $ket(1)$, epr: $(ket("00") + ket("11")) / sqrt(2)$, // <NAME> pf: ( plus: $ket(#h(-0.5pt)+#h(0pt)++)$, minus: $ket(#h(-0.5pt)-#h(0pt)--)$ ) ) #let q = "quantum" #let l-- = line(length: 100%) #let l- = line(length: 50%) #let title-case(s) = upper(s.first()) + s.slice(1) #let os12 = $1/sqrt(2)$ #let tp = $times.circle$ // tensor product #let xor = $plus.circle$ // binary XOR #let squared-enum(..numbers, color: none, fill: none) = move( dy: -2pt, box( // stroke: 0.65pt + color, fill: fill, radius: 20%, height: 1em, inset: (x: 3pt, y: 1.5pt) )[ #text( color, weight: 900, { numbers.pos().map(str).join(".") } ) ] ) #let sparkle(content) = [#box(rotate(10deg, scale(x: -100%, emoji.sparkles)))#text(rgb("#ffac33"), style: "italic", content)#h(1.25pt)#box(rotate(10deg, emoji.sparkles))] #let boxed( content, color: accent.lighten(0%), fill: accent.lighten(80%), weight: 400 // block: false ) = box( fill: fill, radius: 3pt, inset: (x: 2pt), outset: (y: 2pt), text( color, weight: weight, content ) ) #let bold-first(..numbers, color: none) = [ #if numbers.pos().len() == 1 { if color != none { text(fill: color, weight: "bold", numbers.pos().map(str).join(".") + ".") } else { text(weight: "bold", numbers.pos().map(str).join(".") + ".") } } else { numbers.pos().map(str).join(".") + "." } ] #let std-block = block.with( fill: catppuccin.latte.base, radius: 1em, inset: 1em, stroke: catppuccin.latte.crust, width: 100%, breakable: true, ) #let suggested-topics-for-question(content) = { std-block(content) } #let agenda-block(content) = { std-block( fill: catppuccin.latte.base, [ #text(size: 13pt, catppuccin.latte.text, weight: "bold", "Agenda") #v(-4pt) #move( dx: -1em, rule( length: 100% + 2em, stroke: 1pt + catppuccin.latte.crust ) ) #v(-4pt) #text(catppuccin.latte.text, content) ] ) } #let report-block(content) = { std-block( fill: catppuccin.latte.base, [ #text(size: 13pt, catppuccin.latte.text, weight: "bold", [#emoji.excl#h(4pt) Possible Report Weakness]) #v(-4pt) #move( dx: -1em, rule( length: 100% + 2em, stroke: 1pt + catppuccin.latte.crust ) ) #v(-4pt) #text(catppuccin.latte.text, content) ] ) } #let quest-block(content) = { std-block( fill: catppuccin.latte.base, [ #text(size: 13pt, catppuccin.latte.text, weight: "bold", [#emoji.quest#h(4pt) Question]) #v(-4pt) #move( dx: -1em, rule( length: 100% + 2em, stroke: 1pt + catppuccin.latte.crust ) ) #v(-4pt) #text(catppuccin.latte.text, content) ] ) } #let tp = $times.circle$ //EPR = 1/sqrt(2) * (ket00 + ket11) #let EPR = $1/sqrt(2)(ket(00) + ket(11))$ #let gates = ( X: $mat(delim: "[", 0, 1; 1, 0)$, Y: $mat(delim: "[", 0, i; -i, 0)$, Z: $mat(delim: "[", 1, 0; 0, -1)$, I: $mat(delim: "[", 1, 0; 0, 1)$, H: $1/sqrt(2) mat(delim: "[", 1, 1; 1, -1)$, S: $mat(delim: "[", 1, 0; 0, i)$, // Phase gate T: $mat(delim: "[", 1, 0; 0, e^(i pi"/"4))$, SWAP: $mat(delim: "[", 1, 0, 0, 0; 0, 0, 1, 0; 0, 1, 0, 0; 0, 0, 0, 1)$, CNOT: $mat(delim: "[", 1, 0, 0, 0; 0, 1 ,0, 0; 0, 0, 0, 1; 0,0,1,0)$, CZ: $mat(delim: "[", 1,0,0,0; 0, 1, 0, 0; 0 ,0, 1, 0; 0, 0, 0, -1)$, TOFFOLI: $mat(delim: "[", 1, 0, 0, 0, 0, 0, 0, 0; 0, 1, 0, 0, 0, 0, 0, 0; 0, 0, 1, 0, 0, 0, 0, 0; 0, 0, 0, 1, 0, 0, 0, 0; 0, 0, 0, 0, 1, 0, 0, 0; 0, 0, 0, 0, 0, 1, 0, 0; 0, 0, 0, 0, 0, 0, 0, 1; 0, 0, 0, 0, 0, 0, 1, 0; )$, ) // S = [1 0; 0 im] # Phase gate // T = [1 0; 0 exp(im*pi/4)] # T gate (pi/8 gate) // TOFFOLI = [ // 1 0 0 0 0 0 0 0; // 0 1 0 0 0 0 0 0; // 0 0 1 0 0 0 0 0; // 0 0 0 1 0 0 0 0; // 0 0 0 0 1 0 0 0; // 0 0 0 0 0 1 0 0; // 0 0 0 0 0 0 0 1; // 0 0 0 0 0 0 1 0; // ] // SWAP = [ // 1 0 0 0; // 0 0 1 0; // 0 1 0 0; // 0 0 0 1; // ] // CNOT = [1 0 0 0; 0 1 0 0; 0 0 0 1; 0 0 1 0] // CZ = [1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 -1] #let km = $ket(#h(-0.025em)minus)$ #let nameref( label, name, supplement: none, ) = { show link : it => text(accent, it) link( label, [#ref(label, supplement: supplement). #name] ) } #let numref(label) = ref(label, supplement: none) #let ra = text(catppuccin.latte.maroon, sym.arrow.r) #let pm = $plus.minus$ #let tablex = tablex.with(stroke: 0.25pt, auto-lines: false, inset: 0.5em) #let trule = hlinex(stroke: 0.25pt) #let thick-rule = hlinex(stroke: 0.75pt) #let double-rule(cols) = ( hlinex(), colspanx(cols)[#v(-0.75em)], hlinex(), ) #let N2(exponent) = { if exponent == [1] { $sqrt(N) / sqrt(2)$ } else { $sqrt(N) / sqrt(2^exponent)$ } } #let comma-separate(xs) = xs.map(str).join(", ") #let as-vec(xs, delim: "(") = { let elements = comma-separate(xs) // let expr = "$ vec(" + elements + ", delim: \"" + delim + "\") $" let expr = "$ vec(" + elements + ") $" set math.vec(delim: delim) eval(expr) } #let as-mat(M, delim: "(") = { let elements = M.map(comma-separate).join("; ") let expr = "$ mat(" + elements + ") $" set math.mat(delim: delim) eval(expr) } // #as-vec(range(10), delim: "[") // #let M = ( // (1, 2, 3), // (4, 5, 6), // (7, 8, 9), // (10, 11, 12), // ("a", "b", "c"), // ("cos(x)", "1/2", "x^2"), // // (1.2, $a$, $b$) // ) // #as-mat(M, delim: "{") #let roots-of-unity-matrix(N) = { let M = () for i in range(N) { let row = () for j in range(N) { let exponent = i * j if exponent == 0 { row.push(1) } else { row.push("omega^" + str(exponent)) } } M.push(row) } M } #let H(bits) = $H^(tp bits)$ #let swatch(color, content: none, s: 6pt) = { if content != none { content // h(0.1em) } h(1pt, weak: true) box( height: s, width: s, fill: color, // stroke: 1pt + color, radius: s/2, baseline: (s - 0.5em) / 2, ) } #let sr = swatch(red) #let sb = swatch(blue) #let prot-title(content) = align(center, text(size: 16pt, content)) #let prot-block = std-block.with( fill: accent.lighten(95%), stroke: (paint: accent.lighten(20%)) ) #let a = text(catppuccin.latte.yellow, weight: "bold", "Alice") #let b = text(catppuccin.latte.blue, weight: "bold", "Bob") #let e = text(catppuccin.latte.maroon, weight: "bold", "Eve") #let bold-enum = (..numbers) => text(weight: 900, numbers.pos().map(str).join(".") + ".") #let same(item, amount) = for i in range(amount) { (item,) }
https://github.com/darioglasl/Arbeiten-Vorlage-Typst
https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/05_Qualitätssicherung/03_integration_tests.typ
typst
== Integration Tests <headingIntegrationTests> TODO: text
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/pagebreak-01.typ
typst
Other
// Pagebreak, empty with styles and then pagebreak // Should result in one auto-sized page and two green-colored 2cm wide pages. #pagebreak() #set page(width: 2cm, fill: green) #pagebreak()
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/include-00.typ
typst
Other
#set page(width: 200pt) = Document // Include a file #include "modules/chap1.typ" // Expression as a file name. #let chap2 = include "modu" + "les/chap" + "2.typ" -- _Intermission_ -- #chap2
https://github.com/TimPaasche/Typst.Template.SimpleDocument
https://raw.githubusercontent.com/TimPaasche/Typst.Template.SimpleDocument/master/main.typ
typst
MIT License
#import "template/style.typ": setPage #show: doc => setPage( headerLine1: "Line 1", headerLine2: "Line 2", authors: ( ( name: "<NAME>", mnr: 12345 ), ), doc ) #text( font: "Cascadia Mono", size: 20pt, weight: "bold", "Überschrift" ) #lorem(100)