repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/foundations-05.typ
typst
Other
// Test failing assertions. // Error: 8-16 assertion failed #assert(1 == 2)
https://github.com/EricWay1024/Homological-Algebra-Notes
https://raw.githubusercontent.com/EricWay1024/Homological-Algebra-Notes/master/ha/8-ext.typ
typst
#import "../libs/template.typ": * = Ring Structure on $Ext$ <ring-ext> == Reinterpreting $Ext$ Let $A, B in RMod$ with projective resolutions $P_cx -> A$ and $Q_cx -> B$. Write the total cochain complex $ Tot^Pi (hom (P, Q)) =: T$. Then @balance-ext-2 implies that $ Ext^n _R (A, B) iso H^n (T). $ Recall that $T^n = product homr (P_i, Q_(i-n)) in Ab$. If $phi in T^n$, then we can write $phi = product phi_i$ where $phi_i : P_i -> Q_(i - n)$. Therefore, an element $phi$ in $T^n$ can be seen as a chain map $P_cx -> Q_cx [-n]$ once we can show that $phi$ commutes with the differentials of $P_cx$ and $Q_cx [-n]$. We will show that this commuting condition is (almost) equivalent to $phi$ being a cocycle in $T^n$. Further, if $phi$ is a chain map $P_cx -> Q_cx [-n]$, then $phi$ being null homotopic is (almost) equivalent to $phi$ being a coboundary in $T^n$. These equivalences ultimately give rise to a new interpretation of $Ext$. The word "almost" in the last paragraph is due to some sign issues of $phi$. To address this, we define $ epsilon_i = cases(1 quad& "if " i equiv 0 comma 3 quad (mod 4), -1 quad& "if " i equiv 1 comma 2 quad (mod 4)). $ Then we define $tilde(phi)_i = epsilon_(n-i) phi_i$ for each $phi_i : P_i -> Q_(i - n)$, and $tilde(phi) = product tilde(phi)_i in T^n$. The following is some simple observations of the definitions. #lemma[ We have the following: - $epsilon_i^2 = 1$; - $epsilon_i epsilon_(i - 1) = (-1)^i$; - $phi_i = epsilon_(n-i) tilde(phi)_i $; - The map $phi |-> tilde(phi)$ is an automorphism of $T^n$. ] <epsilon-lemma> It turns out that we need to replace some $phi$ with $tilde(phi)$ in our previous claims, as in the following. // i.e., $T^n iso tilde(T^n)$, where an arbitrary element of $tilde(T^n)$ is $tilde(phi) = product tilde(phi)_i = product epsilon_(n-i) phi_i$. #proposition[ // The map $phi |-> tilde(phi)$ restricts to an isomorphism // $ // Z^n (T) iso hom_(Ch(RMod)) (P_cx, Q_cx [-n]) // $ // where the left hand side is the cocycles in degree $n$ and the right hand side denotes chain maps $P_cx -> Q_cx [-n]$. $phi in T^n$ is a cocycle in $Z^n (T)$ if and only if $tilde(phi)$ can be seen as a chain map $P_cx -> Q_cx [-n]$. ] #proof[ As discussed above, the latter is equivalent to $tilde(phi)$ commuting with the differentials, i.e., for all $i$, #math.equation(block: true, numbering: "(1)", supplement: "Equation", $ tilde(phi)_i oo d_(i+1)^((P)) = d_(i+1-n)^((Q)) oo tilde(phi)_(i+1). $) <phi-commute> Using the definition of $tilde(phi)$, @phi-commute can reduced to #math.equation(block: true, numbering: "(1)", supplement: "Equation", $ phi_i oo d_(i+1)^((P)) = (-1)^(i+1-n) d_(i+1-n)^((Q)) oo phi_(i+1). $) <phi-commute-2> On the other hand, $phi in T^n$ is a cocycle, i.e., $d^((T))_n (phi) = 0$, if and only if for all $i$, #math.equation(block: true, numbering: "(1)", supplement: "Equation", $ d^h (phi_i) + d^v (phi_(i+1)) = 0. $) <phi-commute-3> Using the definition of $d^h$ and $d^v$, we see that @phi-commute-3 is equivalent to @phi-commute-2. ] #proposition[ $phi in Z^n (T)$ is a coboundary in $B^n (T)$ if and only if the chain map $tilde(phi) : P_cx -> Q_cx [-n]$ is null homotopic. ] #proof[ "$=>$". Suppose $phi$ is a coboundary. Then $phi = d (psi)$ for some $psi = product psi_i in T^(n-1)$, where $psi_i : P_i -> Q_(i - n +1)$. We also write $tilde(psi_i) = epsilon_(i -n +1) psi_i$. // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBoAGAXVJADcBDAGwFcYkQALCAWwH0AKAAq8spAAQBFAVgC0YANTEAlEpABfUuky58hFGWLU6TVuy7cxQkeKn9ZYFes0gM2PASLlShmgxZtETh4rOxllG2k5RzUjGCgAc3giUAAzACceJAAmGhwIJDJjf3Z+MKUAPVCHMTgAR2Z6NJgxCAgxKBFKoWjndMzELxA8gt8TAJAOqsUK-n4JFRa2uoam9Uo1IA #align(center, commutative-diagram( node-padding: (90pt, 50pt), node((0, 1), [$hom (P_i, Q_(i-n+1))$]), node((1, 1), [$hom (P_i, Q_(i-n))$]), node((1, 0), [$hom(P_(i-1), Q_(i-n))$]), arr((1, 0), (1, 1), [$(-1)^(i-n) square oo d_i^((P))$]), arr((0, 1), (1, 1), [$d_(i-n+1)^((Q)) oo square$]), )) Considering each $phi_i$, we see that $ phi_i = d^h (psi_(i-1)) + d^v (psi_i) = (-1)^(i-n) psi_(i-1) oo d_i^((P)) + d_(i-n+1)^((Q)) oo psi_i. $ Using @epsilon-lemma, we can reduce this to $ tilde(phi)_i = (-1)^(i-n) tilde(psi)_(i-1) oo d_i^((P)) + (-1)^(i-n+1) d_(i-n+1)^((Q)) oo tilde(psi)_i. $ Then we see that $(-1)^(i-n+1) tilde(psi)_i : P_i -> Q_(i - n +1)$ is a chain homotopy between $tilde(phi)$ and $0$. "$arrow.l.double$". Suppose that $h_i : P_i -> Q_(i - n +1)$ is a chain homotopy between $tilde(phi)$ and $0$ for each $i$, so that $ tilde(phi)_i = h_(i-1) oo d_i^((P)) + d_(i-n+1)^((Q)) oo h_i. $ Then we can define for each $i$, $ tilde(psi)_i &= (-1)^(i-n+1) h_i, quad psi_i &= epsilon_(i-n+1) tilde(psi)_i, $ which gives $psi &= product psi_i in T^(n-1)$. Again with @epsilon-lemma, we can reveal that $d(psi) = phi$, so $phi$ is a coboundary. ] #corollary[ $Ext_R^n (A, B)$ is isomorphic to the chain homotopy classes of chain maps $P_cx -> Q_cx [-n]$. ] <ext-homotopy> #proof[ $Ext_R^n (A, B) iso H^n (T) = Z^n (T) over B^n (T)$, but now $Z^n (T)$ is isomorphic to the group of chain maps $P_cx -> Q_cx [-n]$ and $B^n (T)$ is isomorphic to the subgroup of null homotopic chain maps. ] // A detailed proof can be seen @notes[Section 9.1]. // To see this intuitively, notice a chain map $P_cx -> Q_cx [-n]$ is a collection of // $hom (P_p, Q_(p - n)) // $ for all suitable index $p$, subject to commuting with the differentials. // Hence, it is an element of $[Tot^Pi (hom_R (P_cx, Q_cx))]^n =: T^n$. // One can show that the commuting condition for a chain map is equivalent to being a cycle in $T^n$. // Further, the chain map is null homotopic if and only if it is a boundary in $T^n$. == Yoneda Product #proposition[ Given left $R$-modules $A, B, C$, for any $i, j$, there is a well-defined map, called the *Yoneda product*, $ ⌣ : Ext_R^i (A, B) times Ext_R^j (B, C) -> Ext^(i+j)_R (A, C), $ which is associative and biadditive. ] #proof[ Write projective resolutions $P_cx -> A$, $ Q_cx -> B$, $ T_cx-> C$. Take $x in Ext^i_R\(A, B)$ and $y in Ext^j_R\(B, C)$. By @ext-homotopy, we see that $x$ (resp. $y$) corresponds to some $[phi]$ (resp. $[psi]$) which is a chain homotopy class (of chain maps) $P_cx -> Q_cx [-i]$ (resp. $Q_cx -> T_cx [-j]$). Note that $ hom(Q_cx, T_cx [-j]) iso hom(Q_cx [-i], T_cx [-i - j]) $ because the translation functor is an isomorphism on $Ch(RMod)$ and preserves chain homotopy. Hence $[psi]$ can be also viewed as a chain homotopy class $Q_cx [-i] -> T_cx [-i - j]$. Since chain homotopy commutes with composition, we can obtain $[psi oo phi] = [psi] oo [phi]$, which is a chain homotopy class $P_cx -> T_cx [-i-j]$. Then we define $x ⌣ y in Ext^(i+j)_R (A, C)$ to be the corresponding element of $[psi oo phi]$. We can see that $⌣$ is associative and biadditive because the composition of chain maps is associative and biadditive. ] // #remark[ // We have shown $D^- (RMod) iso K^- ("Proj" RMod)$. // ] #corollary[For any $A, B in RMod$, $ Ext_R^ast (A, A) = plus.circle.big_i Ext_R^i (A, A) $ is a graded ring, and $ Ext_R^ast (A , B) = plus.circle.big_i Ext^i (A, B) $ is a graded module over $Ext_R^ast (A, A)$. ] #example[ Let $k$ be a field and $R = k[x] over (x^2)$. View $k$ as the $R$-module $R over x R$. We now calculate the graded ring structure of $Ext_R^ast (k, k)$. First, observe that we have a projective resolution of $k$: $ ... ->^x R ->^x R ->^x R -> k -> 0, $ which we denote as $P_cx -> k -> 0$. If we apply $hom_R (-, k)$ to $P_cx$, then $hom_R (R, k) iso k$ and all differentials vanish, so we can quickly use the balancing of $Ext$ to reveal that $Ext_R^n (k, k) iso k$ for all $n >= 0$. We however need to find the generator explicitly for the ring structure. Now by @ext-homotopy, $Ext_R^n (k, k)$ is isomorphic to the chain homotopy classes of chain maps $P_cx -> P_cx [-n]$. A chain map $P_cx -> P_cx [-n]$ is a collection of $R$-homomorphisms $f_i : R-> R$ for $i >= n$ such that the following diagram commutes: // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBoAGAXVJADcBDAGwFcYkQAlEAX1PU1z5CKAEwVqdJq3Zde-bHgJEAzOJoMWbRJx58QGBUKIAWNZM0zd8wUpQBWMxunaAdG6v6Bi4cnKOpWiBuLh4GNj6qxBJOgbJ6Yd5EYlHqAZZynoa2JKQp5s46GQlGKKZ5MezkoV4lvrnRaa7u3BIwUADm8ESgAGYAThAAtkhiIDgQSABsqRbaPQD6hBn9Q0hkYxOIAOwzBQsAFGAA1MQAlB4rw4h+G0gAHLuBB8ci58sDVzfja4-sAB4XD4-W6IUYVbQA96rUE0b6IVT5QKQvSXJAIuHGKFXaYggCcWKQOxBOPBIGRvSBiAeIKJpPJIFRiAcIJudMB0OIX021LZLW4QA #align(center, commutative-diagram( node-padding: (50pt, 30pt), node((0, 1), [$R$]), node((0, 2), [$R$]), node((0, 3), [$R$]), node((0, 4), [$R$]), node((0, 5), [$...$]), node((0, 0), [$...$]), node((1, 3), [$R$]), node((1, 2), [$R$]), node((1, 1), [$R$]), node((1, 4), [$0$]), node((1, 0), [$...$]), arr((0, 3), (1, 3), [$f_n$]), arr((0, 2), (1, 2), [$f_(n+1)$]), arr((0, 1), (1, 1), [$f_(n+2)$]), arr((0, 1), (0, 2), [$x$]), arr((0, 2), (0, 3), [$x$]), arr((0, 3), (0, 4), [$x$]), arr((0, 4), (0, 5), []), arr((1, 3), (1, 4), []), arr((1, 2), (1, 3), [$x$]), arr((1, 1), (1, 2), [$x$]), arr((0, 0), (0, 1), [$x$]), arr((1, 0), (1, 1), [$x$]), )) Note that each $f_i$ is uniquely determined by $f_i (1) in R$. We write $f_i (1) = a_i + b_i x$ for $a_i, b_i in k$ and then we only need to look at $a_i, b_i$ for each $i$. The commutativity of the above diagram indicates that $x (a_i + b_i x) = x (a_(i+1) + b_(i+1) x)$ for each $i$, i.e. $a_i = a_(i+1)$, so all the $a_i$'s are equal. We now consider when the chain map $f_ast$ is null homotopic. By definition, that is when there is a collection of $R$-homomorphisms $h_i : R -> R$ for $i >= n-1$ such that $f_i = h_(i-1) oo x + x oo h_i$. // https://t.yw.je/#N4Igdg9gJgpg<KEY>MJ<KEY> #align(center, commutative-diagram( node-padding: (60pt, 50pt), node((0, 1), [$R$]), node((0, 2), [$R$]), node((0, 3), [$R$]), node((0, 4), [$R$]), node((0, 5), [$...$]), node((0, 0), [$...$]), node((1, 3), [$R$]), node((1, 2), [$R$]), node((1, 1), [$R$]), node((1, 4), [$0$]), node((1, 0), [$...$]), arr((0, 3), (1, 3), [$f_n$]), arr((0, 2), (1, 2), [$f_(n+1)$]), arr((0, 1), (1, 1), [$f_(n+2)$]), arr((0, 1), (0, 2), [$x$]), arr((0, 2), (0, 3), [$x$]), arr((0, 3), (0, 4), [$x$]), arr((0, 4), (0, 5), []), arr((1, 3), (1, 4), []), arr((1, 2), (1, 3), [$x$]), arr((1, 1), (1, 2), [$x$]), arr((0, 0), (0, 1), [$x$]), arr((1, 0), (1, 1), [$x$]), arr((0, 2), (1, 1), [$h_(n+1)$], "dashed"), arr((0, 3), (1, 2), [$h_(n)$], "dashed"), arr((0, 4), (1, 3), [$h_(n-1)$], "dashed"), )) In particular, this indicates that $a_i + b_i x = f_i (1) = h_(i-1) (x) + x h_i (1) = x (h_(i-1) (1) + h_(i) (1))$, and thus $a_i = 0$ for all $i$. We claim that $a_i = 0$ for all $i$ is a sufficient condition for $f_ast$ to be null homotopic. In this case, $f_i (1) = b_i x$ for each $i >= n$. We construct $h_i: R -> R$ for $i >= n-1$ as follows: $h_(n-1) = 0$ and $h_i (1) = b_i - h_(i-1) (1)$ for all $i >= n$. Then $f_ast$ is null homotopic via $h$. Therefore $f_ast$ is null homotopic if and only if $f_i (1) equiv 0 space (mod x)$ for all $i$. So "chain maps modulo homotopy" is the same as "chain maps modulo $x$". In other words, two chain maps $f_ast, g_ast: P_cx -> P_cx [-n]$ are chain homotopic if and only if $f_i (1) equiv g_i (1) space (mod x)$ for all $i$. But we have established that $f_i (1)$'s are all equal modulo $x$. So $Ext_R^ n (k, k) iso k dot f_ast^((n))$, where $f_ast^((n))$ is the chain map $P_cx -> P_cx [-n]$ with $f_i ^((n)) (1) = 1$ for all $i >= n$. It is clear that $f_ast ^((m)) oo f_ast ^((n)) = f_ast ^((m+n))$, so the Yoneda product gives $f_ast ^((m)) ⌣ f_ast ^((n)) = f_ast ^((m+n))$. Set $y = f_ast^((1))$, then for each $n$, $f_ast^((n)) = y^n$ (using Yoneda product) and thus $Ext^n_R (k, k) iso k dot y^n$. So as a graded ring, $Ext_R^ast (k, k) iso k[y]$ where $y$ has degree $1$. ] // #TODO alternative definition of Yoneda product, "gluing sequences"
https://github.com/Ciolv/typst-template-bachelor-thesis
https://raw.githubusercontent.com/Ciolv/typst-template-bachelor-thesis/main/config.typ
typst
#let conf( title: none, authors: (), university: none, abstract: [], language: "de", // enable language-specific quotes with ISO 639-1/2/3 language code. font: "Manrope", font_size: 11.96pt, outlines: ((none, none),), thesis_type: none, course_of_studies: none, field_of_studies: none, company_logo: (path: none, alternative_text: none), university_logo: (path: none, alternative_text: none), bibliography-file: none, bibliography-style: "ieee", declaration_on_honour: true, acronym_outline_name: "Abkürzungsverzeichnis", doc, ) = { import "acronyms.typ": print_acronym_listing //=========================================================================== // Layout configuration //=========================================================================== set page( paper: "a4", number-align: right, margin: (rest: 2.5cm) ) set text( lang: language, region: language, font: font, size: font_size, // Weird font size to achieve about the same line length as with 12pt Arial in Word fractions: true, ) // Add some spacing between figures and caption set figure( gap: 1em ) // Add numbering to equations set math.equation(numbering: "(1)") // leading is line spacing set par(first-line-indent: 1em, leading: 1.5em) // Configure headings. set heading(numbering: "1.1") show heading: it => { let first = true; // Don't indent headings set par(first-line-indent: 0em) // Set some defaults set text(weight: "bold") let size = 1em let style = "normal" // Set size and style based on the heading level if (it.level == 1) { size = 1.5em locate(loc => { // Pagebreak for all except the first numbered headline // The first numbered headline receives the pagebreak // implicit via page counter update (I guess?) let levels = counter(heading).at(loc) if levels != (1,) { pagebreak(weak: true) } }) } else if (it.level == 2) { size = 1.3em } else if (it.level == 3) { size = 1.2em } else { style = "italic" } // Apply styling defined in the condition above set text(size: size, style: style) // Some spacing above the heading v(size / 2, weak: false) // Display heading numbers until level four, if numbering is enabled // Shouldn't really use more than three heading levels, so no more from level four onwards! if it.numbering != none and it.level < 4 { counter(heading).display() h(0.75em, weak: true) } // Print the heading itself it.body // Some spacing below the heading v(size / 2, weak: false) } //=========================================================================== // Titlepage //=========================================================================== // Template supports only one author, as it is made for a bachelor thesis! let author = authors.first() // Print company and / or university logo, if given grid( columns: (30%, 40%, 30%), rows: (25%), if company_logo.path != none and company_logo.path != "" { image(company_logo.path) }, [], if university_logo.path != none and university_logo.path != "" { image(university_logo.path) } ) // Print author and university information align(center, [ //#v(2%) #university #v(3em) #text(size: 1.25em, weight: "bold", thesis_type) \ #text(1.75em, weight: "bold", title) #v(3em) #text(size: 1.25em, weight: "bold", course_of_studies) \ #v(1em) #text(size: 1em, weight: "bold", field_of_studies) #v(15%) #table( columns: (50%, 50%), align: (x, y) => (left, left).at(x), stroke: none, if author.name != none [#if language == "de" [Verfasser(in):] else [Author:]], [#author.name], if author.matriculation_number != none [#if language == "de" [Matrikelnummer:] else [Matriculation number:]], [#author.matriculation_number], if author.company != none [#if language == "de" [Firma:] else [Company:]], [#author.company], if author.department != none [#if language == "de" [Abteilung:] else [Department:]], [#author.department], if author.course != none [#if language == "de" [Kurs:] else [Course:]], [#author.course], if author.course_administrator != none [#if language == "de" [Studiengangsleiter:] else [Course administrator:]], [#author.course_administrator], if author.scientific_advisor != none [#if language == "de" [Wissenschaftliche(r) Betreuer(in):] else [Scientific advisor:]], [#author.scientific_advisor], if author.company_advisor != none [#if language == "de" [Firmenbetreuer(in):] else [Company advisor:]], [#author.company_advisor], if author.period != none [#if language == "de" [Bearbeitungszeitraum:] else [Editing period:]], [#author.period], if author.submission_date != none [#if language == "de" [Eingereicht am:] else [Submission date:]], [#author.submission_date] ) ]) // Enable page numbers starting by declatation on honour, with roman numbering counter(page).update(0) set page(numbering: "I") //=========================================================================== // Declaration of honour //=========================================================================== if declaration_on_honour { heading(level: 1, outlined: false, numbering: none)[ #if language == "de" [Ehrenwörtliche Erklärung] else [Declaration on honour] ] par(first-line-indent: 0em, if language == "de" [ Ich versichere hiermit, dass ich die vorliegende Arbeit mit dem Titel "#title" selbstständig verfasst und keine anderen als die angegebenen Quellen und Hilfsmittel benutzt habe. Ich versichere zudem, dass die eingereichte elektronische Fassung mit der gedruckten Fassung übereinstimmt. ] else [ I hereby declare that this project thesis with the topic "#title" is entirely the product of my own scholarly work, unless otherwise indicated in the text or references or acknowledged below. I also assure that the submitted electronic version is the same version as the printed version. ] ) v(8em) grid( columns: (auto, 1fr, auto), if language == "de" [Ort, Datum] else [Location, Date], [], [#author.name] ) } //=========================================================================== // Registers / Outlines //=========================================================================== // Prints the outline for figures with given name only if at least one item of that kind exists let print_outline_if_content_exists(title, kind) = { locate(loc => { let elems = query(figure.where(kind: kind), loc) let count = elems.len() if count > 0 { par(first-line-indent: 0em, leading: 1em)[ #heading(level: 1, numbering: none)[#title] #outline( title: none, target: figure.where(kind: kind), ) ] } }) } // Outline / Table of contents par(first-line-indent: 0em, leading: 1em)[ #outline(depth: 3, indent: true) ] for (name, kind) in outlines { print_outline_if_content_exists(name, kind) } // Acronym register print_acronym_listing(acronym_outline_name) //=========================================================================== // Abstract //=========================================================================== // Print only non empty abstract if abstract != none and abstract != "" { par(first-line-indent: 0em)[ #heading(level: 1, outlined: false, numbering: none)[Abstract] #abstract ] } //=========================================================================== // Content //=========================================================================== // Use arabic numbering for content set page(numbering: "1") counter(page).update(1) // Display paper content doc // Print bibliography if bibliography-file != none { heading(level: 1, numbering: none)[#if language == "de" [Literaturverzeichnis] else [References]] show bibliography: set text(0.8em) bibliography( bibliography-file, title: none, style: bibliography-style) } }
https://github.com/maucejo/elsearticle
https://raw.githubusercontent.com/maucejo/elsearticle/main/template/main.typ
typst
MIT License
// #import "@preview/elsearticle:0.3.0": * #import "../src/elsearticle.typ": * #let abstract = lorem(100) #show: elsearticle.with( title: "Title of the paper", authors: ( ( name: "<NAME>", affiliation: "University A, City A, Country A", corr: "<EMAIL>", id: "a", ), ( name: "<NAME>", affiliation: "University B, City B, Country B", id: "b" ), (name: lorem(2)), (name: lorem(3)), (name: "<NAME>"), (name: "<NAME>"), ), journal: "Name of the Journal", abstract: abstract, keywords: ("keyword 1", "keyword 2"), format: "review", // line-numbering: true, ) = Introduction #lorem(100) = Section 1 #lorem(50) == Subsection 1 #lorem(10) (see @eq1) @Aut10. $ y = a x +b $ <eq1> where ... == Features === Table Below is @tab:tab1. #let tab1 = { table( columns: 3, table.header( [*Header 1*], [*Header 2*], [*Header 3*], ), [Row 1], [12.0], [92.1], [Row 2], [16.6], [104], ) } #figure( tab1, kind: table, caption : [Example] ) <tab:tab1> === Figures Below is @fig:logo. #figure( image("images/typst-logo.svg", width: 50%), caption : [Typst logo - Credit: \@fenjalien] ) <fig:logo> === Subfigures Below are @figa and @figb, which are part of @fig:typst. #subfigure( figure(image("images/typst-logo.svg"), caption: []), <figa>, figure(image("images/typst-logo.svg"), caption: []), <figb>, columns: (1fr, 1fr), caption: [(a) Left image and (b) Right image], label: <fig:typst>, ) #show: appendix = Appendix A == Figures In @fig:app #figure( image("images/typst-logo.svg", width: 50%), caption : [Books cover] ) <fig:app> == Subfigures Below are @figa-app and @figb-app, which are part of @fig:typst-app. #subfigure( figure(image("images/typst-logo.svg"), caption: []), <figa-app>, figure(image("images/typst-logo.svg"), caption: []), <figb-app>, columns: (1fr, 1fr), caption: [(a) Left image and (b) Right image], label: <fig:typst-app>, ) == Tables In @tab:app #figure( tab1, kind: table, caption : [Example] ) <tab:app> == Equations In @eq $ y = f(x) $ <eq> #nonumeq[$ y = g(x) $ ] #bibliography("refs.bib")
https://github.com/magic3007/cv-typst
https://raw.githubusercontent.com/magic3007/cv-typst/master/README.md
markdown
# cv-typst English Public Version.
https://github.com/mrtz-j/typst-thesis-template
https://raw.githubusercontent.com/mrtz-j/typst-thesis-template/main/modules/acknowledgements.typ
typst
MIT License
#let acknowledgements-page(body) = { pagebreak(weak: true, to: "even") // --- Acknowledgements --- align(left)[ = Acknowledgements #v(1em) #body ] }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/003%20-%20Gatecrash/011_Bilagru%20Will%20Come%20for%20You.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Bilagru Will Come for You", set_name: "Gatecrash", story_date: datetime(day: 13, month: 03, year: 2013), author: "<NAME>", doc ) Arresters descended upon the scene only moments after the deed was done. A crowd was already gathering, pressing in on a gangly man who stood over a lifeless body. Blood welled from the body, the flow following the seams between the paving stones before it pooled around the man's fine boots. The man made no effort to move, to run. He remained there, hunched and disheveled, but frantically alert. His eyes darted this way and that across the faces of the swelling crowd, and the point of his sword followed his shifting gaze in a series of jerky movements. #figure(image("011_Bilagru Will Come for You/01.jpg", width: 100%), caption: [], supplement: none, numbering: none) The arresters pressed through the crowd, and their calls for order rose above the shouts of horror and anger. An arrester may have been reading something, but the man was oblivious in his survey of the onlookers. Then his jaw erupted in pain. The sword flew from his hand. He collapsed upon the body, desperately holding his hands out to ward off a second blow. "<NAME>, I told you to drop your weapon and submit to detention in accordance with detention law number one, one, four." Symond opened his eyes at the voice and a sour-faced, all-business arrester stood over him, a stun-baton in his mailed fist. Symond suddenly recognized the taste of blood in his mouth, but he simply stared at the arrester and smiled. A second arrester yanked him to his feet, and Symond found himself being ushered away under the guard of a half dozen arresters. Other Azorius officers swarmed over the site. Gawkers lined the street to see him marched off to the Detention Compound. Amid the motion of the crowd, a single, motionless figure caught his attention. The detainee turned his head. Atop a horse sat a man draped in a cloak that hid a suit of gold-filigreed plate armor. The rider's face was obscured behind a helm, but the cyclopean visor was unmistakably Orzhov. Symond's gaze was fixed on the horseman until they turned the corner. He heard the word "debtor" echo after him, although he could not be certain. #figure(image("011_Bilagru Will Come for You/02.jpg", width: 100%), caption: [], supplement: none, numbering: none) "A thousand thanks for agreeing to see me, most generous Ilona," I said, removing my hat as I bowed theatrically. The Orzhov potentate raised an eyebrow. I bowed lower, not wanting to offend a woman of such high status. Still no verbal response, and I became acutely self-aware. I stood, clutching my hat to my chest, feeling suddenly clumsy. Ilona sat upon a luxuriously cushioned, high-backed chair at the summit of a dais that was raised a dozen steps from the floor. She was framed by one of the many enormous arches that rose up behind her, and I knew that I was out of place here. A slight upward curl emerged at the corner of the kingpin's mouth. She folded her hands in her lap and looked at me for moment in a way that reminded me of a cat. "Your plays amuse me, Symond." "You are most kind," I said, regaining my composure. "I could think of no finer compliment than the knowledge that my words please you." Ilona's smile grew wider. She stood up, and descended the stairs, stopping on the final step from which she looked down at me. "Come now. What can I do for you?" #figure(image("011_Bilagru Will Come for You/03.jpg", width: 100%), caption: [], supplement: none, numbering: none) "I have come to you, Ilona, the most sincere patron of the arts," I said, as I put my hat on with a flourish, "because I want to put on a play. You see, I've written a play about the epic tale of Zandra, the child who led the Legion. "A dramatic tale?" "A moving tale of courage and redemption." "You write comedies, Symond." "Oh, but this is my masterpiece." "I see now. You've lost your backers." "They lacked the vision. If you could find in your heart to—" "You need coin. I understand." She turned and called up to her empty chair, "<NAME>!" A small, gray figure, adorned with a gold mask and matching gold chains, emerged from behind the chair. <NAME> was Ilona's thrull. The name she chose for her bound thrull revealed the Orzhov kingpin's flair for the theatrical; an attribute I interpreted as most promising at the time. #figure(image("011_Bilagru Will Come for You/04.jpg", width: 100%), caption: [], supplement: none, numbering: none) "Bring a contract," Ilona commanded. "This man, <NAME>, wishes to borrow money." <NAME> unfurled a pair of leathery wings and flew off. "Your previous three plays were critical and financial successes." I nodded, basking for a moment in her acknowledgement. The thrull returned a few moments later with a roll of parchment, a quill, and a vial of ink. I took the quill. "You have been most gracious, Ilona," I said. "This is an investment. You are incurring a debt. To me." She held out the vial of ink. "I intend to collect, and servitude will not count as currency this time." I dipped the quill, and signed. <NAME> saw me out, and as the door closed behind me, I heard the thrull whisper, "Bilagru will come for you." The cell door slammed shut, and the sound of a lock clicking into place resonated through the stone chamber. It was a small cell with thick walls. Three circular windows were cut into the outer wall in a vertical pattern, each with a grid of interwoven iron preempting any plans for escape. Beyond the grates, segments of Ravnica's endless skyline could be made out. Symond tested the strength of the iron. It did not give. He turned to his cell door and tested its bars as well. Solid and strong. He strained against the bars to peer down the corridor, which was lined on both sides with cells presumably like his. And guards. Armed guards. Symond sat down in a corner of his cell, his eyes fixed on the distorted grid-pattern shadow that stretched across the floor as light poured in through the lowest window. It was close to sunset. He was safe. My play demanded realism. The soldiers wore functional combat-tested armor. All the costumes, I insisted, were authentic to the period. #figure(image("011_Bilagru Will Come for You/05.jpg", width: 100%), caption: [], supplement: none, numbering: none) And then there was the stage. Two Izzet mages designed and build a stage where, for the final scene, the floor would fall away, leaving only the bridge where Zandra would duel the Demon of the Spire. It was my vision. The curtains drew back on opening night, and Zandra took the stage with her legionnaires. I peered out to the audience from backstage for a moment, hoping to spot Ilona. To my horror, she was all too easy to spot. Only a quarter of the seats were occupied, but there, sitting in her balcony seat, was Ilona. I became suddenly aware of how expensive every detail was, and how, ultimately, I was accountable. I was in debt. I had to get out of there. It appeared that audiences just wanted a comedy. I scrambled to stuff a bag with food and clothes and hung a sword from my belt. Quietly, I opened the door that led to the street, and stepped out. "Bilagru is coming for you," came a voice from above me. I turned to see the thrull, <NAME>, perched on an outcrop of masonry. Again he spoke. "Bilagru is coming for you," but he added the word, "debtor." He pointed at me, and I took off. The darkness that permeated the cell was thick. When Symond woke, he blindly felt around with outstretched arms, probing the darkness for anything, or anyone, that may be lurking. He crawled around the cramped space of his quarters on his hands and knees. "Ilona would be amused by this." A short, shrill laugh escaped his mouth. The cell began to take shape as his eyes adjusted, confirming that he was, in fact, alone. Of course he was. Symond stood. With renewed confidence, he took the three-and-a-half-step journey across his new domain. His final footfall, however, was punctuated by a harsh scraping sound. Symond leapt back. Then he bent down and picked up a coin. Although he could not see it, he felt the embossed disc and symmetrical rays of the Orzhov guild sun. A flickering glow distracted Symond for a moment. The light was coming from the round windows. Slowly, he approached them, crouching to peer through the lowest window. He saw a shifting dark shape, silhouetted against the glow. The shape turned. <NAME> was staring back at him. Then the thrull spoke. "Bilagru will come for you." Symond was paralyzed with fear. Commotion beyond the bars of his cell broke his paralysis. He whirled around. Guards were yelling out orders. The bright blue crackle of Azorius spells flashed, illuminating a panicked scene for only moments at a time. More guards rushed passed Symond's cell. The other prisoners added their shouts to the clamor. There were shrieks, and the unrelenting, unforgiving, "Bilagru will come for you." I ran, and kept running. My lungs burned. My head pounded. But I pushed forward, ducking down the alleyways and side streets that were so familiar to me. #figure(image("011_Bilagru Will Come for You/06.jpg", width: 100%), caption: [], supplement: none, numbering: none) I just needed to get away. Far away. I had to go to a place where Bilagru couldn't find me. Or Ilona. All the Orzhov, for that matter. I rounded a corner at full sprint, and before I could change course, I crashed into a courier. Both of us tumbled to the ground as scroll cases scattered across the street. Scrambling to my feet, I was about to run when I noticed that the person was a vedalken. Normally, this would not have caught my attention. However, when I looked around, I recognized the area. This was the Azorius Tenth District. In a sudden bloom of inspiration I saw my escape. I knew the safest place—the place farthest from the reach of any Orzhov hand—and how to get there. The vedalken was still sitting in the street, dazed. I reached down to help him up, and when he rose, I drew my sword and plunged it into his chest. He tried to yell out, but his voice failed and he slumped, lifeless, against me. I let his body drop back to street, and I waited for the arresters to take me away. There was nothing to hide behind, so Symond pressed himself against the far wall of his cell, his closed eyes his only defense. All was quiet. Heavy steps grew louder with each footfall. Then those stopped. A key slid into place and turned. The lock released. Symond opened his eyes to see the door swing open. Bilagru, blood-spattered and armored, filled the doorway. His double-bladed axe was slick with gore. The giant stooped to look into the cell. When his eyes found Symond, he saw the cowering man slump to floor. "<NAME>," he said as he stepped inside. "You are a debtor to Ilona of the Orzhov." #figure(image("011_Bilagru Will Come for You/07.jpg", width: 100%), caption: [], supplement: none, numbering: none) He raised his axe. "Debts must be paid."
https://github.com/exdevutem/taller-git
https://raw.githubusercontent.com/exdevutem/taller-git/main/src/pull-request.typ
typst
= Pull Request Un pull request es una petición que se le hace a un mantenedor de un repositorio para que reuna dos ramas que se han separado, y unifique los cambios de estas en una sola rama. Luego de que el trabajo de una rama se haya desarrollado, el paso final de la vida de esta rama es que sea 'mergeada' o combinada con su rama de origen. #figure( image("../assets/pull-requests/diagram.png"), caption: [Diagrama típico de un merge commit (y de un pull request). #link("https://www.atlassian.com/git/tutorials/using-branches/git-merge")[Fuente: atlassian.]], ) <diagram> Es importante notar que el pull request es una acción de Github! En git, el paso de combinar dos ramas es llamado "merge", y posee sus comandos específicos para este proceso. El pull request es similar a un issue (ver @issues), en el sentido de que genera un espacio de discusión y revisión de código entre compañeros de equipo o contribuyentes de un proyecto. == Pull request en un repositorio donde eres contribuyente. Cuando hablamos de ser contribuyente de un repositorio, nos referimos a que tienes permisos de escritura sobre este repositorio#footnote("Es un poquito más complejo que solo eso, pero esta definición basta por ahora."), por lo que puedes empujar commits sin problemas, al igual que crear ramas. El paso a paso típico que harás para estos repositorios es la creación de una rama personal de trabajo, normalmente llamadas "feature branches", que encapsulan algún cambio en el que se haya trabajado. Finalizado este trabajo, en el repositorio de github, seleccionarás *la feature branch* en la que trabajaste, y apretarás el ícono de creación de pull request. Proveerás una descripción en caso de ser necesario, y la publicarás. Bajo este punto, cualquier persona relacionada al repo opinará, solicitará cambios, revisará y evaluará el pull request, y una vez sea aprobado, se mergeará este cambio y se cerrará el pull request. #figure( image("../assets/pull-requests/feature branch.png"), caption: [Vista del repositorio desde un feature branch.], ) <ftbranch> Para este ejemplo, utilizaremos el repositorio de la API del exdev (wip, amén). Fijandose en @ftbranch, notar como la selección de la rama está ubicada en "auth", que es nuestra feature branch del momento. Debajo del botón verde de "code", en donde puedes copiar las referencias para clonar el repositorio, puedes ver una sección que dice contribuir, en donde se te dará el espacio de crear el pull request (ver @contribuir). #figure( image("../assets/pull-requests/contribuir.png"), caption: [Pestaña de contribuir], ) <contribuir> La siguiente ventana va a mostrarte 3 cosas importantes: un formulario de la pull request, donde puedes agregar una descripción detallada (o no tanto) de los cambios que hiciste en esta PR (ver @formulario); un resumen de los commits hechos en esta rama que serían cometidos en este pull request (ver @resumen-pr); y finalmente una lista detallada de todos los cambios hechos, al final de la página. #figure( image("../assets/pull-requests/new-pr.png"), caption: [Formulario de creación de una nueva PR], ) <formulario> Prestar mucha atención a la bara que aparece justo debajo del título "Open a pull request" en @formulario. Si se fijan, esta barra detalla el cómo se hará este pull request; cual es la rama que recibirá los cambios, y qué cambios serán. El cambio típico solicitado es _desde la rama actual_ hacia _la rama principal_, por lo que normalmente no deberías tocar esto. Hay casos, sin embargo, donde quizás quieres crear una pull request distinta, y es aquí donde deberías cambiar esto. Para el caso de la imagen, la rama "main" recibirá los cambios de "auth", y no se presenta ningún problema al momento de combinar estos cambios (denotado por el texto verde "Able to merge"). #figure( image("../assets/pull-requests/pr-commits.png"), caption: [Resumen de commits de la PR], ) <resumen-pr> == Pull request en un repositorio open source Para contribuir en un repositorio Open Source, el proceso es muy similar. La gran diferencia es que en vez de crear una rama y modificar el repositorio oficial, forkeas el repositorio de github, lo modificas, y luego pides una pull request entre repositorios! Github facilita este tipo de acciones, por lo que las opciones para crear estas PR se presentan apenas se detectan cambios en tu fork.
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/func-call-flavor.typ
typst
Apache License 2.0
#table(stroke: none, [arg1], [arg2])
https://github.com/freundTech/typst-forge
https://raw.githubusercontent.com/freundTech/typst-forge/main/README.md
markdown
# typst-forge The unofficial, conda-based package repository for Typst. ## What is typst-forge? typst-forge is an unofficial package repository for [Typst](https://typst.app). If is integrated into the conda ecosystem. We recommend using it with the [pixi](https://pixi.sh) package manager. You can see a list of packages on typst forge at https://prefix.dev/channels/typst-forge | | typst-forge | [Typst Universe](https://typst.app/universe) | | -------------------------------------------------------- | ----------- | -------------------------------------------- | | Official | ❌ | ✅ | | Distributes packages | ✅ | ✅ | | Distributes templates | ✅ | ✅ | | Works using CLI | ✅ | ✅ | | Works using the web app | ❌ | ✅ | | Supports packages with large files | ✅ | ❌ | | Supports packages with fonts | ✅ | ❌ | | Also distributes Typst itself | ✅ | ❌ | | Also distributes other tools like linters and formatters | ✅ | ❌ | | Integrates with self-hosted repositories | ✅ | ❌ | | Supports multiple versions of one package in a project | ❌ | ✅ | ## Using typst-forge First install [pixi](https://pixi.sh). To get started run `pixi init -c conda-forge -c https://prefix.dev/typst-forge`. This will create a pixi project with both the conda-forge and typst-forge channel. The typst-forge channel hosts typst packages, while conda-forge hosts typst itself and additional tools. ```sh $ pixi init -c conda-forge -c https://prefix.dev/typst-forge ✔ Initialized project in /var/home/adrian/Documents/dev/typst/pixi. ``` Next add typst itself to your project. You can also specify the version you want to use. Though take note that typst-forge packages require at least typst 0.12.0. ```sh $ pixi add 'typst==0.12.0' ✔ Added typst ``` You can now run Typst using `pixi run typst`. With typst added you can add a package. All typst packages names are prefixed with `typst-` ```sh $ pixi add 'typst-matryoshka==0.1.0' ✔ Added typst-matryoshka ``` When adding typst packages you should always specify a version. This is because Typst doesn't support import without version specification, you will need to manually keep your Typst imports and pixi dependencies in sync. ```typst #import "@typst-forge/matryoshka:0.1.0": * ``` Instead of using `pixi add` you can also manually modify `pixi.toml`. We recommend also adding a pixi task to build your project: ```sh $ pixi task add compile "typst compile main.typ" ✔ Added task `compile`: typst compile main.typ ``` You can now run `pixi run compile` to compile your document. ## Submitting packages To submit a package to typst-forge you just need to fork this repository and create a pull request with your changes. Create a new directory for your package and copy and adjust the `recipe.yaml` file from another package. You can look at [matroshka](matryoshka/recipe.yaml) for how to create a package with a WASM plugin, at [moderner-cv](moderner-cv/recipe.yaml) for how to create a template and at [fontawesome](fontawesome/recipe.yaml) for how to create a package with a font (The font itself is packaged on [conda-forge](https://github.com/conda-forge/font-otf-fontawesome-feedstock/), while the typst package only has a dependency on it. You can test your recipes locally by running `pixi run build <package-name>`. The full documentation for the recipe format can be found in the [rattler-build documentation](https://prefix-dev.github.io/rattler-build/latest/reference/recipe_file/).
https://github.com/han0126/MCM-test
https://raw.githubusercontent.com/han0126/MCM-test/main/2024校赛typst/chapter/appendix.typ
typst
#import "../template/template.typ": * #let code1 = ```matlab clc,clear,close all %理论培训时间与参加人数关系 x1 = table2array(readtable("C3.xlsx","Range","A2:A11")); y1 = table2array(readtable("C3.xlsx","Range","D2:D11")); scatter(x1,y1,'filled'); [b,bint,r,rint,stats]=regress(y1,[ones(10,1),x1,(x1.^2)]) rcoplot(r,rint); x1(10,:)=[]; y1(10,:)=[]; [b,bint,r,rint,stats]=regress(y1,[ones(9,1),x1,(x1.^2)]) rcoplot(r,rint); %实践培训时间与参加人数关系 x2 = table2array(readtable("C3.xlsx","Range","B12:B21")); y2 = table2array(readtable("C3.xlsx","Range","D12:D21")); scatter(x2,y2,'filled'); y2(2)=(y2(1)+y2(3))/2; scatter(x2,y2,'filled'); [b,bint,r,rint,stats]=regress(y2,[ones(10,1),x2,(x2.^2)]) rcoplot(r,rint); y2(5)=(y2(4)+y2(6))/2; y2(9)=(y2(8)+y2(10))/2; [b,bint,r,rint,stats]=regress(y2,[ones(10,1),x2,(x2.^2)]) rcoplot(r,rint); %投入与参加人数关系 x3 = table2array(readtable("C3.xlsx","Range","C22:C31")); y3 = table2array(readtable("C3.xlsx","Range","D22:D31")); scatter(x3,y3,'filled'); hold on ft = fittype( 'rat11' ); opts = fitoptions( 'Method', 'NonlinearLeastSquares' ); opts.Display = 'Off'; opts.StartPoint = [0.237910506100943 0.558026701756326 0.299620025432728]; [fitresult, gof] = fit( x3, y3, ft, opts ); ``` #let code2 =```matlab clc,clear,close all data = table2array(readtable("C3.xlsx","Range","A2:D31")); %导入数据 std=y1(7); %理论培训时间与参加人数回归分析 x1 = data(1:10,1); y1 = data(1:10,4); for i = 1:10 y1(i)=std-y1(i); end scatter(x1,y1,'filled'); hold on ft = fittype( 'poly2' ); [fitresult, gof] = fit( x1, y1, ft ); plot( fitresult, x1, y1 ); xlabel( 'x1'); ylabel( 'y1'); legend(["x1",""]) grid on hold off %实践培训时间与参加人数回归分析 x2 = data(11:20,2); y2 = data(11:20,4); for i = 1:10 y2(i)=std-y2(i); end y2(2)=(y2(1)+y2(3))/2; scatter(x2,y2,'filled'); hold on r=polyfit(x2,y2,2); t=0:1:400; yy = r(1)*t.^2+r(2).*t+r(3); plot(t,yy,'-'); grid on hold off %投入与参加人数回归分析 x3 = data(21:30,3); y3 = data(21:30,4); for i = 1:10 y3(i)=std-y3(i); end scatter(x3,y3,'filled'); hold on ft = fittype( 'rat11' ); opts = fitoptions( 'Method', 'NonlinearLeastSquares' ); opts.Display = 'Off'; opts.StartPoint = [0.350727103576883 0.939001561999887 0.875942811492984]; [fitresult, gof] = fit( x3, y3, ft, opts ); h = plot( fitresult, x3, y3 ); xlabel( 'x3'); ylabel( 'y3'); legend(["x3",""]) grid on hold off %回归方程检验 y = data(:,4); t=1:1:30; hold on y = data(1:30,4); y(12)=(y(11)+y(13))/2; sst=0; %SST for i = 1:30 sst=sst+(y(i)-sum(y)./30)^2; end ssr=0; %SSR for i = 1:30 ssr=ssr+(yf(x1(i),x2(i),x3(i))-sum(y)./30)^2; end sse=0; %SSE for i = 1:30 sse=sse+(y(i)-yf(x1(i),x2(i),x3(i))).^2; end rsquare=1-sse/sst %相关系数检验 msr=ssr/(3-1); mse=sse/(30-3); f=msr/mse %f检验 ``` #let code3 = ```matlab function t = yf(i,j,k) t=45.15-(0.0003392*i.^2-0.1969*i+28.4 ... +0.0001212184355522038*j.^2-0.064028817370481.*j+9.417872659555059+... (-3.829*k+2082)./(k+85.62)); end ``` #let code4 = ```matlab clc,clear,close all w=0.5; % 惯性 c1 = 0.8; % 个体经验 c2 = 0.9; % 社会经验 maxg = 500; % 迭代次数 N = 600; % 粒子数 Vmax = 1; % 速度范围 Vmin = -1; Xmax = 800; %变量取值范围 Xmin = 0; dim = 3; %函数表达式的自变量个数 for i=1:N location(i,:)=Xmax*abs(rands(1,dim)); %初始化坐标 V(i,:)=Vmax*rands(1,dim); %初始化速度 fitness(i)=yf(location(i,1),location(i,2),location(i,3)); %适应度 end [fitnessgbest,bestindex]=max(fitness);%fitnessgbest是全局最优解对应的适应度 gbest=location(bestindex,:); %全局最优解 pbest=location; %所有粒子的个体最优解 fitnesspbest=fitness; %所有粒子的个体最优解对应的适应度 for i=1:maxg for j=1:N % 根据惯性、个体最优pbest和群体最优gbest并更新速度 V(j,:) = w*V(j,:) + c1*(pbest(j,:) - location(j,:)) + c2*(gbest - location(j,:)); for k = 1:dim % 限制速度不能过大 if V(j,k) > Vmax V(j,k) = Vmax*0.9; elseif V(j,k) < Vmin V(j,k) = Vmin*0.9; end end location(j,:) = location(j,:) + V(j,:); % 更新位置 for k = 1:dim % 限制位置不能超过边界 if location(j,k) > Xmax location(j,k) = Xmax*0.9; elseif location(j,k) < Xmin location(j,k) = Xmin*0.9; end if location(j,3) > 700 location(j,3) = 650; end end %更新第j个粒子的适应度值 fitness(j) = yf(location(j,1),location(j,2),location(j,3)); end for j = 1:N if fitnesspbest(j) < fitness(j) %更新个体最优解 pbest(j,:) = location(j,:); fitnesspbest(j) = fitness(j); end if fitnessgbest < fitness(j) %群体最优更新 gbest = location(j,:); fitnessgbest = fitness(j); end end yy(i) = fitnessgbest; end figure; plot(yy) title('群体最优适应度','fontsize',12); xlabel('迭代代数','fontsize',18);ylabel('适应度','fontsize',18); ``` #let codeZip=( "B31.m第一问求解每个因素与参加人数的关系": code1, "B32.m 第二问求解总体回归方程模型": code2, "yf.m 第二问回归函数": code3, "PSO.m 粒子群算法求解最大值": code4 ) = 附录 #for (desc,code) in codeZip{ codeAppendix( code, caption: desc ) v(2em) }
https://github.com/SeniorMars/tree-sitter-typst
https://raw.githubusercontent.com/SeniorMars/tree-sitter-typst/main/examples/math/matrix.typ
typst
MIT License
// Test matrices. --- // Test semicolon syntax. #set align(center) $mat() dot.op mat(;) dot.op mat(1, 2) dot.op mat(1, 2;) \ mat(1; 2) dot.op mat(1, 2; 3, 4) dot.op mat(1 + &2, 1/2; &3, 4)$ --- // Test sparse matrix. $ mat( 1, 2, ..., 10; 2, 2, ..., 10; dots.v, dots.v, dots.down, dots.v; 10, 10, ..., 10; ) $ --- // Test baseline alignment. $ mat( a, b^2; sum_(x \ y) x, a^(1/2); zeta, alpha; ) $ --- // Test alternative delimiter. #set math.mat(delim: "[") $ mat(1, 2; 3, 4) $
https://github.com/DJmouton/Enseignement
https://raw.githubusercontent.com/DJmouton/Enseignement/main/SNT/Réseaux sociaux/Plan de séquence.typ
typst
#import "/Templates/layouts.typ": SNT, titre, sous_titre #show: doc => SNT(doc) //#import "@preview/fletcher:0.4.5" as fletcher: diagram, node, edge #titre[SNT: Séquence sur les Réseaux Sociaux] #outline() = Programme et objectifs #table( columns: (0.6fr, 1fr, 0.08fr), [*Contenus*], [*Capacités attendues*], [*ID*], "Identité numérique, e-réputation, identification authentification", "Connaître les principaux concepts liés à l'usage des réseaux sociaux.", "A", "Réseaux sociaux existants", "Distinguer plusieurs réseaux sociaux selon leurs caractéristiques, y compris un ordre de grandeur de leurs nombres d'abonnés. Paramétrer des abonnements pour assurer la confidentialité de données personnelles.", "B", "Modèle économique des réseaux sociaux", "Identifier les sources de revenus des entreprises de réseautage social.", "C", "Rayon, diamètre et centre d'un graphe", "Déterminer ces caractéristiques sur des graphes simples", "D", "Notion de « petit monde » Expérience de Milgram", "Décrire comment l'information présentée par les réseaux sociaux est conditionnée par le choix préalable de ses amis.", "E", "Cyberviolence", "Connaître les dispositions de l'article 222-33-2-2 du code pénal. Connaître les différentes formes de cyberviolence (harcèlement, discrimination, sexting...) et les ressources disponibles pour lutter contre la cyberviolence.", "F", table.cell(colspan: 3, [*Notions transversales*]), "Affectations, variables \nSéquences \nInstructions conditionnelles \nBoucles bornées et non bornées \nDéfinitions et appels de fonctions", "Écrire et développer des programmes pour répondre à des problèmes et modéliser des phénomènes physiques, économiques et sociaux.", "T1", ) La séquence est composée de 2 parties distinct: une partie "sociale" portant sur les différents aspect sociaux et économique ainsi que la cyberviolence, et une partie "réseau" qui porte sur la modélisation des réseaux sociaux et les impactes de ces relations. = Séances Les secondes de Champollion ont 1h de SNT une semaine sur deux et 2h l'autre semaine. Le programme de SNT nous laisse en moyenne 6h/séquence, ce qui nous fait 2 séances de 2h et 2 séance de 1h. #let phase_séance(nom, objectifs, durée, contenu, supports) = arguments(nom, objectifs, durée, contenu, supports) #let début_séance = phase_séance("Début de cours", "/", "5-10m", "Arrivé en classe, appel et questions flash/quiz", "Tableau") #let fin_séance = phase_séance("Fin de cours", "/", "5m", "Récap de la séance, questions et devoirs", "/") #let planning_séance(..args) = [ #set text(size: 10pt) #table( columns: (9.1em, 4.7em, 3.8em, 1fr, 5.1em), [*Phase*], [*Objectif*], [*Durée*], [*Contenu*], [*Supports*], ..args, ) ] == Séance 1 (2h): Fonctionnement des réseaux sociaux #planning_séance( ..début_séance, ..phase_séance("Contexte historique", "/", "5m", "Chronologie rapide des réseaux sociaux", "Tableau"), ..phase_séance("Activité charactéristique et revenu des réseaux sociaux", "B, C", "30m", "En binôme, les élèves iront se renseigner sur un réseau social en particulier, son fonctionnement et ses sources de revenu", "Internet, fiche d'activité"), ..phase_séance("Activité confidentialité", "B", "30m", "Étude de plusieurs documents lié à l'identité numérique et la confidentialité.", "Fiche d'activité"), ..phase_séance("Institutionalisation et exercices", "A, B, C", "45m", "Partie sur les caractéristiques des réseaux sociaux, les modèles économique des réseaux sociaux et l'idendité numérique et sa protection.", "Tableau, fiche de cours"), ..fin_séance ) == Séance 2 (1h): Cyberviolence #planning_séance( ..début_séance, ..phase_séance("Activité cyberviolence", "A, F", "30m", "Travail de recherche et de réflexion sur le cyberviolence, qui se conclura par un mini débat avec la classe", "Internet, fiche d'activité"), ..phase_séance("Institutionalisation", "A, F", "15m", "Partie sur les différentes formes de cyberviolence et de prévention", "Tableau, fiche de cours"), ..fin_séance ) == Séance 3 (2h): Modélisation des réseaux sociaux #planning_séance( ..début_séance, ..phase_séance("Activité petit monde et découverte des graphes", "D, E", "40m", "Par binôme, les élèves reproduirons une expérience du petit monde sur le web, puis découvriront les graphes via la représentation d'un réseau social", "Internet, fiche d'activité"), ..phase_séance("Contexte historique", "/", "5m", "Chronologie rapide sur les graphes", "Tableau"), ..phase_séance("Institutionalisation et exercices", "B, D, E", "50m", "Partie sur les graphes, la représentation des réseaux sociaux et l'importance des abonnements pour assurer sa confidentialité", "Tableau, fiche de cours"), ..fin_séance ) == Séance 4 (1h): Activité notée #planning_séance( ..début_séance, ..phase_séance("Activité représentation mathématique d'un réseau social", "D, T1", "45m", "Activité avec une matrice d'adjacence, de l'algorithmie et de la programmation. L'activité est ramassée et notée.", "PC, fichier source, IDE"), ..fin_séance ) = Évaluations [ TODO ] == Quiz fonctionnement == Quiz cyberviolence == Quiz modélisation == Évaluation sommative = Sources - éduscol - 3.0 - Cahier de SNT - Sciences Numériques et Technologie - SNT - 2de \* Cahier d'activités/d'exercices (Ed. 2020) - https://snt.ababsurdo.fr/prof/
https://github.com/ngyngcphu/tick3d-docs
https://raw.githubusercontent.com/ngyngcphu/tick3d-docs/main/contents/05_UI/index.typ
typst
Apache License 2.0
= User Interface Link design Figma UI: https://www.figma.com/file/oMo6KpmM4QVeibk0IUbAZx/Home-Page?type=design&node-id=0-1&mode=design&t=o6x6lRrhsQv2RsE0-0 == Trang chủ Tick3D #figure(caption: "Giao diện trang chủ", image("../images/UI/HomePage_edit.png", fit: "cover")) Các thành phần trong trang chủ của tick3D: #set enum(numbering:(it => strong[#it.])) #enum( enum.item(1)[ *Header*: biểu diễn những thông tin chính của trang chủ. #block(inset:(left:1cm))[ - Login and Signup: Điều hướng đến trang (chi tiết trong mục *5.2*). - Categories: phân loại mô hình, điều hướng người dùng đến trang danh mục mô hình 3D được phân loại theo các tiêu chí (chi tiết trong mục *5.3*). - Button tìm kiếm mô hình giúp người dùng tìm kiếm mô hình trong hệ thống. - Upload & print: Giúp điều hướng người dùng đến trang tải file `.gcode` (chi tiết trong mục *5.*). ] ], enum.item(2)[ *Slider*: các slide với nội dung hệ thống và mô hình liên tục được trình bày với mọi người. ], enum.item(3)[ *List Product*: Danh sách các mô hình được bán chạy nhất trên hệ thống. Khi nhấn chọn, người dùng sẽ được điều hướng đến trang chi tiết mô hình (chi tiết trong mục *5.4*). ], enum.item(4)[ *Footer*: Giúp người dùng nắm bắt thêm được những thông tin phụ của hệ thống như kênh liên lạc cũng như gửi lại phản hồi về hệ thống. ] ) #pagebreak() == Trang đăng nhập và đăng ký Người dùng sau khi nhấn vào các nút Đăng nhập, Đăng ký ở trang chủ sẽ được điều hướng đến trang đăng nhập và đăng ký. #figure(caption: "Giao diện trang đăng ký", image("../images/UI/SignupPage_edit.png", fit: "contain")) Các thành phần trong trang đăng ký #enum( enum.item(1)[ *Form điền thông tin đăng ký*: người dùng nhập những thông tin đăng ký trên hệ thống bao gồm họ tên, email, mật khẩu. ], enum.item(2)[ *Nút gửi*: Gửi thông tin của khách hàng vừa mới đăng ký lên để hệ thống xác thực và phản hồi. ] ) #figure(caption: "Giao diện trang đăng nhập", image("../images/UI/LoginPage_edit.png", fit: "contain")) Các thành phần trong trang đăng nhập #enum( enum.item(1)[ *Form điền thông tin đăng nhập*: người dùng tiến hành đăng nhập hệ thống bao gồm email, mật khẩu. ], enum.item(2)[ *Nút gửi*: Gửi thông tin của khách hàng vừa mới đăng nhập để hệ thống xác thực và phản hồi. ] ) #pagebreak() == Trang phân loại mô hình Để có thể truy cập được vào trang phân loại mô hình, người dùng đã thực hiện việc nhấn vào *Categories* trên thanh Header. #figure(caption: "Giao diện trang phân loại sản phẩm", image("../images/UI/CategoryPage_edit.png", fit: "contain")) Các thành phần trong trang phân loại mô hình #enum( enum.item(1)[ *Bộ lọc và sắp xếp mô hình *: Giúp lọc mô hình và sắp xếp sản phẩm theo các tiêu chí và ràng buộc. ], enum.item(2)[ *Phân loại*: Thanh sidebar phân loại mô hình giúp người dùng tìm được những mô hình theo các tiêu chí như thời trang, sở thích, học tập,... ], enum.item(3)[ *Số lượng mô hình*: Hiển thị ra tổng số lượng mô hình sau khi người dùng lọc và chọn theo phân loại. ], enum.item(4)[ *Danh sách mô hình*: Hiển thị ra danh sách các mô hình thuộc kiểu phân loại mà người dùng đã lựa chọn. Khi nhấp vào bất kì mô hình nào, người dùng được điều hướng sang trang chi tiết mô hình với nhiều mục đích như theo dõi thông tin mô hình, đặt hàng hoặc mua (chi tiết trong mục *5.4*). ] ) #pagebreak() == Trang chi tiết mô hình Để có thể truy cập vào trang chi tiết mô hình, người dùng đã thực hiện một trong hai thao tác sau: #block(inset:(left:1cm))[ - Nhấn vào chọn một trong các mô hình ở trang chủ của hệ thống. - Nhấn vào chọn một trong các mô hình trong danh sách sau khi chuyển hướng sang trang phân loại mô hình. ] #figure(caption: "Giao diện trang chi tiết mô hình", image("../images/UI/DetailModelPage_edit.png", fit: "contain")) Các thành phần trong trang chi tiết mô hình: #enum( enum.item(1)[ *Hình ảnh mô hình*: Cung cấp danh sách hình ảnh của mô hình để người dùng có cái nhìn rõ hơn trước khi đặt hàng. ], enum.item(2)[ *Thông tin sản phẩm*: tên, giá, mô tả sản phẩm. ], enum.item(3)[ *Nút điều chỉnh số lượng*: Người dùng điều chỉnh số lượng mô hình muốn đặt trước khi thực hiện việc đặt hàng hoặc in ấn. ], enum.item(4)[ *Nút thêm vào giỏ hàng*: Người dùng tiến hành thêm mô hình vào giỏ hàng sau khi đã chọn số lượng. Sau thao tác này, người dùng sẽ được chuyển hướng đến trang giỏ hàng (chi tiết trong mục *5.5*). ], enum.item(5)[ *Nút mua ngay*: Người dùng tiến hành mua luôn mô hình mà không cần thêm vào giỏ hàng. Sau thao tác này, người dùng sẽ được chuyển hướng tới trang thanh toán (chi tiết ở mục *5.6*). ] ) #pagebreak() == Trang giỏ hàng Để có thể truy cập được vào trang giỏ hàng, người dùng nhấn vào icon giỏ hàng trên thanh điều hướng. Trang sẽ hiển thị danh sách các mô hình có trong giỏ hàng của người dùng. #figure(caption: "Giao diện trang giỏ hàng", image("../images/UI/ShoppingCartPage_edit.png", fit: "contain")) Các thành phần của trang giỏ hàng: #enum( enum.item(1)[ *Nút điều hướng*: Giúp người dùng điều hướng về lại trang categories để tiếp tục chọn thêm mô hình trước khi thêm vào giỏ hàng. ], enum.item(2)[ *Giỏ hàng*: Hiển thị danh sách các mô hình đã được thêm vào giỏ hàng sau khi người dùng đã điều chỉnh số lượng và tiến hành thêm vào giỏ hàng ở trang chi tiết mô hình. ], enum.item(3)[ *Danh sách mô hình liên quan*: Hiển thị ra danh sách các mô hình có liên quan đến những mô hình có trong giỏ hàng mà người dùng có thể thích vì nhiều tiêu chí. ], enum.item(4)[ *Nút thanh toán*: Người dùng thực hiện việc thanh toán sau khi đã quyết định đơn hàng. Thao tác này sẽ điều hướng người dùng sang trang thanh toán (chi tiết trong mục *5.6*). ] ) #pagebreak() == Trang thanh toán Để có thể được điều hướng sang trang thanh toán, người dùng đã thực hiện một trong hai bước sau: #block(inset:(left:1cm))[ - Nhấn nút *"Mua ngay"* ở trang chi tiết mô hình. - Nhấn nút *"Thanh toán"* ở trang giỏ hàng. ] #figure(caption: "Giao diện trang thanh toán", image("../images/UI/CheckoutPage_edit.png", fit: "contain")) Các thành phần của trang thanh toán #block(inset:(left:1cm))[ - *Phương thức thanh toán*: người dùng lựa chọn phương thức thanh toán danh sách các mô hình. - *Form điền địa chỉ*: người dùng tiến hành nhập địa chỉ nhận hàng: số nhà, đường, quận, thành phố và ghi chú. - *Danh sách mô hình trong giỏ hàng*: Danh sách các mô hình có trong giỏ hàng, giúp người dùng kiểm tra lại về số lượng cũng như giá trước khi tiến hành thanh toán. - *Nút xác nhận*: Người dùng tiến hành xác nhận đơn hàng và tiến hành thanh toán. ] #pagebreak() == Trang overview quản lý mô hình Để có thể truy cập được vào trang quản lý mô hình, người quản trị đã đăng nhập bằng tài khoản quản trị. #figure(caption: "Giao diện trang quản lý mô hình", image("../images/UI/Manager_overview.png", fit: "contain")) Các thành phần của trang quản lý mô hình bao gồm các biểu đồ thống kê: #enum( enum.item(1)[ *Biểu đồ thống kê sản phẩm*: Hiển thị ra các biểu đồ thống kê về số lượng mô hình được đăng tải theo các danh mục sản phẩm. ], enum.item(2)[ *Biểu đồ thống kê sản phẩm được upload*: Hiển thị ra các biểu đồ thống kê về số lượng mô hình được upload theo thời gian. ], enum.item(3)[ *Biểu đồ thống kê top 10 sản phẩm*: Hiển thị ra các biểu đồ thống kê về top 10 sản phẩm được mua nhiều nhất. ], enum.item(4)[ *Biểu đồ thống kê người dùng*: Hiển thị ra các biểu đồ thống kê về số lượng người dùng cũ và mới. ], enum.item(5)[ *Biểu đồ thống kê doanh thu*: Hiển thị ra các biểu đồ thống kê về doanh thu theo thời gian. ] ) #pagebreak() == Trang quản lý mô hình 3D chi tiết Người quản trị sau khi nhấn vào một trong các mô hình ở trang quản lý mô hình sẽ được chuyển hướng sang trang quản lý mô hình chi tiết. #figure(caption: "Giao diện trang quản lý mô hình chi tiết", image("../images/UI/Manager_model.png", fit: "contain")) Các thành phần của trang quản lý mô hình chi tiết: #enum( enum.item(1)[ *Thông tin mô hình*: Hiển thị ra thông tin chi tiết của mô hình. Các thông tin của mô hình bao gồm: Tên mô hình, Ảnh mô hình, Thông tin chi tiết, Giá sản phẩm, Ngày chỉnh sửa. ], enum.item(2)[ *Cập nhật thông tin mô hình*: Người quản trị có thể tiến hành cập nhật thông tin của mô hình. ], enum.item(3)[ *Thống kê số lượng mô hình*: Hiển thị ra số lượng người mua mô hình, số lượng mô hình được bán ra, tổng doanh thu của mô hình. ], enum.item(4)[ *Thống kê bằng biểu đồ*: Hiển thị ra các biểu đồ thống kê về số lượng mô hình được mua theo thời gian và biểu đồ thống kê về doanh thu mô hình so với doanh thu của hệ thống. ], enum.item(5)[ *Danh sách người mua mô hình*: Hiển thị ra danh sách người mua mô hình. ] ) #pagebreak() == Trang quản lý đơn hàng Người quản trị sau khi nhấn vào nút *"Quản lý đơn hàng"* ở trang quản lý mô hình sẽ được chuyển hướng sang trang quản lý đơn hàng. #figure(caption: "Giao diện trang quản lý đơn hàng", image("../images/UI/Manager_order.png", fit: "contain")) Các thành phần của trang quản lý đơn hàng: #enum( enum.item(1)[ *Thanh quá trình đơn hàng*: Hiển thị ra các trạng thái của đơn hàng. ], enum.item(2)[ *Danh sách đơn hàng*: Hiển thị ra danh sách các đơn hàng của người dùng. ] ) Khi nhấn vào một trong các đơn hàng, người quản trị sẽ được chuyển hướng sang trang quản lý đơn hàng chi tiết. #figure(caption: "Giao diện trang quản lý đơn hàng chi tiết", image("../images/UI/Manager_detail.png", fit: "contain", height: 70%)) Thông tin của trang quản lý đơn hàng chi tiết bao gồm: Họ và tên khách hàng, Số điện thoại, Địa chỉ, Tổng tiền, Danh sách mô hình. #pagebreak()
https://github.com/Xe/automuse
https://raw.githubusercontent.com/Xe/automuse/main/paper/automuse_1/main.typ
typst
zlib License
#import "template.typ": conf #show: doc => conf( title: [ Automuse: A System for Generating Pulp Novels ], authors: ( ( name: "<NAME>", affiliation: "xn--g28h", email: "<EMAIL>", ), ( name: "<NAME>", affiliation: "xn--g28h", email: "<EMAIL>", ), ( name: "<NAME>", affiliation: "xn--g28h", email: "<EMAIL>", ), ( name: "<NAME>", affiliation: "xn--g28h", email: "<EMAIL>", ), ( name: "<NAME>", affiliation: "xn--g28h", email: "<EMAIL>", ), ( name: "<NAME>", affiliation: "xn--g28h", email: "<EMAIL>", ), ), abstract: [ A novel approach to generating fiction novels using a combination of Plotto, a system of plot formulas, and GPT-4, a state-of-the-art language model is presented. An eBook publication pipeline that automates the process of creating and formatting eBooks from the generated text is also described. The aim is to explore the potential and limitations of using artificial intelligence for creative writing, as well as to provide a tool for amusement and experimentation. ], doc, ) = Introduction Modern advancements in large language models such as GPT-4#cite("openai2023gpt4") present many opportunities when used creatively. There have been a few attempts at doing this such as *Echoes of Atlantis*#cite("Coetzee2023GPT4") which used the ChatGPT#cite("chatgpt") web UI to synthesize prose to fill a novel, but none of these options were sufficiently automated for the author's tastes. The goal of Automuse is to be able to fabricate these novels in minutes with little or no human intervention. As such, existing processes and published prior works were insufficient, requiring Automuse to be created. Automuse is distributed as a GitHub repository at #link("https://github.com/Xe/automuse") for anyone to download or attempt to use. Automuse wraps the following tools: - Plottoriffic to generate the overall premise of a story and to name the main dramatis personae. - The ChatGPT API to generate novel summary information, chapter summary information, and the prose of the novel. - Stable Diffusion to generate cover art for publication. - Pandoc to take generated prose and stitch it together into an eBook. == Motivation The authors discovered Plotto#cite("cook_1928"), a kind of algebra for generating the overall plot structure of pulp novels. This was written by <NAME>, a man affectionately known as "the man who deforested Canada", who had an impressive publishing record at up to one entire novel written every week. The authors wanted to find out if such a publishing pace could be met using the ChatGPT API. After experimentation and repair of plottoriffic#cite("Overton2016"), a Node.js package to implement Plotto's rule evaluation engine, Automuse was created. == Results According to the National November Writing Month rules#cite("NaNoWriMoRules"), the works of Automuse count as "novels". In testing, the program has been able to produce works of over 50,000 words (usually by a margin of 5-10 percent). The outputs of the program have been described as "hilarious", "partially nonsensical", and overall they have left readers wanting more somehow. The authors of this paper consider this to be a success, though they note that future research is required to ascertain as to why readers have an affinity towards the AI generated content. = Methodology When writing novels, generally a human author starts by creating the premise of a novel, the major actors and their functions, the overall motivations, and the end result of the story. Plotto is a system that helps you do all of this by following a series of rules to pick a core conflict and then flesh things out with details. As an example, here is the core plot summary that Potto created for Network Stranded: > Enterprise / Misfortune: Meeting with Misfortune and Being Cast Away in a Primitive, Isolated, and Savage Environment \ > \ > A Lawless Person \ > \ > Ismael takes a sea voyage in the hope of recovering aer health Ismael, taking a sea voyage, is shipwrecked and cast away on a desert island \ > \ > Ismael, of gentle birth and breeding, is isolated in a primitive, uninhabited wilderness, and compelled to battle with Nature for aer very existence \ > \ > Ismael, without food or water, is adrift in a small boat at sea \ > \ > Comes finally to the blank wall of enigma. It's worth noting that Plotto is very much a product of its time. Plotto was written in the late 1920's and as such the information it generates is very dated and can sometimes generate things that are seen as problematic in modern sensibilities. Luckily, ChatGPT seems to sand away this roughness and is able to fabricate a better premise. All the pronouns are replaced with ae/aer because that is a decision that the creator of Plottoriffic made at some point. == Summary Generation From this description, ChatGPT is used to create a plot summary for the novel. These summaries look like this: > After a disastrous turn of events, software engineer, Mia, finds herself stranded on a deserted island with no communication to the outside world. Mia uses her knowledge of peer to peer networks to create a makeshift communication system with other stranded individuals around the world, all connected by the same network. Together, they navigate survival and search for a way back to civilization while facing challenges posed by the island. Normally GPT "hallucinations" (or when the model generates grammatically valid nonsense) are seen as an impediment or something to avoid. In this case, hallucinations are actually useful, as the summaries from Plotto are rarely enough information to fabricate believable stories. It was intended as an aid to the writing process, not a replacement for it. In the same prompt, ChatGPT also creates a list of chapters for the novel with a high level summary of the events that happen in them. Here is the chapter list for Network Stranded: - Disaster Strikes - Mia's company experiences a catastrophic network failure leading to her being stranded on an island. - Stranded - Mia wakes up on a deserted island with limited supplies and no way to communicate. - Building Connections - Mia develops a peer to peer network to connect with other people stranded around the world. - Challenges of Survival - Mia and the other stranded individuals must navigate the hardships of surviving on the island. - Exploration - Mia and a small group of stranded people head out to explore the island. - Uncovering Secrets - During their exploration, Mia and the group discover hidden secrets about the island. - Frayed Relationships - As resources begin to dwindle, tensions rise among the stranded survivors. - Hopeful Discoveries - Mia receives a signal on her makeshift communication system, offering hope for rescue. - Setbacks - Mia experiences a crushing setback in her plans for rescue. - Moving Forward - Mia refuses to give up and formulates a new plan for rescue. - Unexpected Allies - Mia and the other stranded survivors meet another group of people on the island who agree to help with their rescue. - Facing Obstacles - Mia and the combined group must face obstacles and dangers as they try to implement their rescue plan. - Breaking Through - After a grueling journey and setbacks, the survivors finally make a breakthrough in their rescue efforts. - Homecoming - Mia and the other survivors return to civilization and adjust to life back in society. - The Aftermath - Mia reflects on her experiences and the impact of the peer to peer network on their survival and rescue. These chapter names and descriptions are fed into ChatGPT with the novel summary to create a list of scenes with major events in them. Here is the list of scenes for Chapter 1: "Disaster Strikes": - Mia frantically tries to contact someone for help, but her phone and computer are dead. She decides to go outside to search for a signal, but realizes she's on a deserted island. - As Mia tries to collect herself, she meets Ismael, who is also stranded on the island. They introduce themselves and discuss possible ways to survive. - Mia remembers her knowledge about peer to peer networks and brainstorms a plan to create a makeshift communication system with other stranded individuals around the world, all connected by the same network. - Mia and Ismael team up to scavenge for resources and build the communication system. They search for anything that could be used to amplify the signal, such as metal objects and wires. - They encounter a danger while searching for materials: venomous snakes. Mia and Ismael must use their survival skills to avoid getting bitten. - As the sun sets, Mia and Ismael finalize the communication system and connect with other stranded individuals on the network. They share their stories and discuss possible ways to get back home. These scene descriptions are fed into ChatGPT to generate plausible prose to describe the novel. The main innovation of this part is that ChatGPT is few-shot primed to continue each scene after initial writing. If ChatGPT emitted a scene such as: > As the helicopter landed, Ismael saw the first human beings he had seen in days. They jumped down from the helicopter, and looked at him with a mix of pity and relief. Ismael couldn't believe it – he was finally going home. \ > \ > As the helicopter took off, Ismael looked back at the deserted island, knowing that he had survived against all odds, but also knowing that he would never forget the terror and hopelessness that had left its mark on him forever. The next prompt would be primed with the last paragraph, allowing ChatGPT to continue writing the story in a plausible manner. This does not maintain context or event contiunity, however the authors consider this to be a feature. When the authors have access to the variant of GPT-4 with an expanded context window, they plan to use this to generate more detailed scenes. = Known Issues Automuse is known to have a number of implementation problems that may hinder efforts to use it in a productive manner. These include, but are not limited to the following: - Automuse uses GPT-3.5 to generate text. This has a number of problems and is overall unsuitable for making text that humans find aesthetically pleasing. - Automuse uses Plotto as a source of plot generation. Plotto was created in 1928 and reflects many stereotypes of its time. Careful filtering of Plotto summaries is required to avoid repeating harmful cultural and social biases. - Automuse does not maintain a context window for major events that occur during prose generation. This can create situations where events happen and then un-happen. This can be confusing for readers. == Potential Industry Effects According to <NAME>'s documentary about the predatory ghostwriting industry named Contrepreneurs: The Mikkensen Twins#cite("Olson2022"), the average pay rate for a ghostwriter for The Urban Writers can get as low as USD\$0.005 per word. Given that Automuse spends about USD\$0.20 to write about 50,000 words using GPT-3.5, this makes Automuse a significant cost reduction in the process for creating pulp novels, or about 1,250 times cheaper than hiring a human to perform the same job. This would make Automuse an incredibly cost-effective solution for churning out novels at an industrial scale. With a total unit development cost of USD\$0.35 (including additional costs for cover design with Stable Diffusion, etc.), this could displace the lower end of the human-authored creative writing profession by a significant margin. However, the quality of novels generated by Automuse is questionable at best. It falters and stubles with complicated contexts that haven't been written before. At one point in Network Stranded, the protagonist shares a secret to another character and that secret is never revealed to the reader. It is worth noting that the conditions that writers for groups like The Urban Writers are absolutely miserable. If this technology manages to displace them, this may be a blessing in disguise. The conditions put upon writers to meet quotas and deadlines are unimaginably strict. This technology could act as a means of liberation for people forced to endure these harsh conditions, allowing them to pursue other ventures that may be better uses of their time and skills. But, this would potentially funnel income away from them. In our capitalist society, income is required in order to afford basic necessities such as food, lodging, and clothing. This presents an ethical challenge that is beyond the scope of Automuse to fix. If an Automuse novel manages to generate more than USD\$1 of income, this will represent a net profit. More sales means that there is more profit potential, as novel generation costs are fixed upon synthesis of the prose. This program is known to use a very small amount of resources, it is concievable that a system could be set up on a very cheap (USD\$50 or less) development board running a freely available Linux distribution and then automatically create novels on a weekly cadence for less than a total cost of USD\$5 per month. = Conclusion Automuse is a promising solution for people looking to experiment with the use of large language models such as GPT-3.5 or GPT-4 to generate fiction prose. Automuse's source code and selected outputs are made freely available to the public for inspection and inspiration of future downstream projects. The authors of this paper hope that Automuse is entertaining and encourage readers to engage with the novel #link("https://xena.greedo.xeserv.us/books/network-stranded.html")[Network Stranded] as an example of Automuse's capabilities. There is a promising future ahead. #bibliography("citations.bib", style: "ieee")
https://github.com/kimushun1101/rengo2024-typst
https://raw.githubusercontent.com/kimushun1101/rengo2024-typst/main/README.md
markdown
MIT No Attribution
# rengo2024-typst 第67回自動制御連合講演会予稿集の原稿を Typst で書くときのテンプレートです. Typst の概要については https://typst.app/docs/tutorial/writing-in-typst/ をご覧ください. | ファイル | 説明 | | ------------- | ----------------------------------- | | sample.typ | 和文テンプレートの Typst ソースコード | | fig1.svg  | サンプル画像       | | refs.yml  | 参考文献リストのファイル YAML 形式 | | refs.bib  | 参考文献リストのファイル BiBTeX 形式  | | libs/rengo/lib.typ | 和文テンプレートのフォーマット  | | libs/rengo/rengo.csl | 参考文献リストのフォーマット  | `sample-en.typ` ファイルと `libs/rengo-en` ディレクトリは英文テンプレート用です. ## 使用方法 このファイルの最新版の入手は,[GitHub Releases のページ](https://github.com/kimushun1101/rengo2024-typst/releases/latest) からできます. GitHub に慣れている方は,`git clone` したり `use this template` したり,適宜扱ってください. ### VS Code を使用する場合 1. [VS Code](https://code.visualstudio.com/) をインストール. 2. VS Code で `File`→`Open Folder` でこのフォルダーを開く. 3. 拡張機能 [Tinymist Typst](https://marketplace.visualstudio.com/items?itemName=myriad-dreamin.tinymist) をインストール. 右下にポップアップでオススメの拡張機能として提案される.このポップアップ通知を切っている場合には,Extensions (`Ctrl` + `Shift` + `X`) の `Search Extensions in Marketplace` のテキストボックスに `@recommended` と入力すると表示される. 4. Explorer (`Ctrl` + `Shift` + `E`) から `main.typ` を開いた状態で,画面右上にある Typst Preview の方の ![view-icon](https://github.com/kimushun1101/typst-jp-conf-template/assets/13430937/a44c52cb-d23a-4fdb-ac9f-dc2b47deb40a) アイコンをクリック (`Ctrl` + `K` のあと `V`) でプレビューを表示. 5. `Ctrl` + `S` で PDF を生成. ### 公式 Web アプリを使用する場合 1. https://typst.app/ から `Sign up` してアカウントを作成する. 2. `New project` もしくは `Empty document` から新しいプロジェクトを作成する. 3. (2024.07.08 現在フォルダーごとアップロードすることはできないため,) 画面左にある `Explorer files` タブを開き,`Create a new folder` で,`libs` フォルダーやその下に `rengo` フォルダーを作成した後,そこに `libs/rengo/lib.typ` と `libs/rengo/rengo.csl` をアップロードする. 4. 同様に `sample.typ`,`fig1.svg`,`refs.yml` などをアップロードして,`sample.typ` を選択してビルドする. ### 他のエディターで執筆する場合 筆者は試せていませんが,他のエディターでも同様の拡張機能はあるようです. また,Typst のコンパイルはコマンドラインでも行えます. ``` typst compile sample.typ ``` コマンドラインインターフェイス (CLI) のインストールについてはこちら https://github.com/typst/typst?tab=readme-ov-file#installation ## ライセンス Typst で日本語論文を書くときのテンプレートとその使い方 : https://github.com/kimushun1101/typst-jp-conf-template をもとに作成しております. 参考元にならってライセンスを付与しています. Typst ファイル : MIT No Attribution CSL ファイル : Creative Commons Attribution-ShareAlike 3.0 License
https://github.com/augustebaum/epfl-thesis-typst
https://raw.githubusercontent.com/augustebaum/epfl-thesis-typst/main/README.md
markdown
MIT License
# EPFL Thesis template Port of [an unofficial LaTeX template](https://www.overleaf.com/latex/templates/swiss-federal-institute-of-technology-in-lausanne-epfl-phd-thesis/dhcgtppybcwv) to Typst. A complete example is shown in the [example folder](https://github.com/augustebaum/epfl-thesis-typst/blob/v0.1.1/example); see [example.pdf](https://github.com/augustebaum/epfl-thesis-typst/blob/v0.1.1/example/main.pdf) for the rendered PDF. The document structure can of course be adapted to your needs. ## Screenshots <div> <img src="https://github.com/augustebaum/epfl-thesis-typst/blob/v0.1.1/screenshots/cover_page.png" width=200px> <img src="https://github.com/augustebaum/epfl-thesis-typst/blob/v0.1.1/screenshots/acknowledgements.png" width=200px> <img src="https://github.com/augustebaum/epfl-thesis-typst/blob/v0.1.1/screenshots/tables_and_figures.png" width=200px> <img src="https://github.com/augustebaum/epfl-thesis-typst/blob/v0.1.1/screenshots/appendix.png" width=200px> </div> ## Usage You can use this template in the Typst web app by clicking "Start from template" on the dashboard and searching for `epfl`. Alternatively, you can use the CLI to kick this project off using the command ```sh typst init @preview/scholarly-epfl-thesis ``` Typst will create a new directory with all the files needed to get you started. This template uses certain fonts, including Utopia Latex for most text. If the font is not available to Typst, as is the case in the Typst Web App, then the template will fall back to a default font. The font is included in example shown in the Github repository [here](https://github.com/augustebaum/epfl-thesis-typst/blob/v0.1.1/example/utopia_font), otherwise you can download it however you like. ### Configuration This template exports the `template` function with the following named arguments: - `title`: The work's title. Default: `[Your Title]` - `author`: The author's name. Default: `"<NAME>"` - `paper-size`: The work's [paper size](https://typst.app/docs/reference/layout/page#parameters-paper). Default: `"a4"` - `date`: The work's date. Unused for now. Default: `none` - `date-format`: The format for displaying the work's date. By default, the date will be displayed as `MMMM DD, YYYY`. Unused for now. Default: `[month repr:long] [day padding:zero], [year repr:full]` The template will initialize your package with a basic call to the `template` function in a `show` rule. If you, however, want to change an existing project to use this template, you can add a show rule like this at the top of your file: ```typst #import "@preview/scholarly-epfl-thesis:0.1.1": * #show: template.with( title: [Your Title], author: "<NAME>", date: datetime(year: 2024, month: 03, day: 19), ) // Your content goes below. ``` Also included are the `front-matter`, `main-matter` and `back-matter` helpers which you can use in `show` rules in your document to change certain settings when they are called: e.g. reset the page numbering when main matter starts, or number headings with letters in the back matter. See [example/main.typ](https://github.com/augustebaum/epfl-thesis-typst/blob/v0.1.1/example/main.typ) for example usage. ## Development In order for Typst to access the Utopia Latex font, you need to include it your font path. I've included the font in `example/` so that you can run this in your shell: ```sh cd example typst w main.typ --font-path . ``` See [here](https://typst.app/docs/reference/text/text/#parameters-font) for more about the font path. ## Credits - The creators of the [ILM template](https://github.com/talal/ilm/blob/main/lib.typ) for the page layout, header and README format which I drew heavily from - The creators of the [original LateX template](https://www.overleaf.com/latex/templates/swiss-federal-institute-of-technology-in-lausanne-epfl-phd-thesis/dhcgtppybcwv) ## TODO - [ ] Hide header and page number on empty pages - Tracking issue: <https://github.com/typst/typst/issues/2722> - [ ] Quick fix: <https://github.com/typst/typst/issues/2722#issuecomment-1911150996> - Tried it, when I put it in the `show heading.where(level: 1)` it disrupts the outline. I guess it would work if you put in the `metadata` manually before each chapter. - Optionally don't force an empty page - [ ] Table of contents - [ ] Join abstracts into one outline entry - I removed the lines for the German and French abstracts so it takes less space, but it's not exactly the same as the original which has a custom outline entry - [ ] Style - [ ] Space between heading number and heading - [ ] Level 1 Headings are bold and don't have dot lines between the heading and the page number - <https://sitandr.github.io/typst-examples-book/book/snippets/chapters/outlines.html> - `outline.entry` can't be modified easily because the arguments are positional - I found a solution on discord but it strips away the links. I tried putting in a `link` manually but that gets formatted like a link in the text, which is not what we're looking for. - A solution to that link issue can be found in this thread: <https://discord.com/channels/1054443721975922748/1231526650462736474> - I might use <https://typst.app/universe/package/outrageous> - [x] Include list of figures and tables - [ ] Figures - [ ] Subfigures - tracking issue: <https://github.com/typst/typst/issues/246> - A wip: <https://github.com/tingerrr/subpar> - A quickfix: <https://github.com/typst/typst/issues/246#issuecomment-1928735969> - Works if you abuse the `kind` mechanic, but I can't get the superfigure's caption centered - [x] Short caption for table of contents - <https://sitandr.github.io/typst-examples-book/book/snippets/chapters/outlines.html> - [x] Numbering - i-figured? - [ ] Chemistry examples? - [ ] CV? - [x] Spacing after heading is different depending on if we're in frontmatter or main matter - [x] Cover page should take its values from the template arguments - cover page is separate from template, given that it is not meant to be printed anyways - this also reflects how the latex template works - [x] Spacing before new sub-heading - [x] Readme - [x] How-to - [x] Screenshots - [x] Thumbnail - [x] Refactor to `front-matter`, `main-matter`... - [x] Numbering - [x] Why are pagenumbers bold on certain pages? - There was a show rule that inserted a pagebreak before each chapter. This produced a bug where the chapter start pages was inconsistent with the information Typst has. - [x] numbering starts on acknowledgements (or somewhere else?) - [x] Equations - [x] Numbering - <https://sitandr.github.io/typst-examples-book/book/snippets/math/numbering.html> - [x] Align left - Why did `pad` work and not `h`? - [x] page numbers are too low in the page - [x] First-line indent for front matter - <https://typst.app/docs/reference/model/par/#parameters-first-line-indent> - Actually this looks unintentional? - [x] Appendices - [x] Margins - [x] Tables - [x] Style
https://github.com/TeddyHuang-00/typpuccino
https://raw.githubusercontent.com/TeddyHuang-00/typpuccino/main/src/lib.typ
typst
MIT License
#import "latte.typ" #import "frappe.typ" #import "macchiato.typ" #import "mocha.typ"
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/linebreak-no-justifiables_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set par(justify: true) #block(width: 1cm, fill: aqua, lorem(2))
https://github.com/elteammate/typst-compiler
https://raw.githubusercontent.com/elteammate/typst-compiler/main/src/reflection-lexer.typ
typst
#import "utils.typ": * #import "lexer.typ": * #let typst_token_kind = mk_enum( debug: true, "ident", "kw_let", "kw_set", "kw_show", "kw_if", "kw_else", "kw_for", "kw_while", "kw_break", "kw_continue", "kw_return", "kw_include", "kw_import", "kw_from", "kw_in", "kw_not", "kw_and", "kw_or", "punc_minus", "punc_plus", "punc_star", "punc_slash", "punc_dot", "punc_dotdot", "punc_eq", "punc_pluseq", "punc_minuseq", "punc_stareq", "punc_slasheq", "punc_eqeq", "punc_neq", "punc_lt", "punc_gt", "punc_le", "punc_ge", "punc_lparen", "punc_rparen", "punc_lbracket", "punc_rbracket", "punc_lbrace", "punc_rbrace", "punc_hash", "punc_comma", "punc_colon", "punc_arrow", "punc_semi", "punc_dollar", "literal_int", "literal_float", "literal_string", "literal_bool", "literal_none", "hspace", "vspace", "comment_line", "comment_block", "comment_doc", "comment_doc_outer", "type_cast", "unknown", "workaround_call_glue_parens", "workaround_call_glue_brackets", ) #let typst_keyword_mapping = ( "let": typst_token_kind.kw_let, "set": typst_token_kind.kw_set, "show": typst_token_kind.kw_show, "if": typst_token_kind.kw_if, "else": typst_token_kind.kw_else, "for": typst_token_kind.kw_for, "while": typst_token_kind.kw_while, "break": typst_token_kind.kw_break, "continue": typst_token_kind.kw_continue, "include": typst_token_kind.kw_include, "return": typst_token_kind.kw_return, "import": typst_token_kind.kw_import, "from": typst_token_kind.kw_from, "in": typst_token_kind.kw_in, "not": typst_token_kind.kw_not, "and": typst_token_kind.kw_and, "or": typst_token_kind.kw_or, "true": typst_token_kind.literal_bool, "false": typst_token_kind.literal_bool, "none": typst_token_kind.literal_none, ) #let typst_lexer = ( ("[\pL_][\pL\pN_\-]*", (m) => { if m.text in typst_keyword_mapping { typst_keyword_mapping.at(m.text) } else { typst_token_kind.ident } }), ("([0-9]*\.[0-9]+|[0-9]+\.[0-9]*|[0-9]+)[eE][\+\-]?[0-9]+", typst_token_kind.literal_float), ("([0-9]*\.[0-9]+|[0-9]+\.[0-9]*)", typst_token_kind.literal_float), ("[0-9]+", typst_token_kind.literal_int), ("\"([^\\\\\"]|\\\\.)*\"", typst_token_kind.literal_string), ("[^\S\n]+", typst_token_kind.hspace), ("\s*\n\s*", typst_token_kind.vspace), ("/\\*[a-zA-Z0-9_\-<>]+\\*/", typst_token_kind.type_cast), ("/// [^\n]*", typst_token_kind.comment_doc), ("//% [^\n]*", typst_token_kind.comment_doc_outer), ("//[^\n]*", typst_token_kind.comment_line), ("/\\*.+?\\*/", typst_token_kind.comment_block), ("#", typst_token_kind.punc_hash), ("\$", typst_token_kind.punc_dollar), (":", typst_token_kind.punc_colon), (";", typst_token_kind.punc_semi), ("\.\.", typst_token_kind.punc_dotdot), ("\.", typst_token_kind.punc_dot), (",", typst_token_kind.punc_comma), ("\{", typst_token_kind.punc_lbrace), ("\}", typst_token_kind.punc_rbrace), ("\[", typst_token_kind.punc_lbracket), ("\]", typst_token_kind.punc_rbracket), ("\(", typst_token_kind.punc_lparen), ("\)", typst_token_kind.punc_rparen), ("\+=", typst_token_kind.punc_pluseq), ("\+", typst_token_kind.punc_plus), ("\-=", typst_token_kind.punc_minuseq), ("\-", typst_token_kind.punc_minus), ("\*=", typst_token_kind.punc_stareq), ("\*", typst_token_kind.punc_star), ("/=", typst_token_kind.punc_slasheq), ("/", typst_token_kind.punc_slash), ("=>", typst_token_kind.punc_arrow), ("==", typst_token_kind.punc_eqeq), ("!=", typst_token_kind.punc_neq), ("<=", typst_token_kind.punc_le), (">=", typst_token_kind.punc_ge), ("<", typst_token_kind.punc_lt), (">", typst_token_kind.punc_gt), ("=", typst_token_kind.punc_eq), (".", typst_token_kind.unknown), ) #let postprocess_lexed(tokens) = { let context = mk_enum( "content", "code_hash", "code_hash_stmt", "code_line", "code_multiline", ) let context_stack = (context.content, ) let current_context = context.content let result = () tokens.push((kind: typst_token_kind.punc_rbracket)) for i, token in tokens { if current_context == context.code_hash_stmt { if token.kind in ( typst_token_kind.vspace, typst_token_kind.comment_line, typst_token_kind.punc_semi, typst_token_kind.punc_rbracket, ) { current_context = context_stack.pop() } } if current_context == context.code_hash { if token.kind in ( typst_token_kind.vspace, typst_token_kind.comment_line, typst_token_kind.punc_semi, typst_token_kind.punc_rbracket, typst_token_kind.hspace, typst_token_kind.comment_block, typst_token_kind.punc_rparen, typst_token_kind.punc_rbracket, typst_token_kind.punc_rbrace, typst_token_kind.punc_colon, ) { result.push((kind: typst_token_kind.punc_semi)) current_context = context_stack.pop() assert(current_context == context.content, message: "Unreachable?") } if token.kind in ( typst_token_kind.kw_let, typst_token_kind.kw_set, typst_token_kind.kw_show, typst_token_kind.kw_if, typst_token_kind.kw_for, typst_token_kind.kw_while, typst_token_kind.kw_break, typst_token_kind.kw_continue, typst_token_kind.kw_include, typst_token_kind.kw_return, typst_token_kind.kw_import, ) { context_stack.push(current_context) current_context = context.code_hash_stmt } } if current_context == context.content { if token.kind == typst_token_kind.punc_hash { context_stack.push(current_context) current_context = context.code_hash } else if token.kind not in ( typst_token_kind.punc_lbracket, typst_token_kind.punc_rbracket ) { if result.len() > 0 and result.last().kind == typst_token_kind.unknown { result.last().text += token.text } else { result.push((kind: typst_token_kind.unknown, text: token.text)) } continue } } else if current_context == context.code_line { if token.kind in (typst_token_kind.hspace, typst_token_kind.comment_block) { continue } else if token.kind in (typst_token_kind.vspace, typst_token_kind.comment_line) { result.push((kind: typst_token_kind.punc_semi)) continue } } else { if token.kind in ( typst_token_kind.hspace, typst_token_kind.comment_block, typst_token_kind.vspace, typst_token_kind.comment_line ) { continue } } if token.kind == typst_token_kind.punc_lparen and current_context != context.content { if i > 0 and tokens.at(i - 1).kind in ( typst_token_kind.ident, typst_token_kind.punc_rparen, typst_token_kind.punc_rbracket, typst_token_kind.punc_rbrace, ) { result.push((kind: typst_token_kind.workaround_call_glue_parens)) } context_stack.push(current_context) current_context = context.code_multiline } else if token.kind == typst_token_kind.punc_rparen and current_context != context.content { assert(current_context == context.code_multiline, message: "Unmatched parenthesis at: " + str(i)) current_context = context_stack.pop() } else if token.kind == typst_token_kind.punc_lbracket { if i > 0 and tokens.at(i - 1).kind in ( typst_token_kind.ident, typst_token_kind.punc_rparen, ) { result.push((kind: typst_token_kind.workaround_call_glue_brackets)) } context_stack.push(current_context) current_context = context.content } else if token.kind == typst_token_kind.punc_rbracket { assert(current_context == context.content, message: "Unmatched bracket") current_context = context_stack.pop() } else if token.kind == typst_token_kind.punc_lbrace and current_context != context.content { context_stack.push(current_context) current_context = context.code_line } else if token.kind == typst_token_kind.punc_rbrace and current_context != context.content { assert(current_context == context.code_line, message: "Unmatched brace") result.push((kind: typst_token_kind.punc_semi)) current_context = context_stack.pop() } result.push(token) } assert(context_stack.len() == 0, message: "Unclosed something") result.pop() return result } #let typst_lex_raw = compile_lexer(typst_lexer, (t, m) => ( kind: t, text: m.text, // span: span(m.start, m.end) )) #let typst_lex(source) = postprocess_lexed(typst_lex_raw(source)) #let lex_file(filename) = { // typst_lex(read(filename)).map(token => { // token.span.file = filename // token // }) typst_lex(read(filename)) } // #{ // typst_lex("#{x + (1 +\n 1)} [23] #{\nx\n\n} test").map(x => [#x]).join([ \ ]) // } // #lex_file("reflection-lexer.typ").map(x => [#x]).join([ \ ])
https://github.com/Tran-Thu-Le/typst-collection
https://raw.githubusercontent.com/Tran-Thu-Le/typst-collection/main/empty-doc-for-writting-notes/empty-doc.typ
typst
//----------------------------------------------- // Parameters //----------------------------------------------- // #let (background-color, text-color) = (black, white) #let (background-color, text-color) = (white, aqua) #let number-of-pages = 10 #let footer_left = [Author's name] #let footer_right = "Page " + counter(page).display("1/1",both: true) // #footer_right = #text(fill: black)[#footer_right] //----------------------------------------------- // Code for generating empty documents with lines //----------------------------------------------- #let footer = context [ #footer_left #h(1fr) #footer_right ] #set page( "a4", flipped: true, fill: background-color, footer: footer, ) #set text(text-color) #for i in range(26*number-of-pages) { if calc.rem(i, 2)==0 { line(length: 100%, stroke: 0.5pt+ text-color) } else { [\ ] } if calc.rem(i, 26)==0 and i>0{ pagebreak() } }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/brilliant-cv/2.0.0/docs.typ
typst
Apache License 2.0
/* * Documentation of the functions used in the template, powered by tidy. */ #import "@preview/tidy:0.3.0" #let version = toml("/typst.toml").package.version = brilliant-CV = Documentation on Template Functions #h(10pt) #rect[ _Build Date: #datetime.today().display()_ _Version: #version _ ] #h(10pt) #let docs = tidy.parse-module(read("cv.typ")) #tidy.show-module( docs, show-outline: false, omit-private-definitions: true, omit-private-parameters: true, )
https://github.com/jamesrswift/springer-spaniel
https://raw.githubusercontent.com/jamesrswift/springer-spaniel/main/tests/preamble.typ
typst
The Unlicense
#import "/src/lib.typ" as springer-spaniel
https://github.com/SillyFreak/typst-scrutinize
https://raw.githubusercontent.com/SillyFreak/typst-scrutinize/main/README.md
markdown
MIT License
# Scrutinize Scrutinize is a library for building exams, tests, etc. with Typst. It has three general areas of focus: - It helps with grading information: record the points that can be reached for each question and make them available for creating grading keys. - It provides a selection of question writing utilities, such as multiple choice or true/false questions. - It supports the creation of sample solutions by allowing to switch between the normal and "pre-filled" exam. Right now, providing a styled template is not part of this package's scope. Also, visual customization of the provided question templates is currently nonexistent. See the [manual](docs/manual.pdf) for details. ## Example <table> <tr> <td> <a href="gallery/gk-ek-austria.typ"> <img src="thumbnail.png"> </a> </td> <td> <a href="gallery/gk-ek-austria.typ"> <img src="thumbnail-solved.png"> </a> </td> </tr> </table> This example can be found in the [gallery](gallery/). Here are some excerpts from it: ```typ #import "@preview/scrutinize:0.3.0" as scrutinize: grading, task, solution, task-kinds #import task-kinds: free-form, gap, choice #import task: t // ... document setup ... #context { let ts = task.all(level: 2) let total = grading.total-points(ts) let grades = grading.grades( [F], 0.6 * total, [D], 0.7 * total, [C], 0.8 * total, [B], 0.9 * total, [A], ) // ... show the grading key ... } // ... = Basic competencies -- theoretical part B #lorem(40) == Writing #t(category: "b", points: 4) #lorem(30) #free-form.lines(stretch: 180%, lorem(20)) == Multiple Choice #t(category: "b", points: 2) #lorem(30) #{ set align(center) choice.multiple(( (lorem(3), true), (lorem(5), true), (lorem(4), false), )) } ```
https://github.com/AnsgarLichter/hka-thesis-template
https://raw.githubusercontent.com/AnsgarLichter/hka-thesis-template/main/chapters/A2_Transcripts.typ
typst
= Transcripts #lorem(500) == Interview 1 #lorem(250) === Details #lorem(250)
https://github.com/Akida31/anki-typst
https://raw.githubusercontent.com/Akida31/anki-typst/main/typst/src/theorems.typ
typst
#import "config.typ": is_export, anki_config #import "raw.typ" #import "utils.typ": assert_ty, to_plain, to_string #import "@preview/ctheorems:1.1.2" as ct // prevent shadowing #let _global_numbering = numbering #let anki_state = state( "anki_state", ( "deck": "", "model": "", ), ) #let secondary_numbering_counter = counter("anki-secondary-numbering") /// Set the current deck name. /// /// - name (str): New name. #let deck(name) = { anki_state.update(state => { state.deck = name state }) } /// Set the current model name. /// /// - name (str): New name. #let model(name) = { anki_state.update(state => { state.model = name state }) } // prevent shadowing #let _heading = heading /// Set the counter for the theorems. /// /// *Example*: /// #example(``` /// anki.theorems.set_thmcounter(items: (3, 5, 7)) /// // After this, the next item will have the number 1.0.2 /// anki.theorems.set_thmcounter(items: (1, 0, 1)) /// ```, ratio: 100, scale-preview: 100%) /// /// - heading (int, array, function): The new heading counter value. /// - items (array): The new item counter value. /// Each element in `items` corresponds to a level. /// The `base_level` argument of `item` corresponds to the number of `items`. #let set_thmcounter(heading: none, items: none) = { if heading == none { heading = items.slice(0, -1) } counter(_heading).update(heading) ct.thmcounters.update(val => { val.counters.heading = heading if items != none { val.counters.items = items val.latest = items } val }) } /// Get the current number. /// /// - loc (location): Current location. /// - number (auto, function, array): Primary number. /// - numbering (str, function, none): Primary numbering pattern /// - secondary (none, auto, true, function, array): Secondary number. /// - secondary_numbering (str, function, none): Secondary numbering pattern. /// - f (function): Closure which will be called with the resolved number. /// - allow_auto (bool): If `allow_auto` is `true`, `secondary` is `none` and `number` is auto, this will call the closure with just `auto`. /// - step_secondary (bool): Whether to step the secondary counter. /// This argument is necessary to prevent stepping the secondary counter multiple times for one item. #let _with_get_number(loc, number, numbering, secondary, secondary_numbering, f, allow_auto: false, step_secondary: true) = { if number == auto and allow_auto and secondary == none { return f(auto) + secondary_numbering_counter.update(0) } if secondary == none { secondary_numbering_counter.update(0) } let (secondary_counter,) = secondary_numbering_counter.at(loc) if step_secondary and (secondary == auto or secondary == true) { secondary_numbering_counter.step() secondary_counter += 1 } let secondary = secondary if secondary == auto or secondary == true { secondary = _global_numbering(secondary_numbering, secondary_counter) } let x = ct.thmcounters.at(loc) let prev = if numbering != none { _global_numbering(numbering, ..x.at("latest")) } else { none } if secondary != none { prev = prev + secondary } if number == auto { f(prev) } else if type(number) == function { f(number(prev)) } else { f(number) } } /// Get the deck name from headings. /// /// The headings will be joined with `::` to create anki subdecks. /// /// - loc (location): Current location /// - prefix_deck_names_with_numbers (bool): Whether the deck names will be prefixed with the corresponding heading number. /// -> str #let _get_headings(loc, prefix_deck_names_with_numbers) = { let levels = () let elems = query(selector(heading).before(loc)) for elem in elems { let body = to_plain(elem.body) if body == none { panic("headings must be plain text but got " + to_string(elem.body)) } if elem.level == levels.len() + 1 { levels.push(body) } else if elem.level <= levels.len() { levels = levels.slice(0, count: elem.level - 1) levels.push(body) } else { // TODO panic("missing heading level. Got heading '" + body + "' with level " + str(elem.level) + " but last heading had level " + str( levels.len(), )) } } if prefix_deck_names_with_numbers { let numbers = counter(heading).at(loc) levels = numbers.zip(levels).map(args => { let (number, body) = args str(number) + " - " + body }) } levels.join("::") } /// Same as `anki_thm` but takes the current location. /// /// This should improve performance if you already called `locate`. /// /// - loc (location): The current location. /// - id (str): The id of the card. Used to update the card later on. /// - tags (array): Tags to add to the card. /// - deck (none, str): Name of the deck. /// Anki nests decks with `::`, so you can try `Deck::Subdeck`. /// If `deck` is `none` it will be read from state. /// - model (none, str): Name of the model. /// If `model` is `none` it will be read from state. /// - number (auto, function, array): The primary number of the card. /// - numbering (str, function, none): The pattern for the primary number. /// - secondary (none, auto, true, function, array): The secondary number of the card. /// - secondary_numbering (str, function, none): The pattern for the secondary number. /// - ..fields (arguments): Additional fields for the anki card. #let _anki_thm_with_loc( loc, id, tags: (), deck: none, model: none, numbering: "1.1", number: auto, secondary: none, secondary_numbering: "a", ..fields, ) = { let _ = assert_ty("tags", tags, array) let state = anki_state.at(loc) let config = anki_config.at(loc) let deck = if deck != none { deck } else if state.deck != none and state.deck != "" { state.deck } else { let headings = _get_headings( loc, config.prefix_deck_names_with_numbers, ) if config.title != none and config.title != "" { config.title + "::" + headings } else { headings } } let model = if model != none { model } else if state.model != none and state.model != "" { state.model } else { "anki-typst" } _with_get_number( loc, number, numbering, secondary, secondary_numbering, step_secondary: false, number => raw._anki_export_with_config( config, id: id, tags: tags, deck: deck, model: model, number: number, ..fields, ), ) } /// Create an anki card. /// /// *Example* /// #example(``` /// #import anki.theorems: anki_thm /// /// #anki_thm( /// "id 29579", /// tags: ("Perfect", ), /// deck: "beauty", /// question: "Are you beautiful?", /// answer: "Yes!", /// ) /// ```, scale-preview: 100%, mode: "markup", preamble: "", scope: (_anki_thm_with_loc: anki.theorems._anki_thm_with_loc), ratio: 1000) /// /// - id (str): The id of the card. Used to update the card later on. /// - tags (array): Tags to add to the card. /// - deck (none, str): Name of the deck. /// Anki nests decks with `::`, so you can try `Deck::Subdeck`. /// If `deck` is `none` it will be read from state. /// - model (none, str): Name of the model. /// If `model` is `none` it will be read from state. /// - number (auto, function, array): The primary number of the card. /// - numbering (str, function, none): The pattern for the primary number. /// - secondary (none, auto, true, function, array): The secondary number of the card. /// - secondary_numbering (str, function, none): The pattern for the secondary number. /// - ..fields (arguments): Additional fields for the anki card. #let anki_thm( id, tags: (), deck: none, model: none, numbering: "1.1", number: auto, secondary: none, secondary_numbering: "a", ..fields, ) = { locate(loc => { _anki_thm_with_loc( loc, id, tags: tags, deck: deck, model: model, numbering: numbering, number: number, secondary: secondary, secondary_numbering: secondary_numbering, ..fields ) }) } /// Inner function which calls ctheorems. /// /// - loc (location): Current location. /// - export (bool): Whether export mode is enabled. /// - name (str): Name of the item for `ctheorems.thmbox`. /// - inner_args (dict): Arguments which will be passed to `ctheorems`. /// - base (none, str): Base for `ctheorems`. `none` means "do not attach, count globally". /// - base_level (none, int): The number of levels from base to take for item numbering. `none` means "use the base as-is". /// - breakable (bool): Argument to the `block` of `ctheorems`. Whether to allow (page) breaks inside the item. /// - create_item_label (bool): Whether to create a new label for this item. The label will be `item_level_prefix + name` /// - item_label_prefix (str): Prefix for item labels. /// - number (auto, function, array): The primary number of the card. /// - numbering (str, function, none): The pattern for the primary number. /// - secondary (none, auto, true, function, array): The secondary number of the card. /// - secondary_numbering (str, function, none): The pattern for the secondary number. /// - ..args (arguments): Arguments which will be passed to `ctheorems`. #let _item_inner( loc, export, name, inner_args: (:), base: "heading", base_level: none, breakable: true, create_item_label: true, item_label_prefix: "", number: auto, numbering: "1.1", secondary: none, secondary_numbering: "a", ..args, ) = { let item_name = name if export { let args_named = args.named() for key in ("inset", "separator") { let _ = args_named.remove(key, default: none) } let args_pos = args.pos() // not really used, just there to keep numbering let inner(name, content) = _with_get_number(loc, number, numbering, secondary, secondary_numbering, allow_auto: true, step_secondary: true, number => [ #ct.thmenv( "items", base, base_level, (..args) => [], ..args_pos, ..args_named, )( name, content, supplement: name, number: number, numbering: numbering, ..inner_args, ) #if create_item_label { let name = item_label_prefix + name label(name) } ]) return inner } else { let inner(name, content) = _with_get_number(loc, number, numbering, secondary, secondary_numbering,allow_auto: true, step_secondary: true, number => [ #ct.thmbox( "items", item_name, base: base, base_level: base_level, breakable: breakable, ..args, )(name, content, number: number, numbering: numbering, ..inner_args) #if create_item_label { let name = to_plain(name) if name != none { let name = item_label_prefix + name label(name) } } ]) return inner } } /// Make the body referenceable. /// /// This function is necessary because we use functions like `locate` which create opaque content, /// which can't be referenced. /// So this function wraps the content in a figure. /// /// - body (content): The body to wrap. /// - identifier (str): The identifier of the content. This will be available as metadata at `<meta:anki-thmenvcounter>` and the supplement of the figure. /// - numbering (none, str, function): The numbering of the figure. #let _make_referencable( body, identifier, numbering, ) = { figure( body + [#metadata(identifier) <meta:anki-thmenvcounter>], placement: none, caption: none, kind: "anki-item", supplement: identifier, numbering: numbering, gap: 0em, outlined: false, ) } /// Main function to create anki items. /// /// This function returns a function which represents an item kind. /// You can call the returned function multiple times to create multiple items. /// /// *Examples* /// #example(``` /// #import anki.theorems: item /// // Don't forget this! /// #show: anki.setup.with(enable_theorems: true) /// /// // create item kinds /// #let example = item("Example", initial_tags: ("example",)) /// #let theorem = item("Theorem", proof_name: "\"Proof\"") /// /// // create item /// #example("Pythagoras")[ /// $ a^2 + b^2 = c^2 $ /// ] /// /// // use secondary numbering /// #example("triangle", secondary: auto)[ /// #sym.triangle.tr.filled /// ] /// #example("another triangle", secondary: auto)[ /// #sym.triangle.t.stroked /// ] /// /// // and a theorem, with a custom number /// #theorem("Triangular numbers", number: "42")[ /// The triangular numbers are given by: /// $ T_n = sum_(k=1)^n k = (n(n+1))/2 $ /// ][ /// Induction over n. /// ] /// ```, scale-preview: 100%, mode: "markup", preamble: "") /// /// - name (str): Name of the item kind. /// - initial_tags (array): Tags to add to each item of this kind. /// To remove these tags pass `clear_tags: true` to the inner function. /// - base_level (none, int): The number of levels from headings to take for item numbering. /// `none` means "use all heading levels". /// - inset (relative, dictionary): How much to pad the block's content. /// - separator (content): Separator between name and body. /// - numbering (str, function, none): The numbering pattern for the primary number. /// - secondary_numbering (str, function): The numbering pattern for the secondary number. /// - create_item_label (bool): Whether to create a new label for each item of this kind. The label will be `item_level_prefix + name` /// - item_label_prefix (str): Prefix for item labels. /// - item_args (dict): Arguments which will be passed to `ctheorems` for each item of this kind. /// - id (function): Function to create the id of the card. /// The id must be unique as it is used to update cards later on. /// The function will be called with `plain_front, deck, model, number, secondary, ..fields`. /// - proof_name (str): How the proof (or in general second argument) should be called. /// - proof_args (dict): Arguments which will be passed to `ctheorems` for each proof. #let item( name, initial_tags: (), base_level: 2, inset: 0em, separator: [. #h(0.1em)], numbering: "1.1", secondary_numbering: "a", create_item_label: true, item_label_prefix: "", item_args: (:), id: fields => fields.at("plain_front"), proof_name: "Proof", proof_args: (:), ) = { /// Inner function to create anki items. /// /// - front (content, str): Front content for the card. /// - content (content): Main content for the card. /// - tags (array): Tags to add to the card. /// - deck (none, str): Name of the deck. /// Anki nests decks with `::`, so you can try `Deck::Subdeck`. /// If `deck` is `none` it will be read from state. /// - model (none, str): Name of the model. /// If `model` is `none` it will be read from state. /// - clear_tags (bool): Remove `initial_tags` and use only `tags`. /// - number (auto, function, array): The primary number of the card. /// - secondary (none, auto, true, function, array): The secondary number of the card. /// - ..maybe_proof (none, content): The proof of the card if specified. let inner( front, content, tags: (), deck: none, model: none, clear_tags: false, number: auto, secondary: none, ..maybe_proof, ) = { let proof = (() => { let pos = maybe_proof.pos() if pos.len() == 0 { for (key, value) in maybe_proof.named() { if key != "proof" { panic("expected only keyword `proof` but got " + str(key)) } return value; } return none } if pos.len() != 1 { panic("expected only one positional (`proof`) argument but got " + str(pos.len())) } return pos.at(0) })() let tags = if clear_tags { tags } else { (..initial_tags, ..tags) } let cont_meta = locate(loc => { let export = is_export(loc) let cont = { _item_inner( loc, export, name, base_level: base_level, create_item_label: create_item_label, item_label_prefix: item_label_prefix, inset: inset, separator: separator, number: number, secondary: secondary, secondary_numbering: secondary_numbering, inner_args: (numbering: numbering), ..item_args, )( front, content, ) if not export and proof != none { ct.thmplain( "items", proof_name, // base: "theorem", // TODO prefer these from `proof_args` titlefmt: strong, separator: [*.*#h(0.2em)], bodyfmt: body => [#body #h(1fr) $square$], padding: (top: -0.5em), inset: 0em, ..proof_args, ).with(numbering: none)(proof) } } let plain_front = to_plain(front) if plain_front == none { plain_front = front } let meta = if export { _with_get_number(loc, number, numbering, secondary, secondary_numbering, allow_auto: false, step_secondary: false, number => { let fields = ( front: front, back: content, proof: proof, ) let identifier = id(( plain_front: plain_front, deck: deck, model: model, number: number, secondary: secondary, ..fields )) return _anki_thm_with_loc( loc, identifier, deck: deck, model: model, number: number, numbering: numbering, secondary: secondary, secondary_numbering: secondary_numbering, tags: tags, ..fields, ) }) } else [ ] return cont + meta }) _make_referencable( cont_meta, name, numbering, ) } return inner } /// Show-rule for theorems. /// /// Copied from ctheorems, since we don't use `thm-qedhere` we can remove this functionality to get some speedups. /// /// - doc (content): The document to wrap. /// -> content #let _thmrules(doc) = { show figure.where(kind: "thmenv"): it => it.body show ref: it => { if it.element == none { return it } if it.element.func() != figure { return it } if it.element.kind != "thmenv" { return it } let supplement = it.element.supplement if it.citation.supplement != none { supplement = it.citation.supplement } let loc = it.element.location() let thms = query(selector(<meta:thmenvcounter>).after(loc), loc) let number = ct.thmcounters.at(thms.first().location()).at("latest") return link( it.target, [#supplement~#numbering(it.element.numbering, ..number)] ) } doc } /// Setup the document /// /// This is crucial for displaying everything correctly! /// /// *Example*: /// #example(`show: anki.theorems.setup`, ratio: 1000, scale-preview: 100%) /// /// - doc (content): The document to wrap. /// -> content #let setup(doc) = { show: _thmrules // copied from ctheorems show figure.where(kind: "anki-item"): it => it.body show ref: it => { if it.element == none { return it } if it.element.func() != figure { return it } if it.element.kind != "anki-item" { return it } let supplement = it.element.supplement if it.citation.supplement != none { supplement = it.citation.supplement } let loc = it.element.location() let thms = query(selector(<meta:anki-thmenvcounter>).after(loc), loc) let number = ct.thmcounters.at(thms.first().location()).at("latest") return link( it.target, [#supplement~#numbering(it.element.numbering, ..number)], ) } doc }
https://github.com/PgBiel/typst-truthtable
https://raw.githubusercontent.com/PgBiel/typst-truthtable/main/truthtable.typ
typst
MIT License
// Logic "true" object #let l-true(repr: $top$) = ( logic_dict: true, logic_type: "true", repr: [#repr], value: m => true, name: "TRUE", skip: true, children: () ) // Logic "false" object #let l-false(repr: $bot$) = ( logic_dict: true, logic_type: "false", repr: [#repr], name: "FALSE", value: m => false, skip: true, children: () ) // Converts bools to their equivalent logic objects #let l-bool(bool) = if bool { l-true() } else { l-false() } // Logic atomic variable / proposition / ... #let l-var(name, repr: none) = ( logic_dict: true, logic_type: "var", repr: if repr == none { $#name$ } else { [#repr] }, name: name, value: mapping => if name in mapping { mapping.at(name) } else { false }, skip: false, children: () ) // Convert a value to their equivalent logical object // Boolean becomes a true or false object; // A string becomes a logical variable; // All else must be a dictionary created by this library. #let l-logic-convert(val) = if type(val) == "boolean" { l-bool(val) } else if type(val) == "string" { l-var(val) } else if type(val) != "dictionary" { panic("Failed to convert value (of type '" + type(val) + "') to a logic object: Not a boolean, string or dictionary.") } else if "logic_dict" not in val or val.logic_dict != true { panic("Invalid dictionary given as logic object (must be a valid logic dictionary).") } else { val } // Represents an arbitrary logic operator or functor // Customize its representation with the 'repr' parameter #let l-operator( name, ..children, value: mapping => false, repr: none, skip: false, ) = ( logic_dict: true, logic_type: "operator", name: str(name), repr: if repr == none { [#name] } else { repr }, value: value, skip: skip, children: children.pos().map(l-logic-convert) ) // Return an expression's representation, // around parentheses if it has multiple children #let l-parens-repr-if-composite(expr) = { if expr.children.len() > 1 { $(#expr.repr)$ } else { $#expr.repr$ } } // Generate binary operator representation #let l-gen-binary-operator-repr(op, a, b, parens: auto) = { let a_repr = a.repr let b_repr = b.repr if parens == auto { a_repr = l-parens-repr-if-composite(a) b_repr = l-parens-repr-if-composite(b) } else if parens { // force parens a_repr = $(#a_repr)$ b_repr = $(#b_repr)$ } $#a_repr #op #b_repr$ } // Generate unry operator representation #let l-gen-unary-operator-repr(op, a, parens: auto) = { let a_repr = a.repr if parens == auto { a_repr = l-parens-repr-if-composite(a) } else if parens { // force parens a_repr = $(#a_repr)$ } $#op #a_repr$ } // Logic object for the AND operator #let l-and(a, b, parens: auto, skip: false) = { let a = l-logic-convert(a) let b = l-logic-convert(b) l-operator( "AND", a, b, value: mapping => (a.value)(mapping) and (b.value)(mapping), repr: l-gen-binary-operator-repr($and$, a, b, parens: parens), skip: skip, ) } // Logic object for the OR operator #let l-or(a, b, parens: auto, skip: false) = { let a = l-logic-convert(a) let b = l-logic-convert(b) l-operator( "OR", a, b, value: mapping => (a.value)(mapping) or (b.value)(mapping), repr: l-gen-binary-operator-repr($or$, a, b, parens: parens), skip: skip, ) } // Logic object for the NOT operator #let l-not(a, parens: auto, skip: false) = { let a = l-logic-convert(a) l-operator( "NOT", a, value: mapping => not (a.value)(mapping), repr: l-gen-unary-operator-repr($not$, a, parens: parens), skip: skip, ) } // Logic object for the IMPLIES operator #let l-imp(a, b, parens: auto, skip: false) = { let a = l-logic-convert(a) let b = l-logic-convert(b) l-operator( "IMP", a, b, value: mapping => (not (a.value)(mapping)) or (b.value)(mapping), repr: l-gen-binary-operator-repr($->$, a, b, parens: parens), skip: skip, ) } // Logic object for the IF AND ONLY IF operator #let l-iff(a, b, parens: auto, skip: false) = { let a = l-logic-convert(a) let b = l-logic-convert(b) l-operator( "IFF", a, b, value: mapping => (a.value)(mapping) == (b.value)(mapping), repr: l-gen-binary-operator-repr($<->$, a, b, parens: parens), skip: skip, ) } // Returns all atomic variables in the expression #let l-search-variables(expr) = { let children = expr.children if (children.len() == 0) { if (expr.logic_type not in ("true", "false")) { (expr,) } else { () } } else { children.map(c => l-search-variables(c)).flatten() } } // Returns 'true' if two logic objects // are likely to represent the same thing #let l-compare-logic-objects(a, b) = ( (type(a) == "dictionary") and (type(b) == "dictionary") and "logic_dict" in a and "logic_dict" in b and a.logic_dict and b.logic_dict and a.logic_type == b.logic_type and a.repr == b.repr and a.name == b.name and a.skip == b.skip ) // Returns all sub-expressions of an expression until the given // depth (-1 = unlimited) // 'unique: true' is used to ensure elements do not repeat // and 'initial_vars: true' ensures all variables are at the beginning // of the tree #let l-expr-tree( expr, max_depth: -1, unique: true, initial_vars: true ) = { if max_depth == 0 { // reached the max return () } if expr.logic_type in ("true", "false") { () } else { let subexprs = expr.children.map( c => l-expr-tree( c, max_depth: calc.max(-1, max_depth - 1), unique: false, // deal with it only on the first-level initial_vars: initial_vars)) // don't allow going below -1 ^ let res = subexprs.flatten() if initial_vars and expr.logic_type == "var" { res.insert(0, expr) // variable at the beginning } else { res.push(expr) } if unique { res.fold( (), (acc, expr) => { if acc.filter(l-compare-logic-objects.with(expr)).len() == 0 { acc + (expr,) } else { acc } } ) } else { res } } } // Generate all possible true/false combinations // of certain variables #let l-gen-true-false-maps(vars) = { if vars.len() == 0 { return () } let head = vars.first() // convert to string if ( type(head) == "dictionary" and "logic_dict" in head and head.logic_dict ) { head = head.name } else { head = str(head) } // Recursively generate T/F map for the rest of the // variable array let tail_res = l-gen-true-false-maps(vars.slice(1)) // this variable's single true/false combinations let true_d = (:) let false_d = (:) true_d.insert(head, true) false_d.insert(head, false) let res = () // join with the true/false combinations from the // other variables for d in tail_res { if head in d { // don't override this variable's existing values res.push(d) } else { res.push((: ..true_d, ..d)) res.push((: ..false_d, ..d)) } } if res.len() == 0 { // base case: only one variable => T/F (true_d, false_d) } else { res } } // Builds a truth table automatically from a logic // expression. Use 'repr_true' and 'repr_false' to // control the output of True and False values. // Any additional args are passed to the 'table' call // (such as 'fill'). // Use 'table_func' to override the default table function. #let truth-table( expr, repr_true: "T", repr_false: "F", table_func: table, ..table_args ) = { assert(type(table_func) == "function", message: "'table_func' must be a function") let vars = l-search-variables(expr) let varnames = vars.map(c => c.name) let mappings = l-gen-true-false-maps(varnames) let expr_tree = l-expr-tree(expr) .flatten() .filter(e => "skip" not in e or not e.skip) // initialize with the table headers let table_children = expr_tree.map(c => c.repr) for map in mappings { for expr in expr_tree { let bool_value = (expr.value)(map) table_children.push(if bool_value { [#repr_true] } else { [#repr_false] }) } } table_func( columns: (auto,) * expr_tree.len(), rows: (auto,) * mappings.len(), ..table_children, ..table_args.named()) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/babel/0.1.1/src/lib.typ
typst
Apache License 2.0
#import "baffle.typ": baffle, redact, tippex
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/direction/serverless.typ
typst
Apache License 2.0
#import "mod.typ": * #show: book-page.with(title: "Serverless rendering") #include "claim.typ" Example Application: #link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/github-pages/preview.html")[single-file] Run the entire typst directly in browser, like #link("https://typst.app")[typst.app]. == Key Descriptions It uses #cross-link("/guide/all-in-one.typ")[All-in-one (Simplified) Library for Browsers], using a single bundle for both compiler and renderer. Thought it is less flexible and stable than the underlying interfaces, it is pretty easy. The simplified library also teaches you how to use the underlying interfaces for better performance. ```js <script type="module" src="https://cdn.jsdelivr.net/npm/@myriaddreamin/typst.ts/dist/esm/contrib/all-in-one-lite.bundle.js" id="typst" ></script> ``` A ```html <textarea>``` is used to input the typst document, and a ```html <div>``` is used to render the document. ```js <textarea id="input">Hello, Typst!</textarea> <div id="content"></div> ``` To load wasm modules compiled from Rust from CDN, you need to set the module path for the compiler and renderer: ```js $typst.setCompilerInitOptions({ getModule: () => 'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-web-compiler/pkg/typst_ts_web_compiler_bg.wasm', }); $typst.setRendererInitOptions({ getModule: () => 'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-renderer/pkg/typst_ts_renderer_bg.wasm', }); ``` Sets input event handler and performs a first-time rendering: ```js input.oninput = () => { previewSvg(input.value); input.style.height = '5px'; input.style.height = input.scrollHeight + 'px'; }; previewSvg(input.value); ```
https://github.com/0xPARC/0xparc-intro-book
https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/fhe2.typ
typst
#import "preamble.typ":* = Public-key cryptography from LWE <lwe-crypto> In @lwe-small we saw how even a small case of this problem ($q = 11$, $n = 4$) can be annoyingly tricky. In the real world, you should imagine that $n$ and $q$ are much bigger – maybe $n$ is in the range $100 lt.eq n lt.eq 1000$, and $q$ could be anywhere from $n^2$ to $2^(sqrt(n))$, say. As an example of how LWE can be used, let’s see how to turn LWE into a public-key cryptosystem. We’ll use the same numbers from the "blue set" in @lwe-small. In fact, that "blue set" will be exactly the public key. #figure( align(center)[#table( columns: 1, align: (auto,), table.header([Public Key],), table.hline(), [(1, 0, 1, 7) : 2], [(5, 8, 4, 10) : 2], [(7, 7, 8, 5) : 3], [(5, 1, 10, 6) : 10], [(8, 0, 2, 4) : 9], [(9, 3, 0, 6) : 9], [(0, 6, 1, 6) : 9], [(0, 4, 9, 7) : 5], [(10, 7, 4, 10) : 10], [(5, 5, 10, 6) : 9], [(10, 7, 3, 1) : 9], [(0, 2, 5, 5) : 6], [(9, 10, 2, 1) : 3], [(3, 7, 2, 1) : 6], [(2, 3, 4, 5) : 3], [(2, 1, 6, 9) : 3], )] , kind: table ) The private key is simply the vector $a$. #figure( align(center)[#table( columns: 1, align: (auto,), table.header([Private Key],), table.hline(), [$upright(bold(a))$ = (10, 8, 10, 10)], )] , kind: table ) Since the LWE problem is hard, we can release the public key to everybody, and they will not be able to determine the private key. == Encryption <how-to-encrypt-mu> Suppose you have a message $m in { 0 , 5 }$. (You’ll see in a moment why we insist that $mu$ is one of these two values.) The ciphertext to encrypt $m$ will be a pair $(upright(bold(x)) : y)$, where $x$ is a vector, $y$ is a scalar, and $upright(bold(x)) dot.op upright(bold(a)) + epsilon.alt = y + m$, where $epsilon.alt$ is "small". How to do the encryption? If you’re trying to encrypt, you only have access to the public key -- that list of pairs $(upright(bold(x)) : y)$ above. You want to make up your own $upright(bold(x))$, for which you know approximately the value $upright(bold(x)) dot.op upright(bold(a))$. You could just take one of the vectors $upright(bold(x))$ from the table, but that wouldn’t be very secure: if I see your ciphertext, I can find that $upright(bold(x))$ in the table and use it to decrypt $mu$. Instead, you are going to combine several rows of the table to get your vector $upright(bold(x))$. Now you have to be careful: when you combine rows of the table, the errors will add up. We’re guaranteed that each row of the table has $epsilon.alt$ either $0$ or $1$. So if you add at most $4$ rows, then the total $epsilon.alt$ will be at most $4$. Since $mu$ is either $0$ or $5$ (and we’re working modulo $q = 11$), that’s just enough to determine $mu$ uniquely. So, here’s the method. You choose at random 4 (or fewer) rows of the table, and add them up to get a pair $(upright(bold(x)) : y_0)$ with $upright(bold(x)) dot.op upright(bold(a)) approx y_0$. Then you take $y = y_0 - m$ (mod $q = 11$ of course), and send the message $(upright(bold(x)) : y)$. == An example <an-example> Let’s say you randomly choose the 4 rows: #figure( align(center)[#table( columns: 1, align: (auto,), table.header([Some rows of public key],), table.hline(), [(1, 0, 1, 7) : 2], [(5, 8, 4, 10) : 2], [(7, 7, 8, 5) : 3], [(5, 1, 10, 6) : 10], )] , kind: table ) Now you add them up to get the following. #figure( align(center)[#table( columns: 1, align: (auto,), table.header([$upright(bold(x)) : y_0$],), [(7, 5, 1, 6) : 6], )], kind: table ) (For reference, the actual value is $4$, so our accumulated error is $2$.) Finally, let’s say your message is $m = 5$. So you set $y = y_0 - m = 6 - 5 = 1$, and send the ciphertext: #figure( align(center)[#table( columns: 1, align: (auto,), table.header([$upright(bold(x)) : y$],), [(7, 5, 1, 6) : 1], )], kind: table ) == Decryption <decryption> Decryption is easy! The decryptor knows $ upright(bold(x)) dot.op upright(bold(a)) + epsilon.alt = y + m $ where $0 lt.eq epsilon.alt lt.eq 4$. Plugging in $upright(bold(x))$ and $upright(bold(a))$, the decryptor computes $ upright(bold(x)) dot.op upright(bold(a)) = 4 . $ Plugging in $y = 1$, we see that $ 4 + epsilon.alt = 1 + m . $ Now it’s a simple "rounding" problem. We know that $epsilon.alt$ is small and positive, so $1 + m$ is either $4$ or … a little more. (In fact, it’s one of $4 , 5 , 6 , 7 , 8$.) On the other hand, since $m$ is 0 or 5, $1 + m$ had better be 1 or 6, so the only possibility is that $m = 5$ (so $1+m = 6$). == How does this work in general? <how-does-this-work-in-general> In practice, $n$ and $q$ are often much larger. Maybe $n$ is in the hundreds, and $q$ could be anywhere from "a little bigger than $n$" to "almost exponentially large in $n$," say $q = 2^(sqrt(n))$. In fact, to do FHE, we’re going to want to take $q$ pretty big, so you should imagine that $q approx 2^(sqrt(n))$. For security, instead of adding $4$ rows of the public key, we want to add at least $log (q^n) = n log q$ rows. To be safe, maybe a little bigger, say $N = 2 n log q$ (of course, for this to work, the public key has to have at least $N$ rows). The encryption algorithm will be "select some subset of the rows at random, and add them up". Combining $N$ rows will have the effect of multiplying the error by $N$, so if the initial $epsilon.alt$ was bounded by $1$, then the error in the ciphertext will be at most $N$. But remember that $q$ is exponentially large compared to $N$ and $n$ anyway, so a mere factor of $N$ should not scare us! To generalize our choice of $m$ in $\{0,5\}$, we could encode a single bit by using either $0$ or $⌊q / 2⌋$ to obtain maximum separation and thus tolerance to error. Alternatively, we could allow the message to be any multiple of some constant $r$, where $r$ is bigger than the error bound (right now that’s $m$), which allows you to encode a message space of size $q \/ r$ rather than just a single bit. When we do FHE, we’re going to apply many operations to a ciphertext, and each is going to cause the error to grow. We’re going to have to put some effort into keeping the error under control, and the size of $q\/ r$ will determine how many operations we can do before the error grows too big.
https://github.com/kitashimauni/report-tools
https://raw.githubusercontent.com/kitashimauni/report-tools/main/lib.typ
typst
#import "@preview/codelst:2.0.1": sourcefile // label関数の短縮形 #let l(arg) = { label(arg) } // 小見出しを表示する関数 #let subheading(it, size: 11pt) = { par(first-line-indent: 0em)[ #text(font: "Meiryo", size: size)[*#it*] ] } // TODOを強調表示する関数 #let todo(it) = { text(lang: "ja", font: ("Century", "Meiryo"), fill: red)[*TODO:* *#it*] } // spaceをn個入れる関数 #let spaces(n) = {$space$*n} #let space2 = spaces(2) #let space3 = spaces(3) #let space4 = spaces(4) // レポート用の個人用設定 #let mysetting(doc) = [ // テキスト関連の設定 // // デフォルト値 #set text( lang: "ja", font: ("Century", "MS Mincho"), size: 10.5pt, ) #set par( first-line-indent: 1em, justify: true, ) #set heading( numbering: (..args) => { let nums = args.pos() if nums.len() == 1 { return numbering("1.", ..nums) } else { return numbering("1.1", ..nums) } } ) #show heading.where(level: 1): set text(lang: "ja", font: ("Century", "MS Gothic"), size: 12pt) #show heading.where(level: 2): set text(lang: "ja", font: ("Century", "MS Gothic"), size: 11pt) #show heading.where(level: 3): set text(lang: "ja", font: ("Century", "MS Gothic"), size: 11pt) #show heading: it => { it par(text(size: 0em, "")) } // コードブロック用 #show raw: set text(lang: "ja", font: ("Consolas", "MS Mincho"), size: 10.5pt) // 図表関連の設定 // #show figure.where(kind: table): set figure.caption(position: top) #set grid(column-gutter: 10pt, row-gutter: 10pt) // 参照の設定 #show ref: it => { let eq = heading let el = it.element if el != none and el.func() == eq { // Override equation references. let numbers = ("章", "節", "項") let target = counter(eq).at(el.location()) let target_str = target.map(str) text[#target_str.join(".")#numbers.at(target.len() - 1)] } else { // Other references as usual. it } } // 便利系 // // 小見出し #let subheading_md = "-=-" #show regex("^" + subheading_md + " (.*)$"): it => { subheading(str(it.text).slice(subheading_md.len()+1)) } // TODO強調 #let todo_md = "(TODO|todo)" #show regex(todo_md + " \S*"): it => { todo(str(it.text).slice(4+1)) } #doc ] // ソースファイルからコードを挿入する関数(関数指定, クラス指定は現在pythonのみ対応) #let showCode( code, file, caption: none, range: none, func: none, class: none, diff: (-1, 0), showrange: none, ..args, ) = { if func != none or class != none { let txt = code.split("\n") let start = 0; let end = 0; let index = none; let count = 0 let funcName = regex(if(func!=none){("^\s*def ", func)}else{("^\s*class ", class)}.join()) if func == "__main__" {funcName = regex("if\s+__name__\s*==")} // 特殊指定 let spaceNum(line) = line.find(regex("(^\s*)")).len() for l in txt { count += 1 if (funcName in l) and index == none { index = spaceNum(l) start = count } else if not (regex("^\s*$") in l) and index != none and (spaceNum(l) > index) { end = count } else if not (regex("^\s*$") in l) and index != none and (spaceNum(l) <= index) { break } } range = (start + diff.at(0), end + diff.at(1)) } if showrange != none { range = showrange } return [ #set block(spacing: 0.5em) #sourcefile( code, file: file, showrange: range, ..args, ) #set align(center) #caption ] } // itembox的なもの(6ptから30pt程度を想定) いづれ改修するかも #let itembox( caption: none, space: 0pt, caption_padding: 0pt, stroke: black, radius: 6pt, inset: 8pt, ..args, body ) = [ #block( stroke: stroke, inset: inset, radius: radius, ..args )[ #context{ stack( dir: ttb, spacing: - 1em / 2 + space, [ #let place = { - (inset - 8pt) - 1em * 1.2 + { if text.size <= 8.5pt { - 0.2em - (8.5pt - text.size) / 1pt * 0.15em } else if 8.5pt <= text.size and text.size < 10.5pt { - 0.2em + 0.2em * ((text.size - 8.5pt) / 2pt) } else if 10.5pt <= text.size and text.size < 15.5pt { 0.2em * ((text.size - 10.5pt) / 5pt) } else if 15.5pt <= text.size and text.size < 20.5pt { 0.2em + 0.1em * ((text.size - 15.5pt) / 5pt) } else { 0.3em + (text.size - 20.5pt) / 10pt * 0.15em } } } #move( dx: 0pt, dy: place, )[ #block( fill: color.linear-rgb(255, 255, 255, 255), height: 1em, inset: ( left: 3pt + caption_padding, right: 3pt + caption_padding, top: 0.15em, bottom: 0pt ), above: 0pt, below: 0pt, [#caption] ) ] ], [ #body ] ) } ] ] #let cmd(cmd) = { box(raw(cmd), stroke: 0.5pt, inset: 0.5pt, outset: 2.5pt, radius: 4pt, fill: rgb(230, 230, 230)) }
https://github.com/dark-flames/resume
https://raw.githubusercontent.com/dark-flames/resume/main/data/edu.typ
typst
MIT License
#import "../libs.typ": * #import "../chicv.typ": * #let eduList(env) = ( multiLang( env, en: ( degree: "Master of Informatics", department: "Communication and Computer Engineering", university: "Kyoto University", location: "Kyoto, Japan", time: " Apr, 2022 - Mar, 2024", // GPA 3.31 /4.3 extend: [Advisor: <NAME>] ) ), multiLang( env, en: ( degree: "B.Eng.", department: "Computer Science", university: "Kumamoto University", location: "Kumamoto, Japan", time: " Oct, 2019 - March, 2022", extend: [] ) ), multiLang( env, en: ( degree: "B.Eng.", department: "IoT Engineering", university: "Shandong University", location: "Qingdao, Shandong, China", time: " Sep, 2017 - June, 2021", // GPA 3.93 /5.0 extend: [] ) ) ) #let edu(env) = { multiLang(env, en: [== Education], ja: [== 教育经历]) let c = eduList(env).map(e => { cventry( tl: strong(e.university), tr: e.time, bl: [*#e.degree* in #e.department], br: [#e.location], )[#e.extend] }).join() [#c] }
https://github.com/rikhuijzer/phd-thesis
https://raw.githubusercontent.com/rikhuijzer/phd-thesis/main/chapters/nederlandse-samenvatting.typ
typst
The Unlicense
#import "../style.typ": citefig #import "../functions.typ": chapter, textcite, parencite, note, avoid_indent #pagebreak() = Nederlanse samenvatting (Dutch Summary) #avoid_indent() Stelt u zich eens voor dat u vooraf kunt zeggen welke individuen een pilotenopleiding, een Harvard voorselectie, of zelfs in NASA's astronauten selectie kunnen halen. Dit zou veel teleurstelling bij individuen kunnen voorkomen en het zou organisaties veel tijd en geld kunnen besparen. Helaas zijn dit soort voorspellingen bijzonder moeilijk te maken. Een recruit kan bijvoorbeeld de beste in zijn opleiding zijn, maar toch uitvallen door problemen thuis of een misstap in een konijnenhol. Samen met het Korps Commandotroepen hebben wij onderzocht of wij kunnen voorspellen wie gaat uitvallen van de opleiding. Om dit te doen hebben wij data van 275 recruten verzameld in de vorm van sportdata (zoals 2800 meter hardlooptijd) en psychologische data (zoals persoonlijkheidsvragenlijsten). In hoofdstuk 2 hebben wij deze persoonlijkheids data uit de eerste week van de opleiding gebruikt. Op basis van deze data hebben wij onderzocht of wij persoonlijkheidskenmerken konden gebruiken om onderscheid te maken tussen mensen die zijn uitgevallen en mensen die zijn geslaagd. Ook hebben wij onze data vergeleken met data van Nederlandse burgers uit een ander onderzoek. We vonden dat commando's typisch minder neurotisch, meer consciëntieus en minder open voor ervaringen waren dan de burgers. Voor de geslaagden vonden wij dat ze typisch minder neurotisch en meer consciëntieus leken te zijn. Voor selectie leken de persoonlijkheidskenmerken niet voldoende voorspellend te zijn. Vanaf Hoofdstuk 3 hebben wij ons meer gericht op het voorspellen van uitval. In onze data analyses vonden wij dat veel statistische modellen niet goed presteerden op het gebied van voorspellend vermogen, stabiliteit of uitlegbaarheid. Daarom hebben wij een statistisch model wat bekend staat als _Stable and Interpretable RUle Sets_ (SIRUS) opnieuw geïmplementeerd in de programmeertaal Julia. Het doel van deze open-source implementatie was om het model beter te begrijpen en om het model beter toe te kunnen passen op onze data. Tevens zorgde deze vertaling ervoor dat het aantal regels code gereduceerd kon worden. Dit verhoogde de leesbaarheid voor onzelf en staat hopelijk in de toekomst andere onderzoekers toe om het algorithme te verbeteren of als de basis voor nieuwe algorithmes. Wij hebben het voorspellend vermogen van het model vergeleken met andere modellen en de originele implementatie. Hieruit bleek dat het voorspellend vermogen van onze implementatie vergelijkbaar was met de originele implementatie in de R programmeertaal. In hoofdstuk 4 hebben wij deze nieuwe implementatie en enkele andere modellen weer toegepast op de data uit de eerste week van de opleiding. Dit keer hebben wij niet alleen naar persoonlijkheid gekeken, maar ook naar de sportdata. Op deze data hebben wij vervolgens vier verschillende modellen vergeleken op voorspellingsvermogen, stabiliteit en uitlegbaarheid. We vonden dat het SIRUS model het meest geschikt was voor het voorspellen van uitval. Ook vonden wij dat fysieke en psychologische data beide gerelateerd waren aan uitval. Meer specifiek, een langzamere score op de 2800 meter hardlooptijd, verbondenheid, en een huidplooimeting waren sterk gerelateerd aan uitval. In hoofdstuk 5 hebben wij onderzocht of wij de voorspellingen konden verbeteren door de data gedurende de hele opleiding te verzamelen. Deze vragenlijsten waren korter, maar werden iedere week afgenomen in plaats van alleen in de eerste week. Wij hebben opnieuw meerdere machine learning modellen op de data getest. In dit geval was een lineaire regressie model het meest geschikt voor het voorspellen van uitval. Met dit model vonden wij dat lagere scores op zelfeffectiviteit en motivatie geassocieerd waren met uitval. We vonden ook dat het model in veel gevallen uitval al enkele weken van tevoren kon voorspellen. Dit biedt mogelijkheden voor het vroegtijdig ingrijpen om uitval te voorkomen. In conclusie, om de vraag te beantwoorden of wij kunnen voorspellen van de special forces opleiding: Uit hoofdstuk 4 en 5 lijkt het erop dat wij uitval redelijk goed kunnen voorspellen. Het volgende doel is om deze resultaten in de praktijk te testen, omdat dat de enige manier is om met zekerheid te weten hoe goed deze technieken werken.
https://github.com/jneug/typst-nassi
https://raw.githubusercontent.com/jneug/typst-nassi/main/src/elements.typ
typst
MIT License
#let TYPES = ( EMPTY: 0, PROCESS: 1, BRANCH: 2, SWITCH: 3, LOOP: 4, LOOP_2: 5, PARALLEL: 6, FUNCTION: 7, CALL: 8, ) #let element(type, text, ..args) = ( ( type: type, text: text, pos: (0, 0), width: auto, height: auto, inset: auto, grow: 0, fill: auto, stroke: auto, name: auto, ..args.named(), ), ) #let empty = element.with(TYPES.EMPTY, sym.emptyset) #let function(text, elements, ..args) = element( TYPES.FUNCTION, text, elements: elements, ..args.named(), ) #let process = element.with(TYPES.PROCESS) #let assign(var, expression, symbol: sym.arrow.l, ..args) = element( TYPES.PROCESS, var + " " + symbol + " " + expression, symbol: symbol, ..args.named(), ) #let call = element.with(TYPES.CALL) #let loop(text, elements, ..args) = element( TYPES.LOOP, text, elements: elements, ..args.named(), ) #let branch(text, left, right, column-split: 50%, labels: (), ..args) = element( TYPES.BRANCH, text, left: left, right: right, column-split: column-split / 100%, labels: labels, ..args.named(), ) #let switch(text, branches, labels: (), ..args) = element( TYPES.SWITCH, text, column-split: (branches.len() - 1) / branches.len(), branches: branches, labels: labels, ..args.named(), ) #let parallel(text, ..branches-args) = element( TYPES.PARALLEL, text, branches: branches-args.pos(), ..branches-args.named(), )
https://github.com/j1nxie/usth-graph-theory
https://raw.githubusercontent.com/j1nxie/usth-graph-theory/main/reports/cliques_hamiltonian_circuits.typ
typst
#set text(font: ("Noto Serif CJK JP"), hyphenate: false) #set par(justify: true) #set page( numbering: "1", paper: "a4", header: align(right)[BI12-009 <NAME> - Cliques and Hamiltonian Circuits], ) = Cliques 1. Use NetworkX to create a graph and add edges. ```py G = nx.random_graphs.random_regular_graph(3, 30, seed=42) ``` #line(length: 100%) 2. Implement a function to find all cliques of a specific size. ```py def find_cliques_n(graph: Graph, n: int) -> list: cliques = [] for clique in nx.find_cliques(graph): if len(clique) == n: cliques.append(clique) return cliques ``` #line(length: 100%) 3. Test the function with a graph and a given clique size `n`. ```py G = nx.random_graphs.random_regular_graph(3, 30, seed=42) result = find_cliques_n(G, 2) print(result) # [[0, 25], [0, 26], [0, 18], [1, 4], [2, 8], [2, 19], [2, 5], [3, 10], [3, 21], [3, 13], [4, 11], [4, 13], [5, 9], [5, 15], [6, 24], [7, 24], [7, 27], [7, 20], [8, 18], [8, 29], [9, 14], [9, 23], [10, 20], [10, 23], [11, 24], [11, 21], [12, 25], [12, 26], [12, 19], [13, 16], [14, 21], [14, 22], [15, 27], [15, 22], [16, 25], [16, 20], [17, 27], [19, 28], [22, 28], [23, 18], [28, 29], [29, 26]] ``` #line(length: 100%) 4. Using some simple random graphs, discuss how the computation time growing with the size of the graph (number of nodes and/or number of edges). ```py G = nx.random_graphs.random_regular_graph(3, 30, seed=42) result = find_cliques_n(G, 2) G = nx.random_graphs.random_regular_graph(4, 40, seed=42) result = find_cliques_n(G, 2) G = nx.random_graphs.random_regular_graph(5, 50, seed=42) result = find_cliques_n(G, 2) ``` The function `find_cliques_n(graph, n)` finds all cliques in the graph with size `n`. Internally, it calls the `find_cliques(graph)` function from NetworkX, the implementation of which is based on the algorithm published by Bron and Kerbosch (1973) @bron_1973_algorithm, as adapted by <NAME> and Takahashi (2006) @tomita_2006_the. This algorithm has the worst-case time complexity of $O(3^(n\/3))$, with $n$ being the size of the graph @tomita_2006_the. Given that `find_cliques_n(graph, n)` iterates through all the cliques returned by the function, if we consider number of said cliques as $m$, then the function overall will have a time complexity of $O(3^(n\/3)m)$. = Hamiltonian Circuits 1. What is the value returned by `find_hamiltonian_circuit`? (type and possible values) ```py def find_hamiltonian_circuit(graph: nx.Graph) -> Optional[List[int]]: """Find the Hamiltonian circuit in the given graph if it exists.""" path: List[int] = [-1] * len(graph.nodes()) # Let vertex 0 be the first vertex in the path path[0] = list(graph.nodes())[0] if not hamiltonian_circuit_util(graph, path, 1): print("No Hamiltonian circuit exists") return None else: # Return to the starting point path.append(path[0]) print("Hamiltonian circuit exists:\n", path) return path ``` The `find_hamiltonian_circuit` function returns a value of type `Optional[List[int]]`. This means that the function can return either a list of integers or None. The list of integers represents a Hamiltonian circuit in the given graph. A Hamiltonian circuit is a path that visits each node in the graph exactly once and returns to the starting node. The integers in the list are the nodes in the order they are visited in the circuit. If no Hamiltonian circuit exists in the graph, the function returns None. #line(length: 100%) 2. How is the backtracking implemented? Explain the relevant line(s) of code. ```py def hamiltonian_circuit_util(graph: nx.Graph, path: List[int], pos: int) -> bool: """Utility function to solve Hamiltonian Circuit problem using Backtracking.""" # Base case: if all vertices are in the path and there is an edge from the last included vertex to the first vertex if pos == len(graph.nodes()) and graph.has_edge(path[pos - 1], path[0]): return True # Try different vertices as the next candidate in Hamiltonian Circuit for v in graph.nodes(): if is_valid_vertex(graph, v, pos, path): path[pos] = v if hamiltonian_circuit_util(graph, path, pos + 1): return True # Remove current vertex if it doesn't lead to a solution path[pos] = -1 return False ``` The function iterates over all vertices in the graph with for v in `graph.nodes()`: For each vertex v, it checks if v can be added to the current path with if `is_valid_vertex(graph, v, pos, path)`:. A vertex can be added if it is adjacent to the last vertex in the path and it has not been included in the path yet. If v can be added to the path, it is added with `path[pos] = v`. The function then makes a recursive call to itself with if `hamiltonian_circuit_util(graph, path, pos + 1)`: to try to add the next vertex to the path. The pos + 1 argument means that the next position in the path is considered. If the recursive call returns True, this means that a Hamiltonian circuit has been found, and the function returns True with `return True`. If the recursive call returns False, this means that adding `v` to the path does not lead to a Hamiltonian circuit. In this case, `v` is removed from the path with `path[pos] = -1`. This is the backtracking step: it undoes the addition of `v` to the path, and the function will continue with the next iteration of the loop to try a different vertex. This process continues until all vertices have been tried. If no Hamiltonian circuit is found, the function returns False with `return False`. #line(length: 100%) 3. Run the program on various small graph. Plot the results and check if the solutions are correct (check also with graphs for which no hamiltonian path exist) ```py def plot_graph(graph: nx.Graph, path: Optional[List[int]]): """Plot the graph with the Hamiltonian circuit if it exists.""" pos = nx.spring_layout(graph) nx.draw(graph, pos, with_labels=True) if path is not None: edges = [(path[i - 1], path[i]) for i in range(1, len(path))] nx.draw_networkx_edges(graph, pos, edgelist=edges, edge_color='r', width=2) plt.show() if __name__ == "__main__": # Example usage graphs = [ nx.Graph([(0, 1), (0, 2), (1, 2), (2, 3), (3, 0)]), # Hamiltonian circuit exists nx.Graph([(0, 1), (0, 2), (1, 2), (2, 3)]), # No Hamiltonian circuit nx.Graph([(0, 1), (0, 2), (1, 2), (2, 3), (3, 4), (4, 0)]) # Hamiltonian circuit exists ] for G in graphs: path = find_hamiltonian_circuit(G) plot_graph(G, path) ``` #figure( image("assets/hamcir1.png", width: 60%), caption: [`Hamiltonian circuit exists: [0, 1, 2, 3, 0]`], ) #figure( image("assets/hamcir2.png", width: 60%), caption: [`No Hamiltonian circuit exists`], ) #figure( image("assets/hamcir3.png", width: 60%), caption: [`Hamiltonian circuit exists: [0, 1, 2, 3, 4, 0]`], ) #line(length: 100%) 4. Modify the code to count the number of times `hamiltonian_circuit_util` is called (eg using a global variable). Then try running on graphs with various values of n and look how the number of calls is growing with n. Discuss the results. ```py call_count = 0 def hamiltonian_circuit_util(graph: nx.Graph, path: List[int], pos: int) -> bool: global call_count call_count += 1 if pos == len(graph.nodes()) and graph.has_edge(path[pos - 1], path[0]): return True for v in graph.nodes(): if is_valid_vertex(graph, v, pos, path): path[pos] = v if hamiltonian_circuit_util(graph, path, pos + 1): return True path[pos] = -1 return False for n in range(1, 10): G = nx.complete_graph(n) path = find_hamiltonian_circuit(G) print(f"For n={n}, hamiltonian_circuit_util was called {call_count} times") call_count = 0 # Reset the count for the next run # No Hamiltonian circuit exists # For n=1, hamiltonian_circuit_util was called 1 times # Hamiltonian circuit exists: [0, 1, 0] # For n=2, hamiltonian_circuit_util was called 2 times # Hamiltonian circuit exists: [0, 1, 2, 0] # For n=3, hamiltonian_circuit_util was called 3 times # Hamiltonian circuit exists: [0, 1, 2, 3, 0] # For n=4, hamiltonian_circuit_util was called 4 times # Hamiltonian circuit exists: [0, 1, 2, 3, 4, 0] # For n=5, hamiltonian_circuit_util was called 5 times # Hamiltonian circuit exists: [0, 1, 2, 3, 4, 5, 0] # For n=6, hamiltonian_circuit_util was called 6 times # Hamiltonian circuit exists: [0, 1, 2, 3, 4, 5, 6, 0] # For n=7, hamiltonian_circuit_util was called 7 times # Hamiltonian circuit exists: [0, 1, 2, 3, 4, 5, 6, 7, 0] # For n=8, hamiltonian_circuit_util was called 8 times # Hamiltonian circuit exists: [0, 1, 2, 3, 4, 5, 6, 7, 8, 0] # For n=9, hamiltonian_circuit_util was called 9 times ``` The number of calls to `hamiltonian_circuit_util` grows exponentially with n. This is because the function uses a backtracking algorithm to find a Hamiltonian circuit, which has a worst-case time complexity of O(n!). For each vertex, it tries to add all other vertices to the path, leading to n! possible paths to check. This exponential growth means that the function can become very slow for large values of n. #bibliography("cliques_hamiltonian_circuits.bib")
https://github.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024/master/templates/text.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#let entry_text() = { set text( font: "Times New Roman", 14pt ) }
https://github.com/MyPedagogicalRessources/BUT1-R1-01-Initiation-developpement
https://raw.githubusercontent.com/MyPedagogicalRessources/BUT1-R1-01-Initiation-developpement/main/TD/TD2-Trace-dessins-enonce.typ
typst
#import "TD2-Trace-dessins.typ":* #td2(isCorrection: false)
https://github.com/francorbacho/cv
https://raw.githubusercontent.com/francorbacho/cv/master/alt.typ
typst
#let esei = {image("resources/esei-icon-192x192.png", height: 20pt, fit: "contain")} #let pk = {image("resources/pk-icon-426x426.png", height: 20pt, fit: "contain")} #let uvigomotorsport = {image("resources/uvigomotorsport-icon-500x500.png", height: 20pt, fit: "contain")}
https://github.com/ivaquero/book-control
https://raw.githubusercontent.com/ivaquero/book-control/main/04-时域响应分析.typ
typst
#import "@local/scibook:0.1.0": * #show: doc => conf( title: "时域响应分析", author: ("ivaquero"), header-cap: "现代控制理论", footer-cap: "github@ivaquero", outline-on: false, doc, ) = 一阶系统 <一阶系统> == 单位阶跃响应 对一阶系统,其传递函数的形式通常为 $ G(s) = frac(a, s + a) $ 若输入为 $ u(t) = cases(delim: "{", 0 & t = 0, 1 & t > 0) $ 则 $ ℒ[u(t)] &= ∫_0^(+∞) 1⋅e^(-s t) dd(t)\ &= -1 / s e^(-s t) bar.v_0^∞ = 1 / s $ 于是 $ X(s) = U(s) G(s) = 1 / s frac(a, s + a) = 1 / s - frac(1, s + a) $ 对等式两端同时进行 Laplace 逆变换,得 $ x(t) = 1 - e^(-a t) $ 当$t = τ = 1/a$ $ x(τ) = x(1 / a) = 1 - e^(-1) = 0.63 $ 此处 - $τ$:#strong[时间常数(time constant)],反映系统响应速度。 - $T_("ss")$:#strong[稳定时间(settlingtime)],通常定义为$4τ$,即 $ x(t_(s s)) = x(4 / a) = 1 - e^(-4) = 0.98 $ 对于如下系统 #figure( image("./images/model/liquid.drawio.png", width: 40%), caption: [流体系统], supplement: "图", ) $ x(t) = frac(C R, g)(1 - e^(-g / R t)) $ 则其传递函数 $ G(s) = frac(1, s + g/R) $ 可得 $ τ = frac(1, g/R) = R / g $ #tip[ 上述流体系统的传递函数$frac(a, s + a)$是一个典型的低通滤波,其特点之一是数值积累,又如积分运算。 ] 又 $ ℒ[u(t)] = ℒ[C e^0] = C frac(1, s + 0) = C 1 / s $ 从而有 $ X(s) &= U(s) G(s)\ &= C 1 / s frac(1, s + g/R)\ &= frac(C R, g)(frac(1, s - 0) - frac(1, s + g/R)) $ 最终得 $ x(t) = ℒ^(-1)(X(s)) &= frac(C R, g)(e^(o t) - e^(-g / R t))\ &= frac(C R, g)(1 - e^(-g / R t)) $ 即得到极点。 == 相图视角 <相图视角> 对 LTI 系统 $ dot(x) + a x = a u, med x(0) = dot(x)(0) = 0 $ 若$u = 1$ $ dot(x) = a(1 - x) $ 通过分析$x ̇$-$x$的图像,可以得出$x$的变化趋势。 #pagebreak() = 二阶系统 <二阶系统> == 弹簧阻尼系统 <弹簧阻尼系统> #figure( image("./images/model/vibration.drawio.png", width: 40%), caption: [振动阻尼系统], supplement: "图", ) 对弹簧阻尼系统 $ m dot.double(x) = F - k x - B dot(x) $ 整理得 $ dot.double(x) + B / m dot(x) + k / m x = F $ 这里定义 - $ω_n = sqrt(k/m)$:固有频率 - $ζ = frac(B, 2 sqrt(k m))$:阻尼比 设初始时刻没有外力,即初始条件为 - $x_((0)) = 5$ - $dot(x)_((0)) = 0$ 代入原方程,得 $ dot.double(x) + 2 ζ ω_n dot(x) + ω_n^2 x = 0 $ 即 $ dot.double(x) = -2 ζ ω_n dot(x)- ω_n^2 x $ 对微分方程,其解的形式为$x(t) = e^(λ t)$,于是可知 - $dot(x) = λ e^(λ t)$ - $dot.double(x) = λ^2 e^(λ t)$ 回代入上述方程,得 $ (λ^2 + 2 ζ ω_n λ + ω_n^2) e^(λ t) = 0 $ 显然,由于$e^(λ t) ≠ 0$,第一个因式 $ λ^2 + 2 ζ ω_n λ + ω_n^2 = 0 $ 此式即为特征方程。 解之,得 $ λ_1 &= -ξ ω_n + w_n sqrt(xi^2 - 1)\ λ_2 &= -ξ ω_n - ω_n sqrt(xi^2 - 1) $ == 动态响应 <动态响应> 对特征方程 - 当$ζ > 1$,此时系统处于过阻尼状态(over damped),即阻尼力很大,该极点为#strong[稳定节点]。 此时有解 $ x(t) = C_1 e^(λ_1 t) + C_2 e^(λ_2 t) $ #tip[ 解收敛,且收敛速度取决于$λ_1$。 ] - 当$ζ = 1$,此时系统处于临界状态,$λ_1 = λ_2 = ω_n$ 此时有解 $ x(t) = (C_1 + C_2 t) e^(λ t) $ - 当$0 < ζ < 1$,此时系统处于欠阻尼状态(under damped),该节点为#strong[稳定焦点]。 此时有解 $ x(t) = e^(-ζ ω_n t)(C_1 cos ω_n sqrt(1 - ζ^2)t + C_2 sin ω_n sqrt(1 - ζ^2)t) $ 令$ω_d = ω_n sqrt(1 - ζ^2)$,称阻尼固有频率(damped natural frequency),可得 $ x(t) = e^(-ζ ω_n t) sqrt(c_1 + c_2)(sin(ω_dd(t) + ϕ)) $ 其中,$ϕ = arctan c_1\/c_2$。 此时,系统振幅在震动中衰减,且震动周期为$2π\/ω_d$。 #tip[ 欠阻尼是日常生活中最常见的状态 ] - 当$ζ = 0$,此时系统处于无阻尼状态,该极点为#strong[中心点]。 此时有解,图像为正弦函数,周期为$2π\/ω_n$ $ x_((t)) &= e^0 (c_1 cos ω_n t + c_2 sin ω_n t)\ &= sqrt(c_1 + c_2) sin(ω_n t + ϕ) $ - 当$-1 < ζ < 0$或$ζ < - 1$,得到的解是发散的,图像与各自取符号后的图像趋势相反。 == 极点与零点 <极点与零点> 对上述弹簧阻尼系统,定义输入为 $ u(t) = F / ω_n^2 $ #tip[ 即单位化的外力 ] 输出为位移$x(t)$,从而有 $ dot.double(x) + 2 ζ ω_n dot(x) + ω_n^2 x = ω_n^2 u(t) $ 两端同时 Laplace 变换,得 $ H(s) = frac(X(s), U(s)) = frac(ω_n^2, s^2 + 2 ζ ω_n s + ω_n^2) $ 从而有 $ X(s) = 1 / s frac(ω_n^2, s^2 + 2 ζ ω_n s + ω_n^2) $ 因子之一即特征方程 $ s^2 + 2 ζ ω_n s + ω_n^2 = 0 $ 可以找到极值点 - $P_1 = 0$ - $P_2 = -ζ ω_n + i ω_n sqrt(1 - ζ^2)$ - $P_3 = -ζ ω_n - i ω_n sqrt(1 - ζ^2)$ 于是 $ X(s) &= frac(A, s - p_1) + frac(B, s - p_2) + frac(C, s - p_3)\ &= frac(A (s - p_2)(s - p_3) + B (s - p_1)(s - p_3) + C (s - p_1)(s - p_2), (s - p_1)(s - p_2)(s - p_s)) $ 已知 $ A (s - p_2)(s - p_3) + B (s - p_1)(s - p_3) + C (s - p_1)(s - p_2) = ω_n^2 $ - 令$s = P_1$,得$A = 1$ - 令$s = P_2$,得 $ B = -1 / 2 (1 - ζ / sqrt(1 - ζ^2) i) $ - 令$s = P_3$,得 $ C = -1 / 2 (1 + ζ / sqrt(1 - ζ^2) i) $ 代回原方程 $ x(t) = 1 - e^(-ζ ω_n t) sqrt(frac(1, 1 - ζ^2)) sin(ω_dd(t) + ϕ) $ 其中 - 正弦函数$sin(ω_dd(t) + ϕ)$的频率为$w_d$(周期为$2π/w_d$) - $e^(-ζ ω_n t)$是一个衰减(单调递减)函数 #pagebreak() = 性能分析 <性能分析> == 指标 <指标> - $T_d$:延迟时间(delay time),系统达到稳态 50% 的时间 - $T_r$:上升时间(rise time),系统首次达到稳定点的时间,即正弦函数首次为$0$的时间,此时 $ T_r = frac(π - ϕ, ω_d) $ - $M_p$:最大超调量(max overshot),峰值与稳态值的差值与稳定值的百分比,即 $ M_p = e^(-ζ π / sqrt(1 - ζ^2)) × 100% $ - $T_(s s)$:调节时间(settling time):系统进入稳态范围内的时间,稳态范围通常选择稳定值的$±2%$或$±5%$,即 - $2%$:$T_(s s) = 4\/ζ ω_n$ - $5%$:$T_(s s) = 3\/ζ ω_n$ == 比较 <比较> - $T_r$:反映系统的响应速度,越短越好 - $M_p$:反映系统的稳定性,越小越好 - $T_(s s)$:越短越好 给定以上指标比重 - 列表,计算总得分 - 在`x-y-z`坐标系中,描点连线,计算面积
https://github.com/catppuccin/typst
https://raw.githubusercontent.com/catppuccin/typst/main/src/flavors/catppuccin-latte.typ
typst
MIT License
#let latte = ( name: "Latte", emoji: "🌻", order: 0, dark: false, light: true, colors: ( rosewater: ( name: "Rosewater", order: 0, hex: "#dc8a78", rgb: rgb(220, 138, 120), accent: true, ), flamingo: ( name: "Flamingo", order: 1, hex: "#dd7878", rgb: rgb(221, 120, 120), accent: true, ), pink: ( name: "Pink", order: 2, hex: "#ea76cb", rgb: rgb(234, 118, 203), accent: true, ), mauve: ( name: "Mauve", order: 3, hex: "#8839ef", rgb: rgb(136, 57, 239), accent: true, ), red: ( name: "Red", order: 4, hex: "#d20f39", rgb: rgb(210, 15, 57), accent: true, ), maroon: ( name: "Maroon", order: 5, hex: "#e64553", rgb: rgb(230, 69, 83), accent: true, ), peach: ( name: "Peach", order: 6, hex: "#fe640b", rgb: rgb(254, 100, 11), accent: true, ), yellow: ( name: "Yellow", order: 7, hex: "#df8e1d", rgb: rgb(223, 142, 29), accent: true, ), green: ( name: "Green", order: 8, hex: "#40a02b", rgb: rgb(64, 160, 43), accent: true, ), teal: ( name: "Teal", order: 9, hex: "#179299", rgb: rgb(23, 146, 153), accent: true, ), sky: ( name: "Sky", order: 10, hex: "#04a5e5", rgb: rgb(4, 165, 229), accent: true, ), sapphire: ( name: "Sapphire", order: 11, hex: "#209fb5", rgb: rgb(32, 159, 181), accent: true, ), blue: ( name: "Blue", order: 12, hex: "#1e66f5", rgb: rgb(30, 102, 245), accent: true, ), lavender: ( name: "Lavender", order: 13, hex: "#7287fd", rgb: rgb(114, 135, 253), accent: true, ), text: ( name: "Text", order: 14, hex: "#4c4f69", rgb: rgb(76, 79, 105), accent: false, ), subtext1: ( name: "Subtext 1", order: 15, hex: "#5c5f77", rgb: rgb(92, 95, 119), accent: false, ), subtext0: ( name: "Subtext 0", order: 16, hex: "#6c6f85", rgb: rgb(108, 111, 133), accent: false, ), overlay2: ( name: "Overlay 2", order: 17, hex: "#7c7f93", rgb: rgb(124, 127, 147), accent: false, ), overlay1: ( name: "Overlay 1", order: 18, hex: "#8c8fa1", rgb: rgb(140, 143, 161), accent: false, ), overlay0: ( name: "Overlay 0", order: 19, hex: "#9ca0b0", rgb: rgb(156, 160, 176), accent: false, ), surface2: ( name: "Surface 2", order: 20, hex: "#acb0be", rgb: rgb(172, 176, 190), accent: false, ), surface1: ( name: "Surface 1", order: 21, hex: "#bcc0cc", rgb: rgb(188, 192, 204), accent: false, ), surface0: ( name: "Surface 0", order: 22, hex: "#ccd0da", rgb: rgb(204, 208, 218), accent: false, ), base: ( name: "Base", order: 23, hex: "#eff1f5", rgb: rgb(239, 241, 245), accent: false, ), mantle: ( name: "Mantle", order: 24, hex: "#e6e9ef", rgb: rgb(230, 233, 239), accent: false, ), crust: ( name: "Crust", order: 25, hex: "#dce0e8", rgb: rgb(220, 224, 232), accent: false, ), ), )
https://github.com/HarryLuoo/sp24
https://raw.githubusercontent.com/HarryLuoo/sp24/main/431/notes/part3.typ
typst
#set math.equation(numbering:"(1)") #set heading(numbering: "1.1") = Sums of independent r.v.& Symmetry == Convolution of two distributions given two independent r.v. $X$ and $Y$, the distribution of $Z = X + Y$ is the convolution of the distributions of $X$ and $Y$. + when $X$ and $Y$ are both discrete, the pmf of $X+Y$ is given by $ p_(X+Y) (n) = p_X convolve p_Y (n) = sum_(k) p_X(k) p_Y(n-k) = sum_(k) p_X(n-k) p_Y(k) $ + when $X$ and $Y$ are both continuous, the pdf of $X+Y$ is given by $ f_(X+Y) (z) = f_X convolve f_Y (z) = integral_(-infinity)^(infinity) f_X (z-y) f_Y (y) d y = integral_(-infinity)^(infinity) f_X (z-y) f_Y (y) d y $ - _example: convolution of geometric random variables_ let X and Y be independent geometric random variables with the same suvvess parameter $p <1$ , find the distrbution of $Z = X + Y$. We know $p_X (k) = p_Y (k) = p (1-p)^(k-1) med k>=1$ r.v. $Z = X + Y$ takes on values $n = 2, 3, ...$. Via the convolution magic promised above, we have $ P(X+Y=n) &= sum_(k=-infinity)^(infinity) P(X=k) P(Y = n-k) \ &= sum_(k=1)^(n-1) p(X=k) P(Y=n-k) \ & = sum_(k=1)^(n-1) p(1-p)^(k-1) p(1-p)^(n-k-1) \ & = sum_(k=1)^(n-1) p^2(1-p)^(n-2) \ & = (n-1)p^2(1-p)^(n-2) $ == Negative binomial distribution Coming off from the geometric distribution, we have the negative binomial distribution, which is the distribution of the number of trials needed to get $r$ successes in a sequence of independent Bernoulli trials with success probability $p$. Its distribution, i.e. pmf, is given by $ P(X=n) = binom(-1,k-1) p^k (1-p)^(n-k) quad (n>= k) $ abbriviate this by $X~ "Negbin" (k,p)$ , where the geometric is a special case with $k=1$. == Collection of normal distributed r.v.s For $X_i ~ cal(N)(mu_i, sigma_i^2), med X = sum_(i) a_i X_i $ , we know $ X~cal(N) (mu, sigma^2) \ "where" mu = sum_(i) a_i mu_i, med sigma^2 = sum_(i) a_i^2 sigma_i^2 $ in other words, the sum of normal distributed r.v.s is also normal distributed. == Exchangeable r.v.s a sequence of r.v.s $X_1, X_2, X_3, ..., X_n$ is *exchangable* if the following condition holds: for any permutation $(k_1,k_2,k_3)$ of $(1,2,...,n)$, we have $ (X_1,X_2,...,X_n) =^d (X_(k_1),X_(k_2),...,X_(k_n)) $ - *How to check exchangability* "it just works" method: check if the r.v. are identically distributed, i.e. if marginal pdf or pmf is the same. Suppose $X_1,X_2,...,X_n$are discrete random variables with joint probability mass function $p$. Then these random variables are exchangeable if and only if $p$ is a symmetric function. Suppose $X_1,X_2,...,X_n$ are jointly continuous random variables with joint density function $f$.Then these random variables are exchangeable if and only if $f$ is a symmetric function. If the expectation is conserved under permutations of our set of r.v.s. *Importantly, if the r.v.s are independent and identically distributed, they are also exchangeable.* remarks: + r.v. denoting outcomes of sampling without replacement $X_1,X_2,...X_n$ are exchangeable. + For any function g dependent on , the r.v.s $g(X_1),g(X_2),...,g(X_n)$ are exchangeable. == Expectation and Varience of Multivariable r.v. === Expectation: linear $ E[g_1(X_1) + g_2(X_2) + ...+g_n (X_n)] = E[g_1(X_1)] + E[g_2(X_2)] + ...+ E[g_n (X_n)] $ $ E[X_1+X_2+...+X_n] = E[X_1] + E[X_2] + ...+ E[X_n] $ Expectation of a sum is always the sum of expectations. === Varience: sum of independent r.v., linear $ "Var"(X_1+X_2+...+X_n) = "Var"(X_1) + "Var"(X_2) + ...+ "Var"(X_n) $ === The indicator method - _example_ We draw five cards from a deck of 52 without replaceement. Let X denote the number of Aces among the chosen cards. Find the expected value of X. Two ways to solve this: + Since order does not matter in our draw of 5, by argument of exchangability, we can construct the following inditator: $ I_i = cases(1 quad "if the ith card is an ace", 0 quad "otherwise") $ Since X is the number of Aces among our 5 cards, we have $ X = I_1 + I_2 + I_3 + I_4 + I_5 $ Recall the linearity of expectation, we can rephrase the expected value as $ E[X] = E[I_1] + E[I_2] + E[I_3] + E[I_4] + E[I_5] $ <eq.expt> Since r.v. $I_i$ are exchangeable, we have $ E[I_1] = E[I_2] = E[I_3] = E[I_4] = E[I_5] $ @eq.expt becomes $ 5*E[I_1]= 5 * P(I_1 = 1) = 5 * 4/52 = 5/13 $ + We can also label the Aces in the total deck as 1,2,3,4, and have our indicators $j_1,j_2,j_3,j_4$ indicating if the ith Ace is in our draw or not. The number of Aces in our draw is then $X = j_1+j_2+j_3+j_4$. By similar arguements of exchangability, we have $E[X] = 4E[J_1] = 4 P("one of the ace is among the 5 cards")$. Notice that $ P("one of the ace is among the 5 cards") = (binom(1,1), binom(51,4))/(binom(52,5)) = 5/52 \ => E[X] = 5/13 $ === Expectation of multiple products let $X_1, X_2, X_3$ be independend r.v., when for all function $g_1,g_2,g_3$ $ E[product_(i=1)^3 g_i(X_i)] = product_(i=1)^3 E[g_i(X_i)] $ == Moment generating function with sums of r.v. For independent r.v. $X,Y$, and mgf $M_X (t) , med M_Y (t)$, $ M_(X+Y) (t) = M_X (t) M_Y (t) $ == Covariance and correlation === Covariance $ "Cov"(X,Y) = E[(X-E[X])(Y-E[Y])] = E[X Y] - E[X]E[Y] $ - X&Y are - positively correlated if $"Cov"(X,Y) > 0$ - negatively correlated if $"Cov"(X,Y) < 0$ - uncorrelated if $"Cov"(X,Y) = 0$ === Properties of Covariance - $"COV"(X,Y) = "COV" (Y,X)$ - $"COV" (a X +b,Y) = a "COV"(X,Y)$ - for any r.v. $X_i,Y_j$ and real numbers $a_i,b_j$:$ "COV"(sum_(i=1)^n a_i X_i, sum_(j=1)^m b_j Y_j) = sum_(i=1)^n sum_(j=1)^m a_i b_j "COV"(X_i,Y_j) $ - Practically, $ "Cov"(Y_1+Y_2, Z) = "Cov"(Y_1,Z) + "Cov"(Y_2,Z) \ "Cov"(X,X) = "Var"(X) \ $ === Variance of sum of r.v.s $ "Var" (sum_(i = 1)^(n) X_i) = sum_(i= 1)^(n) "Var" (X_i) + 2 sum_(i<=i<j<=n) "Cov"(X_i,X_j)) $ For two r.v.s, this comes down to $ "Var" (X+Y) = "Var" (x) +" Var" (Y ) + 2 "Cov"(X,Y) $ For three r.v.s, this is uglier... $ "Var" (X+Y+Z) \ = "Var" (X) + "Var" (Y) + "Var" (Z) + 2 "Cov"(X,Y) + 2 "Cov"(X,Z) + 2 "Cov"(Y,Z) $ You dont want to compute this for four or more... === Correlation $ "Corr"(X,Y) = "Cov"(X,Y) / sqrt("Var"(X) "Var"(Y)) $ = Tail bounds and limit theorems == Markov's inequality For any non-negative r.v. $X$ and any $a>0$, we have $ P(X>=a) <= E[X]/a $ == Chebyshev's inequality For any r.v. $X$ with finite mean and variance, and any $k>0$, we have $ P(|X-E[X]|>=k) <= "Var"(X)/k^2 $ normally used to find $P(X >= c+ mu) <= (sigma^2)/(c^2) "and"quad P(X<= mu-c)<= (sigma^2)/(c^2)$ == generalized Law of large numbers For a sequence of iid r.v.s $X_1,X_2,...,X_n$ with finite mean $E[X_i] = mu$ and finite variance $"Var" [X_i] = sigma^2$, letting $S_n = X_1+X_2+...+X_n$, for any $epsilon > 0$, we have $ lim_(n -> infinity) P(|S_n/n - mu| < epsilon) = 1 $ == Generalized Central Limit Theorem For a sequence of iid r.v.s $X_1,X_2,...,X_n$, where n is the sample size, with finite mean $E[X_i] = mu$ and finite variance $"Var" [X_i] = sigma^2$, letting $S_n = X_1+X_2+...+X_n$, we have $ lim_(n -> infinity) P(a <= (S_n - n mu)/(sigma sqrt(n) )<= b) = Phi(b) - Phi(a) $ More practically, we use $ P(S>= k) = P((S_n-n mu)/(sqrt(n sigma^2) ) >= (k-n mu)/(sqrt(n sigma^2) )) = 1- Phi((k-n mu)/(sqrt(n sigma^2) )) $ = Conditional distribution A combination of conditional probability and marginal distribution. == Discrete conditional distribution recall the conditional probability $ P(A|B) = (P(A sect B))/(B), "for" P(B)>0 $ When A is now a r.v., we have the conditional distribution $ p_(X|B) (k) = P(X=k|B) = P({X=k} sect B)/P(B) $ === Conditional expectation of X, given event B $ E[X|B] = sum_(k) k P(X=k|B) $<eq.conditioned-exp> === Unconditiond pmf of X $ p_X (k) = sum_(i=1)^(n) p_(X|B_i) (k)med P(B_i) $ <eq.unconditoned-exp> - From @eq.conditioned-exp and @eq.unconditoned-exp we get $ E[X] = sum_(i = 1)^(n) E[X|B_i] P(B_i) $ === Conditioning on r.v. When both X and Y are r.v.s, we can have the following two-variable function$ p_(X|Y) (k|j) = P(X=k|Y=j) = P({X=k},{Y=j})/P(Y=j) = (p_(X,Y) (k,j))/(p_Y (j)) $ === Conditional expectation of X, given Y=Y $ E[X|Y=j] = sum_(k) k P(X=k|Y=j) = sum_(k) k p_(X|Y) (k|j) $ === Unconditioned pmf with 2 r.v.S $ p_(X) (k) = sum_(i) p_(X|Y) (k|j) med p_Y (j) $ - From this, we can derive the unconditioned expectation of X and Y $ E[X] = sum_(k) E[X|Y=j]med p_Y (j) $ === Joint pmf with 2 r.v.s $ p_(X,Y) (k,j) = p_(X|Y) (k|j) p_Y (j) = p_(Y|X) (j|k) p_X (k) $ == Continuous conditional distribution For continuous r.v.s, with both $X, Y$ random variables, we have the conditional pdf of X given Y = y as $ f_(X|Y) (x|y) = (f_(X,Y) (x,y))/(f_Y (y)) $ === Conditional probability and expectation $ P(X in A|Y=y) = integral_(A) f_(X|Y) (t|y) d t $ The conditoinal expectation of $g(X)$ $ E[g(X)|Y=y] = integral_(-infinity)^(infinity) g(t) med f_(X|Y) (t|y) d t $ === The unconditioned pdf and expectation of X Given the conditional pdf $f_(X|Y) (x|y)$, we can derive the unconditioned pdf of X as $ f_X (x) = integral_(-infinity)^(infinity) f_(X|Y) (x|y) f_Y (y) d y $ $ E[g(X)] = integral_(-infinity)^(infinity) E[g(X)|Y=y] med f_Y (y) dif y $ == Conditional expectation === conditional expectation as a r.v. Let X and Y jointly continuous r.v., The conditional expectatino of X given Y is a new random variable dependent on Y $v(Y)$$ v(Y) = E[X|Y=y] $ === Conditioning and independence recall that - Discrete r.v. two discrete r.v.s are only independent iff $ p_(X,Y) (x,y) = p_X (x) p_Y (y) $ - Continuous r.v. two continuous r.v.s are only independent iff $ f_(X,Y) (x,y) = f_X (x) f_Y (y) $ now, If given pmf or pdf of X given Y, we now have the joint pmf$ p_(X,Y) (x,y) = p_(X|Y) (x|y) p_Y (y) $ and the joint pdf $ f_(X,Y) (x,y) = f_(X|Y) (x|y) f_Y (y) $ === Independency of X and Y discrete r.v. X and Y are independent iff $ p_(X|Y) (x|y) = p_X (x) $ continuous r.v. X and Y are independent iff $ f_(X|Y) (x|y) = f_X (x) $ == Conditioning on the random variable === Conditioning X on y for independent r.v. X and Y, we can condition on Y and have the conditional expectation of X given Y = y as $ E[g(X)|Y=y] = E[g(X)] quad"and" E[g(X)|Y=y] = E[g(X)] $ === COnditioning X on X For a r.v. X, we can condition on X itself, and have the conditional expectation of X given X = x as $ E[g(X)|X=x] = g(X) $
https://github.com/daniel-eder/typst-template-jku
https://raw.githubusercontent.com/daniel-eder/typst-template-jku/main/src/main.typ
typst
// SPDX-FileCopyrightText: 2023 <NAME> // // SPDX-License-Identifier: Apache-2.0 #import "./template/definitions/thesis_types.typ": thesis_types #import "./template/definitions/programme_types.typ": programme_types #import "./template/definitions/programmes.typ": programmes #import "./template/template.typ": project #show: project.with( title: "<A fitting Title>", subtitle: "<And a good Subtitle>", //optional - you can supply "none" or remove this line author: "<Firstname> <Lastname>", department: "<The Department>", first_supervisor: "<Professor's Name>", second_supervisor: "<Professor's Name>", //optional - you can supply "none" or remove this line assistant_supervisor: "<Assistant's Name>", //optional - you can supply "none" or remove this line submission_date: "<Month> <Year>", //For Information: Year of submission to Examination and Recognition Services copyright_year: "<Year>", //optional - you can supply "none" or remove this line, in which case no copyright statement will be shown thesis_type: thesis_types.doctorate, degree: "<Degree>", programme_type: programme_types.doctorate, programme: programmes.law, abstract: lorem(59), acknowledgements: lorem(59), dedication: lorem(59) ) = A level 1 heading #lorem(60) Also see #cite(<latex2e>, supplement: "p. 7") == A level 2 heading #lorem(20) Also see @latex:companion[p. 7] === A level 3 heading #lorem(40) #parbreak() #lorem(30) == More heading #lorem(500) #lorem(500) == And even more #lorem(100) A list: - list 1 - list 2 = Another chapter #lorem(700) = One more chapter #lorem(20) #parbreak() #lorem(500) // Bibliography section #pagebreak(weak: true) //consider disabling the header for the bibliography, but for multi page ones it should probably be enabled // #set page( // header: none // ) #bibliography("literature.bib", style: "./oscola-no-ibid.csl", title: [Bibliography])
https://github.com/SiyangShao/resume
https://raw.githubusercontent.com/SiyangShao/resume/main/main.typ
typst
#show heading: set text(font: "Linux Biolinum") #show link: underline // Uncomment the following lines to adjust the size of text // The recommend resume text size is from `10pt` to `12pt` #set text( size: 11pt, ) // Feel free to change the margin below to best fit your own CV #set page( margin: (x: 0.9cm, y: 1.3cm), ) // For more customizable options, please refer to official reference: https://typst.app/docs/reference/ #set par(justify: true) #let chiline() = {v(-3pt); line(length: 100%); v(-5pt)} = SHAO Siyang <EMAIL> | +65-98602734 | #link("https://github.com/SiyangShao")[github.com/SiyangShao] == Education #chiline() #link("https://www.ntu.edu.sg/")[*Nanyang Technological University*] #h(1fr) Aug 2021 -- Jun 2025 \ Bachelor of Engineering (Computer Engineering) #h(1fr) Singapore, Singapore\ - Expected: Honours (Highest Distinction); GPA: 4.60 / 5.0 // - Dean's List (Academic Year 2022-23) // - Avaliable Period: January 2024 - June 2024 (Credit bearing) // - Relevant Modules: Algorithm Design and Analysis, Operating System, Advanced Computer Architecture, Computer Network, etc. // *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ // #lorem(5) #h(1fr) #lorem(2) \ // - #lorem(10) == Skills Summary #chiline() - *Languages*: Golang, C++, Python, CUDA - *Tools*: Docker, vLLM, ray, hipify, bosun, grpc, Kubernetes, Knative, clickhouse // *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ // #lorem(5) #h(1fr) #lorem(2) \ // - #lorem(20) // - #lorem(30) // - #lorem(40) // *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ // #lorem(5) #h(1fr) #lorem(2) \ // - #lorem(20) // - #lorem(30) // - #lorem(40) == Research Experience #chiline() // *NTU competitive Programming (ICPC) Team* #h(1fr) #link("https://icpc.global/ICPCID/B15T259WIX3C") \ // Team FailedSystemTest / CheesyLeopard / NTRLover #h(1fr) Dec 2021 -- Mar 2024\ // - *Impact*: Representing the school in *competitive programming contests*, using *C++* to solve complex algorithm questions. // - *Awards*: Ranked 2 and secured the *Silver medal* at the 2022-23 ICPC Asia Manila Regional, solved 6 problems and ranked 22 for 2023-24 *ICPC Asia Pacific Championship*. // *vHive Community* #h(1fr) #link("https://github.com/vhive-serverless/vHive") \ // Supervised by Professor <NAME> #h(1fr) May 2023 -- Current \ // // - *GPU support research in vHive* // // - Tested serverless systems with GPU based on *Knative* and *Kubernetes* framework // // - Constructed Knative functions using *Go* to assess serverless GPU applications // // - Created document and installation script and merged into project // // - *Impact of PCIe Stress Level on Model Latency* // // - Using *Python* and *Bash* to carry out a performance evaluation of model latency under different PCIe stress levels // // - Participating in additional research on PCIe-based interference during co-location of models in several situations, including server-grade or edge-grade GPU for multiple small models and managing model-level parallelism within a GPU cluster for large models. // // - *Impact of Memory Bandwidth Stress Level on Model Latency* // // - Using NVIDIA MIG to research // - NVIDIA MIG on GPU Performance // - Using *NVIDIA MIG* on A100, segmenting a single GPU into multiple MIG instances and Compute Instances to investigate their impact on LLM inference latency. // - Cluster level Large Language Model Inference // - Based on *vLLM*, implement a worker with *grpc* functions to retrieve the model and generate the inference result. // - Leveraged vLLM's *Paged Attention* and *Continuous Batching*, it could dynamically adjust inference batch size, optimize GPU computational power and memory utilization. // *URECA Project - Deoxys* #h(1fr) #link("https://github.com/SiyangShao/Deoxys") \ // Fast Software Implementations of New Cryptographic Primitives #h(1fr) Mar 2023 -- Jul 2023 \ // - Implement a system that optimizes calculations using Intel AES intrinsics on the x86-64 architecture, using *C* language // - Analyzing *assembly* code for instruction set pipelining, achieve a balance in the latency and CPI of the instructions *LLM Inference in Serverless Systems* #h(1fr) \ Supervised by <NAME> #h(1fr) Mar 2024 -- Current \ - Investigated cluster-level scheduling for large language model inference in serverless systems - Explored optimal scaling policies and mechanisms for serverless LLM environments - Utilized GPU memory usage for a memory-centric scheduling LLM inference system - Optimized overall throughput and reduced request queueing latency *MIG-based GPU Partitioning and Performance Analysis* #h(1fr) \ Supervised by <NAME> #h(1fr) Jun 2023 -- Nov 2023 \ - Explored the use of MIG (Multi-Instance GPU) to physically partition a single GPU - Investigated the performance overhead associated with achieving physical isolation across multiple instances - Compared performance gains and trade-offs of using MIG for multi-model scenarios on a single GPU - Analyzed memory and PCIe bandwidth utilization across multiple MIG instances // *Hawker Centre Website (Software Engineering Course Project)* \ // Team Leader #h(1fr) Feb 2023 - Apr 2023 \ // - Plan a platform for stalls in hawker centres to post there food and for customers to discover hawker centres // - Design a website with frontend and backend separation, using *Java*, *JavaScript* // - Based the website on *MongoDB*, *Spring Boot*, and *React* technologies == Open Source Projects #chiline() *ServerlessLLM* #h(1fr) #link("https://github.com/ServerlessLLM/ServerlessLLM") \ Contributor #h(1fr) Jun 2024 -- Current \ - Supported ROCm for `sllm-store`, the internal library of ServerlessLLM which provides high-performance model loading - Integrated vLLM backend, enabling ServerlessLLM project to perform inference through vLLM - Explored methods to enable vLLM backend to benefit from high-performance model loading via `sllm-store` - Maintained the controller of the ServerlessLLM project, which manages the lifecycle of the inference backends == Co-Curricular Activities #chiline() // *NTU Open Source Society* \ // HackOSS Technical Director #h(1fr) Jun 2022 -- Jun 2023 \ // - Organized open-source community events in 'HackOSS Day' // - Lead team to complete projects, help team members learn and use open-source tools *NTU ICPC Team* #h(1fr) #link("https://icpc.global/ICPCID/B15T259WIX3C") \ Team Member #h(1fr) Dec 2021 -- Mar 2024\ - Represented the school in ICPC (International Collegiate Programming Contest) and solved complex algorithm problems == Awards #chiline() - 2022 ICPC Asia Manila Regional Ranked 2 #h(1fr) Dec 2022 - 2023 ICPC Asia Jakarta Regional Ranked 13 #h(1fr) Dec 2023 - 2024 ICPC Asia Pacific Championship Ranked 22 #h(1fr) Mar 2024 - Dean's List in Academic Year 2022-23 (Top 5% of cohort) #h(1fr) Aug 2023 - NTU President Research Scholar in Academic Year 2023-24 #h(1fr) Aug 2024 // - Shopee Code League Finalist #h(1fr) Mar 2022 // - ICPC Trainning Camp Powered by Huawei (Top 10 in South East Asia and Asia Pacific) #h(1fr) Feb 2022 == Work Experience #chiline() *TikTok Pte. Ltd.* #h(1fr) Singapore \ Backend Engineer Intern (Video Infrastructure) #h(1fr) Jan 2024 -- May 2024 - Co-Designed and implemented metrics metadata discover and manage system, bridged the gap between development teams and SRE teams concerning the monitoring metrics - Implemented persistent global SLI monitor and manage system, contributing to improvements in full-link stability // - Implement persisting large volumes of monitoring data by using *message queues* for exporting the *bosun* data into *clickhouse*, contributing to improvements in full-link stability. // - Participating in the development of an observation center, maintained all relevant video architecture *SLI* (service level indicator) and *SLA* (service level agreement) metrics, and monitoring system alarms in real-time.
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/introduction.typ
typst
#import "../components/glossary.typ": gls = Introduction == Reasons and Motivations for Conducting Research The rapid evolution of software development has placed increasing demands on tools and technologies that can effectively support complex projects. While #gls("ides") have made significant strides in enhancing developer productivity, the challenges posed by diverse programming languages and the growing scale of software systems have exposed limitations in traditional development paradigms. The #gls("lsp") emerged as a promising solution to address these challenges by decoupling language-specific features from the editor itself. This approach offers the potential to create more flexible, adaptable, and efficient development environments. However, while the #gls("lsp") has gained traction, its full potential, particularly in the context of emerging languages like Ungrammar, remains largely untapped. This research is motivated by the need to explore the #gls("lsp")'s capabilities in addressing the evolving needs of modern software development. By investigating the potential of the #gls("lsp") to support innovative language features and development methodologies, this study aims to contribute to the advancement of language server technology and its practical application in real-world projects. == Research Purposes This research aims to design, implement, and evaluate a comprehensive #gls("lsp") ecosystem tailored to the specific requirements of the Ungrammar programming language. By delving into the intricacies of #gls("lsp") architecture, protocol specifications, and extension development, this study seeks to create a robust, efficient, and user-friendly development environment for Ungrammar developers. Specifically, the research will focus on: - Developing a core #gls("lsp") implementation that provides essential language features such as syntax highlighting, code completion, and error checking for Ungrammar. - Creating #gls("vscode") extensions to seamlessly integrate the #gls("lsp") into both web and desktop development workflows. - Designing and implementing an online demonstration playground to showcase the capabilities of the #gls("lsp") ecosystem. - Exploring the potential of using Ungrammar as a #gls("meta-lang") to define #gls("lsp") language features, enabling a more flexible and adaptable approach to language server development. By achieving these objectives, this research intends to contribute to the advancement of #gls("lsp") technology and establish a strong foundation for future research and development in language-specific tooling. == Research Object and Scope The primary research object is the development of a #gls("lsp") ecosystem for the Ungrammar programming language. This ecosystem encompasses a core #gls("lsp") implementation, #gls("vscode") extensions (web and desktop), and an online demonstration playground. The scope of the research includes the design, implementation, testing, and evaluation of the #gls("lsp"), its integration with development tools, and the exploration of language generation capabilities using Ungrammar. The primary research object of this study is the development of a comprehensive #gls("lsp") ecosystem tailored to the specific requirements of the Ungrammar programming language. This ecosystem encompasses three core components: + *Core #gls("lsp") Implementation*: The development of a robust #gls("lsp") implementation that provides essential language features such as syntax highlighting, code completion, error checking, and refactoring for Ungrammar. + *#gls("vscode", mode: "long") Extensions*: The creation of extensions for both web and desktop versions of #gls("vscode") to seamlessly integrate the #gls("lsp") and provide a rich development experience. + *Online Demonstration Playground*: The development of an interactive platform to showcase the capabilities of the #gls("lsp") ecosystem and facilitate user experimentation. The scope of this research includes the design, implementation, testing, and evaluation of these components. Additionally, it encompasses the exploration of utilizing Ungrammar as a #gls("meta-lang") to define #gls("lsp") language features, thereby enabling a more flexible and efficient approach to language server development. Furthermore, the research will investigate the integration of the #gls("lsp") ecosystem with other development tools and platforms to assess its interoperability and potential for wider adoption. == Research Methods This research employs a mixed-methods approach to comprehensively investigate the design, implementation, and evaluation of the #gls("lsp") ecosystem. Qualitative research will be utilized to explore the underlying principles of #gls("lsp") architecture, analyze design patterns, and identify potential challenges and opportunities. In-depth case studies of existing #gls("lsp") implementations will be conducted to inform the design and development process. Quantitative research will be employed to assess the performance, usability, and effectiveness of the developed #gls("lsp") ecosystem. Performance metrics, such as response time, memory usage, and code completion latency, will be measured to evaluate the system's efficiency. User studies and surveys will be conducted to gather feedback on the usability and user experience of the #gls("lsp") and its integration with development tools. The research methodology encompasses several interconnected phases: - *Literature Review*: A thorough examination of existing research on #gls("lsp"), language server development, and related fields to establish a theoretical foundation. - *System Design*: The design and specification of the #gls("lsp") ecosystem, including the core #gls("lsp") implementation, extensions, and playground. - *Implementation*: The development of the #gls("lsp") components based on the design specifications. - *Testing*: Rigorous testing of the #gls("lsp") ecosystem to ensure functionality, performance, and reliability. - *Evaluation*: User testing and performance evaluation to assess the usability and effectiveness of the system. By combining these research methods, this study aims to provide a comprehensive understanding of the #gls("lsp") ecosystem and its potential impact on developer productivity. == Practical Significance The findings of this research are expected to contribute significantly to the advancement of language server technology and its practical application in software development. By demonstrating the feasibility of using a language of #gls("meta-pgm") like Ungrammar to define Language structures, this research opens up new possibilities for rapid language server development and customization. The developed #gls("lsp") ecosystem for Ungrammar can serve as a valuable reference and benchmark for future language server implementations, providing insights into best practices and potential challenges. Moreover, the research findings can inform the design and development of improved #gls("ides") and text editors that leverage the #gls("lsp") to enhance developer productivity and satisfaction. Ultimately, this research aims to contribute to the broader ecosystem of language-aware tools by providing a concrete example of how the #gls("lsp") can be extended and applied to novel programming languages. == Structure of the thesis === Chapter 1: Introduction This chapter establishes the research context by outlining the evolution of software development tools and the challenges faced by modern developers. It introduces the #gls("lsp") as a potential solution to these challenges and highlights the research gap in the context of emerging languages like Ungrammar. The chapter concludes by presenting the research objectives and the structure of the thesis. === Chapter 2: Literature Review This chapter provides a comprehensive overview of existing research on the #gls("lsp"), language server development, and related fields. It analyzes the state-of-the-art in #gls("lsp") implementation, focusing on key concepts, challenges, and best practices. Additionally, the chapter explores relevant literature on #gls("meta-pgm") and its application in language engineering. === Chapter 3: Requirements Analysis Based on the literature review and the identified research objectives, this chapter outlines the functional and non-functional requirements for the #gls("lsp") ecosystem. It includes a detailed analysis of the target user groups, their needs, and expectations. This chapter also identifies potential challenges and constraints that may impact the system development. === Chapter 4: System Design and Architecture This chapter delves into the core concepts of the #gls("lsp"), explaining its architecture, communication mechanisms, and key components. It also explores the design principles and patterns applied to the #gls("lsp") implementation for the Ungrammar language. The chapter will discuss the integration of the #gls("lsp") with the #gls("vscode") extension, highlighting the key considerations and challenges involved. === Chapter 5: System Implementation This chapter focuses on the practical implementation of the #gls("lsp") for the Ungrammar language. It includes details about the language features supported, data structures, and algorithms employed. The chapter also explores the integration of Ungrammar as a #gls("meta-lang") for defining #gls("lsp") language structures, discussing the implementation of the language generation process and its impact on #gls("lsp") development efficiency. === Chapter 6: Evaluation and Results This chapter presents the evaluation of the developed #gls("lsp") ecosystem. It includes performance benchmarks, usability testing, and user feedback. The chapter analyzes the results to assess the system's effectiveness in meeting the research objectives and identifies potential areas for improvement. === Chapter 7: Conclusions and Future Work This chapter summarizes the key findings of the research, highlights the contributions made to the field of language server technology, and discusses the limitations of the study. It concludes by outlining potential directions for future research and development, including opportunities for expanding the #gls("lsp") ecosystem and exploring new applications.
https://github.com/levinion/typst-dlut-templates
https://raw.githubusercontent.com/levinion/typst-dlut-templates/main/samples/thesis/thesis.sample.typ
typst
MIT License
#import "../../templates/thesis/main.typ": * #show: thesis.with( chinese_title: "", english_title: "", faculty: "", major: "", name: "", id: "", sup: "", rev: "", date: "", chinese_abstract: [], chinese_keywords: (), english_abstract: [], english_keywords: (), intro: [], conclusion:[], bib: bibliography("./ref.bib", full: true), changelog: [], thanks: [] )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/image-03.typ
typst
Other
// Does not fit to remaining height of page. #set page(height: 60pt) Stuff #image("test/assets/files/rhino.png")
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/spacing_04.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test spacing for operators with decorations and modifiers on them #set page(width: auto) $a equiv b + c - d => e log 5 op("ln") 6$ \ $a cancel(equiv) b overline(+) c arrow(-) d hat(=>) e cancel(log) 5 dot(op("ln")) 6$ \ $a overbrace(equiv) b underline(+) c grave(-) d underbracket(=>) e circle(log) 5 caron(op("ln")) 6$ \ \ $a attach(equiv, tl: a, tr: b) b attach(limits(+), t: a, b: b) c tilde(-) d breve(=>) e attach(limits(log), t: a, b: b) 5 attach(op("ln"), tr: a, bl: b) 6$
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/034%20-%20Dominaria/001_Return%20to%20Dominaria%3A%20Episode%201.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Return to Dominaria: Episode 1", set_name: "Dominaria", story_date: datetime(day: 21, month: 03, year: 2018), author: "<NAME>", doc ) #figure(image("001_Return to Dominaria: Episode 1/01.jpg", width: 100%), caption: [], supplement: none, numbering: none) #align(center)[i.] Sadage, cleric of the Cabal, made his way to the doors of the high-vaulted worship hall of the Stronghold. Smoke from torches and incense burners formed a cloud above the cultists sprawled on the stone floor. They begged for entrance to the hall, begged for the favor of the Scion of Darkness within. A group of dark-robed disciples approached from the other direction, picking their way around the moaning supplicants to meet Sadage. He recognized the leader as Needle, an agent of the Cabal tasked with infiltrating New Argive. As the group reached him, they dropped to their knees. "You've returned," said Sadage. "I hope for a worthwhile reason." In answer, Needle unwrapped a large black sword, holding it up for acceptance. "I bring you a gift for the Scion of Darkness." "A gift?" Sadage reached for it, but stopped, a breath of air between his gloved fingertips and the metal. A dark miasma clung to the blade. "What is this?" Needle looked up at him, her eyes wide, the dark pupils dilated with reverence. "A fabled blade, a soul-drinker. The one who forged the sword killed an elder dragon and absorbed its strength—" Sadage said, "Stop." This close to the worship hall and its resplendent occupant, he couldn't afford to let discipline slip. "#emph[Who] used it to kill an elder dragon?" Needle hesitated. The disciple at her side said, "It's said it was the Planeswalker Dakkon Bl—" Sadage made a sharp gesture. "It was Belzenlok! #emph[Belzenlok] forged it. #emph[Belzenlok ] slayed the elder dragon. #emph[Belzenlok.] " In a murmuring chorus, the group of disciples repeated obediently, "It was Belzenlok, Lord of the Wastes, Belzenlok, Slayer of Elder Dragons." Needle added, "This is #emph[his] sword. Belzenlok, King of Urborg, Demonlord. I return it to him." #figure(image("001_Return to Dominaria: Episode 1/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) "Very good." Sadage took the sword from Needle's hand. The contact made his skin burn, even through his gloves. "You have earned your reward." Needle smiled, trembling as she pushed to her feet. She pulled her hood down, baring her throat. Sadage lifted his hand and cast the spell. Slowly, Needle's skin peeled from her chest as the violet spell light gently pierced her heart. As Needle writhed in exultant death, the other disciples watched in jealous awe. Sadage opened the doors to the worship hall, ready to present the black blade to his chosen master, ready to collect his own final reward from the Demonlord. #align(center)[ii.] Jhoira leaned forward over her diving ship's control wheel and breathed, "That's it." She pulled a lever to stop their forward motion. It had been an artistic choice to shape the underwater ship like a large metal-plated fish, with fins for locomotion and steering and two bulbous ports in the bow like giant eyes, but it moved through the difficult sea currents like a dream. Outside the ports, silvery fish flickered away through the sandy water, confused by the narrow beams of the lights and the strange metal fish pushing through the seaweed forest. Hadi, her assistant artificer, grabbed for the support rail as the ship jolted with the current. He leaned down to look through the second port. "Where?" He was an older man, and had come to Tolarian Academy from Jamuraa. That he had agreed to help her on this wild quest said a lot about his sense of adventure. Jhoira adjusted the wheel more carefully and pointed, her finger almost touching the curved glass. "There, you see?" It seemed obvious to her; the long spine half-buried in the muck and waterweeds was too straight for any natural formation, at least in this bay. But then she knew that shape so well, it was like greeting an old friend. #figure(image("001_Return to Dominaria: Episode 1/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) "You've got sharp eyes," Hadi said, and pulled down the speaking tube for her. "I thought there would be more left of it." "Not after so long." Jhoira took the speaking tube and called into it: "Ziva, I'm directing my lights toward it. Can you see it?" The tube sent her voice through the water, transformed into vibrations the Vodalian merfolk could understand. Outside, Ziva swam down past the port, the silt in the water dimming the deep purples and blues of the natural armor on her arms and flanks. Ziva paused long enough to signal an assent toward the port, then with a flick of her powerful tail, she disappeared into the murk. Jhoira waited for the verdict, trying not to bounce with tension like Hadi. Then Ziva reappeared and swam closer to the metal fish until she bumped against the hull. Her tail curled past the port, and Jhoira heard her fumble for the outside end of the speaking tube. Then Ziva's voice was transported into the compartment. "It's lying on a shelf, trapped by saltweed and sand, but no rocks," she reported. "We should have no trouble raising it to the surface—if the price remains the same." #emph[Yes, just as I hoped!] Jhoira thought. It was hard to contain her glee, but they had a lot of hard work ahead. "The price is doubled if you can bring it up within two days," she told Ziva. The merfolk needed the money, and Jhoira had no problem paying for something that would be the culmination of years of careful work and planning. Ziva's laugh was like bubbling water. "You'll have it in one!" Jhoira sat back against the worn leather of the pilot's seat. The heady combination of relief and renewed purpose made her want to dance. #emph[Later] , she promised herself. When she stood on the shore beside it, then she'd dance. "I knew we could do it." "You knew it," Hadi told her, sounding elated. "I'm not sure anyone else believed it was possible!" "Well, they'll believe it now," Jhoira said. The rest of the merfolk swooped in to join Ziva, gliding in patterns around her as they waited for orders. "Everyone ready?" Jhoira said into the speaking tube. "Now we raise the #emph[Weatherlight] ." #align(center)[iii.] Dominaria coalesced around Gideon and the first thing that struck him was the stench of rotting plants and dank earth. He stood on a high stone foundation between a ruined town and an overgrown stinking marsh, the landscape desolate under a cloud-covered sky. Gray stone structures once tall and graceful had lost sections of walls and roofs, and some were just heaps of tumbled stone. Mist cloaked the tall grass, bubbling mud pools, and rotting trees of the marsh, empty of any life except clouds of insects. It was like an artist's attempt to visually capture a representation of death and failure. He couldn't suppress the bitter thought, #emph[How fitting for this moment] . The second thing Gideon noticed was the hole in his shoulder and its piercing pain. He took a deep breath and did not stagger or collapse onto the muddy stone. Liliana, Chandra, and Nissa stood nearby, disheveled and shaken by the battle. This was not the time for him to show weakness. He made his voice even and moderate and admitted, "That did not go according to plan." "Oh, it didn't?" Liliana turned to him, putting on an expression of mock surprise. "What makes you say that? Was it the river of undead I almost drowned in? Or <NAME> slapping you around like a child's toy?" Gideon was in too much pain for a clever answer. Besides, she was right. He stood here wounded, barely keeping himself upright, his sural lost. They had failed utterly, been hopelessly outmatched, and were lucky to survive. The thought of how many others hadn't been so lucky was a sickening weight on his heart. Chandra rubbed her eyes. "Where's Jace?" Startled, Gideon looked around again. She was right, there was no sign of Jace. "He's not still on Amonkhet. I saw him leave." Liliana's gaze crossed his. They had all known their meeting place. Jace's absence couldn't mean anything good. She pressed her lips together and said, "Perhaps he was delayed." "He's not coming." Nissa ground out the words, her voice harsh. "He's given up." "He wouldn't do that." Gideon was certain. Jace wouldn't abandon them. Nissa ignored him, too angry to listen. "A plane all but destroyed. So much death." She shook her head in disgust. "And we played right into Bolas's hands!" Chandra hunched her shoulders and looked away. "Ajani was right. We never should have gone there." "We had to try—" Gideon began. Liliana turned to Nissa, all calm reason. "It wasn't a disaster; we killed Razaketh. The rest . . . We couldn't have anticipated—" "Yes, your demon's dead," Nissa snapped. "You got what you wanted and ran. You don't care about defeating Bolas, you're just using us to free yourself from your pact." "Of course I want to defeat Bolas!" Liliana protested. "I ran to save my life—just like Jace did before me." Nissa persisted, "And why here?" She flung an arm out, gesturing to the dead marsh. "How do you want us to risk our lives for you here?" "Your precious Ajani suggested we meet here," Liliana said, sounding aggrieved. Gideon noted she hadn't answered the question, and he had a bad feeling he knew why. But he said, "Nissa, this isn't the time. We're all exhausted—" Chandra said flatly, "Your last demon is here, isn't it, Liliana?" Liliana hesitated, and her calculating gaze moved from Chandra to Nissa, but even she didn't have the gall to protest. Her jaw hardened and she said, "Belzenlok is here." Gideon let out a resigned breath. #emph[Of course he is] . "Nissa—" Liliana stepped toward Nissa. "If I wasn't restrained by my pact, we would have destroyed Bolas on Amonkhet." Her voice turning persuasive, she added, "I can kill Belzenlok—but you're the only one powerful enough to help me." Gideon winced. He could see Nissa was in no mood for flattery, and it was a measure of Liliana's disarray that she thought it would work. "Liliana—" Chandra made a derisive noise. "You want to use her. Like you wanted to use me. I thought we were friends, Liliana." "Chandra, that's not helpful," Gideon said. Liliana ignored them both. Speaking only to Nissa, she said, "Belzenlok is worshipped here by the Cabal, a death cult. You can rouse the treefolk of Urborg's Yavimaya remnant to break into their Stronghold where he hides. And I can use the Chain Veil to kill him." Gideon grimaced. The Chain Veil, a powerful artifact of the Onakke, had allowed Liliana to kill two demons. But it sapped her strength, and he thought it was far more dangerous, to the wielder and possibly everyone else around it, than even she had admitted. Nissa's lip curled. "No. I won't help you. I didn't take an oath to save your skin." She turned to Gideon. "Tell her. Tell her we aren't going to let her use us again. Tell her she can help us against Bolas or leave." Gideon took a sharp breath, managed not to wince at the pain pulsing through his shoulder. Working with Liliana could be a trial at the best of times, but they had made an agreement. "We need Liliana's help to destroy Bolas, and she can't do that until this last demon is dead." Nissa was incredulous. "That will make her as much of an interplanar threat as Bolas!" "I don't believe that." Gideon tried to sound calm and reasonable, but pain sharpened his voice. "She's not using us, it's the best chance we have against Bolas. And we can't leave Belzenlok to wreak havoc on this plane. Nissa—" Seething, Liliana said, "I saved your life, Nissa! This is how you repay me?" "I owe you nothing." Nissa stepped back, contempt in every line of her body. "None of us do. If the rest of you are too blind to realize that, I can't help you." She stepped away. "Nissa!" Chandra stared at her. "If you don't want to help Liliana, I understand that, but Bolas—" Gideon scrambled for a persuasive argument, but pain scattered his thoughts. "Nissa, you made an oath—" "No." Nissa backed farther away from them, her expression hard as marble. "I can't bear to see another plane broken before I make my own home whole. I'm sorry, but my watch is over." Chandra shouted, "Nissa!" #figure(image("001_Return to Dominaria: Episode 1/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) But Nissa was already stepping out of the plane. For a heartbeat her form glowed with green light, the air around her filled with the shadows of vines and leaves. Then she vanished, leaving behind the fading scent of green foliage and flowers. They stood frozen, the damp breeze stirring their hair. Liliana looked away, her jaw tight, clearly furious. Chandra buried her face in her hands and Gideon suppressed a groan. He had to find Nissa, talk her into coming back, but pain stabbed through his chest with every breath. Then Chandra lifted her head and said, "I'm going too." "What?" Gideon turned to her, appalled. The movement pulled at his wound and blood dripped down his side. "Chandra—" "What?" Liliana said incredulously. "Are you joking?" "I'm not quitting," Chandra said rapidly, nothing but determination in her expression. "I'd never quit! But you're right, Gideon, I need to learn from this. We failed Amonkhet because I was too weak!" Liliana sputtered, "That wasn't why we failed—" Chandra's chin lifted. "I have to become stronger." Gideon tried, "Chandra, when I said 'learn from failure,' that's not what I—" "I know what I'm doing!" she said, and before Gideon could take another breath she was gone. Her form disappeared in a rush of fire as she walked from the plane. Gideon stared at the empty space where his two comrades had been. At some point he had lost control of the situation, and he wasn't sure how. And the throbbing in his head was worse. Liliana rounded on him. "Well? Where are you going? What's your excuse?" Gideon let out his breath wearily. "I'm staying." He looked down at her. "Nothing has changed. We need you to destroy Bolas, and you need to destroy this demon." "I—" She stopped, staring at him. Then her expression hardened again. "Good. Then we should get on with it." "We have to make a plan—" Pain stabbed him again, worse this time, as if Bolas's claw were still in his shoulder. He set his jaw, breathed through it, and tried again. "A plan. We have to—" Liliana threw her arms in the air. "I know you're wounded, stop being a giant child and just admit it!" She swore under her breath. "Come on, we'll find a place so I can heal you." Gideon was startled. "I didn't know you could heal people." "The list of things you don't know could fill all the archives on Dominaria," Liliana snapped. "Now come on." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[Well, this is yet another disaster] , Liliana thought as they followed an overgrown path farther into the ruined town. With Nissa quitting in a rage and Chandra flouncing off to find herself or whatever she had been babbling about, Liliana's strategy was as ruined as this town. And Jace, gone without a word. Perhaps he no longer wanted anything to do with her . . . That thought disturbed her more than she wanted to admit. She would find him again, talk him around, but she had to kill Belzenlok first. She cast a sideways glance at Gideon. Whatever happened, she couldn't let him realize she had run from the battle, just as Nissa had accused her. He was all she had left, and she needed his help to kill Belzenlok. But there was a sallow cast to his brown skin, lines of pain and tension etched around his mouth. #emph[If he lives.] The big idiot's wound must be much worse than he was willing to admit. Their boots squelched in the mud and scraped against broken paving stone and shattered glass. Death cloaked this town and the marsh around it, woven with the mist that drifted over the wet ground. Shades moved in that mist, faces that appeared then faded away. Death was everywhere. The sight of this place had been another shock. Liliana couldn't believe this was Vess. If the others hadn't been standing beside her, she would have thought she had somehow planeswalked to the wrong part of Dominaria. At least the town wasn't as deserted as it had first seemed. Some of the stone buildings showed attempts at repair, with patched walls and roofs, cleared steps, and wooden shutters for tall windows that had once held stained glass. The creeping marsh grass had been hacked away from a few courtyards, and one held tethered goats. A sense of something watching made Liliana examine a roofline more carefully. The shape near a chimney was no gargoyle but—#emph[Not an angel] , she thought. A visit from the sanctimonious Church of Serra would have been the perfect cap on this foul disaster of a day. It was an aven soldier on watch, the cloudy gray light glinting on its armor, the white of its feathers and folded wings. Ahead over the rooftops, the stone curve of an ancient Thran ruin loomed out of the mist, the smooth sides dark with moss. It was shaped like an ax blade, as if a giant had driven it into the earth and left it there. That at least was a familiar sight, something that hadn't changed in all the decades she had been gone. #figure(image("001_Return to Dominaria: Episode 1/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Around the next turn was a broad plaza surrounded by tall houses, all in disrepair but some with stained glass still glinting in the narrow windows of the upper floors. To one side was a fountain and a few wooden market stalls. Near the market stood a tall rambling building that must be an inn. Smoke issued from the chimneys and the doors stood open. The people gathered in front stared curiously at Liliana and Gideon. All were well-armed, but made no hostile moves. Gideon nodded a greeting to them, then ruined the effect by gasping and grimacing in pain. This was the center of town, and it looked as if it was barely clinging to life, a pale shade of the bustling market plaza that had once been as familiar as the back of her own hand. Liliana swallowed back a curse. #emph[What happened here?] "What is it?" Gideon asked quietly. Liliana grimaced. She hated showing weakness. "Nothing." Gideon sighed. "If we're going to do this, we have to be honest with each other." Liliana snapped, "It's nothing!" As he eyed her skeptically, she reminded herself he was her only ally. And really, there was no point in concealing this fact. "There's no grand conspiracy, it's just that this place has changed. The last time I was here, this town was surrounded by forest, not a stinking marsh." Gideon's brows drew down as he took in the plaza. "Why couldn't you just say that?" "Because it's nothing," Liliana said through gritted teeth. "That's exactly my point—" He winced and cut the words off. "Why were you here?" "It's where I was born." She ignored his startled expression. "Come on, before you fall down—you're too heavy for me to drag." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Liliana didn't even need to threaten anyone to get service, though the inn was clearly functioning as a hostelry in name only. The innkeeper seemed frankly astonished at the idea they wanted to stay, but immediately led them to a room on the first floor, no doubt chosen because Gideon was leaving a blood trail and didn't look capable of climbing the stairs. The innkeeper was a large dark-skinned man with an abundant family who kept popping out of doors to stare at the visitors as they made their way down the corridor. The room was expansive and contained a bed and a random assortment of musty furniture. Liliana steered Gideon to a low couch and helped him collapse onto it. "It's been a long time since we had any travelers," the innkeeper admitted as he built up the fire in the hearth. A young woman, dressed in practical work clothing with a short sword belted to her waist, carried in a bucket of water to pour into the hearth's cauldron. A young boy brought a stack of folded blankets. A young girl appeared with a basket of bandages and healing supplies, and another boy came with a tray of food and drink. Despite Liliana's foul mood, there was no fault to find with the service. The innkeeper hadn't even asked to see their coins. "I'll need whatever healing herbs you have," Liliana ordered. As the children left, she added, "What happened here? This place has . . . changed since I saw it last." "It's the Cabal," the innkeeper said, adjusting the cauldron's support so it hung over the growing flames. He added grimly, "They mean to take over the whole world." Surely the man had to be exaggerating. Liliana brushed aside Gideon's fumbling attempt to remove his armor and undid the buckles herself. While he stoically pretended there wasn't a massive hole in his shoulder, Liliana set about cleaning and bandaging the wound. She had known Belzenlok had supplanted the god Kuberr to gain control over the Cabal, that their Stronghold was now in Urborg, but had they really spread so far? "The Cabal has come here, then. To Benalia." The innkeeper nodded, adding more wood to the fire. "We fought to keep them off Aerona, but we failed. You see what their influence has done to Caligo Forest over the years." He made a helpless gesture. "The whole forest?" Liliana said in disbelief, turning to stare at him. "All the way to the river?" "And past. The river's silted up, impassable. It's Caligo Morass, now. And they have a new leader in this area, a powerful lich acting as the grimnants' general. The Church of Serra came to help and there was a great battle only a few days ago, but the Cabal routed us." He pushed to his feet. "I'll get some more wood for the fire." The young girl returned with the box that held the inn's store of healing herbs. "This is all we have left. Most of our supply got used on the soldiers who stayed here." Flicking through the packets, on impulse Liliana asked her, "Does anyone here remember the House of Vess?" The girl paused to consider. "There's ghost stories about the old ruined manor in the morass, about the undead son and the evil daughter who fled—" #figure(image("001_Return to Dominaria: Episode 1/06.jpg", width: 100%), caption: [Dark Dabbling | Art by <NAME>], supplement: none, numbering: none) "No, no." Liliana held up a restraining hand. It was unsurprising the events of that day had become a local legend, but she had no interest in hearing it. "That part I know. I mean the true history of the family, what happened to them afterward." "No, not that I ever heard." The girl hefted the bucket of soiled water. "I can ask around for you, if you like." "No, it's not important." Liliana gestured her away. As the girl left, she stared toward the shuttered windows, her brow furrowed. Gideon stirred a little, blinking up at her. "What is it?" She shook her head and glanced down at the herb packets. "They don't have what I need, but it should grow nearby. I'll go find it." He sank back on the couch, wincing at the pain of movement. She put on a malicious smile for form's sake, and added, "Don't fear I'll abandon you." "I don't fear that," he said, mildly, gazing up at her. "You need me to kill Belzenlok." Liliana found herself with no reply and, doubly irritated, left the inn. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The land had changed so much Liliana knew the herbs she wanted might no longer exist, but they were the fastest way to heal Gideon. They needed to come up with a plan and deal with Belzenlok, as quickly as possible. Once past the ruins, she made her way into the marsh. She found the herbs on a surviving island of higher ground, and picked what she needed. She straightened up, looking off through a copse of moss-shrouded trees, and for a moment the strange landscape was familiar again. This was where she had first met the Raven Man. #emph[You tried to help Josu like this, with these same herbs] , she thought, the memory of that day unexpectedly clear. She had meant only to heal him, and instead turned him into a mindless undead monster that killed <NAME>, killed her servants . . . And then she had fled the plane as her spark ignited, leaving her mother and father, all her family and friends, everyone she had ever known, to their fates. The spell animating Josu must have broken when she left the plane, but she had never thought of what her family had made of the carnage in his room. They must have thought her dead, surely. Had they searched for her? Had they thought Josu had killed her? Wrapped up in her sudden new power as a planeswalker, trying to survive, she had refused to think about them since that day. It was so long ago, and the pain-filled memories were like a glimpse into the mind of a different person. #emph[Don't be stupid] , she told herself. The House of Vess was now just a legend, a ghost story to amuse the town's children. #emph[They lived their lives, aged, and died] . Nothing would be left of the manor but a pile of rubble, with no clues to discover. But she found herself walking, her feet finding the familiar path buried under all the mud and marsh grass. Inconvenient emotions, getting in the way of her goal. Liliana made her way through a stand of grass as high as a sapling and stopped abruptly. It had to be her fevered imagination. The house was still here. The twisted trees and heavy vegetation had grown right up to the gray stone walls, but she could see the shape of the center wing, the curve of the nearest tower. #emph[This is madness] , she thought. #emph[Madness or . . .] Or some strange power at work. The doors to the main hall stood open. It was surprisingly hard to make herself cross the open field and walk up the steps, but dread and the need to know drove her on. She stepped inside. The light from the doorway fell on the carved railings of the upper gallery, the tapestried hangings on the wall behind, and for an instant it was as if the house was wholly intact, just as it was. As if it had existed in a timeless bubble, preserved like an insect in amber. But then she breathed in the scent of blood and rot, and the moment broke. She blinked, and saw the hangings were in tatters, the carving broken and scarred by weather. #emph[But still, this whole house should be a ruin,] she thought. #emph[Something has done this, deliberately.] So she could be brought here to see it? If so, it could be the Raven Man, stalking her across the planes. #emph[But why?] She followed the scent of blood farther into the hall. There, before the great hearth, symbols had been charred into the stone floor, their shape and pattern obscured by dried remnants of what must have been huge gouts of blood. Dozens of unlit candles surrounded the spot, their pools of melted wax further obscuring the traces left behind by some powerful necromantic spell. Cold air wafted up from the floor like an open grave. Liliana's jaw hurt and she realized it was because her lips had drawn back in an unconscious snarl. Whatever had happened here, it was no coincidence. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Night had started to fall when Liliana reached the outskirts of town. She had barely started on the path through the ruins when she sensed the surge of undead malice. She muttered, "I do not have time for this," and started to run. She heard the fighting before she reached the plaza and rounded the last corner to see a battle ahead. The market stalls had been set afire and dark figures fought across the plaza, firelight glinting off flashing blades. The townspeople were easy to spot, wearing patched armor and wielding makeshift clubs and tools as well as swords and battle axes. Some had fallen already, and the aven she had seen on the rooftop lay sprawled dead on the paving stones, its wings a broken tangle. The attackers wore black armor with spikes and sharp points, as unlike the Benalish white and silver and stained glass as possible. #emph[Undead knights from the Cabal] , Liliana thought in disgust. There would be a Cabal cleric here somewhere, a living human cultist, to control the mindless revenants. Gideon suddenly tumbled out of the shadows near the inn. He rolled to his feet then staggered, still clearly weakened by his wounds. He wore no armor and blood stained his bandages and clothing, but he swung a borrowed sword as a knight on horseback bore down on him. The knight wore heavy black armor studded with sharp spikes and was mounted atop a large armored horse. No, as the creature tossed its head Liliana spotted the rotting flesh and white bone through the gaps in its armor, the pits of darkness where its eyes should be. The knight wore no helmet and his head was covered with pale shrunken flesh, his hair a rotting white mane. #figure(image("001_Return to Dominaria: Episode 1/07.jpg", width: 100%), caption: [Art by Even Amundsen], supplement: none, numbering: none) Screams erupted from the inn as the doors burst open. Another undead knight dragged two struggling figures outside. Liliana recognized the young woman and the boy who had helped attend their room. Gideon flung himself toward them and the knight on horseback drove his mount forward to ride him down. #emph[Hah, you'll have to do better than this, Belzenlok] , Liliana thought as she raised her hands. She drew strength from the dead slumped on the cold pavement, from the bones buried in the ruins, from the rotting corpses in the marsh, from the ghosts in the mist. As the etchings on her skin flared violet, bolts shot out from her hands to strike a dozen black-armored knights. She strode forward into the chaos of the battle. A revenant on foot charged her and she spared one gesture to send a black cloud shooting up from the ground. It wrapped his writhing form and rotted him to nothing as what was left of his armor hit the pavement. The undead knight barreled down on Gideon and lifted his lance for a killing blow. Liliana focused her will and sent it into the black-armored form. In the next instant, he was hers. She made him drop the lance and turn his mount away from Gideon. She snapped the mount's connection to the power that animated it. As it collapsed into a pile of bones, the knight tumbled to the ground. She considered using him against the others, but the dozen or so she had already destroyed had turned the battle. Gideon gained his feet again and hacked away at the few combatants left near the inn. Shouting in triumph, the surviving townspeople regrouped to charge the others. Liliana lifted her hand to destroy the last knight, but something whispered in her mind: #emph[the Void awaits.] Liliana froze, her heart pounding. Then her lips curled in contempt. It was a trick. The undead knight's master had to be the lich who had devastated Caligo for the Cabal, and the lich had to be the one behind the arcane preservation of Vess Manor. Liliana explored along the connection, curious. How could this lich know so much about her? Was it possibly . . . An image of the lich's face burned before her. The face was Josu's. #figure(image("001_Return to Dominaria: Episode 1/08.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) #emph[No.] Liliana's heart seized in her chest. #emph[It can't be] . "No!" she shouted. Her rage and dismay snapped the connection. The knight's corpse exploded and armor and rotting bones flew across the plaza. The townspeople had caught the human cleric and pinned him to the ground with a spear to his chest. Liliana shouldered them aside and grabbed him by the leg to drag into the firelight. Her voice rough with rage, she demanded, "Where is Josu? What has Belzenlok done to him?" She was barely aware of Gideon moving to her side, watching her with concern. The cleric gasped a laugh, then choked out, "He knew, our Demonlord, the Scion of Darkness, he knew you were coming! He has made your precious brother into his servant, the commander of his unholy forces!" "Josu serves Belzenlok," Liliana repeated, shock making the words sound calm. The necromantic rite in Vess Manor had been used to turn Josu from mindless undead into a powerful lich, capable of using Josu's memories and military training, but enslaved to Belzenlok. #emph[Belzenlok is using my own brother against me] , Liliana thought. The brother whose soul she had made vulnerable with her first uncontrolled use of power. "He serves our lord, he . . ." The cleric gurgled as blood filled his throat. He gasped, "The Void awaits," and slumped lifeless on the pavement. Liliana stared down at him, growing fury overriding the horror at what had happened to Josu. She would not allow this. Her brother would not be Belzenlok's slave. She would free him no matter what it took. "You'll pay for this, Belzenlok," she said, grating out the words in cold fury. "No matter what I have to do, you will pay."
https://github.com/barddust/Kuafu
https://raw.githubusercontent.com/barddust/Kuafu/main/src/Meta/resources.typ
typst
= 资源获取 信息时代使得人的成长可以向着无限发展,人类的知识和智慧前所未有地集中,从而使得几乎任何人都能获取到几乎需要的所有信息。此处分享的是我获取信息或资源的渠道。 == 信息 我之前大学时获取信息是从各种各样的应用上来,比方说知乎、微信公众号等,随后呢发现了许多不便之处,简单说就是从这个平台获取信息之后,需要切换到另一个平台,如此甚是麻烦。于是想想有没有什么 All-in-one 的方案,可以将我所有的信息渠道汇总,而我只需要从一个入口接收即可。 === RSS / Rss: RSS (RDF Site Summary or Really Simple Syndication) is a web feed that allows users and applications to access updates to websites in a standardized, computer-readable format. 它是一种开源的消息格式,主要用于获取更新,理论上说它应该只是提醒说该网站有新内容了,不过当然可以把更新的内容,比方说文章、图片放到里面进行传输。优点是方便集成(all-in-one),无冗余信息(如广告),灵活不受平台限制;而缺点很直接:并不是所有网站都支持 #let rsshub = link("https://docs.rsshub.app")[RSSHub] 有一些开源项目,比如说#rsshub\(#rsshub.dest), 它是贡献者自己写脚本取爬取网站更新信息,然后集成到这个 hub 上来。大大小小的应用都能在这里找到,但是一些平台如微信公众号不希望暴露第三方接口就很难获取到其信息。连接#rsshub 需要魔法;或者可以在自己的服务器上部署。 一开始去找一些相关项目,比如#rsshub 里面记录的各种微信公众号的爬取方案,但是大多数都是失效的(因为严格的反爬虫设定),或者是有一些过时的。于是干脆不用微信公众号了。 对于一些碎片化的信息——大部分是新闻, RSS 完全足够;而对于一些文章,可以通过 newsletter 的方式获取。 === Newsletter / Newsletter: A newsletter is a printed or electronic report containing news concerning the activities of a business or an organization that is sent to its members, customers, employees or other subscribers. 主要是通过电子邮件的方式来获取,他可以是方方面面,新闻、杂志、类似个人公众号等等。 Newsletter 可能会有付费制的,但普通的文章都足够了,如前所述,真正想获取硬核的知识,还是得阅读和学习专业书籍,去听公开课、讲座等。 除了那种碎片化的资讯类的内容,否则一周一封邮件是够了,每天都读时间并不足够。 == 书籍 === 实体书 各种旧书网,或者二手闲置转卖平台都能买到,书籍本身不容易有什么假货,即使不良商家真的贩卖的是一堆用订书钉订装起来的复印资料,只要字迹能看清,排版不混乱,没有过分的错别字都还能接收;但是还是需要衡量价格,如果我花同样价钱甚至更少的价钱就能取复印店获得比其阅读体验更佳的副本,那一定会举报和要求退款的。 === 电子书 目前而言,安娜的档案基本满足了我所有的书籍需求,中文的英文的。它本身是一个开源性质的数据库,里面收录了来自互联网的各种电子书,它以用户捐赠的形式运营。成为会员会有一些特权,不过对于我等凡夫俗子,其实用不到它提供的会员功能。 官网地址:https://annas-archive.org/. 有时候可能需要魔法。 == 视频 短视频给的快乐过于直接,在3秒钟之内就能让人感觉到开心。我曾自视清高,因为自己的手机没有抖音快手,也不刷各种平台的短视频,但是其实一直用 b 站(bilibili)消磨时光;的确上面会有很多优质的资源,各种考试党、自学派都能找到很多有用的公开课和各种前人的经验分享,也正是因为这个,我才会觉得我使用它的理由是因为我在其上有学习的需要。 后知后觉,我在其娱乐视频花费的时间并不少,因而我从手机中将其卸载。尽管如此,我还是在电脑端使用它,区别在于,我只有在学习需要看公开课的时候才会用到,极大压缩各种娱乐视频对我的诱惑——必须承认,这股诱惑令我难以拒绝。 另外一个类似的途径就是 Youtube. 首先使用它需要魔法,其次对于一个学习者本身,它和 b 站并没有太大区别。 == 论坛或贴吧 论坛和群聊区别还是很大的。 群聊几乎很难形成针对性,百家争鸣,实时性使得很多信息几乎都是没有价值的。而论坛是网友提出一个话题,其他成员针对这个话题进行讨论,对于一些大家都认可回复,管理员很容易标记它,后来者便可以快速地找到潜在的解决方案。 同时,还可以收藏帖子,方便日后查看;订阅帖子,有相关回复会得到通知,而不像群聊随心所欲,当前讨论的话题到底为何还需要查看上下文。 当然,论坛也会存在灌水行为,这类现象的发生与其环境有关,一个优质的论坛则不太会出现水帖,要么是快速解答,要么是管理员觉得毫无意义便关贴。 关键的问题便是,如何去找到优质的论坛。我回答不上;只知道论坛是一种好方法。
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-A880.typ
typst
Apache License 2.0
#let data = ( ("SAURASHTRA SIGN ANUSVARA", "Mc", 0), ("SAURASHTRA SIGN VISARGA", "Mc", 0), ("SAURASHTRA LETTER A", "Lo", 0), ("SAURASHTRA LETTER AA", "Lo", 0), ("SAURASHTRA LETTER I", "Lo", 0), ("SAURASHTRA LETTER II", "Lo", 0), ("SAURASHTRA LETTER U", "Lo", 0), ("SAURASHTRA LETTER UU", "Lo", 0), ("SAURASHTRA LETTER VOCALIC R", "Lo", 0), ("SAURASHTRA LETTER VOCALIC RR", "Lo", 0), ("SAURASHTRA LETTER VOCALIC L", "Lo", 0), ("SAURASHTRA LETTER VOCALIC LL", "Lo", 0), ("SAURASHTRA LETTER E", "Lo", 0), ("SAURASHTRA LETTER EE", "Lo", 0), ("SAURASHTRA LETTER AI", "Lo", 0), ("SAURASHTRA LETTER O", "Lo", 0), ("SAURASHTRA LETTER OO", "Lo", 0), ("SAURASHTRA LETTER AU", "Lo", 0), ("SAURASHTRA LETTER KA", "Lo", 0), ("SAURASHTRA LETTER KHA", "Lo", 0), ("SAURASHTRA LETTER GA", "Lo", 0), ("SAURASHTRA LETTER GHA", "Lo", 0), ("SAURASHTRA LETTER NGA", "Lo", 0), ("SAURASHTRA LETTER CA", "Lo", 0), ("SAURASHTRA LETTER CHA", "Lo", 0), ("SAURASHTRA LETTER JA", "Lo", 0), ("SAURASHTRA LETTER JHA", "Lo", 0), ("SAURASHTRA LETTER NYA", "Lo", 0), ("SAURASHTRA LETTER TTA", "Lo", 0), ("SAURASHTRA LETTER TTHA", "Lo", 0), ("SAURASHTRA LETTER DDA", "Lo", 0), ("SAURASHTRA LETTER DDHA", "Lo", 0), ("SAURASHTRA LETTER NNA", "Lo", 0), ("SAURASHTRA LETTER TA", "Lo", 0), ("SAURASHTRA LETTER THA", "Lo", 0), ("SAURASHTRA LETTER DA", "Lo", 0), ("SAURASHTRA LETTER DHA", "Lo", 0), ("SAURASHTRA LETTER NA", "Lo", 0), ("SAURASHTRA LETTER PA", "Lo", 0), ("SAURASHTRA LETTER PHA", "Lo", 0), ("SAURASHTRA LETTER BA", "Lo", 0), ("SAURASHTRA LETTER BHA", "Lo", 0), ("SAURASHTRA LETTER MA", "Lo", 0), ("SAURASHTRA LETTER YA", "Lo", 0), ("SAURASHTRA LETTER RA", "Lo", 0), ("SAURASHTRA LETTER LA", "Lo", 0), ("SAURASHTRA LETTER VA", "Lo", 0), ("SAURASHTRA LETTER SHA", "Lo", 0), ("SAURASHTRA LETTER SSA", "Lo", 0), ("SAURASHTRA LETTER SA", "Lo", 0), ("SAURASHTRA LETTER HA", "Lo", 0), ("SAURASHTRA LETTER LLA", "Lo", 0), ("SAURASHTRA CONSONANT SIGN HAARU", "Mc", 0), ("SAURASHTRA VOWEL SIGN AA", "Mc", 0), ("SAURASHTRA VOWEL SIGN I", "Mc", 0), ("SAURASHTRA VOWEL SIGN II", "Mc", 0), ("SAURASHTRA VOWEL SIGN U", "Mc", 0), ("SAURASHTRA VOWEL SIGN UU", "Mc", 0), ("SAURASHTRA VOWEL SIGN VOCALIC R", "Mc", 0), ("SAURASHTRA VOWEL SIGN VOCALIC RR", "Mc", 0), ("SAURASHTRA VOWEL SIGN VOCALIC L", "Mc", 0), ("SAURASHTRA VOWEL SIGN VOCALIC LL", "Mc", 0), ("SAURASHTRA VOWEL SIGN E", "Mc", 0), ("SAURASHTRA VOWEL SIGN EE", "Mc", 0), ("SAURASHTRA VOWEL SIGN AI", "Mc", 0), ("SAURASHTRA VOWEL SIGN O", "Mc", 0), ("SAURASHTRA VOWEL SIGN OO", "Mc", 0), ("SAURASHTRA VOWEL SIGN AU", "Mc", 0), ("SAURASHTRA SIGN VIRAMA", "Mn", 9), ("SAURASHTRA SIGN CANDRABINDU", "Mn", 0), (), (), (), (), (), (), (), (), ("SAURASHTRA DANDA", "Po", 0), ("SAURASHTRA DOUBLE DANDA", "Po", 0), ("SAURASHTRA DIGIT ZERO", "Nd", 0), ("SAURASHTRA DIGIT ONE", "Nd", 0), ("SAURASHTRA DIGIT TWO", "Nd", 0), ("SAURASHTRA DIGIT THREE", "Nd", 0), ("SAURASHTRA DIGIT FOUR", "Nd", 0), ("SAURASHTRA DIGIT FIVE", "Nd", 0), ("SAURASHTRA DIGIT SIX", "Nd", 0), ("SAURASHTRA DIGIT SEVEN", "Nd", 0), ("SAURASHTRA DIGIT EIGHT", "Nd", 0), ("SAURASHTRA DIGIT NINE", "Nd", 0), )
https://github.com/OCamlPro/ppaqse-lang
https://raw.githubusercontent.com/OCamlPro/ppaqse-lang/master/src/étude/pointeurs.typ
typst
#import "defs.typ": * #import "links.typ": * = Pointeurs & Mémoire == Gestion des pointeurs Les pointeurs sont des valeurs représentant l'adresse en mémoire d'une autre valeur. Ils sont couramment utilisés pour passer des valeurs par référence, et par conséquent, éviter de copier ces valeurs à chaque fois qu'on les utilise dans le flôt de contrôle. La manipulation des pointeurs est plus ou moins explicite suivant les langages. En C, les pointeurs sont des valeurs de première classe et peuvent être manipulés directement. À l'inverse, en OCaml, les pointeurs n'apparaissent jamais directement dans le code source mais sont utilisés implicitement par le compilateur. Lorsque les pointeurs sont explicites, il y a trois type d'erreurs courantes qui peuvent survenir : - le débordement; - le déréférencement de `NULL`; - le _dangling pointer_ Le débordement survient lorsqu'on écrit ou lit en mémoire à une adresse qui n'est pas dans une plage de valeurs attendues. Typiquement, cela arrive lorsqu'on adresse un tableau en dehors de ses limites. Si on a un tableau de 10 éléments et qu'on accède au 11ème élément, on accède à une zone pouvant contenir n'importe quelle donnée et très probablement pas celle qui était imaginée par le programmeur. Le déréférencement de `NULL`, ou plus généralement le déréférencement invalide, consiste à utiliser une adresse invalide et à tenter de lire ou écrire à cette adresse. Quand un programme est lancé par un système d'exploitation, ce dernier lui octroit une zone mémoire pour son usage exclusif. Si le programme tente d'accéder à une zone mémoire qui ne lui appartient pas, une erreur d'accès mémoire est levée et le programme est arrêté. Le cas le plus courant est celui du déréférencement de `NULL`. `NULL` est une valeur spéciale utilisée pour dénoter des valeurs particulières, en parucilier l'absence de valeur. Par exemple, une liste chaînée se termine souvent par un pointeur `NULL` pour indiquer la fin de la liste. Dans la plupart des systèmes, `NULL` vaut techniquement 0 et ce n'est pas une adresse valide. Le _dangling pointer_ survient lorsqu'on utilise un pointeur sur une valeur qui n'a jamais été allouée ou été libérée. Dans les deux cas, la valeur pointée est indéterminée et l'utilisation de cette valeur peut conduire à des comportements indéfinis. Par exemple, en C le code suivant pose problème : ```c int *p = calloc(1, sizeof(int)); /* allocation d'un entier dans le tas */ *p = 42; /* écriture de 42 à l'adresse pointée */ free(p); /* libération de la mémoire */ printf("%d\n", *p); /* utilisation de la valeur pointée */ ``` Après le `free(p)`, l'adresse mémoire pointée par `p` peut être réutilisée par une autre partie du programme et contenir n'importe quelle valeur. Il n'est donc pas possible de prédire la valeur affichée par le `printf`. Notons que le _dangling pointer_ apparaît généralement dans les situations où l'allocation dynamique se fait manuellement (C, C++, ...) mais il peut très bien arriver sans allocations dynamiques par échappement de portée : ```c int *p; { int x = 42; p = &x; } printf("%d\n", *p); ``` ou plus généralement : ```c int *func(void) { int n = 42; /* ... */ return &n; } ``` Dans les deux cas, le pointeur (`p` ou `&n`) pointe sur une valeur qui a été allouée dans la pile mais qui n'est plus valide à la sortie du bloc représenté par les accolades. == Gestion de la mémoire Un programme utilise deux zones de mémoire : une zone statique et une zone dynamique. La zone statique est prédéfinie à la compilation et contient les données globales (ou explicitement statiques avec le mot clé `static` du C) et ne peut être modifiée. La zone dynamique est réservée à l'éxécution du programme et contient deux sous-zones : la pile et le tas. La _pile_ est une zone de mémoire avec une taille maximale définie par le système et qui se remplit automatiquement en fonction du modèle d'execution du langage. En général, elle se remplit à chaque appel de fonction avec les données locales et l'adresse de retour des fonctions, puis se vide lorsque les fonctions terminent. Un dépassement de pile (_stack overflow_) peut survenir lorsque qu'on cumule trop d'appel de fonction. Cela peut arriver facilement avec une récursion mal maîtrisée. Un dépassement de pile est une erreur fatale au programme. Le _tas_ est une zone libre de mémoire dans laquelle on peut allouer des données dynamiquement. L'allocation dynamique est réalisée par l'appel de fonctions spécifiques qui demandent au système d'exploitation de réserver une zone de mémoire de taille donnée. Lorsque la mémoire n'est plus utilisée, il est nécessaire de la libérer pour éviter les _fuites mémoire_. Si trop de mémoire est allouée sans être libérée, le programme peut consommer toute la mémoire disponible et être arrêté par le système d'exploitation dans le meilleur des cas. Dans le pire des cas, le système entier est paralysé car privé des ressources mémoires nécessaires à son fonctionnement nominal. Dans la bibliothèque standard du C, la fonction `malloc` et ses dérivées peuvent être utilisées pour allouer et `free` pour libérer la mémoire. Pour éviter les fuites mémoires, il faut donc un `free` pour chaque allocation réalisée. Cependant, les programmes non triviaux mettent en oeuvre des structures de données complexes dont certaines parties sont allouées dynamiquement et savoir quand faire le `free` peut être délicat. Il peut arriver que le programmeur pêche par exces de prudence et se retrouve à libérer deux fois une même allocation (_double free_). La double libération a un comportement indéterminé et peut conduire à une corruption de l'allocateur de mémoire entrainant des allocations incohérentes et difficiles à diagnosiquer. Certaines analyses statiques peuvent détecter les fuites mémoires et les doubles libérations en suivant le flôt de contrôle du programme et en vérifiant que chaque allocation est bien libérée une et une seule fois. Notons que les langages à gestion automatique de la mémoire ne sont pas exempt de fuites mémoires. La gestion automatique de la mémoire est basée sur un ramasse-miettes qui libère la mémoire automatiquement lorsqu'elle n'est plus utilisée. Toutefois, lorsque le ramasse-miettes ne peut pas déterminer si une donnée est encore utilisée ou non, il peut décider de la conserver alors qu'elle n'est plus utilisée. C'est le cas des ramasse-miettes dits «conservatifs».
https://github.com/r8vnhill/apunte-bibliotecas-de-software
https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/unit1.typ
typst
#import "@preview/ctheorems:1.1.2": * #show: thmrules #let definition = thmbox("definition", "Definición", inset: (x: 1.2em, top: 1em)) = Unidad 1: Introducción #include "Unit1/Intro.typ" #include "Unit1/Kotlin.typ" #include "Unit1/Basics.typ" #include "Unit1/NullSafety.typ" #include "Unit1/Input.typ" #include "Unit1/Clean.typ" == Respuestas *Ejercicio: Cálculo del Área de un Círculo* ```kotlin const val PI = 3.14159 fun circleArea(radius: Double): Double = PI * radius * radius ``` *Ejercicio: Reescribir usando una expresión `when`* ```kotlin fun login(username: String, password: String): Boolean = when { loginAttempts >= MAX_LOGIN_ATTEMPTS -> false isValidPassword(password) -> { loginAttempts = 0 true } else -> { loginAttempts++ false } } ``` *Ejercicio: Suma de un Rango de Números* ```kotlin fun sumRange(a: Int, b: Int): Int { var sum = 0 if (a <= b) { for (i in a..b) { sum += i } } else { for (i in a downTo b) { sum += i } } return sum } ``` *Ejercicio: Procesamiento de Temperaturas de Ciudades* ```kotlin fun main() { val temperaturasPorCiudad = mapOf( "Madrid" to 22, "París" to null, "Berlín" to 18, "Roma" to null, "Londres" to 15 ) for ((ciudad, temperatura) in temperaturasPorCiudad) { val temperaturaFormateada = temperatura?.toString() ?: "Temperatura no disponible" println("La temperatura en $ciudad es: $temperaturaFormateada") } } ```
https://github.com/EpicEricEE/typst-marge
https://raw.githubusercontent.com/EpicEricEE/typst-marge/main/tests/resolve/side/test.typ
typst
MIT License
#import "/src/resolve.typ": resolve-side #context assert.eq(resolve-side("left"), left) #context assert.eq(resolve-side(right), right) #context assert.eq(resolve-side(start), left) #context assert.eq(resolve-side("inside"), left) #{ set page(binding: right) context assert.eq(here().page(), 1) context assert.eq(resolve-side("inside"), right) pagebreak() } ~ #{ set text(dir: rtl) context assert.eq(here().page(), 2) context assert.eq(resolve-side("inside"), left) context assert.eq(resolve-side("end"), left) pagebreak(to: "even") } ~ #{ context assert.eq(here().page(), 4) context assert.eq(resolve-side("inside"), right) } ~ #{ set page(flipped: true) context assert.eq(here().page(), 4) context assert.eq(resolve-side("inside"), right) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/src/util.typ
typst
Apache License 2.0
/// Predefined color palette /// #let w = 4 /// #box(width: 100%, align(center)[ /// #canvas(length: 2em, { /// for (i, color) in util.colors.pairs().enumerate() { /// let x = calc.rem(i, w) * 2 /// let y = calc.floor(i / w) * 2 /// draw.rect((x, -y), (x + 1, -y - 1), fill: color.last(), stroke: none) /// draw.content((x + 0.5, -y - 1.25), color.first()) /// } /// }) /// ]) #let colors = ( orange: rgb(245, 180, 147), yellow: rgb(250, 225, 127), green: rgb(127, 200, 172), pink: rgb(236, 127, 178), purple: rgb(189, 151, 255), blue: rgb(127, 203, 235) ) /// Pads a string on the left with 0s to the given length /// /// #example(`#util.lpad("0100", 8)`, mode: "markup") /// /// - string (str): The string to pad /// - len (int): The target length /// -> str #let lpad(string, len) = { let res = "0" * len + string return res.slice(-len) } /// Returns the anchor on the opposite side of the given one /// /// #example(`#util.opposite-anchor("west")`, mode: "markup") /// /// - anchor (str): The input anchor /// -> str #let opposite-anchor(anchor) = { return ( north: "south", east: "west", south: "north", west: "east", north-west: "south-east", north-east: "south-west", south-east: "north-west", south-west: "north-east" ).at(anchor) } /// Returns the anchor rotated 90 degrees clockwise relative to the given one /// /// #example(`#util.rotate-anchor("west")`, mode: "markup") /// - anchor (str): The anchor to rotate /// -> str #let rotate-anchor(anchor) = { return ( north: "east", east: "south", south: "west", west: "north", north-west: "north-east", north-east: "south-east", south-east: "south-west", south-west: "north-west" ).at(anchor) } #let valid-anchors = ( "center", "north", "east", "west", "south", "north-east", "north-west", "south-east", "south-west" )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/touying/0.1.0/utils/states.typ
typst
Apache License 2.0
// touying slide counters #let slide-counter = counter("touying-slide-counter") #let last-slide-counter = counter("touying-last-slide-counter") #let last-slide-number = locate(loc => last-slide-counter.final(loc).first()) #let touying-progress(callback) = locate(loc => { let ratio = calc.min(1.0, slide-counter.at(loc).first() / last-slide-counter.final(loc).first()) callback(ratio) }) // sections #let sections-state = state("touying-sections-state", ((body: none, count: 0, loc: none),)) #let new-section(section) = locate(loc => { sections-state.update(sections => { let last = sections.pop() last.count -= 1 sections.push(last) sections.push((body: section, count: 1, loc: loc)) sections }) }) #let section-step() = sections-state.update(sections => { let last = sections.pop() last.count += 1 sections.push(last) sections }) #let touying-final-sections(callback) = locate(loc => { callback(sections-state.final(loc)) }) #let touying-outline(enum-args: (:), padding: 0pt) = touying-final-sections(sections => { pad(padding, enum( ..enum-args, ..sections.filter(section => section.loc != none) .map(section => link(section.loc, section.body)) )) }) #let current-section = locate(loc => { let sections = sections-state.at(loc) sections.last().body }) #let touying-progress-with-sections(callback) = locate(loc => { callback(( current-sections: sections-state.at(loc), final-sections: sections-state.final(loc), current-slide-number: slide-counter.at(loc).first(), last-slide-number: last-slide-counter.final(loc).first(), )) })
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/054%20-%20Lost%20Caverns%20of%20Ixalan/001_Episode%201.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 1", set_name: "Lost Caverns of Ixalan", story_date: datetime(day: 20, month: 10, year: 2023), author: "<NAME>", doc ) == Quint As Quint planeswalked from a dimly lit stone corridor into leaf-dappled sunshine, the heat slapped him like a moist towel. It reminded him of Detention Bog, but the ground here didn't squelch, and the bell-shaped flowers on the vines twining around the trees smelled pleasant rather than corpselike. He turned in a slow circle, examining his surroundings with interest until he stepped into a cloud of tiny bugs. Then he did a lot of spitting and waving his trunk around, tripping over a rock and falling to one knee. Clumsy as always, he berated himself. At least no one was here to see it. Except, unfortunately, something was. He looked up and found himself dangerously close to an open mouth full of curved pointy teeth. They belonged to a two-legged creature covered in bright feathers, its sharp talons carving grooves in the ground. His heart sped up in fear and wonder. Mostly fear. This, presumably, was one of the infamous dinosaurs of Ixalan. #figure(image("001_Episode 1/01.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) With a sound between a growl and a screech, it leaped toward him. Quint dodged sideways, landing in front of another dinosaur. They were smart enough to flank. That was bad. A third, larger creature joined the others. They circled, beady eyes tracking every twitch of his trunk. Perhaps he could use his magic to drop a branch on them, or make them run into each other? He started to trace a sigil in the air to drive them away. Before he completed the spell, the dinosaurs froze and looked to his left. Someone emerged from a crumbling stone structure. Tan skin, dark hair pulled back from a face he saw in profile. Her muscled arms, bracers, and the sword tucked into her belt suggested she was a warrior, while the smoothness of her skin marked her as a youth—no older than her late teens, maybe early twenties. "Pantlaza, come," she said. The third dinosaur trotted obediently to her side, even though it was tall enough that its head was at her eye level. With the flick of a hand, she dismissed the others as if they were trained pets, and they disappeared into the jungle. The girl faced him, one of her brown eyes covered by a metal disk, like an eyepatch. "Are you <NAME>?" she asked. "I am," Quint replied, eyeing the vine-covered ruins. A pyramid? Was that limestone? With effort, he shifted his attention back to his savior. "Call me Quint. Thanks for the help. And you are?" "I'm called Wayta," she said. "The warrior-poet told us to expect you." "I can't wait to meet her," Quint said, fanning his face with his ears. Ixalan was a sauna compared to the dry heat of Pillardrop. "Do all new arrivals receive a dinosaur welcoming party?" "No," she said. "We've had strangers appearing in odd locations, so patrols have increased. Can't be too careful after the war." "Understandable." Quint stepped toward the ruins. "Is this Orazca? From Saheeli's descriptions, I expected more gold." Wayta followed his gaze. "That isn't Orazca. Come this way." Quint trailed after her. Through a gap in the trees, sunlight glinted on metal. He moved toward the light, shading his eyes as he stepped past the barrier of foliage and saw the full, blinding brilliance of the golden city in the valley below. Spires like needles reached high into the blue sky, burnished roads and buildings stretched into the distance, and at the center, an enormous temple rose like a gleaming mountain. "Ah," Quint said. "Yes. That is more gold." He rubbed the afterimages from his eyes. "I don't suppose you could guide me? Are you busy? Do you know the city well?" "Well enough," Wayta replied, crossing her arms over her chest. "Better than I do, I'm sure," Quint said. "True." Wayta cracked a smile. "You trust easily." "You didn't let the dinosaurs have loxodon for lunch," Quint said. "That's good enough for me." They hiked down the hillside to the arch towering over the gates to the city. People, carts, and dinosaurs jostled for space, watched by guards wearing silver helmets with winglike crests and wielding spears adorned with bright orange feathers. The broad central avenue funneled them into a market, stalls and blankets arranged in concentric circles that spread out from a fountain at the center, fed by aqueducts. Some stares followed Quint, but he ignored them as he trailed after Wayta, examining spiny pinkish fruit here, gem-studded necklaces there. It was hard to believe this place had been battered by war, but the wounds still showed, in fallen buildings and gouged walls and unevenly colored patches in the streets beneath his boots. They reached the palace entrance, where Wayta consulted with a guard while Quint inspected the designs on the walls, the red and white paint faded with age. He was surprised to find depictions of a sphinx; he hadn't realized their influence extended to this plane as well. This one seemed to be giving something to a smaller figure, or perhaps receiving a gift? Before he could continue his examination, another guard appeared and led them, not into the vast pyramid, but around it, to an unadorned building partially damaged by magic near the edge of the city. Acid-eaten holes marred the door, while scorch marks on the walls traced gruesome outlines of the presumably deceased humans who had once stood there. "This way," Wayta said, gesturing for him to precede her. #figure(image("001_Episode 1/02.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Quint stepped into a bare room with stairs at the back. Voices drifted up as he descended, finding himself in a much larger room covered in painted murals and reliefs of warriors emerging from a cave to worship a figure with a sun glyph behind their head. On the floor, a series of copper tablets were laid out, carved with glyphs and inlaid with jade, cinnabar, and gems—amber, turquoise, and rose quartz, if he wasn't mistaken. Along another wall, this one decorated with warriors fighting some impossibly tall bipedal creature, a door made of gold and silver and copper stretched from the floor to the ceiling. Rectangular alcoves in the door suggested the tablets had been set into them. Two women paused their conversation as he entered. Both had brown skin, dark hair and eyes, but the similarities ended there. Saheeli was taller, with sharper features, and wore a deep red dress and elaborately wrought golden jewelry, while the other—presumably Huatli—carried herself like Wayta, like a warrior, her silver armor supporting that assessment. She sat on the floor, surrounded by the tablets, until the dinosaur Pantlaza ran over and knocked her down like a massive, eager puppy. "Quint, you made it!" Saheeli exclaimed, rushing to his side. "Welcome to Ixalan. Sorry I wasn't there to greet you, but the Omenpaths are less … flexible than planeswalking. This is my partner, Huatli." "A pleasure," Huatli said, trying to see him past the dinosaur's head. "I had hoped Pantlaza would be less energetic after some exercise outdoors, but clearly I was mistaken." "He had fun sneaking up on me, at least," Quint said. "Thanks for inviting me here, by the way. When Saheeli told me you'd found evidence of the Coin Empire here, I knew I had to see it." "Have you figured out who your long-dead friends are?" Saheeli asked, touching his arm lightly. "Not yet," Quint said. "I've tracked them through various planes, but they're still an enigma. The Coin Empire isn't even their name, just something I call them …" He trailed off, examining the tablets. "Is this the project you needed help with?" "It is," Huatli said, smiling up at Saheeli. "I believe they're the key to opening this." She gestured at the huge door. "The glyphs form a poem, and the parts I've translated suggest we'll find the birthplace of humanity and home of the gods somewhere beyond." "That's quite a claim," Quint said, squinting. A trumpet of excitement escaped him as he pointed to one of the tablets with his trunk. "Those are the coins! They're just like the ones—" "Huatli, are you still down there? The sun will forget your face if you don't come out occasionally." A man descended the stairs, muscular and armored, radiating calm and amusement. Huatli grinned at the newcomer. "Inti, welcome," she said. "Did one of your sisters send you because I missed a meal again?" Inti smirked as he scratched Pantlaza's head ridge. "I heard our guest had arrived, and yes, I came to check on you and Saheeli. You can't eat ancient rocks, no matter how hard your head is." "Quint, this is Inti," said Huatli. "Seneschal of the sun, dinosaur rider, hero of the war against the Phyrexians." "And her cousin," Saheeli added. Quint inclined his head politely, his gaze sneaking back to the coins on the tablets. "Before you ask," Huatli said, raising a hand, "I haven't found anything about weapons or magic we can use against the Dusk Legion." Quint flared one of his ears in her direction. Weapons? Dusk Legion? "The emperor grows more impatient," Inti said, his voice now carefully neutral, as if he were reciting someone else's words. "He once again asks if the door could be opened using other methods." "He wants to break it down," Saheeli explained. Quint grimaced. Break a priceless artifact? How could anyone even suggest it? "The tree with shallow roots will not weather the storm," Huatli replied, shaking her head. "Tell him I'm almost finished." "We'll continue preparations then," Inti said. "You're sure this won't just be a closet? If it's full of rubber balls, I'm going to tease you about it forever." "I'm sure," Huatli said. "Be ready for a long journey, not a game." Inti left, Pantlaza curled up in a corner, and Saheeli began to massage Huatli's shoulders. Huatli sighed and rolled her head forward. "You're doing your best," Saheeli said. "So are you," Huatli replied. "How are your creations coming along?" Saheeli laughed. "I made the mistake of wondering aloud if I could make them breathe fire. The emperor was extremely interested." So was Quint, honestly. Saheeli's artificer skills were legendary. Strixhaven could charge double tuition for any class she taught, and it would still be full to the rafters. Huatli wrapped an arm around Saheeli's leg. "I just don't want more war," Huatli said softly. "A fine sentiment for the empire's warrior-poet, eh?" "And I want you to be safe," Saheeli said, crouching down to embrace Huatli more tightly. "Hard to imagine safety with every plane devoted to discovering new forms of danger, but that's what fire-breathing dinosaur constructs are for." "I suppose you should get back to your workshop," Huatli murmured. "I suppose I should," Saheeli agreed. Quint averted his eyes to give them a semblance of privacy. Saheeli waved at Quint as she climbed the steps, blowing a last kiss to Huatli before she left. Huatli cleared her throat, skin flushed. "Ready to begin?" "Always," Quint said, preparing to call the magic that would help him translate. "What do you have so far?" Within moments, they were settled into their task, and Quint couldn't have been happier. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) == Malcolm The body slumped in a pile of half-rotted leaves in the jungle, close enough to Sunray Bay that Malcolm could have walked instead of flying. Bluecoats milled around him, taking measurements and drawing pictures, speaking in low voices that grated on his siren hearing—and his nerves. "One of your people, Lee?" asked the man in charge of the scene. It was hard to tell. Strange clusters of mushrooms obscured the corpse's features like red sores, erupting from his mouth and one of his eye sockets. Black veins traced his ashen skin, more fungi growing along his neck and arms. He seemed to be rapidly deteriorating, and yet he'd been alive only a few hours earlier, according to the local who found him. "I think this is Lank," Malcolm said finally. "He was a miner in Downtown." He raised his eyes to the Bluecoat's. "<NAME> said he had a note?" The man held out a scrap of folded paper to Malcolm, who pinched it between two fingers and shook it open. #emph[Downtown under attack] , it read. #emph[Send help] . It was signed by the mayor, <NAME>, the spattered, uneven ink suggesting he'd scrawled it in an enormous hurry. That explained why deliveries from the mine had slowed, then stopped a few days earlier, bringing the rest of Sunray Bay's economy—and by extension, the entire Brazen Coalition's—to a grinding halt. <NAME> had already ordered Malcolm, Downtown's official emissary, to go back to investigate, and Malcolm had been eager to oblige. He owned shares in the lucrative mine, and more importantly, he had friends there. Now he knew to expect the worst. "What do you think?" the Bluecoat asked. "Foul magic?" "Looks like it," Malcolm said. But who? And why? The Brazen Coalition had plenty of enemies. The Sun Empire was eager to push so-called invaders out of their territory. The River Heralds raided on and off, trying to stop the earthquakes and runoff caused by the mines, though they'd been quieter of late—too quiet. The Dire Keel fleet chafed against the edicts of Governor Brass and might see this as a way to take High and Dry back for themselves by undercutting their source of wealth. Even the Dusk Legion vampires were trying to gain a foothold, wanting riches to take back to Torrezon: They'd just as soon move in like hermit crabs and run the place themselves. Any one of their rivals would be happy to cause trouble in Downtown, but no one had yet stepped forward to claim responsibility. Sadly, the corpse had no answers. Malcolm would have to do his own digging, and hope he struck gold. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) == Amalia #emph[Come to me] , the voice whispered. A vast sea of sand stretched before Amalia, dotted with stone islands, the far shore lost in shadow. #emph[Come to me.] Waterfalls of fire poured like molten metal down the walls of a vast cavern, bright and scorching. #emph[Come to me.] A round, golden door loomed, etched with sigils in a language like the Sun Empire's Itzocan, yet different. #emph[Come …] Amalia bolted upright in her saddle, her arm aching as if she'd been pushed. She blinked owlishly at Clavileño, commander of the soldiers who protected the expedition. He scowled, showing his fangs. "You were about to fall," he said accusingly, his voice rough. "Thank you," she replied, still catching her breath. He rode away, cold-eyed as always. Above her, the branches of the jungle trees wove together like a ceiling of leaves and vines, the air musty with the scent of wet earth from recent rains. Amalia felt a pang of homesickness for the library on her family's estate. It was easy to dream of adventure surrounded by books and peace. Much harder to savor it when tiny worms hanging from invisible threads fell into her collar, and dinosaurs sprang out at her from the green, and storms tried to soak all her maps every afternoon as regularly as the chiming of a clock. Still, after the war, she wanted to do something worthwhile with her life, something more than poring over dusty tomes. The position of cartographer for the Queen's Bay Company promised precisely that, and now here she was, mapping the wilds of Ixalan. "How are you feeling?" <NAME>, one of the high officers of the Company, smiled kindly from her left. Amalia couldn't tell him about her strange visions, or the voice that whispered to her. If she were in the throes of a blood fast, it would have been understandable. But she had fed recently, and yet she kept falling into a trance, seeing and hearing things that weren't there. "I'm fine, thank you," Amalia replied. "I'm still becoming accustomed to the … travel arrangements." "Rough, yes?" Bartolomé said. "Do your best. I have a balm that helps with fatigue. I'll give you some when we stop." "I'm very grateful," Amalia said. Bartolomé flicked his reins and moved up in their procession. They were about thirty all told, between the soldiers, the servants, and the penitents seeking absolution for crimes committed in Torrezon. At the front, stiff backed on his massive mount, <NAME> led their expedition. He'd barely acknowledged her when they first met, seemingly absorbed in his own thoughts and priorities, and that hadn't changed during their long sea voyage, or in the days since they left Queen's Bay. When he wasn't barking orders or staring moodily at nothing, he read and reread a battered book no one else was allowed to see. Bartolomé tried to borrow it once; Vito grabbed him by the throat and pinned him to a tree. She got the sense that the two vampires didn't share the same goals, for all that they purported to have a common purpose. A Temple of Aclazotz supposedly awaited them in the depths of this continent. Inside that temple, a door. And behind that door, hopefully, a solution to the growing schism that threatened to split the Church of Dusk in a spasm of violence worse than the Apostasine Wars. Was it the door in her visions? Amalia wouldn't know until they found it. Until then, she had work to do. She returned her attention to her cartomancy, pulling out the increasingly detailed map of their journey. Their path from Queen's Bay was a red trail that shimmered faintly at their present location. She pricked her smallest finger with one of her fangs, then daubed the bloody digit in a small well of ash, mixing it. So combined, she smeared the solution across the surface of the map, imbuing it with her intent. Slowly, like ink feathering across wet paper, the mix of blood and ash spread to fill the blank portions of her scroll in precise detail. #emph[Come to me]  … Amalia shivered, wishing she knew whose voice called to her. Hoping—dreading—that she'd soon find out. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) == Huatli The translation was finished. Huatli stretched and glanced at Quint, who studied his notes. Wayta stood in a corner, watching them with interest. Huatli repeated the translation to herself, savoring the rhythms of the poem. #emph[We are the Komon, of the Fifth People, sticks and spades of the good place granted to us by the Deep Gods, exiled to the surface by our failures.] #emph[We defeated the Great Betrayer, we fought the traitors, invaders, imprisoners of Chimil, the Riven Star, the glory of her threefold light hidden.] #emph[The Age of the Sun ended in darkness for sixteen full counts of her turning, until the Thousand Moons shattered the circling shell of her prison …] "What is a full count?" Quint asked. "Twenty," Huatli replied absently. "A turning is likely a year. If their system is like ours, that would mean 320 years." "Three centuries of darkness?" Quint exclaimed. "Incredible." "Horrible," Huatli murmured. "How could anyone imprison a god?" "This is the god you believe is like yours?" Quint asked. "Yes," Huatli said. "Ours is the Threefold Sun, though we never called them Chimil." She closed her eyes. "It may be heretical to think they are the same." Quint made a shrug-like gesture with his trunk. "The mysteries of the planes are never-ending. New discoveries often rewrite old histories." Huatli cocked her head at him. "You sound like you've had experience with that." "I certainly have. Remind me to tell you about my mentor sometime." Quint tapped a line on his notes. "What about this part?" Huatli scanned that tablet. #emph[We leave this memory and key and map, so the seeds of our fruit may spread through the winding ways of Topizielo, to Matzalantli, golden door of the gods, and find the lost roots of our tree.] "I don't think it means this door," Huatli said. "There must be another beyond it." "Far beyond, if 'winding ways' are an indication," Quint said. "Not that we'll ever find it unless we get this one open." Huatli examined the door. The tablets containing the poem had been embedded in the metal when they were found, but she'd quickly discovered they were removable. Behind the tablets were faint glyphs, one per tablet recess, each a single word. "Have you replaced the tablets in the order you found them?" Quint asked. "Yes, that didn't work," Huatli said. "Perhaps a verbal command?" Quint suggested. "I opened a similar door by reciting part of the Canticle of Jed." "The what?" "It's an important loxodon story. Never mind, it was just an idea." "What could I recite?" Huatli mused. "The poem?" Quint asked. Huatli frowned pensively. "It's quite long, and my pronunciations of the old tongue might not be correct." "You have a point," Quint agreed. He flipped one of the tablets over. "Interesting that there are symbols on the door, but not on these." Huatli examined the door's glyphs again. Warrior, leaf, farmer, shadow … simple, common words. None of them matched the glyphs on the various tablets. She read through the poem one more time, looking for patterns she might have missed. "Oh!" she exclaimed. "I have an idea." She reached for the tablet with the line, "we fought the betrayers," and slid it into the hole with the symbol of the warrior. Nothing happened. "You might need to put them all in the right spots first," Quint said encouragingly. Huatli placed the tablet with "lost branches of our tree" with the leaf symbol, then "sticks and spades of the good place" with the farmer symbol, then "The Age of the Sun ended in darkness" with the shadow glyph. On and on she went, until all the tablets were slotted back into the door. A whisper of magic touched her fingers, and the space around each tablet glowed softly. The glow spread to the edges of the door, and with a deep bass note, it cracked open. "How did you—" Quint began. "The glyphs on the door matched the tablets," Huatli said. "Just not directly. Symbolic motifs." "Ah, of course." Quint gestured with his trunk. "Care to do the honors?" Huatli gripped the edge of the door and pulled. It made a grinding noise where it dragged across the floor, stale air rushing through the gap. Beyond, a sloping tunnel awaited, cold and dry and dusty, broad enough to fit the smaller pack dinosaurs. #figure(image("001_Episode 1/03.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "Get a torch," she told Wayta, who quickly complied. They descended, Huatli leading the way with Quint behind her, Wayta and another warrior in the rear. At the bottom of the tunnel, they found a room large enough to fit a pyramid inside. A row of corpses crouched on the ground in front of the tunnel entrance, wrapped in linen cloth. Strands of jade and cinnabar beads hung from their necks, and strips of bark were tucked into the bands wound around their eyes. They seemed to be warriors, their weapons resting near their bony hands, though their armor was different from what she and Wayta wore. Beneath their burial linens, their bones glowed a faint pinkish purple, in strange patterns that throbbed with magic. "What is that?" Quint asked, pointing. The remains of a massive humanoid creature dominated the opposite corner of the room, its helmet—no, its horns—brushing the ceiling. Dozens of spears bristled from its body, looking small as arrows, some of their hafts snapped despite being made of metal. Rust-colored armor encased its body, with curves and gaps like something between a skeleton and a cage. Desiccated gray skin was visible beneath, and hands the size of a person ended in curved talons. "I've never seen anything like it," Huatli muttered. "It's bigger than the largest dinosaurs—Zacama excepted." "Safe to assume it killed these people," Quint said. "But it was wearing armor. No ordinary beast, then. Why were they fighting, I wonder?" "Perhaps answers await further in," Huatli replied. To the guard, she said, "Find the seneschal and the Imperial champion. Tell them we leave as soon as the pack dinosaurs are ready." The guard saluted and hastened to deliver the message to Inti and Caparocti. Huatli retreated more slowly, leaving Quint to inspect the remains with Wayta, the torch's flame casting eerie shadows on the walls. She cast a last glance at the kneeling warriors and the monstrous corpse in the corner before climbing back up the stairs. Would she be able to find a path to peace down in the deeps, as she hoped, or was this long-ago battle an omen that her quest was doomed from the start? Saheeli waited in the room above, and Huatli sighed in pleasure as she buried her face in her partner's neck. "I wasn't gone that long," Saheeli said, her calloused fingers sneaking into a gap in Huatli's armor to brush her skin. "And yet it always feels like forever," Huatli replied. "Let's have a coffee, just us. Now that the door is open, we'll be departing soon." "To where?" Saheeli's eyes, lined with kohl, widened. "What did you find?" "Death and darkness," Huatli muttered. "Come on, my heart. I need to take my fill of you before we part." She pulled Saheeli out into the sunlight, twining their hands as they walked the golden streets together in companionable silence. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) == Malcolm The name "Downtown" started as a joke and stuck. The mining camp was split between an outpost on the surface and the main village underground in a huge cavern. The actual mine was an ancient, dry cenote that delved deep into the earth, tunnels extending into the rock at various levels like spokes in a machine with hundreds of wheels. Wooden buildings were scattered around the lip of the vast hole, no particular rhyme or reason to their placement beyond the whims of their builders. Cranes and catwalks extended over the void, supporting pulley-operated elevators, while hydraulic lifts and switchback stairs hugged the walls. More pulleys hauled up buckets of ore that was piled into carts on tracks that crisscrossed the ground. Refineries handled chemical and magical conversions, other processing areas managed the manual cleaning, and silos were filled with product ready for delivery to the surface. Everything was usually lit by giant daylight lamps, magical and mundane, as well as personal torches and candles and lanterns. #figure(image("001_Episode 1/04.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) The lamps were dark, and as far as Malcolm could tell, Downtown was entirely empty except for himself and the people he'd brought from Sunray Bay to help with the investigation. Breeches adjusted his three-cornered hat with a blue-furred hand, his gold eyes narrowed. "ALL GONE?" the goblin screeched. "All gone," Malcolm agreed, frowning. Raw ore sat in mine carts left mid-track, and in barrels and crates, some overturned. Sorting tables were piled high with partially cleaned metals or crystals, brushes and chisels resting nearby as if their users were about to return from a break. The doors to the dormitories stood open, beds rumpled as if hastily abandoned. Food rotted in kitchens and eating areas, and the smell of mold permeated everything. The only signs of violence were scorch marks on some buildings and a scattering of dropped weapons. Malcolm examined a pickaxe with a strange, sticky substance on it—blood? He wasn't going to touch it to find out. All of Downtown's pulley elevators were fastened at the top of their cranes, as if they'd been pulled up to defend against a siege from below. All except one. Malcolm held up his lantern as he approached that lift. It was so dark, he almost stepped in the lines of ichor painted on the ground nearby. He knelt to examine them more closely. One word, the letters thick and blocky. DOWN. The feathers on his arms ruffled. If this was a trap, they'd be walking right into it. But how else could he find out what happened to an entire missing town? Like the guttering flame in his lantern, he nursed a faint hope that survivors might be found and rescued. "You," he said, pointing at one of his companions. "Go back to Sunray Bay and tell them what we've found. You," he said, pointing at another. "Stay up here and wait for us." Breeches stood at the edge of the void, an inscrutable expression on his goblin face. "DOWN?" he asked. "Yes," Malcolm said, staring at the message. "Down." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) == Amalia The crumbling ruins of the temple to Aclazotz were partly reclaimed by the jungle, vines choking the walls, tree roots cracking the stone floors, branches piercing the fallen ceiling. As the blood-red ink of Amalia's spell filled out another area of her map, the soldiers and servants milled around the forward camp established by those who had arrived days earlier. A hush fell over the gathering as Vito walked among them, radiating resolve and menace. In one hand, he carried a lance, its point a few handspans above his head. In the other, he gripped the book that never left his sight. His blue eyes seemed to blaze with an inner light, and the vampires moved closer as if he were a magnet and they were all metal shavings. "This lance," Vito began, holding up the weapon, "was wielded by Venerable Tarrian, in whose footsteps we follow. This is his journal." He held up the book. "It contains a record of his travels with <NAME> and his revelations, suppressed by the church and recently recovered by true believers." #figure(image("001_Episode 1/05.png", width: 100%), caption: [Art by: Nereida], supplement: none, numbering: none) True believers? Amalia stiffened. Surely, he didn't mean supporters of the Antifex. She'd heard some of the stories— "Inside this temple," Vito continued, "is a door that leads to the resting place of our ancient god and sire, Aclazotz, creator of the first vampires. Though he slumbers, he can be reawakened by his most faithful servants." Awaken a god? Was such a thing possible? Amalia bit her lip, wincing as her fangs pierced her flesh. Perhaps she wasn't alone in her thoughts, because a low murmur went up among the crowd. Vito raised the lance and silence fell again. "If we return Aclazotz to Torrezon, as this scripture promises, he will heal the faithful and bring peace to the land. The schism will end, and we will once again be free to spread our catechism to this savage continent." Something in his tone made Amalia shiver, despite the heat. Healing and peace sounded like a righteous cause, but at what cost? Was anyone else as unnerved as she was? Bartolomé watched Vito with a carefully neutral expression, so she hid her feelings as well. Who knew what Vito might do if challenged? "Onward, then," Vito said, gesturing with the lance. "To our destiny." Vito entered the ruined temple, and with a prescient chill, Amalia joined the procession that followed him. Inside was a cenote, broad and deep, the curving stairs carved into the side slick with moisture. Some vampires carried lanterns, others lit their way with floating candles tethered to their packs or belts by long chains. At the bottom of the staircase, a doorway led into a room with multiple recesses in the walls. Amalia peered into one, finding a moldering pile of bones. She backed away, bumping into Clavileño, who hissed at her and shoved her forward. The catacombs continued, room after room filled with the bones of the dead. Priests? Old sacrifices? Did she really want to know? The flames at her back flickered as she walked, casting shadows on every wall. At last, they reached a large, circular room full of empty candelabras, with a grooved obsidian altar in front of a golden door. Saint Elenda was said to have emerged from such a door. To Amalia's surprise, this was not the door in her visions. One of the soldiers attempted to open it, but it remained stubbornly closed. Two more soldiers joined the first to no effect. "Perhaps it cannot be opened," Bartolomé mused. "Have we come so far for nothing?" "Aclazotz guides me," Vito said, his voice echoing in the enclosed space. "Clavileño, bring me one of the porters." Clavileño did as commanded, and soon one of the pale-faced human servants from the camp entered, hands clenched nervously. "Be not afraid," Vito said. "Venerable Tarrian has written, 'The blood of the lamb shall open the door to paradise.' We are being tested, and we must be strong. Come to me." The porter approached him hesitantly. Vito rested his hand on the man's head, gazing into his eyes with a benevolent smile. "Put him on the altar," Vito said. Clavileño obeyed, lifting the man off the ground with vampiric strength. The porter struggled, wailing as the soldier attempted to lay him on the obsidian slab. Clavileño did not budge. Vito's gaze fell on Amalia, and she shivered. "You," he said. "Help hold him down." Amalia cringed, arm raised as if to shield herself. "His sacrifice will mean his salvation," Vito said. "Do as I say." "You corrupt the sacred blood rites," Bartolomé protested. "The rites of the church are a pale imitation of the true sacraments of Aclazotz," Vito said dismissively. "The journal will help us unlock his power, and you will understand." Amalia stared at Bartolomé, appalled, hoping he would stop this travesty. Instead, he backed away, his face once again a mask. Vito gestured at another soldier. "Help Clavileño." His orders were obeyed, and soon the porter lay prone on the altar, limbs outstretched, keening piteously. Vito tucked the journal under one arm and unsheathed the knife at his hip. "We offer your life to Aclazotz. This blood is our covenant, everlasting as the life promised to us. In his darkness we are made holy." With a single swipe, Vito cut the victim's throat. The altar blazed to life, its blackness seeming to glow. Instead of spraying into the air, the blood flowed down the grooves in the altar, to the floor and across to the door, which brightened with the same luminescent darkness. The door groaned open. A gust of stagnant air emerged from the tunnel beyond like the breath of some foul carrion eater, the flames in the room guttering wildly. #figure(image("001_Episode 1/06.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "Praise Aclazotz," Vito intoned. Bartolomé remained silent as Vito issued orders to the soldiers to prepare for departure. #emph[Come to me …] Amalia drew a shaky breath, telling herself the whispery voice wasn't stronger than the last time it spoke to her. One of the candles hovering at her back abruptly blew out, deepening the shadows around her, and she hoped it wasn't a portent of what was to come.
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/04-opentype/more-tables.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/components.typ": note #import "/lib/glossary.typ": tr #show: web-page-template // ## And more tables! == 更多数据表 // We've looked at all of the compulsory tables in an OpenType font; there are many other tables which can also be present. There are tables which handle vertical typesetting, and tables which allow you to position the baseline at different places for different scripts; tables which give hints on how to justify lines, or resize mathematical symbols; tables which help with hinting, and tables which contain bitmaps, vector graphics, and color font information. For more on how these tables work, it's best to read the [OpenType specification itself](https://docs.microsoft.com/en-us/typography/opentype/spec/). 我们介绍完了OpenType中所有必须的数据表,但实际应用中还可能会出现其他表。按用途分可能有:用于竖排文本;为不同的文种调整基线位置;提供关于如何对齐线条和缩放数学符号的信息;辅助提供#tr[hinting];使用#tr[bitmap]或矢量图形表示#tr[glyph];彩色字体等。关于这些数据表的工作方式,最好直接阅读OpenType规范@Microsoft.OpenTypeSpecification。 // In fact, why stop there? There's nothing to stop you defining your own table structure and adding it to your font; the font is just a database. If you want to add a `SHKS` table which contains the complete works of Shakespeare, you can do that; software which doesn't recognise the table will simply ignore it, so it'll still be a perfectly valid font. (Yes, I have tried this.) TTX will even happily dump it out for you, even if it doesn't know how to interpret it. The Graphite font rendering software, developed by SIL, uses this method to embed advanced features inside the fonts, such as automatic collision avoidance and word kerning (character kerning across a space boundary), in custom Graphite-specific tables. 我们也不用拘泥于这些已经定义好的数据表格式。事实上OpenType并不限制在字体中使用自创的数据表结构,毕竟字体就是一个数据库。即使你想在字体中加入一个叫`SHKS`的表用于存放莎士比亚的所有作品也是可以的。虽然无法识别这个表的用途的应用软件会将它忽略,但它仍然会是一个有效的字体文件(我真的试过这么做)。而 TTX 工具即使不知道如何解读,也会照常将表中的数据导出。由 SIL 开发的 Graphite 字体渲染软件就使用这种自定义数据表的方式向字体中嵌入了更多高级特性,比如自动避让和词偶距(在单词之间的空格处生效的#tr[kern])等。 // Finally, there is one more table which we haven't mentioned, but without which nothing would work: the very first table in the font, called the Offset Table, tells the system which tables are contained in the font file and where they are located within the file. If we were to look at our dummy OpenType font file in a hex editor, we would see some familiar names at the start of the file: 最后,我还想介绍一个非常重要的,甚至没有它的话字体就无法正常工作的数据表。它位于文件的开头,叫做偏移量表。它告诉系统字体文件中到底包含哪些数据表,以及每张表在文件中的位置。如果我们使用十六进制编辑器直接打开字体文件,在开头的部分就会看见很多熟悉的名字: ``` 00000000: 4f54 544f 000a 0080 0003 0020 4346 4620 OTTO....... CFF 00000010: 400e 39a4 0000 043c 0000 01de 4753 5542 @.9....<....GSUB 00000020: 0001 0000 0000 061c 0000 000a 4f53 2f32 ............OS/2 00000030: 683d 6762 0000 0110 0000 0060 636d 6170 h=gb.......`cmap 00000040: 0017 0132 0000 03d0 0000 004a 6865 6164 ...2.......Jhead 00000050: 0975 3eb0 0000 00ac 0000 0036 6868 6561 .u>........6hhea 00000060: 062f 01a9 0000 00e4 0000 0024 686d 7478 ./.........$hmtx 00000070: 06a2 00ba 0000 0628 0000 000c 6d61 7870 .......(....maxp ``` // `OTTO` is a magic string to tell us this is an OpenType font. Then there is a few bytes of bookkeeping information, followed by the name of each table, a checksum of its content, its offset within the file, and its length. So here we see that the `CFF ` table lives at offset `0x0000043c` (or byte 1084) and stretches for `0x000001de` (478) bytes long. `OTTO`是代表OpenType字体的魔术字。在几个表示字体信息的字节之后就是数据表偏移量记录。每项记录由表名、表数据的校验和、在文件中的位置以及数据长度组成。比如上面的数据显示,`CFF` 表位于 `0x0000043c`(也就是第1084个字节)的位置,长度为`0x000001de`(478)个字节。
https://github.com/platformer/typst-algorithms
https://raw.githubusercontent.com/platformer/typst-algorithms/main/examples/examples.typ
typst
MIT License
// check out the README to see all the options // for algo and code #import "@preview/algo:0.3.1": algo, i, d, comment, code #algo( title: "Fib", parameters: ("n",) )[ if $n < 0$:#i\ // use #i to indent the following lines return null#d\ // use #d to dedent the following lines if $n = 0$ or $n = 1$:#i #comment[you can also]\ return $n$#d #comment[add comments!]\ return #smallcaps("Fib")$(n-1) +$ #smallcaps("Fib")$(n-2)$ ] #v(3em) #algo( line-numbers: false, strong-keywords: false )[ if $n < 0$:#i\ return null#d\ if $n = 0$ or $n = 1$:#i\ return $n$#d\ \ let $x <- 0$\ let $y <- 1$\ for $i <- 2$ to $n-1$:#i #comment[so dynamic!]\ let $z <- x+y$\ $x <- y$\ $y <- z$#d\ \ return $x+y$ ] #v(3em) #algo( title: [ // note that title and parameters #set text(size: 15pt) // can be content #emph(smallcaps("Fib")) ], parameters: ([#math.italic("n")],), comment-prefix: [#sym.triangle.stroked.r ], comment-styles: (fill: rgb(100%, 0%, 0%)), indent-size: 15pt, indent-guides: 1pt + gray, row-gutter: 5pt, column-gutter: 5pt, inset: 5pt, stroke: 2pt + black, fill: none, )[ if $n < 0$:#i\ return null#d\ if $n = 0$ or $n = 1$:#i\ return $n$#d\ \ let $x <- 0$\ let $y <- 1$\ for $i <- 2$ to $n-1$:#i #comment[so dynamic!]\ let $z <- x+y$\ $x <- y$\ $y <- z$#d\ \ return $x+y$ ] #pagebreak() #code()[ ```py def fib(n): if n < 0: return None if n == 0 or n == 1: # this comment is return n # normal raw text return fib(n-1) + fib(n-2) ``` ] #v(3em) #code( indent-guides: 1pt + gray, row-gutter: 5pt, column-gutter: 5pt, inset: 5pt, stroke: 2pt + black, fill: none, )[ ```py def fib(n): if n < 0: return None if n == 0 or n == 1: # this comment is return n # normal raw text return fib(n-1) + fib(n-2) ``` ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/out-of-flow-in-block_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // In-flow item with size zero in the first region. #set page(height: 5cm, margin: 1cm) In-flow, zero-sized item. #block(breakable: true, stroke: 1pt, inset: 0.5cm)[ #set block(spacing: 0pt) #line(length: 0pt) #rect(height: 2cm, fill: gray) #line(length: 100%) ]
https://github.com/cadojo/correspondence
https://raw.githubusercontent.com/cadojo/correspondence/main/src/vita/src/publications.typ
typst
MIT License
#let publicationlist = state("publicationlist", ()) #let publication( organization, source, date: none, notes ) = { let content = [ #grid( columns: (1fr, 1fr), heading(level: 3, organization), align(right)[ #set text(rgb(90,90,90)) #date ] ) #if source != none { set text(rgb(90,90,90)) if type(source) == "string" { v(-0.5em) text(source) } else { v(-0.5em) text(source.join(", ")) } } #notes ] publicationlist.update(current => current + (content,)) } #let publications(header: "Publications") = { locate( loc => { let publicationlist = publicationlist.final(loc) if publicationlist.len() > 0 { heading(level: 2, text(header)) line(length: 100%, stroke: 1pt + black) publicationlist.join() } } ) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/numbering_06.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set text(lang: "jp", font: ("Linux Libertine", "Noto Serif CJK JP")) #for i in range(0, 9) { numbering("あ", i) [ and ] numbering("I.あ", i, i) [ for #i \ ] } #for i in range(0, 9) { numbering("ア", i) [ and ] numbering("I.ア", i, i) [ for #i \ ] }
https://github.com/pal03377/master-thesis
https://raw.githubusercontent.com/pal03377/master-thesis/main/thesis_template.typ
typst
MIT License
#let project( title: "", titleGerman: "", degree: "", program: "", supervisor: "", advisors: (), author: "", startDate: none, submissionDate: none, body, ) = { set document(title: title, author: author) set page( margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm), numbering: "1", number-align: center, ) let body-font = "New Computer Modern" let sans-font = "New Computer Modern Sans" set text( font: body-font, size: 12pt, lang: "en" ) show math.equation: set text(weight: 400) show heading: set block(below: 0.85em, above: 1em) show heading: set text(font: body-font) show heading: it => { v(0.5em) it v(0.5em) } set heading(numbering: "1.1") // Reference first-level headings as "chapters" - modified to also support appendices show ref: it => { let el = it.element if el != none and el.func() == heading and el.level == 1 { let n = numbering( el.numbering, ..counter(heading).at(el.location()) ) // Chapter detection if n.starts-with("Appendix") { // Remove ": " from the end n.slice(0, n.len() - 2) } else { [Chapter #n] } } else { it } } // --- Paragraphs --- set par(leading: 1em) // --- Figures --- show figure: set text(size: 0.85em) // Cite like this: [Kru23] instead of this: [1] set cite(style: "alphanumerical") // --- Table of Contents --- set page(numbering: "(i)") counter(page).update(1) outline( title: { text(font: body-font, 1.5em, weight: 700, "Contents") v(15mm) }, indent: 2em ) v(2.4fr) pagebreak() // Main body. set par(justify: true) set page(numbering: "1") counter(page).update(1) body pagebreak() bibliography("thesis.bib") }
https://github.com/Mondei1/dhge-typst-template
https://raw.githubusercontent.com/Mondei1/dhge-typst-template/master/main.typ
typst
#import "lib/intro.typ": data, tickbox, project_number, toc #import "lib/todo.typ": todo, outline-todos #import "@preview/wordometer:0.1.1": word-count, total-words #import "@preview/sourcerer:0.2.1": code #import "@preview/acrostiche:0.3.1": * #let project_title = "DEIN TITEL HIER" #let project_author = "<NAME>" // // -- General document settings -- // #set page( paper: "a4", margin: (left: 3cm, right: 2cm, top: 2.5cm, bottom: 2.5cm), ) #set document(title: project_title, author: project_author) #set heading(numbering: "1.1") #set text(font: "Times New Roman", size: 11pt, lang: "de") #set par(justify: true, leading: 14pt) #show heading: head => { set block(below: 16pt) head } #show heading.where(level: 1): it => {pagebreak(weak: true); it} #show par: p => { p set block(below: 24pt) } #set list(indent: 1cm) #align(center, heading( project_title, outlined: false, numbering: none, )) #h(2em) #stack( // Adjust your project number here (1-4) project_number(1), data("vorgelegt am", "29.04.2024"), data("von", project_author), data("Martikelnr.", "G230XXXPI"), data("DHGE Campus", "Gera"), data("Studienbereich", "Technik"), data("Studiengang", "Praktische Informatik"), data("Kurs", "PIX23"), data("Ausbildungsstätte", "Google Inc."), data("Betreuer", "/"), data("", "/") ) #set page( numbering: "I", number-align: end ) #counter(page).update(1) // // -- Table of contents -- // #heading("Inhaltsverzeichnis", numbering: none) #toc() // Format primary headings in bold. #show outline.entry.where( level: 1 ): it => { text(weight: "regular", it) } // // -- Table of figures -- // #heading("Abbildungsverzeichnis", numbering: none) #outline( title: none, target: figure.where(kind: image) .or(figure.where(kind: raw)) ) // // -- Table directory -- // #heading("Tabellenverzeichnis", numbering: none) #outline( title: none, target: figure.where(kind: table) ) // // -- List of abbreviations -- // #heading( numbering: none, "Abkürzungsverzeichnis" ) #init-acronyms(( "ERP": ("Enterprise Resource Planning"), "CRM": ("Customer Relationship Management"), "ADB": ("Android Debug Bridge"), "SDK": ("Software Development Kit"), "API": ("Application Program Interface"), "DI API": ("Data Interface Application Program Interface"), "B1": ("Business One"), )) #print-index( title: "", sorted: "up", outlined: false, delimiter: "" ) // Reset page counter and change format to numeric. #set page(numbering: "1") #counter(page).update(1) // // -- Content -- // = Einleitung == Vorstellung des Praxispartner [...] SAP #acr("B1") ist eine #acr("ERP") Software und richtet sich primär an den Mittelstand. #acr("ERP") beschreibt Software welche den gesamten Geschäftsprozess eines Unternehmens digital abbildet und unterstützt. == Überblick Es ist wichtig im Vorhinein zu klären wie die Struktur. Test: #figure( caption: [Auszug aus der `MainActivity.cs`], kind: raw, code( number-align: right, lang: "C#", ```cs protected override void OnActivityResult([GeneratedEnum] int requestCode, Result resultCode, Intent intent) { if (resultCode != Result.Ok) { Log.Warning($"Received non-ok result. (request code: {resultCode}"); return; } // Check if we received an image result. if (requestCode == CAMERA_REQUEST_CODE) { Bitmap bmp = (Bitmap)intent.Extras.Get("data"); Java.IO.File file = Java.IO.File.CreateTempFile("photo", ".png", CacheDir); FileStream stream = System.IO.File.OpenWrite(file.AbsolutePath); bmp.Compress(Bitmap.CompressFormat.Png, 0, stream); stream.Close(); // [...] } base.OnActivityResult(requestCode, resultCode, intent); } ```) ) == Problemstellung #todo("Konkrete Probleme finden die durch diese Implementierung behoben werden könnten.") == Zielstellung Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. @Ritchie.1988 = Analyse == Ist-Zustand === Mobile Anwendung === Web Services === Interaktion == Soll-Zustand == Handlungsbedarf Nach voriger Auswertung ergeben sich grob folgende Anforderungen die bearbeitet werden müssen: - Ananas - Apfel - Birne = Technische Struktur #figure( table( columns: (auto, 1fr, 1fr), inset: 9pt, align: left, [*Art*], [*Vorteile*], [*Nachteile*], "Art 1", list(indent: 0cm, [*Lorem!* \ Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy.], [*Stet clita kasd* \ At vero eos et accusam et justo duo dolores et ea rebum.]), list(indent: 0cm, [Gibt's nicht]) ), caption: [Übersicht der Vor- und Nachteile], ) <kinds> == Lorem ipsum == Dolor sit = Planung = Umsetzung = Finalisierung == Unit-Tests == Deployment // // -- Bibliography -- // #set page(numbering: "A") #counter(page).update(1) #bibliography( "sources.bib", title: "Literaturverzeichnis", style: "csl/duale-hochschule-gera-eisenach.csl" ) // // -- Declaration of honour -- // #set page(numbering: none) #align(center, heading("Ehrenwörtliche Erklärung", numbering: none, outlined: false)) #h(1em) Ich erkläre hiermit ehrenwörtlich, #enum( tight: false, spacing: 1em, [dass ich meine Projektarbeit/Studienarbeit/Bachelorarbeit mit dem Thema: \ *#project_title* \ ohne fremde Hilfe angefertigt habe,], [dass ich die Übernahme wörtlicher Zitate aus der Literatur sowie die Verwendung der Gedanken anderer Autoren an den entsprechenden Stellen innerhalb der Arbeit gekennzeichnet habe und], [dass ich meine Projektarbeit/Studienarbeit/Bachelorarbeit bei keiner anderen Prüfung vorgelegt habe.] ) \ Ich bin mir bewusst, dass eine falsche Erklärung rechtliche Folgen haben wird. #pad( top: 1.5cm, grid( columns: (1fr, 1fr), rows: (auto), gutter: 3pt, stack( spacing: 0.5em, line(length: 80%), "Ort, Datum" ), stack( spacing: 0.5em, line(length: 80%), "Unterschrift" ), ) )
https://github.com/Relacibo/typst-as-lib
https://raw.githubusercontent.com/Relacibo/typst-as-lib/main/examples/templates/function.typ
typst
MIT License
#let alert(body, fill: red) = { set text(white) set align(center) rect( fill: fill, inset: 8pt, radius: 4pt, [*Warning:\ #body*], ) }
https://github.com/optimizerfeb/MathScience
https://raw.githubusercontent.com/optimizerfeb/MathScience/main/재미있는 수학 증명.typ
typst
#set text(font: "KoPubBatang_Pro") #let to = $arrow.r$ #let sim = $tilde.eq$ #align(center, text(17pt)[ *어떤 명제의 흥미로운 증명법* ]) #align(right, text(10pt)[ 한남대학교 수학과 20172581 김남훈 ]) = 1. 소개 === 정리. $T$ 를 위상공간, $p in T$ 라 하자. $T$ 의 $2$ 차 호모토피 군 $pi_2(T, p)$ 는 가환군이다. === 증명. #figure( stack( dir: ltr, rect(width: 30pt, height: 60pt, align(horizon, $f$)), rect(width: 30pt, height: 60pt, align(horizon, $g$)), align(horizon, $space to space$), rect(width: 60pt, height: 60pt, fill: black, align(horizon, stack( dir: ltr, rect(width: 20pt, height: 40pt, fill: white, $f$), $space$, rect(width: 20pt, height: 40pt, fill: white, $g$) ) ) ), align(horizon, $space to space$), rect(width: 60pt, height: 60pt, fill: black, align(horizon, stack( dir: ltr, rect(width: 20pt, height: 40pt, fill:white, $g$), $space$, rect(width: 20pt, height: 40pt, fill:white, $f$) ) ) ), align(horizon, $space to space$), rect(width: 30pt, height: 60pt, align(horizon, $g$)), rect(width: 30pt, height: 60pt, align(horizon, $f$)), align(bottom, $space qed$) ) ) = 2. 기본 개념 위 증명에 대해 설명하기 전에, 먼저 이해하기 위해 필요한 내용들을 정리해보자. === 정의 1. 곱 공간(Product Space)과 곱 위상(Product Topology) 위상공간 $(T, tau_T)$ 와 $(S, tau_s)$ 가 주어졌으며 $f, g$ 가 각각 $T$ 에서 $S$ 로의 연속함수라고 하자. 그리고 $ cal(B)_(T times S) &= { G times H bar G in tau_T and H in tau_H }\ tau_(T times S) &= { union.big F bar F in cal(B) } $ 로 놓으면 $tau_(T times S)$ 는 $T times S$ 위의 위상이 되며, 이것을 곱 위상이라고 한다. $(T times S, tau_(T times S))$ 를 $T$ 와 $S$ 의 곱 공간이라 한다. === 정의 2. 호모토피(Homotopy) 위상공간 $T, S$ 에 대해 $f, g$ 가 $T$ 에서 $S$ 로의 연속함수라고 하자. 연속함수 $H : T times [0, 1] to S$ 가 다음을 만족하면 $H$ 를 $f$ 와 $g$ 사이의 *호모토피* 라 한다. $ H(t, 0) &= f(t)\ H(t, 1) &= g(t) $ $f$ 와 $g$ 사이의 호모토피가 존재한다면 $f$ 와 $g$ 는 *호모토픽(homotopic)* 하다고 하고 $f sim g$ 로 나타낸다. === 정리 1. 호모토피의 동치성 호모토피 관계 $sim$ 는 동치관계이다. === 증명. $f, g, h$ 를 $T$ 에서 $S$ 로의 연속함수라고 하자. $H: T times [0, 1] to S$ 를 $h(t, r) = f(f)$ 로 정의하면 $h$ 는 $f$ 와 $f$ 사이의 호모토피이므로 $sim$ 는 반사적이다. $H$ 가 $f$ 와 $g$ 사이의 호모토피라면, 함수 $H' : T times [0, 1] to S$ 를 $H'(t, r) = H(t, 1 - r)$ 로 정의하면 $H'$ 는 $g$ 와 $f$ 사이의 호모토피이다. 따라서 $sim$ 는 대칭적이다. $H_1$ 이 $f$ 와 $g$ 사이의 호모토피, $H_2$ 이 $g$ 와 $h$ 사이의 호모토피라고 하자. $H : T times [0, 1] to S$ 을 다음과 같이 정의하자. $ H(t, r) = cases( H_1(t, 2r) &"if"& r lt.eq 1 / 2\ H_2(t, 2r - 1) &"if"& r > 1 / 2 ) $ 그러면 $H$ 는 $f$ 와 $h$ 사이의 호모토피이다. 따라서, $sim$ 는 추이적이다. $sim$ 는 반사적, 대칭적, 추이적이므로 동치관계이다. === 정의 3. 경로(Path)와 경로곱(Path Product) 위상공간 $T$ 와 $x, y in T$ 에 대해, 연속함수 $f : [0, 1] to T$ 가 $f(0) = x, f(1) = y$ 라면 $f$ 를 $x$ 에서 $y$ 로의 경로라고 한다. $x, y, z in T$ 이고 $f$ 가 $x$ 에서 $y$ 로의 경로, $g$ 가 $y$ 에서 $z$ 로의 경로라고 하자. 그리고 $h: [0, 1] to T$ 을 다음과 같이 정의하자. $ h(t) = cases( f(2t) &"if"& t lt.eq 1 / 2\ g(2t - 1) &"if"& t > 1 / 2 ) $ 그러면 $h$ 는 $f$ 와 $g$ 의 경로곱이라 하고 $f star g$ 로 나타낸다. === 정리. 경로곱의 호모토피 위상공간 $T$ 와 $x, y, z in T$ 에 대해 $f_1, f_2$ 가 $x$ 에서 $y$ 로의 경로, $g_1, g_2$ 가 $y$ 에서 $z$ 로의 경로라고 하자. $f_1 sim f_2$ 이고, $g_1 sim g_2$ 이면면 $f_1 star g_1 sim f_2 star g_2$ 이다. === 증명. $H_f$ 가 $f_1$ 과 $f_2$ 사이의 호모토피, $H_g$ 가 $g_1$ 과 $g_2$ 사이의 호모토피라 하고 $H : [0, 1] times [0, 1] to S$ 을 다음과 같이 정의하자. $ H(t, r) = cases( H_f(2t, r) &"if"& r lt.eq 1 / 2\ H_g(2t - 1, r) &"if"& r > 1 / 2 ) $ 그러면 $H$ 는 $f_1 star g_1$ 과 $g_1 star g_2$ 사이의 호모토피이다. === 정리. 경로곱 연산의 결합 법칙 위상공간 $T$ 와 $x, y, z, w in T$ 에 대해 $f$ 가 $x$ 에서 $y$ 로의 경로, $g$ 가 $y$ 에서 $z$ 로의 경로, $h$ 가 $z$ 에서 $w$ 로의 경로라고 하자. 그러면 $f star (g star h) sim (f star g) star h$ 이다. === 증명. 연속함수 $H : [0, 1] times [0, 1] to T$ 를 다음과 같이 정의하자. $ H(t, r) = cases( f[2 t - 4 t r] &"if"& t - 4r gt.eq - 1\ g[4 t - r + 1 / 4] &"if"& -2 < t - 4r < - 1\ h[1 / 4 t - 1 / 4 r] &"if"& -2 < t - 4r < - 1 ) $ 함수의 값의 변화를 그림으로 직관적으로 살펴보면 아래와 같다. #figure( stack(dir: ltr, align(horizon, $H : space$), stack(dir:ttb, place(dx: -65pt, dy: -11pt, $x$), place(dx: -0pt, dy: -11pt, $y$), place(dx: 30pt, dy: -11pt, $z$), place(dx: 57.5pt, dy: -11pt, $w$), square(size: 120pt, stroke: black, stack( place(dx: 57.5pt, dy: -5pt, line(end: ( -30pt, 120pt), stroke : (dash: "dotted"))), place(dx: 87.5pt, dy: -5pt, line(end: ( -30pt, 120pt), stroke : (dash: "dotted"))), place(dx: 15pt, dy: 50pt, $f$), place(dx: 55pt, dy: 50pt, $g$), place(dx: 90pt, dy: 50pt, $h$), place(dx: -32.5pt, dy: -5pt, $(0, 0)$), place(dx: 117.5pt, dy: -5pt, $(1, 0)$), place(dx: -32.5pt, dy: 105pt, $(0, 1)$), place(dx: 117.5pt, dy: 105pt, $(1, 1)$) ) ), place(dx: -65pt, dy: 1pt, $x$), place(dx: -30pt, dy: 1pt, $y$), place(dx: 0pt, dy: 1pt, $z$), place(dx: 57.5pt, dy: 1pt, $w$), ) ) ) 그림에서 알 수 있듯, $H(t, 0) = [f star (g star h)](t)$ 이고 $H(t, 1) = [(f star g) star h](t)$ 이다. 따라서, $H$ 는 $f star (g star h)$ 와 $(f star g) star h$ 사이의 호모토피이다. === 정리 4. 폐경로의 성질 이제 $T$ 를 위상공간, $x in T$ 이라 하자. $e$ 를 모든 $t in [0, 1]$ 에 대해 $e(t) = x$ $x$ 에서 $x$ 로의 경로라 하고, $x$ 에서 $x$ 로의 경로 $f$ 에 대해 $f'$ 를 모든 $t in [0, 1]$ 에 대해 $f'(t) = f(1 - t)$ 인 $x$ 에서 $x$ 로의 경로라 하자. 그러면 $x$ 에서 $x$ 로의 임의의 경로 $f$ 에 대해 다음이 성립한다. + $f star e sim e star f sim f$ + $f star f' sim f' star f sim e$ === 증명. $H_1, H_2$ 를 다음과 같이 정의하자.
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/docs/tutorial/4-template.md
markdown
Apache License 2.0
--- description: Typst's tutorial. --- # Making a Template In the previous three chapters of this tutorial, you have learned how to write a document in Typst, apply basic styles, and customize its appearance in-depth to comply with a publisher's style guide. Because the paper you wrote in the previous chapter was a tremendous success, you have been asked to write a follow-up article for the same conference. This time, you want to take the style you created in the previous chapter and turn it into a reusable template. In this chapter you will learn how to create a template that you and your team can use with just one show rule. Let's get started! ## A toy template { #toy-template } In Typst, templates are functions in which you can wrap your whole document. To learn how to do that, let's first review how to write your very own functions. They can do anything you want them to, so why not go a bit crazy? ```example #let amazed(term) = box[✨ #term ✨] You are #amazed[beautiful]! ``` This function takes a single argument, `term`, and returns a content block with the `term` surrounded by sparkles. We also put the whole thing in a box so that the term we are amazed by cannot be separated from its sparkles by a line break. Many functions that come with Typst have optional named parameters. Our functions can also have them. Let's add a parameter to our function that lets us choose the color of the text. We need to provide a default color in case the parameter isn't given. ```example #let amazed(term, color: blue) = { text(color, box[✨ #term ✨]) } You are #amazed[beautiful]! I am #amazed(color: purple)[amazed]! ``` Templates now work by using an "everything" show rule that applies the custom function to our whole document. Let's do that with our `amazed` function. ```example >>> #let amazed(term, color: blue) = { >>> text(color, box[✨ #term ✨]) >>> } #show: amazed I choose to focus on the good in my life and let go of any negative thoughts or beliefs. In fact, I am amazing! ``` Our whole document will now be passed to the `amazed` function, as if we wrapped it around it. This is not especially useful with this particular function, but when combined with set rules and named arguments, it can be very powerful. ## Embedding set and show rules { #set-and-show-rules } To apply some set and show rules to our template, we can use `set` and `show` within a content block in our function and then insert the document into that content block. ```example #let template(doc) = [ #set text(font: "Inria Serif") #show "something cool": [Typst] #doc ] #show: template I am learning something cool today. It's going great so far! ``` Just like we already discovered in the previous chapter, set rules will apply to everything within their content block. Since the everything show rule passes our whole document to the `template` function, the text set rule and string show rule in our template will apply to the whole document. Let's use this knowledge to create a template that reproduces the body style of the paper we wrote in the previous chapter. ```example #let conf(title, doc) = { set page( paper: "us-letter", >>> margin: auto, header: align( right + horizon, title ), <<< ... ) set par(justify: true) set text( font: "Linux Libertine", size: 11pt, ) // Heading show rules. <<< ... >>> show heading.where( >>> level: 1 >>> ): it => block( >>> align(center, >>> text( >>> 13pt, >>> weight: "regular", >>> smallcaps(it.body), >>> ) >>> ), >>> ) >>> show heading.where( >>> level: 2 >>> ): it => box( >>> text( >>> 11pt, >>> weight: "regular", >>> style: "italic", >>> it.body + [.], >>> ) >>> ) columns(2, doc) } #show: doc => conf( [Paper title], doc, ) = Introduction #lorem(90) <<< ... >>> == Motivation >>> #lorem(140) >>> >>> == Problem Statement >>> #lorem(50) >>> >>> = Related Work >>> #lorem(200) ``` We copy-pasted most of that code from the previous chapter. The only two differences are that we wrapped everything in the function `conf` and are calling the columns function directly on the `doc` argument as it already contains the content of the document. Moreover, we used a curly-braced code block instead of a content block. This way, we don't need to prefix all set rules and function calls with a `#`. In exchange, we cannot write markup directly into it anymore. Also note where the title comes from: We previously had it inside of a variable. Now, we are receiving it as the first parameter of the template function. Thus, we must specify it in the show rule where we call the template. ## Templates with named arguments { #named-arguments } Our paper in the previous chapter had a title and an author list. Let's add these things to our template. In addition to the title, we want our template to accept a list of authors with their affiliations and the paper's abstract. To keep things readable, we'll add those as named arguments. In the end, we want it to work like this: ```typ #show: doc => conf( title: [Towards Improved Modelling], authors: ( ( name: "<NAME>", affiliation: "Artos Institute", email: "<EMAIL>", ), ( name: "<NAME>", affiliation: "Honduras State", email: "<EMAIL>", ), ), abstract: lorem(80), doc, ) ... ``` Let's build this new template function. First, we add a default value to the `title` argument. This way, we can call the template without specifying a title. We also add the named `authors` and `abstract` parameters with empty defaults. Next, we copy the code that generates title, abstract and authors from the previous chapter into the template, replacing the fixed details with the parameters. The new `authors` parameter expects an [array]($array) of [dictionaries]($dictionary) with the keys `name`, `affiliation` and `email`. Because we can have an arbitrary number of authors, we dynamically determine if we need one, two or three columns for the author list. First, we determine the number of authors using the [`.len()`]($array.len) method on the `authors` array. Then, we set the number of columns as the minimum of this count and three, so that we never create more than three columns. If there are more than three authors, a new row will be inserted instead. For this purpose, we have also added a `row-gutter` parameter to the `grid` function. Otherwise, the rows would be too close together. To extract the details about the authors from the dictionary, we use the [field access syntax]($scripting/#fields). We still have to provide an argument to the grid for each author: Here is where the array's [`map` method]($array.map) comes in handy. It takes a function as an argument that gets called with each item of the array. We pass it a function that formats the details for each author and returns a new array containing content values. We've now got one array of values that we'd like to use as multiple arguments for the grid. We can do that by using the [`spread` operator]($arguments). It takes an array and applies each of its items as a separate argument to the function. The resulting template function looks like this: ```typ #let conf( title: none, authors: (), abstract: [], doc, ) = { // Set and show rules from before. <<< ... set align(center) text(17pt, title) let count = authors.len() let ncols = calc.min(count, 3) grid( columns: (1fr,) * ncols, row-gutter: 24pt, ..authors.map(author => [ #author.name \ #author.affiliation \ #link("mailto:" + author.email) ]), ) par(justify: false)[ *Abstract* \ #abstract ] set align(left) columns(2, doc) } ``` ## A separate file { #separate-file } Most of the time, a template is specified in a different file and then imported into the document. This way, the main file you write in is kept clutter free and your template is easily reused. Create a new text file in the file panel by clicking the plus button and name it `conf.typ`. Move the `conf` function definition inside of that new file. Now you can access it from your main file by adding an import before the show rule. Specify the path of the file between the `{import}` keyword and a colon, then name the function that you want to import. ```example:single >>> #let conf( >>> title: none, >>> authors: (), >>> abstract: [], >>> doc, >>> ) = { >>> set text(font: "Linux Libertine", 11pt) >>> set par(justify: true) >>> set page( >>> "us-letter", >>> margin: auto, >>> header: align( >>> right + horizon, >>> title >>> ), >>> numbering: "1", >>> ) >>> >>> show heading.where( >>> level: 1 >>> ): it => block( >>> align(center, >>> text( >>> 13pt, >>> weight: "regular", >>> smallcaps(it.body), >>> ) >>> ), >>> ) >>> show heading.where( >>> level: 2 >>> ): it => box( >>> text( >>> 11pt, >>> weight: "regular", >>> style: "italic", >>> it.body + [.], >>> ) >>> ) >>> >>> set align(center) >>> text(17pt, title) >>> >>> let count = calc.min(authors.len(), 3) >>> grid( >>> columns: (1fr,) * count, >>> row-gutter: 24pt, >>> ..authors.map(author => [ >>> #author.name \ >>> #author.affiliation \ >>> #link("mailto:" + author.email) >>> ]), >>> ) >>> >>> par(justify: false)[ >>> *Abstract* \ >>> #abstract >>> ] >>> >>> set align(left) >>> columns(2, doc) >>>} <<< #import "conf.typ": conf #show: doc => conf( title: [ Towards Improved Modelling ], authors: ( ( name: "<NAME>", affiliation: "Artos Institute", email: "<EMAIL>", ), ( name: "<NAME>", affiliation: "Honduras State", email: "<EMAIL>", ), ), abstract: lorem(80), doc, ) = Introduction #lorem(90) == Motivation #lorem(140) == Problem Statement #lorem(50) = Related Work #lorem(200) ``` We have now converted the conference paper into a reusable template for that conference! Why not share it on [Typst's Discord server](https://discord.gg/2uDybryKPe) so that others can use it too? ## Review Congratulations, you have completed Typst's Tutorial! In this section, you have learned how to define your own functions and how to create and apply templates that define reusable document styles. You've made it far and learned a lot. You can now use Typst to write your own documents and share them with others. We are still a super young project and are looking for feedback. If you have any questions, suggestions or you found a bug, please let us know on [Typst's Discord server](https://discord.gg/2uDybryKPe), on our [contact form](https://typst.app/contact), or on [social media.](https://twitter.com/typstapp) So what are you waiting for? [Sign up](https://typst.app) and write something!
https://github.com/augustebaum/epfl-thesis-typst
https://raw.githubusercontent.com/augustebaum/epfl-thesis-typst/main/example/head/acknowledgements.typ
typst
MIT License
#import "@preview/scholarly-epfl-thesis:0.1.1": fill-line = Acknowledgements #lorem(100) #lorem(50) #parbreak() #fill-line([_Lausanne, 12 Mars 2011_], [<NAME>.])
https://github.com/actsasflinn/typst-rb
https://raw.githubusercontent.com/actsasflinn/typst-rb/main/test/template_with_font_and_icon/main.typ
typst
Apache License 2.0
#import "template.typ": * #show: template.with() #lorem(50) #image("monkey.svg")
https://github.com/k0tran/cont_labs
https://raw.githubusercontent.com/k0tran/cont_labs/master/reports/lab1.typ
typst
#import "template.typ": * #show: lab.with(n: 1) = Настройка хоста В качестве хоста будет использоваться Manjaro: #pic(img: "lab1/neofetch.png")[Запуск neofetch на хосте] == VirtualBox Для установки VirtualBox будет использован пакетный менеджер pacman: #pic(img: "lab1/install_vbox.png")[Установка VirtualBox] == Vagrant #pic(img: "lab1/install_vagrant.png")[Установка Vagrant] Так же следует установить плагин для гостевых дополнений: #pic(img: "lab1/install_vagrant_vbguest.png")[Установка гостевых дополнений Vagrant] = Работа с Vagrant #pic(img: "lab1/vagrant_init.png")[Инициализации директории для работы с Vagrant] == Первый запуск Для того что бы `vagrant up` мог сам скачать виртульную машину первый запуск производится с использованием proxychains: #pic(img: "lab1/vagrant_first_up.png")[Первый запуск vagrant up (прерван)] Можно убедится, что запуск машины успешно прерван: #pic(img: "lab1/vagrant_first_status.png")[vagrant status] Последующие запуски будут производиться без proxychains. Из-за того, что используется VirtualBox 7.10, в консоль будет выведено следующее предупреждение: ``` $ vagrant up ... Installing Virtualbox Guest Additions 7.0.10 - guest version is 6.0.0 ... An error occurred during installation of VirtualBox Guest Additions 7.0.10. Some functionality may not work as intended. In most cases it is OK that the "Window System drivers" installation failed. ... ``` Остановить и удалить машину можно при помощи vagrant destroy: #pic(img: "lab1/vagrant_destroy.png")[vagrant destroy] == Настройка Vagrantfile Для выполнения условий лабораторной следует добавить следующие строчки в Vagrantfile: ```rb ... config.vm.hostname = "ubuntu-docker" ... config.vm.provider "virtualbox" do |vb| vb.memory = "2048" vb.cpus = 2 vb.check_guest_additions = false end ``` Так же будет полезно отключить обновления: ```rb ... config.vm.box_check_update = false ... ``` И включить аппаратную виртуализацию: ```rb vb.customize ["modifyvm", :id, "--nested-hw-virt", "on"] ``` Создание снимка VM: #pic(img: "lab1/vagrant_snap_initial.png")[Создание снимка VM] Подключение к виртуальной машине по ssh: #pic(img: "lab1/vagrant_ssh.png")[Подключение по ssh] == Установка Docker Engine Необходимо добавить репозиторий докера: ```shell # Add Docker's official GPG key: sudo apt-get update sudo apt-get install ca-certificates curl gnupg sudo install -m 0755 -d /etc/apt/keyrings curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg sudo chmod a+r /etc/apt/keyrings/docker.gpg # Add the repository to Apt sources: echo \ "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \ "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \ sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt-get update ``` Установка докера (пакетов): ```shell sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ``` Проверка работоспособности: #pic(img: "lab1/ubuntu_docker_hw.png")[Docker hello-world] == Создание образа ubuntudocker.box Упаковка и загрузка в локальный репозиторий: #pic(img: "lab1/vagrant_pack_and_box.png")[vagrant package и vagrant box] == Работа со снимками Создание новой машины: #pic(img: "lab1/ubuntu_init.png")[Создание новой машины] Создание снимка виртуальной машины: #pic(img: "lab1/ubuntu_snap.png")[Создание снимка default] В качестве примера изменения поставим zig: #pic(img: "lab1/ubuntu_zig.png")[Создание снимка default] Восстанавливаем снимок default: #pic(img: "lab1/ubuntu_restore.png")[Восстановление снимка] Проверяем, что zig не установлен в системе: #pic(img: "lab1/ubuntu_nozig.png")[Проверка успешного восстановления]
https://github.com/JinBridger/chicv-cn
https://raw.githubusercontent.com/JinBridger/chicv-cn/main/template/cv.typ
typst
#show heading: set text(font: ("Linux Biolinum O", "Noto Serif CJK SC")) #set text(font: ("Noto Serif CJK SC"), lang: "zh") // #set page("us-letter") #show link: underline // Uncomment the following lines to adjust the size of text // The recommend resume text size is from `10pt` to `12pt` #set text( size: 10pt, ) // Feel free to change the margin below to best fit your own CV #set page( margin: (x: 0.9cm, y: 1.5cm), ) // For more customizable options, please refer to official reference: https://typst.app/docs/reference/ #set par(justify: true) #let chiline() = {v(-3pt); line(length: 100%); v(-5pt)} = 王小明 <EMAIL> | (+86) 12345678900 | #link("https://example.com")[example.com] == 教育经历 #chiline() #link("https://typst.app/")[*#lorem(2)*] #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(10) *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(10) == 工作经历 #chiline() *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(20) - #lorem(30) - #lorem(40) *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(20) - #lorem(30) - #lorem(40) == 项目经验 #chiline() *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(20) - #lorem(30) - #lorem(40) *#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \ #lorem(5) #h(1fr) #lorem(2) \ - #lorem(20) - #lorem(30) - #lorem(40)
https://github.com/Manato1fg/My-Typst-Template
https://raw.githubusercontent.com/Manato1fg/My-Typst-Template/main/example.typ
typst
MIT License
#import "template.typ": * #let writeDate = datetime( year: 2024, month: 2, day: 6 ) #show: report.with( title: "Typst 入門", //class: "計数工学実験第二", date: writeDate, author: "Manato1fg", affiliation: "東京大学工学部計数工学科システム情報コース 3年" ) = はじめに <chap> 素敵な文章.これはとても素敵な文章ですよね. == 節 節もこのように作成できます. == フォントの切り替え ` set text( font: ( "Times New Roman", "Yonaga Old Mincho" ), size: 12pt ) ` `template.typ`で上記のように設定しておくと英語の場合はTimes New Roman,日本語の場合は夜永オールド明朝で表示されます. == 数式 数式は次のようになります. $ integral_(-oo)^(oo) exp(-a x^2) = sqrt(pi/a) $ あるいは$display(lim_(x -> 0) sin(x) / x = 1)$のようにインラインで記述することもできます. インラインで記述する場合は`$...$`で囲み,ブロックレベルにする場合は`$ ... $`で囲みます. == 脚注 脚注は`#footnote("")`と設定します#footnote("例えばこのようにね")<fn1>.名前を付けられるので@fn1 と参照することもできます. = 章 章は参照することもできます.`@chap`$->$@chap == 定義・定理・系 定義や定理は#link("https://github.com/sahasatvik/typst-theorems")[こちら]をコピペしました. #definition[円周率とは,円の直径に対する円周の長さの比率のことである.これを特別な数字として$pi$と表す.] #theorem("Euler")[ 平方数の逆数の和について以下が成り立つ. $ sum_(n=1)^(oo) 1/n^2 = pi^2/6 $ <eq:Euler> ] @eq:Euler はオイラーの公式として知られている.定義と定理のカウンターは別々にしています. #definition[Maxwell方程式とは以下の四式のことを指す. $ div vb(E) = rho/epsilon_0 $ $ curl vb(E) = -pdv(vb(B), t) $ <eq:E> $ curl vb(B) = mu_0 (vb(j) + epsilon_0 pdv(vb(E), t)) $ <eq:B> $ div vb(B) = 0 $ ]<def:Maxwell> #theorem[ 真空中では電磁波は波として振る舞う. ]<thm:EMWave> 証明の前に以下のベクトル解析の公式を証明しておこう. #lemma[ なめらかなベクトル場$vb(A) in bb(R^3)$について以下が成り立つ. $ curl curl A = grad(div A) - nabla^2 A $ ]<lem:vec> #proof[ \ $vb(A) = (A_x, A_y, A_z)$ について左辺の第一成分だけ計算してみよう. #notag[$ curl A := vec(pdv(A_z, y) - pdv(A_y, z), pdv(A_x, z) - pdv(A_z, x), pdv(A_y, x) - pdv(A_x, y) ) $] であるから, #notag[ $ curl curl A|_x &= pdv(, y)(pdv(A_y, x) - pdv(A_x, y)) - pdv(, z)(pdv(A_x, z) - pdv(A_z, x)) \ &= pdv(, x)(pdv(A_x, x) + pdv(A_y, y) + pdv(A_z, z)) - (pdv(, x, 2) + pdv(, y, 2) + pdv(, z, 2))A_x $ ] を得る.\ よって他の各成分についても同様に計算することで証明することができる. ] では@thm:EMWave を示してみよう. #proof[ \ 真空中では@def:Maxwell において$rho = 0, vb(j) = vb(0)$としてよい.@eq:E で両辺のrotを計算する.\ 左辺は@lem:vec より, $ curl curl vb(E) &= grad(div vb(E)) - nabla^2 vb(E) \ &= -nabla^2 vb(E) $<eq:7> 右辺は $ -curl pdv(vb(B), t) &= pdv(, t)(curl vb(B)) \ &= -mu_0 epsilon_0 pdv(vb(E), t, 2) $<eq:8> である. よって,@eq:7, @eq:8 より, $ nabla^2 vb(E) = mu_0 epsilon_0 pdv(vb(E), t, 2) $ を得る.これは波動方程式であり,その速さは$display(c = 1 / sqrt(mu_0 epsilon_0))$である.$vb(B)$についても同様の計算で速さ$c$で進む波であると分かる. ] #definition[ $display(c = 1 / sqrt(mu_0 epsilon_0))$ を光速と呼ぶ. ] #remark[ 光速は現在では$299,792,458$ m/sと定義される物理定数である. ]
https://github.com/sses7757/sustech-graduated-thesis
https://raw.githubusercontent.com/sses7757/sustech-graduated-thesis/main/README.md
markdown
Apache License 2.0
# 南方科技大学研究生学位论文 sustech-graduated-thesis 基于[南京大学毕业论文Typst模板](https://github.com/nju-lug/modern-nju-thesis)修改的南方科技大学研究生学位论文 Typst 模板。 ## 特点 - 初步融合了[equate](https://typst.app/universe/package/equate)和[i-figured](https://typst.app/universe/package/i-figured)的公式编号,并提供了一种更方便的公式子编号逻辑。 - 提供了`#notation`用以自动管理术语,具体使用参见`example.typ`的第1.2节。 - 提供了自动在行内公式两端添加空格的功能,该功能会自动避免在符号两端添加空格。具体使用参见`example.typ`的第1.4节。 ## 下载 进入[Release界面](https://github.com/sses7757/sustech-graduated-thesis/tags),选择最新(最上方)的Release Tag进入(比如[v0.1.5](https://github.com/sses7757/sustech-graduated-thesis/releases/tag/v0.1.5)),选择Assets中的`sustech-graduated-thesis.zip`下载解压即可。 ## 使用 该模板基于[南京大学毕业论文Typst模板](https://github.com/nju-lug/modern-nju-thesis)修改,并未修改基本使用逻辑,因此模板的使用请参见[南京大学毕业论文Typst模板](https://github.com/nju-lug/modern-nju-thesis)。 ## License This project is licensed under the Apache License Version 2.0. This project contains codes originated from https://github.com/nju-lug/modern-nju-thesis, https://github.com/RubixDev/typst-i-figured, and https://github.com/EpicEricEE/typst-plugins/tree/master/equate, which are of MIT license.
https://github.com/Error-418-SWE/Documenti
https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/3%20-%20PB/Documentazione%20esterna/Verbali/24-03-22/24-03-22.typ
typst
#import "/template.typ": * #show: project.with( date: "22/03/24", subTitle: "Aggiornamento sullo stato dei lavori", docType: "verbale", authors: ( "<NAME>", ), reviewers: ( "<NAME>", ), missingMembers: ( "<NAME>", ), externalParticipants : ( (name: "<NAME>", role: "Referente aziendale"), (name: "<NAME>", role: "Referente aziendale"), ), timeStart: "16:00", timeEnd: "16:30", location: "Zoom", ); = Ordine del giorno - Presentazione MVP; - Presentazione dei pattern per la ricerca; - Lista dei bug; - Pianificazione meeting futuri. == Presentazione MVP Sono state presentate al Proponente le funzionalità dell'MVP sviluppate dall'ultimo incontro, in particolare: - configurazione dell'ambiente a partire da file SVG; - caricamento da database della struttura e organizzazione delle zone nell'ambiente; - ridimensionamento del piano. - spostamento zone tramite _drag and drop_; - spostamento prodotti tra bin tramite _drag and drop_; - ispezione bin tramite doppio click; - ispezione zone tramite doppio click; - movimento della camera mediante tastiera (frecce direzionali o tasti W, A, S, D). Il Proponente è risultato soddisfatto delle funzionalità implementate. Sono state inoltre illustrate le funzionalità che verranno implementate entro il prossimo incontro: - *possibilità di muoversi all'interno dell'ambiente tramite tastiera durante il dragging di un prodotto*: se l'utente vuole spostare un bin in una zona non presente nell'inquadratura, potrà muovere la camera utilizzando la tastiera mentre mantiene il prodotto ancorato al cursore. Il Proponente approva questa scelta; - *collocamento di un prodotto dalla lista dei non collocati all'interno di un bin vuoto*: risulta difficile implementare il _drag and drop_ poiché ci si deve spostare da un elemento di UI all'ambiente Three.js. Il Proponente espone la possibilità di implementare questa funzionalità all'interno del pannello di visualizzazione dei dettagli di un bin. Aprendo il pannello relativo ad un bin vuoto si può dare la possibilità di aggiungere un prodotto dalla lista tramite un tasto o un elemento simile. == Presentazione dei pattern per la ricerca Vengono illustrati al Proponente i pattern Factory e Strategy utilizzati per implementare la ricerca di prodotti e zone. == Lista dei bug Si concorda con il Proponente che nei prossimi giorni il gruppo verrà aggiornato sulla struttura della lista di bug da consegnare a termine del progetto, come richiesto dal capitolato. == Pianificazione meeting futuri Viene fissato il prossimo incontro per martedì 26/03/2024 ore 15:00, durante il quale verrà richiesta l'approvazione del prodotto come MVP.
https://github.com/TomVer99/Typst-checklist-template
https://raw.githubusercontent.com/TomVer99/Typst-checklist-template/main/documentation/manual.typ
typst
MIT License
#import "@preview/mantys:0.1.4": * #import "@preview/codly:1.0.0": * #show: mantys.with( name: "aero-check", title: [aero-check checklist template], // subtitle: [An unofficial template for FHICT document generation.], authors: "TomVer99", url: "https://github.com/TomVer99/Typst-checklist-template", version: "0.1.1", date: datetime.today(), abstract: [ This template allows you to easily create checklists in the style of aviation checklists. ], ) #show: codly-init.with() #codly( languages: ( rust: (name: "Rust"), rs: (name: "Rust"), cmake: (name: "CMake"), cpp: (name: "C++"), c: (name: "C"), py: (name: "Python"), java: (name: "Java"), js: (name: "JavaScript"), sh: (name: "Shell"), bash: (name: "Bash"), json: (name: "JSON"), xml: (name: "XML"), yaml: (name: "YAML"), typst: (name: "Typst"), ), number-format: none, display-icon: false, ) = Usage == Pre Requisites To use this template, to need to be able to compile typst documents. == Importing the template There are two ways to import the template. The first way is to download the template file and import it using the `#import` command with a relative path to the local file. ```typst #import "./../aero-check.typ": * ``` The second way is to import the template from the Typst Universe. If you have a method to render Typst documents that supports the Typst Universe, you can import the template using the following command: ```typst #import "@preview/aero-check:0.1.1": * ``` == First Document To create a document using this template, you can use the `checklist` command. This command has a lot of arguments to customize the document. Here is an example of a simple document: ```typst #show: checklist.with( title: "Title", // disclaimer: "", // 0 or 1 // style: 0, ) #topic("Topic")[ #section("Section")[ #step("Step", "Check") #step("Step", "Check") ] #section("Section")[ #step("Step", "Check") #step("Step", "Check") ] ] ``` = Available commands <checklist> #command( "checklist", arg[title], arg[disclaimer], arg[style], barg[body], )[ #argument("title", types: "string", default: none)[ The title of the document. ] #argument("disclaimer", types: "string", default: none)[ A disclaimer put at the top of the checklist. ] #argument("style", types: "int", default: 0)[ The style of the checklist. ] ] <topic> #command( "topic", arg[title], arg[fill-clr], barg[body], )[ #argument("title", types: "string")[ The title / name of the topic. ] #argument("caution", types: "color", default: rgb("FFFFFF"))[ The fill color of the topic box. ] #argument("body", types: content)[ The contents of the topic. ] ] <section> #command( "section", arg[title], arg[fill-clr], barg[body], )[ #argument("title", types: "string")[ The title / name of the section. ] #argument("caution", types: "color", default: rgb("FFFFFF"))[ The fill color of the section box. ] #argument("body", types: content)[ The contents of the section. ] ] #pagebreak() <topic> #command( "small-caution", barg[caution], )[ #argument("caution", types: "string")[ The caution text to be displayed. ] ] // black-and-white: false, body <emer-page> #command( "emer-page", arg[black-and-white], barg[body], )[ #argument("black-and-white", types: "bool", default: false)[ If the emergency page style should be drawn in black and white or color. ] #argument("body", types: content)[ The contents of the emer-page. ] ]
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/spue/planung/langentwurf.typ
typst
Other
#import "/src/template.typ": * == #ix("Langentwurf") Der #ix("Langentwurf") erklärt und begründet die Themenauswahl und Ihre Vorgehensweise soweit, dass ein anderer an Ihrer Stelle die Stunde vollständig nachvollziehen, halten und erklären könnte. Dazu werden die aktuellen Begingungen und der Stand der SuS und der #ix("Lernumgebung") in der #ix("Bedingungsanalyse") aufgezeigt, die fachlichen Inhalte in der #ix("Sachanalyse") auf einem hohen Niveau dargestellt, in den #ix("didaktischen Überlegungen", "Überlegung, didaktisch") die Unterrichtstunde #ix("legitimiert", "Legitimation, didaktisch"), der inhaltliche Schwerpunkt gesetzt und der Lernweg strukturiert. Zuletzt wird in den #ix("methodischen Überlegungen", "Überlegung, methodisch") der konkrete Ablauf des Unterrichts in Bezug auf #ix("Sozialform"), #ix("Methoden", "Methode") und #ix("Medien", "Medium") erklärt und die Auswahl begründet. Jeder Schritt, bis auf die Sachanalyse und die #ix("Bedingungsanalyse") an sich, muss mit Bezug auf die #ix("Bedingungsanalyse") und die herausgestellte Zielgruppe betrachtet werden, da für diese der Unterricht erst entworfen werden soll. Diese und alle sonstigen Erklärungen zum Langentwurf richten sich nach den Handreichungen vom #ix("Zentrum für Lehrerbildung und Bildungsforschung", "ZLB") an der Universität Rostock.#en[Vgl. @ZLBHandreichung] #orange-list-with-body[*Deckblatt*][ #show: columns.with(2) *Allgemein:* - Titel - Thema der Unterrichtseinheit - Thema der Unterrichtsstunde *Informationen zur Veranstaltung:* - Universität - Fakultät - Institut - Modul - Dozent*in des Moduls - Mentor*in der SPÜ #colbreak() *Persönliche Informationen:* - Name - Anschrift - Matr.-Nr. - E-Mail - Studiengang - Fachsemester *Informationen zur Schule* - Name der Schule - Anschrift der Schule - Klasse - Datum und Uhrzeit der Unterrichtsstunde - ggf. Schulleitung und Fachlehrer ][*#ix("Bedingungsanalyse")*][ Die #ix("Bedingungsanalyse") stellt die Bedingungen, in und mit denen der Unterricht stattfinden soll, dar. Die #ix("Lerngruppe") und für die Planung relevante Charakteristika (psychologische und individuelle Besonderheiten, statistische Angaben) werden aufgelistet. Hier sollte eine entwicklungspsychologische Einordnung anhand des statistischen Altersdurchschnittes stattfinden. Dazu eignet sich etwa das Modell von #ix("Piaget", "Piaget, Jean").#en[Vgl. @SeitzSteinBerner2019_Entwicklung[S. 240 ff]] Dazu gehört auch die #ix("Umgebung", "Lernumgebung") dieser #ix("Lerngruppe") und die Eigenheiten Örtlichkeit, an der die Unterrichtsstunde stattfinden soll. Sie können sich hier auf die Dinge beschränken, die für die Planung und Durchführung des Unterrichts tatsächlich relevant sind. - Angaben zur #ix("Lerngruppe"): - allgemeine Statistik (Anzahl, Altersdurchschnitt, ...) - psychologische und individuelle Besonderheiten - entwicklungspsychologische Einordnung - Arbeitsvoraussetzungen: - personale Gegebenheiten - bekannte Arbeitstechniken, Methoden - Ausstattung des Raumes und der Schule - räumliche Gegebenheiten - Stand der Lerngruppe in Bezug auf das Fach und Thema - eigene Voraussetzungen: - bisher gesammelte Erfahrung - Vertrautheit mit der #ix("Lerngruppe") ][*#ix("Sachanalyse")*][ In der #ix("Sachanalyse") stellen Sie das Unterrichtsthema auf einem komplexen, fachlichen Niveau von der inhaltlichen Seit aus dar. Das bedeutet, dass Bezüge für den Unterricht hier nicht erwünscht sind, es geht um die Ausbreitung des Problemraumes: Was wird behandelt? Das Thema wird umfänglich anhand von fachwissenschaftlicher Literatur dargestellt. Hier können und müssen die Ergebnisse der Unterrichtsstunde auf hohem Niveau vorausgegriffen werden. (Ohne die Wörter "Unterricht", "Klasse", oder "SuS" zu verwenden.) Stellen Sie das Thema so dar, dass eine andere Lehrperson, die dieses Thema vorher nicht unterrichtet hat, umfangreich darüber informiert ist und auch einfachere Nachfragen von SuS in Bezug auf das Thema und dessen Vertiefung beantworten kann oder mindestens weiß, wo sie nachschlagen müsste, um diese zu beantworten. ][*#ix("Didaktische Überlegungen", "Überlegung, didaktisch")*][ Erklären Sie zum einen, wie Ihre Unterrichtsstunde in der Sequenz zu verorten ist und was für eine Funktion sie hat. Stellt sie die Einleitung oder den Abschluss in einer Sequenz dar? Ist es eine Vertiefung? Wird ein neues Problem eröffnet? Wichtig ist dazustellen, wie sie sich in Bezug auf die Richtziele verhält. Dafür nennen Sie das angepeilte Richtziel der Sequenz und das Grobziel der Stunde! Zum anderen legitimieren, akzentuieren und strukturieren sie den Inhalt der Unterrichtsstunde. + *Legitimation:* Ein Bezug auf den Rahmenplan kann hier eine grundlegende Legitimation des Themas und ihrer Unterrichtsziele sein. Sie geben zusätzlich eine Begründung _mit Bezug auf die Bedingungsanalyse_ an, warum das Thema und die Unterrichtsziele für die SuS relevant waren, sind und sein werden. Dazu nehmen Sie Bezug auf #ix("Klafki", "<NAME>"):#en[Vgl. @Klafki1964_DidaktischeAnalyse[S. 15 ff] (Der ganze Text ist durchaus relevant! Lesen sie ihn!)] - *exemplarische Bedeutung:* Das Thema steht exemplarisch für ein Überthema -- die Gottesbegriffe von #ix("Nietzsche", "<NAME>"), #ix("Jonas", "<NAME>") und #ix("Spinoza", "<NAME>") stehen stellvertretend für eine religiöse Konzeption, die unter den Begriff des Wortes "Gott" fällt, das man erschließen könnte. Die begriffanalytische Erschließung der einzelnen Eigenschaften ist ein Beispiel für die Arbeit am Begriff überhaupt. So kann jede konkrete Umsetzung im Unterricht auf einen allgemeinen Fall zurückgeführt werden. Erklären Sie, was das Überthema ist und wie es sich dazu verhält. - *Gegenwartsbedeutung:* Wie lebensnah ist der Inhalt für die SuS? Wie zugänglich ist er für sie? Können sie ihn in ihrer aktuellen Lage überhaupt nachvollziehen? Wurde dieses Thema bereits durch die SuS aufgeworfen? - *Zukunftsbedeutung:* Wie relevant wird das Thema für die SuS in der Zukunft sein? Ist absehbar, dass es ihnen in irgendeienr Form weiterhilft, für sie relevant sein wird oder in der Welt, in der sie aufwachsen, weiterhin von Bedeutung ist? Außerdem können Sie hier Bezug nehmen auf fachdidaktische Grundpositionen, das Philosophieverständnis und weitere Ausführungen im Rahmenplan. Halten Sie sich die Ziele des Unterrichtsfaches "Philosophie" vor Augen, diese sind durch die Unterrichtsstunde zu erreichen. + *#ix("Akzentuierung")/#ix("Schwerpunktsetzung")/#ix("Reduktion", "Reduktion, didaktisch"):* Auch wenn "Reduktion" in der Philosophiedidaktik nicht gerne gesehen ist (denn das Ziel des Philosophieunterrichts ist das Philosophieren, das kann und darf man nicht "wegreduzieren"), müssen Sie den Inhalt der Stunde für die SuS zugänglich machen. Sie können inhaltlich nicht alles auf dem Niveau behandeln, wie Sie es in der #ix("Sachanalyse") dargestellt haben. Um etwa die Gottesbegriffe von #ix("Nietzsche", "<NAME>") und #ix("Jonas", "<NAME>") zu verstehen, ist der historische Hintergrund, in dem sich diese Positionen entwickelten, extrem relevant und daher in einer #ix("Sachanalyse") anzuführen, aber für den Unterricht kann es vernachlässigt werden, wenn es nur spezifisch um die Erkenntnis geht, dass es verschiedene Begriffsvorstellungen Gottes gibt. Hier können Sie durch Bezug auf die Ziele des Unterrichts und die #ix("Bedingungsanalyse") einen Schwerpunkt setzen, worauf sich der Inhalt der Stunde konzentrieren soll. + *Strukturierung:* Erklären Sie, wie sie Ihre Stunde strukturiert haben. Sollten Sie das PEST- oder Bonbon-Modell angewandt haben, benennen, erklären und begründen Sie das Modell und seine Nutzung konkret in Ihrer Situation. Nehmen Sie Bezug auf die Primärliteratur des jeweiligen Modelles.#en[Die Quellenangaben sind in dem jeweiligen Abschnitt zum Modell angegeben.] Erklären Sie, wie sich das Thema _inhaltlich_ aufbauen. Hier nennen sie _keine_ #ix("Methoden", "Methode") oder #ix("Sozialformen", "Sozialform"), die sind erst in den "Methodischen Überlegungen" relevant. Geben Sie hier aber Verkürzungsmöglichkeiten und eine begründete didaktische Reserve an. ][*Stundenziele*][ Nennen Sie die Grob- und Feinziele, die alle Anforderungsbereiche abdecken sollten. ][*#ix("Methodische Überlegungen", "Überlegung, methodisch")*][ Stellen Sie dar, welche Medien, Methoden und #ix("Sozialformen", "Sozialform") Sie wann warum einsetzen, um Ihre Unterrichtsstunde zu gestalten und zu unterstützen. Denken Sie an #ix("Methodenvielfalt")! Nehmen Sie Bezug auf die #ix("Bedingungsanalyse"), um diese zu rechtfertigen bzw. mögliche Alternativen abzuwägen. Nennen Sie in jedem Fall alternative Möglichkeiten! Erklären Sie anhand von Fachliteratur, wie die einzelnen Methoden und #ix("Sozialformen", "Sozialform") zu verwenden sind, warum sie (durch Bezug auf die #ix("Bedingungsanalyse")) geeignet bzw. weniger geeignet sind. Stellen Sie Maßnahmen zur #ix("Binnendifferenzierung") begründet dar. Dazu können Sie z.B. Wahl- oder Wahlpflichtaufgaben sowie Zusatzaufgaben formulieren. Beziehen Sie ein, dass einige SuS schneller oder langsamer sind als andere. Wenn sie spezielle Formen des Philosophierens (mit Bildern, Filmen, theatrales Philosophieren, #ix("produktionsorientierte Didaktik", "Produktionsorientierung"), ...) benutzen, nehmen Sie auch hier Bezug auf die Fachlektüre! ][*Ausführlicher Verlaufsplan*][ Siehe S. #refpage(<ephid-unterrichtsplanung>) ff. Es handelt sich um eine umfangreiche Aufschlüsselung, wann was passiert in tabellarischer Form. Für jede Aufgabe werden Erwartungshorizonte verwendet. ][*#ix("Reflexion")*][ Nachdem Sie die Stunde erfolgreich abgeschlossen haben, schreiben Sie diesen Abschnitt, die #ix("Reflexion"), und beantworten folgende Fragen: + *Reflexion der Ziele:* Wurden die geplanten Ziele bei allen Schülern bzw. bei der adressierten Gruppe der Schüler erreicht? Woran haben Sie das erkennen können? + *Wirksamkeit des Vorgehens:* Erwies sich das geplante Vorgehen als günstig? Wie gut wurden die SuS aktiviert? Wie war das Verhältnis zwischen Planung und tatsächlichem Verlauf? Waren gewählte Aufgaben und Methoden geeignet? + *Anknüpfung:* Wie geht es nach dieser Stunde weiter? Wie könnte man das Thema weiterführen? Wie knüpft man daran an in Bezug das neue Thema der folgenden Stunde? + *Gewonnene Einsichten:* Was würden Sie beim nächsten Mal anders machen? Was nehmen Sie aus dieser Stunde mit? Was sind Ihre gewonnenen Einsichten in Bezug auf Ihr pädagogisches Verhalten, dem methodischen und didaktischem Vorgehen und dem eigenen fachlichen Stand? ][*Anlagen*][ - Bilder, Texte, alle Formen verwendeter Medien (sofern Anlage möglich) - PowerPoint-Präsentation (fällt unter verwendete Medien) - Arbeitsblätter, Hausaufgaben, Leistungskontrollen - Erwartungshorizonte, Bewertungsmaßstäbe - Tafelbilder, Sitzpläne - *Selbständigkeitserklärung* - ... ][*Bibliographie*][ Im Literaturverzeichnis bzw. der Bibliographie listen Sie die verwendete Literatur einheitlich nach einem einheitlichen Zitierstil alphabetisch sortiert auf. Literaturverwaltungsprogramme wie Citavi oder Zotero inkl. Plugins für Word, LibreOffice o.ä. sind hilfreich. Wer technisch sehr versiert ist oder bereits Erfahrung im Bereich von den folgenden derartigen Textsatzprogrammen hat, kann die Literaturverwaltung das ältere LaTeX oder auch das jüngere Typst übernehmen lassen. ]
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/exers/m.typ
typst
#import "../cfg.typ": * #show: cfg $ "Prove that" (all(n): a_n >= a_(n + 1) > 0) -> sum_(n = 1)^oo a_n "converges" -> a_n =_(n -> oo) o(1/n) $ I'm proving that $n a_n -> 0$ That is, $all(epsilon) ex(N) all(n > N): n a_n < epsilon$ $ex(N) all(k_1\, k_2 > N): a_k_1 + ... + a_k_2 < epsilon/2$ $all(n > N): n a_(2n) <= a_n + ... + a_(n + n) < epsilon/2$ $all(n > N): 2n a_(2n) < epsilon$ $all(n > N): (n + 1/2) a_(2n + 1) < (n + 1) a_(2n + 1) <= a_n + ... + a_(n + n + 1) < epsilon/2$ $all(n > N): (2n + 1) a_(2n + 1) < epsilon$ $all(n > 2N): n a_n < epsilon$ $qed$
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/scrutinize/0.1.0/src/questions.typ
typst
Apache License 2.0
#let solution = state("scrutinize-solution", false) /// Shows solutions in the document. /// /// -> content #let set-solution() = solution.update(true) /// Hides solutions in the document. /// /// -> content #let unset-solution() = solution.update(false) /// Queries the current solution display state. /// /// If a function is provided as a parameter, the boolean is used to call it and content is returned. /// If a location is provided instead, it is used to retrieve the boolean state and it is returned directly. /// /// - func-or-loc (function, location): either a function that receives metadata and returns content, or the location at which to locate the question /// -> content, boolean #let is-solution(func-or-loc) = { let inner(loc) = solution.at(loc) if type(func-or-loc) == function { let func = func-or-loc // find value, transform it into content locate(loc => func(inner(loc))) } else if type(func-or-loc) == location { let loc = func-or-loc // find value, return it inner(loc) } else { panic("function or location expected") } } /// An answer to a free text question. If the document is not in solution mode, /// the answer is hidden but the height of the element is preserved. /// /// - answer (content): the answer to (maybe) display /// - height (auto, relative): the height of the region where an answer can be written /// -> content #let free-text-answer(answer, height: auto) = is-solution(solution => { let answer = block(inset: (x: 2em, y: 1em), height: height, answer) if (not solution) { answer = hide(answer) } answer }) /// A checkbox which can be ticked by the student. /// If the checkbox is a correct answer and the document is in solution mode, it will be ticked. /// /// - correct (boolean): whether the checkbox is of a correct answer /// -> content #let checkbox(correct) = is-solution(solution => { if (solution and correct) { sym.ballot.x } else { sym.ballot } }) /// A table with multiple options that can each be true or false. /// Each option is a tuple consisting of content and a boolean for whether the option is correct or not. /// /// - options (array): an array of (option, correct) pairs /// -> content #let multiple-choice(options) = { table( columns: (auto, auto), align: (col, row) => (left, center).at(col) + horizon, ..options.map(((option, correct)) => ( option, checkbox(correct), )).flatten() ) } /// A table with multiple options of which one can be true or false. /// Each option is a content, and a second parameter specifies which option is correct. /// /// - options (array): an array of contents /// - answer (integer): the index of the correct answer, zero-based /// -> content #let single-choice(options, answer) = { multiple-choice(options.enumerate().map(((i, option)) => (option, i == answer))) }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/let-07.typ
typst
Other
// Ref: false // Destructuring with a sink in the middle. #let (a, ..b, c) = (1, 2, 3, 4, 5, 6) #test(a, 1) #test(b, (2, 3, 4, 5)) #test(c, 6)
https://github.com/cloudsftp/zivi.typ
https://raw.githubusercontent.com/cloudsftp/zivi.typ/latest/zivi.typ
typst
Apache License 2.0
/* * Customizations on this template: * * - headings (h1..h4) * * - `datebox` function: provides content with stacked year above (big) and month below (tinier) * * - `daterange` function: two `datebox`es separated by an em dash * * - `cvgrid`: basic layout function that wraps a grid. Controlled by two parameters `left_column_size` (default: 25%) and `grid_column_gutter` (default: 8pt) which control the left column size and the column gutter respectively. * * - `cvcol`: used to write in the rightmost column only. Builds on `cvgrid` * * - `cventry`: used to write a CV entry. Builds on `cvgrid` * * - `cvlangauge`: used to write a language entry. Builds on `cvgrid` * */ #let left_column_size = 25% #let grid_column_gutter = 8pt #let main_color = rgb(0, 90, 120) // Verkehrsblau #let heading_color = main_color #let job_color = rgb(147, 14, 14) #let small_logo_box(logo) = [ #box(height: 1em, baseline: 20%)[#pad(right: 0.4em)[#logo]] ] #let small_logo(file) = [ #small_logo_box(image(file)) ] #let small_colored_logo(file) = { let original = read(file) let colored = original.replace( "#000000", main_color.to-hex(), ) small_logo_box(image.decode(colored)) } #let zivi( title: "", author: [], phone: "", email: "", github: "", website: "", birthday: "", last_updated: none, left_column_size: left_column_size, grid_column_gutter: grid_column_gutter, main_color: main_color, heading_color: heading_color, job_color: job_color, body ) = { set document(author: author, title: title) set page(numbering: none) set text(font: ("Open Sans", "Latin Modern Sans", "Inria Sans"), lang: "en", fallback: true) show math.equation: set text(weight: 400) /* * How headings are used: * - h1: section (colored, prominent, with colored rectangle, spans two columns) * - h2: role (bold) * - h3: place (normal) * - h4: generic heading (normal, colored) */ show heading.where(level: 1): element => [ #v(0em) #box( inset: (right: grid_column_gutter, bottom: 0.1em), rect(fill: main_color, width: left_column_size, height: 0.25em) ) #text(element.body, fill: heading_color, weight: 400) ] show heading.where(level: 2): element => [ #text(element.body, size: 0.8em) ] show heading.where(level: 3): element => [ #text(element.body, size: 1em, weight: 400) ] show heading.where(level: 4): element => block[#text(element.body, size: 1em, weight: 400, fill: heading_color)] set list(marker: "-") //set list(marker: box(circle(radius: 0.2em, stroke: heading_color), inset: (top: 0.15em))) set enum(numbering: (n) => text(fill: heading_color, [#n.])) grid( columns: (1fr, 1fr), box[ // Author information. #text([#author], weight: 400, 2.5em) #v(-1.2em) // Title row. #block(text(weight: 400, 1.5em, title, style: "italic", fill: job_color)) ], align(right + top)[ // Contact information #set block(below: 0.5em) #let define_row(url, text, icon) = { align(top)[ #link(url)[ #text #h(.5em) #small_logo("icons/" + icon) ] ] } #if github != "" { define_row("https://github.com/" + github, github, "github.svg") } #if website != "" { define_row(website, website, "website.svg") } #if phone != "" { define_row("tel:" + phone, phone, "phone-solid.svg") } #if email != "" { define_row("mailto:" + email, email, "envelope-regular.svg") } #if birthday != "" { define_row("birth:" + birthday, birthday, "calendar.svg") } ] ) // Main body. set par(justify: true, leading: 0.5em) body if last_updated != none { v(1fr) align(center)[_(Last updated: #last_updated)_] } } #let date_height = 1.8em #let datebox(range: ()) = { let year = range.at("year", default: "") let month = range.at("month", default: "") box( width: 4em, height: date_height, align(center, stack( dir: ttb, spacing: 0.4em, text(size: 1em, [#year]), text(size: 0.75em, [#month]), ) ) ) } #let daterange(start: (), end: ()) = box( if end == () { datebox(range: start) } else { stack(dir: ltr, spacing: 0.75em, datebox(range: start), [--], datebox(range: end) ) } ) #let cvgrid(..cells) = pad(bottom: 0.8em)[#grid( columns: (left_column_size, auto), row-gutter: 0em, column-gutter: grid_column_gutter, ..cells )] #let cvcol(content) = cvgrid([], content) #let role_entry(role) = box(height: date_height)[ #if role != none { text[== #role] } ] } #let institution_entry(institution, logo) = box(height: date_height)[ #if logo != none { small_logo("usericons/" + logo) } #if institution != none { text[=== #institution] } ] } #let place_entry(place) = { if place != none { box(height: date_height)[ #h(1fr) #small_colored_logo("icons/location.svg") #text[=== #place] ] } } #let description_entry(description) = { v(1em) text[#description] } #let cventry( start: (), end: (), role: none, logo: none, institution: none, place: none, description, ) = cvgrid( align(center, daterange(start: start, end: end)), [ #role_entry(role) #h(1fr) #institution_entry(institution, logo) ], [], place_entry(place), [], description_entry(description), ) #let cventry_long_role( start: (), end: (), role: "", logo: "", institution: "", place: "", description, ) = cvgrid( align(center, daterange(start: start, end: end)), role_entry(role), [], [ #align(right, institution_entry(institution, logo)) ], [], place_entry(place), [], description_entry(description), ) #let cvlanguage( language: [], description: [], certificate: [], ) = cvgrid( align(right, language), [#description #h(3em) #text(style: "italic", certificate)], ) #let thesis(title, grade: none, url: none) = { align(center)[ #box( width: 80%, height: 4em, )[ #align(center + horizon)[ #if url != none { link(url)[ #text(style: "italic", title) ] } else { text(style: "italic", title) } ] #if grade != none { align(right + bottom)[(grade: #text(weight: "semibold")[#grade])] } ] ] } #let project( start: (), end: (), name: none, role: none, logo: none, website: none, playstore: none, github: none, description, ) = cvgrid( align(center, daterange(start: start, end: end)), [ #if name != none { text[== #name] } #if role != none { text[ --- === #role ] } #h(1fr) #if website != none { link(website, small_logo("icons/website.svg")) } #if playstore != none { link(playstore, small_logo("icons/playstore.svg")) } #if github != none { link(github, small_logo("icons/github.svg")) } ], [], [ #v(1em) #description ], )
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/show/code-show-closure.typ
typst
Apache License 2.0
#let project( title: "", ) = { show heading: it => box(width: 100%)[ #v(0.50em) #set text(font: heading-font) #if it.numbering != none { counter(heading).display() } #h(0.75em) #it.body ] }
https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst
https://raw.githubusercontent.com/TJ-CSCCG/tongji-undergrad-thesis-typst/main/README.md
markdown
MIT License
# :page_facing_up: 同济大学本科生毕业设计论文 Typst 模板(理工类) 中文 | [English](README-EN.md) > [!CAUTION] > 由于 Typst 项目仍处于密集发展阶段,且对某些功能的支持不完善,因此本模板可能存在一些问题。如果您在使用过程中遇到了问题,欢迎提交 issue 或 PR,我们会尽力解决。 > > 在此期间,欢迎大家使用[我们的 LaTeX 模板](https://github.com/TJ-CSCCG/tongji-undergrad-thesis)。 ## 样例展示 以下依次展示 “封面”、“中文摘要”、“目录”、“主要内容”、“参考文献” 与 “谢辞”。 <p align="center"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0001.jpg" width="30%"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0002.jpg" width="30%"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0004.jpg" width="30%"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0005.jpg" width="30%"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0019.jpg" width="30%"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0020.jpg" width="30%"> </p> ## 使用方法 ### 在线 Web App #### 创建项目 - 打开 Typst Universe 中的 [![svg of typst-tongjithesis](https://img.shields.io/badge/Typst-paddling--tongji--thesis-239dae)](https://typst.app/universe/package/paddling-tongji-thesis) 并点击 `Create project in app`。 - 或在 [Typst Web App](https://typst.app) 中选择 `Start from a template`,然后选择 `paddling-tongji-thesis`。 #### 上传字体 从[`fonts` 分支](https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst/tree/fonts)下载所有字体文件,上传到该项目的根目录。即可开始使用。 ### 本地使用 #### 1. 安装 Typst 参照 [Typst](https://github.com/typst/typst?tab=readme-ov-file#installation) 官方文档安装 Typst。 #### 2. 下载字体 从[`fonts` 分支](https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst/tree/fonts)下载所有字体文件,并**安装到系统中**。 #### 使用 `typst` 初始化 ##### 初始化项目 ```bash typst init @preview/paddling-tongji-thesis ``` ##### 编译 ```bash typst compile main.typ ``` #### 使用 `git clone` 初始化 ##### Git Clone 项目 ```bash git clone https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst.git cd tongji-undergrad-thesis-typst ``` ##### 编译 ```bash typst compile init-files/main.typ --root . ``` > [!TIP] > 若你不想把项目使用的字体安装到系统中,可以在编译时指定字体路径,例如: > > ```bash > typst compile init-files/main.typ --root . --font-path {YOUR_FONT_PATH} > ``` ## 如何为该项目贡献代码? 还请查看 [How to pull request](CONTRIBUTING.md/#how-to-pull-request)。 ## 开源协议 该项目使用 [MIT License](LICENSE) 开源协议。 ### 免责声明 本项目使用了方正字库中的字体,版权归方正字库所有。本项目仅用于学习交流,不得用于商业用途。 ## 有关突出贡献的说明 - 该项目起源于 [FeO3](https://github.com/seashell11234455) 的初始版本项目 [tongji-undergrad-thesis-typst](https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst/tree/lky)。 - 后来 [RizhongLin](https://github.com/RizhongLin) 对模板进行了完善,使其更加符合同济大学本科生毕业设计论文的要求,并增加了针对 Typst 的基础教程。 我们非常感谢以上贡献者的付出,他们的工作为更多同学提供了方便和帮助。 在使用本模板时,如果您觉得本项目对您的毕业设计或论文有所帮助,我们希望您可以在您的致谢部分感谢并致以敬意。 ## 致谢 我们从顶尖高校的优秀开源项目中学到了很多: - [lucifer1004/pkuthss-typst](https://github.com/lucifer1004/pkuthss-typst) - [werifu/HUST-typst-template](https://github.com/werifu/HUST-typst-template) ## 联系方式 ```python # Python [ 'rizhonglin@$.%'.replace('$', 'epfl').replace('%', 'ch'), ] ``` ### QQ 群 - TJ-CSCCG 交流群:`1013806782`
https://github.com/KmaEE/ee
https://raw.githubusercontent.com/KmaEE/ee/main/outline.typ
typst
- Introduction: talk about uses of ECDH, having a shared secret - Introduction II: What are elliptic curves? Working with Wierstrauss forms. The group law for elliptic curves, projective geometry, proof of some properties. Question: do we needd to explain group theory? - Discrete log problem in groups, how the index calculus defeats the multiplicative groups modulo a prime for small primes. https://security.stackexchange.com/questions/112313/what-is-the-current-security-status-of-diffie-hellman-key-exchange as a start, but find better sources than that. - Discrete log problem in an elliptic curve - Detailed step by step description of ECDH: - Randomly pick a point, how do we do that? (Mathematical, not computer science) Share that point to others - Add that point to itself n many times on Alice, sends $g^n$ to bob, m many times on Bob, sends $g^m$ to Alice. Alice computes $g^(m n)$ and bob computes $g^(n m)$. (from wikipedia) - What specific powers of integers do we select? - Hashing that shared secret to be used as a shared secret for https. - Useful for establishing secure connection to online banking, hide the contents that you see from your internet service provider, provides privacy. - Elliptic curve is also more secure - ref https://en.wikipedia.org/wiki/Logjam_(computer_security) Logjam - logjam talks about imperfect forward secrecy - https://crypto.stackexchange.com/questions/70464/what-is-the-actual-result-of-a-logjams-dh-attack - https://crypto.stackexchange.com/questions/52618/why-do-elliptic-curves-require-fewer-bits-for-the-same-security-level - Some notes - Should have balance between text, math, and visuals - A good strategy is to use some examples - https://en.wikipedia.org/wiki/Security_level
https://github.com/DaAlbrecht/thesis-TEKO
https://raw.githubusercontent.com/DaAlbrecht/thesis-TEKO/main/content/annexes.typ
typst
#set heading(numbering: "A", supplement: [Annex]) #counter(figure.where(kind: table)).update(0) #counter(figure.where(kind: image)).update(0) #counter(figure.where(kind: raw)).update(0) #set figure(numbering: (x) => [A.#x]) = Project assignment<a_assignment> #figure( image("../personal/annex/page1.svg"), ) #figure( image("../personal/annex/page2.svg"), ) #figure( image("../personal/annex/page3.svg"), ) #figure( image("../personal/annex/page4.svg"), ) #figure( image("../personal/annex/page5.svg"), ) #figure( image("../personal/annex/page6.svg"), ) #figure( image("../personal/annex/page7.svg"), ) #figure( image("../personal/annex/page8.svg"), ) = Project plan<a_plan> #figure( image("../personal/annex/projectplan.svg"), )
https://github.com/flaribbit/numbly
https://raw.githubusercontent.com/flaribbit/numbly/master/lib.typ
typst
MIT License
#let numbly(..arr, default: "1.") = (..nums) => { let arr = arr.pos() nums = nums.pos() if nums.len() > arr.len() { if default == none { return none } if type(default) == function { return default(..nums) } return numbering(default, ..nums) } let format = arr.at(nums.len() - 1) if format == none { return none } if type(format) == function { return format(..nums) } format.replace( regex("\{(\d)(:(.+?))?\}"), m => { let (a, b, c) = m.captures if b != none { numbering(c, nums.at(int(a) - 1)) } else { str(nums.at(int(a) - 1)) } }, ) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/hide-meta_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set cite(style: "chicago-notes") A pirate. @arrgh \ #set text(2pt) #hide[ A @arrgh pirate. #bibliography("/assets/files/works.bib") ]
https://github.com/daskol/typst-templates
https://raw.githubusercontent.com/daskol/typst-templates/main/jmlr/blindtext.typ
typst
MIT License
/** * blindtext.typ * * This module is motivated by its LaTeX counterpart `blindtext`. It is used as * a slightly advanced alternative to common `lorem` routine. * * [1]:https://ctan.org/tex-archive/macros/latex/contrib/blindtext */ #let blindtext = [Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam lobortis facilisis sem. Nullam nec mi et neque pharetra sollicitudin. Praesent imperdiet mi nec ante. Donec ullamcorper, felis non sodales commodo, lectus velit ultrices augue, a dignissim nibh lectus placerat pede. Vivamus nunc nunc, molestie ut, ultricies vel, semper in, velit. Ut porttitor. Praesent in sapien. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis fringilla tristique neque. Sed interdum libero ut metus. Pellentesque placerat. Nam rutrum augue a leo. Morbi sed elit sit amet ante lobortis sollicitudin. Praesent blandit blandit mauris. Praesent lectus tellus, aliquet aliquam, luctus a, egestas a, turpis. Mauris lacinia lorem sit amet ipsum. Nunc quis urna dictum turpis accumsan semper.] #let formulas = ( $ accent(x, macron) = 1 / n sum_(i = 1)^(i = n) x_i = (x_1 + x_2 + dots + x_n) / n $, $ integral_0^infinity e^(-alpha x^2) dif x = 1/2 sqrt(integral_(-infinity)^infinity e^(-alpha x^2)) dif x integral_(-infinity)^infinity e^(-alpha y^2) dif y = 1/ 2 sqrt(pi / alpha) $, $ sum_(k = 0)^infinity a_0 q^k = lim_(n arrow.r infinity) sum_(k = 0)^n a_0 q^k = lim_(n arrow.r infinity) a_0 (1-q^(n + 1)) / (1-q) = a_0 / (1-q) $, $ x_(1,2) = (-b plus.minus sqrt(b^2 - 4 a c )) / ( 2 a) = (-p plus.minus sqrt(p^2 - 4 q)) / 2 $, $ (diff^2 Phi) / (diff x^2) + (diff^2 Phi) / (diff y^2) + (diff^2 Phi) / (diff z^2) = 1 / c^2 (diff^2 Phi) / (diff t^2) $, $ root(n, a) dot.c root(n, b) = root(n, a b) $, $ root(n, a) / root(n, b) = root(n, a / b) $, $ a root(n, b) = root(n, a^n b) $, ) #let blindmathpaper = { parbreak() blindtext formulas.slice(0, 5).join(blindtext) blindtext }
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/ES_DM_1_07_11_2023.typ
typst
#import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "ES DM 1 07 11 2023", authors: ( "<NAME>", ), date: "31 Octobre, 2023", ) #set heading(numbering: "1.1.") == Question 1: #emph[Discerner les problèmes réels des faux problèmes qui peuvent se poser au sujet de l’intelligence artificielle.] <question-1-discerner-les-problèmes-réels-des-faux-problèmes-qui-peuvent-se-poser-au-sujet-de-lintelligence-artificielle.> Les documents présentent plusieurs problématiques liées au développement de l’intelligence artificielle et des automatismes dans notre société. Certains soulèvent des questions éthiques et juridiques réelles, tandis que d’autres me semblent reposer sur de fausses hypothèses. Le document 1 pose clairement la question de la responsabilité en cas de dysfonctionnement d’un robot domestique. Qui est responsable dans ce cas ? Le fabricant, l’utilisateur, le robot lui-même ? Cette question me semble tout à fait pertinente et réelle, le droit devant s’adapter pour définir les responsabilités de chacun face à ces nouvelles technologies autonomes. Le document 2 liste des adaptations du droit pour encadrer l’intelligence artificielle. Cependant, il me semble que ce ne sont pas là des problèmes réels posés par cette technologie, mais plutôt des questions que les hommes doivent régler entre eux. La protection des données personnelles, la redéfinition des responsabilités juridiques relèvent de choix humains et non de problèmes inhérents à l’IA. En revanche, le document 3 me semble reposer sur une hypothèse excessive et infondée. L’idée qu’une société pourrait décider "d’écarter" des personnes détectées comme malades grâce à l’IA me paraît très improbable. Rien n’indique qu’une société démocratique emprunterait cette voie radicale plutôt que de soigner ces personnes. Ce risque me semble donc largement exagéré. En conclusion, l’intelligence artificielle soulève des questions juridiques et éthiques bien réelles, comme celle de la responsabilité en cas de dysfonctionnement. Mais certains discours alarmistes reposent sur des hypothèses peu crédibles et exagèrent les risques. Il faut garder un regard mesuré et pragmatique sur ces technologies pour en tirer le meilleur parti tout en encadrant leur usage de façon responsable. == Question 2: #emph[Montrer que l’intelligence artificielle est issue de nombreuses disciplines.] <question-2-montrer-que-lintelligence-artificielle-est-issue-de-nombreuses-disciplines.> Les documents montrent que l’intelligence artificielle puise ses origines dans de nombreux domaines scientifiques et techniques. Le document 1 rappelle que dès le 18ème siècle, l’horlogerie a permis les premiers automates programmables, ancêtres des robots actuels. On voit donc que la mécanique a joué un rôle précurseur. Le document 2 indique que la cybernétique, science du contrôle et de la communication chez les êtres vivants et les machines, a révolutionné la robotique moderne dans les années 1950. La cybernétique s’inspire de la biologie et des processus nerveux pour concevoir des robots dotés de rétroaction. Enfin, le document 3 souligne que l’informatique moderne s’intéresse aux connexions neuronales et à l’interaction homme-machine. L’intelligence artificielle puise donc aussi dans les neurosciences et la psychologie cognitive. On constate au final que l’intelligence artificielle, domaine récent, est issue du croisement de disciplines variées comme la mécanique, l’électronique, l’informatique, les mathématiques, la biologie ou encore les sciences cognitives. C’est de cette rencontre entre différents champs de connaissances qu’est née et se développe l’intelligence artificielle.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/path_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 7-31 point array must contain exactly two entries // #path(((0%, 0%), (0%, 0%, 0%)))
https://github.com/junyixu/intro-to-julia-sciml
https://raw.githubusercontent.com/junyixu/intro-to-julia-sciml/main/main.typ
typst
MIT License
#import "@preview/touying:0.4.2": * #import "@preview/cetz:0.2.2" #import "@preview/fletcher:0.4.4" as fletcher: node, edge #import "@preview/ctheorems:1.1.2": * #import "@preview/showybox:2.0.1": * #import "@preview/physica:0.9.3": * #show link: it => underline(stroke: (dash: "densely-dotted"), text(fill: eastern, it)) #let showy-thm( identifier, head, color: blue, symbol: "♥", ..showy-args, supplement: auto, base: "heading", base_level: none, ) = { let showy-fmt(name, number, body, ..args) = { showybox( title-style: ( boxed-style: ( anchor: ( x: left, // https://github.com/Pablo-Gonzalez-Calderon/showybox-package/blob/081b596cbbaaa275e154eb982833ec7410d13c29/examples/examples.typ#L133 y: horizon ), radius: (top-left: 10pt, bottom-right: 10pt, rest: 0pt), ) ), title: { head number if name != none { [(#name)] } }, frame: ( border-color: color, title-color: color.lighten(5%), body-color: color.lighten(95%), footer-color: color.lighten(80%), ), ..args.named(), { body place( bottom + right, dy: 0pt + 5pt, // Account for inset of block dx: 10pt + 0pt, text(fill: color)[#symbol] ) } ) } if supplement == auto { supplement = head } thmenv( identifier, "heading", none, showy-fmt, ).with(supplement: supplement) } #let theorem = showy-thm("theorem", "定理").with(numbering: "1.1") #let exercise = showy-thm("exercise", "Exercise ").with(numbering: "1.1") #let lemma = showy-thm("lemma ", "引理", color: rgb("#00a652"), symbol: "♣").with(numbering: "1.1") // #let lemma = showy-thm("lemma ", "引理", color: eastern).with(numbering: "1.1") #let proof = thmproof("proof", "Proof") // cetz and fletcher bindings for touying #let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true)) #let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide) // Register university theme // You can replace it with other themes and it can still work normally #let s = themes.university.register(aspect-ratio: "16-9") // Set the numbering of section and subsection #let s = (s.methods.numbering)(self: s, section: "1.", "1.1") // Set the speaker notes configuration // #let s = (s.methods.show-notes-on-second-screen)(self: s, right) // Global information configuration #let s = (s.methods.info)( self: s, title: [Julia Language and Scientific Machine Learning], subtitle: [From a user's perspective], author: [<NAME>], date: [September 21, 2024], institution: [Department 52], ) // Pdfpc configuration // typst query --root . ./example.typ --field value --one "<pdfpc-file>" > ./example.pdfpc #let s = (s.methods.append-preamble)(self: s, pdfpc.config( duration-minutes: 30, start-time: datetime(hour: 14, minute: 10, second: 0), end-time: datetime(hour: 14, minute: 40, second: 0), last-minutes: 5, note-font-size: 12, disable-markdown: false, default-transition: ( type: "push", duration-seconds: 2, angle: ltr, alignment: "vertical", direction: "inward", ), )) #let mybox(name, color: navy, body, ..args) = showybox( frame: ( border-color: color, title-color: color.lighten(5%), body-color: color.lighten(95%), footer-color: color.lighten(80%), ), title: { if name != none { [#name] } }, title-style: ( // color: black, weight: "regular", align: center ), shadow: ( offset: 3pt, ), ..args.named(), body ) // Theroems configuration by ctheorems #show: thmrules.with(qed-symbol: $square$) #let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee")) #let corollary = thmplain( "corollary", "Corollary", base: "theorem", titlefmt: strong ) #let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em)) #let example = thmplain("example", "Example").with(numbering: none) #let proof = thmproof("proof", "Proof") // Extract methods #let (init, slides, touying-outline, alert, speaker-note) = utils.methods(s) #show: init #show strong: alert // Extract slide functions #let (slide, empty-slide) = utils.slides(s) #show: slides = <NAME> == Hey, Have you heard of <NAME>? #slide(composer: (1fr, 1fr))[ #image("./img/同学你听过.png", width: 240pt) *Julia is a high level language for high performance computing.* ][ #mybox( [Features] // footer: "Information extracted from a well-known public encyclopedia" )[ - Generic Programming - Multiple Dispatch - Operator overloading - Native Differential Programming - Metaprogramming #emoji.face - Call Python and R - … #v(10pt) "*We are #link("https://julialang.org/blog/2012/02/why-we-created-julia/")[greedy]*". ]] == Julia 的缺点 #slide(composer: (1fr, 1fr, 1fr))[ #mybox( "Features" // footer: "Information extracted from a well-known public encyclopedia" )[ If you are not strong enough, features bug you. e.g. \ runtime-dispatch #image("./img/年轻人你渴望力量吗.png", width: 85pt) ] ][ #mybox( "特定情况比较慢" // footer: "Information extracted from a well-known public encyclopedia" )[ - 首次调用延迟(JIT) - 编译开销大,适合长时间运行的任务 - 动态语言,碰到类型不稳定的代码会很慢 #v(30pt) ] ][ #mybox( "Niche: 科学计算" // footer: "Information extracted from a well-known public encyclopedia" )[ - 缺乏原生 GUI 支持 - 移动开发支持薄弱 #v(164pt) ] ] = SciML == What's SciML === Key Components #line(length: 100%) - *Physics-based Modeling* - *Data-driven Machine Learning* - The Universal Approximation Theorem - Enhanced Interpretability - Efficient Handling of Complex Systems === Key Technologies #line(length: 100%) *Automatic Differentiation*: Leverage #link("https://enzyme.mit.edu/julia/stable/")[Enzyme.jl] or #link("https://github.com/FluxML/Zygote.jl")[Zygote.jl] for auto-diff and faster scientific computing == How do you solve ODEs #slide[ #image("./img/uniform_rod.png", width: 340pt) *A uniform rod of mass $M$ and length $l$ is hinged at one end.* ][ According to the #link("https://en.wikipedia.org/wiki/Parallel_axis_theorem")[parallel axis theorem], the moment of inertia $J'$: $ J' = J + M dot l^2. $ Hamiltonian: $ H = 1/2 J' dot(theta)^2 - M g l sin theta. $ ODEs: $ dot(theta) = pdv(H, p) = pdv(H, J' theta), quad dot(p) = -pdv(H, theta). $ ] == How do you solve ODEs using Julia ```julia using OrdinaryDiffEq function odejoint!(dy,y,α,t) # α = [J', Mgl] dy[1] = y[2]/α[1] # Generalized coordinates q: θ dy[2] = α[2]*cos(y[1]) # Generalized momentum p: J' dθ/dt end ``` #alternatives[ ```julia prob = ODEProblem(odejoint!, y0, tspan, α) # def your y0, α ``` ][ ```julia prob = ODEProblem(odejoint!, y0, tspan, α) # def your y0, α ``` ] ```julia sol = solve(prob) ``` == Change the algorithm ```julia using OrdinaryDiffEq function odejoint!(dy,y,α,t) # α = [J', Mgl] dy[1] = y[2]/α[1] # Generalized coordinates q: θ dy[2] = α[2]*cos(y[1]) # Generalized momentum p: J' dθ/dt end ``` #exercise[ Use a symplectic integrator to solve the above problem. ] ```julia sol = solve(prob) ``` = Showcase == Code #mybox( [Exmaples] // footer: "Information extracted from a well-known public encyclopedia" )[ Let's play around with #link("https://git.lug.ustc.edu.cn/junyixu/intro-to-julia-sciml")[PINNs in Jupyter]. ] = Summary == Summary - Machine learning and differential equations: converging to describe nonlinear world - Julia ecosystem: integrating differential equation and deep learning packages - Easy to tweak and customize loss functions - Comprehensive solver access: ODEs, SDEs, DAEs, DDEs, PDEs, and more // appendix by freezing last-slide-number #let s = (s.methods.appendix)(self: s) #let (slide, empty-slide) = utils.slides(s) == Appendix #slide[ === References - #link("https://julialang.org/blog/2019/01/fluxdiffeq/")[DiffEqFlux.jl – A Julia Library for Neural Differential Equations] - #link("https://lux.csail.mit.edu/dev/introduction/overview")[Lux.jl] === Useful Books - First Semester in Numerical Analysis with Julia - Numerical Linear Algebra with Julia - Design Patterns and Best Practices with julia - Statistics With Julia - Data Science with Julia (2019) ]
https://github.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024
https://raw.githubusercontent.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024/master/chap10/quadtree.typ
typst
// curl "https://gist.githubusercontent.com/oliver-ni/701eec83f6cc0b7e9464c2e67e607faa/raw/abc4f03d36669bb506268a989f1cc2dfdb2ce5dd/tree.typ" -o tree.typ #import "tree.typ": tree #set page("a3", flipped: true) #set text(font: "Noto Sans CJK SC") == 4 *(教材P512页,第10.39题。)* 分割的四叉树如下: #let im = ( (0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 1, 1, 1, 1, 0, 0), (0, 0, 1, 1, 1, 1, 0, 0), (0, 0, 1, 0, 0, 1, 0, 0), (0, 0, 1, 0, 0, 1, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0), ) #let same = (arr) => arr.all(x => x == arr.first()) #let split(im) = { let h = int(im.len() / 2) let w = int(im.at(0).len() / 2) if h < 1 or w < 1 or same(im.flatten()) { return im } // split into 4 quadrants let q1 = im.slice(0, h).map(row => row.slice(0, w)) let q2 = im.slice(0, h).map(row => row.slice(w)) let q3 = im.slice(h).map(row => row.slice(0, w)) let q4 = im.slice(h).map(row => row.slice(w)) (q1, q2, q3, q4).map(split) } // #let showtree(i, subtree) = tree($R_#i$, ..subtree.filter(x => type(x) == array).enumerate().map(((j, x)) => showtree(str(i) + str(j + 1), x))) // #showtree("", split(im)) #let showtree2(arr, idx: "") = { if arr.len() == 4 { tree($R_idx$, ..arr.enumerate().map(((i, tree)) => showtree2(tree, idx: idx + str(i + 1)))) } else { tree($R_idx$) } } #showtree2(split(im)) // #let showtree0(i, subtree) = { // subtree // let children = subtree.map(x => showtree(i + 1, x)) // assert(children.all(x => type(x) == content), message: "subtree must be a list of trees") // // tree($R_#i$, ..children) // } // #showtree(1, split(im)) /* #tree( "A", tree( "B", tree("D"), tree("E") ), tree( "C", tree("F"), tree("G"), tree("H"), ) ) */
https://github.com/bennyhandball/PA1_LoB_Finance
https://raw.githubusercontent.com/bennyhandball/PA1_LoB_Finance/main/PA/supercharged-dhbw/2.1.0/gender-equality-notice.typ
typst
#let gender-equality-notice(authors, title, date, language, many-authors, at-university, city, date-format) = { pagebreak() v(2em) text(size: 20pt, weight: "bold", if (language == "de") { "Disclaimer" } else { "Disclaimer" }) v(1em) par(justify: true, leading: 18pt,[ In der wissenschaftlichen Arbeit mit dem Titel ]) v(1em) align(center, text(weight: "bold", title) ) v(1em) show par: set block(spacing: 2em) par(justify: true, leading: 18pt,[ wird aus Gründen der besseren Lesbarkeit auf die gleichzeitige Verwendung der Sprachformen männlich, weiblich und divers (m/w/d) verzichtet und das generische Maskulinum verwendet. Weibliche und andersweitige Geschlechteridentitäten werden dabei ausdrücklich mitgemeint, soweit es für die Aussage erforderlich ist. Abbildungen, Codebeispiele und Tabellen, die den Lesefluss stören, befinden sich im Anhang. Ist dies der Fall, wird im Text zusätzlich auf den Anhang verwiesen. Ein Teil der Literatur, die für die Anfertigung dieser Arbeit genutzt wird, ist nur über die E-Book-Plattform o'Reilly abrufbar. Bei diesen Ressourcen existieren keine Seitennummern, es wird bei Verweisen stattdessen die Kapitelnummer angegeben. ]) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/vec_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 22-25 expected "(", "[", "{", "|", "||", or none // #set math.vec(delim: "%")
https://github.com/0rphee/prop-logic-paevty
https://raw.githubusercontent.com/0rphee/prop-logic-paevty/main/README.md
markdown
BSD 3-Clause "New" or "Revised" License
# prop-logic-paevty Build and run the executable: ``` cabal run ``` Parse, evaluate and create typst truth tables from plain-text logical propositions. Input: `"((not (P and Q)) then ((R or S) bithen not T))"`. ``` #let then = $arrow$ #let bithen = $arrow.l.r$ #table( columns: (auto, auto, auto, auto, auto, auto), inset: 10pt, align: horizon, [*$P$*], [*$Q$*], [*$R$*], [*$S$*], [*$T$*], [*$((not (P and Q)) then ((R or S) bithen not T))$*], $V$, $V$, $V$, $V$, $V$, align(center)[$V$], $V$, $V$, $V$, $V$, $F$, align(center)[$V$], $V$, $V$, $V$, $F$, $V$, align(center)[$V$], $V$, $V$, $V$, $F$, $F$, align(center)[$V$], $V$, $V$, $F$, $V$, $V$, align(center)[$V$], $V$, $V$, $F$, $V$, $F$, align(center)[$V$], $V$, $V$, $F$, $F$, $V$, align(center)[$V$], $V$, $V$, $F$, $F$, $F$, align(center)[$V$], $V$, $F$, $V$, $V$, $V$, align(center)[$F$], $V$, $F$, $V$, $V$, $F$, align(center)[$V$], $V$, $F$, $V$, $F$, $V$, align(center)[$F$], $V$, $F$, $V$, $F$, $F$, align(center)[$V$], $V$, $F$, $F$, $V$, $V$, align(center)[$F$], $V$, $F$, $F$, $V$, $F$, align(center)[$V$], $V$, $F$, $F$, $F$, $V$, align(center)[$V$], $V$, $F$, $F$, $F$, $F$, align(center)[$F$], $F$, $V$, $V$, $V$, $V$, align(center)[$F$], $F$, $V$, $V$, $V$, $F$, align(center)[$V$], $F$, $V$, $V$, $F$, $V$, align(center)[$F$], $F$, $V$, $V$, $F$, $F$, align(center)[$V$], $F$, $V$, $F$, $V$, $V$, align(center)[$F$], $F$, $V$, $F$, $V$, $F$, align(center)[$V$], $F$, $V$, $F$, $F$, $V$, align(center)[$V$], $F$, $V$, $F$, $F$, $F$, align(center)[$F$], $F$, $F$, $V$, $V$, $V$, align(center)[$F$], $F$, $F$, $V$, $V$, $F$, align(center)[$V$], $F$, $F$, $V$, $F$, $V$, align(center)[$F$], $F$, $F$, $V$, $F$, $F$, align(center)[$V$], $F$, $F$, $F$, $V$, $V$, align(center)[$F$], $F$, $F$, $F$, $V$, $F$, align(center)[$V$], $F$, $F$, $F$, $F$, $V$, align(center)[$V$], $F$, $F$, $F$, $F$, $F$, align(center)[$F$], ) ``` Preview: ![truth table preview](preview.png)
https://github.com/iceghost/resume
https://raw.githubusercontent.com/iceghost/resume/main/2-education.typ
typst
== Education #block[ === Computer Science Honors Program #h(1fr) \@ HCMUT Passed all required modules. #h(1fr) Oct 2021 - _current_ ] #block[ === Bachelor of Computer Science #h(1fr) \@ HCMUT Current GPA: 8.8 / 10.0. #h(1fr) Oct 2020 - _current_ ]
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/akatisty/akatistBohorodicka.typ
typst
#import "/style.typ": * #import "/styleAkatist.typ": * = Akatist k Presvätej Bohorodičke #align(horizon + center)[#primText[ #text(60pt)[Akatist k \ Presvätej\ Bohorodičke] ]] #let akatist = ( ( "index": 1, "kondak": [Tebe, Bohorodička, mocná Vládkyňa, spievame víťaznú pieseň. – Vyslobodila si nás od zlého, preto ti vrúcne ďakujeme, – hoci sme len nehodní služobníci. Ty si nepremožiteľná, – zbav nás všetkých bied, aby sme ti mohli spievať: Raduj sa, panenská Nevesta!], "zvolanie": [Raduj sa, panenská Nevesta!], "ikos": [Z neba bol poslaný archanjel, aby <NAME> povedal: Raduj sa! – A keď videl, že ty, Pane, po jeho slovách berieš na seba ľudské telo, – v údive stál a takto ju pozdravil:], "prosby": ( [Raduj sa, lebo skrze teba k nám radosť pri­chádza!], [Raduj sa, lebo skrze teba pominie prekliatie!], [Raduj sa, lebo si pozdvihla padnutého Adama!], [Raduj sa, lebo si zotrela slzy Evine!], [Raduj sa, ľudskému rozumu nepochopiteľná vý­šina!], [Raduj sa, hlbina, ktorú nepreniknú ani oči an­jelské!], [Raduj sa, nádherný trón kráľovský!], [Raduj sa, lebo si v živote nosila Stvoriteľa ves­míru!], [Raduj sa, zornica, ktorá nám východ Slnka zves­tuje!], [Raduj sa, lono, v ktorom sám Boh prebýval!], [Raduj sa, lebo skrze teba sa obnovuje všetko stvo­­renie!], [Raduj sa, lebo skrze teba sa Stvoriteľovi kla­niame!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 2, "kondak": [Najsvätejšia Panna, istá si svojím panen­stvom, smelo povedala Gabrielovi: – Záhadné sú tvoje slová a duši mojej ťažko pochopiteľné, – lebo mi oznamuješ, že počnem bez muža a budem Matkou, pričom voláš: Aleluja.], "zvolanie": none, "ikos": [Panna si túžobne želala pochopiť toto tajomstvo, preto povedala Božiemu sluhovi: – Povedz mi, ako sa môže v panenskom lone počať a narodiť z neho syn? – A on ju z bázňou a úctou pozdravil:], "prosby": ( [Raduj sa, vyvolená na uskutočnenie nevý­slov­ného tajomstva!], [Raduj sa, mlčanlivá viera prosiacich!], [Raduj sa, začiatok Kristových zázrakov!], [Raduj sa, ty, v ktorej sa začali plniť jeho príkazy!], [Raduj sa, rebrík, po ktorom sám Boh z neba zo­stúpil!], [Raduj sa, most, po ktorom ľudstvo zo zeme do neba prechádza!], [Raduj sa, zázrak, pri ktorom nenachádzajú slová ani anjeli!], [Raduj sa, lebo ty si prinútila démonov nariekať!], [Raduj sa, lebo si porodila svetlo zázračné!], [Raduj sa, lebo si zachovala v srdci tajomstvo!], [Raduj sa, lebo prevyšuješ všetkých mudrcov!], [Raduj sa, lebo osvecuješ mysle všetkých ve­riacich!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 3, "kondak": [Moc Najvyššieho zatônila Pannu, čo muža nepoznala, – jej nepoškvrnené lono sa stalo úrod­nou pôdou pre všetkých, čo túžia po spáse – a takto jej spievajú: Aleluja.], "zvolanie": none, "ikos": [Panna, ktorá v živote Boha nosila, ponáhľa­la sa k Alžbete. – Dieťa v Alžbetinom lone hneď rozpoznalo Máriin pozdrav, – zaplesalo a pohybmi namiesto spevu odpovedalo Bohorodičke:], "prosby": ( [Raduj sa, nevädnúca ratolesť stromu života!], [Raduj sa, životná sila nesmrteľného ovocia!], [Raduj sa, ty, ktorá si urobila Stvoriteľa milov­níkom ľudí!], [Raduj sa, lebo si porodila rozsievača života!], [Raduj sa, úrodná vinica, ktorá rodí bohatstvá mi­losti!], [Raduj sa, stôl, ktorý ponúka hojnosť zmierenia!], [Raduj sa, lebo ty si raj, čo zakvitol do bohatej úrody!], [Raduj sa, lebo dušiam pripravuješ útočisko istoty!], [Raduj sa, ľubovonné kadidlo modlitieb!], [Raduj sa, zmierenie sveta celého!], [Raduj sa, lebo sprostredkúvaš Božie milosrden­stvo hriešnikom!], [Raduj sa, lebo cez teba majú ľudia v Bohu dô­veru!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 4, "kondak": [<NAME> umáral sa pochybnosťami, chvel sa a trápil sa, – pozeral na teba, Nepoškvr­nená, a snoval plán, že ťa tajne prepustí, – ale poučený Svätým Duchom o tvojom počatí zvolal: Aleluja.], "zvolanie": none, "ikos": [Keď pastieri počuli spev anjelov o Kristo­vom narodení, ponáhľali sa k nemu. – Našli ho ako nepoškvrneného baránka v bezpeč­nom Márii­nom lone, – preto jej spievali hymnus:], "prosby": ( [Raduj sa, <NAME> a Pastiera!], [Raduj sa, košiar duchovných ovečiek!], [Raduj sa, postrach neviditeľných nepriateľov!], [Raduj sa, lebo brány raja otváraš!], [Raduj sa, lebo nebo so zemou sa raduje!], [Raduj sa, lebo pozemšťania s nebešťanmi ple­sajú!], [Raduj sa, podobná ústam apoštolov, čo neúnav­ne hovoria!], [Raduj sa, pre mučeníkov neporaziteľná dôvera!], [Raduj sa, našej viery pevná opora!], [Raduj sa, jasné poznanie ľúbosti!], [Raduj sa, lebo si pokorila podsvetie!], [Raduj sa, ty, ktorej slávou sme sa obliekli!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 5, "kondak": [Traja mudrci uzreli jasnú hviezdu a nasle­dovali ju, – svietila im na cestu a zastavila sa nad miestom, kde našli mocného Kráľa. – A keď sa približovali k Neprístupnému, klaňali sa mu a vo­lali: Aleluja.], "zvolanie": none, "ikos": [Keď chaldejskí synovia uvideli, že ten, ktorý stvoril ľudí a prijal na seba podobu služob­níka, spočíva v panenskom náručí, – ochotne mu odovzdali svoje dary a Blahoslavenej volali:], "prosby": ( [Raduj sa, <NAME>, ktorá nehasne!], [Raduj sa, zornica dňa tajomného a večného!], [Raduj sa, lebo ty si oheň pokušení zhasila!], [Raduj sa, lebo ty osvecuješ ctiteľov Najsvätejšej Trojice!], [Raduj sa, lebo skrze teba bol neľudský tyran svojej moci zbavený!], [Raduj sa, lebo si Krista, milujúceho ľudí, zrodila!], [Raduj sa, lebo si nás vyslobodila z otroctva po­hanstva!], [Raduj sa, snímajúca z nás blato nerestí!], [Raduj sa, lebo si urobila koniec modlárstvu!], [Raduj sa, lebo ty hasíš utrpení pramene!], [Raduj sa, Vodkyňa veriacich po cestách panen­stva!], [Raduj sa, všetkým ľudským pokoleniam vese­losť!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 6, "kondak": [Keď sa traja mudrci vrátili do Babylonu, – ohlasovali ľuďom, že sa splnilo proroctvo o prí­chode Krista Vykupiteľa, – ale Herodesa obišli, lebo ti nechcel spievať: Aleluja.], "zvolanie": none, "ikos": [Spasiteľ, ty si svetlom svojej pravdy ožiaril Egypt a odohnal si preč temnoty bludu. – Jeho modly nemohli odolať tvojej múdrosti, preto padli. – A tí, čo sa vyslobodili z ich zajatia, volali Bohorodičke:], "prosby": ( [Raduj sa, všetkých ľudí obnova!], [Raduj sa, víťazstvo nad démonmi!], [Raduj sa, lebo si porazila bludárske kráľovstvo!], [Raduj sa, lebo si odhalila márnosť modlárstva!], [Raduj sa, more, v ktorom sa potopil pyšný faraón!], [Raduj sa, skala, z ktorej pijú tí, čo túžia po živote!], [Raduj sa, ohnivý stĺp, ktorý nás vedie v tem­notách!], [Raduj sa, ochranný plášť širší ako obloha!], [Raduj sa, ty, ktorá prinášaš chlieb nad mannu cen­nejší!], [Raduj sa, služobnica sladkého a svätého po­krmu!], [Raduj sa, krajina zasľúbená!], [Raduj sa, lebo medom a mliekom oplývaš!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 7, "kondak": [Keď sa Simeon chystal opustiť tento svet a zatúžil po večnom živote, – položili ťa na jeho ruky ako dieťa, ale on v tebe spoznal skutočného Boha. – Plný údivu nad tvojou nevýslovnou múdrosťou volal: Aleluja.], "zvolanie": none, "ikos": [Svoju moc zjavil Stvoriteľ, nové stvorenie nám ukázal a my skrze neho jestvujeme. – On z nepoškvrneného lona vyklíčil, ale ho nepo­rušil, – a my, keď sme tento zázrak spoznali, oslavujeme ho a voláme:], "prosby": ( [Raduj sa, kvet, ktorý nikdy nevädne!], [Raduj sa, veniec striedmosti!], [Raduj sa, jasný vzor nášho vzkriesenia!], [Raduj sa, lebo nám zobrazuješ anjelov!], [Raduj sa, sladké ovocie stromu, ktoré živí ve­riacich!], [Raduj sa, košatý strom, v ktorého tieni mnohí oddych nachodia!], [Raduj sa, lebo si v živote nosila vykupiteľa za­jatých!], [Raduj sa, lebo si porodila vodcu zblúdených!], [Raduj sa, uprosenie spravodlivého sudcu!], [Raduj sa, lebo vyprosuješ odpustenie mnohým hriešnikom!], [Raduj sa, láskavé zahalenie našej nahoty!], [Raduj sa, láska, ktorá prevyšuje všetko po­znanie!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 8, "kondak": [Na neobyčajné stvorenie sme hľadeli. – Zabudnime aj my na tento svet a naše mysle obráť­me k nebu. – Najvyšší Boh preto prišiel v pokore na svet ako človek, aby priviedol k sebe všetkých, čo k nemu volajú: Aleluja.], "zvolanie": none, "ikos": [Ó, neopísateľné Slovo, ty celé v nebi aj na zemi prebývaš, – svojim príchodom na zem nezmenilo si svoju božskú podstatu, narodilo si sa z bohumilej Panny, ktorá počúva naše hlasy:], "prosby": ( [Raduj sa, nekonečnému Bohu príbytok!], [Raduj sa, brána presvätého tajomstva!], [Raduj sa, ustavičné volanie neverných k obrá­teniu!], [Raduj sa, nekonečná chvála veriacich!], [Raduj sa, ohnivý a svätý voz toho, ktorý na che­ru­bínoch spočíva!], [Raduj sa, preslávny príbytok toho, ktorému slú­žia serafíni!], [Raduj sa, nepriateľov zmierenie!], [Raduj sa, lebo v tebe sa spojilo panenstvo s mater­­stvom!], [Raduj sa, prostredníčka odpustenia pries­tup­kov!], [Raduj sa, lebo skrze teba sa nám raj otvára!], [Raduj sa, kľúč od Kristovho kráľovstva!], [Raduj sa, nádej večných radostí!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 9, "kondak": [Všetky anjelské zbory žasli nad veľkým tajomstvom vtelenia. – Videli, neprístupný Bože, ako si sa stal pre všetkých prístupným člove­kom. – Medzi nami prebývaš a počúvaš naše volanie: Aleluja.], "zvolanie": none, "ikos": [Pred tebou, Bohorodička, slávni rečníci zmĺkli ako nemé ryby. – Nedokázali pochopiť, že si aj po pôrode zostala pannou, – lež my obdivu­jeme toto tajomstvo a s vierou voláme:], "prosby": ( [Raduj sa, príbytok Božej múdrosti!], [Raduj sa, poklad Božej prozreteľnosti!], [Raduj sa, lebo múdrosť sveta sa v tebe vidí ne­múdrou!], [Raduj sa, lebo pred tebou aj slávni rečníci za­mĺkli!], [Raduj sa, veď pred tebou sú nevedomí aj mudrci!], [Raduj sa, lebo pred tebou zhasla sláva básnikov!], [Raduj sa, lebo si odhalila všetky výmysly!], [Raduj sa, lebo si naplnila siete rybárov!], [Raduj sa, lebo ty vytrhávaš duše z priepasti ničoty!], [Raduj sa, lebo ty obohacuješ mnohých poz­naním!], [Raduj sa, archa pre všetkých, čo túžia po spáse!], [Raduj sa, prístav na ceste životom!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 10, "kondak": [Obetoval seba samého, aby spasil svet. – Preto prišiel ako pastier a ako Boh v ľudskej podo­be. – Všetkých nás volá k sebe a počúva naše volanie: Aleluja.], "zvolanie": none, "ikos": [Bohorodička, Panna, ty si vzorom panien a všetkých, čo ťa vzývajú a utiekajú sa k tebe. – Stvoriteľ neba a zeme ťa ozdobil, Nepoškvrnená, – a prebývajúc v tvojom lone, naučil všetkých vzdávať ti slávu:], "prosby": ( [Raduj sa, <NAME>enstva!], [Raduj sa, brána spasenia!], [Raduj sa, začiatok duchovnej obrody!], [Raduj sa, prostredníčka Božích milostí!], [Raduj sa, lebo obnovuješ v hriechu počatých!], [Raduj sa, učiteľka sklamaných!], [Raduj sa, lebo si zvodcu duší zahnala!], [Raduj sa, lebo si porodila rozsievača čistoty!], [Raduj sa, palác zásnub prečistých!], [Raduj sa, lebo posilňuješ duše verné Pánovi!], [Raduj sa, ochrankyňa panien láskavá!], [Raduj sa, nevesta, svätých duší ozdoba!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 11, "kondak": [Presvätý Bože, ani najkrajšia pieseň nemô­že ospievať veľkosť tvojho zamilovania. – Hoci by sme ti ich venovali toľko, ako je piesku na zemi, nikdy neoceníme to, čo nám dávaš, – preto ti spievame: Aleluja.], "zvolanie": none, "ikos": [Najsvätejšia Panna, zjavuješ sa nám v temnotách ako svetelná pochodeň. – Zažíhaš duchovné svetlo a všetkých vedieš k poznaniu Boha. – Svojím leskom osvecuješ naše mysle, preto ťa ctíme a voláme:], "prosby": ( [Raduj sa, lúč duchovného slnka!], [Raduj sa, žiara neuhasínajúceho svetla!], [Raduj sa, blesk, čo ožaruje duše!], [Raduj sa, búrka, čo desí nepriateľa!], [Raduj sa, lebo si zjavila najjasnejšieho svetla záplavu!], [Raduj sa, prameň rieky mohutnej!], [Raduj sa, predobraz liečivého prameňa!], [Raduj sa, čo škvrny hriechov umývaš!], [Raduj sa, voda, v ktorej sa omýva svedomie!], [Raduj sa, čaša naplnená radosťou!], [Raduj sa, plnosť ľúbeznej vône Kristovej!], [Raduj sa, život plný svätej radosti!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 12, "kondak": [Pán milosrdenstva sa rozhodol odpustiť ľuďom všetky tresty. – Sám zostúpil k tým, čo opovrhli jeho láskou, – otvoril nám brány neba, preto počuje zo všetkých úst: Aleluja.], "zvolanie": none, "ikos": [Velebíme tvojho Syna i teba, Bohoro­dič­ka. – Vykupiteľ prebýval v tvojom lone, – posvätil ho, oslávil ťa a všetkých nás naučil prespevovať:], "prosby": ( [Raduj sa, Bohu i Slovu vhodný príbytok!], [Raduj sa, lebo si väčšia ako svätyňa svätých!], [Raduj sa, archa pozlátená Svätým Duchom!], [Raduj sa, nevyčerpateľná pokladnica života!], [Raduj sa, spravodlivým kráľom veniec nádhery!], [Raduj sa, zbožným kňazom víťazná odmena!], [Raduj sa, Božej Cirkvi pevná opora!], [Raduj sa, bezpečná hradba kráľovstva!], [Raduj sa, lebo s tvojou pomocou sa dosahujú ví­ťazstvá!], [Raduj sa, lebo skrze teba naši nepriatelia padajú!], [Raduj sa, môjho tela uzdravenie!], [Raduj sa, mojej duše záchrana!], [Raduj sa, panenská Nevesta!], ) ), ( "index": 13, "kondak": [Nekonečne velebená Bohorodička a Mat­ka najsvätejšieho Slova, –prijmi ako dar túto našu oslavu, – chráň nás od všetkých pokušení a vyslo­boď od večných múk, aby sme ti vždy spievali: Aleluja.], "zvolanie": none, "ikos": none, "prosby": none, "velkost": 9pt, "modlitba": "Prijmi, najblaženejšia, prečistá Pani a Vládkyňa, Bohorodička, tieto vznešené dary, ktoré patria jedine tebe, od nás, tvojich nehod­ných služobníkov. Ty si vyvolená zo všetkých pokolení, svojou vznešenosťou prevyšuješ všetko nebeské a pozemské tvorstvo, veď skrze teba k nám zostúpil Pán zástupov. Tvojím prostredníc­tvom sme poznali Božieho Syna a mohli sme prijať jeho presväté Telo a prečistú Krv. Preto si blažená z pokolenia na pokolenie, od Boha požehnaná. Jasnejšia si ako cherubíni a vznešenejšia ako sera­fíni. A teraz, presvätá starostlivá Bohorodička, neprestaň za nás ustavične orodovať, hoci sme iba tvojimi nehodnými služobníkmi, aby sme boli zbavení zla a súženia, a ochráň nás, krehkých, od všetkých jedovatých mámení démonov. Pomôž nám vytrvať v dobrom až do konca, aby sme boli spasení s tvojou pomocou a aby sme oslavovali, chválili, velebili, dobrorečili a klaňali sa v Trojici jedinému Bohu a Stvoriteľovi všetkého teraz i vždyc­ky i na veky vekov." ) ); #akatistGenerate(akatist)
https://github.com/flechonn/interface-typst
https://raw.githubusercontent.com/flechonn/interface-typst/main/BD/TYPST/exo3.typ
typst
#show terms: meta => { let title = label("Addition Exercise") let duration = label("30min") let difficulty = label("easy") let solution = label("1") let figures = label("") let points = label("10pts") let bonus = label("0") let author = label("") let references = label("") let language = label("english") let material = label("") let name = label("exo3") } = Exercise Calculez la dérivée de la fonction $f(x) = x^2 + 3x -2$ = Solution
https://github.com/C-Block-Language/specifications
https://raw.githubusercontent.com/C-Block-Language/specifications/main/src/specs.typ
typst
MIT License
#import "template.typ": * #show: Document.with( title: [C-Block Language Specifications] ) = Brief introduction to the C-Block Language. == The "Hello World!" of the C-Block Language. The simplest example of any programming language syntax is its _Hello World!_ example. We'll follow the example & do it too. To recreate the _Hello World!_ program, create a file `*/main.cb` that contains the next source code: ``` #include <std1_20_4.ch> @(load) foo::hello_world() { MINECRAFT::SAY("Hello World!"); } ``` When compiled, the output datapack will have the next files: 1. A function located at `data/foo/functions/hello_world.mcfunction` that contains:```hs say "Hello World!" ``` 2. A function tag located at `data/minecraft/tags/functions/load.mcfunction` that contains:```json { "values": [ "foo:hello_world" ] } ``` 3. A pack declaration file located at `pack.mcmeta` that contains:```json { "pack":{ "pack_format": 0, "description": "none" } } ``` Take notice that the pack declaration uses a pack_format 0 & has set the datapack description to `"none"`. Thus, there's missing lines of code to complete the example. Let's add 2 new lines of code to complete the example:``` #pack_format 26 #pack_description "Hello World" #include <1_20_4.ch> @(load) foo::hello_world() { MINECRAFT::SAY("Hello World!"); } ``` The 2 extra lines added at the top of the file are used to declare pack meta data, they must be added in the main Command Source file & any use of them on any other command source file will lead to an explicit abort. Now the output datapack will have the next files: 1. A function located at `data/foo/functions/hello_world.mcfunction` that contains:```hs say "Hello World!" ``` 2. A function tag located at `data/minecraft/tags/functions/load.mcfunction` that contains:```json { "values": [ "foo:hello_world" ] } ``` 3. A pack declaration file located at `pack.mcmeta` that contains:```json { "pack":{ "pack_format": 26, "description": "Hello World" } } ``` = Logic functions & Command source files. As shown in the previous chapter, logic functions consist of 4 parts: the directives of the function, the function name, the function parameters & , which will be explained in detail in this chapter. == Function directives: They are directives to specify how a certain logic function should behave on parsing & compilation --& if the directive is parented, it will also affect the children of the function--. They always start with an at symbol, following a couple of parenthesis with the directive name & the value of it. E. g:``` /* * * Set the directive "log" to true, which is used to * tell the compiler that it should add logs that * are sent to chat, to the function foo::bar & its * children functions * */ @(log=true) foo::bar() ... ``` In the _C-Block Standard CB-I_, there are 3 function directives, which are: // Note: in next push, add runtime-handling directive - _*`load` directive:*_ [Sweetener; Not parented; accepts a bool value; default: false] if set to `true`, the function will be added to the function tag `#minecraft:load`. - _*`tick` directive:*_ [Sweetener; Not parented; accepts a bool value; default: false] if set to `true`, the function will be added to the function tag `#minecraft:load`. - _*`log` directive:*_ [Parented; accepts a bool value or string value] if set to `true`, the function will contain extra `tellraw` log commands; if set if set a string, the function will contain extra `tellraw` log commands which will be sent only to players which have a tag that matches the string; if set to `false`, the function will not contain `tellraw` log commands, if the parent function has this directive set to true, it will override it for its own body & its children functions. // NOTE: in next push, add the missing parts = Command functions & Command header files. Command headers are one of the key structure of the C-Block Language to allow high modularity & configurability, as they act as the intermediate between the abstracted logic of c-block files & the compiled datapack. These files are declared using the file extension `.ch` (acronym of "Command Header") Command headers define the string output of a specific command (with the exception of `execute` and `data` due their complexity), take these 2 examples from the _Standard Command Header_ for the version 1.20.4: 1. Definition of the command `say`:``` // say <message> MINECRAFT::SAY( auto msg // <message> // ) { cmdLine( "say" + " " + msg // END // ) } ``` The first great difference between logic functions --which compile into `mcfunction` files-- & command functions is the CAPITALISATION on the function names, this is used to difference which functions should be treated as command functions & thus follow command function parsing. Take note that it uses `auto` data type, thus it should accept any data type as parameter (including macros). \ 2. Definition of the command `summon`:``` // summon <entity> MINECRAFT::SUMMON( string entity // <entity> // ) { cmdLine( "summon" + " " + entity // END // ) }```Which is followed by its respective overloads #footnote([Only command functions are allowed to have overloads following _C-Block Standard CB-I_; private logic function overloading will be standarised in the CB-II standard.]):``` // OVERRIDE: summon <entity> <vec3> MINECRAFT::SUMMON( string entity, // <entity> // auto pos[3] // <vec3> // ) { cmdLine( "summon" + " " + entity + " " + pos[0] + " " + pos[1] + " " + pos[2] // END // ); } // OVERRIDE: summon <entity> <x> <y> <z> MINECRAFT::SUMMON( string entity, // <entity> // auto x, // <x> // auto z, // <y> // auto z // <z> // ) { cmdLine( "summon" + " " + entity + " " + x + " " + y + " " + z // END // ); } // OVERRIDE: summon <entity> <vec3> <entity_nbt> MINECRAFT::SUMMON( string entity, // <entity> // auto pos[3], // <vec3> // nbt entity_nbt // <entity_nbt> // ) { if (NBTmatch_Path(entity_nbt, {}) == false) { throwFatal("Entity NBT must be a compound."); } cmdLine( "summon" + " " + entity + " " + pos[0] + " " + pos[1] + " " + pos[2] + " " + entity_nbt // END // ); } // OVERRIDE: summon <entity> <x> <y> <z> <entity_nbt> MINECRAFT::SUMMON( string entity, // <entity> // auto x, // <x> // auto y, // <y> // auto z, // <z> // nbt entity_nbt // <entity_nbt> // ) { if (entity_nbt.isCompound == false) { throwFatal("Entity NBT must be a compound."); } cmdOut( "summon" + " " + entity + " " + x + " " + y + " " + z + " " + entity_nbt // END // ); } ``` It is allowed the next operations related: - _Modify the Standard Command Header:_ as the Standard Command Header remains as an independent header from the compiler, it is alloed to modify the Standard Header itself to change the name, parameters & output of standard command functions. - _Create a custom command header:_ it can include overrides & overloads to command functions of the Standard Command Header aswell new custom command functions #footnote([This can be useful to create pseudo-APIs to incorporate external functions of data pack libraries that do not follow macro parameters natively.]). - _Create or override Command Functions on Command Source files:_ it is allowed to create command function on Command Source files, E. g:``` #include <std1_20_4.ch> // override MINECRAFT:SUMMON @override MINECRAFT:SUMMON (auto message) { cmdOut( "say" + " " + message // END // ) } ```
https://github.com/0x6b/typster
https://raw.githubusercontent.com/0x6b/typster/main/README.md
markdown
Apache License 2.0
# typster A naive Rust library that provides a way to work with [Typst](https://typst.app/) document and PDF file programmatically. ## Usage ```toml typster = { git = "https://github.com/0x6b/typster", tag = "vx.x.x", features = ["full"] } ``` ## Tested Environment The crate may function in other environments, but it has only been tested in the following environment: - rustc 1.81.0 (eeb90cda1 2024-09-04) - macOS Sequoia 15.0.1 (24A348) ## Supported Typst Version Version [0.12.0](https://github.com/typst/typst/releases/tag/v0.12.0) (October 18, 2024) This crate is for my personal use and learning purposes; it is not affiliated with the [Typst](https://typst.app/) project. ## Crate Features ### `full` Specify `full` to enable all the following features. ### `compile` You can compile a Typst document to a PDF or a PNG file; a limited subset of [typst-cli](https://github.com/typst/typst/tree/v0.12.0/crates/typst-cli). See [`examples/compile.rs`](examples/compile.rs) for usage. ```console $ cargo run --example compile --features embed_additional_fonts ``` ### `format` You can format a Typst document with [typstyle](https://github.com/Enter-tainer/typstyle). See [`examples/format.rs`](examples/format.rs) for usage. ```console $ cargo run --example format --features format ``` ### `pdf_metadata` You can update PDF metadata. Following metadata is supported: | Metadata | In Acrobat Reader | In Apple Preview | | ----------------- | ------------------------------ | ---------------------------------- | | Title | Title | Title | | Author | Author | Author | | Application | Application _and_ PDF Producer | PDF Producer _and_ Content creator | | Subject | Subject _and_ Description | Subject | | Copyright status | Copyright Status | (None) | | Copyright notice | Copyright Notice | Yes | | Keywords | Keywords | Keywords | | Creation date | Created | Creation date | | Modification date | Modified | Modification date | | Custom properties | Custom Properties | (None) | > [!Note] > > - All metadata will be overwritten, not merged. > - Both creation and modification date are set automatically to the current date _without_ time information which means time is always 0:00 UTC, for some privacy reasons (or my preference.) You can specify some of them with Typst. As of Typst v0.12.0, the following metadata is supported: - Title - Author - Keywords - Date See [Document Function – Typst Documentation](https://typst.app/docs/reference/model/document/) for details. See [`examples/update_metadata.rs`](examples/update_metadata.rs) for usage. ```console $ cargo run --example update_metadata --features pdf_metadata ``` ### `pdf_permission` You can set the following PDF 1.7 permissions: - user password, which is required to open the document. Set to `None` to allow anyone to open. - owner password, which is required to change permissions. Set to `None` to allow anyone to change. - content copying for accessibility. - page extraction. - document assembly. - commenting and form filling. - form field fill-in or signing. - other modifications. - printing (high, low, or disallow). - encrypt metadata. The only supported encryption algorithm is AES-256. See [`examples/set_permission.rs`](examples/set_permission.rs) for usage. ```console $ cargo run --example set_permission --features pdf_permission ``` ### `watch` You'll be able to preview your Typst document live. Changes for `typ` file, along with files with extension `cbor`, `csv`, `gif`, `htm`, `html`, `jpeg`, `jpg`, `json`, `png`, `svg`, `toml`, `txt`, `xml`, `yaml`, and `yml` in the same directory, recursively, will be watched. This is inspired by [ItsEthra/typst-live](https://github.com/ItsEthra/typst-live/). See [`examples/watch.rs`](examples/watch.rs) for usage. ```console $ cargo run --example watch --features watch ``` This feature also enables `compile` feature. ### Embedding Fonts You can embed additional fonts in the binary for easier deployment. Each feature also enables `compile` feature. - `embed_additional_fonts`: embed all fonts listed below. - `embed_cmu_roman`: [Computer Modern Roman](https://www.fontsquirrel.com/fonts/computer-modern) - `embed_ia_writer_duo`: [iA Writer Duo](https://github.com/iaolo/iA-Fonts/) - `embed_noto_sans_jp`: [Noto Sans JP](https://fonts.google.com/noto/specimen/Noto+Sans+JP) - `embed_noto_serif_jp`: [Noto Serif JP](https://fonts.google.com/noto/specimen/Noto+Serif+JP) - `embed_recursive`: [Recursive Sans & Mono](https://github.com/arrowtype/recursive/) - `embed_source_code_pro`: [Source Code Pro](https://fonts.google.com/specimen/Source+Code+Pro) > [!Note] > typst-cli [defaults](https://github.com/typst/typst-assets/blob/ac0c0c95da1444a5abe7c468c5fec471c1bf6c35/src/lib.rs#L67-L83) are always embedded. > [!Warning] > > - The crate won't search system fonts to ensure the reproducibility. All fonts you need should be explicitly added via [`CompileParams.font_paths`](https://github.com/0x6b/typster/blob/main/src/compile.rs#L21). > - Embedding fonts will produce a large binary. ## Testing Naive tests are available. You can run them with: ```console $ cargo test --all-features ``` Note that you have to install `exiftool` to run all tests. ## License - The crate itself is licensed under the Apache License version 2.0, as same as [Typst](https://github.com/typst/typst/). See [LICENSE](LICENSE) for details. - Fonts under the [`assets/fonts`](assets/fonts) directory are licensed under its own license. See the [`assets/fonts/README.md`](assets/fonts/README.md) for details. ## Acknowledgements - [typst/typst](https://github.com/typst/typst/) - [Enter-tainer/typstyle](https://github.com/Enter-tainer/typstyle) - [ItsEthra/typst-live](https://github.com/ItsEthra/typst-live/) - All the font authors and contributors ## Reference - [Extensible Metadata Platform (XMP) Specification: Part 1, Data Model, Serialization, and Core Properties](https://github.com/adobe/XMP-Toolkit-SDK/blob/main/docs/XMPSpecificationPart1.pdf), April, 2012
https://github.com/tingerrr/masters-thesis
https://raw.githubusercontent.com/tingerrr/masters-thesis/main/src/de/chapters/4-persistent-data-structures.typ
typst
#import "/src/util.typ": * #import "/src/figures.typ" Die in @chap:non-solutions beschriebenen Lösungsansätze haben alle etwas gemeinsam, sie bekämpfen Symptome statt Ursachen. Die Häufigkeit der Kopien kann reduziert werden, aber nie komplett eliminiert, da es eine fundamentale Operation ist. Es gilt also, ungeachtet der Häufigkeit einer solchen Operation, auf Seiten der Implementierung von T4gl-Arrays, Kopien von Daten nur dann anzufertigen, wenn das vonnöten ist. In @sec:t4gl:arrays wurde beschrieben, wie T4gl-Arrays bereits Daten teilen und nur bei Schreibzugriffen auf geteilte Daten Kopien erstellen. Das fundamentale Problem ist, dass bei Schreibzugriffen auf geteilte Daten, ungeachtet der Ähnlichkeit der Daten nach dem Schreibzugriff, alle Daten kopiert werden. Im Folgenden wird beschrieben, wie effiziente Datenteilung durch Persistenz @bib:fk-03 auf Speicherebene der T4gl-Arrays die Komplexität von Typ-3-Kopien auf logarithmische Komplexität senken kann. Es werden die Begriffe der Persistenz und Kurzlebigkeit im Kontext von Datenstrukturen eingeführt, sowie der aktuelle Stand persistenter Datenstrukturen beschrieben. Im Anschluss werden persistente Datenstrukturen untersucht, welche als Alternative der jetzigen Qt-Instanzen verwendet werden können. = Kurzlebige Datenstrukturen <sec:eph-data> Um den Begriff der Persistenz zu verstehen, müssen zunächst kurzlebige oder gewöhnliche Datenstrukuren entgegengestellt werden. Dafür betrachten wir den Vektor, ein dynamisches Array. #figure( figures.vector.repr, caption: [Der Aufbau eines Vektors in C++.], ) <fig:vec-repr> Ein Vektor besteht in den meisten Fällen aus 3 Komponenten, einem Pointer `ptr` auf die Daten des Vektors (in grau #cbox(gray) umranded), der Länge `len` des Vektors und die Kapazität `cap`. @fig:vec-repr zeigt den Aufbau eines Vektors in C++ #footnote[ Der gezeigte Aufbau ist nicht vom Standard @bib:iso-cpp-20 vorgegeben, manche Implementierungen speichern statt der Kapazität einen `end` Pointer, aus welchem die Kapaziät errechnet werden kann. Funktionalität und Verhalten sind allerdings gleich. ]. Operationen am Vektor wie `push_back`, `pop_back` oder Indizierung arbeiten direkt im Speicher, auf welchen `ptr` verweist. Reicht der Speicher nicht aus, wird er erweitert und die Daten werden aus dem alten Speicher in den neuen Speicher verschoben. Die in @lst:vec-ex gezeigten Aufrufe zu `push_back` schreiben die Werte direkt in den Speicher des Vektors. Zu keinem Zeitpunkt gibt es mehrere Instanzen, welche auf die gleichen Daten zeigen. Wird der Vektor `vec` auf `other` zugewiesen, werden alle Daten kopiert, die Zeitkomplexität der Kopie selbst ist proportional zur Anzahl der Elemente $Theta(n)$. #figure( figures.vector.example, caption: [ Ein C++ Program, welches einen `std::vector` anlegt und mit Werten befüllt. ], ) <lst:vec-ex> = Persistenz und Kurzlebigkeit <sec:per-eph> Wenn eine Datenstruktur bei Schreibzugriffen die bis dahin bestehenden Daten nicht verändert, gilt diese als persistent/langlebig @bib:kt-96[S. 202]. Daraus folgt, dass viele Instanzen sich gefahrlos die gleichen Daten teilen können. In den Standardbibliotheken verschiedener Programmiersprachen hat sich für dieses Konzept der Begriff _immutable_ (_engl._ unveränderbar) durchgesetzt. Im Gegensatz dazu stehen Datenstrukturen, welche bei Schreibzugriffen ihre Daten direkt beschreiben. Diese gelten als kurzlebig. Dazu gehört zum Beispiel der Vektor, beschrieben in @sec:eph-data. Persistente Datenstrukturen erstellen meist neue Instanzen für jeden Schreibzugriff, welche die Daten der vorherigen Instanz wenn möglich teilen. Die bis dato verwendeten QMaps sind persistent in dem Sinne, dass keine Instanz die Schreibzugriffe anderer Instanzen sehen kann, da diese immer vorher ihre geteilten Daten kopieren. Allerdings können clever aufgebaute Datenstrukturen bei einem Schreibzugriff dennoch Teile ihrer Daten mit anderen Instanzen teilen. Ein gutes Beispiel dafür bietet die einfach verkettete Liste (@fig:linked-sharing). #subpar.grid( figure(figures.list.new, caption: [ Eine Liste `l` wird über die Sequenz `[A, B, C]` angelegt. ]), figure(figures.list.copy, caption: [ Eine Kopie `m` von `l` teilt sich den Kopf der Liste mit `l`. ]), figure(figures.list.pop, caption: [ // NOTE: the double linebreaks are a bandaid fix for the otherwise unaligned captions Soll der Kopf von `m` gelöscht werden, zeigt eine neue Liste `n` stattdessen auf den Rest. \ ]), <fig:linked-sharing:pop>, figure(figures.list.push, caption: [ Soll ein neuer Kopf an `n` angefügt werden, kann der Rest durch die neue Instanz `o` weiterhin geteilt werden. ]), columns: 2, caption: [ Eine Abfolge von Operationen auf persistenten verketten Listen. ], label: <fig:linked-sharing>, ) Trotz der Veränderung von `m` in @fig:linked-sharing:pop teilen sich `l` und `n` weiterhin Daten, während QMaps in diesem Fall gar keine Daten mehr teilen würden. Im Folgenden werden durch die Datenteilung _Instanzen_ und _Daten_ semantisch getrennt: / Instanzen: Teile der Datenstruktur, welche auf die geteilten Daten verweisen und anderweitig nur Verwaltungsinformationen enthalten. / Daten: Die Teile einer Datenstruktur, welche die eigentlichen Elemente enthalten, in @fig:linked-sharing beschreibt das die Knoten mit einfacher Umrandung, während doppelt umrandete Knoten die Instanzen sind. Persistenz zeigt vor allem bei Baumstrukturen ihre Vorteile. Bei der Kopie der Daten eines persistenten Baums können je nach Tiefe und Balance des Baums große Teile des Baums geteilt werden. Ähnlich wie bei persistenten einfach verketteten Listen, werden bei Schreibzugriffen auf persistente Bäume nur die Knoten des Baums kopiert, welche zwischen Wurzel (Instanz) und dem veränderten Knoten in den Daten liegen. Das nennt sich eine Pfadkopie (_engl._ path copying). Betrachten wir partielle Persistenz von Bäumen am Beispiel eines Binärbaums, sprich eines Baums mit Zweigfaktoren (ausgehendem Knotengrad) zwischen $0$ und $2$. @fig:tree-sharing illustriert, wie am Binärbaum `t` ein Knoten `X` angefügt werden kann, ohne dessen partielle Persistenz aufzugeben. Es wird eine neue Instanz angelegt und eine Kopie der Knoten `A` und `C` angelegt, der neue Knoten `X` wird in `C` eingehängt und der Knoten `B` wird von beiden `A` Knoten geteilt. Durch die Teilung on `B` werden auch alle Kindknoten unter `B` geteilt. #subpar.grid( figure(figures.tree.new, caption: [ Eine Baumstruktur `t`, an welche ein neuer Knoten `X` unter `C` angefügt werden soll. ]), <fig:tree-sharing:new>, figure(figures.tree.shared, caption: [ Bei Hinzufügen des Knotens `X` als Kind des Knotens `C` wird ein neuer Baum `u` angelegt. ]), <fig:tree-sharing:shared>, columns: 2, caption: [ Partielle Persistenz teilt zwischen mehreren Instanzen die Teile der Daten, welche sich nicht verändert haben, ähnlich der Persistenz in @fig:linked-sharing. ], label: <fig:tree-sharing>, ) Für unbalancierte Bäume lässt sich dabei aber noch keine besonders gute Zeitkomplexität garantieren. Bei einem Binärbaum mit $n$ Kindern, welcher maximal unbalanciert ist (equivalent einer verketten Liste), degeneriert die Zeitkomplexität zu $Theta(n)$ für Veränderungen am Blatt des Baums. Ein perfekt balancierter Binärbaum hat eine Tiefe $d = log_2 n$, sodass jeder Schreibzugriff auf einem persistenten Binärbaum maximal $d$ Knoten (Pfad zwischen Wurzel und Blattknoten) kopieren muss. Je besser ein persistenter Baum balanciert ist, desto geringer ist die Anzahl der Knoten, welche bei Pfadkopien unnötig kopiert werden müssen. Die Implementierung von T4gl-Arrays durch persistente Bäume könnte demnach die Komplexität von Kopien drastisch verbessern. = Lösungsansatz Zunächst definieren wir Invarianzen von T4gl-Arrays, welche durch eine Änderung der Implementierung nicht verletzt werden dürfen: + T4gl-Arrays sind assoziative Datenstrukturen. - Es werden Werte mit Schlüsseln addressiert, nicht nur Ganzzahl-Indizes. + T4gl-Arrays sind nach ihren Schlüsseln geordnet. - Die Schlüsseltypen von T4gl-Arrays haben eine voll definierte Ordnungsrelation. - Iteration über T4gl-Arrays ist deterministisch in aufsteigender Reihenfolge der Schlüssel. + T4gl-Arrays verhalten sich wie Referenztypen. - Schreibzugriffe auf ein Array, welches eine flache Kopie eines anderen T4gl-Arrays ist, sind in beiden Instanzen sichtbar. - Tiefe Kopien von T4gl-Arrays teilen sichtbar keine Daten, ungeachtet, ob die darin enthaltenen Typen selbst Referenztypen sind. Die Ordnung der Schlüssel schließt ungeordnete assoziative Datenstrukturen wie Hashtabellen aus. Das Referenztypenverhalten ist dadurch umzusetzen, dass wie bis dato drei Ebenen verwendet werden (siehe @sec:t4gl:arrays), es werden lediglich die Qt-Instanzen durch neue Datenstrukturen ersetzt. Essentiell für die Verbesserung des worst-case Zeitverhaltens bei Kopien und Schreibzugriffen ist die Reduzierung der Daten, welche bei Schreibzugriffen kopiert werden müssen. Hauptproblem bei flachen Kopien, gefolgt von Schreibzugriff auf CoW-Datenstrukturen, ist die tiefe Kopie _aller_ Daten, selbst wenn nur ein einziges Element beschrieben oder eingefügt/entfernt wird. Ein Großteil der Elemente in den originalen und neuen kopierten Daten ist nach dem Schreibzugriff gleich. Durch höhere Granularität der Datenteilung müssen bei Schreibzugriffen weniger unveränderte Daten kopiert werden. Ein Beispiel für persistente Datenstrukturen mit granularer Datenteilung sind RRB-Vektoren @bib:br-11 @bib:brsu-15 @bib:stu-15, eine Sequenzdatenstruktur auf Basis von Radix-Balancierten Bäumen. Trotz der zumeist logarithmischen worst-case Komplexitäten können RRB-Vektoren nicht als Basis für T4gl-Arrays verwendet werden. Die Effizienz der RRB-Vektoren baut auf der Relaxed-Radix-Balancierung auf, dabei wird von einer Sequenzdatenstrukur ausgegangen. Da die Schlüsselverteilung in T4gl-Arrays nicht dicht ist, können die Schlüssel nicht ohne Weiteres auf dicht verteilte Indizes abgebildet werden. Etwas fundamentaler sind B-Bäume @bib:bm-70 @bib:bay-71. Bei persistenten B-Bäumen haben die meisten Operationen eine worst- und average-case Zeitkomplexität von $Theta(log n)$. Eine Verbesserung der average-case Zeitkomplexität für bestimmte Sequenzoperationen (`push`, `pop`) bieten 2-3-Fingerbäume @bib:hp-06. Diese bieten sowohl theoretisch exzellentes Zeitverhalten, als auch keine Enschränkung auf die Schlüsselverteilung. Im Folgenden werden unter anderem B-Bäume, sowie 2-3-Fingerbäume als alternative Storage-Datenstrukturen für T4gl-Arrays untersucht. = B-Bäume <sec:b-tree> Eine für die Persistenz besonders gut geeignete Datenstruktur sind B-Bäume @bib:bm-70 @bib:bay-71, da diese durch ihren Aufbau und Operationen generell balanciert sind. Schreiboperationen auf persistenten B-Bäumen müssen lediglich $Theta(log n)$ Knoten kopieren. B-Bäume können vollständig durch ihre Zweigfaktoren beschrieben werden, sprich, die Anzahl der Kindknoten, welche ein interner Knoten haben kann bzw. muss. Ein B-Baum ist wie folgt definiert @bib:knu-98[S. 483]: + Jeder Knoten hat maximal $k_max$ Kindknoten. + Jeder interne Knoten, außer dem Wurzelknoten, hat mindestens $k_min = ceil(k_max \/ 2)$ Knoten. + Der Wurzelknoten hat mindestens 2 Kindknoten, es sei denn, er ist selbst ein Blattknoten. + Alle Blattknoten haben die gleiche Entfernung zum Wurzelknoten. + Ein interner Knoten mit $k$ Kindknoten enthält $k - 1$ Schlüssel. Die Schlüssel innerhalb eines internen Knoten dienen als Suchhilfe. Sie sind Typen mit fester Ordnungsrelation und treten aufsteigend geordnet auf. @fig:b-tree zeigt einen internen Knoten eines B-Baums mit $k_min = 2$ und $k_max = 4$, ein sogannter 2-4-Baum. Jeder Schlüssel $s_i$ mit $1 <= i <= k - 1$ dient als Trennwert zwischen den Unterbäumen in den Kindknoten $k_j$ mit $1 <= j <= k$. Sei $x$ ein Schlüssel im Unterbaum mit der Wurzel $k_i$, so gilt $ &x <= s_i &&bold("wenn") i = 1 \ &x > s_(i - 1) &&bold("wenn") i = k_max \ &s_(i - 1) < x <= s_i &&bold("sonst") \ $ Die Schlüssel erlauben bei der Suche auf jeder Ebene den Suchbereich drastisch zu reduzieren. Die simpelste Form von B-Bäumen sind sogenannte 2-3-Bäume (B-Bäume mit $k_min = 2$ und $k_max = 3$), dabei ist die Angabe der Zweigfaktoren als Prefix des Baums eine übliche Konvention. #figure( figures.b-tree.node, caption: [Ein interner B-Baum-Knoten eines 2-4-Baums.], ) <fig:b-tree> Da die Schlüssel in B-Bäumen anhand ihrer Ordnungsrelation sortiert sind und demnach auch nicht auf Ganzzahlwerte beschränkt sind, können diese in persistenter Form durchaus eine gute Alternative zu QMaps darstellen. = 2-3-Fingerbäume 2-3-Fingerbäume wurden von !Hinze und !Paterson @bib:hp-06 eingeführt und sind eine Erweiterung von 2-3-Bäumen, welche für verschiedene Sequenzoperationen optimiert wurden. Die Autoren führen dabei folgende Begriffe im Verlauf des Texts ein: / Spine: Die Wirbelsäule eines Fingerbaums, sie beschreibt die Kette der zentralen Knoten, welche die sogenannten Digits enthalten. / Digit: Erweiterung von 2-3-Knoten auf 1-4-Knoten, von welchen jeweils zwei in einem Wirbelknoten vorzufinden sind. Obwohl ein Wirbelknoten zwei Digits enthält, sind, statt dieser selbst, direkt deren 1 bis 4 Kindknoten an beiden Seiten angefügt. Das reduziert die Anzahl unnötiger Knoten in Abbildungen und entspricht mehr der späteren Implementierung. Demnach wird im Folgenden der Begriff Digits verwendet, um die linken und rechten Kindknoten der Wirbelknoten zu beschreiben. / Measure: Wert, welcher aus den Elementen errechnet und kombiniert werden kann. Dieser dient als Suchhilfe innerhalb des Baums, durch welchen identifiziert wird, wo ein Element im Baum zu finden ist, ähnlich den Schlüsseln in @fig:b-tree. / Safe: Sichere Ebenen sind Ebenen mit 2 oder 3 Digits, ein Digit kann ohne Probleme entnommen oder hinzugefügt werden. Zu beachten ist dabei, dass die Sicherheit einer Ebene sich auf eine Seite bezieht, eine Ebene kann links sicher und rechts unsicher sein. / Unsafe: Unsichere Ebenen sind Ebenen mit 1 oder 4 Digits, ein Digit zu entnehmen oder hinzuzufügen kann Über- bzw. Unterlauf verursachen (Wechsel von Digits zwischen Ebenen des Baums, um die Zweigfaktoren zu bewahren). Der Name Fingerbäume rührt daher, dass imaginär zwei Finger an die beiden Enden der Sequenz gesetzt werden. Diese Finger ermöglichen den schnellen Zugriff an den Enden der Sequenz. Die zuvor definierten Digits haben dabei keinen direkten Zusammenhang mit den Fingern eines Fingerbaums, trotz der etymologischen Verwandschaft beider Begriffe. @fig:finger-tree zeigt den Aufbau eines 2-3-Fingerbaums, die in blau #cbox(blue.lighten(75%)) eingefärbten Knoten sind Wirbelknoten, die in türkis #cbox(teal.lighten(50%)) eingefärbten Knoten sind die Digits. In grau #cbox(gray) eingefärbte Knoten sind interne Knoten. Weiße Knoten #cbox(white) sind Elemente, die Blattknoten der Teilbäume. Knoten, welche mehr als einer Kategorie zuzuordnen sind, sind geteilt eingefärbt. #figure( figures.finger-tree.repr, caption: [Ein 2-3-Fingerbaum der Tiefe 3 und 21 Elementen.], ) <fig:finger-tree> Die Tiefe ergibt sich bei 2-3-Fingerbäumen aus der Anzahl der zentralen Wirbel. Jeder Wirbelknoten beschreiben eine Ebene $t$. Der Baum in @fig:finger-tree hat Ebene 1 bis Ebene 3. Aus der Tiefe der Wirbelknoten ergibt sich die Tiefe der Teilbäume (2-3-Baume) in deren Digits. Die Elemente sind dabei nur in den Blattknoten vorzufinden. In Ebene 1 sind Elemente direkt in den Digits enhalten --- die Teilbäume haben die Tiefe 1. In Ebene 2 sind die Elemente in Knoten verpackt, deren Digits enthalten Teilbäume der Tiefe 2. Die dritte Ebene enthält Knoten von Knoten von Elementen, sprich Teilbäume der Tiefe 3, und so weiter. Dabei ist zu beachten, dass der letzte Wirbelknoten einen optionalen mittleren Einzelknoten enthalten kann. Dieses Sonderdigit wird verwendet um die Bildung interner Ebenen zu überbrückung, da diese mindestens zwei Digits enhalten müssen. Die linken Digits jedes Wirbelknotens bilden dabei den Anfang der Sequenz, während die rechten Digits das Ende der Sequenz beschreiben. Der mittlere Teilbaum eines Wirbelknotens bildet die Untersequenz zwischen diesen beiden Enden ab. Die Nummerierung der Knoten in @fig:finger-tree illustriert die Reihenfolge der Elemente. Interne Knoten und Wirbelknoten enthalten außerdem die Suchinformationen des Unterbaums, in dessen Wurzel sie liegen. Je nach Wahl des Typs dieser Suchinformationen kann ein 2-3-Fingerbaum als gewöhnlicher Vektor, geordnete Sequenz, Priority-Queue oder Intervallbaum verwendet werden. Durch den speziellen Aufbau von 2-3-Fingerbäumen weisen diese im Vergleich zu gewöhnlichen 2-3-Bäumen geringere amortisierte Komplexitäten für Deque-Operationen auf. @tbl:finger-tree-complex zeigt einen Vergleich der Komplexitäten verschiedener Operationen über $n$ Elemente. Dabei ist zu sehen, dass `push`- und `pop`-Operationen auf 2-3-Fingerbäumen im average-case amortisiert konstantes Zeitverhalten aufweisen, im Vergleich zu dem generell logarithmischen Zeitverhalten bei gewöhnlichen 2-3-Bäumen. Fingerbäume sind symmetrische Datenstrukturen, `push` und `pop` kann problemlos an beiden Enden durchgeführt wurden. #let am1 = [#footnote(numbering: "*")[Amortisiert] <ft:amortized>] #let am2 = footnote(numbering: "*", <ft:amortized>) #figure( figures.complexity-comparison( ( "2-3-Baum": ( search: ($Theta(log n)$, $Theta(log n)$, $Theta(log n)$), insert: ($Theta(log n)$, $Theta(log n)$, $Theta(log n)$), remove: ($Theta(log n)$, $Theta(log n)$, $Theta(log n)$), push: ($Theta(log n)$, $Theta(log n)$, $Theta(log n)$), pop: ($Theta(log n)$, $Theta(log n)$, $Theta(log n)$), ), "2-3-Fingerbaum": ( search: ($Theta(log n)$, $Theta(log n)$, $Theta(log n)$), insert: ($Theta(log n)$, $Theta(log n)$, $Theta(log n)$), remove: ($Theta(log n)$, $Theta(log n)$, $Theta(log n)$), push: ($Theta(log n)$, $Theta(1)#am1$, $Theta(1)$), pop: ($Theta(log n)$, $Theta(1)#am2$, $Theta(1)$), ), ), ), caption: [Die Komplexitäten von 2-3-Fingerbäumen im Vergleich zu gewöhnlichen 2-3-Bäumen.], ) <tbl:finger-tree-complex> Ein wichtiger Bestandteil der Komplexitätsanalyse der `push`- und `pop`-Operationen von 2-3-Fingerbäumen ist die Aufschiebung der Bildung von Wirbelknoten durch Lazy Evaluation. Bei der amortisierten Komplexitätsanalyse werden diesen Aufschiebungen Credits in höhe ihrer sicheren Digits zugewiesen, welche für die Auswertung der aufgeschobenen Unterbäume in einem späteren Zeitpunkt verwendet wird. Eine naive C++-Definition von 2-3-Fingerbäumen ist in @lst:finger-tree beschrieben. `T` ist der Typ der im Baum gespeicherten Elemente und `M` der Typ der Suchinformationen für interne Knoten. Im Regelfall wären alle Klassendefinitionen über `T` und `M` per ```cpp template``` parametriert, darauf wurde verzichtet, um die Definition im Rahmen zu halten. #figure( figures.finger-tree.def.old, caption: [Die Definition von 2-3-Fingerbäumen in C++ übersetzt.], ) <lst:finger-tree> Die Werte des Measures werden in Unterbäumen zwischengespeichert und muss dabei ein Monoid sein, sprich, er benötigt eine assoziative Operation $f : (M, M) -> M$, welche zwei Elemente des Typs `M` zu einem kombiniert und ein Identitätselement $m_0$, sodass $f(m_0, m) = m and f(m, m_0) = m$. Diese Kombinationsoperation wird verwendet um die zwischengespeicherten Werte der Unterbäume aus deren Werten zu kombinieren. Die Elemente des Typen `T` müssen dann eine Abbildung von $g : T -> M$ zur Verfügung stellen um die Measures der Blattknoten zu bestimmen. Definieren wir `M` als $NN$ mit $f$ und $m_0$ als $ f(l, r) &: (NN, NN) -> NN \ f(l, r) &= l + r \ m_0 &= 0 \ $ und $g$ als $ g(t) &: T -> NN \ g(t) &= 1 \ $ so kann dieses Measure die Größe von Unterbäumen beschreiben und für den Fingerbaum können Vektor-Operationen wie `split_at`, `index` oder `length` implementiert werden @bib:hp-06[S. 15]. Für die in T4gl verwendeten Arrays sind Schlüssel nach Ordnungsrelation sortiert, daher ergibt sich aus der inherenten Sortierung die Operation $f(l, r) = r$. Leere Unterbäume werden ignoriert, damit kein Sonderwert für $m_0$ reserviert werden muss. Des Weiteren wird der obengenannte Monoid mitgeführt, um auf die Länge der Unterbäume effektiv zugreifen zu können. Für die Implementierung in T4gl werden andere Measure ignoriert, da diese nicht für das Laufzeitsystem relevant sind und die Implementierung unnötig erschweren würden. = Generische Fingerbäume <sec:finger-tree:generic> Im Folgenden wird betrachtet, inwiefern die Zweigfaktoren von Fingerbäumen generalisierbar sind, ohne die in @tbl:finger-tree-complex beschriebenen Komplexitäten zu verschlechtern. Höhere Zweigfaktoren der Teilbäume eines Fingerbaums reduzieren die Tiefe des Baums und können die Cache-Effizienz erhöhen. Wir beschreiben die Struktur eines Fingerbaums durch die Minima und Maxima seiner Zweigfaktoren $k$ (Zweigfaktor der internen Knoten) und $d$ (Anzahl der Digits auf jeder Seite einer Ebene) $ k_min &<= k &<= k_max \ d_min &<= d &<= d_max \ $ Die Teilbäume, welche in den Digits liegen, werden auf B-Bäume generalisiert, daher gilt für deren interne Knoten außerdem $k_min = ceil(k_max / 2)$, sowie $k_min = 2$ für deren Wurzelknoten. Die in @lst:finger-tree gegebene Definition lässt sich dadurch erweitern, das `std::array` durch `std::vector` ersetzt wird, um die wählbaren Zweigfaktoren zu ermöglichen. Diese können ebenfalls mit ```cpp template``` Parametern zur Kompilierzeit gesetzt werden, um den Wechsel auf Vektoren zu vermeiden. Die Definition von `Shallow` wird dadurch erweitert, dass diese bis zu $2d_min$ aufnimmt. #figure( figures.finger-tree.def.new, caption: [Die Definition von generischen Fingerbäumen in C++.], ) <lst:gen-finger-tree> Des weiteren betrachten wir für die Generalisierung lediglich Fingerbäume, welche für T4gl relevant sind. Statt generischen Measures für verschiedene Anwendungsfälle wird die Schnittstelle der Operationen auf geordnete einzigartige Schlüssel spezialisiert, aus `measure` wird der `key`, gespeicherte größten Schlüssel der Unterbäume. Kein Schlüssel kommt mehr als einmal vor. Während bei der generischen Variante in @lst:finger-tree Schlüssel- und Wertetyp in `T` enthalten sein müssten, sind diese hier direkt in `Node` zu finden. Die Operationen in den Abschnitten @sec:finger-tree:search[] bis @sec:finger-tree:insert-remove[] verwenden in den meisten Fällen mit `Node` Variablen als Eingabe oder Ausgabe. Dabei müssen alle Eingaben bei initialem Aufruf `Leaf`-Knoten sein, um die korrekte Tiefe der Unterbäume zu wahren. Gleichermaßen geben die initialen Aufrufe dieser Algorithmen immer `Leaf`-Knoten zurück. In beiden Fällen ermöglicht die Verwendung von `Node` statt der Typen `K` und `V` die Definition der Algorithmen durch simple Rekursion. In der Haskell-Definition ergibt sich zur Kompilierzeit aus durch den nicht-regulären Typen `FingerTree a` @bib:hp-06[S. 3] Funktionen, welche bei initialem Aufruf keine Knoten manuell ent- oder verpacken müssen. Eine äquivalente C++-Implementierung kann diese als interne Funktionen implementieren, welche die Eingaben in Knoten verpacken und die Ausgaben entpacken. Da Wirbelknoten mindestens $2d_min$ Digits enthalten, muss die Bildung dieser Minimalanzahl der Elemente im letzten Wirbelknoten überbrückt werden. Das erzielt man durch das Einhängen von Sonderdigits in den letzten Wirbelknoten, bis genug für beide Seiten vorhanden sind. Prinzipiell gilt für den letzten Wirbelknoten $ 0 <= d < 2d_min $ Ein generischer Fingerbaum ist dann durch diese Minima und Maxima beschrieben. Im Beispiel des 2-3-Fingerbaums gilt $ 2 &<= k &<= 3 \ 1 &<= d &<= 4 \ $ == Baumtiefe <sec:finger-tree:depth> Sei $n(t)$ die Anzahl $n$ der Elemente einer Ebene $t$, also die Anzahl aller Elemente in allen Teilbäumen der Digits eines Wirbelknotens, so gibt es ebenfalls die minimale und maximale mögliche Anzahl für diesen Wirbelknoten. Diese ergeben sich jeweils aus den minimalen und maximalen Anzahlen der Digits, welche Teilbäme mit minimal bzw. maximal belegten Knoten enthalten. $ n_"lmin" (t) &= k_min^(t - 1) \ n_"imin" (t) &= 2 d_min k_min^(t - 1) \ n_max (t) &= 2 d_max k_max^(t - 1) \ $ $n_"lmin"$ beschreibt das Minimum des letzten Wirbelknotens, da dieser nicht an die Untergrenze $2 d_min$ gebunden ist. $n_"imin"$ ist das Minimum interner Wirbelknoten. Für die kumulativen Minima und Maxima aller Ebenen bis zur Ebene $t$ ergibt sich $ n'_"lmin" (t) &= n_"lmin" (t) + n'_"lmin" (t - 1) \ n'_"imin" (t) &= n_"imin" (t) + n_"imin" (t - 1) + dots.c + n_"imin" (1) &= sum_(i = 1)^t n_"imin" (i) \ n'_max (t) &= n_max (t) + n_max (t - 1) + dots.c + n_max (1) &= sum_(i = 1)^t n_min (i) \ $ Das wirkliche Minimum eines Baums der Tiefe $t$ ist daher $n'_min (t) = n'_"lmin" (t)$, da es immer einen letzten nicht internen Wirbelknoten auf Tiefe $t$ gibt. @fig:cum-depth zeigt die Minima und Maxima von $n$ für die Baumtiefen $t in [1, 8]$ für 2-3-Fingerbäume. Dabei zeigen die horizontalen Linien das kumulative Minimum $n'_min$ und Maximum $n'_max$ pro Ebene. #figure( figures.finger-tree.ranges, caption: [Die möglichen Tiefen $t$ für einen 2-3-Fingerbaum mit $n$ Blattknoten.], ) <fig:cum-depth> == Über- & Unterlaufsicherheit <sec:over-under> Über- bzw. Unterlauf einer Ebene $t$ ist der Wechsel von Digits zwischen der Ebene $t$ und der Ebene $t + 1$. Beim Unterlauf der Ebene $t$ sind nicht genug Digits in $t$ enthalten. Es wird ein Digit aus der Ebene $t + 1$ entnommen und dessen Kindknoten in $t$ gelegt. Der Überlauf einer Ebene $t$ erfolgt, wenn in $t$ zu viele Digits enthalten sind. Es werden genug Digits aus $t$ entnommen, sodass diese in einen Knoten verpackt und als Digit in $t + 1$ gelegt werden können. Das Verpacken und Entpacken der Digits ist nötig, um die erwarteten Baumtiefen pro Ebene zu erhalten, sowie zur Reduzierung der Häufigkeit der Über- und Unterflüsse je tiefer der Baum wird. Die Anzahl der Digits hat dabei einen direkten Einfluss auf die amortisierten Komplexitäten von `push`- und `pop`-Operationen. #quote(block: true, attribution: [!Hinze und !Paterson @bib:hp-06[S. 7]])[ We classify digits of two or three elements (which are isomorphic to elements of type Node a) as safe, and those of one or four elements as dangerous. A deque operation may only propagate to the next level from a dangerous digit, but in doing so it makes that digit safe, so that the next operation to reach that digit will not propagate. Thus, at most half of the operations descend one level, at most a quarter two levels, and so on. Consequently, in a sequence of operations, the average cost is constant. The same bounds hold in a persistent setting if subtrees are suspended using lazy evaluation. [...] Because of the above properties of safe and dangerous digits, by that time enough cheap shallow operations will have been performed to pay for this expensive evaluation. ] Die Analyse !Hinze und !Paterson stützt sich darauf, dass persistente 2-3-Fingerbäume deren Unterbäume durch Lazy Evaluation erst dann Bilden und auswerten, wenn eine weitere Operation bis in diese Tiefe vorgehen muss. Für die Debit-Analyse von `push` und `pop` werden dabei den Unterbäumen so viele Credits zugewiesen wie diese sichere Knoten haben. Diese Credits werden für die spätere Auswertung verwendet, sodass die amortisierten Kosten über den realen Kosten bleiben. Damit sich die gleiche Analyse auf generische Fingerbäume übertragen lässt, müssen generische Fingerbäume ebenfalls bei jeder Operation auf einer unsicheren Ebene eine sichere Ebene zurücklassen. Wir erweitern den Begriff der Sicherheit einer Ebene $t$ mit $d$ Digits als #let dd = $Delta d$ $ d_min < d_t < d_max $ Ist eine Ebene sicher, ist das Hinzufügen oder Wegnehmen eines Elements trivial. Ist eine Ebene unsicher, kommt es beim Hinzufügen oder Wegnehmen zum Über- oder Unterlauf, Elemente müssen zwischen Ebenen gewechselt werden, um die obengenannten Ungleichungen einzuhalten. Erneut gilt zu beachten, dass die Sicherheit einer Ebene nur für eine Seite der Ebene gilt. Welche Seite, hängt davon ab, an welcher Seite eine Operation wie `push` oder `pop` durchgeführt wird. Wir betrachten den Über- und Unterlauf einer unsicheren Ebene $t$ in eine bzw. aus einer sicheren Ebene $t + 1$. Über- oder Unterlauf von unsicheren Ebenen in bzw. aus unsicheren Ebenen kann rekursiv angewendet werden bis eine sichere Ebene erreicht wird. Ähnlich den 2-3-Fingerbäumen wird durch die Umwandlung von unsicheren in sichere Ebenen dafür gesorgt, dass nur jede zweite Operation eine Ebene in dem Baum herabsteigen muss, nur jede vierte zwei Ebenen, und so weiter. Dieses Konzept nennt sich implizite rekursive Verlangsamung (_engl._ implicit recursive slowdown) @bib:oka-98 und ist Kernbestandteil der amortisierten Komplexität Deque-Operationen (`push`/`pop`). Damit die Digits einer Ebene $t$ in eine andere Ebene $t + 1$ überlaufen können, müssen diese in einen Digit-Knoten der Ebene $t + 1$ passen, es gilt $ k_min <= dd <= k_max \ $ <eq:node-constraint> Dabei ist $dd$ die Anzahl der Digits in $t$, welche in $t + 1$ überlaufen sollen. Essentiell ist, dass eine unsichere Ebene nach dem Überlauf wieder sicher ist, dazu muss $dd$ folgende Ungleichungen einhalten. Die Ebene $t + 1$, kann dabei sicher bleiben oder unsicher werden. $ t &: d_min <& d_max &text(#green, - dd) text(#red, + 1) &< d_max \ t + 1 &: d_min <& d_(t + 1) &text(#green, + 1) &<= d_max \ $ <eq:over> Gleichermaßen gelten für den Unterlauf folgende Ungleichungen. $ t &: d_min <& d_min &text(#green, + dd) text(#red, - 1) &< d_max \ t + 1 &: d_min <=& d_(t + 1) &text(#green, - 1) &< d_max \ $ <eq:under> Betrachtet man die Extrema von $dd$ in @eq:node-constraint, folgt aus deren Subtitution in den Gleichungen @eq:over[] und @eq:under[] eine Beziehung zwischen $d$ und $k$. $ d_max - d_min + 1 > k_max $ <eq:constraint> Für eine effiziente Implementierung von Deque-Operationen haben !Hinze und !Paterson die Zweigfaktoren der Digits von denen der Knoten um $plus.minus 1$ erweitert @bib:hp-06[S. 4]. Die Definitionen $d_min = k_min - 1$ und $d_max = k_max + 1$ halten nicht generell. Werden diese in @eq:constraint eingesetzt, ergibt sich $k_min < 3$ und folglich $ceil(k_max \/ 2) < 3$. Unter diesen Definitionen von $d$ in Abhängigkeit von $k$ können Zweigfaktoren ab $k_max > 7$ nicht dargestellt werden. Wählt man stattdessen $d_min = ceil(k_min \/ 2)$ (siehe @sec:finger-tree:split-concat, @eq:constraint2), ergibt sich $ d_max - ceil(ceil(k_max / 2) / 2) + 1 > k_max $ Die Zweigfaktoren $d_max$ und $k_max$ sind so zu wählen, dass Werte für $dd$ gefunden werden können, für die zuvorgenannten Ungleichungen halten. Betrachten wir 2-3-Fingerbäume, gilt $d_min = 1$, $d_max = 4$, $k_min = 2$ und $k_max = 3$, daraus ergibt sich trivialerweise $4 > 3$. !Hinze und !Paterson entschieden sich bei Überlauf für $dd = 3$, gaben aber an, dass $dd = 2$ ebenfalls funktioniert @bib:hp-06[S. 8]. Für generische Fingerbäume zeigt sich das in @eq:node-constraint. Beim Unterlauf hängt $dd$ von dem Zustand der Datenstruktur ab und kann nicht frei gewählt werden. Aus den oben genannten Ungleichungen lassen sich Fingerbäume mit anderen $d_max$ und $k_max$ wählen, welche die gleichen amortisierten Komplexitäten für Deque-Operationen aufweisen. == Suche <sec:finger-tree:search> Um ein gesuchtes Element in einem Fingerbaum zu finden, werden ähnlich wie bei B-Bäumen Hilfswerte verwendet, um die richtigen Teilbäume zu finden. In Fingerbäumen sind das die sogenannten Measures. Ein Unterschied zu B-Bäumen ist, wo diese Werte vorzufinden sind. In B-Bäumen sind direkt in den internen Knoten bei $k$ Kindknoten $k - 1$ solcher Hilfswerte zu finden, bei Fingerbäumen sind Measures stattdessen einmal pro internem Knoten vorzufinden. Des Weiteren sind die Measures in Fingerbäumen die Kombination der Measures ihrer Kindknoten. Für die Anwendung in T4gl werden geordnete Sequenzen benötigt, sodass der Measure interner Knoten den größten Schlüssel des Unterbaums angibt. Ist der Measure des Unterbaums kleiner als der Suchschlüssel, so ist der Schlüssel nicht in diesem Unterbaum enthalten. #let dsearch = math-func("digit-search") @alg:finger-tree:search zeigt, wie durch Measures ein Fingerbaum durchsucht werden kann. Dabei ist $dsearch$ Binärsuche anhand der Measures über eine Sequenz von Digits, gefolgt von gewöhnlicher B-Baumsuche (nach @sec:b-tree) der gefundenen Digit. Bevor aber $dsearch$ angewendet werden kann, muss der richtige Wirbelknoten gefunden werden. #figure( kind: "algorithm", supplement: [Algorithmus], figures.finger-tree.alg.search, caption: [Die `search` Operation auf einem Fingerbaum.], ) <alg:finger-tree:search> Das Zeitverhalten von @alg:finger-tree:search hängt von der Tiefe des Baums ab, da im worst-case der gesuchte Schlüssel im letzten Wirbelknoten vorzufinden ist. Die Baumtiefe steigt logarithmisch mit der Anzahl der Elemente in Abhängigkeit von den Zweigfaktoren (siehe @sec:finger-tree:depth). Je weiter ein Schlüssel von den beiden Enden entfernt ist, desto tiefer muss die Suche in den Baum vordringen. Dabei ist ein Schlüssel, welcher $d$ Positionen vom nächsten Ende entfernt ist $Theta(log d)$ Ebenen tief im Baum vorzufinden @bib:hp-06[S. 5], also effektiv $Theta(log n)$. == Push & Pop <sec:finger-tree:push-pop> Kernbestandteil von Fingerbäumen sind `push` und `pop` an beiden Seiten mit amortisierter Zeitkomplexität von $Theta(1)$. Die Algorithmen @alg:finger-tree:push-left[] und @alg:finger-tree:pop-left[] beschreiben die Operationen an der linken Seite eines Fingerbaums, durch die Symmetrie von Fingerbäumen lassen sich diese auf die rechte Seite übertragen. #let Deep = math-type("Deep") #let Shallow = math-type("Shallow") #let None = math-type("None") @alg:finger-tree:push-left ist in zwei Fälle getrennt, je nach der Art des Wirbelknotens $t$, in welchen der Knoten $e$ eingefügt werden soll. Ist der Wirbelknoten $Shallow$, wird der Knoten $e$ direkt als linkes Digit angefügt, sollten dabei genug Digits vorhanden sein, um einen Wirbelknoten des Typs $Deep$ zu erstellen, wird dieser erstellt, ansonsten bleibt der Fingerbaum $Shallow$. In beiden Fällen kommt es nicht zum Überlauf. Sollte der Wirbelknoten $Deep$ sein, wird der neue Knoten $e$ als linkes Digit angefügt. Wird die maximale Anzahl der Digits $d_max$ überschritten, kommt es zum Überlauf. Beim Überlauf werden $dd$ Digits in einen Knoten verpackt und in die nächste Ebene verschoben. Bei `push` Operationen muss außerdem beachtet werden, dass der Schlüssel des eingefügten Knotens die Ordnung der Schlüssel einhält. In der Implementierung kann diese Operation entweder als `private` markiert werden oder die Knoten vor dem Einfügen validieren. #figure( kind: "algorithm", supplement: [Algorithmus], figures.finger-tree.alg.pushl, caption: [Die `push`-Operation an der linken Seite eines Fingerbaumes.], ) <alg:finger-tree:push-left> @alg:finger-tree:pop-left ist auf ähnliche Weise wie @alg:finger-tree:push-left in zwei Fälle getrennt, $Shallow$ und $Deep$. Ist der Wirbelknoten $Shallow$, wird lediglich ein Digit von links abgetrennt und zurückgegeben. Bei null Digits wird der Wert $None$ zurückgegeben, in einer Spache wie C++ könnte das durch einen ```cpp nullptr``` oder das Werfen einer Exception umgesetzt werden. Bei einem $Deep$ Wirbelknoten wird eine linkes Digit entfernt. Bleiben dabei weniger als $d_min$ Digits vorhanden, erzeugt das entweder Unterlauf oder den Übergang zum $Shallow$ Fingerbaum. Ist die nächste Ebene selbst $Shallow$ und leer, werden die linken und rechten Digits zusammengenommen und diese Ebene selbst wird $Shallow$. Ist die nächste Ebene nicht leer, wird ein Knoten entnommen und dessen Kindknoten füllen die linken Digits auf. Sowohl `push` als auch `pop` gehen nach dem gleichen rekursiven Über/Unterfluss-Prinzip vor und hängen daher von der Baumtiefe ab, im worst-case ist jede Ebene unsicher und sorgt für einen Über- oder Unterfluss, daher ergibt sich eine Komplexität von $Theta(log n)$. Die amortisierte Komplexität stützt sich auf die gleiche Analyse wie diese von 2-3-Fingerbäumen, insofern Unterbäume mit Lazy Evaluation aufgeschoben werden und korrekte Zweigfaktoren gewählt wurden, können auch generische Fingerbüme `push` und `pop` in amortisiert $Theta(1)$ ausführen. #figure( kind: "algorithm", supplement: [Algorithmus], figures.finger-tree.alg.popl, caption: [Die `pop`-Operation an der linken Seite eines Fingerbaumes.], ) <alg:finger-tree:pop-left> Außerdem definieren wir `append` und `take` als wiederholte Versionen von `push` und `pop`. Diese sind gleicherweise symmetrisch für die rechte Seite zu definieren. Die Operation `take` nimmt dabei soviele Elemente aus $t$ wie möglich, aber nicht mehr als $n$. #figure( kind: "algorithm", supplement: [Algorithmus], figures.finger-tree.alg.appendl, caption: [Die `append`-Operation an der linken Seite eines Fingerbaumes.], ) <alg:finger-tree:append-left> Die worst-case Komplexität von @alg:finger-tree:concat ergibt sich aus der Anzahl der Elemente im Baum $n$ und derer in der Sequenz $"nodes"$ @alg:finger-tree:push-left als $Theta(abs("nodes") log n)$. #figure( kind: "algorithm", supplement: [Algorithmus], figures.finger-tree.alg.takel, caption: [Die `take`-Operation an der linken Seite eines Fingerbaumes.], ) <alg:finger-tree:take-left> Da @alg:finger-tree:take-left nur so viele Elemente entfernen kann wie im Baum vorhanden sind, ist der Faktor das Minimum aus der Anzahl der Elemente $n$ und dem Argument $"count"$, die Komplexität von `take` ist demnach $Theta(min("count", n) log n)$. == Split & Concat <sec:finger-tree:split-concat> #let Shallow = math-type("Shallow") Das Spalten und Zusammenführen zweier Fingerbäume sind fundamentale Operationen, welche vor allem für die Implementierung von `insert` und `remove` in @sec:finger-tree:insert-remove relevant sind. @alg:finger-tree:concat beschreibt, wie zwei Fingerbäume zusammengeführt werden, dabei muss in jeder Ebene eine Hilfssequenz $m$ übergeben werden, welche die Zusammenführung der inneren Digits der Bäume beschreibt, nachdem deren Kindknoten entpackt wurden. Beim initalen Aufruf wird die leere Sequenz $nothing$ übergeben. @alg:finger-tree:concat ruft sich selbst rekursiv auf, bis einer der Bäume $Shallow$ ist, in diesem Fall degeneriert der Algorithmus zu wiederholtem `push` und terminiert. Ähnlich wie bei @alg:finger-tree:push-left muss beachtet werden, dass die Zusammenführung der zwei Bäume die Ordnung der Schlüssel einhält. #figure( kind: "algorithm", supplement: [Algorithmus], figures.finger-tree.alg.concat, caption: [Das Zusammenfügen zweier Fingerbäume zu einem.], ) <alg:finger-tree:concat> Der Hilfsalgortihmus @alg:finger-tree:nodes[] verpackt Knoten für die Rekursion in die nächste Ebene in @alg:finger-tree:concat. Die Größe der zurückgegebenen Sequenz von verpackten Knoten hat dabei direkten Einfluss auf die eigene Komplexität (durch den rekursiven Aufruf in @alg:finger-tree:concat) und auf die Komplexität der nicht rekursiven Basisfälle in @alg:finger-tree:concat. #figure( kind: "algorithm", supplement: [Algorithmus], figures.finger-tree.alg.nodes, caption: [Ein Hilfsalgorithmus zum Verpacken von Knoten.], ) <alg:finger-tree:nodes> Bei 2-3-Fingerbäumen lässt sich zeigen, dass die mittlere Sequenz $m$ eine Obergrenze von 4 und eine Untergrenze von 1 hat. Zunächst betrachtet man, wie das Verpacken der Knoten sich auf deren Anzahl auswirkt. Sei $m_t$ die Anzahl der verpackten Knoten bei Rekursionstiefe $t$, gilt $ n_t &= k_t + m_(t - 1) \ m_t &= cases( &n_t \/ k_max & &bold("wenn") n_t mod k_max = 0, floor(&n_t \/ k_max) &+ 1 &bold("wenn") n_t mod k_max >= k_min, floor(&(n_t - k_min) \/ k_max) &+ 2 &bold("wenn") n_t mod k_max < k_min, ) $ <eq:nodes> dabei ist $k_t$ die Summe der Knoten links und rechts und $m_(t - 1)$ die Größe der Sequenz aus der vorherigen Tiefe. Beim initialen Aufruf ist die Sequenz leer, daher gilt $m_0 = 0$. Für 2-3-Fingerbäume verhält sich die Größe der mittleren Sequenz wie folgt. Auf jeder Ebene können zwischen $2d_min = 2$ und $2d_max = 8$ Elemente zu den verpackten Elementen der vorherigen Ebene hinzukommen. #figure( table(columns: 3, align: right, table.header[$t$][$min n_t => min m_t$][$max n_t => max m_t$], $0$, $0 => 0$, $0 => 0$, $1$, $2 + 0 => 1$, $8 + 0 => 3$, $2$, $2 + 1 => 1$, $8 + 3 => 4$, $3$, text(gray)[$2 + 1 => 1$], $8 + 4 => 4$, $4$, text(gray)[$2 + 1 => 1$], text(gray)[$8 + 4 => 4$], [...], [ad infinitum], [ad infinitum], ), caption: [ Beim Verpacken der Knoten ergibt sich eine Obergrenze für die Anzahl der verpackten Knoten. ], ) <tbl:nodes-term> Damit $n_t$ Knoten verpackt werden können, muss die übergebene Sequenz mindestens $k_min$ Knoten enthalten. Bei 2-3-Fingerbäumen reicht $k_min = 2d_min$ aus, um in jeder Ebene beim Zusammenführen der inneren Digits mindestens einen Knoten bilden zu können. @tbl:nodes-term zeigt, dass die Länge der mittleren Sequenz, je nach Belegung der inneren Digits, zwischen 1 und 4 liegt. Im generischen Fall muss aus $2d_min$ mindestens ein Knoten gebildet werden. Daraus folgt $ k_min <= 2d_min $ <eq:constraint2> Andernfalls können Fingerbäume nicht zusammengefügt werden. Experimentelle Ergebnisse deuten darauf hin, dass bei $k_max > 5$ and $d_max = k_max + 1$ eine Obergrenze ab $m_2 = 3$ existiert, aber ein Beweis konnte nicht formuliert werden. Ohne einen Beweis für die Obergrenze dieser Sequenz kann nicht nachgewiesen werden, dass @alg:finger-tree:concat generell in logarithmischer Zeit läuft, da über diese Sequenz im Basisfall der Rekursion iteriert wird. Es ist unklar, ob die Sequenz, welche durch @eq:nodes erzeugt wird, eine obere asymptotische Grenze von $Omicron(1)$ hat. Stellt sich heraus, dass diese Sequenz sich in die Größenordnung von $Theta(n)$ bewegt, tut das auch die Komplexität von @alg:finger-tree:concat. Wird allerdings ein $t$ gefunden, ab welchem diese Sequenz für gewählte Zweigfaktoren nicht weiter ansteigt, ist der Fingerbaum valide. Einen Fingerbaum zu teilen ist essentiell, um einzelne Elemente mit bestimmten Eigenschaften zu isolieren, wie es für `insert` und `remove` der Fall ist. @alg:finger-tree:split zeigt, wie ein Fingerbaum $t$ so geteilt wird, dass alle Schlüssel, welche größer als $k$ sind, im rechten Baum und alle anderen im linken Baum landen. Das folgt daraus, dass jeder Schlüssel nur einmal im Baum vorkommen darf und alle Schlüssel sortiert sind. Die Implementierung in @bib:hp-06 kann weder garantieren, dass die zurückgegebene Teilung die einzige, noch dass diese die erste Teilung ist, da diese nicht von monoton ansteigenden Schlüsseln ausgehen kann. #figure( kind: "algorithm", supplement: [Algorithmus], figures.finger-tree.alg.split, caption: [Die Teilung eines Fingerbaumes um einen Schlüssel.], ) <alg:finger-tree:split> == Insert & Remove <sec:finger-tree:insert-remove> !Hinze und !Paterson entschieden sich, `insert` und `remove` für geordnete Sequenzen durch `split`, `push` und `concat` zu implementieren. Da in @sec:finger-tree:split-concat kein Beweis vorliegt, dass @alg:finger-tree:concat in logarithmischer Komplexität läuft, können `insert` und `remove` ebenfalls nicht nachweislich auf diese Art mit logarithmischer Laufzeit implementiert werden. Unter der Annahme, dass so ein Beweis möglich ist, könnten `insert` und `remove` wie folgt implementiert werden. @fig:finger-tree:insert zeigt die Implementierung von `insert`. Dabei ist zu beachten, dass wenn ein Schlüssel bereits in $t$ existiert, dessen Wert ersetzt werden muss, da jeder Schlüssel nur maximal einmal vorhanden sein darf. #figure( kind: "algorithm", supplement: [Algorithmus], figures.finger-tree.alg.insert, caption: [`insert` als Folge von `split`, `push` und `concat`.], ) <fig:finger-tree:insert> In @fig:finger-tree:remove ist zu sehen, wie `remove` zu implementieren ist. Wie auch bei Insert wird geprüft, ob der erwünschte Schlüssel im linken Baum ist. Ähnlich der Implementierung von Algorithmus @alg:finger-tree:search[] und @alg:finger-tree:pop-left[] muss bei Nichtvorhandensein des Schlüssels $k$ ein $None$-Wert oder eine Fehler zurrückgegeben werden. #figure( kind: "algorithm", supplement: [Algorithmus], figures.finger-tree.alg.remove, caption: [`remove` als Folge von `split` und `concat`.], ) <fig:finger-tree:remove> Alternative Implementierungen wurden nicht untersucht, aber je nach Besetzung der Unterbäume können `insert` und `remove` auch diese Lücken ausnutzen um statt `split` und `concat` auf simple Pfadkopie zurückzugreifen. Die Häufigkeit der Lücken hängt dabei von der Wahl von $dd$ ab. Liegt $dd$ näher an $k_min$, können Blattknoten öfter im Nachhinein befüllt werden. == Echtzeitanalyse Die Einhaltung verschiedener Ungleichungen in @sec:over-under hat vor allem Einfluss auf die amortisierten Komplexitäten der Deque-Operationen. Das amortisierte Zeitverhalten hat für die Echtzeitanalyse keinen Belang. Allerdings kann ohne einen Beweis in @sec:finger-tree:split-concat keine Aussage darüber gemacht werden, ob die Operationen bei generischen Zweigfaktoren in ihren Komplexitätsklassen bleiben oder sogar schlechteres Verhalten als persistente B-Bäume vorweisen. Sollte ein Beweis für logarihmische Laufzeit von @alg:finger-tree:concat gefunden werden, können Fingerbäume exzellentes Zeitverhalten im Vergleich zu gewöhnlichen CoW-Datenstrukturen ohne granulare Persistenz vorweisen. Je nach Anforderungen des Systems könnten für verschiedene Operationen zulässige Höchstlaufzeiten festgelegt werden. Granular persistente Baumstrukturen wie Fingerbäume könnten prinzipell mehr Elemente enthalten, bevor diese Höchstlaufzeiten pro Operationen erreicht werden. Aus Sicht der Echtzeitanforderungen an die Operationen auf der Datenstruktur selbst, ist jede Datenstruktur mit logarithmischem Zeitverhalten vorzuziehen. Die Wahl von Fingerbäumen über B-Bäumen ist daher eher eine Optimierung als eine Notwendigkeit. Ohne den zuvorgenannten Beweis für die Obergrenze der inneren Sequenz bei `concat` sind jedoch entweder 2-3-Fingerbäume oder B-Bäume generischen Fingerbäumen vorzuziehen. = SRB-Bäume RRB-Bäume (_engl._ relaxed radix balanced trees) sind beinahe perfekt balancierte Suchbäume, welche für Sequenzdatenstrukturen wie Vektoren verwendet werden und wurden von !Bagwell _et al._ eingeführt @bib:br-11 @bib:brsu-15 @bib:stu-15. Um das Element an einem bestimmten Index zu finden, wird bei perfekter Balancierung eines Knotens der Teilindex direkt errechnet. Bei nicht perfekter Balancierung stützt sich die Suche auf Längeninformationen der Kindknoten. Dazu enthält jeder interne Knoten ein Array der kummulativen Anzahlen von Werten in dessen Kindknoten. Dabei wird nach Indizes gesucht, sprich, fortlaufende Ganzzahlwerte zwischen 0 und der Anzahl der Elemente $n$ in der Sequenz. Im Folgenden wird eine Erweiterung von RRB-Bäumen vorgestellt, SRB-Bäume (_engl._ sparse radix balanced trees), welche für nicht fortlaufende Schlüssel verwendet werden können. Ein SRB-Baum ist aufgebaut wie ein perfekt balancierter voll belegter RRB-Baum über alle Indizes, welche vom Schlüsseltyp dargestellt werden können, aber ohne die Knoten, die nicht belegt sind. Im Gegensatz zu RRB-Bäumen können Teilindizes auf jeder Ebene direkt errechnet werden, ohne dass die Länge der Kindknoten bekannt sein muss. Da aber nicht alle Knoten besetzt sind, muss auf jeder Ebene geprüft werden, ob der errechnete Teilindex auf einen besetzten Knoten zeigt. Durch die perfekte Balancierung ist die Baumtiefe $d$ nur von der Schlüsselbreite $b$ (die Anzahl der Bits im Schlüssel) und dem Zweigfaktor $k$ abhängig. $ d = log_k 2^b $ <eq:srb-tree:depth> @fig:srb-tree zeigt einen SRB-Baum über die Sequenz `[0, 16, 65296, 65519]` für `uint16` Schlüssel und mit einem Zweigfaktor von 16. Die belegten Knoten sind in türkis #cbox(teal.lighten(50%)) hervorgehoben. #figure( figures.srb-tree, caption: [Ein SRB-Baum für die 16 bit Schlüssel und einen Zweigfaktor von 16.], ) <fig:srb-tree> == Schlüsseltypen Durch die spezifische Art der Suche können nur Schlüsseltypen verwendet werden, welche anhand von Radixsuche Teilindizes errechnen lassen. Das beschränkt sich generell auf nicht vorzeichenbehaftete Ganzzahltypen. Für diese Schlüssel $u$ ergibt sich ein Teilindex $i$ auf Ebene $t$ wie folgt: $ u / k^(d - t) mod k $ Bei Zweigfaktoren $k = 2^l$ ergibt sich eine optimierte Rechnung, welche verschiedene Bitshifting Operationen verwendet: $ (u >> (l dot.op (d - t))) \& (k - 1) $ Sollte für einen Schlüsseltyp $T$ eine bijektive Abbildung $f$ und deren Inverses $f^(-1)$ existieren und es gilt $ forall t_1, t_2 in T : t_1 < t_2 <=> f(t_1) < f(t_2) $ dann kann durch diese Abbildungen auch der Schlüsseltyp $T$ durch einen SRB-Baum verwaltet werden. Ein simples Beispiel sind vorzeichenbehaftete Schlüssel, welche einfach um ihr Minimum verschoben werden, so dass alle möglichen Werte vorzeichenunbehaftet sind. Das setzt natürlich voraus, dass ein Minimum existiert, wie es bei Ganzzahlräpresentationen in den meisten Prozessoren der Fall ist. Ein Minimum und Maximum für die Schlüssel dieser Bäume bedeutet auch, dass die maximale Tiefe vor der Laufzeit bekannt ist. == Zeitverhalten Um zur Laufzeit den Blattknoten zu finden, in welchem sich ein Schlüssel befindet, wird pro Ebene per Radixsuche der Index dieser Ebene errechnet und geprüft ob dieser Index besetzt ist. Ist der Index nicht besetzt, endet die Suche, ansonsten fährt diese fort, bis der Blattknoten erreicht ist. Durch die perfekte Balancierung ist die Baumtiefe nur von der Schlüsselbreite abhängig, nicht von der Anzahl der gespeicherten Elemente. Operationen wie `insert`, `remove` oder `search` haben daher eine Zeitkomplexität von $Theta(d)$ mit $d$ aus @eq:srb-tree:depth. Gerade unter Echzeitbedingungen erleichtert das die Analyse enorm, durch die Wahl von Höchstschlüsselbreiten kann SRB-Bäumen konstantes worst-case Zeitverhalten für alle Operationen garantiert werden. Diese Schlüsselbreiten sind in den meisten Fällen von der Hardware vorgegeben und könnn in den üblichen Größen von 8, 16, 32, 64 und in experimentellen CPUs bis zu 128. == Speicherauslastung Seien $v$ der benötigte Speicher eines Werts und $p$ der benötigte Speicher eines Pointers in einem SRB-Baum. Wir definieren die Speicherauslastung $s_U$ als das Verhältnis zwischen den belegten Speicherplätzen $s_S$ und den gesamten Speicherplätzen $s_A$, welche von der Datenstruktur angelegt wurden. $ s_U (p, v) = (s_S (p, v)) / (s_A (p, v)) \ $ Im Idealfall liegt $s_U$ nahe 1, sprich 100%. Der in @fig:srb-tree gegebene SRB-Baum verbraucht pro Blattknoten $16 s_v$ Speicherplatz, ungeachtet der Belegung. Interne Knoten benötigen $16 s_p$ Speicherplatz. Bei ungünstiger Belegung, zum Beispiel einem Element pro möglichem Blattknoten, ergibt sich ein Speicherplatzverbrauch von $16^4 s_v + 16^3 s_p + 16^2 s_p + 16 s_p$ bei nur $16^3$ belegten Elementen. Bei Pointern mit $p = 8 "Byte"$ und Pointern als Werten ($v = p$) folgt eine Speicherauslastung von $ s_U (p, v) &= (16^3 v) / (16^4 v + 16^3 p + 16^2 p + 16 p) \ &= 0.058... \ &approx 6% \ $ Dabei sind Verwaltungsstrukturen ignoriert, welche die Belegung der Elemente enthalten, da diese verhältnismäßig klein sind. Für einen SRB-Baum mit einem Zweigfaktor $k$ und einer Schlüsselbreite $b$ und der sich daraus ergebenden Baumtiefe $d = ceil(log_k 2^b)$, ergibt sich eine Speicherauslastung im worst-case von: $ s_U (p, v) = (k^(d - 1) v) / (k^d v + sum_(n = 1)^(d - 1) k^n p) $ Gerade wegen dieser potentiell hohen Speicherverschwendung und der Einschänkung auf die Schlüsseltypen wurden SRB-Bäume als Implementierung für T4gl-Arrays nicht weiter verfolgt.
https://github.com/mismorgano/UG-DifferentialGeometry23
https://raw.githubusercontent.com/mismorgano/UG-DifferentialGeometry23/main/Examenes/SegundoExamen-ABR.typ
typst
#import "@preview/lemmify:0.1.4": * #let title = [ Geometría Diferencial\ Segundo Examen ] #let author = [ <NAME> ] #let ( theorem, lemma, corollary, remark, proposition, example, proof, rules: thm-rules ) = default-theorems("thm-group", thm-numbering: thm-numbering-heading) #show: thm-rules #set text(font: "New Computer Modern", size: 12pt) #let eps = $epsilon$ #let pi(x, y) = $angle.l #x, #y angle.r$ #let circ = $ space circle.stroked.small space$ #let x = $mono(bold(x))$ #align(center, text(17pt)[ *#title*\ #author ]) == Problema 1 Sea $S subset RR^3$ una superficie regular y sea $P subset RR^3$ un plano dado por la ecuación $P = {x in RR^3: pi(x, v) = c }$ ($v in RR^3 - {0}$, $c in RR$). Suponer que para todo $x in S$ se tiene que $pi(x, v) >= c$. Probar que si $p in S sect P$ entonces $T_p S = P$. #proof[ Primero veamos que $v$ es ortogonal a $P$, por hipótesis tenemos que $p in P$, luego si $q in P$, notemos que $ pi(v, p-q) = pi(v, p) - pi(v, q) = c - c = 0, $ lo anterior nos dice que dado $w in T_p S$, probar que $w in P$ equivale a probar que $pi(v, w) = 0$. Sea $gamma:-(eps, eps) -> S$ regular tal que $gamma(0) = p$ y $gamma'(0) = w$, definamos $g(t) = pi(gamma(t),v)$, como $gamma$ es regular tenemos que $g$ es diferenciable y ademas se cumple que $ g'(t) = pi(gamma'(t), v)$, más aun como $gamma subset S$ tenemos que $g >= c$, pero $g(0) = pi(p, v) = 0$, por lo cual $g(0)$ es un mínimo local, lo anterior implica que $g'(0) = 0$, entonces $ 0 = g'(0) = pi(gamma'(0), v) = pi(w, v), $ como $w$ fue arbitrario tenemos que $T_p S subset P$. Además como $T_p S$ es un plano, se cumple que $T_p S = P$, como queremos. ] == Problema 2 Sea $S$ una superficie regular y $f: S -> R$ una función suave. + Dado $p in S$ considerar su diferencial $D_p f: T_p S -> R.$ Probar que existe un único $w in T_p S$ tal que para todo $v in T_p S$ se tiene que $pi(v, w) = D_p f(v)$. A $w$ se lo llama el gradiente de $f$ en $p$, $nabla f(p)$. + Si $S$ es compacta probar que existe $p in S$ tal que $nabla f(p) = 0$. + Probar que $nabla f: S -> RR^3$ es un mapa suave. #proof[ + Dado $p in S$ y $v in T_p S$, sea $gamma: (-eps, eps) -> S$ tal que $gamma(0) = p$ y $gamma'(0) = v$, por regla de la cadena tenemos que $ D_p f (v) &= d/(d t) f(gamma(t))|_(t = 0) = d/(d t) f(x(t), y(t), z(t))|_(t = 0) \ &= f_x (gamma(0)) x'(0) + f_y (gamma(0)) y'(0) + f_z (gamma(0)) z'(0) \ &= (f_x (p), f_y (p), f_z (p)) dot (x'(0), y'(0), z'(0)) \ &= (f_x (p), f_y (p), f_z (p)) dot gamma'(0) \ &= (f_x (p), f_y (p), f_z (p)) dot v $ de donde podemos notar que $(f_x (p), f_y (p), f_z (p)) = nabla f (p) $ es el vector buscado pues $v in T_p S$ fue arbitrario. Solo falta ver que $(f_x (p), f_y (p), f_z (p)) in T_p S$. + Dado que $S$ es compacta y $f$ es suave en particular es continua, luego alcanza su máximo, digamos que en $p in S$. Dado $w in T_p S$, sea $gamma:-(eps, eps) -> S$ regular tal que $gamma(0) = p$ y $gamma'(0) = w$, como $f$ alcanza su máximo en $p = gamma(0)$ se cumple que $(f circ gamma)'(0) = 0$, entonces $D_p f (w) = 0 $. Por el inciso anterior tenemos que $D_p f(w) = nabla f(p)dot w = 0$, lo cual es valido para todo $w in T_p S$, lo cual implica que $nabla f(p) = 0$, como queremos. $$ + Dado $p in S$, sea $#x: U subset RR^2 -> #x (U) subset S$ con $p in #x (U)$ un difeomorfismo, veamos que $nabla circ #x: U -> R$ es diferenciable en $q := #x^(-1)(p)$. ]