repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/Noxsios/cv
https://raw.githubusercontent.com/Noxsios/cv/main/cv.typ
typst
MIT License
#import "@preview/splash:0.3.0": tailwind #set document(title: "<NAME> CV", author: "<NAME>", keywords: ("software engineer", "razzle", "<NAME>", "cv", "resume")) #set page( margin: (x: 0.5in, y: 0.5in), footer: [ #set text(8pt) #let head = read(".git/HEAD").trim() #if head.contains(": ") { head = head.split(": ").at(1).trim() } else { head = head.slice(0, 7) } #if head == "refs/heads/main" { head = read(".git/refs/heads/main").trim().slice(0, 7) } #let url = "https://github.com/Noxsios/cv/tree/"+head `git checkout` #link(url)[#raw(head)] ] ) #set text( size: 11pt, weight: 300, fill: tailwind.slate-950, font: "PT Sans", fallback: true, ) #show heading: it => { set text(weight: 400) smallcaps(it) } #let h2(header) = { rect( width: 100%, stroke: (left: none, top: none, right: none, bottom: (paint: black, thickness: 1pt, cap: "round")), [== #header] ) } #let quad(tl: "tl", tr: "tr", bl: "bl", br: "br") = { grid( columns: (70%, 30%), align(left)[ #tl \ #emph(strong(text(tailwind.slate-700, bl))) \ ], align(right)[ #text(tailwind.slate-700, tr) \ #emph(text(tailwind.slate-700, br)) ] ) } #set list( marker: ([•], [◦]) ) #grid( columns: (1fr, 1fr), align(left)[ #smallcaps( text( size: 16pt, [Harry `"razzle"` Randazzo] ) ) \ #link("https://razzle.cloud") \ `$ curl -sL meta.razzle.cloud` ], align(right)[ Email : #link("mailto:<EMAIL>") \ Mobile : +1-213-986-8048 ] ) #h2[Experience] #let pe( header: quad, events: array, ) = { header v(0.5em) list( ..events, marker: [◦], ) } #show link: underline #pe( header: quad( tl: [Defense Unicorns], tr: [Remote], bl: [Software Engineer], br: [2022 --- Present], ), events: ( [Architected and implemented core features, refactored legacy code, mentored new developers, engineering technical lead on #link("https://docs.zarf.dev")[Zarf]: a tool to package cloud native applications and deployments, delivering DevSecOps to air gap environments.], [Won multiple company-wide hackathons, including one that resulted in Defense Unicorns first AI web application deployed to a DoD customer.], )) #pe( header: quad( tl: [USAF --- Platform One], tr: [San Antonio, TX], bl: [Software Developer], br: [2021 --- 2022], ), events: ( [Wrote a Python command-line interface (CLI) for the automation of product releases and release notes generation, greatly expediting the release process on a bi-weekly basis.], [Built a #link("https://docs-bigbang.dso.mil")[documentation compiler] for the Big Bang product; assembles the documentation for Big Bang and its packages (20+) into a single, versioned, searchable and clean site.] )) #pe( header: quad( tl: [USAF --- 1st Combat Communications Squadron], tr: [Ramstein AB, Germany], bl: [Tactical Computer Networking Technician #sym.arrow.r Software Developer], br: [2019 --- 2021], ), events: ( [Designed and implemented a web application that combined data from 5+ Air Force systems, producing a simple, searchable, and printable dashboard of an organization's deployment readiness and personnel administrative status.], [Core network architect for the team that designed and deployed the DoD's first counter small unmanned aerial system (cSUAS) platform.], [Sole network technician for deployed U.S. emergency medical personnel during NATO's largest medical emergency field exercise in its history (2500+ participants, 39 partner nations).], )) #h2[Education] #quad( tl: [University of Maryland Global Campus], tr: [Adelphi, MD], bl: [Bachelor of Science in Computer Networks & Cybersecurity; GPA: 4.0], br: [2020 --- 2023] ) #quad( tl: [Airmen Coders], tr: [Remote (Germany \<--\> U.S.A.)], bl: [Software Development Immersive Course Graduate], br: [May 2020 --- Aug. 2020] ) #h2[Projects] #link("https://vai.razzle.cloud")[vai] - A simple task runner written in Go. Imagine Makefile and GitHub Actions had a baby. #link("https://blog.razzle.cloud")[blog.razzle.cloud] - My personal website and blog. Built with Zola, hosted by Vercel. #link("https://palx-pwa.pages.dev")[palx-pwa.pages.dev] - Given a base color, generate a palette, render all the shades, and provide download buttons for a variety of formats. Written in Svelte with SvelteKit. #link("https://dsn-converter.pages.dev")[dsn-converter.pages.dev] - Offline first web app that allows for conversion of European Defense Switched Network (DSN) phone numbers to their commercial equivalent. Written in React with TypeScript. #h2[Skills] #let skill = it => { box( // fill: tailwind.slate-950, stroke: tailwind.slate-950, inset: (x: 0.5em, y: 0.5em), radius: 4pt, text( // fill: tailwind.slate-100, it ) ) } Experienced building services and applications with the following technologies: #grid( columns: 7, column-gutter: 0.5em, skill[Go], skill[OCI/Docker], skill[JavaScript/TypeScript], skill[Svelte/SvelteKit], skill[REST APIs], skill[Kubernetes], skill[Python], )
https://github.com/tingerrr/chiral-thesis-fhe
https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/src/core/component.typ
typst
#import "component/abstract.typ": make-abstract #import "component/acknowledgement.typ": make-acknowledgement #import "component/appendix.typ": make-appendix #import "component/affidavit.typ": make-affidavit #import "component/glossary.typ": make-glossary #import "component/table-of-contents.typ": make-table-of-contents #import "component/title-page.typ": make-title-page #import "component/outline.typ": make-outline
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/terms.typ
typst
Apache License 2.0
// Test term list. --- // Test with constructor. #terms( ([One], [First]), ([Two], [Second]), ) --- // Test joining. #for word in lorem(4).split().map(s => s.trim(".")) [ / #word: Latin stuff. ] --- // Test multiline. #set text(8pt) / Fruit: A tasty, edible thing. / Veggie: An important energy source for vegetarians. --- // Test style change. #set text(8pt) / First list: #lorem(6) #set terms(hanging-indent: 30pt) / Second list: #lorem(5) --- // Test grid like show rule. #show terms: it => table( columns: 2, inset: 3pt, ..it.children.map(v => (emph(v.term), v.description)).flatten(), ) / A: One letter / BB: Two letters / CCC: Three letters --- / Term: Not in list /Nope --- // Error: 8 expected colon / Hello
https://github.com/domanteli0/views-presentation
https://raw.githubusercontent.com/domanteli0/views-presentation/main/views.typ
typst
// Get Polylux from the official package repository #import "@preview/polylux:0.3.1": * #import "@preview/polylux:0.3.1": polylux-slide as slide // Make the paper dimensions fit for a presentation and the text larger #set page(fill: rgb(39,40,34)) #set text(fill: rgb(255, 255, 255)) #let TEXT_SIZE = 23pt #set text(font: "Inria Sans") #set text(size: TEXT_SIZE) #show heading: set text(size: 30pt) #set page(paper: "presentation-16-9") #pdfpc.config() #set quote(block: true, quotes: true) #show quote: set emph() #show quote: set pad(x: 1em) #let code(lang: "none", size: TEXT_SIZE, width: auto, raw_text: "") = { block(radius: 5pt, fill: rgb(22,21,15), inset: 10pt, width: width)[ #align(left + top)[ #set text(size: size) #raw(raw_text, lang: lang) ] ] } #slide[ #align(horizon + center)[ #box(width: 70%)[ = Views: A way for pattern matching to cohabit with data abstraction ] by <NAME> #v(1em) ] #pdfpc.speaker-note( "~~~ some notes ~~~" ) ] // #pagebreak() // === Panašumai tarp `Idris` ir `Miranda` #slide[== Pattern matching'as #align(horizon + center)[ #grid(columns: 3, rows: 1, gutter: 0.5em, [ #set text(size: 35pt) $ x^0 &= 1 \ x^(n+1) &= x dot x^n $ ], [ #set text(size: 35pt) $->$ ], [ #set text(size: 30pt) #code(lang: "idris", raw_text: read("ex/ind.idr")) ] ) ] #pdfpc.speaker-note( "~~~ some notes ~~~" ) ] #slide[== Pattern matching'as vs abstrakcija #quote(attribution: "<NAME>")[ Pattern matching depends on making public a free data type representation, while data abstraction depends on hiding the representation. ] ] #slide[ == Views #align(horizon + center)[ #set text(size: 27pt) #box(width: 75%)[ Paslėpti implementacijos detales _*ir*_ leisti pattern match'inti ant tam tikrų duomenų ] ] #quote(attribution: [<NAME>])[ A view allows any type to be viewed as a free data type, thus combining the clarity of pattern matching with the efficiency of data abstraction. ] ] #slide[ == Sintaksė #columns(2)[ *Miranda* #code(lang: "miranda", size: 20pt, raw_text: read("ex/syntax1.m").split("\n").join("\n")) #colbreak() *Idris* #code(lang: "idris", size: 20pt, raw_text: read("ex/syntax1.idr")) ] ] #slide[ == Sintaksė *Miranda* #grid(columns: 2, column-gutter: 1em, [ #code(lang: "miranda", size: 20pt, raw_text: read("ex/syntax2_1.m")) ],[ #code(lang: "miranda", size: 20pt, raw_text: read("ex/syntax2_2.m")) ]) ] #slide[=== Int $<->$ Nat #grid(columns: 2, [ #code(raw_text: "view int ::= Zero | Succ int in n = Zero, if n = 0 = Succ (n - 1), if n > 0 out Zero = 0 out (Succ n) = n + 1 ") #code(raw_text: read("ex/fib1.m")) ], []) #pdfpc.speaker-note( "NOTE: rekursyviai konvertuojama (n - 1)" ) ] #slide[=== Int $<->$ Nat #code(size: 20pt, raw_text: "viewtype ::= Zero | Succ int viewin n = Zero, if n = 0 = Succ (n - 1), if n > 0 viewout Zero = 0 viewout (Succ n) = n + 1 ") #code(size: 20pt, raw_text: "fib m = case viewin m of Zero => viewout Zero Succ m' => case vienin m' of Zero => viewout (Succ (viewout Zero)) Succ m' => fib n + fib (viewout (Succ n)) ") #pdfpc.speaker-note( "Views'ai - funkcijos konvertavimui" ) ] #slide[=== SnocList #align(center +horizon)[ #code(raw_text: "view list α ::= Nil | (list α) Snoc α in (x Cons Nil) = Nil Snoc x in (x Cons (xs Sonc x')) = (x Cons xs) Snoc x' out (Nil Snoc x) = x Cons Nil out ((x Cons xs) Snoc x') = x Cons (xs Snoc x') ") #code(raw_text: "last (xs Snoc x) = x") #v(1em) ] ] #slide[=== In, out & inout #code(raw_text: "view list α ::= Nil | (list α) Snoc α inout (x Cons Nil) = Nil Snoc x inout (x Cons (xs Sonc x')) = (x Cons xs) Snoc x' ") #pdfpc.speaker-note( "NOTE: inout" ) ] #slide[== Efektyvumas #v(1em) `1 Cons (2 Cons (3 Cons (4 Cons Nil)))` $=>$\ $=>$ `((((Nil Snoc 1) Snoc 2) Snoc 3) Snoc 4)` #pdfpc.speaker-note( "yra tam tikras šališkumas" ) ] #slide[== `Join` reprezentacija #align(center + horizon)[ #one-by-one[ #v(0.5em) #code(raw_text: "list α :== Nil | Unit α | (list α) Join (list α)") ][ #v(0.5em) #code(raw_text: "[1, 2]") #code(raw_text: "(Unit 1) Join (Unit 2)") #code(raw_text: "(Nil Join (Unit 1)) Join ((Unit 2) Join Nil)") #code(raw_text: "(Unit 1) Join (( Unit 2) Join Nil)") ] ] #pdfpc.speaker-note( "yra tam tikras šališkumas" ) ] #slide[== `Join` reprezentacija #code(raw_text: "view list α ::= Nil | α Cons (list α) in (Unit x) = x Cons Nil in (Nil Join xs) = in xs in ((Unit x) Join xs) = x Cons xs in ((xs Join ys) Join zs) = in (xs Join (ys Join zs)) out (x Cons xs) = (Unit x) Join xs ") #pdfpc.speaker-note( "yra tam tikras šališkumas" ) ] #slide[=== Pavyzdys: koordinatės #code(raw_text: "abstype complex with zpart, ypart, rpart, tpart :: complex -> real mkcart, mkpole :: real -> real -> complex ") #code(raw_text: "add c c' = mkcart (xpart c + xpart c') (ypart c + ypart c') mult c c' = mkpole (rpart c × rport c') (tpart c + tpart c') ") ] #slide[=== Pavyzdys: koordinatės #code(raw_text: "complex ::= Pole real real in (Pole r t) = Cart (r × cos t) (r × sin t) out (Cart x y) = Pole (sqrt (x^2 + y^2)) (atan2 x y)") #code(raw_text: "add (Cart x y)(Cart x' y' ) = Cart (x + x') (x + y') mul (Pole r t) (Pole r' t') = Pole (r × r') (t + t')") #code(raw_text: "abstype complex with complex ::= Cort real real complex ::= Pole real real ") ] #slide[=== Kiti pritaikymai: `zip` #code(raw_text: "view list (α, β) ::= Zip (list α, list β) innout Nil = Zip (Nil, Nil) innout ((a, b) Cons Zip (as, bs)) = Zip (a Cons as, b Cons bs)") #uncover(2)[ #align(center + horizon)[ #code(raw_text: "f cs = e as bs where as = [a | (a, b) <- cs] bs = [b | (a, b) <- cs] ") $ arrow.b $ #code(raw_text: "f (Zip (as, bs)) = e as bs") ] ] ] #slide[=== Kiti pritaikymai: predikatai #align(center + horizon)[ #code(size: 25pt, raw_text: "view int ::= EvenP int | OddP int in n = EvenP n, if n mod 2 = 0 = Oddp n, if n mod 2 = 1 out EvenP n = n, if n mod 2 = 0 out OddP n = n, if n mod 2 = 1 ") ] ] #slide[=== Kiti pritaikymai: `@` #code(raw_text: "view α ::= α as α in x = x as x out (x as x') = x, if x = x' ") #code(raw_text: "factorial (n as Zero) = 1 factorid (n as Succ n') = n × factorial n' ") ] #slide[=== Kiti pritaikymai: `@` #grid(columns: 2, gutter: 1em, [ #code(width: 100%, raw_text: read("ex/as2.idr")) ], [ #code(width: 100%, raw_text: read("ex/as1.idr")) ] ) ] #slide[== Equational reasoning à la Referential Transparency // Viena iš savybių, kurią Views'ai išsaugo -- tai referential transparency #quote("A linguistic construction is called referentially transparent when for any expression built from it, replacing a subexpression with another one that denotes the same value does not change the value of the expression.", attribution: "Wikipedia") #align(center)[arba \ #v(0.1em) $ x(x + 1) = x^2 + x = x(x + 1)$ ] ] #slide[== Equational reasoning à la Referential Transparency #one-by-one[ #code(raw_text: "view list α ::= Nil | (list α) Snoc α inout (x Cons Nil) = Nil Snoc x inout (x Cons (xs Sonc x')) = (x Cons xs) Snoc x' ") ][ #code(raw_text: "rotleft (x Cons xs) = x Snoc xs rotright (xs Snoc x) = x Cons xs") #code(raw_text: "rotleft [1,2,3,4] = [2,3,4,1] rotright [1,2,3,4] = [4,1,2,3]") ][ #code(raw_text: "rotright (rotleft xs) = xs") ] ] #slide[== Referential transparency #code(raw_text: "rotleft (x Cons xs) = xs Snoc x rotright (xs Snoc x) = x Cons xs") #alternatives[ #align(top)[ #code(raw_text: "rotright (rotleft (x Cons xs)) = ? ") ] ][ #align(top)[ #code(raw_text: "rotright (rotleft (x Cons xs)) = = rotright (xs Snoc x) ") ]][ #code(raw_text: "rotright (rotleft (x Cons xs)) = = rotright (xs Snoc x) = x Cons xs") ] ] #slide[== Indukcija #v(1em) Norint įrodyti, kad savybė $P(x s)$ galioja kiekvienam sąrašui $x s$, pakanka parodyti, kad: #v(0.5em) #one-by-one[ - $P("Nil")$ galioja, ir - $P(x s "Snoc" x)$ galioja, darant prielaidą, kad $P(x s)$ galioja. ] ditto: natūralūs skaičiai ] #slide[== Realizacija #v(1em) #only(1)[#align(center)[ `Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero))))))` ]] #align(horizon + center)[ #only(2)[ #code(raw_text: "view int ::= Zero | Succ int in n = Zero, if n = 0 = Succ (n - 1), if n > 0 out Zero = 0 out (Succ n) = n + 1 ") #code(raw_text: read("ex/fib1.m")) ] #only(3)[ #code(size: 20pt, raw_text: "viewcase z s n = z, if n = 0 = s (n - 1), if n > 0 zero = 0 succ = n + 1 ") #code(size: 20pt, raw_text: "fib m = viewcase zero (\λm'. viewcase (succ zero) (\λn. n + fib (succ n)) m') m") ] ] ] #slide[== Realizacija #align(center + horizon)[ #code(raw_text: "fibx a b Zero = a fibx a b (Succ n) = fibx b (a+b) n ") $ arrow.b $ #code(raw_text: "fibx a b m = a, if m = 0 = fibx b (a + b) (m - 1), if m > 0 ") ] ] #slide[== Išvados #one-by-one[][ ✔ Abstracija \ ][ ✔ Efektyvumas (performance) \ ][ ✔ Įskaitomumas \ ][ #pad(1em)[ #quote("It is particularly worrying when we are forced to choose between valuable methods such as pattern matching and data abstraction. Views move this trade-off from the ‘necessary’ to the ‘avoidable’ category.") ] ] ] #slide[#align(center + horizon)[#text(size: 40pt)[ *Klausimai?*]]] #slide[== Extra pavyzdys: medžiai]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/big-todo/0.1.0/lib.typ
typst
Apache License 2.0
//Function to insert TODO #let todo(body, big_text: 40pt, small_text: 15pt, gap: 2mm) = { set text(size: 0pt) //to hide default figure text, figures is only used for outline as only headings and figures can used for outlining at this point figure(kind: "todo", supplement: "", outlined: true, caption: body)[ #block()[ #set text(fill: red, size: big_text, weight: "bold") ! TODO ! ] #v(gap) #block[ #set text(fill: red, size: small_text, weight: "bold") #body ] ] } //Function to insert TODOs outline #let todo_outline = outline( title: [TODOs], target: figure.where(kind: "todo") )
https://github.com/jomaway/typst-teacher-templates
https://raw.githubusercontent.com/jomaway/typst-teacher-templates/main/ttt-utils/lib/random.typ
typst
MIT License
/// create a hash value from a seed for some content #let hash(value, seed) = { array(bytes(repr(value))).fold(seed, (a,b) => (a.bit-lshift(1)).bit-xor(b)) } /// shuffle an array. /// /// - arr (array): the array to randomize /// - seed (int): a seed to start with. if auto the current date will be used (default). /// -> array #let shuffle(arr, seed: auto) = arr.sorted(key: it => { let now = datetime.today() let rand = if (seed == auto) { int(now.year() + now.month() * 256 * now.day() * 65535) } else { seed } hash(it,rand) })
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/ibanator/0.1.0/lib.typ
typst
Apache License 2.0
#let lib = plugin("typst_iban.wasm") /// Validates the given IBAN, returning an ISO 13616-1 formatted string if the validation was successful. /// If the validation was unsuccessful, the function panics with an error. /// /// iban (string): The IBAN to format. /// validate(boolean): If true, the IBAN will be validated before formatting. /// -> string #let iban(iban, validate: true) = { if validate { let res = lib.check_iban(bytes(iban)) if res.at(0) != 1 { panic("Invalid IBAN") } } // Format the string by creating groups of 4 chars. let iban_len = iban.len() let result = "" for i in range(0, iban_len, step: 4) { result += iban.slice(i, calc.min(iban_len, i + 4)) + " " } return result.trim(at: end) }
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/制作模版/template.typ
typst
#set par( justify: true, leading: 0.52em, ) = 制作模版 在本教程的前三章中,您已经学习了如何使用 Typst 编写文档、应用基本样式以及深入自定义其外观以符合发布者的样式指南。因为你在上一章写的论文取得了巨大的成功,你被要求为同一会议写一篇后续文章。这一次,您希望采用在上一章中创建的样式,并将其转换为可重用的模板。在本章中,您将学习如何创建一个模板,您和您的团队只需一个显示规则即可使用该模板。让我们开始吧! == 玩具模版 在 Typst 中,模板是可以包装整个文档的函数。要了解如何做到这一点,让我们首先回顾一下如何编写自己的函数。他们可以做任何你想让他们做的事情,所以为什么不疯狂一点呢? #image("1.png") 此函数采用单个参数 ,并返回一个被星星包围的内容块。我们还将整个东西放在一框里,这样令我们惊讶的术语就不会通过换行符与它的闪光点分开.*termterm* Typst 附带的许多函数都具有可选的命名参数。我们的函数也可以拥有它们。让我们在函数中添加一个参数,选择文本的颜色。我们需要提供默认颜色,以防未给出参数。 #image("2.png") 模板现在通过使用“所有内容”显示规则来工作,该规则将自定义函数应用于整个文档。让我们用我们的函数来做到这一点.*amazed* #image("3.png") 现在,我们的整个文档将传递给函数,就好像我们将其包裹在函数周围一样。这对于这个特定的函数不是特别有用,但是当与集合规则和命名参数结合使用时,它可能非常强大.*amazed* == 嵌入设置和显示规则 为了将一些设置和显示规则应用于我们的模板,我们可以在函数中的内容块中使用然后将文档插入到该内容块中.*setshow* #image("4.png") 就像我们在上一章中已经发现的那样,集合规则将适用于其内容块中的所有内容。由于“所有内容”显示规则将我们的整个文档传递给函数,因此模板中的文本集规则和字符串显示规则将应用于整个文档。让我们利用这些知识创建一个模板,再现我们在上一章中写的论文的正文风格.*template* #image("5.png") 我们从上一章复制粘贴了大部分代码。唯一的两个区别是,我们将所有内容都包装在函数中,并直接在参数上调用列函数,因为它已经包含了文档的内容。此外,我们使用了大括号的代码块而不是内容块。这样,我们就不需要在所有设置的规则和函数调用前面加上。作为交换,我们不能再将标记直接写入其中.*confdoc* 还要注意标题的来源:我们以前把它放在一个变量中。现在,我们接收它作为模板函数的第一个参数。因此,我们必须在调用模板的 显示规则中指定它。 == 具有命名参数的模板 我们在上一章的论文有一个标题和一个作者名单。让我们将这些内容添加到我们的模板中。除了标题之外,我们还希望我们的模板能够接受作者列表及其隶属关系和论文摘要。为了保持可读性,我们将添加这些参数作为命名参数。最后,我们希望它像这样工作: #image("6.png") 让我们构建这个新的模板函数。首先,我们向参数添加一个默认值。这样,我们可以在不指定标题的情况下调用模板。我们还添加了默认值为空的命名和参数。接下来,我们将上一章中生成标题、摘要和作者的代码复制到模板中,将固定的详细信息替换为参数.*titleauthorsabstract* 新参数需要一个包含关键字的字典数组。由于我们可以拥有任意数量的作者,因此我们会动态确定作者列表是否需要一列、两列或三列。首先,我们在数组上使用 .len() 方法确定作者的数量。然后,我们将列数设置为此计数的三个最小值,这样我们创建的列数就不会超过三列。如果作者超过三位,则将插入新行。为此,我们还在函数中添加了一个参数。否则,行之间的距离会太近。为了从字典中提取有关作者的详细信息,我们使用字段访问语法。*authorsnameaffiliationemailauthorsrow-guttergrid* 我们仍然必须为每个作者提供一个网格参数:这是数组的*map*方法派上用场的地方。它采用一个函数作为参数,该参数与数组的每个项目一起调用。我们给它传递一个函数,该函数格式化每个作者的详细信息,并返回一个包含内容值的新数组。现在,我们有一个值数组,我们想将其用作网格的多个参数。我们可以通过使用点差运算符来做到这一点。它采用一个数组,并将其每个项作为单独的参数应用于函数。 生成的模板函数如下所示: #image("7.png") == 单独的文件 大多数情况下,模板是在不同的文件中指定的,然后导入到文档中。这样,您写入的主文件将保持整洁,并且您的模板可以轻松重复使用。通过单击加号按钮在文件面板中创建一个新的文本文件并将其命名为 。将函数定义移动到该新文件中。现在,您可以通过在显示规则之前添加导入来从主文件访问它。指定关键字和冒号之间的文件路径,然后命名要导入的函数.*conf.typconfimport* #image("8.png") 现在,我们已将会议论文转换为该会议的可重复使用的模板!为什么不在 Typst 的 Discord 服务器上分享它,以便其他人也可以使用它呢? == 回顾 恭喜,您已经完成了 Typst 的教程!在本节中,您学习了如何定义自己的函数,以及如何创建和应用定义可重用文档样式的模板。你已经走了很远,学到了很多东西。您现在可以使用 Typst 编写自己的文档并与他人共享。 我们仍然是一个超级年轻的项目,正在寻找反馈。如果您有任何问题、建议或发现错误,请在 Typst 的 Discord 服务器、我们的联系表格或社交媒体上告诉我们。 那你还在等什么?注册并写点东西! #image("9.png")
https://github.com/jeffa5/typst-cambridge
https://raw.githubusercontent.com/jeffa5/typst-cambridge/main/thesis/cambridge.typ
typst
MIT License
// Given a location at the start of a page, obtain the current // heading. Current means: // - The first heading on this page if present. // - Else, the previous heading if one exists. // - Else, return none. #let get-current-heading(loc, level: 1) = { let heading-selector = heading.where(level: level, outlined: true) let el = query(heading-selector.after(loc), loc).at(0, default: none) if el != none and el.location().page() == loc.page() { return none } else { return query(heading-selector.before(loc), loc).at(-1, default: none) } } #let figure_caption(it) = { strong[#it.supplement #it.counter.display(it.numbering)#it.separator] it.body } #let front-page(title, subtitle, author, college, college-shield) = { let lastline = "This dissertation is submitted for the degree of Doctor of Philosophy" [ #set par(justify: false) #align(center, image(width: 20em, "light-logo.svg")) #align(center + horizon, text(2.5em, title)) \ #v(4em) #align(center + horizon, text(2em, subtitle)) \ #v(4em) #align(center + horizon, [#text(1.5em, author) \ #image(width: 5em, college-shield) #text(1.3em, college)]) #align(center + bottom, text(1em, lastline)) #v(1em) ] } #let declaration(name, date) = [ #heading(level: 1, outlined: false, "Declaration") #v(2em) This thesis is the result of my own work and includes nothing which is the outcome of work done in collaboration except as declared in the preface and specified in the text. It is not substantially the same as any work that has already been submitted, or, is being concurrently submitted, for any degree, diploma or other qualification at the University of Cambridge or any other University or similar institution except as declared in the preface and specified in the text. It does not exceed the prescribed word limit of 60 000 words. #v(2em) #align(right, [#name \ #date]) ] #let summary-page(content) = [ #heading(level: 1, outlined: false, "Summary") #content ] #let acknowledgements-page(content) = [ #heading(level: 1, outlined: false, "Acknowledgements") #content ] #let glossary() = [ #heading(level: 1, outlined: false, "Glossary") ] #let index() = [ #set heading(numbering: none) #show heading.where(level: 1): it => { set text(1.6em, weight: "regular") v(2em) it.body v(-0.5em) line(length: 100%, stroke: 0.5pt) v(2em) } #heading(level: 1, "Index") ] #let clearpage(compact) = { if not compact { pagebreak(to: "odd") } } #let listoffigures(selector) = { outline(title: [List of figures], target: figure.where(kind: selector)) } #let listoftables(selector) = { outline(title: [List of tables], target: figure.where(kind: selector)) } #let listoflistings(selector) = { outline(title: [List of listings], target: figure.where(kind: selector)) } #let tableofcontents() = { show outline.entry.where(level: 1): it => { strong(it) } outline(indent: auto, depth: 3) } #let thesis( title: none, author: none, college: none, college-shield: none, subtitle: none, short-title: none, short-author: none, date: none, summary: none, acknowledgements: none, compact: false, figure-selector: image, table-selector: table, listing-selector: raw, use-glossary: true, use-index: true, body, ) = { let leading = if compact { 1em } else { 1.5em } set page( paper: "a4", // One Cambridge thesis-binding company, <NAME> & Son, recommend on their web page to leave 30 mm margin on the spine and 20 mm on the other three sides of the A4 pages sent to them. About a centimetre of the left margin is lost when the binder stitches the pages together. margin: ( inside: 30mm, outside: 20mm, top: 20mm, bottom: 20mm, ), ) show heading: set block(above: 2em, below: 2em) show heading.where(level: 1): it => { set text(1.6em, weight: "regular") v(2em) it.body v(-0.5em) line(length: 100%, stroke: 0.5pt) v(2em) } set par(leading: leading, first-line-indent: leading, justify: true) front-page(title, subtitle, author, college, college-shield) clearpage(compact) declaration(author, date) clearpage(compact) summary-page(summary) clearpage(compact) acknowledgements-page(acknowledgements) clearpage(compact) tableofcontents() clearpage(compact) if figure-selector != none { listoffigures(figure-selector) clearpage(compact) } if table-selector != none { listoftables(table-selector) clearpage(compact) } if listing-selector != none { listoflistings(listing-selector) clearpage(compact) } if use-glossary { glossary() clearpage(compact) } set page(numbering: "1", header: { locate(loc => { let current-page = counter(page).at(loc).first() let current-chapter = get-current-heading(loc) let current-section = get-current-heading(loc, level: 2) if current-chapter != none { if calc.rem(current-page, 2) == 0 { let current-section-text = if current-section == none {[]} else { emph[#numbering(current-section.numbering, ..counter(heading).at(current-section.location())). #current-section.body] } [ #h(1fr) #current-section-text #v(-0.5em) #line(length: 100%, stroke: 0.5pt) ] } else { [ #emph[Chapter #counter(heading.where(level: 1)).display(). #current-chapter.body] #h(1fr) #v(-0.5em) #line(length: 100%, stroke: 0.5pt) ] } } else {[]} }) }) set heading(numbering: "1.1") show heading.where(level: 1, numbering: "1") : it => { set text(1em, weight: "regular") v(2em) h(1fr) [Chapter #counter(heading).display()] set text(1.6em, weight: "regular") line(length: 100%, stroke: 0.5pt) block[ #it.body ] line(length: 100%, stroke: 0.5pt) v(2em) } show heading.where(level: 2): it => { set text(1.2em) it } show heading.where(level: 3): it => { set text(1.1em) it } show heading.where(level: 4): it => { set text(1em) it } show figure.where(kind: table): set figure.caption(position: top) // show figure.caption: figure_caption body if use-index { clearpage(compact) index() } } // For rendering chapters separately. #let chapter( compact: false, body, ) = { let leading = if compact { 1em } else { 1.5em } set page( paper: "a4", // One Cambridge thesis-binding company, <NAME> & Son, recommend on their web page to leave 30 mm margin on the spine and 20 mm on the other three sides of the A4 pages sent to them. About a centimetre of the left margin is lost when the binder stitches the pages together. margin: ( inside: 30mm, outside: 20mm, top: 20mm, bottom: 20mm, ), ) show heading: set block(above: 2em, below: 2em) show heading.where(level: 1): it => { set text(1.6em, weight: "regular") v(2em) it.body v(-0.5em) line(length: 100%, stroke: 0.5pt) v(2em) } set par(leading: leading, first-line-indent: leading, justify: true) set page(numbering: "1", header: { locate(loc => { let current-page = counter(page).at(loc).first() let current-chapter = get-current-heading(loc) let current-section = get-current-heading(loc, level: 2) if current-chapter != none { if calc.rem(current-page, 2) == 0 { let current-section-text = if current-section == none {[]} else { emph[#numbering(current-section.numbering, ..counter(heading).at(current-section.location())). #current-section.body] } [ #h(1fr) #current-section-text #v(-0.5em) #line(length: 100%, stroke: 0.5pt) ] } else { [ #emph[Chapter #counter(heading.where(level: 1)).display(). #current-chapter.body] #h(1fr) #v(-0.5em) #line(length: 100%, stroke: 0.5pt) ] } } else {[]} }) }) set heading(numbering: "1.1") show heading.where(level: 1) : it => { set text(1em, weight: "regular") v(2em) h(1fr) [Chapter #counter(heading).display()] set text(1.6em, weight: "regular") line(length: 100%, stroke: 0.5pt) block[ #it.body ] line(length: 100%, stroke: 0.5pt) v(2em) } show heading.where(level: 2): it => { set text(1.2em) it } show heading.where(level: 3): it => { set text(1.1em) it } show heading.where(level: 4): it => { set text(1em) it } show figure.where(kind: table): set figure.caption(position: top) // show figure.caption: figure_caption body }
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/casoslov/casy/cas6.typ
typst
#import "/style.typ": * #import "/SK/texts.typ": * #import "../styleCasoslov.typ": * = Šiesty čas #show: rest => columns(2, rest) #nacaloBezKnaza #zalm(53) #zalm(54) #zalm(90) #si #lettrine("Aleluja, aleluja, aleluja, sláva tebe, Bože.") #note[(3x)] #lettrine("Pane, zmiluj sa.") #note[(3x)] == Tropáre #note[Berieme tropár, prípadne tropáre podľa predpisu] #primText[I teraz: (Bohorodičník)] #lettrine("Keďže nemáme dostatok odvahy pre množstvo našich hriechov, * ty, Bohorodička Panna, pros toho, ktorý sa z teba narodil, * veď mnoho zmôže modlitba Matky k Vládcovej dobrosrdečnosti. * Neprehliadni modlitby hriešnych, Prečistá, * lebo ten, ktorý sa rozhodol aj trpieť za nás, * je milosrdný a má moc zachrániť.") #zoznam(( "Pane, príď nám čím skôr v ústrety so svojím milosrdenstvom, * lebo sme veľmi úbohí. * Pre slávu svojho mena nám pomôž, Bože, naša spása, * a vysloboď nás; * a pre svoje meno odpusť nám hriechy.", )) #trojsvatePoOtcenas == Kondák #note[Berieme kondák podľa predpisu] #lettrine("Pane, zmiluj sa.") #primText([40x]) #vKazdomCase #ektenia(3) #lettrine("Čestnejšia si ako cherubíni * a neporovnateľne slávnejšia ako serafíni, * bez porušenia si porodila Boha Slovo, * opravdivá Bohorodička, velebíme ťa.") Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami. #prepustenieMaleBezKnaza
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/hover/annotate_fn.typ
typst
Apache License 2.0
/// #let fn = `(..fn-args) => any`; /// /// - fn (function, fn): The `fn`. /// - max-repetitions (int): The `max-repetitions`. /// - repetitions (int): The `repetitions`. /// - args (any, fn-args): The `args`. #let touying-fn-wrapper(fn, max-repetitions: none, repetitions: none, ..args) = none #(/* ident after */ touying-fn-wrapper);
https://github.com/jmuchovej/typst-iconify
https://raw.githubusercontent.com/jmuchovej/typst-iconify/main/lib.typ
typst
//! typst-iconify //! https://github.com/jmuchovej/typst-iconify #let iconify = state("iconify", (:)) #let from-key(name) = { let (library, icon) = name.replace("iconify::", "").split(":") return (library: library, icon: icon) } #let to-key(library: auto, icon: auto) = (library, icon).join(":") #let icon-key(name) = { let state-key = ("iconify", name).join("::") return state-key } #let load-icon(alias, iconset, icon) = { let file-path = "./icons/" + iconset + "/" + icon + ".svg" let state-key = icon-key(to-key(library: alias, icon: icon)) state(state-key, none).update(image(file-path, height: 1em)) } #let load-icons(alias, iconset) = { let icon-list = json("./collections/" + iconset + ".json").icons for icon in icon-list { load-icon(alias, iconset, icon) } } // TODO support dynamically calling icons #let show-icon(name) = ( context { let state-key = icon-key(name) let (library, icon) = from-key(name) return state(state-key).get() } ) #let prefetch-icons(..iconsets) = { let desired-icons = (:) for icon in iconsets.pos() { desired-icons.insert(icon, icon) } for (alias, icon) in iconsets.named() { assert( icon not in desired-icons, message: "Found " + icon + " already specified! Please clean-up your icon specification!", ) desired-icons.insert(alias, icon) } iconify.update(desired-icons) for (alias, iconset) in desired-icons { load-icons(alias, iconset) } } #let icon(name, height: 1em, width: 1em, ..args) = { return show-icon(name) }
https://github.com/hrbrmstr/2023-10-20-wpe-quarto-typst
https://raw.githubusercontent.com/hrbrmstr/2023-10-20-wpe-quarto-typst/main/params-test/_extensions/params/typst-template.typ
typst
#let article( title: "TITLE", footer: "FOOTER", margin: (x: 1.25in, y: 1.25in), paper: "us-letter", lang: "en", region: "US", doc ) = { set page( paper: paper, margin: margin, footer: footer ) set text( lang: lang, region: region, ) text( size: 24pt, weight: 700, title ) doc }
https://github.com/daskol/typst-templates
https://raw.githubusercontent.com/daskol/typst-templates/main/iclr/README.md
markdown
MIT License
# International Conference on Learning Representations (ICLR) ## Usage You can use this template in the Typst web app by clicking _Start from template_ on the dashboard and searching for `clear-iclr`. Alternatively, you can use the CLI to kick this project off using the command ```shell typst init @preview/clear-iclr ``` Typst will create a new directory with all the files needed to get you started. ## Example Papers Here are an example paper in [LaTeX][1] and in [Typst][2]. ## Configuration This template exports the `iclr` function with the following named arguments. - `title`: The paper's title as content. - `authors`: An array of author dictionaries. Each of the author dictionaries must have a name key and can have the keys department, organization, location, and email. ```typst #let authors = ( ..., ( names: ([Coauthor1], [Coauthor2]), affilation: [Affiliation], address: [Address], email: "<EMAIL>", ), ... ) ``` - `keywords`: Publication keywords (used in PDF metadata). - `date`: Creation date (used in PDF metadata). - `abstract`: The content of a brief summary of the paper or none. Appears at the top under the title. - `bibliography`: The result of a call to the bibliography function or none. The function also accepts a single, positional argument for the body of the paper. - `appendix`: Content to append after bibliography section (can be included). - `accepted`: If this is set to `false` then anonymized ready for submission document is produced; `accepted: true` produces camera-redy version. If the argument is set to `none` then preprint version is produced (can be uploaded to arXiv). The template will initialize your package with a sample call to the `iclr` function in a show rule. If you want to change an existing project to use this template, you can add a show rule at the top of your file. ## Issues - Common issue is related to Typst's inablity to produce colored annotation. In order to mitigte the issue, we add a script which modifies annotations and make them colored. ```shell ../colorize-annotations.py \ example-paper.typst.pdf example-paper-colored.typst.pdf ``` See [README.md][3] for details. - The author instructions says that preferable font is MS Times New Roman but the official example paper uses serifs like Computer Modern and Nimbus font families. Monospace fonts are not specified. - ICML-like bibliography style. The bibliography slightly differs from the one in the original example paper. The main difference is that we prefer to use author's lastname at first place to search an entry faster. [1]: example-paper.latex.pdf [2]: example-paper.typst.pdf [3]: ../#colored-annotations [2024]: https://iclr.cc/Conferences/2024/CallForPapers [2025]: https://iclr.cc/Conferences/2025/CallForPapers
https://github.com/8LWXpg/typst-ansi-render
https://raw.githubusercontent.com/8LWXpg/typst-ansi-render/master/test/demo.typ
typst
MIT License
#import "../ansi-render.typ": ansi-render as __ansi-render, terminal-themes #set document(date: none) // workaround before set is implemented #let ansi-render = __ansi-render.with(inset: 5pt, radius: 3pt, theme: terminal-themes.vscode) = Render text directly #ansi-render("\u{1b}[38;2;255;0;0mThis text is red.\u{1b}[0m \u{1b}[48;2;0;255;0mThis background is green.\u{1b}[0m \u{1b}[38;2;255;255;255m\u{1b}[48;2;0;0;255mThis text is white on a blue background.\u{1b}[0m \u{1b}[1mThis text is bold.\u{1b}[0m \u{1b}[4mThis text is underlined.\u{1b}[0m \u{1b}[38;2;255;165;0m\u{1b}[48;2;255;255;0mThis text is orange on a yellow background.\u{1b}[0m") #ansi-render("\u{1b}[38;5;196mRed text\u{1b}[0m \u{1b}[48;5;27mBlue background\u{1b}[0m \u{1b}[38;5;226;48;5;18mYellow text on blue background\u{1b}[0m \u{1b}[7mInverted text\u{1b}[0m \u{1b}[38;5;208;48;5;237mOrange text on gray background\u{1b}[0m \u{1b}[38;5;39;48;5;208mBlue text on orange background\u{1b}[0m \u{1b}[38;5;255;48;5;0mWhite text on black background\u{1b}[0m") #ansi-render("\u{1b}[31;1mHello \u{1b}[7mWorld\u{1b}[0m \u{1b}[53;4;36mOver and \u{1b}[35m Under! \u{1b}[7;90mreverse\u{1b}[101m and \u{1b}[94;27mreverse") = Render text from a file #ansi-render(read("test.txt"), theme: terminal-themes.vscode-light, font: none) = Uses the font supports ligatures #ansi-render(read("test.txt"), font: "Cascadia Code", theme: terminal-themes.putty) = Render bold text with bright colors #let bold-bright-test = "\u{1b}[30mNormal\t \u{1b}[90mBright\t \u{1b}[1;30mBold\u{1b}[0m \u{1b}[31mNormal\t \u{1b}[91mBright\t \u{1b}[1;31mBold\u{1b}[0m \u{1b}[32mNormal\t \u{1b}[92mBright\t \u{1b}[1;32mBold\u{1b}[0m \u{1b}[33mNormal\t \u{1b}[93mBright\t \u{1b}[1;33mBold\u{1b}[0m \u{1b}[34mNormal\t \u{1b}[94mBright\t \u{1b}[1;34mBold\u{1b}[0m \u{1b}[35mNormal\t \u{1b}[95mBright\t \u{1b}[1;35mBold\u{1b}[0m \u{1b}[36mNormal\t \u{1b}[96mBright\t \u{1b}[1;36mBold\u{1b}[0m \u{1b}[37mNormal\t \u{1b}[97mBright\t \u{1b}[1;37mBold\u{1b}[0m" #grid( columns: 2, gutter: 10pt, ansi-render(bold-bright-test, theme: terminal-themes.vintage), ansi-render(bold-bright-test, theme: terminal-themes.vintage, bold-is-bright: true), )
https://github.com/lkoehl/typst-boxes
https://raw.githubusercontent.com/lkoehl/typst-boxes/main/README.md
markdown
MIT License
# typst-boxes Colorful boxes in [Typst](https://github.com/typst/typst). Check out [the example project](https://typst.app/project/rp9q3upfc69bPUCbv0BjzX) to see all boxes in action Current features include: - a colorful box is in four different colors (black, red, blue, green) - a colorful box with a slanted headline - a box with a simple outline - a rotateable stickynote ## Colorbox ![colorbox_example](examples/colorbox.png) ### Usage ``` #colorbox( title: lorem(5), color: "blue", radius: 2pt, width: auto )[ #lorem(50) ] ``` ## Slanted Colorbox ![slantedColorbox_example](examples/slanted-colorbox.png) ### Usage ``` #slanted-colorbox( title: lorem(5), color: "red", radius: 0pt, width: auto )[ #lorem(50) ] ``` ## Outline Colorbox ![outlinebox_example](examples/outline-colorbox.png) ### Usage ``` #outline-colorbox( title: lorem(5), width: auto, radius: 2pt, centering: false )[ #lorem(50) ] #outline-colorbox( title: lorem(5), color: "green", width: auto, radius: 2pt, centering: true )[ #lorem(50) ] ``` ## Stickybox ![stickybox](examples/stickybox.png) ### Usage ``` #stickybox( rotation: 5deg, width: 5cm )[ #lorem(20) ] ```
https://github.com/rem3-1415926/Typst_Thesis_Template
https://raw.githubusercontent.com/rem3-1415926/Typst_Thesis_Template/main/sec/sec2.typ
typst
MIT License
= Some Chapter #lorem(60) == Subchapter a #lorem(300) == Subchapter b #lorem(100) === Subsubchapter ba #lorem(100) === Subsubchapter bb #lorem(100) === Subsubsubchapter bba #lorem(100) ==== StoppedCountingchapter bbaa #lorem(100)
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/NormeDiProgetto/meta.typ
typst
MIT License
#let title = "Norme di Progetto"
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/themes/gallery/university.typ
typst
#import "../../../../polylux.typ": * #import themes.university: * #show: university-theme.with( short-author: "Short author", short-title: "Short title", short-date: "Short date", ) #title-slide( authors: ("<NAME>", "<NAME>"), title: "Title", subtitle: "Subtitle", date: "Date", institution-name: "University Name", logo: image("dummy-logo.png", width: 60mm) ) #slide(title: [Slide title], new-section: [The section])[ #lorem(40) ] #slide(title: "A longer slide title with 2 columns")[ #lorem(30) ][ #lorem(30) ] #focus-slide(background-img: image("background.svg"))[ *Another variant with an image in background...* ] #matrix-slide[ left ][ middle ][ right ] #matrix-slide(columns: 1)[ top ][ bottom ] #matrix-slide(columns: (1fr, 2fr, 1fr), ..(lorem(8),) * 9)
https://github.com/lucifer1004/leetcode.typ
https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/helpers.typ
typst
#let zip(..lists) = { let lists = lists.pos() if lists == () { () } else { let ret = () let len = lists.fold( lists.first().len(), (a, b) => if a > b.len() { b.len() } else { a } ) for i in range(0, len) { let curr = () for list in lists { curr.push(list.at(i)) } ret.push(curr) } ret } } #let flatten(list) = { let ret = () for item in list { if type(item) == "array" { for sub in flatten(item) { ret.push(sub) } } else { ret.push(item) } } ret } #let fill(value, n) = { let ret = () for i in range(n) { ret.push(value) } ret } #let display(value) = { if type(value) == "array" { // display arrays [[#value.map(display).join(", ")]] } else if type(value) == "dictionary" and value.type == "linkedlist" { // display linked lists let ret = () let now = value while now.next != none { ret.push(display(now.val)) now = now.next } [#ret.join(" -> ")] } else { repr(value) } } // The implementation is not efficient since we can only do clones #let linkedlist(arr) = { let now = (val: none, next: none, type: "linkedlist") for i in range(arr.len()) { now = (val: arr.at(arr.len() - 1 - i), next: now, type: "linkedlist") } now } #let testcases(solution, reference, inputs) = { let cells = () for key in inputs.first().keys() { cells.push(strong(key)) } cells.push([*answer*]) cells.push([*yours*]) for input in inputs { for key in input.keys() { cells.push(display(input.at(key))) } cells.push(display(reference(..input.values()))) cells.push(display(solution(..input.values()))) } v(2em) heading(level: 2, outlined: false, numbering: none, [Test Cases]) table( align: center, columns: fill(1fr, inputs.first().len() + 2), ..cells, ) }
https://github.com/nafkhanzam/typst-common
https://raw.githubusercontent.com/nafkhanzam/typst-common/main/src/common/currency.typ
typst
#let round-fixed-str(num, d) = { let res = str(calc.round(num, digits: d)) let pad = res.split(".") let post-len = 0 if pad.len() < 2 { if d != none and d > 0 { res += "." } } else if pad.len() >= 2 { post-len = pad.at(1).len() } pad = d - post-len while pad > 0 { res += "0" pad -= 1 } return res } #let print-currency(num, prefix: none, splitter: [,], split-num: 3, d: 0, comma: ".") = { if num < 0 [\- ] [#prefix] num = calc.abs(num) let res = str(num) if d != none { res = round-fixed-str(num, d) res = res.replace(".", comma) } let res-split = res.split(comma) let left = res-split.at(0) let right = res-split.at(1, default: none) let mod = calc.rem(left.len(), split-num) [#left.slice(0, mod)] let i = mod while i < left.len() { if i > 0 { splitter } [#left.slice(i, i + split-num)] i += split-num } if right != none { comma + [#right] } } #let print-rp(num) = print-currency(num, prefix: [Rp ], comma: ",", splitter: ".")
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/call-10.typ
typst
Other
// Error: 2:1 expected quote #func("]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/smartquotes_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 25-28 expected 2 characters, found 1 character // #set smartquote(quotes: "'")
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/WS-latest_CN.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (1 - 32)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [1], [孙颖莎], [CHN], [3581], [2], [陈梦], [CHN], [3488], [3], [王曼昱], [CHN], [3438], [4], [早田希娜], [JPN], [3339], [5], [张本美和], [JPN], [3277], [6], [朱雨玲], [MAC], [3210], [7], [王艺迪], [CHN], [3192], [8], [陈幸同], [CHN], [3154], [9], [伊藤美诚], [JPN], [3131], [10], [范思琦], [CHN], [3130], [11], [何卓佳], [CHN], [3121], [12], [钱天一], [CHN], [3104], [13], [张瑞], [CHN], [3098], [14], [郑怡静], [TPE], [3098], [15], [桥本帆乃香], [JPN], [3086], [16], [平野美宇], [JPN], [3075], [17], [金琴英], [PRK], [3055], [18], [刘炜珊], [CHN], [3054], [19], [木原美悠], [JPN], [3010], [20], [陈熠], [CHN], [3009], [21], [石洵瑶], [CHN], [3006], [22], [蒯曼], [CHN], [2993], [23], [韩莹], [GER], [2992], [24], [大藤沙月], [JPN], [2986], [25], [申裕斌], [KOR], [2978], [26], [朱芊曦], [KOR], [2950], [27], [佐藤瞳], [JPN], [2946], [28], [长崎美柚], [JPN], [2942], [29], [索菲亚 波尔卡诺娃], [AUT], [2937], [30], [小盐遥菜], [JPN], [2936], [31], [安妮特 考夫曼], [GER], [2931], [32], [李恩惠], [KOR], [2928], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (33 - 64)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [33], [徐孝元], [KOR], [2925], [34], [森樱], [JPN], [2916], [35], [边宋京], [PRK], [2915], [36], [王晓彤], [CHN], [2915], [37], [玛妮卡 巴特拉], [IND], [2910], [38], [芝田沙季], [JPN], [2909], [39], [袁嘉楠], [FRA], [2896], [40], [杜凯琹], [HKG], [2886], [41], [横井咲樱], [JPN], [2858], [42], [田志希], [KOR], [2828], [43], [覃予萱], [CHN], [2823], [44], [妮娜 米特兰姆], [GER], [2818], [45], [范姝涵], [CHN], [2804], [46], [伯纳黛特 斯佐科斯], [ROU], [2803], [47], [阿德里安娜 迪亚兹], [PUR], [2797], [48], [布里特 伊尔兰德], [NED], [2796], [49], [吴洋晨], [CHN], [2789], [50], [李雅可], [CHN], [2784], [51], [杨屹韵], [CHN], [2783], [52], [高桥 布鲁娜], [BRA], [2777], [53], [朱成竹], [HKG], [2755], [54], [倪夏莲], [LUX], [2751], [55], [BAJOR Natalia], [POL], [2750], [56], [金娜英], [KOR], [2741], [57], [WINTER Sabine], [GER], [2740], [58], [伊丽莎白 萨玛拉], [ROU], [2738], [59], [韩菲儿], [CHN], [2720], [60], [PESOTSKA Margaryta], [UKR], [2714], [61], [梁夏银], [KOR], [2711], [62], [笹尾明日香], [JPN], [2708], [63], [杨晓欣], [MON], [2706], [64], [齐菲], [CHN], [2704], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (65 - 96)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [65], [普利西卡 帕瓦德], [FRA], [2703], [66], [纵歌曼], [CHN], [2701], [67], [琳达 伯格斯特罗姆], [SWE], [2698], [68], [张安], [USA], [2694], [69], [蒂娜 梅谢芙], [EGY], [2693], [70], [GHORPADE Yashaswini], [IND], [2691], [71], [徐奕], [CHN], [2688], [72], [金河英], [KOR], [2686], [73], [李昱谆], [TPE], [2681], [74], [崔孝珠], [KOR], [2678], [75], [斯丽贾 阿库拉], [IND], [2665], [76], [LEE Daeun], [KOR], [2663], [77], [POTA Georgina], [HUN], [2662], [78], [李皓晴], [HKG], [2658], [79], [陈思羽], [TPE], [2655], [80], [朱思冰], [CHN], [2654], [81], [LIU Hsing-Yin], [TPE], [2649], [82], [王 艾米], [USA], [2645], [83], [张墨], [CAN], [2645], [84], [AKAE Kaho], [JPN], [2631], [85], [MATELOVA Hana], [CZE], [2628], [86], [吴咏琳], [HKG], [2627], [87], [BADAWY Farida], [EGY], [2625], [88], [单晓娜], [GER], [2614], [89], [OJIO Yuna], [JPN], [2611], [90], [克里斯蒂娜 卡尔伯格], [SWE], [2610], [91], [艾希卡 穆克吉], [IND], [2605], [92], [曾尖], [SGP], [2605], [93], [傅玉], [POR], [2601], [94], [HUANG Yu-Chiao], [TPE], [2601], [95], [奥拉万 帕拉南], [THA], [2600], [96], [邵杰妮], [POR], [2594], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (97 - 128)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [97], [RAKOVAC Lea], [CRO], [2587], [98], [DRAGOMAN Andreea], [ROU], [2583], [99], [李时温], [KOR], [2583], [100], [ARAPOVIC Hana], [CRO], [2582], [101], [刘佳], [AUT], [2574], [102], [DIACONU Adina], [ROU], [2573], [103], [刘杨子], [AUS], [2572], [104], [<NAME>], [ITA], [2564], [105], [UESAWA Anne], [JPN], [2561], [106], [苏蒂尔塔 穆克吉], [IND], [2560], [107], [<NAME>], [SRB], [2560], [108], [SAWETTABUT Suthasini], [THA], [2558], [109], [KAMATH Archana Girish], [IND], [2556], [110], [LUTZ Charlotte], [FRA], [2552], [111], [<NAME>], [ROU], [2545], [112], [WAN Yuan], [GER], [2540], [113], [TOLIOU Aikaterini], [GRE], [2539], [114], [陈沂芊], [TPE], [2539], [115], [<NAME>], [KOR], [2537], [116], [CHENG Hsien-Tzu], [TPE], [2534], [117], [LAM Yee Lok], [HKG], [2533], [118], [ZHANG Xiangyu], [CHN], [2533], [119], [SAWETTABUT Jinnipa], [THA], [2526], [120], [HUANG Yi-Hua], [TPE], [2521], [121], [<NAME>], [KOR], [2520], [122], [ZHANG Sofia-Xuan], [ESP], [2520], [123], [GHOSH Swastika], [IND], [2518], [124], [ZARIF Audrey], [FRA], [2517], [125], [玛利亚 肖], [ESP], [2514], [126], [CHA Su Yong], [PRK], [2512], [127], [SU Pei-Ling], [TPE], [2503], [128], [CHASSELIN Pauline], [FRA], [2500], ) )
https://github.com/FelipeCybis/quarto-physmed-template
https://raw.githubusercontent.com/FelipeCybis/quarto-physmed-template/main/README.md
markdown
MIT License
## Physmed Templates for Quarto This repository provides Quarto custom formats for slightly modified slide templates (revealjs) and posters (typst) that can be used by people in the Physics for Medicine Institute. Templates here are very much inspired provided by formats found in [Awesome quarto#Presentation formats](https://github.com/mcanouil/awesome-quarto?tab=readme-ov-file#real-life-examples). | Posters (typst) | Example | Usage | |-------------------------|--------------|---------------------------------| | [landscape](https://github.com/FelipeCybis/quarto-physmed-template/tree/main/physmed-poster-landscape) | [PDF](https://felipecybis.github.io/quarto-physmed-template/physmed-poster-landscape/template.pdf) | `quarto use template FelipeCybis/quarto-physmed-template/physmed-poster-landscape`| | [portrait](https://github.com/FelipeCybis/quarto-physmed-template/tree/main/physmed-poster-portrait) | [PDF](https://felipecybis.github.io/quarto-physmed-template/physmed-poster-portrait/template.pdf) | `quarto use template FelipeCybis/quarto-physmed-template/physmed-poster-portrait`| | Slides (revealjs) | Example | Usage | |-------------------------|--------------|---------------------------------| | [slides](https://github.com/FelipeCybis/quarto-physmed-template/tree/main/physmed-slides) | [HTML](https://felipecybis.github.io/quarto-physmed-template/) | `quarto use template FelipeCybis/quarto-physmed-template/physmed-slides`| Alternatively, these commands can be used with `quarto install extension` instead of `quarto use template`. This will install the template extension without any of the necessary scaffolding files to start from.
https://github.com/darioglasl/Arbeiten-Vorlage-Typst
https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/Anhang/03_Projektplan/00_index.typ
typst
== Projektplan In diesem Kapitel vom Anhang wird auf das Projektmanagement, die Planung und das Risikomanagement eingegangen. #include "00_projektmanagement.typ" #include "01_planung.typ" #include "02_risikomanagement.typ"
https://github.com/Woodman3/modern-ysu-thesis
https://raw.githubusercontent.com/Woodman3/modern-ysu-thesis/main/pages/bachelor-cover.typ
typst
MIT License
#import "../utils/datetime-display.typ": datetime-display #import "../utils/style.typ": 字号, 字体 #import "../utils/custom-cuti.typ": fakebold #import "../utils/indent.typ": fake-par,indent // 本科生封面 #let bachelor-cover( // documentclass 传入的参数 anonymous: false, twoside: false, fonts: (:), info: (:), // 其他参数 stoke-width: 0.5pt, min-title-lines: 2, info-inset: (x: 0pt, bottom: 1pt), info-key-width: 72pt, info-key-font: "黑体", info-value-font: "楷体", column-gutter: 22pt, row-gutter: 11.5pt, anonymous-info-keys: ("grade", "student-id", "author", "supervisor", "supervisor-ii"), bold-info-keys: ("title",), bold-level: "bold", datetime-display: datetime-display, ) = { // 1. 默认参数 fonts = 字体 + fonts info = ( title: ("基于 Typst 的", "南京大学学位论文"), grade: "20XX", student-id: "1234567890", author: "张三", department: "某学院", major: "某专业", supervisor: ("李四", "教授"), submit-date: datetime.today(), ) + info // 2. 对参数进行处理 // 2.1 如果是字符串,则使用换行符将标题分隔为列表 if type(info.title) == str { info.title = info.title.split("\n") } // 2.2 根据 min-title-lines 填充标题 info.title = info.title + range(min-title-lines - info.title.len()).map((it) => " ") // 2.3 处理提交日期 if type(info.submit-date) == datetime { info.submit-date = datetime-display(info.submit-date) } // 3. 内置辅助函数 let info-key(body) = { // rect( // width: 100%, // inset: info-inset, // stroke: none, text( font: fonts.at(info-key-font, default: "黑体"), size: 字号.小二, body ) // ) } let info-value(key, body) = { // set align(left) // rect( // width: 100%, // inset: info-inset, // stroke: none, text( font: fonts.at(info-value-font, default: "楷体"), size: 字号.小二, weight: if (key in bold-info-keys) { bold-level } else { "regular" }, bottom-edge: "descender", body, ) // ) } let info-long-value(key, body) = { grid.cell(colspan: 1, info-value( key, if anonymous and (key in anonymous-info-keys) { "██████████" } else { body } ) ) } let info-short-value(key, body) = { info-value( key, if anonymous and (key in anonymous-info-keys) { "█████" } else { body } ) } // 4. 正式渲染 pagebreak(weak:true,to:"odd" ) // 居中对齐 set align(center) image("../assets/vi/ysulogo.png", height: 1.86cm,width: 6.33cm ) v(40pt) fakebold(text(size: 字号.小初, font: fonts.黑体)[本科生毕业设计(论文)]) v(32pt*2) set align(left) // set par(leading: 2em, justify:true ) indent text(size: 字号.小二, font: fonts.黑体, "论文题目") h(column-gutter) text(size: 字号.小二, font: fonts.楷体, weight: "regular", info.title.at(0)) v(22.35pt*5*1.25 ) // grid( // columns: (info-key-width,340pt), // column-gutter: column-gutter, // row-gutter: row-gutter, // info-key("作者姓名"), // info-long-value("author", info.author), // info-key("专  业"), // info-long-value("major", info.major), // info-key("指导教师"), // info-long-value("supervisor", info.supervisor.sum()), // ) [ #indent#info-key("作者姓名") #h(column-gutter) #info-long-value("author", info.author) #v(row-gutter) #indent #info-key("专  业") #h(column-gutter) #info-long-value("major", info.major) #v(row-gutter) #indent #info-key("指导教师") #h(column-gutter) #info-long-value("supervisor", info.supervisor.sum()) ] v(字号.小四*5) set align(center) text(font:字体.宋体,size:字号.小二,weight: "bold",info.submit-date) }
https://github.com/SeniorMars/tree-sitter-typst
https://raw.githubusercontent.com/SeniorMars/tree-sitter-typst/main/examples/compiler/methods.typ
typst
MIT License
// Test method calls. // Ref: false --- // Test whitespace around dot. #test( "Hi there" . split() , ("Hi", "there")) --- // Test mutating indexed value. #{ let matrix = (((1,), (2,)), ((3,), (4,))) matrix.at(1).at(0).push(5) test(matrix, (((1,), (2,)), ((3, 5), (4,)))) } --- // Test multiline chain in code block. #{ let rewritten = "Hello. This is a sentence. And one more." .split(".") .map(s => s.trim()) .filter(s => s != "") .map(s => s + "!") .join("\n ") test(rewritten, "Hello!\n This is a sentence!\n And one more!") } --- // Error: 2:2-2:15 type array has no method `fun` #let numbers = () #numbers.fun() --- // Error: 2:2-2:43 cannot mutate a temporary value #let numbers = (1, 2, 3) #numbers.map(v => v / 2).sorted().map(str).remove(4) --- // Error: 2:3-2:19 cannot mutate a temporary value #let numbers = (1, 2, 3) #(numbers.sorted() = 1) --- // Error: 2-5 cannot mutate a constant #box.push(1)
https://github.com/ryuryu-ymj/mannot
https://raw.githubusercontent.com/ryuryu-ymj/mannot/main/README.md
markdown
MIT License
# Mannot A package for highlighting and annotating in math blocks in [Typst](https://typst.app/). A full documentation is [here](docs/doc.pdf). ## Example ```typst $ mark(1, tag: #<num>) / mark(x + 1, tag: #<den>, color: #blue) + mark(2, tag: #<quo>, color: #red) #annot(<num>, pos: top)[Numerator] #annot(<den>)[Denominator] #annot(<quo>, pos: right, yshift: 1em)[Quotient] $ ``` ![Example1](examples/showcase.svg) ## Usage Import and initialize the package `mannot` on the top of your document. ```typst #import "@preview/mannot:0.1.0": * #show: mannot-init ``` To highlight a part of a math block, use the `mark` function: ```typst $ mark(x) $ ``` ![Usage1](examples/usage1.svg) You can also specify a color for the highlighted part: ```typst $ // Need # before color names. mark(3, color: #red) mark(x, color: #blue) + mark(integral x dif x, color: #green) $ ``` ![Usage2](examples/usage2.svg) To add an annotation to a highlighted part, use the `annot` function. You need to specify the tag of the marked content: ```typst $ mark(x, tag: #<x>) // Need # before tags. #annot(<x>)[Annotation] $ ``` ![Usage3](examples/usage3.svg) You can customize the position of the annotation and the vertical distance from the marked content: ```typst $ mark(integral x dif x, tag: #<i>, color: #green) + mark(3, tag: #<3>, color: #red) mark(x, tag: #<x>, color: #blue) #annot(<i>, pos: left)[Set pos to left.] #annot(<i>, pos: top + left)[Top left.] #annot(<3>, pos: top, yshift: 1.2em)[Use yshift.] #annot(<x>, pos: right, yshift: 1.2em)[Auto arrow.] $ ``` ![Usage4](examples/usage4.svg) For convenience, you can define custom mark functions: ```typst #let rmark = mark.with(color: red) #let gmark = mark.with(color: green) #let bmark = mark.with(color: blue) $ integral_rmark(0, tag: #<i0>)^bmark(1, tag: #<i1>) mark(x^2 + 1, tag: #<i2>) dif gmark(x, tag: #<i3>) #annot(<i0>)[Begin] #annot(<i1>, pos: top)[End] #annot(<i2>, pos: top + right)[Integrand] #annot(<i3>, pos: right, yshift: .6em)[Variable] $ ``` ![Usage5](examples/usage5.svg)
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/044%20-%20Innistrad%3A%20Crimson%20Vow/003_Episode%202%3A%20The%20Dolorous%20Weight%20of%20Pleasantries.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 2: The Dolorous Weight of Pleasantries", set_name: "Innistrad: Crimson Vow", story_date: datetime(day: 03, month: 11, year: 2021), author: "<NAME>", doc ) "Have you seen her yet?" "No, have you?" "Terrible, just terrible, to make us wait so long just for her to make an appearance. She might think she's Lord of Innistrad, but—" "Don't say that so loudly, Relio—" "But she's far from it! I won't believe it until I see it myself." #figure(image("003_Episode 2: The Dolorous Weight of Pleasantries/01.jpg", width: 100%), caption: [Voldaren Estate | Art by: <NAME>], supplement: none, numbering: none) Relio drinks from his goblet. A little blood dribbles down his chin, staining his pure white ruff, which Cordelia warned him would happen. He never listens to her. Don't feed on wastrels, she told him, but there he went; don't antagonize the Nusfar simply because they look like children, she said, only to find him dangling blood-soaked candies over the head of a girl at least five times his age. Of all the vampires Cordelia knows, Relio seems the most eager to part with his immortality. Frankly, she's sick of dealing with it. There's so much else to see. Stromkirk cultist meetings had their own charms, yes, but they didn't have an ounce of this ostentation. Cordelia likes a good prophetic sermon as much as the next woman, but sometimes it's good to see how the other side lives. Practically everyone's gathered at the Voldaren Estate for the wedding. Olivia's truly outdone herself with the decorating. Cordelia didn't know that was possible. Still, it's hard to argue with the sights. The Voldaren Estate is swirling with red: the carpet red beneath their feet, chased with golden thread; red in the gowns and suits of the attendees per the dress code; red, beautiful and dark, in the tiered blood fountains every few paces. But most impressive were the swirling red petals dancing through the air. Once, centuries ago, Cordelia tended gardens. Watching the petals float in the air reminds her of days long gone. And it's far better than listening to Relio go on. He's still talking, but she's no longer paying attention. Something about Olivia letting the Domnathi come. And what was so bad about that, she wanted to ask? Oh, yes, they consorted with demons, but there aren't any demons #emph[here] , or at least none that Cordelia can see, and at least the Domnathi listened to the dress code. Relio came in white and blue. Honestly. His sleeves are already purpling with all the petals, the blood regaining its liquid form when it meets the cloth. A human walks by, thankfully providing another distraction from her companion's ceaseless chattering. Olivia's fine taste truly is on display tonight—thralls are strapping, lithe, beautiful, and handsome, but never boring. The tray in his hands holds crystal goblets of fresh blood; Cordelia considers for a long moment if she'd be chastised for drinking straight from the tap instead. There are no marks on this man's rippling form. Probably not worth risking it if he's someone's special pet. Besides, there are five duels going on in the hall already, one of which has taken a turn toward evisceration. It's unbecoming to eviscerate someone at a wedding. Doesn't stop the Nusfar, though. Few things do. As Cordelia picks up another goblet, a boy who looks all of ten drives his hand into a man's chest. She tuts. The victim is <NAME>, a Markov known for dueling at the drop of a hat—but all the martial skill on the Plane won't save you against the pure predator instinct of the Nusfar. She liked Kristoff, though, as passionate everywhere as he was on the battlefield. Watching him bleed out now, she feels only the barest trace of sadness. Ah well. Love is as fleeting as a flower, even for immortals. "And just look at who she's invited. Monsters. I tell you, being a vampire doesn't mean what it used to mean," Relio prattles. "Why, that we're all bowing to this #emph[madwoman ] should tell you something." "Relio, you're a Voldaren," she says flatly. "That only means I know her better than most! Two hundred years ago we'd never be cavorting with #emph[Domnathi—] " Relio's next nonsense dies the moment he does, drowned in the blood welling up from his mouth. Like a waterfall, it spills down his chest. He reaches out for Cordelia, but she sidesteps his dying grasp. Three seconds later, his corpse falls with a #emph[thunk] onto the polished marble floor. <NAME>, noted demon sympathizer, stands just behind him. Crimson tendrils weave about her fingers. Dark, arterial blood fills her goblet. When she fixes Cordelia with her steely glare, it is all she can do to keep from running away. "Terribly boring man," she says. "Friend of yours?" "No. Not at all, <NAME>, not at all," Cordelia says. The rumored one-time lover of Griselbrand smirks. "Good. And you are?" "Cordelia—" "Ahh, yes, a Stromkirk, aren't you?" she says. The way she studies Cordelia's outfit feels uncomfortably like a cat surveying a mouse. "I've had #emph[questions ] for your kind lately, but it seems no one will answer them for me. Isn't that a shame?" There are whispers about what <NAME> does to people who won't answer her questions. Faint ones, because everyone's terrified of speaking them aloud. The Domnathi bloodline is famous for consorting with demons, though to what end remains unclear. And even worse than that, it's said they'll do~favors for those demons, in exchange for powers of which other vampires can only dream. And when it came to Henrika herself, well~ A human thrall wordlessly bends over to drag Relio's body away. It's enough to divert Cordelia's attention for just a second. A primal fear comes over her: she may be a vampire, but so was Relio. She's not looking to end up like him. If Henrika wants, she could just kill her right— #emph[Ting, ting, ting.] Silence rolls over the grand hall like a crimson tide as all eyes land on the dais. <NAME> has finally arrived. #figure(image("003_Episode 2: The Dolorous Weight of Pleasantries/02.jpg", width: 100%), caption: [Olivia, Crimson Bride | Art by: <NAME>], supplement: none, numbering: none) And what an entry she's made! Floating down the steps in her wedding finery, her swirling, haunted sanguine train held aloft by bats! Every gleaming arcane light glitters anew, every one illuminating some new detail: the glimmer of her golden jewels, the glint of her teeth, the glamor of a gown made from the spirits of her oldest victims. In all the time Cordelia's been alive—a few hundred years now—she's never seen such sartorial heights. That collar has got to be at least as tall as some toddlers. Even Henrika's impressed, a soft #emph[hmm ] escaping her lips. She drapes an arm around Cordelia. "What a shame, the party's begun." "Wh-what a shame," Cordelia repeats. But Olivia saves them from any further conversation. "Greetings, my #emph[dearest ] friends, my most #emph[ardent ] enemies!" No good can ever come of her sounding so happy. "I see we've already had some murders. What fun! I can't tell you how happy it makes me to have blood sacrifices at my wedding! But what would a wedding be without a groom?" She holds aloft her glass in signal to some unseen forces. Soon she is no longer alone on the dais: a group of immaculately dressed thralls—most in Avacynian finery, for the joke—emerge carrying an elaborate stone coffin: marble inlaid with gold, crowned by Markovian rays. The thralls set the coffin down standing up. In that moment, the ballroom is as silent as it will ever be. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) <NAME> walks face first into danger. That's her usual routine. It#emph[ usually] works. Tonight, as she tries to walk past the guards outside the Voldaren Estate, it doesn't. Instead, Teferi grabs her by the shoulders just as a bird flies into the wall. Whatever magic they've got incinerates it right then and there. Crumbles of bird-shaped ash fall where it made contact. "Well~I guess that's not going to work," Chandra says. Adeline stifles a laugh, which almost makes the whole thing worth it. Chandra hasn't heard her laugh in a while. With some bitterness, she glances to the towering guards on either side of the gate. It isn't their fault #emph[directly] , but they are part of the problem. #figure(image("003_Episode 2: The Dolorous Weight of Pleasantries/03.jpg", width: 100%), caption: [By Invitation Only | Art by: <NAME>], supplement: none, numbering: none) Coming right to the front gates was Arlinn's idea. If there was a wedding going on—and if they showed up in a small group, with Sorin—then maybe they'd be let in. Chandra thought it was stupid from the get-go. Who ever heard of letting the enemy waltz right into your operation just because they came in fancy dress? But Sorin thought it was worth a shot, too, so here they were. But as far as she's concerned, the right answer here is to light the whole thing on fire. The guards will scatter, or else they'll get caught, and they can fight this out. It was do-or-die time on Innistrad. On the way here, their group rallied whomever they could get to join up. Turns out, it's a lot easier to do when there's a plan, and when that plan involves crashing a vampire party. There's a lot of anger out there on the moors and the heaths and the cliffs, a lot of fire just looking for something to consume. Chandra knows all about that. The ranks of mounted cathars lying in wait will charge right in. Sigardan priests will start their chants, bright prayer wrapping about the gathered townspeople like the wings of angels, and that will be that. There'll be no hope for any of the vampires. Scoop up the Moonsilver Key and go. But when things seem simplest to her, they're often more complicated to everyone else. Looking on the faces of her companions—only the five of them, the rest concealed not far off—she gets the feeling that must be the case here, too. Especially Sorin. He looks like someone slipped vinegar into his serving of blood, which is impressive given that she didn't think he could possibly look any more sour. First time for everything, she supposes. "No one enters without an invitation," the guards say. <NAME> must have selected two vampires whose voices could perfectly harmonize for just this job, because they do, and it is the most sonorous dismissal in all of Innistrad. "What about if we all come in with him?" Arlinn asks. She looks handsome in her wedding outfit, but then she looks handsome in most things. Still, she's got excellent taste: a well-tailored oxblood jerkin, sprigs of birch embroidered at the collar, her red-slashed sleeves ending in fresh-pressed white cuffs. A fur mantle worn over one shoulder adds a woodsy touch; knowing her, she probably took down the bear herself. It is nice to see her all cleaned up—like seeing your favorite aunt at a party. "He has an invitation." "One person per invitation," the guards intone together. "But that doesn't make any sense," Chandra says. "Not even a plus-one?" "You can definitely afford to let more people in," says Kaya, gesturing at their gilded armor. "It isn't a matter of scarcity." "And if you want to make sure all of Innistrad bows to its new lady, then you need investment from #emph[everyone,] " says Arlinn. "You can't just invite vampires." "It's bad form," agrees Teferi. "One person per invitation." Chandra wants to scream. The answer's so simple. Just go in, right? Just go in. But there are wards all around the place—wards the witches haven't been able to crack and the priests haven't been able to dispel. The vampire army is there as well all along the watch towers, waiting for any sign of unrest. Who knows how many of them have magic of their own? Who knows how hungry they are? Sure, Arlinn and Adeline managed to put together a small army's worth of people—but was everyone ready to come to blows here? Right here, right now? As much as Chandra wants to fight, she can't ignore the cost of it out in the open like this. Without the key, or the immediate hope of the key, it's going to end like the Harvesttide Massacre. That day carved itself into her mind, and the scar of it will remain for years, she's sure: the bodies lying out in the balmy orange of the setting sun; their blood, red as cranberry wine, seeping into the festive costumes they'd spent so much time putting together. Dressing as werewolves and vampires was meant to be an act of defiance. To see their bodies lying broken instead~Battlefields were sickening enough on their own. But these were innocent people. Barely grown, some of them. And when she thinks of them—no, no. They can't just walk in. Maybe Adeline knows what she's thinking. The cathar's hand is a comforting weight on Chandra's shoulder, as is the faint smell of leather that always announces her presence. The parade armor she's wearing is swoon-worthy enough, engraved with Avacynian symbols, but she always smells so good, too. "Patience rewards the virtuous," she says, "but~I admit, it's difficult sometimes to be virtuous." "Tell me about it," says Chandra. Best not to let it linger. "Real shame, though. Here we are, both looking sharp, with nowhere to go. I was promised a party." "A party? Is that all this is?" The deep voice hits like a punch to the ribs. Chandra doesn't flinch. In some sense, she's happy he's finally paying attention to the world around him instead of brooding. "I mean, it isn't #emph[just ] a party," she says. "I'm trying to lighten the mood, Sorin." "I'm certain this is all a fun romp for you, Nalaar, but I'll remind you, there are adults present," said Sorin. "Some of the adults could use a laugh," Teferi says. "Chandra's proven herself time and again. She's earned her right to joke around. This isn't her homeworld, either—she could have ignored the summons, or left after Harvesttide. But she's here." Sorin looked down at the invitation in his hands. He furrowed his brow. Chandra thought he looked just like a moody old portrait, which made her laugh, because he'd hate to hear that. She was at least quick enough to bite her lip to stifle it. No matter how ridiculous Sorin is as a person—or how much she might dislike him—it's hard to imagine what she'd be feeling in this situation. "Will you be all right in there alone?" Arlinn asks him. "I can try to follow you," Kaya offers. It's a funny thought, a little ghost Kaya hovering around the sullen Sorin. Chandra knows it doesn't work that way; Kaya isn't#emph[ really] a ghost, so at most, she'd be following behind him at full size. Still, somehow the image feels right. But what feels right, too, is the way he sighs and shakes his head. "I've been alone for centuries," he says. "This will be no different." She wants to ask him what he means because he won't be alone. He's related to a bunch of people in that place. Must be someone in there he likes, right? But as he strides between the guards, Sorin doesn't have the air of a man who likes anyone. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Sorin walks alone. The guards on either side of him must think otherwise. With the barrier secure, they opted to escort him to the castle, sending messenger bats for reinforcements to replace them at the outer gates. Every one of his footfalls is echoed by theirs—the sharp tap of his shoes on the marble floors, the soft clatter of their armor. If they chose, they could move as soundlessly as moonlight through the darkness. But instead, there is the steady rhythm of their steps for company. And soon, their braying. "You didn't adhere to the dress code," says one. Sorin does not know his name, nor does he care to. "The colors were specified in the invitation." Towers floated atop chunks of rock on either side of them. Within each of those towers, a host of Voldarens and their guests pour blood for each other. The scent of debauchery reaches him even here. He wonders if all of them are adhering to the dress code. In the distance, the churning sea continues ever on its course, ignorant to what occurs here. He says nothing. Petals of blood land on his cloak, coloring the frost. Onward through the gates of the castle, filigreed with the Voldaren symbol and Olivia's silhouette within it. The sheer audacity of the woman. If egos alone could conquer, <NAME> would have long since carved her throne from the bones of Innistrad. Tonight, she will. The woman at the door looks him up and down with clear disgust, as if his finery is somehow less appropriate because it is black and gray. Sorin might not have the patience for vampire politicking, but he knows well enough how to dress. Unlike many of these whelps. "Your invitation?" He hands it over, fuming though he may be. They knew who he was. Everyone knew who he was. Olivia must have told this girl to act in such a way—a simple fledgling at the door to welcome all the lords and ladies. Had Olivia picked her for the way she pouted? For the utter disinterest in her voice? "Go ahead." A younger Sorin would have bristled at this. But he is older now, and tired. The sooner this is over with the better. Onward through the doors, where music swallows him whole. Enthralled musicians play near gilded fountains of blood. The piece is at least three hundred years old by his count; everyone here knows it. And, indeed, there are some who dance to the tune, even here where the party has not yet begun. The green light filtering in through the windows lends everything an eerie cast, as if he is watching a painting in place of people. But then it comes, inevitable as the outside tides—one of the revelers gets hungry, wanders over, and tears out a musician's throat. Really, some of these guests can't be counted as people. To be given over to your desires so thoroughly that you cannot keep yourself from ruining the entertainment is to be less than human. And they are all like this. Yes, for thousands of years, they have all been like this. "Sorin? Is that <NAME>?" He keeps walking. The hallways of the Voldaren Estate are meant to confuse. It's one of Olivia's oldest tricks: get the revelers drunk by one means or another, tell them they absolutely shouldn't wander off, make a few people disappear when they do. There are more geists in the Muttering Corridors than there are pages in all of Olivia's library. Each one a victim of hers. Each one wandering these weird halls, where doors sometimes lead to sudden drops and stairs are given to rearrange. But the trick of it is that the Voldaren Estate follows Olivia's whims. And she is as predictable as she is loathsome. On some level, he knew this was going to happen. Something like this. During his ignoble prison sentence, she was already making ludicrous grabs for power. It was only natural that someone so nakedly ambitious would hit on the idea of a political marriage. And once she'd had the idea, there were few on Innistrad who could offer her an increase in power. Henrika loved revenge more than power; the Falkenrath had no one to offer; <NAME> would sooner give himself to the unknowable beings of the sea. That left Sorin—unattainable to her—or his grandfather. He should have known. The closer they come to the ballroom, the more people they run into. Thralls who do not dare to look at him. Fledglings who do so with abandon, as if the act of laying eyes on <NAME> is something so profoundly profane as to change the course of their ageless existence. "That's him, the man in the rock," they say. "How #emph[droll] !" "Shouldn't he have a mouth like a Gorger?" He's familiar with the term, but only in passing. The Falkenrath had earned a new name for themselves. "He's handsome, for such a fool." They giggle as they flit by him, mouths red with their last meals. Glasses clink together. Behind him, the guards' armor keeps clattering; above him, petals of blood float on clouds of music. Silently, he thinks of all he has done to enable this life they lead. He hates it here. Onward, to the ballroom itself, a space so wide it is difficult to imagine how it fits within the castle's architecture. The moon alone could not provide ample lighting; spectral yellow-green magic fills in the gaps. Dancers, duelists, lollygaggers, and layabouts—there are hundreds of them gathered, and all are reflected upon the polished marble floors. Fountains of blood offer succor and inebriation; chained thralls offer something a little #emph[fresher ] for the connoisseurs among the crowd. A lithe man by the doors blows a horn. "Announcing the #emph[extremely welcomed, very honored] , <NAME>!" He thinks, not for the first time, of murder. But he knows what will come of that, surrounded here by those who want to see him brought low. All Olivia must do is say the word. Then they will all descend upon him, crows to the carrion, and all the sangromancy on the Plane will only buy him another few moments. Meanwhile, Arlinn's ramshackle coalition will wait outside none the wiser. So, he does not kill the crier, and he does not kill any of the people who turn to look at him then. How many eyes are upon him? He does not know, but he can feel every one like the tip of a dagger across his flesh. But the stake in his heart comes when he looks upon the dais. There's no mistaking it: that is his grandfather's coffin. And that woman, cloaked in the roiling souls of her victims, is <NAME>. Silence reigns in the house of abandon. Even from here—even across the ballroom—he can tell when she begins to smile. "My #emph[dearest] Sorin," she calls. "What a #emph[delight] ! You're right on time." He scowls. A wave of restrained laughter rolls through the crowd. He doffs his cloak, casting it behind him, walking down the aisle to his grandfather's stolen coffin. "Olivia, it's always a pleasure," he says. "I see you've spared no expense." "And why should I? This joyous occasion deserves only the finest, wouldn't you agree? I wouldn't want your grandfather to wake to anything less than the best." He cannot keep himself from clenching his teeth together. But he continues. One step, another. Falling petals. Clinking glasses. Olivia snaps her fingers. One of the thralls hands her an ornate knife. "Ask him yourself, if you like," she says. "It'll only be a moment." "What you're doing is madness." "Madness? Oh, my dear boy, this is the wisest thing I've ever done," she answers. The daggers shift then, the crowd's attention now on Olivia. With a small flourish, she rakes the knife across her arm. Old blood, potent blood, blood dark as the night around them, drips onto <NAME>'s coffin. #figure(image("003_Episode 2: The Dolorous Weight of Pleasantries/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) The red chandelier above, the red carpets below, joined by the woman in her red wedding dress, the red blood on the white slab coffin. Each drip makes him angrier. Every instant that woman's foul blood runs along the carvings of his family histories is an insult. #emph[His grandfather] —his grandfather, who created everything these people so value! His grandfather, who created them, used as a simple political tool. He knows what is going to happen. The grooves run all the way to the inner workings of the coffin. Any moment now, that woman's blood will drip onto his grandfather's lips. The rush of it will leave him overwhelmed—and, worse, her own memories and emotions will mingle with his. Sorin was so careful whenever he woke his grandfather. He'd wait and wait until his own storm of emotions had settled, he'd keep his mind trained on pleasant memories, he'd do whatever was necessary to see that his grandfather woke comfortably. To wake from slumber is a frightening thing, much as no one wants to admit it. And now his grandfather is going to wake tasting that woman's blood, thick with ambition, surrounded by these #emph[insects] ~ It is, in the end, a childish thought. Perhaps the most childish thought he's ever had—and certainly the most childish thought he's had in recent memory. But it is there, at the core of all this, a single thought that echoes and echoes. He doesn't want to lose his grandfather. He doesn't want to see his grandfather get hurt. In all the Planes, no one had known him longer. No one knew the story of his life so well, from his childhood to his ascendancy, his failures to his triumphs. No one else remembered anymore. All the others were dead. The realization is the flame, his rage the powder. The instant he has the thought is the instant everything changes. The explosion incinerates all caution. Sorin charges ahead. The guards are there to meet him, four standing with spears interlinked. Mice before cats have more hope of survival. When Sorin pounces on one, he tears out their throat before the two of them even hit the ground. Two of the others he freezes in place, their blood stopping in their bodies. He readies to leap again, toward Olivia— But in his haste, he's forgotten the last man. A thick, heavy chain around his neck chokes his progress, yanking him backward like a collared dog. If he can go just one more step, he could stop Olivia in place, stop this whole ritual. But the guard drags him one step back, his feet tripping over the bodies. Sorin snarls. His eyes lock on the sight in front of him: the coffin, the blood, Olivia's smiling face. One~more~step~ Another guard joins the first, another Blessed Silver chain around his chest. He strains forward. A third guard. A fourth. More and more pile on, faster than his magic can work on them, faster than he can stop them. All he can do is try to reach them—and watch. Watch as the coffin slides open and his grandfather emerges from within. <NAME> does not survey the gathered crowd, nor his restrained grandson—he has eyes only for <NAME>. He smiles at her. Sorin strains to remember his grandfather smiling like this before now. It's beatific, pure, and all the more horrifying for that. He's smiling like a #emph[child] . "Ladies, gentlemen, and Sorin," Olivia announces, "I present to you my handsome, perfect betrothed: <NAME>." He takes her hand. For long, horrible moments, he drinks the blood from her wrist. Only after this does he rise from the coffin. #figure(image("003_Episode 2: The Dolorous Weight of Pleasantries/05.jpg", width: 100%), caption: [Edgar's Awakening | Art by: <NAME>], supplement: none, numbering: none) Done with his meal, he dabs at his face with a handkerchief. Now he turns to face the crowd, now he takes in the sight. "Grandfather!" Sorin shouts. "Grandfather, she's controlling you—" It is only then that Edgar regards him, and only as a man might regard his unruly pet. The smile from only moments ago sags into sympathy. "Sorin, please. You're ruining the festivities." "The festivities?" Sorin repeats. He can't think of anything else to say. There was a small hope tucked away within him—a hope he hadn't even acknowledged—that Olivia's charms might fail to ensorcell his grandfather. Could it truly be so easy as this? His grandfather shows no signs of changing course. Olivia snaps her fingers; a host of thralls spring to action. Like spiders weaving a web, they swirl about him, helping him piece by piece into his wedding finery. Sorin's stomach sinks. He realizes, faintly, that the guards have stopped holding him back. He could move now if he wanted. But he can't summon the strength. Not as Olivia takes his grandfather's arm, not as the guests smile at him. "Why the long face? It isn't as if you'll be alone on the groom's side," Olivia says. He's too worn down to dignify it with a response. But she makes good on her word—he won't be. There are other coffins. He has so many relatives; it'd be impossible to store them all at Markov manor. Many slumbered on their own properties. And they hadn't escaped Olivia's notice. Olivia flits from one coffin to the other like a mad honeybee. A few drops is all it takes to start the process of waking the ancients. Somehow, despite Edgar being her promised husband, she never seems to take her eyes off Sorin. He wonders how much she knows. He wonders if she's picked them out by hand, the ancestors he most detested. He suspects that she has. It wouldn't be a difficult thing to do—he's rarely seen eye to eye with the rest of his family. He isn't sure when it happens, but it does, perhaps by the time his third aunt wakes from her slumber to sneer at him. <NAME> looks away. One by one, his family passes him by. One by one they kiss his cheeks and demand he does the same. All the while they say nothing, for there is nothing to be said. There's a wedding on, after all, and talking with Sorin always ruined the mood in Markov Manor.
https://github.com/Han-duoduo/mathPater-typest-template
https://raw.githubusercontent.com/Han-duoduo/mathPater-typest-template/main/chapter/chap6.typ
typst
Apache License 2.0
= 模型的评价与分析 模型的优点:在本题中,通过写出冲突、混淆和干扰三种情况对应的MR数矩阵,结合整数规划进行决策,从而求得较优解。在处理具体问题时,由于决策变量可能性太多,故根据概率论中的大数定律使用蒙特卡洛仿真模拟法从而避免了遍历,大大加速了模型的计算速度并且证明了在实验次数达到一定次数时所模拟的最优解是较好的局部解。在求解多目标规划时,采用分层序列方法,取一定范围内的较优解从而整个模型具有通用性,同时根据大数定律灵敏度较低,受到外界因素导致错误的概率较低。 模型的不足:由于蒙特卡洛法的无可避免的弊端性,在本模型中使用的蒙特卡洛方法与实际结果之间存在误差,每次模拟的结果具有随机性所以无法确保所得的解一定是全局最优解,只能得到较好的全局局部解。 模型的推广:在求解时,可以进一步与权重法相结合,进一步引入 三个权重,同时通过每次逐步微小的改变权重在使得模型更加准确的情况下可以进一步验证模型的稳定性。 总的来说,该模型基于概率论的大数定律采用的蒙特卡洛法加快计算速度并且稳定性较高。但缺少进一步的概率或者理论上的严格证明使得其具有一定的局限性,可以进一步更换遗传算法或者神经网络等启发式智能算法。
https://github.com/sdsc-ordes/modos-poster
https://raw.githubusercontent.com/sdsc-ordes/modos-poster/main/src/sdsc_poster.typ
typst
Creative Commons Attribution 4.0 International
#import "/src/themes/themes.typ" #import "/src/utils/scripts.typ"
https://github.com/sebaseb98/clean-math-thesis
https://raw.githubusercontent.com/sebaseb98/clean-math-thesis/main/chapter/conclusions_outlook.typ
typst
MIT License
= Conclusions and Outlook <chap:conclusions_outlook> #lorem(300)
https://github.com/RhenzoHideki/dlp2
https://raw.githubusercontent.com/RhenzoHideki/dlp2/main/relatorio-03/relatorio-03.typ
typst
#import "@preview/klaro-ifsc-sj:0.1.0": report #show: doc => report( title: "Modificações Timer", subtitle: "DISPOSITIVOS LÓGICOS PROGRAMÁVEIS II (DLP029007)", // Se apenas um autor colocar , no final para indicar que é um array authors:("<NAME>,<NAME>",), date: "2 de abril de 2024", doc, ) = Introdução No relatório será apresentado o desenvolvimento de um relógio digital, utilizando diferentes metodos e evoluções do código, começando com um clock de 50MHz e posteriormente utilizando um PLL para a geração de um sinal de clock de 10 kHz. #pagebreak() = Resolução == Adicionar o centesimo A primeira parte do projeto foi a adição do centésio de segundo. Inicialmente foi-se dado um código para ser adaptado. O código trabalhado tinha os contadores de segundos e de minutos. A implementação teve 2 etapas. Primeiramente ajustando o código que foi dado em aula e o adaptando para adicionar mais uma contagem , sendo essa os centisegundos . A segunta parte foi corrigir a contagem do clock , isso ocorreu pois o código original contava para o ciclo de 50 MHz seria igual a 1 segundo, porém agora seria necessário contar valores abaixo de 1 segundo , e como queriamos contra o centisegundo a adaptação foi dividir os contadores que geravam 1 segundo por 100 , dessa forma foi possível obter o centésimo de segundo. Esta parte foi a adição do centésio de segundo. A visualização do rtl ficou da seguinte maneira: #figure( image("./Figuras/q1.png",width:90%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); Visualização do .do para testar o código #figure( image("./Figuras/q1t.png",width:90%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); == Adicionar PLL A segunda parte do projeto foi a implementação da componente que converte o clock de 50MHz para 10KHz. A adição do PLL foi dada da seguinte forma : \ Compilar o código, seguir na aba ipcatalog e procurar pelo elemento ALTPLL #figure( image("./Figuras/ipcatalog.png",width:50%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); Selecionando o elemente ALTPLL será aberto uma aba nova, nesta aba serão configuradas os elementos para ser gerado o pll desejado. Primeiramente colaca-se a frequência correta de entrada em inclk0 input. #figure( image("./Figuras/ppl1.png",width:90%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); #pagebreak() Após colocar a frênquencia de entrada correta , é colocado na terceira pagina das configurações em "Output clock", nessa aba é necessário selecionar "Enter output clock frequency" para ajustar a frequência deseja, no caso deste projeto foi decidida a frequência de 10 MHz #figure( image("./Figuras/ppl2.png",width:90%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); Após a selecionar a frequência de saída , pula-se para a ultima etapa e seliciona-se tanto os arquivos com final .cmp e .vhd #figure( image("./Figuras/ppl3.png",width:90%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); Desta forma é gerado o arquivo PLL , que deverá ser inserido no top-level do código do projeto desejado. Abaixo parte do código gerado , nele é possivel ver os parâmetros para a converção de clock que ocorre ```vhdl GENERIC MAP ( bandwidth_type => "AUTO", clk0_divide_by => 5000, clk0_duty_cycle => 50, clk0_multiply_by => 1, clk0_phase_shift => "0", compensate_clock => "CLK0", inclk0_input_frequency => 20000, ``` Após inserir o pll o novo RTL ficou desta maneira: #figure( image("./Figuras/q2.png",width:90%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); Uma visualização do .do sendo executado para vizualizar o funcionamento do pll #figure( image("./Figuras/q2t.png",width:90%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); #pagebreak() == Modificar contadores para o BCD Nesta etapa do projeto foi desejada a remoção dos conversores BCD vistos nos RTLs anteriores. Para a adaptação do projeto foi primeiramente necessário remover os conversores Bin2BCD. Após esta remoção foi feita uma adaptação no código de contagem timer , esta que envolveu ao invés de contar-se os valores de unidade e decimais juntos , foi alterado para contagens separadas. Desta forma as contagens sairam de forma separada em unidade e decimal dos centisegundos , segundos e minutos. Dessa forma cumprindo o requisito da parte 3. Abaixo está o RTL da parte 3 , nele é possivel ver que houve a remoção dos conversores. #figure( image("./Figuras/q3.png",width:90%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); #figure( image("./Figuras/q3t.png",width:90%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); #figure( image("./Figuras/q3t2.png",width:90%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); == Modificar para o LFSR A quartar parte é remover os contadores e substitui-los por LFSR #figure( image("./Figuras/q4.png",width:90%), caption: [ Fonte: Elaborada pelo autor ], supplement: "Figura" ); #pagebreak() == Comparativos Como pedido , foi analizada as diferenças entres os resultados feitos nas diferentes partes. #align(center)[ #table( columns: (auto,auto,auto,auto,auto), align: center, [],[Binario],[Binario],[BCD],[BCD], [],[50M],[FreqGrupo],[FreqGrupo],[FreqGrupo LFSR], [LE],[262],[249],[86],[73], [Register],[124],[129],[37],[37], ) ] = Conclusão A partir da implementação das diferentes partes foi possível analizar a otimização dos sistemas. A utilização e redução de elementes mostra diretamente como a otimização pode afetar o espaço oculpado pelo código. A primeira etapa do Binario transicionando da primeira parte para a utilização do PLL reduzil a utilização de alguns elementos lógicos. A transição da segunda parte para a terceira foi a maior otimização , evitar códigos que convertem binário para BCD economizaram vários elementos lógicos. A terceita para quarta teve uma leve otimização , optando por não utilizar um contador convencional mas sim um contador LFSR
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/canvas-functions.typ
typst
#set page(width: auto, height: auto, margin: .5cm) #import "@preview/cetz:0.2.0": draw, chart #import "@preview/cetz:0.2.0" #let canvas-functions = ( line: draw.line, circle: draw.circle, rect: draw.rect, group: draw.group, grid: draw.grid, piechart: chart.piechart, bluechart: chart.piechart.with(inner-label: (content: (value, label) => [#text(blue, str(value))], radius: 110%)), // the label is right on the middle ) #let data = ( ([Belgium], 24), ([Germany], 31), ([Greece], 18), ([Spain], 21), ([France], 23), ([Hungary], 18), ([Netherlands], 27), ([Romania], 17), ([Finland], 26), ([Turkey], 13), ) #cetz.canvas({ // this stuff does something let colors = gradient.linear(red, blue, green, yellow) canvas-functions.at("bluechart")( data, value-key: 1, label-key: 0, radius: 4, slice-style: colors, inner-radius: 1, outset: 3, outer-label: (content: "%", radius: 110%)) })
https://github.com/NOOBDY/formal-language
https://raw.githubusercontent.com/NOOBDY/formal-language/main/q6.typ
typst
The Unlicense
#let q6 = [ 6. + Given an alphabet $Sigma$, for any language $L subset.eq Sigma^ast$, prove that $L^(**) = L^*$ and $L^*L^* = L^*$. Proof $L^(**) = L^*$ $ because L^*L^* &= L^* \ therefore L^(**) &= L^*L^* ... L^* \ &= L^* $ Proof $L^*L^* = L^*$ $ L^* L^* &= (L^+ union epsilon.alt)(L^+ union epsilon.alt) \ &= L L^+ union L^+ union epsilon.alt \ &= L^* $ + Prove that every finite language is regular. Every finite language can be accepted by a finite automata. + Given an example of a non-regular language $A$ and a regular language $B$ such that $A subset.eq B$. $ A &= {0^n 1^n | n in NN} \ B &= {0^n 1^m | n, m in NN} $ + Given an example of a non-regular language $A$ and a regular language $B$ such that $B subset.eq A$. $ A &= {0^n 1^n | n in NN} \ B &= {01} $ Let $L$ be any regular language over some $Sigma$. Define the languages: $ L^oo &:= union.big_(k >= 1){w^k | w in L}, \ L^(1/oo) &:= {w | w^k in L "for all" k >= 1}, \ sqrt(L) &:= {w^k in L "for some" k >= 1}. $ And also for any $k in NN$, let $ L^((k)) &:= {w^k | w in L}, \ L^((1/k)) &:= {w | w^k in L}. $ 5. Prove that $L^((1/3))$ is regular. + What about $L^((3))$? Not regular, $ "Let" L = a b^n \ L^((3)) = a b^n a b^n a b^n $ + Let $k in NN$. Prove that there are only finitely many languages of the form $L^((1/k))$ and that they are all regular. + Is $L^(1/oo)$ regular or not? + Is $sqrt(L)$ regular of not? + What about $L^oo$? Let the number of states be $n$ $ forall i in NN, n_i = sum_(k=1)^i k $ ]
https://github.com/Skimmeroni/Appunti
https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Statistica4AI/Introduction/Probability.typ
typst
Creative Commons Zero v1.0 Universal
#import "../Stats4AI_definitions.typ": * Probability provides methods to quantify chance and randomness related to a certain event. Any activity or process having at least one outcome, all being random (not knowable in advance) is called an *experiment*. The set containing all possible outcomes of an experiment, denoted as $cal(S)$, is called *sample space*. #exercise[ Provide some examples of experiments. ] #solution[ - The roll of a six-sided dice is an experiment, since the resulting value of the dice is unknown until the dice is rolled. The sample space $cal(S)$ contains $6$ elements: $ cal(S) = {1, 2, 3, 4, 5, 6} $ - The drawing of a card from a (standard) deck is an experiment, since the value of the card is unknown until the card is drawn. The sample space $cal(S)$ contains $52$ elements: $ cal(S) = { A suit.heart, 2 suit.heart, dots, Q suit.heart, K suit.heart, A suit.diamond, 2 suit.diamond, dots, Q suit.diamond, K suit.diamond, A suit.club, 2 suit.club, dots, Q suit.club, K suit.club, A suit.spade, 2 suit.spade, dots, Q suit.spade, K suit.spade} $ - The gender assigned to the offspring of a couple is an experiment, since their gender is unknown until (roughly) $4$ months since conception. The sample space $cal(S)$ contains $8$ elements: $ cal(S) = {M M M, M M F, M F M, F M M, M M F, F F M, F M F, F F F} $ ] Any subset of the sample space is called an *event*. An event can be either *simple* if it's a singleton (it contains a single outcome of the experiment) or *compound* otherwise (it contains multiple outcomes). An event can either occur or not occur, depending on the outcome of the experiment. #exercise[ Provide some examples of events. ] #solution[ - Consider the roll of a six-sided dice. The subset $A = {1, 3, 5}$ of the sample space $cal(S)$ corresponds to the event "an even number". It is a compound event; - Consider the drawing of a card from a deck. The subset $B = {A suit.heart, A suit.diamond, A suit.club, A suit.spade, K suit.heart, K suit.diamond, K suit.club, K suit.spade}$ of the sample space $cal(S)$ corresponds to the event "either an ace or a king of any set". It is a compound event; - Consider the gender assigned to the offspring of a couple. The subset $C = {F F F}$ of the sample space $cal(S)$ corresponds to the event "exclusively female offspring". It is a simple event. ] Being sets, events can be manipulated using set algebra. In particular, given two events $A$ and $B$: - The *complement* of $A$, denoted as $A^(c)$, corresponds to the event containing all outcomes not contained in $A$. That is, $A^(c)$ occurs if and only if $A$ does not occur. $A^(c)$ is also called the *complementary event* of $A$; - The *intersection* of $A$ and $B$, denoted as $A sect B$, corresponds to the event containing all outcomes contained both in $A$ and in $B$. That is, $A sect B$ occurs if and only if both $A$ and $B$ occur at the same time; - The *union* of $A$ and $B$, denoted as $A union B$, corresponds to the event containing all outcomes contained either in $A$, in $B$ or in both. That is, $A union B$ occurs if at most $A$ or $B$ occurs. #exercise[ Provide some examples of complemented, intersected and unified events. ] #solution[ - Consider the roll of a six-sided dice. The subset $A = {1, 2, 3, 4, 5}$ of the sample space $cal(S)$ corresponds to the event "any number but $6$". It is the complement of the event "exactly six"; - Consider the drawing of a card from a deck. The subset $B = {A suit.heart, A suit.diamond, A suit.club, A suit.spade, K suit.heart, K suit.diamond, K suit.club, K suit.spade}$ of the sample space $cal(S)$ is actually a union of two smaller events, the first being "an ace of any set" and the second being "a king of any set"; - Consider the gender assigned to the offspring of a couple. Consider the two events "a male as first born" and "a female as third born". Their intersection, representing the event "a male as first born and a female as third born" is given by: $ {M M M, M M F, M F M, M F F} sect {M M F, M F F, F M F, F F F} = {M M F, M F F} $ ] The empty set $emptyset$ denotes the event of having no outcome whatsoever, also called the *null event*. If the intersection of two events is the null event, such events are said to be *mutually esclusive* events, or *disjoint* events. In other words, two events are said to be mutually esclusive if they have no way of happening at the same time. // Add an example of disjoint events // Add some graphics concerning Venn diagrams Modern probability theory, like set theory, is defined axiomatically. Such axioms are also called *Kolmogorov axioms*, and are (supposed to be) the minimum amount of axioms that are needed to construct a theory of probability free of contradictions. To an event $A$, it is possible to associate a value called its *probability*, denoted as $P(A)$, that represents a measure of likelihood, certainty or confidence of such event to occur (intuitively, the higher the value of probability, the higher the likelihood). Probabilities obey three axioms, here stated: + For any event $A$, $P(A) gt.eq 0$. That is, the probability of an event happening is non negative; + $P(cal(S)) = 1$. That is, the probability of any even happening at all is fixed as $1$; + If $A_(1), A_(2), dots$ is a collection of countably infinite disjoint events, the following equality holds: $ P(A_(1) union A_(2) union dots) = sum_(i = 1)^(infinity) P(A_(i)) $ That is, given a set of events where no event can occur if at most another one of them occurs, the probability of any such event to occur is the sum of the individual probabilities. From such axioms, it is possible to derive many useful consequences. #theorem[ $P(emptyset) = 0$. That is, the null event cannot occur. ] <Null-event-has-probability-zero> #proof[ Consider the countably infinite collection of events $emptyset, emptyset, dots$. By definition, the null event is disjoint with itself, since set algebra gives $emptyset sect emptyset = emptyset$. The collection $emptyset, emptyset, dots$ is therefore made up of disjoint events, and by set algebra $emptyset union emptyset union dots = emptyset$, therefore $P(emptyset union emptyset union dots) = P(emptyset)$. Since by axiom $3$ $P(emptyset union emptyset union dots) = sum_(i = 1)^(infinity) P(emptyset)$, by transitive property $sum_(i = 1)^(infinity) P(emptyset) = P(emptyset)$. Since by axiom $1$ the value of $P(emptyset)$ has to be non negative, such equality can hold exclusively if $P(emptyset) = 0$. ] #theorem[ If $A_(1), A_(2), dots, A_(n)$ is a collection of finitely many disjoint events, the following equality holds: $ P(A_(1) union A_(2) union dots union A_(n)) = sum_(i = 1)^(n) P(A_(i)) $ ] <3rd-Kolmogorov-axiom-for-finite-collections> #proof[ Consider the countably infinite collection of events $A_(1), A_(2), dots, A_(n), A_(n + 1) = emptyset, A_(n + 2) = emptyset, dots, emptyset$, that is, a collection constructed by encoding countably infinitely many null events to the original collection. Applying axiom $3$ to such collection gives: $ P(A_(1) union A_(2) union dots A_(n) union emptyset union emptyset union dots union emptyset) = sum_(i = 1)^(infinity) P(A_(i)) $ It is possible to split the summation in two like so: $ P(A_(1) union A_(2) union dots union A_(n)) + P(emptyset union emptyset union dots union emptyset) = sum_(i = 1)^(n) P(A_(i)) + sum_(i = n + 1)^(infinity) P(emptyset) $ But by @Null-event-has-probability-zero, $P(emptyset) = 0$. Therefore: $ P(A_(1) union A_(2) union dots union A_(n)) + P(emptyset union emptyset union dots union emptyset) = P(A_(1) union A_(2) union dots union A_(n)) + 0 = sum_(i = 1)^(n) P(A_(i)) $ ] #theorem[ For any event $A$, $P(A) + P(A^(c)) = 1$. ] <Probability-of-complementary-event> #proof[ By definition of complementary event, $A union A^(c) = cal(S)$. They are also disjoint events, since one cannot happen it the other one happened. It is therefore possible to apply @3rd-Kolmogorov-axiom-for-finite-collections and state that $sum_(i = 1)^(2) P(A_(i)) = P(A) + P(A^(c)) = P(A union A^(c))$. But, as stated, $A union A^(c) = cal(S)$, and by axiom $2$ $P(cal(S)) = 1$. Therefore, by transitive property, $P(A) + P(A^(c)) = 1$. ] #theorem[ For any event $A$, $0 lt.eq P(A) lt.eq 1$. ] <Double-boundary-on-probability-value> #proof[ By @Probability-of-complementary-event, $P(A) + P(A^(c)) = 1$. By axiom $1$, both probabilities are greater or equal than $0$, therefore, for the equality to hold, both probabilities have to be lower or equal than $1$. Combining the two boundaries, $0 lt.eq P(A) lt.eq 1$. ] #theorem[ For any two events $A$ and $B$, $P(A union B) = P(A) + P(B) - P(A sect B)$. ] <Probability-of-union-of-two-generic-events> #proof[ By set algebra, the event $A union B$ can itself be seen as the union of two disjoint events, $A$ and $A^(c) sect B$. It is therefore possible to apply @3rd-Kolmogorov-axiom-for-finite-collections, resulting in: $ P(A union B) = P(A union (A^(c) sect B)) = P(A) + P(A^(c) sect B) $ In the same fashion, the event $B$ can be seen as the union of the disjoint events $A sect B$ and $A^(c) sect B$. Applying @3rd-Kolmogorov-axiom-for-finite-collections gives: $ P(B) = P((A sect B) union (A^(c) sect B)) = P(A sect B) + P(A^(c) sect B) $ Moving $P(A sect B)$ to the left side gives $P(B) - P(A sect B) = P(A^(c) sect B)$. Substituting such expression in the first equation gives $P(A union B) = P(A) + P(B) - P(A sect B)$. ] #theorem[ For any three events $A$, $B$ and $C$: $ P(A union B union C) = P(A) + P(B) + P(C) - P(A sect B) - P(A sect C) - P(B sect C) + P(A sect B sect C) $ ] <Probability-of-union-of-three-generic-events> #proof[ Works similarly as @Probability-of-union-of-two-generic-events. ] #theorem("Boole's inequality")[ Given any countable set of events $A_(1), A_(2), dots, A_(n)$: $ P(union.big_(i = 1)^(infinity) A_(i)) lt.eq sum_(i = 1)^(infinity) P(A_(i)) $ ] // #proof[ // If the events $A_(1), A_(2), dots, A_(n)$ are disjoint, // $P(union.big_(i = 1)^(infinity) A_(i))$ is indeed equal // to $sum_(i = 1)^(infinity) P(A_(i))$ by virtue of axiom // $3$. Otherwise, // ] It should be stressed that the Kolmogorov axioms simply describe the rules by which probability works, but do not define the probability of any event itself. Infact probabilities can be assigned to any event in any possible way that is constrained by the axioms, but such value can have no bare on reality or on intuition and yet construct a model that is consistent. #exercise[ Provide an example of a probability model that constrasts with reality but obeys Kolmogorov's axioms. ] #solution[ Consider the toss of a coin. Such action can be conceived as an experiment, since whose side the coin is gonna land when tossed is unknown until the coin lands. Only two events are possible, heads or tails; since a coin cannot land on both sides at the same time, such events are disjoint. It is a known fact that the probability of both events is $0.5$, and indeed such assignment respects all of three axioms. But by choosing the assignment, say, $0.2$ to the landing on heads and $0.8$ to the landing on tails, no axiom is violated, even though such an assignment has very little resonance with experience or common sense. This does not mean that probabilities can be assigned at libitum, since they still ought to comply with the axioms. For example, assigning $0.4$ to the probability of the coin to land on heads and $0.3$ to the probability of the coin to land on tails won't do, since axiom $2$ would be violated. As another example, assigning $1.5$ to the probability of the coin to land on heads and $-0.5$ to the probability of the coin to land on tails would violate axiom $1$, and therefore invalid. ] The appropriate or correct assignment depends on how one _interprets_ probability, that is to say how one intends the link between the mathematical treatment of probability and the physical world. This quest is just as philosophical as mathematical. One possible and often invoked interpretation of probability is the *objective* interpretation, also called *frequentist* interpretation. Consider an experiment that can be repeatedly performed in an identical and independent fashion, and let $A$ be an event consisting of a fixed set of outcomes of the experiment. If the experiment is performed $n$ times, the event $A$ will occur $n(A)$ times (with $0 lt.eq n(A) lt.eq n$) and will not occur $n - n(A)$ times. The ratio $n(A) slash n$ is called the *relative frequency* of occurrence of the event $A$ in the sequence of $n$ attempts. Empirical data suggests that the relative frequency fluctuates considerably if $n$ is a small number, while tends to stabilize itself as $n$ grows. Ideally, repeating such experiment infinitely many times, it would be possible to obtain a "perfect" frequency, called *limiting relative frequency*. The objective interpretation of probability states that this limiting relative frequency is indeed the probability of $A$ to occurr. // Provide an example, possibly introducing graphs such as the one on the // textbook This interpretation of probability is said to be objective in the sense that it rests on a property of the experiment and not on the concerns of the agent performing it (ideally, two agents performing the same experiment the same number of times would obtain the same relative limiting frequency, and therefore the same probability). This interpretation has limited appliability, since not all events can be performed $n$ number of times to draw similar conclusions. In situations such as these, it makes more sense to interpret probability in a *subjective* way, which can be thought of as the "degree of confidence" with which an agent believes an event to occur. The simplest situation to model is the one where to each simple event $E_(1), E_(2), dots, E_(N)$ is assigned the same value of probability $P(E_(i))$: $ 1 = sum_(i = 1)^(N) P(E_(i)) => P(E_(i)) = frac(1, N) $ That is, if there are $N$ equally likely outcomes, the probability of one of such outcomes to happen is $1 slash N$. More generally, consider an event $A$ containing $N(A)$ number of outcomes. Then the task of computing probabilities reduces itself to *counting*: $ P(A) = sum_(E_(i) in A) P(E_(i)) = sum_(E_(i) in A) frac(1, N) = frac(N(A), N) $ Given two events $A$ and $B$ with $P(B) > 0$, the probability of $A$ to occur given that $B$ occurred is called the *conditional probability* of $A$ given $B$, and is given as: $ P(A divides B) = frac(P(A sect B), B) $ // Why is the formula like so? #theorem("Law of total probability")[ Let $A_(1), A_(2), dots, A_(n)$ be a finite partition of a sample space $cal(S)$ such that no event has assigned zero probability, and let $B$ be any event in $cal(S)$. Then: $ P(B) = P(B divides A_(1)) P(A_(1)) + dots + P(B divides A_(n)) P(A_(n)) = sum_(i = 1)^(n) P(B divides A_(i)) P(A_(i)) $ // The graphical representation is actually kinda nice ] <Law-of-total-probability> // #proof[ // It can be retrieved on ProofWiki // ] #theorem("Bayes' theorem")[ Let $A_(1), A_(2), dots, A_(n)$ be a finite partition of a sample space $cal(S)$. Each event $A_(j)$ has a probability $P(A_(j))$, also called its *prior probability*, that is non zero. Let $B$ be any event in $cal(S)$ whose probability is non zero. The probability $P(A_(j) divides B)$, also called the *posterior probability*, is given as: $ P(A_(j) divides B) = frac(P(A_(j) sect B), P(B)) = frac(P(B divides A_(j)) P(A_(j)), sum_(i = 1)^(infinity) P(B divides A_(i)) P(A_(i))) $ ] <Bayes-theorem> // #proof[ // To be added // ] #exercise[ An electronics store sells three different brands of DVD players. Of its DVD player sales, $50 percent$ are brand $1$ (the least expensive), $30 percent$ are brand $2$, and $20 percent$ are brand $3$. Each manufacturer offers a $1$-year warranty on parts and labor. It is known that $25 percent$ of brand $1$'s DVD players require warranty repair work, whereas the corresponding percentages for brands $2$ and $3$ are $20 percent$ and $10 percent$, respectively. // Add the probability tree + What is the probability that a randomly selected purchaser has bought a brand 1 DVD player that will need repair while under warranty? + What is the probability that a randomly selected purchaser has a DVD player that will need repair while under warranty? + If a customer returns to the store with a DVD player that needs warranty repair work, what is the probability that it is a brand 1 DVD player? ] // #solution[ // What is the solution? Apply the law of total probability and Bayes theorem // ] // #exercise[ // Rare disease example from lecture // ] Consider two events, $A$ and $B$, the second happening after the first. The fact that $B$ occurred may or may not influence the probability of $A$ to occur. If the probability of $A$ to happen is the same whether or not $B$ happened, that is to say if $P(A)$ and $P(A divides B)$ are equal, The event $A$ is said to be *independent* of $B$. Otherwise, it's said to be *dependent* of $B$. #theorem[ Event independence is symmetric. In other words, given two events $A$ and $B$, if $A$ is independent of $B$, then $B$ is independent of $A$. ] <Event-independence-is-symmetric> #proof[ If $A$ is independent of $B$, then $P(A divides B) = P(A)$. Applying @Bayes-theorem gives: $ P(A divides B) = cancel(P(A)) = frac(P(B divides A) cancel(P(A)), P(B)) => P(B divides A) = P(B) $ Which, by definition, means that $B$ is independent of $A$ as well. ] An equivalent definition of independent events is as follows. Given two independent events $A$ and $B$, by the previous definition $P(A) = P(A divides B)$, so: $ P(A divides B) = frac(P(A sect B), P(B)) => P(A) = frac(P(A sect B), P(B)) => P(A sect B) = P(A) P(B) $ Event independence can be extended to a situation with more than two events. Given a collection of $n$ events $A_(1), A_(2), dots, A_(n)$, such events are said to be *mutually independent* if for every $k = 2, 3, dots, n$ and for every subset of indices $i_(1), i_(2), dots, i_(k)$: $ P(A_(i, 1) sect A_(i, 2) sect dots sect A_(i, k)) = P(A_(i, 1)) dot P(A_(i, 2)) dot dots dot P(A_(i, k)) $
https://github.com/YunkaiZhang233/a-level-further-maths-topic-questions-david-game
https://raw.githubusercontent.com/YunkaiZhang233/a-level-further-maths-topic-questions-david-game/main/fs1/chi-square.typ
typst
#import "../template.typ": * #import "../shortcut.typ": * #prob( [Edexcel IAL Statistics 3, June 2022, Q7], [ The following table shows observed frequencies, where $x$ is an integer, from an experiment to test whether or not a six-sided die is biased. #table( columns: (80pt, 60pt, 60pt, 60pt, 60pt, 60pt, 60pt), [Number on die], [1], [2], [3], [4], [5], [6], [Observed frequency], [$x + 6$], [$x - 8$], [$x + 8$], [$x - 5$], [$x + 4$], [$x - 5$], ) A goodness of fit test is conducted to determine if there is evidence that the die is biased. (a) Write down suitable null and alternative hypotheses for this test. #marks(1) It is found that the null hypothesis is not rejected at the 5% significance level. (b) Hence - (i) find the minimum value of $x$ #marks(8) - (ii) determine the minimum number of times the die was rolled. #marks(2) ] ) #prob( [Edexcel IAL S3, Jan 2021, Q3], [ The students in a group of schools can choose a club to join. There are 4 clubs available: Music, Art, Sports and Computers. The director collected information about the number of students in each club, using a random sample of 88 students from across the schools. The results are given in Table 1 below. #table( columns: (100pt, 60pt, 60pt, 60pt, 60pt), [], [Music], [Arts], [Sports], [Computers], [Number of students], [14], [28], [27], [19], ) The director uses a chi-squared test to determine whether or not the students are uniformly distributed across the 4 clubs. (a) (i) Find the expected frequencies he should use. Given that the test statistic he calculated was 6.09 (to 3 significant figures) (ii) use a 5% level of significance to complete the test. You should state the degrees of freedom and the critical value used. #marks(4) The director wishes to examine the situation in more detail and takes a second random sample of 88 students. The director assumes that within each school, students select their clubs independently. The students come from 3 schools and the distribution of the students from each school amongst the clubs is given in Table 2 below. #table( columns: (100pt, 60pt, 60pt, 60pt, 60pt), [School], [Music], [Arts], [Sports], [Computers], [School A], [3], [10], [9], [8], [School B], [1], [11], [13], [5], [School C], [11], [6], [7], [4], ) The director wishes to test for an association between a student's school and the club they choose. (b) State hypotheses suitable for such a test. #marks(1) (c) Calculate the expected frequency for School C and the Computers club. #marks(1) The director calculates the test statistic to be 7.29 (to 3 significant figures) with 4 degrees of freedom. (d) Explain clearly why his test has 4 degrees of freedom. #marks(2) (e) Complete the test using a 5% level of significance and stating clearly your critical value. #marks(2) ] )
https://github.com/adfaure/invoice-template
https://raw.githubusercontent.com/adfaure/invoice-template/main/README.md
markdown
MIT License
# invoice-template ## Install the template Install following: https://github.com/typst/packages/?tab=readme-ov-file#local-packages ## Result The file example.pdf shows an invoice example generated with this template. ## Compile Install typst, or use the flake file with `nix develop` Then `typst compile example.typ`
https://github.com/lyzynec/hys-or-kys
https://raw.githubusercontent.com/lyzynec/hys-or-kys/main/06/main.typ
typst
#import "../lib.typ": * #knowledge[ #question(name: [Define a reset system as a subset of hybrid systems.])[] #question(name: [Define a switched/switching systems and discuss the mechanisms for switching.])[] #question(name: [Define a piecewise affine (PWA) system.])[] #question(name: [Enumerate and briefly explain various concepts of a solution of an ordinary differential equation (classical, extended/Carathéodory, Filippov).])[] #question(name: [Explain the concept of a sliding mode.])[] ] #skills[ #question(name: [For a simple switched system, determine if the solution qualifies as Carathéodory or Filippov.])[] ]
https://github.com/dismint/docmint
https://raw.githubusercontent.com/dismint/docmint/main/security/quiz1.typ
typst
#import "template.typ": * #show: template.with( title: "Quiz 1", subtitle: "6.566" ) = OS and VM Isolation The motivation for this lecture is to solve the problem of isolation. We want to stop different containers from having access to each other to prevent malicious use cases. == Linux Processes Uses UIDs as well as per-file permissions, and is primarily used for fine-grained sharing between users rather than absolute isolation between two systems. == Linux Containers / Abstraction: Packaging software with all dependencies, useful if different versions of dependencies are needed. / Isolation: Ensure that code runs securely on the same machine as other apps. Namespaces enable control over what files, process, etc are visible, while cgroups control resource use to handle performance isolation and balance. The problem with using these two techniques is that there is still a shared kernel underneath, and with many ways to abuse the kernel. seccomp-bpf attempts to somewhat solve this issue by preventing what kind of system calls can be made, could not be good as it limits the kind of syscalls that can be used to more common ones, which may break compatibility with some software. VMs are a relatively foolproof solution, but have a high start-up cost and overhead. == Firecracker Uses KVM for virtual CPU and memory, have QEMU in Rust running, supporting a minimal set of devices. A block device is used instead of a disk. The Rust implementation should supposedly be memory safe and has a much smaller footprint than regular QEMU. Firecracker utilizes several safety mechanisms including chroot, namespaces, UIDs, and seccomp-bpf to ensure that any potential attacks can not be exploded into something much larger. KVM bugs still continue to be a large problem for Firecracker. == gVisor Reimplement the syscall interface in a separate user-space process. The rewritten Go system calls are less likely to have bugs, and any bugs that do happen aren't directly in the kernel so it's harder to exploit it. seccomp-bpf can be used for further control as well. There is an overhead in redirecting every single system call to gVisor. Gofer refers to the part of gVisor that can access the files, Sentry is the reimplementation of all the system calls. A common pattern we see is that of the supervisor monitoring processes. Firecracker offers only about a tenth of the system calls, gVisor allows a little more. = Software Fault Isolation Software fault isolation does not rely on hardware or OS support like virtualization, and is therefore a very powerful technique. However developers need to be looped in, as an existing binary can't be run in isolation. A modern version of SFI is found in WebAssembly. == WebAssembly An adversary can run any of the functions in the Wasm module, but should not be able to access memory outside of what's assigned to the sandbox.
https://github.com/topdeoo/NENU-Thesis-Typst
https://raw.githubusercontent.com/topdeoo/NENU-Thesis-Typst/master/layout/mainmatter.typ
typst
#import "../fonts/fonts.typ": font-family, font-size #import "@preview/i-figured:0.2.4" #import "@preview/numbly:0.1.0": numbly #import "../utils/format.typ": fake-par, unpack /// 正文部分设置 #let mainmatter( fonts: (:), // TODO 支持硕士论文的书写规范要求 text-args: auto, //! 标题配置 heading-font: auto, heading-size: (font-size.四号, font-size.小四, font-size.五号), heading-pagebreak: (true, false), heading-align: (center, auto), heading-padding: (top: 2*15.6pt - .7em, bottom: (2*15.6pt - .7em, 1.5*15.6pt - .7em)), //! 页眉配置 header-title: ("东北师范大学学士学位论文",), header-vspace: 0em, //! 段落配置 leading: 1.25 * font-size.五号 - 0.7em, spacing: 1.25 * font-size.五号 - 0.7em, justify: true, first-line-indent: 2em, figure-sep: " ", figure-caption-style: strong, ..args, it, ) = { //! 设置字体与字号 fonts = font-family + fonts if text-args == auto { text-args = (font: fonts.宋体, size: font-size.五号) } if heading-font == auto { heading-font = (fonts.宋体,) } let heading-text-args-lists = args.named().pairs().filter(pair => pair.at(0).starts-with("heading-")).map(pair => ( pair.at(0).slice("heading-".len()), pair.at(1), )) let array-at(arr, pos) = { arr.at(calc.min(pos, arr.len()) - 1) } //! 设置正文样式 //! 1. 文字与段落(文字大小,间距,段落行间距,缩进,代码块) set text(..text-args) set par( leading: leading, justify: justify, first-line-indent: first-line-indent, ) show par: set block(spacing: spacing) show raw: set text(font: fonts.等宽) //! 2. 脚注 show footnote.entry: set text(font: fonts.宋体, size: font-size.五号) //! 3. 图片&表格设置 show heading: i-figured.reset-counters show figure: i-figured.show-figure show figure.where(kind: table): set figure.caption(position: top) set figure.caption(separator: figure-sep) show figure.caption: figure-caption-style show figure.caption: set text(..text-args) //! 4. 公式编号 show math.equation.where(block: true): i-figured.show-equation //! 5. 列表显示(专业名词不缩进) show terms: set par(first-line-indent: 0pt) //! 标题 set heading( numbering: numbly( "第{1:一}章", "{1:1}.{2}", "{1}.{2}.{3}", ), ) show heading: it => { // TODO 取消此处的硬编码 if it.level == 1 { v(1em) } set text( font: array-at(heading-font, it.level), size: array-at(heading-size, it.level), weight: "bold", ..unpack(heading-text-args-lists.map(pair => (pair.at(0), array-at(pair.at(1), it.level)))), ) set block( above: heading-padding.top, below: array-at(heading-padding.bottom, it.level), ) it fake-par } show heading: it => { if (array-at(heading-pagebreak, it.level)) { if ("label" not in it.fields() or str(it.label) != "no-auto-pagebreak") { pagebreak(weak: true) } } if (array-at(heading-align, it.level) != auto) { set align(array-at(heading-align, it.level)) it } else { set align(left) it } } //! 页眉与页脚 set page(..( header: { counter(footnote).update(0) locate(loc => { // TODO 增加硕士/博士学位论文支持 set text(font: fonts.宋体, size: font-size.五号) set align(center) stack( header-title.at(0), v(.3em), line(length: 100%), ) v(header-vspace) }) }, numbering: (..idx) => { text(size: font-size.五号, numbering("1", idx.pos().first())) }, )) counter(page).update(1) it }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/ascii-ipa/1.1.0/src/lib.typ
typst
Apache License 2.0
#import "translations/branner.typ": * #import "translations/praat.typ": * #import "translations/sil.typ": * #import "translations/xsampa.typ": * #let apply-translations(content, translations, reverse) = { let (from, to) = if reverse {( 1, 0 )} else {( 0, 1 )} for translation in translations { content = content.replace(translation.at(from), translation.at(to)) } return content } #let translate(content, translations, reverse, override-font) = { let translation = apply-translations(content, translations, reverse) return if override-font { set text(font: "Linux Libertine") translation } else { translation } } #let branner(content, reverse: false, override-font: false) = translate(content, branner-translations, reverse, override-font) #let praat(content, reverse: false, override-font: false) = translate(content, praat-translations, reverse, override-font) #let sil(content, reverse: false, override-font: false) = translate(content, sil-translations, reverse, override-font) #let xsampa(content, reverse: false, override-font: false) = translate(content, xsampa-translations, reverse, override-font) #let phonetic(content) = [[#content]] #let phonemic(content) = [/#content/] #let orthographic(content) = [⟨#content⟩] #let prosodic(content) = [{#content}] #let phnt = phonetic #let phnm = phonemic #let orth = orthographic #let prsd = prosodic
https://github.com/xubaiw/typst-rote
https://raw.githubusercontent.com/xubaiw/typst-rote/main/README.md
markdown
# Typst Rote This package includes utility functions for creating rote learning materials in typst. These functions utilize the `terms` and `underline` elements to create cloze test and mnemonic test. See `example.typ` for basic usage. ## Installation This package is not mature enough to be published to Typst Universe. You can use the [utpm](https://github.com/Thumuss/utpm) package manager to make a local clone. ## Roadmap - [x] `#cloze(content)` - [x] `#mnemonic(content)` - [ ] link between different parts
https://github.com/alerque/polytype
https://raw.githubusercontent.com/alerque/polytype/master/content/prime-symbol.md
markdown
+++ title = "The Prime Symbol" description = "In math mode, prime-time is always a good time." extra.typesetters = [ "typst", "sile", "xelatex", "groff" ] extra.typesetter_args = { groff = "-e -P-pA7" } +++ Assorted ways of entering and rendering the troublesome prime symbol. One issue is in math mode. A typesetter has to account for how different fonts position their prime symbols. Another problem crops up in text where quotes marks get used for things like feet and inch units in lengths or minute and second units in latitude and longitude coordinates. It should be possible to *not* trigger smart quotes in these cases.
https://github.com/saurabtharu/Internship-repo
https://raw.githubusercontent.com/saurabtharu/Internship-repo/main/Internship%20Report%20-%20typst/chapters/chapter-4-conclusion%20and%20learning%20outcomes.typ
typst
#import "../template.typ": * = Chapter 4: Conclusion and Learning Outcomes \ /* == 4.1. Completed Tasks #v(15pt, weak: true) #set enum(numbering: "i.") + Sucessfully deployed nginx website and implemented SSL Certificate for secure communication. + Deployed Java Application in tomcat and configured nginx for reverse proxy for the java application. + Configured to monitor a particular process and send alert on crashes. + Configured self-hosted git service on local infrastructure . + Setup MySQL replication for data backup and incident recovery + Configured distributed file system (NFS) to share files among various nodes within a network. == 4.2 Remaining Tasks + ArgoCD for continuous delivery. + K3S for managing workload and services. */ == 4.1. Conclusion #v(15pt, weak: true) In conclusion, the internship at F1Soft International as a DevOps Engineer exposed me to various aspects of DevOps. This included knowledge gain in diverse DevOps areas like deployment of website with SSL/TLS certificate, Virtual Machine networking, containerization and utilizing Kubernetes (K3s) for container orchestration, implementation of monitoring tools such as Prometheus and Grafana. Practical task were done using theoretical knowledge acquired from the program. At the end of it all, adopting different DevOps methodologies that were learnt brought about better system performance and reliability. With the help of mentors and other colleagues, my interpersonal skills were also sharpened during this internshipr period henceforth having a huge positive influence on me both professionally and personally. #v(10pt) == 4.2. Learning Outcome #v(15pt, weak: true) Here are the key areas where I gained substantial knowledge and practical experience: #set enum(numbering: "i.") + *Technical Skills* \ Developed my technical skills like operating system troubleshooting, managing bare-metal infrastructure, automating repeated tasks with bash script. Got opportunity to dig deep into using linux command line as well as monitoring tools like monit, prometheus, and grafana. Learned about monitoring various process of linux and send email alert if needed. Along with this various other tools like ansible, used for DevOps were learned. + *Professional Development* \ Enhanced the ability to work effectively in a team-oriented environment. Problem-solving skills were improved by addressing real-world technical challenges and implementing practical solutions. Professional growth was further shaped by the mentorship and guidance received from experienced professionals. + *Time Management* \ Effective time management was crucial during the internship, as multiple tasks were assigned simultaneously. Work was prioritized, achievable goals were set, and deadlines were consistently met. + *Documentation* \ The importance of thorough documentation was emphasized throughout the internship. Detailed records of configurations, processes, and performance metrics were maintained, ensuring transparency and reproducibility. Comprehensive reports and documentation were compiled to communicate project progress, improving technical writing and communication skills. + *Continuous Learning* \ A habit of continuous learning was cultivated during the internship, encouraging the intern to stay updated with the latest industry trends and advancements. Self-directed learning was regularly engaged in, exploring new tools and technologies to enhance existing systems and processes /* Throughout my internship at F1Soft International, I was exposed to a comprehensive range of DevOps practices and technologies, which significantly expanded my technical skill set and deepened my understanding of DevOps in a real-world fintech environment. Here are the key areas where I gained substantial knowledge and practical experience: #set enum(numbering: "i.") + *Linux*: \ I extensively used Linux operating systems, mastering both basic and advanced functionalities such as file system management, user and group permissions, process management, and shell scripting. Proficiency in Linux was fundamental for server management and deployment processes, forming the backbone of my daily tasks. + *Networking Concepts*: \ I developed a robust understanding of networking principles, including TCP/IP, DNS, DHCP, and subnetting. Additionally, I learned to configure and manage network interfaces and services, ensuring seamless communication and security within the infrastructure. This knowledge was essential for designing and maintaining reliable network setups. + *Nginx Website Hosting*: \ I gained hands-on experience configuring and managing Nginx for web hosting. This involved setting up virtual hosts, configuring SSL certificates for HTTPS, and optimizing Nginx performance for handling high-traffic scenarios. These skills ensured that web applications were secure, accessible, and performant. + *Tomcat Web Hosting*: \ I worked extensively with Apache Tomcat, deploying and managing Java web applications. This included configuring Tomcat servers, optimizing performance, and ensuring security. Understanding Tomcat’s architecture and deployment processes was crucial for managing enterprise-level web applications. + *Load Balancing and Reverse Proxy with Nginx*: \ I implemented load balancing and reverse proxy solutions using Nginx, distributing incoming traffic across multiple backend servers to enhance reliability and scalability of web applications. This setup improved security and performance by offloading tasks from backend servers. + *HAProxy and Keepalived for Load Balancing*: \ I used HAProxy and Keepalived to set up robust load balancing and failover solutions. HAProxy efficiently managed high traffic volumes, while Keepalived provided failover capabilities to ensure high availability. This combination was crucial for maintaining uninterrupted service. + *Using Firewalld*: \ I configured and managed the built-in firewall (Firewalld) in Linux systems to enhance security. Setting up firewall rules to control network traffic was essential for protecting the infrastructure from unauthorized access and potential threats. + *Containerization*: \ I explored containerization technologies, focusing on Docker. This included creating, managing, and orchestrating containers to ensure consistent and efficient application deployment across different environments. Containerization streamlined the deployment process and ensured consistency. + *Containerizing Tomcat Websites*: \ I containerized Tomcat-based web applications, simplifying deployment and ensuring consistency across development, staging, and production environments. This involved creating Docker images for Tomcat applications, configuring Docker Compose, and managing container lifecycles. + *SSL for HTTPS*: \ I implemented SSL certificates to secure web applications by enabling HTTPS, ensuring data integrity and security during transmission. Generating and managing SSL certificates and configuring web servers to use them were critical for secure communications. + *Self-Hosting Git Services*: \ I set up and managed self-hosted Git services like Gitea and Gogs. This included configuring repositories, managing user access, and ensuring the security and availability of version control systems. Self-hosted Git services provided greater control over source code management. + *Using MinIO for Object Storage*: \ I utilized MinIO, an open-source object storage solution, to set up and manage scalable and high-performance storage infrastructure. MinIO enabled secure and efficient storage of large amounts of unstructured data. + *Monitoring and Alerts with Monito*: \ I configured monitoring tools like Monito to track system performance and send email notifications when specific triggers or thresholds were met. This proactive system management helped quickly identify and resolve issues, minimizing downtime and ensuring optimal performance. + *Bash Scripting*: \ I developed proficiency in Bash scripting for automating repetitive tasks, streamlining workflows, and enhancing productivity. Automating complex tasks with Bash scripting reduced human error and saved time. + *Network File System (NFS) for Synchronization*: \ I implemented NFS to enable file sharing and synchronization across multiple servers, facilitating seamless data access and collaboration. NFS was crucial for environments requiring consistent and shared data access. + *Using Monitoring Tools (Uptime-Kuma, Grafana, Prometheus, Loki)*: \ I deployed and configured monitoring tools to track system health, performance metrics, and log management. Uptime-Kuma provided uptime monitoring, Grafana offered data visualization, Prometheus handled time-series data, and Loki managed log aggregation. These tools provided comprehensive insights into system operations, aiding proactive maintenance and troubleshooting. + *MySQL Replication*: \ I set up and managed MySQL replication to ensure data redundancy and high availability. Configuring master-slave replication, monitoring replication status, and managing failover scenarios were essential for maintaining data integrity and minimizing downtime in case of failures. + *Self-Hosted Docker Registry*: \ I configured and managed a self-hosted Docker registry to securely store and distribute Docker images within the organization. This provided greater control over the deployment pipeline and ensured the availability of Docker images for various environments. + *Cryptography and Public Key Infrastructure (PKI)*: \ I gained knowledge in cryptography and PKI, including implementing encryption techniques, key management, and digital certificates to secure communications and data. Understanding cryptography was critical for protecting sensitive information and ensuring secure transactions. + *K3s and Rancher for Kubernetes Management*: \ I used K3s and Rancher to deploy, manage, and scale Kubernetes clusters. K3s provided a lightweight Kubernetes distribution, while Rancher offered a user-friendly interface for cluster management. These tools enabled efficient orchestration and management of containerized applications. + *Managing Linux LVM Partitions*: \ I acquired skills in managing Logical Volume Manager (LVM) partitions on Linux systems, enabling flexible disk space management and storage optimization. LVM allowed for dynamic resizing of disk partitions, facilitating better resource utilization and storage management. These experiences have significantly enhanced my technical skills and prepared me for future roles in the DevOps field. The comprehensive exposure to various tools, technologies, and practices has equipped me with the knowledge and confidence to tackle complex DevOps challenges and contribute effectively to any technology-driven organization. */ #pagebreak()
https://github.com/UBOdin/data_structures_book
https://raw.githubusercontent.com/UBOdin/data_structures_book/main/chapters/4-lists.typ
typst
#import "@preview/cetz:0.2.2" = The Sequence and List ADTs Now that we have the right language to talk about algorithm runtimes (asymptotic complexity), we can start talking about actual data structures that these algorithms can use. Since the choice of data structure can have a huge impact on the complexity of an algorithm, it's often useful to group specific data structures together by the roles that they can fulfill in an algorithm. We refer to such a grouping as an *abstract data type* or ADT. == What is an ADT? An ADT is, informally, a contract that states what we can expect from a data structure. Take, for example, a Java `interface` like the following: ```java public interface Narf<T> { public void foo(T poit, int zort); public T bar(int zort); public int baz(); } ``` This `interface` states that any class that implements `Narf` must provide `foo`, `bar`, and `baz` methods, with arguments and return values as listed above. This is not especially helpful, since it doesn't give us any idea of what these methods are supposed to do. Contrast `Narf` with the following interface: ```java public interface MutableSequence<T> { public void set(int index, T element); public T get(int index); public int size(); } ``` `Sequence` is semantically identical to `Narf`, but far more helpful. Just by reading the names of these methods, you get some idea of what each method does, and how it interacts with the state represented by a `Sequence`. You can build a mental model of what a Sequence is from these names. An Abstract Data Type is defined in three parts: 1. Formal rules for the type of data being stored (a data type). 2. One or more operations for accessing or modifying that state (an interface). 3. Any other rules for the state (constraints). For most ADTs discussed in this book, the ADT models sort of collection of elements. The difference between them is how you're allowed to interact with the data. A data structure is a *specific* strategy for organizing the data modeled by an ADT. We say that the data structure implements (or conforms to) an ADT if: 1. The data structure stores the same type of data as the ADT 2. Each of the operations required by the ADT can be implemented on the data structure 3. We can prove that the operation implementation is guaranteed to respect the rules for the ADT's state. == The Sequence ADT A very common example of an ADT is a sequence. Examples include: - The English alphabet ('A', 'B', ..., 'Z') - The Fibonacci Sequence (1, 1, 2, 3, 5, 8, ...) - An arbitrary collection of numbers (42, 19, 86, 23, 19) What are some commonalities in these examples? - Every sequence is a collection of elements of some type `T` (integer, character, etc...) - The same element may appear multiple times. - Every sequence has a size (that may be infinite). We often write $N$ to represent this size. - Every element (or occurrence of an element) is assigned to an index: $0 <= "index" < N$. - Every index in the range $0 <= "index" < N$ has exactly one element assigned to it. What kind of operations can we do on a sequence#footnote[ Note: Although several of the ADTs and data structures we'll present throughout this book correspond to interfaces and classes from the Java standard library, `Sequence` is *not* one of them. However, it serves as a useful simplification of the `List` interface from the Java standard library that we *will* encounter later on. ]? ```java public interface Sequence<T> { /** Retrieve the element at a specific index or throw an IndexOutOfBounds exception if index < 0 or index >= size() */ public T get(int index); /** Obtain the size of the sequence */ public int size(); } ``` To recap, we have a mental model, and a series of rules: - A sequence contains $N$ elements. - Every index $i$ from $0 <= i < N$ identifies exactly one element (no more, no less). The `get` method returns the element identified by `index`, and the `size` method returns $N$. === Sequences by Rule For some of the example sequences listed above, we can implement this interface directly. For example, for the English alphabet: ```java public class Alphabet implements Sequence<Character> { /** Retrieve the element at a specific index */ public Character get(int index) { if(index == 0){ return 'A'; } if(index == 1){ return 'B'; } /* ... */ if(index == 25){ return 'Z'; } throw IndexOutOfBoundsException("No character at index "+index) } /** Obtain the size of the sequence */ public int size() { return 26; } } ``` Is `Alphabet` a sequence? Yes! It implements the two operations of a sequence: - `size`: There are $N = 26$ elements. - `get`: Every element from $0 <= i < 26$ is assigned exactly one value. Similarly, we can implement the Fibonacci sequence according to the Fibonacci rule $"Fib"(x) = "Fib"(x-1) + "Fib"(x-2)$: ```java public class Fibonacci implements Sequence<Int> { /** Retrieve the element at a specific index */ public Int get(int index) { if(index < 0){ throw IndexOutOfBoundsException("Invalid index: "+index) } if(index == 0){ return 0; } if(index == 1){ return 1; } return get(index-1) + get(index-2); } /** Obtain the size of the sequence */ public int size() { return INFINITY; } } ``` Is `Fibonacci` a sequence? Yes! It implements the two operations of a sequence: - `size`: There are $N = infinity$ elements. - `get`: Every element from $0 <= i < infinity$ is assigned exactly one value derived from the value of preceding elements of the sequence as $"Fib"(i-1) + "Fib"(i-2)$#footnote[ If you're paying attention, you might notice that we're waving our hands a bit with this proof. Specifically, how do we convince ourselves that there is *exactly* one value at index $i$, and not zero (can $"Fib"(i)$ return `IndexOutOfBoundsException` for $i >= 0$), or more than 1 (will $"Fib"(i)$ always return the same value)? Proving either of these will require a technique called *induction* that we'll come back to later in the book. ]. === Arbitrary Sequences Often, however, we want to represent an sequence of *arbitrary* elements. We won't have simple rule we can use to translate the index into a value. Instead, we need to store the elements somewhere if we want to be able to retrieve them. The easiest way to store a sequence, when we know the size of the sequence up front is called an *array*. Let's take a brief diversion into the guts of a computer. Most computers store data in a component called RAM#footnote[ What you're about to read is called the RAM model of computing. It is a blatant lie: The way computers store and access data involves multiple levels of caches, disks, and networked storage. However, the RAM model is quite useful as a starting point. We'll walk the lie back when we introduce the External Memory model towards the end of the book. ]. You can think of RAM as being a ginormous sequence of bits (0s and 1s). Folks who work on computers have, over the course of many years, come to agree on some common guidelines for how to represent other types of information in bit sequences. The details of most of these guidelines (e.g., Little- vs Big-endian, Floating-point encodings, Characters and strings, etc...) are usually covered in a computer organization or computer architecture class. However, there's a few details that are really helpful for us to review. First, we group every 8 bits into a 'byte'. A byte can take on $2^8 = 256$ different possible values. It turns out that this is enough to represent most simple printable characters. Similarly, bytes can be grouped together into 2, 4, or 8 bytes, allowing us to represent more complex data like emoji, larger integers, negative numbers, or floating point numbers. Strings are a special case that we'll come back to in a moment. For example, the ASCII character encoding#footnote[ The American Standard Code for Information Interchange forms the basis for most modern character 'encodings'. More recent encodings (e.g. UTF-8, UTF-16) extend the ASCII code, and sometimes require more than one byte per printable character. ] forms the basis for most character representations we use today, and assigns each of the letters of the English alphabet (upper and lower case, and a few other symbols) to a particular sequence of 8 bits (one byte). Most modern computers are 'byte-addressable', meaning that every byte is given its own address. The first byte is at address 0000, followed by address 0001, then address 0002, and so forth. If we want to represent a value that takes up multiple bytes (e.g., a 4-byte integer), we typically point at the address of the first byte of the value. === Arrays Let's say we have a series of values we want to store. For example, let's say we wanted to store the sequence 'H', 'e', 'l', 'l', 'o'. The ASCII code for 'H' is hexadecimal 0x48, or binary 01001000. We could store that value at one specific address in RAM. The value takes up one byte of space, so we could put the second value in the sequence 'e' (hexadecimal 0x65, or binary 10101001) in the byte right after it. We then similarly store the remaining three elements of the sequence, each in the byte after the previous one. #figure( image("graphics/lists-memory-array.svg", width: 50%), caption: [ RAM (1) can be viewed as a sequence of bits (2). We can break these bits up into fixed size chunks (3). Each fixed size chunk can be used to identify some value, like for example a character (4). Thus a sequence of characters can be stored somewhere in RAM (5). ] ) This arrangement, where we just concatenate elements side by side in memory is really useful, _if each element always uses up the same number of bytes_. Specifically, if we want to retrieve the $i$th element of the sequence, we need only two things: 1. The position of the 0th element in RAM (Let's call this $S$) 2. The number of bytes that each element takes up (Let's call this $E$). The the $i$th element's $E$ bytes will always start at byte $S + i dot E$ (with 0 being the first element). ==== Array Runtime Analysis In order to retrieve the $i$'th element of an array, we need one multiplication, and one addition. This is true regardless of how big the array is. If the array has a thousand, or a million, or a trillion elements, we can still obtain the address of the $i$th element with one multiplication and one addition. Given the address, we can then obtain the value in a single access to memory. In other words, the cost of retrieving an element from an array is constant (i.e., $Theta(1)$)#footnote[ If you're paying close attention, you might note that we still need to retrieve $E$ bytes, and so technically the cost of an array access is $Theta(E)$. However, we're mainly interested in how runtime scales with the size of the collection, as $E$ is fixed upfront, and usually very small. So, more precisely, *with respect to $N$*, the cost of retrieving an element from an array is $Theta(1)$. The even more attentive reader might be aware of things like caches, which as previously mentioned, we're going to ignore for now. ]. ==== Side Note: Memory Allocation Most operating systems provide a way to allocate contiguous regions of memory (in C, this operation is called `malloc`, in Java it is called `new`). Eventually, when the data is no longer necessary (C's `free` operation, or based on Java's automatic 'garbage collector'), the allocated memory is returned to the general pool of 'free' memory. We will assume that both allocating and freeing memory are constant-time ($Theta(1)$) operations#footnote[ Again, this is a lie. Depending on the operating system's implementation (e.g., if it allocates pages lazily or not), allocating memory may require linear time in the size of the allocation, or non-constant (e.g., logarithmic or linear) time in the number of preceding allocations. Nevertheless, for the rest of the book, we'll treat it as being constant ] It's important to note that once memory is allocated, it has a fixed size. It is not generally possible to simply resize a previously allocated chunk of memory, since that memory is located at a specific position in RAM, and it is possible that the space immediately following the array may already be in-use#footnote[ C provides a `realloc` operation that opportunistically _tries_ to extend an allocated chunk of memory if space exists for it. However, if this is not possible, the entire allocation will be copied byte-for-byte to a new position in memory where space does exist. As we'll emphasize shortly, copying an array is a linear ($Theta(N)$) operation. ]. ==== Arrays In Java Java provides a convenient shorthand for creating and accessing arrays using square brackets. To instantiate an array, use `new`: ```java int[] myArray = new int[100]; ``` Note that the type of an integer array is `int[]`#footnote[ Java sort of allows you to store variable size objects in an array. For example, `String[]` is a valid array type. The trick to this is that Java allocates the actual string _somewhere else in RAM_ called the heap. What it stores in the actual array is the address of the string (also called a pointer). ], and the number of elements in the array must be specified upfront (`100` in the example above). To access an element of an array use `array[index]`. ```java myArray[10] = 29; int myValue = myArray[10]; assert(myValue == 29); ``` Java arrays are *bounds-checked*. That is, Java stores the size of the array as part of the array itself. The array actually starts 4 bytes after the official address of the array; these bytes are used to store the size of the array. Whenever you access an array element, Java checks to make sure that the index is greater than or equal to zero and less than the size. If not, it throws an `IndexOutOfBounds` exception otherwise. As a convenient benefit, bounds checking means we can get the array size from Java. ```java int size = myArray.size assert(size == 100) ``` Since the size is stored at a known location, we can always retrieve it in constant ($O(1)$) time. To prove to ourselves that the `Array` implements the `Sequence` ADT, we can implement its methods: ```java public class ArraySequence<T> implements Sequence<T> { T[] data; public ArraySequence(T[] data){ this.data = data; } public T get(int index) { return data[index]; } public int size() { return data.size; } } ``` The `ArraySequence`, initialized by an array, follows the rules for a `Sequence`: - `size`: There are $N = $`data.size` elements in the array - `get`: The `i`th element of the sequence is `data[i]`. === Mutable Sequences The Fibonacci sequence and the English alphabet are examples of *immutable* sequences. Immutable sequences are pre-defined and can not be changed; We can't arbitrarily decide that the 10th Fibonacci number should instead be 3. However, if the sequence is given explicitly (e.g., as an array), then it's physically possible to just modify the bytes in the array to a new value. To accommodate such edits, we can make our `Sequence` ADT a little more general by adding a way to modify its contents. We'll call the resulting ADT a `MutableSequence`#footnote[ Note: Like `Sequence`, the `MutableSequence` is not a native part of Java. Its role is subsumed by `List`, which we'll discuss shortly. ]. ```java public interface MutableSequence<T> extends Sequence<T> { public void set(int index, T element) } ``` The `extends` keyword in java can be used to indicate that an interface takes in all of the methods of the extended interface, and potentially adds more of its own. In this case `MutableSequence` has all of the methods of `Sequence`, plus its own `set` method. A Mutable Sequence introduces one new rule: - After we call `set(i, value)` with a valid index (i.e., $0 <= i < N$), every following call to `get(i)` for the same index will return the `value` passed to set (until the next time index `i` is set). ==== Mutable Array To prove to ourselves that the array implements the `MutableSequence` ADT, we can implement its methods: ```java public class MutableArraySequence<T> implements MutableSequence<T> { T[] data; public ArraySequence(int size){ this.data = new T[size]; } public void set(int index, T element) { data[index] = value; } public T get(int index) { return data[index]; } public int size() { return data.size; } } ``` As before, we can show that the array satisfies the rules on `get` and `size`, leaving the new rule: - `set`: Calling set overwrites the array element at `data[index]` with value, which is the value returned by `get(index)`. === Array Summary Observe that each of the three `MutableSequence` methods are implemented in a single, primitive operation. Thus: - `get`: Retrieving an element of an Array (i.e., `array[index]`) is $Theta(1)$ - `set`: Updating an element of an array (i.e., `array[index] = ...`) is $Theta(1)$ - `size`: Retrieving the array's size (i.e., `array.size`) is $Theta(1)$ Recall that `size` accesses a pre-computed value, stored with the array in Java. //////////////////////////////////////////// == The List ADT Although we can change the individual elements of an array, once it's allocated, the size of the array is fixed. This is reflected in the `MutableSequence` ADT, which does not provide a way to change the sequence's size. Let's design our next ADT by considering how we might want to change an array's size: - Inserting a new element at a specific position - Removing an existing element at a specific position It's also useful to treat inserting at/removing from the front and end of the sequence as special cases, since these are both particularly common operations. We can summarize these operations in the `List` ADT#footnote[ See Java's #link("https://docs.oracle.com/javase/8/docs/api/java/util/List.html")[List interface] for the full list of operations supported on `List`s. Most of these operations are so-called syntactic sugar on top of these basic operations, offering cleaner code, but no new functionality. ]: ```java public interface List<T> extends MutableSequence<T> { /** Append an element to the end of a list */ public void add(T element); /** Insert an element at an arbitrary position */ public void add(int index, T element); /** Remove an element at a specific index */ public void remove(int index); // ... and more operations that are not relevant to us for now. } ``` `List` brings with it a new set of rules: - After calling `add(index, element)` with a valid $0 <= "index" <= N$ (note that $N$ is an allowable index): - Every element previously at an index $i >= "index"$ will be moved to index $i+1$ - The value `element` will be the new element at index $"index"$, - `size()` will increase by 1. - After calling `remove(index)` with a valid $0 <= "index" < N$: - Every element previously at an index $i > "index"$ will be moved to index $i-1$ - The value previously at index $"index"$ will be removed - `size()` will decrease by 1. Note that calling `add(element)` is the same as calling `add(element, size())`. === A simple Array as a List We can still use `Array`s to implement the `List` ADT. However, recall that it's not (generally) possible to resize a chunk of memory once it's been allocated. Since we can't change the size of an `Array` once it's allocated#footnote[ Again, the C language has a method called `realloc` that can *sometimes* change the size of an array... if you're lucky and the allocator happens to have some free space right after the array. However, in this book we try to avoid relying purely on unconstrained luck. ], we'll need to allocate an entirely new array to store the updated list. Once we allocate the new array, we'll need to copy over everything in our original array to the new array. ```java public class SimpleArrayAsList<T> extends MutableArraySequence implements List<T> { // data, get, set, size() inherited from MutableArraySequence public void add(T element){ add(size(), element); } public void add(int index, T element) { // Skipped: Check that index is in-bounds. T[] newData = new data[size() + 1]; for(i = 0; i < newData.length; i++){ if(i < index){ newData[i] = data[i]; } else if(i == index){ newData[i] = element; } else { newData[i] = data[i-1]; } } data = newData; } public void remove(int index) { // Skipped: Check that index is in-bounds. T[] newData = new data[size() - 1]; for(i = 0; i < newData.length; i++){ if(i < index){ newData[i] = data[i]; } else { newData[i] = data[i+1]; } } } } ``` Does this satisfy our rules? - `add`: `newData` is one larger, elements at positions `index` and above are shifted right by one position, and `element` is inserted at position `index`. - `remove`: `newData` is one smaller, and elements at positions `index` and above are shifted left by one position. Let's look at the runtime of the `add` method: - We'll assume that memory allocation is constant-time ($Theta(1)$)#footnote[ Lies! Lies and trickery! Memory allocation may require zeroing pages, multiple calls into the kernel, page faults, and a whole mess of other nonsense that scale with the size of the memory allocated. Still, especially for our purposes here, it's usually safe to assume that the runtime of memory allocation is a bounded constant. ]. - We already said that array changes and math operations are constant-time ($Theta(1)$) So, we can view the the `add` method as ```java public void add(int index, T element) { /* Theta(1) */ for(i = 0; i < newData.size; i++) { if(/* Theta(1) */){ /* Theta(1) */ } else if(/* Theta(1) */){ /* Theta(1) */ } else { /* Theta(1) */ } } } ``` Since every branch of the `if` inside the loop is the same, we can simplify the loop body to just $Theta(1)$. Recalling how we use $Theta$ bounds in an arithmetic expression, we can rewrite the runtime and simplify it as: - $T_"add"(N) = Theta(1) + sum_(i = 0)^"newData.size" Theta(1)$ - $ = Theta(1) + sum_(i = 0)^(N+1) Theta(1)$ (`newData` is one bigger than the original $N$) - $ = Theta(1) + (N+2) dot Theta(1)$ (Plugging in the formula for summation of a constant) - $ = Theta(1+N+2)$ (Merging $Theta$s) - $ = Theta(N)$ (Dominant term) If you analyze the runtime of the `remove` method similarly, you'll likewise get $Theta(N)$. == Linked Lists $Theta(N)$ is not a particularly good runtime for simple "building block" operations like `add` and `remove`. Since these will be called in loops, the `Array` data structure is not ideal for situations where a `List` is required. The main difficulty with the `Array` is that the entire list is stored in the same memory allocation. A single chunk of memory holds all elements in the list. So, instead of allocating one chunk for the entire list, we can go to the opposite extreme and give each element its own chunk. Giving each element its own chunk of memory means that we can allocate (or free) space for new elements without having to copy existing elements around. However, it also means that the elements of the list are scattered throughout RAM. If we want to be able to find the $i$th element of the list (which we need to do to implement `get`), we need some way to keep track of where the elements are stored. One approach would be to keep a list of all $N$ addresses somewhere, but this brings us back to our original problem: we need to be able to store a variable-size list of $N$ elements. Another approach is to use the chunks of memory as part of our lookup strategy: We can have each chunk of memory that we allocate store the address of (i.e., a pointer to) the *next* element in the list. That way, we only need to keep track of a single address: the position of the *first* element of the list (also called the list head). The resulting data structure is called a linked list. @linked_list_vs_array contrasts the linked list approach with an `Array`. #figure( image("graphics/lists-memory-linkedlist.svg", width: 50%), caption: [ Instead of allocating a fixed unit of memory like an array, a linked list consists of chunks of memory scattered throughout RAM. Each element gets one chunk that has a pointer to the next (and/or previous) element in the sequence. ] ) <linked_list_vs_array> === Side Note: How Java uses Memory Java represents chunks of memory as classes, so we can implement a linked list by defining a new class that contains a value, and a reference to the next node on the list. It's important here to take a step back and think about how Java represents chunks of memory. Specifically, primitive values (`int`, `long`, `float`, `double`, `byte`, and `char`) are stored *by value*. This means that if you have a variable with type `long`, that variable directly stores a number. If you assign the value to a new variable, the new variable stores a *copy* of the number. ```java long x = 12; long y = x; x = x + 5; System.out.println(x); // prints 17 System.out.println(y); // prints 12 ``` On the other hand, objects (anything that extends `Object`) and arrays are stored *by reference*. This means that what you're storing is the _address_ of the actual object value (aka a pointer). When you assign the object to a new variable, what you're _really_ doing is copying the address of the object or array; both variables will now point to the *same* object. ```java int[] x = new [1, 2, 3, 4, 5]; int[] y = x; x[2] = 10; System.out.println(y[1]); // prints 2 System.out.println(y[2]); // prints 10 System.out.println(y[3]); // prints 4 ``` === A Linked List as a List We refer to the chunk of memory that we allocate for each element of a linked list as a `Node`. In java, we can allocate `Node` objects if we define them as a class, here storing the element represented by the `Node`, and a reference (pointer) to the next `Node`. We use java's `Optional` type to represent situations where a `Node` is not present#footnote[ An `Optional` extends existing types to indicate that the value may be present or absent (empty). Although java already allows for object variables to take a `null` value, using `Optional` instead makes it easier for people writing code to know when it's necessary to explicitly check for a missing value (e.g., `value.isPresent()`). Since `Optional` was added to java, it's been considered bad practice to use `null`. As a further side note, `Optional` can actually be viewed as a `MutableSequence`. Implementing this is left as an exercise for the reader. ] A simple linked list, also known as a 'singly' linked list, is just a reference to a `head` node (which is empty if the list is empty). The last element of the list has an empty `next`. ```java public class SinglyLinkedList<T> implements List<T> { class Node { T value; Optional<Node> next = Optional.empty(); public this(T value) { this.value = value; } } /** The first element of the list, or None if empty */ Optional<Node> head = Option.none(); /* method implementations */ } ``` To help us convince ourselves that we're actually creating a list, let's state some rules for this structure we're building: 1. If the list is empty then `head.isEmpty()`. 2. If the list is non-empty, then `head` refers to the $0$th node. 3. The $x$th node stores the $x$th element of the list. - *Corrolary*: There are $N$ nodes. 4. If the $x$th node is the last node (i.e., $x = N-1$), then the node's `next.isEmpty()`. 5. If the $x$th node is not the last node, then the node's `next` points to the $x+1$th node. Rules about how a data structure should behave are often called *invariants*. When writing your own code and/or data structures, a great way to avoid bugs is to write down the invariants that you expect your code to follow, and then proving that your code follows the rules ("preserves the invariant"). ==== Linked List `get` #let mark_step = { import cetz.draw: * (where, what) => { content(where, text(blue, weight: "bold")[#what]) circle(where, radius: 0.4, stroke: blue) } } #let linked_list_pointer = { import cetz.draw: * (from, to, color: black) => { let line_start = (rel: (1.5, 0.5), to: from) let line_end = (rel: (0, 0.5), to: to) let mark_start = (line_end, 0.5, line_start) line(line_start, line_end, stroke: color) mark(mark_start, line_end, symbol: ">", stroke: color, fill: color) } } #let linked_list_head = { import cetz.draw: * (at, to) => { content((rel: (0,0.5), to: at), [*HEAD*], name: "head") linked_list_pointer((0, 0), to) } } #let linked_list = { import cetz.draw: * (elems) => { for (position, letter, next) in elems { grid(position, (rel: (2, 1), to: position)) content((rel: (0.5,0.5), to: position), letter) if next != none { linked_list_pointer(position, next) } else { // content((x+1.5, 0.5), $emptyset$) } } } } #figure( cetz.canvas({ import cetz.draw: * scale(0.5) linked_list_head((0,0), (3,0)) linked_list( ( ((3, 0), "M", (6, 0)), ((6, 0), "o", (9, 0)), ((9, 0), "p", (12, 0)), ((12, 0), ".", none) ) ) for (idx) in (1, 2, 3) { let edge = (idx * 3, 0) arc((rel: (0, 1), to: edge), start: 45deg, stop: 135deg, radius: 2, stroke: blue) mark((rel: (-0.5, 1.5), to: edge), (rel: (0, 1), to: edge), symbol: ">", stroke: blue, fill: blue) mark_step((rel: (-1, 2.2), to: edge), [#(idx - 1)]) } line( (9.5, 0), (9.5, -1.5), stroke: blue) mark( (9.5, -1.0), (9.5, -1.5), symbol: ">", stroke: blue, fill: blue) mark_step((10.2, -0.8), [3]) }), caption: "Retrieving the character at index 2 from a linked list representing the list ['M', 'o', 'p', '.']" ) To retrieve a specific element $i$ of the list, we need to find the $i$th node. Since all we have to start is the $0$th node (the `head`; step ⓪), we can start there. If that's the node we're looking for, great, we're done; Otherwise, the only other place we can go is the $1$st node (step ①). We repeat this process, moving from node to node until we get to the $i$th node (step ②), and return the corresponding value (step ③). ```java public T get(int index) { if(index < 0){ throw new IndexOutOfBoundsException() } Option<Node> currentNode = head; for(i = 0; i < index; i++){ if(currentNode.isNone){ throw new IndexOutOfBoundsException() } currentNode = currentNode.get().next; } if(currentNode.isNone){ throw new IndexOutOfBoundsException() } return currentNode.get().value; } ``` Note that, if the rules we set for ourselves are being followed, we can prove to ourselves that this implementation is correct. Recall that we said `get(index)` is correct if it returns the $"index"$th element of the list. 1. We start with `currentNode` assigned to `head`; By the rules we set for ourselves, this is the 0th node. 2. The $i$th node has a pointer to the $(i+1)$th node, which we follow $i$ times. 3. After $i$ steps, `currentNode` has been reassigned to the $0 + underbrace(1 + ... + 1, i "times") = 0 + sum_i 1 = i$th node. 4. It follows from step 4 and the fact that the loop iterates `index` times that after the loop, `currentNode` is the $"index"$th node. 5. It follows from step 5 and the rule that the $i$th node (if it exists) contains the $i$th element (if it exists), that the `value` in `currentNode` which `get` returns is the $"index"$th node 6. Since a correct `get` is one that returns the $"index"$th node, we can conclude that `get` is correct. As usual, we can figure out the runtime of a snippet of code, starting by replacing every primitive operation with $Theta(1)$ ```java public T get(int index) { if( /* Theta(1) */ ){ throw /* Theta(1) */ } /* Theta(1) */ for(i = 0; i < index; i++){ if( /* Theta(1) */ ){ throw /* Theta(1) */ } /* Theta(1) */ } if( /* Theta(1) */ ){ throw /* Theta(1) */ } return /* Theta(1) */ } ``` Before the `for` loop, we have only constant-time operations. Similarly, we have only constant-time operations inside the body of the loop. Both can be simplified to $Theta(1)$ Let's start by figuring out the runtime of what's inside the for loop. $sum_(i=0)^("index"-1) Theta(1) = (("index"-1) - 0 + 1) dot Theta(1) = "index" dot Theta(1) = Theta("index")$ Since this is only the body of the for loop, we can add back the constant time operations before and after the loop to get the total runtime of `get`: $T_"get"("index") = Theta(1) + Theta("index") + Theta(1) = Theta("index")$. The $Theta("index")$ runtime is a little unusual: With arrays, most costs were expressed in terms of the size of the array itself. That is, our asymptotic runtime complexity was given in terms of $N$, while here, it's given in terms of $"index"$. However, we know that $0 <= "index" < N$, and we we can use that fact to create an analogous bound on the runtime of `get`#footnote[ The proof here is given only for _valid_ inputs. For values of index less than zero, the function aborts immediately, and we can prove to ourselves (based on the rule that the last element in the list has an empty `next` node) that we will never go through the loop more than $N$ times. Strictly speaking, the runtime should be, $Theta(min(N, "index"))$. However, this added complexity makes no immediate impact on our discussion, and so we omit it. ]. Since $"index" < N$, `get` is at worst linear in the size of the array, and so we get the upper bound: $T_"get"(N) = O(N)$ Similarly, since $"index" >= 0$, so `get` _could be_ constant time (e.g., `get(0)` requires only constant time), and we get the lower bound: $T_"get"(N) = Omega(1)$ ==== Linked List `set` #figure( cetz.canvas({ import cetz.draw: * scale(0.5) linked_list_head((0,0), (3,0)) linked_list( ( ((3, 0), "M", (6, 0)), ((6, 0), "o", (9, 0)), ((9, 0), "p", (12, 0)), ((12, 0), ".", none) ) ) for (idx) in (1, 2, 3) { let edge = (idx * 3, 0) arc((rel: (0, 1), to: edge), start: 45deg, stop: 135deg, radius: 2, stroke: blue) mark((rel: (-0.5, 1.5), to: edge), (rel: (0, 1), to: edge), symbol: ">", stroke: blue, fill: blue) mark_step((rel: (-1, 2.2), to: edge), [#(idx - 1)]) } line( (9.5, 0), (9.5, -1.5), stroke: blue) mark( (9.5, -0.5), (9.5, 0), symbol: ">", stroke: blue, fill: blue) mark_step((10.2, -0.8), [3]) content((9.5, -2), text(blue)['o']) }), caption: "Updating the character at index 2 to 'o', on the linked list representing the list ['M', 'o', 'p', '.']. After the set, the linked list represents the list ['M', 'o', 'o', '.']" ) To set the $i$th element of a linked list, just like `get`, we need to first find the $i$th element. As a result, the code for `set` is almost exactly the same as `get`, except for the very last line. ```java public void set(int index, T element) { if(index < 0){ throw new IndexOutOfBoundsException() } Option<Node> currentNode = head; for(i = 0; i < index; i++){ if(currentNode.isNone){ throw new IndexOutOfBoundsException() } currentNode = currentNode.get().next; } if(currentNode.isNone){ throw new IndexOutOfBoundsException() } currentNode.get().value = element; } ``` Using our Linked List invariants, we can similarly prove that our implementation of set follows the rules that we set out for `List`'s `set` operation. Remember that `set(index, element)` is supposed to change the linked list so that the next time we call `get(index)`, we get `element` instead of what was there before. 1. We start with `currentNode` assigned to `head`; By the rules we set for ourselves, this is the 0th node. 2. The $i$th node has a pointer to the $(i+1)$th node, which we follow $i$ times. 3. After $i$ steps, `currentNode` has been reassigned to the $0 + underbrace(1 + ... + 1, i "times") = 0 + sum_i 1 = i$th node. 4. It follows from step 4 and the fact that the loop iterates `index` times that after the loop, `currentNode` is the $"index"$th node. 5. It follows from step 5 and the rule that the $i$th node (if it exists) contains the $i$th element (if it exists), that the `value` in `currentNode` which `set` changes is the $"index"$th node 6. Since any subsequent calls to `get` will return the $"index"$th node, we can conclude that `set` is correct. *Side Note*: Observe how the proof for `set` is almost exactly the same as the proof for `get`. As usual we can figure out the runtime by replacing every primitive operation with $Theta(1)$ ```java public void set(int index, T element) { if( /* Theta(1) */ ){ throw /* Theta(1) */ } /* Theta(1) */ for(i = 0; i < index; i++){ if( /* Theta(1) */ ){ throw /* Theta(1) */ } /* Theta(1) */ } if( /* Theta(1) */ ){ throw /* Theta(1) */ } /* Theta(1) */ } ``` Once we replace all primitive operations with $Theta(1)$, `set` and `get` are exactly the same. Taking the same steps gets us to a runtime of $Theta("index")$, or $O(N)$. ==== Linked List `add` #figure( cetz.canvas({ import cetz.draw: * scale(0.5) linked_list_head((0,0), (3,0)) linked_list( ( ((3, 0), "M", (6, 0)), ((6, 0), "o", (9, 0)), ((9, 0), "o", none), ((15, 0), ".", none) ) ) linked_list( ( ((12, 2), "f", none), ) ) for (idx) in (1, 2, 3) { let edge = (idx * 3, 0) arc((rel: (0, 1), to: edge), start: 45deg, stop: 135deg, radius: 2, stroke: blue) mark((rel: (-0.5, 1.5), to: edge), (rel: (0, 1), to: edge), symbol: ">", stroke: blue, fill: blue) mark_step((rel: (-1, 2.2), to: edge), [#(idx - 1)]) } linked_list_pointer( (9, 0), (15, 0), color: gray) linked_list_pointer( (9, 0), (12, 2), color: blue) linked_list_pointer( (12, 2),(15, 0), color: blue) mark_step((13, 1.2), [3]) }), caption: "Inserting the character 'f' at index 3, on the linked list representing the list ['M', 'o', 'o', '.']. After the add, the linked list represents the list ['M', 'o', 'o', 'f', '.'] (the call of the noble dogcow)." ) Unlike the array, where we manually need to copy over every element of the array to a new position, in a linked list, the position of each node is given relative to the previous node. If we insert a new node by redirecting the `next` value of the previous node, we automatically shift every subsequent node by one position to the right. ```java public void add(int index, T element) { if(index < 0){ throw new IndexOutOfBoundsException() } Node newNode = new Node(element); if(head.isEmpty){ /* Case 1: Initially empty list */ head = Optional.of(newNode); } else if(index == 0){ /* Case 2: Insertion at head */ newNode.next = head; head = Optional.of(newNode); } else { /* Case 3: Insertion elsewhere */ Option<Node> currentNode = head; for(i = 0; i < index-1; i++){ if(currentNode.isNone){ throw new IndexOutOfBoundsException() } currentNode = currentNode.get().next; } if(currentNode.isNone){ throw new IndexOutOfBoundsException() } newNode.next = currentNode.get().next; currentNode.get().next = Optional.of(newNode); } } ``` Let's prove to ourselves that this code is correct, and start by recalling our rules for how `add` is supposed to behave: 1. The size of the List grows by 1. 2. The value `element` will be the new element at index $"index"$. 3. Every element previously at an index $i >= "index"$ will be moved to index $i+1$. #let oldlinkedlist = () => {$L_"old"$} #let newlinkedlist = () => {$L_"new"$} #let oldlinkedlistsize = () => {$N_"old"$} #let newlinkedlistsize = () => {$N_"new"$} Let's set aside the size rule for the moment and focus on the other two rules. We have our original list ($oldlinkedlist()$ of size $oldlinkedlistsize()$), and the list we get after calling `add` ($newlinkedlist()$ of size $newlinkedlistsize() = oldlinkedlistsize()+1$). Collectively, the latter two rules give us four cases for what will happen if we call $newlinkedlist()$.`get`($i$): 1. If $0 <= i <$ `index`: $newlinkedlist()$.`get`($i$) = $oldlinkedlist()$.`get`($i$) 2. If $i =$ `index`: $newlinkedlist()$.`get`($i$) = `element` 3. If $newlinkedlistsize() > i >$ `index`: $newlinkedlist()$.`get`($i$) = $oldlinkedlist()$.`get`($i-1$) 4. If $i >= newlinkedlistsize()$: $newlinkedlist()$.`get`($i$) throws an exception We'll want to show that after calling `add`, any subsequent call to `get`($i$) will return the correct value. We already proved that `get` is correct if the linked list follows the rules we set forth for ourselves, so we need to show that the new linked list is correct for the updated list. In other words, we want to show that: 1. All nodes at position $0 <= i <$ `index` are left unchanged. 2. The newly created node (at position `index`) is pointed to by the node at position `index`$-1$, or by `head` if `index` $= 0$. 3. All nodes previously at positions `index` $ <= i < oldlinkedlistsize()$ are now at position $i+1$. 4. The node at position $newlinkedlistsize()-1$ has an empty `next`. The code has three cases that we'll look at individually. *Case 1: Initially empty list*: Going down the list of things we need to prove: 1. There are no other nodes, so nothing changes. 2. The newly created node is at position $0$, and so is correctly pointed to by `head` after the code runs. 3. There are no other nodes, so nothing needs to change. 4. Since $newlinkedlistsize() = 1$, we need the node at position $newlinkedlistsize() - 1 = 0$ to have an empty next. Since this is the node we just created, this is true. *Case 2: Insertion at head*: Going down the list of things we need to prove: 1. Since `index` $=0$, there can be no nodes at positions before `index`, so nothing changes. 2. The newly created node is at position $0$, and so is correctly pointed to by `head` after the code runs. For the remaining two rules, consider the fact that the (newly created) $0$th node's `next` field now points at the node that used to be the `head`. - By our rules for linked lists, this means that the old $0$th element is now the $1$st element (correct). - The new $1$st element is pointing at what used to be the $1$st element, but is now the $2$nd element (also correct). - The new $2$nd element is pointing at what used to be the $2$nd element, but is now the $3$rd element (also correct). - The new $3$rd element is pointing at what used to be the $3$rd element, but is now the $4$th element (also correct). This pattern continues: The new $i$th element is pointing at what used to be the $i$th element, but is now the $i+1$th element (still correct), up until we get to the $newlinkedlistsize()-1$th element, which used to be the $oldlinkedlistsize()-1$th element, which still (correctly) has an empty `next`. *Case 3: Insertion anywhere else*: Going down the list of things we need to prove: 1. The code finds the node at position `index`$-1$, skipping over all preceding nodes. These are unchanged. 2. The newly created node is pointed to by the node at position `index`$-1$, putting it at position `index`. For the remaining two rules, we want to consider what happens to the node previously at position `index`, but also need to consider the possibility that there was no node at this index to begin with (if `index` $= oldlinkedlistsize()$). If the node exists, then as in *Case 2*, the node at position `index` moves to position `index`$+1$, likewise repositioning every following node, including the final one. If the node doesn't exist, then the newly created node's `next` field is assigned an empty value, (correctly) making it the last node in the list. ==== Aside: Invariants and Rule Preservation It's worth taking a step back at this point and reviewing what we just did and why. We defined the expected state of the linked list (in terms of the behavior of `get` and our rules for a correct linked list) _after_ the set, but we did so relatively to its state _before_ the set. Specifically, we showed that, if the list was correct before we called `set`, it would still be correct (for the new list) after we called `set`, or in other words, we showed that `set` *preserves the invariants* we defined for the linked list. Invariants are an extremely useful debugging technique for data structures (and other code). If you can precisely define one or more rules (invariants) for your data structure, you can check to see whether your code follows the rules: If you get a correct data structure as input to your function, is it always the case that you get a correct data structure as an output (keeping in mind that the function may change the definition of correctness). ==== Linked List `add` runtime The runtime of `add` follows a pattern very similar to that of `set`: ```java public void add(int index, T element) { if( /* Theta(1) */ ){ /* Theta(1) */ } /* Theta(1) */ if( /* Theta(1) */ ){ /* Case 1: Initially empty list */ /* Theta(1) */ } else if( /* Theta(1) */ ){ /* Case 2: Insertion at head */ /* Theta(1) */ } else { /* Case 3: Insertion elsewhere */ /* Theta(1) */ for(i = 0; i < index-1; i++){ /* Theta(1) */ } if( /* Theta(1) */ ){ /* Theta(1) */ } /* Theta(1) */ } } ``` Based on the the outer if statement, we have three cases: $T_("add")("index") = cases( Theta(1) "if case 1", Theta(1) "if case 2", Theta(1) + sum_(i=0)^("index"-1) ( Theta(1) ) "if case 3", )$ Simplifying the third case, we get: - $Theta(1) + sum_(i=0)^("index"-1) ( Theta(1) )$ - $Theta(1) + ("index" - 1 + 0 + 1) ( Theta(1) )$ - $Theta(1) + "index" dot Theta(1)$ - $Theta(1) + Theta("index")$ - $Theta("index")$ So... $T_("add")("index") = cases( Theta(1) "if case 1", Theta(1) "if case 2", Theta("index") "if case 3", )$ Since $"index" = 0$ in cases 1 and 2, we can further simplify to $T_("add")("index") = cases( Theta("index") "if case 1", Theta("index") "if case 2", Theta("index") "if case 3", ) = Theta("index")$ As before, $Theta("index") in O(N)$ and $Theta("index") in Omega(1)$ ==== Linked List `remove` #figure( cetz.canvas({ import cetz.draw: * scale(0.5) linked_list_head((0,0), (3,0)) linked_list( ( ((3, 0), "M", (6, 0)), ((6, 0), "o", none), ((9, 0), "o", (12, 0)), ((12, 0), "f", (15, 0)), ((15, 0), ".", none) ) ) for (idx) in (1, 2) { let edge = (idx * 3, 0) arc((rel: (0, 1), to: edge), start: 45deg, stop: 135deg, radius: 2, stroke: blue) mark((rel: (-0.5, 1.5), to: edge), (rel: (0, 1), to: edge), symbol: ">", stroke: blue, fill: blue) mark_step((rel: (-1, 2.2), to: edge), [#(idx - 1)]) } linked_list_pointer( (6, 0), (9, 0), color: gray) arc((12, 0), start: -45deg, stop: -147deg, radius: 2.9, stroke: blue) mark((11.5, -0.5), (12, 0), symbol: ">", stroke: blue, fill: blue) mark_step((12.5, -0.75), 2) }), caption: "Removing the element at index 2 from the linked list representing the list ['M', 'o', 'o', 'f', '.']. After removal, the linked list represents the list ['M', 'o', 'f', '.']" ) As with `add`, we can benefit from the relative positioning of linked list nodes by simply moving a `next` reference to skip over the removed linked list node. ```java public void remove(int index) { if(index < 0){ throw new IndexOutOfBoundsException() } if(head.isEmpty){ /* Case 1: Initially empty list */ throw new IndexOutOfBoundsException(); } else if(index == 0){ /* Case 2: Deletion from head */ head = head.get().next; } else { /* Case 3: Deletion elsewhere */ Option<Node> currentNode = head; for(i = 0; i < index-1; i++){ if(currentNode.isNone){ throw new IndexOutOfBoundsException() } currentNode = currentNode.get().next; } if(currentNode.isNone){ throw new IndexOutOfBoundsException() } currentNode.next = currentNode.get().next; } } ``` The proof of correctness and `remove`'s runtime of $Theta("index")$ are left as an exercise for the reader. ==== Linked List `size` (Take 1) The size of the list is the number of elements. Thinking back to our rules, the last node is the node with an empty `next` pointer, so we need to figure out where this node is located ```java public int size() { Option<Node> currentNode = head; int count = 0; while( ! currentNode.isEmpty() ){ currentNode = currentNode.get().next count += 1 } return count } ``` Let's see if we can prove that this code is correct. This code is a bit harder to think about than `get` and `set`, since in both of those cases we had a nice handy `for` loop to keep track of how many 'steps' we take through the list. Here, the while loop just keeps going until `currentNode.isEmpty()`. When trying to tackle a tricky proof like this, it can often help to break down the proof into cases. Let's start with the simplest case: What happens if the list is empty ($N=0$)? 1. `count` starts off at 0. 2. If the list is empty, then by our rules for linked lists `head` is empty, so we start off with `currentNode` empty as well. 3. Since `currentNode` is empty from the start, we skip the `while` loop's body entirely. 4. `count` is never modified, and we correctly return 0. Let's tackle the next simplest case next: What happens if the list only has 1 element ($N=1$) 1. `count` starts off at 0. 2. `head` points to the $0$th element of the list, so `currentNode` starts off pointing to the $0$th node. 3. Since `currentNode` is not empty, we enter the body of the while loop. 4. We increment `count` to $1$, and update `currentNode` from the $0$th node to its `next` reference. 5. By our rules for linked lists, since the list has only 1 element, the $0$th node's `next` reference is empty, so `currentNode` is now empty and we exit the `while` loop. 6. We correctly return `count`$=1$, Moving on, let's see what happens if the list has 2 elements ($N=2$) 1. `count` starts off at 0. 2. `head` points to the $0$th element of the list, so `currentNode` starts off pointing to the $0$th node. 3. Since `currentNode` is not empty, we enter the body of the while loop, increment count, and update `currentNode` to its `next` reference. 4. We increment `count` to $1$, and update `currentNode` from the $0$th node to its `next` reference, the $1$st node. 5. We increment `count` to $2$, and update `currentNode` from the $1$st node to its `next` reference. 6. By our rules for linked lists, since the list has only 2 elements, the $1$st node's `next` reference is empty, so `currentNode` is now empty and we exit the `while` loop. 7. We correctly return `count`$=2$, Moving on, let's try a list with 3 elements ($N=3$) 1. `count` starts off at 0. 2. `head` points to the $0$th element of the list, so `currentNode` starts off pointing to the $0$th node. 3. Since `currentNode` is not empty, we enter the body of the while loop, increment count, and update `currentNode` to its `next` reference. 4. We increment `count` to $1$, and update `currentNode` from the $0$th node to its `next` reference, the $1$st node. 5. We increment `count` to $2$, and update `currentNode` from the $1$st node to its `next` reference, the $2$nd node. 6. We increment `count` to $3$, and update `currentNode` from the $2$nd node to its `next` reference. 7. By our rules for linked lists, since the list has only 3 elements, the $2$st node's `next` reference is empty, so `currentNode` is now empty and we exit the `while` loop. 8. We correctly return `count`$=3$, Although the proof is different for each case, you might notice a pattern forming. For a list of _any_ size, we can come up with a similar proof by adding a bunch of lines into the middle, all from the template: We increment `count` to $i$, and update `currentNode` from the $i-1$th node to its `next` reference, the $i$th node. In other words, it looks like the code ties the values of `count` and `currentNode` together. We can use this intuition to define a rule for ourselves: If `currentNode` is not empty, it always points to the `count` node of the list. This is true at the start of the loop, since `count`$=0$ and by our rules for linked lists, `currentNode` points at the $0$th node. Now, if we know that `currentNode` (if non-empty) points to the `count` node of the linked list when we *start* the loop body, we can show that it's still true at the end of the loop body: 1. If `currentNode` points to the $i$th node of the list, by our rules for linked lists, its `next` element points to the $i+1$th node. 2. If `count` is $i$ to start, then incrementing it sets it to $i+1$ 3. From lines 1 and 2, after the loop body, `count`$=i+1$ and `currentNode` is the $i+1$th node, and we're still following the rule. Since the rule holds at the *start* of the loop, and since the loop body preserves the rule, we know that the rule is also followed at the *end* of the loop. We call a rule that is satisfied at the start of a loop and preserved by the loop body, a *loop invariant*. The loop ends at the very first point where `currentNode` becomes empty. This happens in one of two cases: - `head` is empty. - The `next` element of `currentNode` is empty. By our rules for linked lists, the first case happens only when the list is empty, and we've already shown that `size` is correct in this case. Similarly, by our rules for linked lists, the second case happens only when `currentNode` points to the last (i.e., $N-1$th) node of the linked list. From that, and our loop invariant, it must be the case that `count` is $N-1$. Since `count` gets incremented one last time on the 2nd line of the loop body, when the loop ends `count`$=N$, which is also correct. ==== Aside: Loop Invariants Once again, let's take a quick moment to review what we just did, because it's very useful trick for debugging loops in your code#footnote[ Although it's a bit too early to use the term in the main body of the text, loop invariants are a specific example of a proof trick called "induction". We'll come back to induction as a more general technique next chapter, when we talk about recursion. ]. We started by trying to prove that our code was correct for a couple of simple example cases. From those simple example cases, we found a pattern in the proof: a rule that our code seemed to obey throughout our proof. We then set up a *loop invariant* based on that pattern and showed that (i) it held at the start of the loop, and (ii) each line of the loop preserved the rule. Because we could show that the invariant held at the start of the loop, and each loop iteration preserved the invariant, we inferred that the invariant had to be true at the end of the loop as well. We used the fact that the invariant was true at the end of the loop to prove that `size` was correct. When debugging code with loops, try tracing through the loop manually for a few iterations. You'll often start noticing patterns and relationships between elements of the code. Try to pin down *exactly* what that pattern is (like `currentNode` always points to the `count` node in our example), and write down the loop invariant. Then, try to prove to yourself that (i) the pattern holds at the start of the loop, (ii) the pattern is preserved by the loop body. ==== Linked List `size` (Take 1) runtime As usual, we can replace all primitive operations with $Theta(1)$ ```java public int size() { /* Theta(1) */ while( /* Theta(1) */ ){ /* Theta(1) */ } return /* Theta(1) */ } ``` Once again, the `while` loop makes our job a little harder. However, just as before, we can use the loop invariant to help ourselves out: 1. $"count"$ starts at 0. 2. Each loop iteration increments $"count"$ by 1. 3. The loop ends when $"count" = N$. Combining these facts, we can definitively state that the loop goes through $N$ iterations. So, we get: $Theta(1) + underbrace(Theta(1) + ... + Theta(1), N "times") + Theta(1) = (N+2) dot Theta(1) = Theta(N+2) = Theta(N)$ ==== Linked List `size` (Take 2) It's not great when a function has a $Theta(N)$ runtime, and it's really bad when it's something as fundamental as `size`. Many algorithms need to know the size of a collection, so it would be useful to have a way to cut the runtime to something more practical. In the case of `size`, there's one simple trick that lets us cut the runtime down to $Theta(1)$: Precomputing the size. Let's add a `N` field to the linked list and modify the `size` method to just return it. ```java public class SinglyLinkedList<T> implements List<T> { class Node { T value; Optional<Node> next = Optional.empty(); public this(T value) { this.value = value; } } /** The first element of the list, or None if empty */ Optional<Node> head = Option.none(); /** The precomputed size of the list */ private int N = 0; public int size() { return this.N; } /* method implementations */ } ``` The list starts off empty ($N = 0$), so initially this method is correct. However, we need to make sure that it stays correct as we change the structure. There are two operations, `add` and `remove`, that modify the size of a list, incrementing and decrementing the list's size. We need to modify these operations to properly maintain $N$: ```java public void add(int index, T element) { /* ... as before ... */ this.N += 1; } public void remove(int index) { /* ... as before ... */ this.N -= 1; } ``` Let's review the trade-off we just made: Both changes add an additional $Theta(1)$ runtime cost to `add` and `remove`. This doesn't change the overall code complexity of either ($Theta("index")$, or equivalently $O(N)$)#footnote[ In practice, incrementing and decrementing an integer is a relatively inexpensive operation in most cases, so even outside of the magical land of asymptotics, this is usually a worthwhile trade. That said, there are _some_ exceptions, primarily when dealing with concurrency (synchronized integers are expensive) or with random memory access (we'll talk about this later in the book). ]. In exchange, the asymptotic runtime complexity of `size` drops from $Theta(N)$ to $Theta(1)$. To summarize, the asymptotic runtime complexity of all the other operations stays the same, and `size`'s asymptotic runtime complexity drops massively. This is almost always a worthwhile trade. == The Iterator ADT In the next section, we'll introduce a new type of abstract data type called the Iterator (sometimes called a 'Cursor'). Iterators are a little unique as far as this class goes, in that they represent something a bit different from a collection. They represent a loop over the elements of a collection. The ability to abstractly loop over the elements of a collection is really useful for keeping the abstraction layer around our other collection types, as we'll see shortly. We'll start with a motivating example. === Motivation: Summing up Integers Have a look at the following code, which takes a `List` of `Integer`s and computes their sum. Before you read on, try to work out the code's runtime for yourself. ```java public int computeSum(List<Integer> list) { int sum = 0; for(i = 0; i < list.size(); i++) { sum += list.get(i); } return sum; } ``` Seriously, stop reading and figure out the code's runtime before you read on. I mean it. Did you figure it out yet? Ok... if you read on without figuring it out for yourself, you're cheating yourself of a learning experience. You've been warned thrice. Using our normal technique of replacing primitive operations would lead you to a runtime of $Theta(N)$, but this is actually not correct. We're allowed to replace *primitive* operations with $Theta(1)$. However, this particular block of code relies on two non-primitive operations: the block of code invokes `list.size()` and `list.get()`. For these, instead of $Theta(1)$, we need to "plug in" the runtime complexities that we computed before. But what is the runtime complexity of these operations? To answer that question, we need to know which `List` data structure we're using. For arrays, which store the size explicitly, the `size` operation is $Theta(1)$. For linked lists, our first attempt was a `size` operation that was $Theta(N)$, but then we came up with an optimization that got us down to $Theta(1)$. So: $T_("size")(N) = cases( Theta(1) "if using an array", Theta(1) "if using a linked list", ) = Theta(1)$ Since all cases are the same, it doesn't matter which structure we're using, `size` is always $Theta(1)$. However, the same isn't true for `get`. Recall that for the linked list, the cost of `get` depends on the index. $T_("get")("index") = cases( Theta(1) "if using an array", Theta("index") "if using a linked list", )$ Since there are two possibilities here, we can't define a simple theta bound for `get`, but we can provide upper and lower bounds $O("index")$ and $Omega(1)$. Let's plug this all into our code and see what we get: ```java public int computeSum(List<Integer> list) { /* Theta(1) */ for(i = 0; i < list.size(); i++) { /* Theta(1) + T_get(i) */ } return /* Theta(1) */; } ``` Since we don't have a (simple) tight bound for $T_("get")(i)$, we can switch to using both upper and lower bounds. Remember that wherever you see $Theta(f(N))$, it means that $f(N)$ is *both* an upper and a lower bound, so we can always replace $Theta(f(N))$ in an arithmetic expression, with $O(f(N))$ or $Omega(f(N))$. Solving for the upper bound first, we get: - $T_("computeSum")(N) = O(1) + (sum_(i=0)^N O(1) + T_("get")(i)) + O(1)$ - $= O(1) + (sum_(i=0)^N O(1) + O(i)) + O(1)$ - $= O(1) + (sum_(i=0)^N O(i)) + O(1)$ - $= O(1) + (sum_(i=0)^N i dot O(1)) + O(1)$ - $= O(1) + O(1) dot (sum_(i=0)^N i) + O(1)$ - $= O(1) + O(1) dot (frac(N dot (N+1), 2)) + O(1)$ - $= O(1) + O(1) dot (N^2/2 + N/2) + O(1)$ - $= O(1) + O(N^2/2 + N/2) + O(1)$ - $= O(1) + O(N^2) + O(1)$ - $= O(N^2)$ And then for the lower bound: - $T_("computeSum")(N) = Omega(1) + (sum_(i=0)^N Omega(1) + T_("get")(i)) + Omega(1)$ - $= Omega(1) + (sum_(i=0)^N Omega(1) + Omega(1)) + Omega(1)$ - $= Omega(1) + (sum_(i=0)^N Omega(1)) + Omega(1)$ - $= Omega(1) + Omega(1) dot (sum_(i=0)^N 1) + Omega(1)$ - $= Omega(1) + Omega(1) dot (N - 0 + 1) + Omega(1)$ - $= Omega(1) + Omega(N + 1) + Omega(1)$ - $= Omega(1) + Omega(N) + Omega(1)$ - $= Omega(N)$ So `computeSum` will take *at least* linear time, but could take as much as quadratic time! If we work our way backwards through the summation, the limiting factor seems to be $T_"get"$. If $T_"get"$ were constant-time, for example if we were certain that `list` was an array, we could re-do the summations with $T_("get") = O(1)$. Try it yourself, and you'll see that the upper bound on the runtime works out to $O(N)$. This is *much* better. As we saw in the last chapter, for a sufficiently large list, quadratic to linear can be the difference between an algorithm that takes seconds, and one that takes hours. So, how do we fix it? One strategy might be to observe that you can loop over the elements of a linked list *much* faster if you have some insight into the list's structure. Instead of using a loop variable `i`, you can use a pointer to the 'current' node: ```java public int computeSumOfLinkedList(LinkedList<Integer> list) { int sum = 0; for(list.Node currentNode = list.head; currentNode.isPresent(); currentNode = currentNode.get().next) { sum += currentNode.get().value; } return sum; } ``` In this version of the algorithm, every operation is primitive. Note that the algorithm looks almost identical to that of `size` (take 1). The proof that this this algorithm also runs $Theta(N)$ is similar, and is left as an exercise for the reader. Most importantly, the $Theta(N)$ we get from this algorithm is much better than the $O(N^2)$ we got from the "generic" version of the algorithm that we saw at the start of the section. However, this improved performance comes at a steep cost: The new algorithm is specialized to linked lists. If we need to change to a different data structure (e.g., the Buffered Array that we'll introduce shortly), then we have to rewrite the summation algorithm from scratch. === Abstracting Loops The motivating problem goes beyond just computing sums: *Any* loop over the elements of a linked list using `get` is going to have an $O(N^2)$ runtime. We can play a similar trick, looping over the linked list nodes instead of the index, for any loop. However, doing so requires us to know that we're working with a linked list. So let's dig a little deeper. To move from one index to the next, the generic linked list loop simply increments $i$ to $i+1$ (a constant-time operation). For the array, where the index is sufficient to find the value in constant time, the overall cost of stepping from one element of the list to the next is constant. However, for a linked list, going from an index to a value is a linear-time operation, since we need to find the node corresponding to the index. The 'trick' underlying the specialized linked list version of the loop, is that moving from a linked list *node* to the `next` node can be done in constant time. The structure of the loop is the same, but instead of using an index $i$, we use a node reference. Looking at the commonalities between `computeSum` and `computeSumOfLinkedList`, the following code structure is common to both: ```java public void computeSumV2(List<Integer> list) { int sum = 0; for( PositionType i = list.firstPosition(); i.isNotAtEnd(); i.moveToNext()) { sum += i.getValue(); } } ``` This code structure includes five placeholders: 1. The type of the position reference (`PositionType`). 2. A way to initialize the position reference to the first element (`firstPosition`). 3. A way to test whether there are more positions left to visit (`isNotAtEnd`) 4. A way to move to the next position (`moveToNext`) 5. A way to get the value at the current position (`value`) #table( columns: 3, inset: 10pt, align: horizon, stroke: none, table.header( [], table.vline(), `computeSum`, `computeSumOfLinkedList`, ), table.hline(), [`PositionType`], `int`, `list.Node`, [`firstPosition`], `0`, `list.head`, [`isNotAtEnd`], `i < N`, `i.isPresent()`, [`moveToNext`], `i += 1`, `i = i.get().next`, [`getValue`], `list.get(i)`, `i.get().value`, ) === The Iterator ADT The `Iterator` abstract data type, abstractly models the position of a loop in a list, providing the five operations named above. Iterators are implemented in each language slightly differently, but in Java, the main parts of the `Iterator` interface look like: ```java public interface Iterator<E> { /** * Returns true if there are more values to retrieve * (The `isAtEnd` of our example above) */ public boolean hasNext(); /** * Retrieves the next element and advances the iterator * to the next position. * (Combines `moveToNext` and `getValue` from our example) */ public E next(); /* A few other methods that aren't relevant yet */ } ``` To initialize the iterator, the `List` interface defines an `iterator` method that returns an iterator pointing to the first position (`firstPosition` in our example). Plugging this into our template pattern, we get: ```java public void computeSumWithIterators(List<Integer> list) { int sum = 0; for( Iterator<Integer> i = list.iterator(); i.hasNext(); /* next() automatically advances the iterator */) { sum += i.next(); } return sum; } ``` ==== Case Study: Array Iterator To build an iterator, we can look at the table above and plug in the corresponding operations for `hasNext` and `next`. For the array, this means using the index. ```java public class SimpleArrayIterator<T> extends Iterator<T> { SimpleArrayAsList<T> array; int i = 0; /** `firstPosition` */ public this(SimpleArrayAsList<T> array) { this.array = array } /** `isNotAtEnd` */ public boolean hasNext() { return i < array.size; } /** `getValue` and `moveToNext` */ public T next() { T currentValue = array.get(i); i += 1; return currentValue; } } ``` ==== Case Study: Linked List Iterator For the linked list, this means using the linked list node. ```java public class SinglyLinkedListIterator<T> extends Iterator<T> { Optional<Node> currentNode; /** `firstPosition` */ public this(SinglyLinkedList<T> list) { this.currentNode = list.head; } /** `isNotAtEnd` */ public boolean hasNext() { return currentNode.isPresent(); } /** `getValue` and `moveToNext` */ public T next() { T currentValue = currentNode.get().value; currentNode = currentNode.get().next; return currentValue; } } ``` === Summation Runtime with Iterators Note that, each of these implementations use exclusively primitive operations. As a result, both iterators' initialization, `hasNext` and `next` are constant-time. Returning to the iterator-based implementation of `computeSum`, we can figure out the runtime: ```java public void computeSumWithIterators(List<Integer> list) { /* Theta(1) */ for( /* Theta(1) */; /* Theta(1) */; /* 0 */) { /* Theta(1) */ } return /* Theta(1) */ } ``` This gives us a runtime of: $T_("computeSumWithIterators")(N) = Theta(1) + (sum_{i = 0}^{N-1} Theta(1) ) + Theta(1) = Theta(N)$ Using iterators, we get the same $Theta(N)$ runtime for a loop over either list implementation, but we get the benefit *without having to specialize the loop implementation*. The resulting code is far more flexible, since we can freely swap in *any* other data structure implementation, without impacting the code's correctness (or, in this case, performance). ==== Java Iterator shorthand Looping over the elements of a collection with iterators is such a common pattern that Java adds a bit of syntax to make it easier to write. Note the `for` syntax below. ```java public void computeSumWithIteratorsV2(List<Integer> list) { int sum = 0; for(Integer i : list) { sum += i.next(); } return sum; } ``` `computeSumWithIterators` and `computeSumWithIteratorsV2` do exactly the same thing. ```java for(T element : collection){ /* ... */ } ``` is simply a shorthand for: ```java for(Iterator<T> iter = collection.iterator(); iter.hasNext(); ){ T element = iter.next(); ... } ``` === List Access by Reference Iterators have another benefit. They give us a highly efficient way to reference a *specific* element of a list. Remember that for Arrays, we can efficiently identify an element by its index. For any operation that we want to perform on specific elements of the Array, we can use the list index to identify the element we want to affect. For example, let's talk about the following bit of code, which deletes every instance of an element in the list. ```java public void removeAll<T>(List<T> list, T element) { for(i = 0; i < list.length(); i++){ if(list.get(i).equals(element)){ list.remove(i); i -= 1; } } } ``` The code iterates through every element of the list, and then calls `remove` on the element being removed. In the implementation above, we use the index (`i`) to refer to a specific element. However, remember that that this is exactly the type of loop that led us to come up with iterators, since it performs quadratically if `list` is a `LinkedList`. Let's replace the code with an iterator#footnote[ If you try running `removeAllWithIterator` for real, you'll notice that it actually won't work. Because `remove` changes the list, it also 'invalidates' all iterators on the list. Keep reading on for a way to implement this algorithm without breaking the iterator. ]. ```java public void removeAllWithIterator<T>(List<T> list, T element) { int i = 0; for(Iterator<T> iter = list.iterator(); iter.hasNext();){ if(iter.next().equals(element)){ list.remove(i); } else { i++; } } } ``` Note that we can't get rid of the list index (`i`), since we need a way to tell `remove` which element to remove. However, this has an unexpected consequence on performance: If `list` is a `LinkedList`, `remove` has a runtime complexity of $Theta(i)$. If we do a runtime analysis of removeAllWithIterator, plugging in the cost of `remove` on a `LinkedList`#footnote[ The analysis is only slightly different if you plug in the $O(N)$ cost of `remove` for an `Array`. ], we start with: ```java public void removeAllWithIterator<T>(List<T> list, T element) { /* O(1) */ for(/* O(1) */){ if( /* O(1) */){ /* O(i) */ } else { /* O(1) */ } } } ``` The `for` loop visits every element of the list. Although `i` isn't incremented for *every* element of the list, we can use the number of elements we've visited as a _upper bound_ on `i`. That is: $i in O(v)$ (where $v$ is the number of visited nodes. Using this insight, we can compute the total runtime (with $N$ as the `length` of `list`) as: $T_"removeAllWithIterator" (N) = O(1) + O(1) + sum_(v : 0)^N O(1) + cases(O(i), O(1))$ The cases block is upper-bounded by $O(i)$, and $O(i)+O(1) = O(i)$, so $T_"removeAllWithIterator" (N) = O(1) + O(1) + sum_(v : 0)^N O(i)$ As we noted above, $i in O(v)$, so: $T_"removeAllWithIterator" (N) = O(1) + O(1) + sum_(v : 0)^N O(v)$ Applying our summation rules, we can simplify the summation: $T_"removeAllWithIterator" (N) = O(1) + O(1) + O(N^2)$ And one more simplification step gets us: $T_"removeAllWithIterator" (N) = O(N^2)$ $O(N^2)$ isn't great, so let's take a step back and ask ourselves why that's the runtime complexity. We need to do a loop over $N$ elements just to find the elements that don't fit, so it'll be difficult to get the runtime under $O(N)$#footnote[ This is a tiny lie, but true for Arrays and Linked Lists. We'll get to efficiently finding elements in the sections on Trees and Hash Tables. ]. However, in every iteration of the loop, we have the $O(i)$ call to `remove`. That $O(i)$ factor is there because it takes us `i` steps to find the linked list node for the `i`th element. However, remember that *once we have the `i`th linked list node, actually removing the element is $O(1)$.* To understand why that bit of information is useful, let's remember that the the `LinkedList` iterator works by storing a reference to the current linked list node. The variable `iter` already stores a reference to the `i`th linked list node! Meanwhile, here we are in this algorithm, repeatedly looking for an `i`th node that we already have. To address this performance issue, `Java` iterators include a `remove` method that removes the element most recently returned by `next`. Our algorithm changes only slightly: ```java public void removeAllWithIteratorV2<T>(List<T> list, T element) { for(Iterator<T> iter = list.iterator(); iter.hasNext();){ if(iter.next().equals(element)){ iter.remove(); } } } ``` The implementation of `remove` for an Array-based `Iterator` remains $O(N)$ (since the array still needs to shift elements at indices above $i$ to the left). However, for a `LinkedList`-based iterator, the `remove` method drops to $O(1)$, since the iterator already has a _reference_ to the linked list node. Although `remove` is the only method that appears in an iterator, you can see that nearly every other operation on a `LinkedList` (`add`, `set`) is $O(i)$ for essentially the same reason: `List` uses the list position to identify elements, and it costs $O(i)$ to find the linked list node for the `i`th element. However, if we already have a reference to the `i`th element (technically the $i-1$th element), each of these operations can be performed in $O(1)$. Because of this unusual behavior, we usually give *two* separate runtimes for `LinkedList` operations: One runtime for the operation applied to a given index (on the `List` itself) and one runtime for the operation applied to a reference (e.g., on the `Iterator`). 1. `get(i)` - *By Index*: $O(i)$ - *By Reference*: $O(1)$ 2. `set(i, v)` - *By Index*: $O(i)$ - *By Reference*: $O(1)$ 3. `add(i, v)` - *By Index*: $O(i)$ - *By Reference*: $O(1)$ 4. `remove(i)` - *By Index*: $O(i)$ - *By Reference*: $O(1)$ === Doubly Linked Lists In the simple `LinkedList` we've described so far, often called a *Singly* linked list, each node contains a pointer to the next node in the chain (or `null` if it's the last node). This is convenient for moving _forwards_ through the list, but sometimes it's convenient to be able to go _backwards_ through the list as well. For example, try implementing the `LinkedList` iterator's `remove` method with a singly linked list, and you'll find that you need to keep track of several of the preceding nodes. In a *Doubly* linked list, each linked list node also keeps a pointer to the previous node, and the linked list itself usually keeps pointers to the first _and last_ nodes in the list. Although the extra pointers require extra book-keeping, all of the extra work is constant time. As a result, a doubly linked list's operations have asymptotic runtime complexities that are at least as good as a singly linked list. In fact, the `add` (i.e., append) operation becomes $O(1)$, since we have a pointer to the last element in the list (and so can access it _by reference_). Moving forward, *we will assume that every linked list is a Doubly Linked List*. == Array List, take 2 (Buffered Arrays) There are many situations where it's useful to be able to append to a list. As we already discussed, Java implements append as a special case of `add` that omits the `index` argument. For example, if we have a `List` of log entries, new log entries will always be added to the end. Similarly, implementations of some ADTs like `Stack` and `Queue`, which we'll discuss later, involve putting new elements at the end of a `List`. #figure( image("graphics/lists-array-add.svg", width: 50%), caption: [ Adding an item to an array requires (1) allocating a new space for the array, (2) copying the contents of the old array to the new space, and (3) updating the data pointer to the new space. ] )<array_add> As we just discussed, we can append to a doubly linked list in $O(1)$, but let's come back to the humble array, for which the `add` operation is shown in @array_add. Thinking back, remember that the cost of `add` comes from two general tasks: 1. Copying every element of the array to a new array with one extra space: $O(N)$ 2. Shifting every element of the array to the right by one spot: $O(N-i)$ In the case of append, we're inserting at the end; In other words $i=N$, and the cost of second step is $O(N-N) = 0$. Since we're inserting at the last element, nothing needs to be moved over to make space for the new element. However, we can't directly benefit from this observation, since we still need to copy every element into a new array. So let's think how we might be able to avoid that copy. === Buffered Arrays (Attempt 1: Fixed Increment) #figure( image("graphics/lists-bufferedarray.svg", width: 50%), caption: [ An `ArrayList` allocates extra space to efficiently support append operations. The example above shows an `ArrayList` with 5 elements in use, and 5 unused spaces. The structure keeps track of both how many elements in the array are in-use, and how big the allocated array is. ] )<bufferedarray> One idea might be to set aside a little bit of extra space in the array when we first allocate it. Let's say that when we're asked to create an $N$ element array, we instead allocate space for $N+B$ elements (@bufferedarray). The extra $B$ elements are held in reserve until `add` is called. Now, the next $B$ calls to `add` are free, and even after that, we can still allocate another $B$ elements. Here's a simplified version of this idea with the one argument `add` implemented: ```java public class FixedIncrementArrayList<T> implements List<T> { static int B = 10; T[] data = new T[0]; int size = 0; /* Other methods omitted */ public void add(T elem) { if(size >= data.length){ T[] temp = new T[data.length + B]; for(i = 0; i < data.length; i++){ temp[i] = data[i]; } data = temp; } data[size] = elem; size += 1; } } ``` If we're out of space (`size >= data.length`), we allocate a new array (`temp`) that is $B$ elements bigger, and copy every element of `data` into it. After we replace the old array with the new one, we have free space. Regardless of whether we had to allocate more space or not, we put the new `elem` into the first free slot, and shift `size` over by one step. It should be clear that, in the common case (which happens in $(B-1)/B$ calls to `add`), this data structure will be faster than `Array`. But let's dig deeper and do a proper analysis. Tagging every step in the algorithm with the runtime, we get: ```java public void add(T elem) { if(/* O(1) */){ /* O(1) */ for(/* O(1), looping with i from 0 to N */){ /* O(1) */ } /* O(1) */ } /* O(1) */ /* O(1) */ } ``` Summing this up, we get: $( cases(O(1) + (sum_(i=0)^N O(1)) + O(1), O(1)) ) + O(1) + O(1)$ We can apply the summation rule for summation of a constant, and get rid of some of the redundant $O(1)$s $( cases(O(N), O(1)) ) + O(1)$ Remembering that Big-$O$ is an _upper_ bound, we take the worse case $O(N) + O(1) = O(N)$ So, from a worst-case perspective, it seems as though we haven't actually improved anything. That makes sense: On *any* call to `add`, it's possible that we might trigger the worst case behavior, and have to pay the $O(N)$ cost. On the other hand, $B-1$ out of every $B$ calls only have to pay $O(1)$, so while any *one* call to `add` might behave badly, maybe this leads to better performance on average? === Amortized Analysis A large part of the reason that asymptotic runtime complexity is useful is that it allows us to plan out our algorithms. Big-$O$, a.k.a. "worst-case" run-times are a safe bet for that planning process, since you know that it can't be any worse. However, there are some cases where strictly using Big-$O$ ends up being too conservative, and you actually end up with an algorithm that has better performance than following the rules of worst-case analysis would lead you to believe. On the other hand, just giving up and saying "well, the analysis says X, but it's usually faster" isn't helpful when you're trying to be precise. In short, we still want to be able to make _some_ formal claim about the runtime of this new `add` function that will help us to understand its behavior, but Big-$O$ isn't the right language to use for that. We need to define some new terms#footnote[ Amortized complexity, which we discuss here, is one of two relaxations of simple, or "unqualified" asymptotic complexity. We'll talk about Expected complexity in the next chapter, as we introduce Quick Sort. ]. Intuitively, even if every $B$'th call to `add` is slow, most calls to `add` are fast. If we're trying to prove something, maybe we can show that these fast calls "average" out to a faster runtime if we call `add` repeatedly. For example, let's take the following loop, which just appends $L$ elements to a list of some sort: ```java public void addLots(List<Integer> list, int L) { for(i = 0; i < L; i++) { list.add(i); } } ``` Let's start off by seeing what happens if we assume that `list` starts off as an empty `SimpleArrayAsList`. ```java public void addLots(List<Integer> list, int L) { for(/* O(1), looping with i from 0 to L */) { /* O(N) = O(i) */; } } ``` For a simple array, appending a new element is $O(N)$. If we start off with an empty array, then on the `i`th insertion, $N = i$, so the add costs $O(i)$. This gives us a total runtime of: $T_"addLots1" (L) = O(1) + sum_(i = 0)^L (O(1) + O(i))$ Plugging in our standard summation formula and simplifying, we get: $T_"addLots1" (L) = O(1) + O(L^2) = O(L^2)$ Now let's try the same thing with `FixedIncrementArrayList`. If we do it naively, we get _exactly_ the same result, since `add` is $O(N) = O(i)$. However, this specific loop gives us a pattern we can benefit from: We know that every $B$ calls to `add` will be $O(N)$ and every other call will be $O(1)$. The summation looks like this (assuming $L$ is divisible by $B$): $T_"addLots2" (L) = underbrace( (overbrace(O(1) + ... + O(1), (B-1) "times") + O(B)) + ... + (overbrace(O(1) + ... + O(1), (B-1) "times") + O(L/B dot B)), L/B "times" )$ Collapsing the $(B-1)$ times, we get: $T_"addLots2" (L) = underbrace( (O(B-1) + O(B)) + (O(B-1) + O(2 dot B)) + ... + (O(B-1) + O(L/B dot B)), L/B "times" )$ We can rearrange these terms to get: $T_"addLots2" (L) = (underbrace(O(B-1) + ... + O(B-1), L/B "times")) + (underbrace(O(1 dot B) + O(2 dot B) + O(3 dot B) + ... + O(L/B dot B), L/B "times"))$ And again, simplifying, we get: $T_"addLots2" (L) = O(L/B dot (B-1)) + sum_(i = 1)^(L/B) O(i dot B) = O(L) + O(B) dot sum_(i = 1)^(L/B) O(i)$ Plugging in our summation formula and simplifying, we get $T_"addLots2" (L) = O(L) + O(B) dot O(L^2 / B^2) = O(L) + O(L^2 / B) = O(L^2 / B)$ This should make intuitive sense: Since we're only paying the cost of an expensive copy on every $B$ insertions, the cost of $L$ appends into an empty `FixedIncrementArrayList` is $1/B$th of the cost of the same appends into a simple array list. If we average the individual cost of each of the $L$ calls, each individual call "behaves" like its runtime is $O(L/B)$. Put another way, in the worst possible case, `FixedIncrementArrayList.add` is $O(N)$. However, if we're specifically analyzing the behavior of `add` when it is called in a loop, it's actually 100% safe to pretend like `add` is $O(N/B)$. We want a way to talk about this sort of behavior, where an operation on a data structure has a better runtime when it's called in a loop: A way to distinguish the 'looping' runtime complexity from the normal runtime complexity. The technical term for this better runtime is the "*amortized* runtime complexity" of the algorithm. *Formally*, if the amortized runtime complexity of an operation is $O(f(N))$, then the normal, or "unqualified" runtime complexity#footnote[ If the term "unqualified" seems a bit strange here, it's because the term "amortized" is a _qualifier_ that modifies the meaning of runtime complexity. "un-qualified" doesn't mean that it's not good at anything, but just that we're talking about the runtime complexity without any qualifiers. Next chapter, we'll introduce one more type of qualifier: "expected." ] of $N$ calls to the operation are guaranteed to be $O(N dot f(N))$. For the running example, we would say that: - The *unqualified* runtime complexity of `add` for `FixedIncrementArrayList` is $O(N)$ - The *amortized* runtime complexity of `add` for `FixedIncrementArrayList` is $O(N/B)$ Note that, it's possible to describe amortized complexity bounds as being "tight", if we know that we can't get a better bound. It's worth noting that the *tight amortized runtime complexity is never worse than the tight unqualified runtime complexity* of an algorithm, since invoking an algorithm in a loop can not make it slower. Formally, if the unqualified runtime is $O(f(N))$, then $N$ invocations is $sum_(i=0)^N O(f(N)) = O(N dot f(N))$, so by our definition above, the amortized runtime can not be worse than $O(f(N))$. === Buffered Arrays (Attempt 2: Exponential Increment) *(Alternative title: Try this one neat trick to get your asymptotic runtime bound down to $O(1)$)* The amortized runtime complexity of `add` for `FixedIncrementArrayList` is better than that of `SimpleArrayAsList`. However, in most cases $B$ is a constant, and so asymptotically $O(N)$ and $O(N/B)$ are the same. Put another way, doubling $N$ still doubles the runtime, even under amortized analysis. However, as it turns out, if we're a bit more clever about how we resize the array, we can actually push the asymptotic bound down to a lower complexity class: $O(1)$. The trick here is that, instead of adding a fixed size to the array ($B$) whenever we resize it, we always double the size of the array instead. This is the idea behind the `ArrayList` that is implemented in the Java standard library. ```java public class ArrayList<T> implements List<T> { T[] data = new T[1]; int size = 0; /* Other methods omitted */ public void add(T elem) { if(size >= data.length){ T[] temp = new T[data.length * 2]; // Double the array size for(i = 0; i < data.length; i++){ temp[i] = data[i]; } data = temp; } data[size] = elem; size += 1; } } ``` Analyzing the amortized runtime of this new version of `add` is a little trickier than the previous two instances of Array-based lists, but we can use the same strategy that worked with `FixedIncrementArrayList`: (i) Plug `ArrayList` into `addLots`, (ii) Rearrange terms to put the fast and slow cases together, (iii) Simplify. Let's start by figuring out how 'slow' calls there are, where we need to copy. - The first `add` call is $O(1)$ (array length 1). - The 2nd `add` call requires a copy (array length 2). - The 3rd `add` call requires a copy, and the next 1 call is $O(1)$ (array length 4). - The 5th `add` call requires a copy, and the next 3 calls are $O(1)$ (array length 8). - The 9th `add` call requires a copy, and the next 7 calls are $O(1)$ (array length 16). - The 17th `add` call requires a copy, and the next 15 calls are $O(1)$ (array length 32). The general pattern here is that the $i$th copy occurs on the $(2^(i)+1)$th call to `add`. All the remaining calls are cheap. Put another way, after $2^x$ calls to `add`, we will have resized the array $x-1$ times. So, if we want to call `add` $N$ times, we can set up an equation to solve for $x$: $N = 2^x$ Log is the inverse of exponent, so: $log_2 N = log_2 2^x = x$ Plugging this back into our formula ($x-1$), we find that we will have resized the array $log_2 (N) - 1 = O(log_2(N))$ times. On the $i$th time we need to resize the array, the array will have $2^(i-1)$ elements in it. So, we can figure out the total runtime of the calls to add as: $T_"addLots3" (L) = underbrace( O(1) + 2 O(1) + 4 O(1) + ... + (N-1) O(1), log_2 (N) - 1 "times" ) + underbrace( O(1) + O(1) + ... + O(1), N - (log_2 (N) - 1) "times" ) )$ We can summarize this as: $T_"addLots3" (L) = (sum_(i = 0)^(log_2 (N) - 1) 2^(i) O(1)) + (sum_(i = 0)^(N - (log_2 (N) - 1)) O(1)) $ Factoring out the $O(1)$ terms and expanding out the summations, we get: $T_"addLots3" (L) = O(1) dot (2^(log_2 (N) - 1 + 1) - 1) + O(1) dot (N - log_2 (N) + 2) $ Simplifying and noting that $2^(log_2 (N)) = N$, we get $T_"addLots3" (L) = (O(N) - O(1)) + (O(N) - O(log_2(N)) + O(1)) $ And since the dominant term here is $O(N)$, the whole thing reduces to $T_"addLots3" (L) = O(N)$ Remember that `addLots` calls `add` $N$ times, so each individual call 'behaves' like it is $O(N) / N = O(1)$. In other words, the *amortized* runtime complexity of `add` is $O(1)$! It's left as an exercise for you to prove that the unqualified runtime complexity of `add` is still $O(N)$, so this might feel a bit weird: $N$ calls to an $O(N)$ operation should normally be $O(N^2)$, but in this specific case, it's actually $O(N)$, a substantially lower complexity class. What is it about exponentially growing the array, doubling its size every time, that makes this possible? The intuition here is that every time you double the size of the array from $N$ to $2N$ you're putting in $O(N)$ work to copy elements, but you can now do $N$ insertions before you need to copy again. This is true, even as $N$ grows. Each time, no matter how big $N$ gets, $O(N)$ work gets you another $N$ insertions. The $O(N)$ work "amortizes" over the next $N$ insertions, and the ratio of cost to insertions stays the same. Contrast this with the Fixed-Increment Array List, where increasing the size of the array from $N$ to $N+B$ took $N$ work, but only provided space for another $B$ insertions. $N$ grows, while $B$ stays the same, and the ratio of cost to insertions keeps growing. *Note:* It can be tempting to think that, if a data structure promises an $O(1)$ amortized runtime for an operation, you can safely treat the operation as $O(1)$ in all cases. However, as exemplified in `ArrayList`, the cost of array resizing can actually get quite high. Even though the cost amortizes over multiple calls, there are many use cases where `ArrayList` is not appropriate. For example, let's say you're building a high-performance scientific data sensing application, which needs to be able to append sensor readings with sub-microsecond latencies. `ArrayList` would *not* be appropriate for such an application, because some sensor readings would have to block on the array list while it resizes, violating the quality of service guarantees. == Recap To summarize, we have introduced two ADTs: `Sequence` and the more general `List`; as well as three main data structures: The `Array`, the `LinkedList`, and the `ArrayList`. Overall asymptotic runtime bounds for these structures, assuming a Doubly-Linked list with a pointer to the last element, are as follows: #table( columns: 5, inset: 10pt, align: horizon, stroke: none, table.header( [], table.vline(), `Array`, [`LinkedList` (by Idx)], [`LinkedList` (by Ref)], `ArrayList` ), table.hline(), [`get(i)`], $O(1)$, $O(i)$, $O(1)$, $O(1)$, [`set(i,v)`], $O(1)$, $O(i)$, $O(1)$, $O(1)$, [`add(i,v)`], $O(N)$, $O(i)$, $O(1)$, [$O(N-i)$ amortized, $O(N)$ unqualified], [`add(v)`], $O(N)$, $O(1)$, $O(1)$, [$O(1)$ amortized, $O(N)$ unqualified], [`remove(i)`], $O(N)$, $O(i)$, $O(1)$, $O(N-i)$, )
https://github.com/vonhyou/typst-resume-template
https://raw.githubusercontent.com/vonhyou/typst-resume-template/master/section.typ
typst
#let list_items(items: ()) = { for item in items { let left_item = item.at(0) let right_item = item.at(1) text(left_item + h(1fr) + right_item) } } #let section( title: "Section", items: () ) = { grid( columns: (65pt, auto), gutter: 10pt, text(size: 12pt, weight: "bold", smallcaps(title)), list_items(items: items) ) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/yagenda/0.1.0/README.md
markdown
Apache License 2.0
# yagenda A Typst template for meeting agendas using Yaml for agenda items. To get started: ```typst typst init @preview/yagenda:0.1.0 ``` And edit the `main.typ` example. The data are drawn from `agenda.yaml`. ![Preview of the first page](thumbnail.png) ## Contributing PRs are welcome! And if you encounter any bugs or have any requests/ideas, feel free to open an issue. ## Acknowledgements The Typst grid layout was designed by [PgSuper on Discord](https://discord.com/channels/1054443721975922748/1219401775908655115).
https://github.com/Skimmeroni/Appunti
https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Matematica4AI/LinAlg/Spaces.typ
typst
Creative Commons Zero v1.0 Universal
#import "../Math4AI_definitions.typ": * Let $V$ be a set, whose elements are called *vectors*. A vector $underline(v)$ is denoted as $underline(v) = (v_(1), v_(2), dots, v_(n))$, where each $v_(i)$ with $1 lt.eq i lt.eq n$ is called the $i$-th *component* of $underline(v)$. Let $+$ be an operation on such set, a _sum_ of vectors, that has two vectors as arguments and returns another vector. That is, foreach $(underline(x), underline(y)) in V times V$ there exists a vector $underline(v) in V$ such that $underline(x) + underline(y) = underline(v)$. Let $dot$ be another operation, a _product_ between a vector and a real number, that has a real number and a vector as argument and returns another vector. That is, foreach $lambda in RR$ and $underline(v) in V$ there exists a vector $underline(w) in V$ such that $lambda dot underline(v) = underline(w)$. Suppose those operations possess the following properties: - $(V, +)$ is an Abelian group; - The product has the distributive property, such that for every $lambda in RR$ and for every $underline(x), underline(y) in V$ it is true that $lambda dot (underline(x) + underline(y)) = lambda dot underline(x) + lambda dot underline(y)$; - The product has the associative property, such that for every $lambda, mu in RR$ and for every $underline(x) in V$ it is true that $(lambda + mu) dot underline(x) = lambda dot underline(x) + mu dot underline(x)$; - For every vector $underline(v) in V$, it is true that $1 dot underline(v) = underline(v)$. If that is the case, the set $V$ is called *vector space*. It should be noted that it does not matter what the elements of a vector space actually are (be they numbers, functions, polynomals, etcetera); as long as the aforementioned properties hold for the two operations, such set shares all of the properties that a vector space possesses. For the sake of readability, the product between a real number and a vector is often represented without the dot. That is to say, the expressions $lambda dot underline(x)$ and $lambda underline(x)$ have the same meaning. #exercise[ Denote as $RR^(n)$ the set containing all vectors of real components #footnote("This is a misnomer.") in the $n$-dimensional plane. Prove that $RR^(n)$ constitutes a vector space. ] #solution[ It is possible to define both a sum between two vectors in the $n$-dimensional plane and a product between a vector in the $n$-dimensional space and a real number. To sum two vectors in the $n$-dimensional space, it suffices to sum each component with each component. To multiply a vector in the $n$-dimensional space with a real number it suffices to multiply each component by that number: #grid( columns: (0.5fr, 0.5fr), [$ mat(v_(1); v_(2); dots.v; v_(n)) + mat(w_(1); w_(2); dots.v; w_(n)) = mat(v_(1) + w_(1); v_(2) + w_(2); dots.v; v_(n) + w_(n)) $], [$ lambda mat(v_(1); v_(2); dots.v; v_(n)) = mat(lambda v_(1); lambda v_(2); dots.v; lambda v_(n)) $] ) Both operations obey the properties stated: - $(RR^(n), +)$ constitutes an Abelian group. Infact: - The sum has the associative property: $ mat(v_(1) + w_(1); v_(2) + w_(2); dots.v; v_(n) + w_(n)) + mat(u_(1); u_(2); dots.v; u_(n)) = mat(v_(1) + w_(1) + u_(1); v_(2) + w_(2) + u_(2); dots.v; v_(n) + w_(n) + u_(n)) = mat(v_(1); v_(2); dots.v; v_(n)) + mat(w_(1) + u_(1); w_(2) + u_(2); dots.v; w_(n) + u_(n)) $ - There exists an identity element, in the form of the vector whose components are all zero: $ mat(v_(1); v_(2); dots.v; v_(n)) + mat(0; 0; 0; 0) = mat(v_(1) + 0; v_(2) + 0; dots.v; v_(n) + 0) = mat(0 + v_(1); 0 + v_(2); dots.v; 0 + v_(n)) = mat(v_(1); v_(2); dots.v; v_(n)) $ - Each vector in the $n$-dimensional space has an inverse element with respect to the sum, that is the same vector multiplied by $-1$: $ mat(v_(1); v_(2); dots.v; v_(n)) + (-1) mat(v_(1); v_(2); dots.v; v_(n)) = mat(v_(1); v_(2); dots.v; v_(n)) + mat(-v_(1); -v_(2); dots.v; -v_(n)) = mat(v_(1) + (-v_(1)); v_(2) + (-v_(2)); dots.v; v_(n) + (-v_(n))) = mat(-v_(1) + v_(1); -v_(2) + v_(2); dots.v; -v_(n) + v_(n)) = mat(0; 0; dots.v; 0) $ - The sum has the commutative property: $ mat(v_(1); v_(2); dots.v; v_(n)) + mat(w_(1); w_(2); dots.v; w_(n)) = mat(v_(1) + w_(1); v_(2) + w_(2); dots.v; v_(n) + w_(n)) = mat(w_(1) + v_(1); w_(2) + v_(2); dots.v; w_(n) + v_(n)) = mat(w_(1); w_(2); dots.v; w_(n)) + mat(v_(1); v_(2); dots.v; v_(n)) $ - The product has the associative property: $ (lambda + mu) mat(v_(1); v_(2); dots.v; v_(n)) = mat((lambda + mu) v_(1); (lambda + mu) v_(2); dots.v; (lambda + mu) v_(n)) = mat(lambda v_(1) + mu v_(1); lambda v_(2) + mu v_(2); dots.v; lambda v_(n) + mu v_(n)) = mat(lambda v_(1); lambda v_(2); dots.v; lambda v_(n)) + mat(mu v_(1); mu v_(2); dots.v; mu v_(n)) = lambda mat(v_(1); v_(2); dots.v; v_(n)) + mu mat(v_(1); v_(2); dots.v; v_(n)) $ - The product has the distributive property: $ lambda (mat(v_(1); v_(2); dots.v; v_(n)) + mat(w_(1); w_(2); dots.v; w_(n))) = lambda mat(v_(1) + w_(1); v_(2) + w_(2); dots.v; v_(n) + w_(n)) = mat(lambda (v_(1) + w_(1)); lambda (v_(2) + w_(2)); dots.v; lambda (v_(n) + w_(n))) = mat(lambda v_(1) + lambda w_(1); lambda v_(2) + lambda w_(2); dots.v; lambda v_(n) + lambda w_(n)) = lambda mat(v_(1); v_(2); dots.v; v_(n)) + lambda mat(w_(1); w_(2); dots.v; w_(n)) $ - Multiplying a vector by the number $1$ leaves the vector unchanged: $ 1 mat(v_(1); v_(2); dots.v; v_(n)) = mat(1 v_(1); 1 v_(2); dots.v; 1 v_(n)) = mat(v_(1); v_(2); dots.v; v_(n)) $ ] #exercise[ Denote as $PP_(n)$ the set containing all polynomials with real coefficients and degree less than or equal to $n$. Prove that $PP_(n)$ constitutes a vector space. ] #solution[ It is possible to define both a sum between two polynomials with real coefficients and degree $lt.eq n$ and a product between a polynomial with real coefficients and degree $lt.eq n$ and a real number. To sum two such polynomials it suffices to sum the coefficients of their monomials having the same degree: $ (a_(n) x^(n) + a_(n - 1) x^(n - 1) + dots + a_(1) x + a_(0)) + (b_(m) x^(m) + b_(m - 1) x^(m - 1) + dots + b_(1) x + b_(0)) = \ a_(n) x^(n) + a_(n - 1) x^(n - 1) + dots + (a_(m) + b_(m)) x^(m) + (a_(m - 1) + b_(m - 1)) x^(m - 1) + dots + (a_(1) + b_(1)) x + (a_(0) + b_(0)) $ To multiply a polynomial with real coefficients and degree $lt.eq n$ with a real number it suffices to multiply each coefficient of its monomials by such number: $ lambda (a_(n) x^(n) + a_(n - 1) x^(n - 1) + dots + a_(1) x + a_(0)) = (lambda a_(n)) x^(n) + (lambda a_(n - 1)) x^(n - 1) + dots + (lambda a_(1)) x + (lambda a_(0)) $ Both operations satisfy the properties required. // Maybe add such? ] Given a vector space $V$, a set $W$ is said to be a *subspace* of $V$ if it's a subset of $V$ and it's itself a vector space with respect to the same operations defined for $V$. #theorem[ Let $V$ be a vector space. To prove that a set $W$ is a subspace of $V$ it suffices to prove that it is a subset of $V$ and is algebraically closed with respect to the same operations defined for $V$. ] <Subspace-proven-by-being-algebraically-closed> // #proof[ // To be added // ] #exercise[ Consider the vector space $RR^(3)$. Prove that the set $W_(1)$ is a subspace of $RR^(3)$ while $W_(2)$ is not. #grid( columns: (0.5fr, 0.5fr), [$ W_(1) = {mat(x_(1); x_(2); x_(3)) : mat(x_(1); x_(2); x_(3)) in RR^(3), x_(1) + x_(2) = 0} $], [$ W_(2) = {mat(x_(1); x_(2); x_(3)) : mat(x_(1); x_(2); x_(3)) in RR^(3), x_(2) = 2x_(3) + 1} $] ) ] #solution[ The first set is a subspace of $RR^(3)$ because it is a subset of $V$ and is algebraically closed: $ mat(x_(1); x_(2); x_(3)) + mat(y_(1); y_(2); y_(3)) = mat(x_(1); -x_(1); x_(3)) + mat(y_(1); -y_(1); y_(3)) = mat(x_(1) + y_(1); -x_(1) - y_(1); x_(3) + y_(3)) => x_(2) + y_(2) = -x_(1) - y_(1) => x_(2) + y_(2) + (x_(1) + y_(1)) = 0 $ $ lambda mat(x_(1); x_(2); x_(3)) = lambda mat(x_(1); -x_(1); x_(3)) = mat(lambda x_(1); -lambda x_(1); lambda x_(3)) => lambda x_(2) = -lambda x_(1) => lambda(x_(1) + x_(2)) = 0 $ The second one, on the other hand, is not: $ mat(x_(1); x_(2); x_(3)) + mat(y_(1); y_(2); y_(3)) = mat(x_(1); 2x_(3) + 1; x_(3)) + mat(y_(1); 2y_(3) + 1; y_(3)) = mat(x_(1) + y_(1); 2x_(3) + 2y_(3) + 2; x_(3) + y_(3)) => 2x_(3) + 2y_(3) + 2 eq.not 2(x_(3) + y_(3)) + 1 $ ] #theorem[ Let $V$ be a vector space. The sets ${underline(0)}$ and $V$ are always subspaces of $V$. ] // #proof[ // To be added (it's easy) // ]
https://github.com/taooceros/MATH-542-HW
https://raw.githubusercontent.com/taooceros/MATH-542-HW/main/Midterm/Midterm.typ
typst
#import "@local/homework-template:0.1.0": * #let tensor = $times.circle$ #let div = $\/$ = Problem 1 Let $A = ZZ div 3 cplus ZZ div 12$. Find the number of elements in $A tensor_ZZ A$. #let zmod(x) = $ZZ div #x$ #let solution = solution.with(base_level: 0) #solution[ $ A tensor_ZZ A &= (ZZ div 3 cplus ZZ div 12) tensor_ZZ (ZZ div 3 cplus ZZ div 12) \ &= (ZZ div 3 tensor_ZZ ZZ div 3) cplus (ZZ div 3 tensor_ZZ ZZ div 12) cplus (ZZ div 12 tensor_ZZ ZZ div 3) cplus (ZZ div 12 tensor_ZZ ZZ div 12) \ $ We know that $ZZ div 3 tensor ZZ div 3$ has $3$ elements because there are $3$ element in $ZZ div 3$ that divides $3$, and thus this is isomorphic to $ZZ div 3$. Similarly, $ZZ div 12 tensor ZZ div 12$ has $12$ elements. Finally, $ZZ div 3 tensor ZZ div 12$ has $3$ elements because $ZZ div 3 tensor ZZ div 12 cong (ZZ div 3) div (12 ZZ div 3)$, and since $12$ divides $3$ the $12 ZZ div 3$ is the trivial group. Since tensor is commutative, we have that $ZZ div 12 tensor ZZ div 3 cong ZZ div 3 tensor ZZ div 12$, and thus $ZZ div 12 tensor ZZ div 3$ has $3$ elements. ] = Problem 2 Find the number of pairs $(x,y) in (zmod(30) times zmod(30))$ so that $4x + 10 y = 0$ and $10x + 4y = 0$. #solution[ This is equivalent to find the number of solutions for the following equation $ mat(4, 10;10, 4) mat(x;y) = mat(0;0) $ And it is equivalent to find the number of solutions for the SNF of the matrix $A = mat(4, 10;10, 4)$. We know that the only invertible element in $ZZ$ is $plus.minus 1$. Thus, the SNF of the matrix is $S mat(2, 0;0, 42) T$, where the left top corner must be $gcd(4, 10, 10, 4)$ and the right bottom corner is the determinant of matrix $A$. Since we are in $zmod(30)$, $42 = 6 times 7$, and $7$ is invertible in $zmod(30)^times$ and thus it is equivalent to $6$, and $2 | 30$. Thus, the number of solutions is $2 times 6 = 12$. ] = Problem 3 A _generating set_ of a group $G$ is a set $S subset G$ so that the smallest subgroup of $G$ containing $S$ is $G$ itself. Prove of disprove: there is a subgroup of $zmod(12)^5$ whose smallest generating set has size $7$. #solution[ Assume such a subgroup $H$ exists. Consider the preimage of $H$ under the map that sends $ZZ^5 -> zmod(12)^5$. Observes that the preimage is a subgroup of $ZZ^5$ and it must contains a generating set at least the size of the generating set of $H$. Thus, the preimage must have a generating set of size larger or equal to $7$. Note that a subgroup in $ZZ^5$ is a $ZZ$-submodule, and since $ZZ$ is a PID, all of its submodule is free and must have smaller rank than $ZZ^5$. Thus, the preimage must have rank at most $5$. The rank is equal to the smallest generating set of the module, and thus we have a contradiction. ] = Problem 4 #let GL(n, F) = $op("GL")_#n (#F)$ Let $G$ be a finite subgroup of $GL(n, CC)$. Let $D$ be the subgroup of diagonal matrices in $GL(n, CC)$. Show that if $G$ is abelian then it is conjugate to a subgroup of $D$. #let diag(..args) = { let args = args.pos(); let length = args.len(); let result = (); for (i, e) in args.enumerate() { let row = (); for j in range(i) { row.push(0) } row.push(e) for j in range(length - i - 1) { row.push(0) } result.push(row); } math.mat(..result) } #solution[ We know that $C^n$ is a $C[G]$-module. Further we know that $CC^n$ can be written as sum of one dimensional simple $C[G]$-modules, denoted as $V_i$. Then we further know that each $V_i$ will be determined by the action of $G$, i.e. $delta_i : G -> CC^times$, and thus there must exist some $B$ such that $forall A in G : B A B^(-1) = diag(delta_1(g), dots.down, delta_n(g)) in D$ ] = Problem 5 Suppose that $(a,b)$ and $(c, d)$ are two elements of $ZZ^2$ and let $G$ be the subgroup of $ZZ^2$ that they generate. Suppose that $a d - b c = 12$. Find the number, up to isomorphism, of all possible quotient groups $ZZ^2 div G$. #solution[ It suffices to consider all matrix of the form $A = mat(a, b; c, d)$ where $a d - b c = 12$ and $a,b,c,d in ZZ$. Note that $a d - b c = det(A)$, and $det(A) = d_1 times d_2$, where $d_1$ and $d_2$ are the invariant factors of $A$. Thus it suffices to consider all the possible invariant factor of $A$. Since $12 = 3 times 4$, and thus the only invariant factor combination is $(1,12)$ and $(2,6)$, which means the number of quotient group is only $2$ up to isomorphism. ] = Problem 6 Let $A = ZZ cplus zmod(6) cplus zmod(3)$. Consider the homomorphsm $phi : A -> QQ tensor_ZZ A$ given by $phi(a) = 1 tensor a$. Find the number of elements in $ker(phi)$. #solution[ We know that $QQ tensor_ZZ A = QQ tensor (ZZ cplus zmod(6) cplus zmod(3)) = QQ tensor ZZ cplus QQ tensor zmod(6) cplus QQ tensor zmod(3)$. Since this is a direct sum of three tensor product, it will be $0$ if and only if all three entries are $0$. Firstly consider how many elements in $zmod(6)$ that will be $0$ when sending $a arrow.bar 1_QQ tensor a$. Since $6$ divides $1$ in $QQ$, we know that all elements in $zmod(6)$ will be $0$ when sending $a arrow.bar 1_QQ tensor a$. Similar reasoning yield us that all elements in $zmod(3)$ will be $0$ when sending $a arrow.bar 1_QQ tensor a$. Finally, we know that $QQ tensor_ZZ ZZ$ is isomorphic to $QQ$ with isomorphism $f : (q tensor z) arrow.bar q dot z$, and thus $QQ tensor ZZ$ will be $0$ if and only if $z$ is $0$, which means we have only $0$ maps to $0$ in $phi$. Therefore the number of elements in $ker(phi)$ is $1 times 3 times 6 = 18$. ] = Problem 7 Suppose that $A$ is $4 times 4$ matrix with rational entries and whose characteristic polynomial is $x^2(x^2+1)$. Produce a finite collection $S$ of explicit matrices and show that, for some $B$ in $GL(4, QQ)$, $B A B^(-1)$ belongs to $S$. #solution[ It suffices to find the all possible Rational Canonical Form with characteristic polynomial $x^2 (x^2 + 1)$. The prime decomposition of $x^2 (x^2 + 1)$ is $ x, x, (x^2 + 1) $ We know that the product of invariant factors are the characteristic polynomial. Thus the possible invariant factors are $ x^2(x^2 + 1) = x^4 + x^2 \ x, x(x^2 + 1) = x^3 + x \ $ Using the algorithm in the book, we can find the possible Rational Canonical Form are $ mat(0, 0, 0, 0; 1, 0 ,0, 0; 0, 1, 0, -1; 0, 0, 1, 0) \ mat(0, 0, 0, 0; 0, 0, 0, 0; 0, 1, 0, -1; 0, 0, 1, 0;) \ $ Since these are the only two possible Rational Canonical Form with charateristic polynomial $x^2 (x^2 + 1)$, we know that $A$ must be conjugate to one of them. ]
https://github.com/soarowl20240613/geelypaper
https://raw.githubusercontent.com/soarowl20240613/geelypaper/main/opening.typ
typst
#let noindent(body) = { set par(first-line-indent: 0em) body } #let opening( title: "", faculty: "", profession: "", author: "", studentnumber: "", adviser: "", purpose: none, status: none, method: none, result: none, plan: none, bibliography: none, audit: none, body: none, ) = { set document(title: title, author: author) set enum(numbering: "1.a,i.") set par(first-line-indent: 2em, justify: true) show par: set block(spacing: 0.65em) set text(font: ("Times New Roman", "SimSun"), lang: "zh") //************ 标题页设置 v(5fr) // align(center, image("logo.png", width: 50%)) v(10pt) set align(center) text(3em, "吉利学院") v(10pt) text(3em, "毕业论文(设计)开题报告") v(10fr, weak: true) let hline() = [#v(-0.7em)#line(length: 20em)] table( columns: (20%, auto), stroke: none, [题#h(2em)目:], [#title#hline()], [学#h(2em)院:], [#faculty#hline()], [专#h(2em)业:], [#profession#hline()], [学生姓名:], [#author#hline()], [学#h(2em)号:], [#studentnumber#hline()], [指导教师:], [#adviser#hline()], ) v(10fr, weak: true) set align(left) pagebreak() //************ let h1em = [#h(1em)#v(-0.7em)#line(length: 1em)] let h2em = [#h(2em)#v(-0.7em)#line(length: 2em)] let signature = { grid( columns: (2fr, 1fr, 2fr, 1fr, 2fr), [指导教师(签字):], [], [教研室负责人(签字):], [], [#align(end)[#h(2em)年#h(1em)月#h(1em)日]], ) } table( columns: (1fr,), [*一、选题依据和意义*#linebreak()#purpose], [*二、国内外研究状况*#linebreak()#status], [*三、研究内容及思路方法*#linebreak()#method], [*四、预期结果*#linebreak()#result], [*五、进度计划*#linebreak()#plan], [*六、参考文献*#linebreak()#bibliography], [审阅意见:#linebreak()#audit#signature], ) body }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/include.typ
typst
Apache License 2.0
#include #include "ident.typ" #include;"ident.typ" #include"ident.typ"; #include("ident.typ"); #include { "ident.typ" };
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/scripting/ops.typ
typst
// Test binary expressions. --- ops-add-content --- // Test adding content. #([*Hello* ] + [world!]) --- ops-unary-basic --- // Test math operators. // Test plus and minus. #for v in (1, 3.14, decimal("12.43"), 12pt, 45deg, 90%, 13% + 10pt, 6.3fr) { // Test plus. test(+v, v) // Test minus. test(-v, -1 * v) test(--v, v) // Test combination. test(-++ --v, -v) } #test(-(4 + 2), 6-12) // Addition. #test(2 + 4, 6) #test("a" + "b", "ab") #test("a" + if false { "b" }, "a") #test("a" + if true { "b" }, "ab") #test(13 * "a" + "bbbbbb", "aaaaaaaaaaaaabbbbbb") #test((1, 2) + (3, 4), (1, 2, 3, 4)) #test((a: 1) + (b: 2, c: 3), (a: 1, b: 2, c: 3)) --- ops-add-too-large --- // Error: 3-26 value is too large #(9223372036854775807 + 1) --- ops-binary-basic --- // Subtraction. #test(1-4, 3*-1) #test(4cm - 2cm, 2cm) #test(1e+2-1e-2, 99.99) // Multiplication. #test(2 * 4, 8) // Division. #test(12pt/.4, 30pt) #test(7 / 2, 3.5) // Combination. #test(3-4 * 5 < -10, true) #test({ let x; x = 1 + 4*5 >= 21 and { x = "a"; x + "b" == "ab" }; x }, true) // With block. #test(if true { 1 } + 2, 3) // Mathematical identities. #let nums = ( 1, 3.14, decimal("12.45"), 12pt, 3em, 12pt + 3em, 45deg, 90%, 13% + 10pt, 5% + 1em + 3pt, 2.3fr, ) #for v in nums { // Test plus and minus. test(v + v - v, v) test(v - v - v, -v) // Test plus/minus and multiplication. test(v - v, 0 * v) test(v + v, 2 * v) // Integer or decimal addition does not give a float. if type(v) not in (int, decimal) { test(v + v, 2.0 * v) } if type(v) not in (relative, decimal) and ("pt" not in repr(v) or "em" not in repr(v)) { test(v / v, 1.0) } } // Make sure length, ratio and relative length // - can all be added to / subtracted from each other, // - multiplied with integers and floats, // - divided by integers and floats. #let dims = (10pt, 1em, 10pt + 1em, 30%, 50% + 3cm, 40% + 2em + 1cm) #for a in dims { for b in dims { test(type(a + b), type(a - b)) } for b in (7, 3.14) { test(type(a * b), type(a)) test(type(b * a), type(a)) test(type(a / b), type(a)) } } // Test division of different numeric types with zero components. #for a in (0pt, 0em, 0%) { for b in (10pt, 10em, 10%) { test((2 * b) / b, 2) test((a + b * 2) / b, 2) test(b / (b * 2 + a), 0.5) } } --- ops-binary-decimal --- // Addition. #test(decimal("40.1") + decimal("13.2"), decimal("53.3")) #test(decimal("12.34330") + decimal("45.96670"), decimal("58.31000")) #test(decimal("451113.111111111111111111111") + decimal("23.222222222222222222324"), decimal("451136.333333333333333333435")) // Subtraction. #test(decimal("40.1") - decimal("13.2"), decimal("26.9")) #test(decimal("12.34330") - decimal("45.96670"), decimal("-33.62340")) #test(decimal("1234.111111111111111111111") - decimal("0.222222222222222222324"), decimal("1233.888888888888888888787")) // Multiplication. #test(decimal("40.5") * decimal("9.5"), decimal("384.75")) #test(decimal("-0.1234567890123456789012345678") * decimal("-2.0"), decimal("0.2469135780246913578024691356")) // Division. #test(decimal("1.0") / decimal("7.0"), decimal("0.1428571428571428571428571429")) #test(decimal("9999991.6666") / decimal("3.0"), decimal("3333330.5555333333333333333333")) #test(decimal("3253452.4034029359598214312040") / decimal("-49293591.4039493929532"), decimal("-0.0660015290170614346071165643")) --- ops-binary-decimal-int --- // Operations between decimal and integer. #test(decimal("2359.123456789123456789001234") + 2, decimal("2361.123456789123456789001234")) #test(decimal("2359.123456789123456789001234") - 2, decimal("2357.123456789123456789001234")) #test(decimal("2359.123456789123456789001234") * 2, decimal("4718.246913578246913578002468")) #test(decimal("2359.123456789123456789001234") / 2, decimal("1179.561728394561728394500617")) --- ops-binary-decimal-multiplication-division-imprecision --- // Test digit truncation by multiplication and division. #test(decimal("0.7777777777777777777777777777") / 1000, decimal("0.0007777777777777777777777778")) #test(decimal("0.7777777777777777777777777777") * decimal("0.001"), decimal("0.0007777777777777777777777778")) --- ops-add-too-large-decimal --- // Error: 3-47 value is too large #(decimal("79228162514264337593543950335") + 1) --- ops-subtract-too-large-decimal --- // Error: 3-48 value is too large #(decimal("-79228162514264337593543950335") - 1) --- ops-multiply-inf-with-length --- // Test that multiplying infinite numbers by certain units does not crash. #(float("inf") * 1pt) #(float("inf") * 1em) #(float("inf") * (1pt + 1em)) --- ops-attempt-nan-length --- // Test that trying to produce a NaN scalar (such as in lengths) does not crash. #let infpt = float("inf") * 1pt #test(infpt - infpt, 0pt) #test(infpt + (-infpt), 0pt) // TODO: this result is surprising #test(infpt / float("inf"), 0pt) --- ops-unary-bool --- // Test boolean operators. // Test not. #test(not true, false) #test(not false, true) // And. #test(false and false, false) #test(false and true, false) #test(true and false, false) #test(true and true, true) // Or. #test(false or false, false) #test(false or true, true) #test(true or false, true) #test(true or true, true) // Short-circuiting. #test(false and dont-care, false) #test(true or dont-care, true) --- ops-equality --- // Test equality operators. // Most things compare by value. #test(1 == "hi", false) #test(1 == 1.0, true) #test(30% == 30% + 0cm, true) #test(1in == 0% + 72pt, true) #test(30% == 30% + 1cm, false) #test("ab" == "a" + "b", true) #test(() == (1,), false) #test((1, 2, 3) == (1, 2.0) + (3,), true) #test((:) == (a: 1), false) #test((a: 2 - 1.0, b: 2) == (b: 2, a: 1), true) #test("a" != "a", false) #test(decimal("1.234") == decimal("1.23400000000"), true) #test(235 == decimal("235.0"), true) // Functions compare by identity. #test(test == test, true) #test((() => {}) == (() => {}), false) // Content compares field by field. #let t = [a] #test(t == t, true) #test([] == [], true) #test([a] == [a], true) #test(grid[a] == grid[a], true) #test(grid[a] == grid[b], false) --- ops-compare --- // Test comparison operators. #test(13 * 3 < 14 * 4, true) #test(5 < 10, true) #test(5 > 5, false) #test(5 <= 5, true) #test(5 <= 4, false) #test(45deg < 1rad, true) #test(10% < 20%, true) #test(50% < 40% + 0pt, false) #test(40% + 0pt < 50% + 0pt, true) #test(1em < 2em, true) #test((0, 1, 2, 4) < (0, 1, 2, 5), true) #test((0, 1, 2, 4) < (0, 1, 2, 3), false) #test((0, 1, 2, 3.3) > (0, 1, 2, 4), false) #test((0, 1, 2) < (0, 1, 2, 3), true) #test((0, 1, "b") > (0, 1, "a", 3), true) #test((0, 1.1, 3) >= (0, 1.1, 3), true) #test((0, 1, datetime(day: 1, month: 12, year: 2023)) <= (0, 1, datetime(day: 1, month: 12, year: 2023), 3), true) #test(("a", 23, 40, "b") > ("a", 23, 40), true) #test(() <= (), true) #test(() >= (), true) #test(() <= (1,), true) #test((1,) <= (), false) #test(decimal("123.0000000000000000000000001") > decimal("123.0"), true) #test(decimal("123.5") < decimal("122.444"), false) #test(decimal("459.9999999999999999999999999") < 460, true) #test(decimal("128.50") > 460, false) --- ops-in --- // Test `in` operator. #test("hi" in "worship", true) #test("hi" in ("we", "hi", "bye"), true) #test("Hey" in "abHeyCd", true) #test("Hey" in "abheyCd", false) #test(5 in range(10), true) #test(12 in range(10), false) #test("" in (), false) #test("key" in (key: "value"), true) #test("value" in (key: "value"), false) #test("Hey" not in "abheyCd", true) #test("a" not /* fun comment? */ in "abc", false) --- ops-not-trailing --- // Error: 10 expected keyword `in` #("a" not) --- func-with --- // Test `with` method. // Apply positional arguments. #let add(x, y) = x + y #test(add.with(2)(3), 5) #test(add.with(2, 3)(), 5) #test(add.with(2).with(3)(), 5) #test((add.with(2))(4), 6) #test((add.with(2).with(3))(), 5) // Make sure that named arguments are overridable. #let inc(x, y: 1) = x + y #test(inc(1), 2) #let inc2 = inc.with(y: 2) #test(inc2(2), 4) #test(inc2(2, y: 4), 6) // Apply arguments to an argument sink. #let times(..sink) = { let res = sink.pos().product() if sink.named().at("negate", default: false) { res *= -1 } res } #test((times.with(2, negate: true).with(5))(), -10) #test((times.with(2).with(5).with(negate: true))(), -10) #test((times.with(2).with(5, negate: true))(), -10) #test((times.with(2).with(negate: true))(5), -10) --- ops-precedence-basic --- // Multiplication binds stronger than addition. #test(1+2*-3, -5) // Subtraction binds stronger than comparison. #test(3 == 5 - 2, true) // Boolean operations bind stronger than '=='. #test("a" == "a" and 2 < 3, true) #test(not "b" == "b", false) --- ops-precedence-boolean-ops --- // Assignment binds stronger than boolean operations. // Error: 2:3-2:8 cannot mutate a temporary value #let x = false #(not x = "a") --- ops-precedence-unary --- // Precedence doesn't matter for chained unary operators. // Error: 3-12 cannot apply '-' to boolean #(-not true) --- ops-precedence-not-in --- // Not in handles precedence. #test(-1 not in (1, 2, 3), true) --- ops-precedence-parentheses --- // Parentheses override precedence. #test((1), 1) #test((1+2)*-3, -9) // Error: 8-9 unclosed delimiter #test({(1 + 1}, 2) --- ops-associativity-left --- // Math operators are left-associative. #test(10 / 2 / 2 == (10 / 2) / 2, true) #test(10 / 2 / 2 == 10 / (2 / 2), false) #test(1 / 2 * 3, 1.5) --- ops-associativity-right --- // Assignment is right-associative. #{ let x = 1 let y = 2 x = y = "ok" test(x, none) test(y, "ok") } --- ops-unary-minus-missing-expr --- // Error: 4 expected expression #(-) --- ops-add-missing-rhs --- // Error: 10 expected expression #test({1+}, 1) --- ops-mul-missing-rhs --- // Error: 10 expected expression #test({2*}, 2) --- ops-unary-plus-on-content --- // Error: 3-13 cannot apply unary '+' to content #(+([] + [])) --- ops-unary-plus-on-string --- // Error: 3-6 cannot apply '-' to string #(-"") --- ops-not-on-array --- // Error: 3-9 cannot apply 'not' to array #(not ()) --- ops-compare-relative-length-and-ratio --- // Error: 3-19 cannot compare relative length and ratio #(30% + 1pt <= 40%) --- ops-compare-em-with-abs --- // Error: 3-14 cannot compare 1em with 10pt #(1em <= 10pt) --- ops-compare-normal-float-with-nan --- // Error: 3-22 cannot compare 2.2 with float.nan #(2.2 <= float("nan")) --- ops-compare-int-and-str --- // Error: 3-26 cannot compare integer and string #((0, 1, 3) > (0, 1, "a")) --- ops-compare-array-nested-failure --- // Error: 3-42 cannot compare 3.5 with float.nan #((0, "a", 3.5) <= (0, "a", float("nan"))) --- ops-divide-by-zero-float --- // Error: 3-12 cannot divide by zero #(1.2 / 0.0) --- ops-divide-by-zero-int --- // Error: 3-8 cannot divide by zero #(1 / 0) --- ops-divide-by-zero-angle --- // Error: 3-15 cannot divide by zero #(15deg / 0deg) --- ops-binary-arithmetic-error-message --- // Special messages for +, -, * and /. // Error: 3-10 cannot add integer and string #(1 + "2", 40% - 1) --- add-assign-int-and-str --- // Error: 15-23 cannot add integer and string #{ let x = 1; x += "2" } --- ops-divide-ratio-by-length --- // Error: 4-13 cannot divide ratio by length #( 10% / 5pt ) --- ops-divide-em-by-abs --- // Error: 3-12 cannot divide these two lengths #(1em / 5pt) --- ops-divide-relative-length-by-ratio --- // Error: 3-19 cannot divide relative length by ratio #((10% + 1pt) / 5%) --- ops-divide-relative-lengths --- // Error: 3-28 cannot divide these two relative lengths #((10% + 1pt) / (20% + 1pt)) --- ops-subtract-int-from-ratio --- // Error: 13-20 cannot subtract integer from ratio #((1234567, 40% - 1)) --- ops-multiply-int-with-bool --- // Error: 3-11 cannot multiply integer with boolean #(2 * true) --- ops-divide-int-by-length --- // Error: 3-11 cannot divide integer by length #(3 / 12pt) --- multiply-negative-int-with-str --- // Error: 3-10 number must be at least zero #(-1 * "") --- ops-assign --- // Test assignment operators. #let x = 0 #(x = 10) #test(x, 10) #(x -= 5) #test(x, 5) #(x += 1) #test(x, 6) #(x *= x) #test(x, 36) #(x /= 2.0) #test(x, 18.0) #(x = "some") #test(x, "some") #(x += "thing") #test(x, "something") --- ops-assign-unknown-var-lhs --- #{ // Error: 3-6 unknown variable: a-1 // Hint: 3-6 if you meant to use subtraction, try adding spaces around the minus sign: `a - 1` a-1 = 2 } --- ops-assign-unknown-var-rhs --- #{ let a = 2 a = 1-a a = a -1 // Error: 7-10 unknown variable: a-1 // Hint: 7-10 if you meant to use subtraction, try adding spaces around the minus sign: `a - 1` a = a-1 } --- ops-assign-unknown-parenthesized-variable --- // Error: 4-5 unknown variable: x #((x) = "") --- ops-assign-destructuring-unknown-variable --- // Error: 4-5 unknown variable: x #((x,) = (1,)) --- ops-assign-to-temporary --- // Error: 3-8 cannot mutate a temporary value #(1 + 2 += 3) --- ops-assign-to-invalid-unary-op --- // Error: 2:3-2:8 cannot apply 'not' to string #let x = "Hey" #(not x = "a") --- ops-assign-to-invalid-binary-op --- // Error: 7-8 unknown variable: x #(1 + x += 3) --- ops-assign-unknown-variable --- // Error: 3-4 unknown variable: z #(z = 1) --- ops-assign-to-std-constant --- // Error: 3-7 cannot mutate a constant: rect #(rect = "hi") --- ops-assign-to-shadowed-std-constant --- // Works if we define rect beforehand // (since then it doesn't resolve to the standard library version anymore). #let rect = "" #(rect = "hi")
https://github.com/metamuffin/typst
https://raw.githubusercontent.com/metamuffin/typst/main/tests/typ/visualize/svg-text.typ
typst
Apache License 2.0
// Test SVG with text. --- #set page(width: 250pt) #figure( image("/diagram.svg"), caption: [A textful diagram], )
https://github.com/Walfisch115/thb-typst-template
https://raw.githubusercontent.com/Walfisch115/thb-typst-template/main/thesis/main.typ
typst
#import "conf.typ": conf #show: conf.with( title: "TITEL", author: "AUTOR", matrikelNumber: 12345678, supervisor: "ERSTER", secondReviewer: "ZWEITER", place: "TATTOOINE", date: "HEUTE", abstract: lorem(70), ) = Einleitung Dies ist ein Typoblindtext. An ihm kann man sehen, ob alle Buchstaben da sind und wie sie aussehen. Manchmal benutzt man Worte wie Hamburgefonts, Rafgenduks oder Handgloves, um Schriften zu testen (Laugwitz, Held & Schrepp, 2006). #figure( image("Bild1.png"), caption: [Beispielhafte Abbildung, modifiziert nach <NAME> und Magerko (2020)] ) Sehr bekannt ist dieser: The quick brown fox jumps over the lazy old dog. Oft werden in Typoblindtexte auch fremdsprachige Satzteile eingebaut, um die Wirkung in anderen Sprachen zu testen (Oberquelle, 1991). In Lateinisch sieht zum Beispiel fast jede Schrift gut aus. Quod erat demonstrandum. Seit 1975 fehlen in den meisten Testtexten die Zahlen, weswegen nach TypoGb. 204 §0 ab dem Jahr 2034 Zahlen in 86 der Texte zur Pflicht werden (vgl. DIN EN ISO 9241-110, 2006). #figure( table(image("Bild2.png")), caption: "Beispielhafte Tabelle aus Borghoff und Schlichter (1998)" ) Genauso wichtig in sind mittlerweile auch Âçcèñtë, die in neueren Schriften aber fast immer enthalten sind. Ein wichtiges aber schwierig zu integrierendes Feld sind OpenType-Funktionalitäten. Je nach Software und Voreinstellungen können eingebaute Kapitälchen, Kerning oder Ligaturen (sehr pfiffig) nicht richtig dargestellt werden (Friedrich et al. 1995). Nach Raskin (1994) ist ein wichtiges aber schwierig zu integrierendes Feld die OpenType-Funktionalität. Je nach Software und Voreinstellungen können eingebaute Kapitälchen, Kerning oder Ligaturen (sehr pfiffig) nicht richtig dargestellt werden. = Kapitel 2 (z.B. Analyse) Dies ist ein Typoblindtext. An ihm kann man sehen, ob alle Buchstaben da sind und wie sie aussehen. #footnote[Merke: Kapitel sind inhaltlich zu benennen: z.B. Analyse] == Erstes Unterkapitel (Ebene 2) Dies ist ein Typoblindtext. An ihm kann man sehen, ob alle Buchstaben da sind und wie sie aussehen. Sehr bekannt ist dieser: The quick brown fox jumps over the lazy old dog. Oft werden in Typoblindtexte auch fremdsprachige Satzteile eingebaut, um die Wirkung in anderen Sprachen zu testen. === Erstes Unterunterkapitel (Ebene 3) Dies ist ein Typoblindtext. An ihm kann man sehen, ob alle Buchstaben da sind und wie sie aussehen. Sehr bekannt ist dieser: The quick brown fox jumps over the lazy old dog. Oft werden in Typoblindtexte auch fremdsprachige Satzteile eingebaut, um die Wirkung in anderen Sprachen zu testen. === Zweites Unterunterkapitel (Ebene 3) Dies ist ein Typoblindtext. An ihm kann man sehen, ob alle Buchstaben da sind und wie sie aussehen. Sehr bekannt ist dieser: The quick brown fox jumps over the lazy old dog. Oft werden in Typoblindtexte auch fremdsprachige Satzteile eingebaut, um die Wirkung in anderen Sprachen zu testen. == Zweites Unterkapitel (Ebene 2) #lorem(10) Merke: in der Regel gibt es kein Unterkapitel n.1, wenn es nicht auch ein Unterkapitel n.2 gibt. Falls doch, dann sollte das Unterkapitel n.1 aufgelöst werden sodass das Kap. n keine Unterkapitel mehr aufweist. = Weiteres Kapitel (z B. Konzeption) Dies ist ein Typoblindtext. An ihm kann man sehen, ob alle Buchstaben da sind und wie sie aussehen. Sehr bekannt ist dieser: The quick brown fox jumps over the lazy old dog. Oft werden in Typoblindtexte auch fremdsprachige Satzteile eingebaut, um die Wirkung in anderen Sprachen zu testen. == Erstes Unterkapitel (Ebene 2) #lorem(50) === Erstes Unterunterkapitel (Ebene 3) #lorem(50) === Zweites Unterunterkapitel (Ebene 3) #lorem(50) == Zweites Unterkapitel (Ebene 2) #lorem(50) = Weiteres Kapitel (z.B. Implementierung) #lorem(50) == Erstes Unterkapitel (Ebene 2) #lorem(50) === Erstes Unterunterkapitel (Ebene 3) #lorem(50) === Zweites Unterunterkapitel (Ebene 3) #lorem(50) == Zweites Unterkapitel (Ebene 2) #lorem(50) = Letztes Kapitel #lorem(50) == Zusammenfassung #lorem(50) == Offene Punkte #lorem(50) == Ausblick #lorem(50)
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/004%20-%20Dragon's%20Maze/011_Battle%20for%20the%20Ninth.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Battle for the Ninth", set_name: "Dragon's Maze", story_date: datetime(day: 19, month: 06, year: 2013), author: "<NAME>", doc ) Gideon wiped the dirt and dust from his face and smiled. "They took the bait," Anza said excitedly, as pieces of the building rained down on their heads. Broken bricks lay strewn about them; they were barely visible to each other in the dust-filled air. "That's one thing about the Gruul you can count on," Gideon said. Another massive club swing caved in a nearby wall, which sent debris everywhere and snapped three huge support beams. The upper floors fell in around them like an avalanche—chairs, tables, and crockery clattered about in a torrent. They could hear a giant bellow with battle-rage outside. He was getting closer. #figure(image("011_Battle for the Ninth/01.jpg", width: 100%), caption: [], supplement: none, numbering: none) "Krokt!" Gideon said as he spat dust. "It's only a matter of time before he sniffs us out. Get back to the square, tell Dars that we're coming and to get into position. Look out!" Gideon shoved Anza out of the way as a second swing from the giant's club crushed the remaining wall and sent Gideon sprawling. He looked up and saw Anza move faster than a viashino as she jumped and scuttled through the clouds of dust and wreckage to the back alley. Gideon scrambled to his feet while the giant continued to swing wildly, chunks of buildings flying into the street like corkballs in a game of borlist. Just behind the giant, Gideon could hear a vast horde of Gruul as they beat the earth and chanted for war. Good, Gideon thought as he sprinted away. Bring them all. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) <NAME> heard the chaos echoing through the narrow streets of the Ninth District. All manner of hell was breaking loose and he still had no sign of Jura. Gideon had Dars assemble the Boros legion known as the Firefist in the square, hidden in the surrounding buildings. Many before had tried to reclaim the Ninth but all had failed. The unguilded citizens looked from behind their barred doors and shuttered windows at the Firefist. The citizens had learned just to board up the doors and wait it out when the guilds arrived in force. When the sounds of destruction echoed up the street to the square, they were much closer. The legionnaires stiffened and reached for their swords. The time had come. #figure(image("011_Battle for the Ninth/02.jpg", width: 100%), caption: [], supplement: none, numbering: none) "We're ready, captain." Dars's corporal, Jazek, looked at him with anticipation. "Good. Wait until Jura draws them into the square." Just then, Anza appeared on the street and ran across the expanse of the square; Dars met her under a stone archway. "They're coming," Anza said between breaths. "Commander Jura won't be far behind." "I'm sure he's made himself close friends of the Gruul," Dars said. "Did he draw enough of them out?" "Scab-Clan sent a couple big ones, Captain," Anza said, taking a drink from a canteen. "And there were plenty behind him ready for blood. Commander Jura's probably going to bring every Gruul in the Ninth to our position." "That's the plan." Dars smiled. He drew his sword and strode into the square to address his legion. "Firefist, positions! Now let's see if those Rakdos bastards take the bait and we'll have ourselves a real party." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Gideon ran into the great square like a madman, a horde of Gruul raging behind him like a storm. "Wait for it!" Gideon shouted as he sprinted past the center of the square toward the Boros front line. The Gruul poured into the square at the far end, ready for mayhem. As soon as the Gruul crossed the center of the square Gideon yelled, "Now!" Dars commanded, "Fire!" From the rooftops and upper floors, a blaze of Boros magic lit the square with streams of fire that slammed into the Gruul. Gruul warriors burst into flames and massive beasts crumpled into heaps, but the relentless horde plowed ahead through the bodies of the fallen toward the Boros line. #figure(image("011_Battle for the Ninth/03.jpg", width: 100%), caption: [], supplement: none, numbering: none) "Charge!" Gideon and the Boros rushed from their positions to engage the Gruul hand-to-hand. Behind them, a wave of firstblades, reckoners, and commandos bellowed their battle cries honoring the Ordruun and their sacred oaths. They crashed into a surge of Gruul warriors and beasts from the Ghor and Scab-Clan. Gideon threaded his way through the Boros ranks to find Dars. "Any sign from the Rakdos?" "Nothing," Dars said. "No sign." "Krokt." Gideon spat. "We can't hold the Gruul forever and we can't let them go. I just need that grinning dromad to get here with the Rakdos." Suddenly, from the other side of the square, a mad howl could be heard over the din of battle. An olive-skinned Boros knight clad in shining armor ran before a chaotic tangle of demons and deviants. A smile broke across the knight's face in a flash of white teeth when he saw Gideon. Gideon called, "Tajic! Look out!" A thunderclap of demonic magic hit Tajic like a cannonball and enveloped him in a cloud of fire and sulfur. Gideon stopped in his tracks but Tajic emerged untarnished, a smile still on his face. Boros fighters rushed to intercept the Rakdos as Tajic came to a stop before Gideon. "Jura, my friend! I return as promised!" Tajic's eyes twinkled with mirth as he brushed himself off. Tajic noticed Gideon's face. "Don't worry, Jura, it was just a little puff of smoke." #figure(image("011_Battle for the Ninth/04.jpg", width: 100%), caption: [], supplement: none, numbering: none) "I was wondering when you'd get here," Gideon said to the Boros maze runner. "Looks like you got their attention." "It was easy," Tajic said. "You just have to know what insults to use." Gideon looked for the Firefist captain. "Dars, the Rakdos have arrived!" Dars ordered a knight to sound the trumpet. In three sharp notes, the Firefist disengaged from the Gruul and fought their way back to form a bristling wall of Boros spears and swords as the Rakdos poured into the square in a scrabbling stream of insanity. They instantly tore into the Gruul with frenzy and relish. Boros minotaurs, deep in battle-fury, were dragged from the fight as they came to their senses enough to remember their training and fall back. "Contain them!" Gideon, Dars, and Tajic all yelled over the mayhem as they rushed to help hold areas of the Firefist line that showed signs of faltering. "Keep them in the square at all costs!" #figure(image("011_Battle for the Ninth/05.jpg", width: 100%), caption: [], supplement: none, numbering: none) Every effort of the Firefist was put into containing the chaos. Rakdos and Gruul slaughtered each other in the center of the square, lost in a frenzy of blood and rage. The Boros closed ranks on the outskirts of the battle and slowly closed in like the noose of a snare-trap. As the main company of the Firefist held the melee, Gideon had Tajic peel away with a platoon of reckoners and commandos to scout the remaining areas. Tajic linked up with a few patrols of Orzhov enforcers and knights who had already used their influence to root out some of the Dimir puppetmasters and ringleaders embedded within the Ninth. <NAME> cashed in a few favors to gain intelligence that only an Orzhov could obtain. There was a deal made with the Obzedat, of course: the Boros and Orzhov would share protection duties over the Ninth, but Teysa had assured them that she would be the one to oversee the district's welfare. It was a hard sell to Aurelia, but the angelic warmaster understood as much as anyone that uprooting the Dimir sleeper cells and purging them from the Ninth was necessary to take back the district. Of course, with the Dimir, one could never be too sure. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("011_Battle for the Ninth/06.jpg", width: 100%), caption: [], supplement: none, numbering: none) Gideon stood with the warleader after everyone had left. She picked up a small building from the large central table where a model of the Ninth district was laid out and looked at it for a moment. "You have done the Boros and me a great service, Jura," Aurelia said as she twirled the model in her fingers. Then she looked up at him. "You have done the citizens of Ravnica an even greater one. Are you certain you do not wish to join our ranks and serve the citizens of Ravnica?" Gideon smiled. "Nothing would please me more than to aid you and the Boros, warleader. I have not fought alongside better soldiers in all my time, but I am needed elsewhere. There are other battles I must fight." Aurelia looked at him with eyes that saw far more than mere human vision. Gideon wondered how much the angel understood of the forces outside Ravnica, or if she was aware of them at all. He offered his hand, Aurelia clasped his forearm in a grip of iron that sent heat and power buzzing into his body. "Thank you, Jura." She released his arm. He could still feel the energy working in his bones. Gideon bowed. "It was an honor, warleader." Suddenly, she smiled at him, energy radiating from her face. Gideon almost took a step back. It was all at once beautiful and overwhelming, and then just as suddenly she turned and walked out of the room. As she left she said, "You are always welcome at Sunhome, Jura."
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/029%20-%20Aether%20Revolt/004_Revolution%20Begins.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Revolution Begins", set_name: "Aether Revolt", story_date: datetime(day: 02, month: 01, year: 2017), author: "<NAME>, <NAME> & <NAME>", doc ) #emph[In a bid for power, Tezzeret installed himself as Grand Consul; now he holds the city of Ghirapur in his clutches. But there are those who refuse to stand for his tyranny. The renegade inventors plan to strike the Aether Hub. Victory would mean fuel for their inventions—and for their rebellion.] #figure(image("004_Revolution Begins/01.png", height: 40%), caption: [], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Ghirapur was constantly reinventing itself. Buildings were torn down all the time, and rebuilt stronger, taller, with better materials, better techniques. Almost every block, every square had seen some measure of renovation and repair within the last few years. The city had little room for history and less for nostalgia. In most parts of the city, the dust smelled of construction and sweat. There was never time for the scent of old wood and tarnished brass to settle in. Ghirapur left very little space for decay. But there were places. Narrow alleys where too many shadows seemed to fall, spots where the permits for renovation kept failing to be approved, spaces that most simply circumnavigated out of habit. Chandra Nalaar followed closely behind her mother into one of these forgotten causeways, a hood pulled up over her hair, and her eyes cast firmly on the ground in front of her feet. #figure(image("004_Revolution Begins/02.jpg", width: 100%), caption: [Concealed Courtyard | Art by Jung Park], supplement: none, numbering: none) "This place has been around for decades, you know." <NAME>'s voice was soft and even. "It's belonged to an aetherborn family all that time; they've kept it intact. Kiran...we used to come here. A long time ago." Chandra didn't look up. "Why are we here, mom?" "Gonti keeps this place off the Consulate patrol routes. People sympathetic to what we need to do, we'll find them here." Pia looked up at the unmarked doorway and breathed in the scent of grease, smoke, and spice. The door swung easily open on well-oiled hinges, and a flood of sound and light spilled out onto the street. Chandra pulled her hood back as she stepped into the club. Two dozen low round tables surrounded by cushions and small stools were set out in a wide semicircle around a small stage, raised only a foot off the floor; each table held a colorful lamp and was surrounded by people of all kinds engaged in whispered conversation. On stage was a chikara player playing softly under low lights, a part of the ambiance rather than the focus on the room. Pia waved to him as she entered and raised two fingers, and the musician nodded in understanding. "Look around you, Chandra." Pia smiled. "Some of the best inventors, pilots, and thinkers in all of Ghirapur. They're here brooding over what happened at the Fair, and they're just waiting for a spark to get them moving. They're rebellious by nature, but we need an actual rebellion." Chandra nodded. "So, what, you're gonna give a little speech? Rile 'em up a bit? Sounds like a plan." Pia smiled. "Actually, they've heard it all before from me. Renegade Prime and all that. They're still on the fence, and they need to hear something different. Chandra, I want you to do it." Chandra opened her mouth, but no sound came out. She closed it, opened it, and tried again. "Mom, no. That's not...The whole 'inspiring oration' thing does not work for me. Really. What would I even say? They don't know me." "You're wrong about that. They do know you. They know what you've already done here for us, and they know where you come from." Pia waved again to the chikara player, who wrapped up his song, gave a small bow to small applause, and left the stage. "Just tell them what you feel. They already have enough reasons. They need someone to fan the flame." "Yeah, but..." Chandra stopped as she saw the faces of everyone in the club turn to her. Some hopeful, some despondent, some angry, some blank. But almost all of them smiled, just a bit, as they recognized her. "Yeah. Fan the flames. Doing it," she muttered to herself as she stepped cautiously up onto the low stage. "Hi. I'm, well, I guess you know who I am. <NAME>. Pia's daughter." A pause. "Um...Kiran's daughter." The words almost didn't come, but she took another breath when she heard the murmurs and saw the nods of the crowd before her. "Some of you probably knew him." More nodding. "Some of you...I bet some of you maybe knew him better than I ever got to. And you know what? That's not all right! That #emph[you] got to know my dad, and I #emph[didn't] . That you got to work with him, talk to him, laugh with him, and I didn't. They took him away from me. From my mom. And when she decided to fight back, you all just...you just #emph[let] her. They took from her, so of course she'd fight. But you? Not yet. You let her fight alone, because they hadn't taken #emph[enough] ." The crowd got a little louder. Some of them seemed offended, but none rose to leave. Chandra continued. "Well, today they took the rest. All your work, all your efforts, all your tools, everything. They took everything because that's what they do. And you're still sitting in here eating and drinking and complaining and not #emph[doing] anything. What did they take from you? What else do they #emph[have] to take?" The words tumbled to a halt. She glared out at a mirror-sea of eyes and goggle lenses, faces scowling or impassive. "...Forget it," she muttered. "I should go." People rose from their seats, arguing. Chandra stomped off the stage. "I'm sorry, mom. This was a bad idea. I..." Pia smiled, and put a hand on her daughter's shoulder. "Shh. Just wait." A furious young woman stalked up to Chandra, jabbing her finger into the air. "Yeah, sorry about your dad, but what are we supposed to do? They took my ship. The one thing I could have fought back with, I don't have it anymore. You want me to fight? #emph[How?] " Her fists clenched. "#emph[I] —!" Pia placed a stilling hand on the small of her back. She clamped her jaw shut in a clack of teeth, and felt the hairs rising at the nape of her neck. The crowd grumbled its support for the woman. "They took all my tools. Stripped my whole workshop," offered an elderly dwarf. "Three years I spent working on my generator! And now they took it, all my blueprints, all my prototypes! I've got nothing!" Patrons took to their feet, arguing amongst themselves, venting their complaints. The spark had caught quickly, and within minutes; the club threatened to become a riot, spilling out into the streets. The patrons had largely forgotten about Chandra, who sidled back to her mother, looking a bit hesitant. "So...now what?" "Well, now we..." Pia trailed off. "Oh. This was not part of the plan." An extravagantly dressed aetherborn flanked by a pair of armed bodyguards glided into the room from a back alcove. They waved their hand and almost immediately the crowd calmed, their anger doused with a chill of fear. The aetherborn spoke quietly, almost at a whisper. "Friends, please. Such a display. You know as well as I do that this establishment is pledged to peace and prosperity. Normally, I would instruct the troublemakers to leave." They turned to Pia, and the light of their eyes dimmed momentarily. "However. I was not unmoved by your complaints. Some of them might have merit. And I believe I can offer amelioration. Please, accompany me." They gestured for Pia, Chandra, and a few other patrons to follow them into a back room. At the same time, guards stepped in front of the front door, their hands going to their weapons—not drawing them yet, but the statement was made. Chandra looked at Pia, wordlessly asking whether it was time to leave...dramatically. Pia shook her head. Almost sheepishly, Chandra and the others followed the aetherborn into the back office. One of the bodyguards manipulated a switch hidden in the office's ornate molding, and a narrow door swung open, revealing a tunnel and a descending set of stairs. The aetherborn went first, offering no further explanation. The tunnel was narrow, but well-lit by small aether-lamps; rather than the damp, musty air one might expect from an underground passage, this one was warm, with the scents of half a dozen different styles of cuisine mingling together. "I'll regret asking, I'm sure, but where are you taking us?" The pilot fidgeted with her bracers, eyeing the narrow walls with some suspicion. "You haven't guessed? We're going to have a conversation with the most secure individual in Ghirapur, in the most secure location. And we are going to come to a resolution that will preclude further disruption." "You're taking us to Gonti." It wasn't quite a question. Chandra froze. "#emph[What?] Whoa, no. That's not happening. Gonti sold us out once already. We're leaving." She raised glowing fists. "I'll make my own exit if I need to." The aetherborn turned their head to the side quizzically. "Pyromancy in a narrow, flammable hallway? It's not so desperate as that. Besides, we're here. You can take your objections up with Gonti directly." They pressed open a door, revealing an opulent office. A single aetherborn sat at the head of a long table, fingers arched before them. "You took longer than expected. Time is of great value to us. Sit." Some of the group moved, but Chandra didn't cross the threshold. "You betrayed us to the Consulate. Why should we listen to a thing you have to say?" "Aether above, my friend! Thank you. It's so rare that I get to correct a human for shortsightedness. I pushed you to act. I took cautious and meticulous planning off the table. What remained was decisiveness. And here you are. Prepared to act decisively. Won't you please sit?" Gonti gestured to an open chair; Pia was already sitting down next to it. "Let me see if I understand," continued Gonti, tenting their fingers. "You have no tools. You have no ships. You have no aether. Everything that could serve as a potential weapon against the Consulate has been seized." Gonti gestured behind them, and a guard opened a wide door, revealing a glittering storeroom. "Fortuitously, I have some small experience at keeping the hands of the Consulate away from my valuables." #figure(image("004_Revolution Begins/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Gonti stood and bowed graciously. "As Ghirapur's single largest collector of the exceptional, I believe I have what you'll need for your little insurrection." They nodded to Pia. "I offer it in the spirit of...public service." "Don't be cute," Chandra said. "What's your price?" Gonti's eyes glittered like stars in winter. "I expect that will depend on how useful we prove to one another. Would you not agree?" #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("004_Revolution Begins/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Sram chewed pensively on a tiny set of fine-detail pliers as he looked out the slanted windows of the Aether Hub's control room. The gantries and catwalks beneath him were lit by the glowing lines of aether tubes criss-crossing the facility. An elf had once described the Aether Hub to him as Ghirapur's beating heart. Melodramatic, but accurate enough as a metaphor. As he watched, one of the glowing blue tubes flickered and dimmed. "Pressure drain in junction twelve," said one of Sram's edificers. The engineer's tone was calm, but the control room was abuzz with nervous activity. That was the fourth junction that had "malfunctioned" this evening and the second that Sram had witnessed personally. "Reroute to thirteen and nine," said Sram. "No repair order just yet." The maintenance teams sent to fix the first two malfunctions had found nothing out of the ordinary, and a Consulate escort had knocked on Sram's door an hour ago to tell him that the Hub was suffering some kind of problem and they needed him—the Hub's chief architect—to figure it out. So here he was, chewing on his pliers, hunting for signs of breakdown or sabotage, instead of drinking a mug of warm turmeric milk and getting ready for bed. Allocation was supposed to be #emph[boring] . The operators of the Hub directed the city's aether supply where it was needed. Consulate facilities had priority, then the various neighborhoods according to their need. Ideally, aether was distributed equitably and everyone was happy. When construction of the Inventors' Fairgrounds had begun, the portions allotted to "under-utilized neighborhoods" were reduced per Consulate decree, and the muttering—Sram's and the citizens'—had begun. But it was just an emergency measure, he assured himself. Just temporary, surely. Since the crackdown, "emergency" allocation had become standard practice. Worse—it had become #emph[political] . Neighborhoods received aether, or didn't, at central Consulate direction, and all of them were getting less than normal. Instead, the edificers at the Hub had been ordered to increase supply to Consulate facilities. "Senior Edificer," said his assistant Rajni, behind him. "Hhrm?" he said. "Consul Kambal is here to see you," said Rajni. They hadn't hauled a Consul out of bed to deal with malfunctions. This was something else. Sram stopped chewing, considered, and left the pliers in his mouth as he turned. There was Kambal—#emph[Consul ] Kambal—with his shrewd eyes and his hovering attendants. Thick scents of camphor and sandalwood attar flooded the room; the man must have soaked his coat in it. The Consul, on the short side for a human, still loomed over Sram, and took evident pleasure in doing so. #figure(image("004_Revolution Begins/05.jpg", width: 100%), caption: [Kambal, Consul of Allocation | Art by Vincent Proce], supplement: none, numbering: none) "Comful," said Sram, around the pliers. Kambal's mustache twitched gratifyingly. Sram's superiors had always said that chewing on things while he thought was his worst habit: unprofessional, unhygienic, and boorish, showing disrespect for both his station and his tools. Now Sram was senior edificer, and most of those former superiors were either happily retired or still tinkering away in mid-level technical jobs. Several of them now reported to him. Kambal, the Consul of Allocation, was the only one of those superiors who still gave Sram orders. Sram's distaste for the man was matched only by Kambal's obvious disdain for Sram. "Senior Edificer," said Kambal. "I wasn't expecting to find you working the night shift." Sram took the pliers out of his mouth. "Malfunctions," he said. "I wouldn't expect the Consul of Allocation to come all the way out here to talk with the night shift supervisor, if you'll pardon me for saying so." "It's an urgent matter," said Kambal. "Just as well you're here to discuss it." He gestured to the interior wall of the control room, where an aether-flow diagram showed supply to various parts of the city. The neighborhoods of Ghirapur were dim or dark. Consulate facilities glowed. "Earlier today," said Kambal, "this facility received a supply requisition from the Spire. It was ignored." "I didn't ignore it," said Sram. "I read it very carefully and concluded that it had to be an error. I returned a query. As soon as I get the correct order, I can—" "There was no error, Senior Edificer," said Kambal. "The Grand Consul signed the order himself." Sram couldn't keep himself from snorting. "With respect, Consul, did you actually read the request? It was for a constant flow, indefinitely, at a rate that would drain the city's reservoirs in under a week. It was a mistake." "No, Senior Edificer. It was an order." In Sram's experience, the two were hardly mutually exclusive. "Consul," he said. "We'd have to cut the flow to most of the city. Even other official facilities. I don't have the authority—" "I defer to your expertise in making the necessary adjustments," said Kambal. "Authorization granted." So the slimy bastard had come down here to bully one of Sram's subordinates into obeying an outrageous order. "Kambal, #emph[no] . I can't do this. It's dereliction." "You have your orders, Senior Edificer," said Kambal. "Carry them out, or someone else will." "In writing," said Sram. "I want this in writing. With your signature." Kambal glared at him for an interminable moment, silent, his mustache twitching. The control room shook. "What—" "Explosion at junction nine!" said an edificer. "Damn!" said Sram. He turned back to the window. A dazzling spray of blue lit up the night, then dissipated. "Report!" The edificers chattered technical details at him about pressure spikes, routing plans, and the extent of the damage. "Sram, what is happening?" demanded Kambal. "You're leaving," said Sram. "Now." Kambal's eyes went wide. "We'll discuss the supply issue later," he said. "In the meantime, defend this facility." Obviously. The Consul whirled and vanished up the stairs with his attendants—no doubt to an airship on the roof. Good. The room shook again, and this time the blue flash of the explosion lit the whole room. That one was closer. Twenty-three? "Explosion at twenty-three!" #emph[Still got it] , thought Sram. The control room was louder now. Alarms sounded. Edificers dispatched repair teams and coordinated flow reroutes. Security teams reported multiple incursions. Sram stuck the pliers back in his mouth and listened. He tried to see the shape of the attack. Nine and twenty-three. Not vital. Certainly not irreparable, even given the size of the blasts. The renegades were off to a bad start if they were trying to disrupt the Hub's operations. #emph[If] . Nine and twenty-three were lousy choices to sabotage the Hub. That made them great places to blow holes in the walls without damaging anything vital. "Shut it down," he said, around the pliers. "Full lockdown." "Full lockdown," came the acknowledgment. Maybe this was a siphon raid, and the explosions were meant to draw off the facility's guards while siphoners made off with as much aether as they could drain. If so, they'd underestimated how easily the edificers could cut off most of the facility. Sram turned to Kailash, a fellow dwarf who commanded the security forces that guarded the building. He took the pliers out of his mouth. "Commander, those explosions may have breached our defenses." "Understood," she said. One of the edificers, a vedalken with close-cropped hair, turned away from her station. "Lockdown's not responding," she said. "The feeds are still open." "Is that even possible?" asked another edificer, a young human man barely out of training. Sram closed his eyes and saw the Hub's blueprints. Sometimes he dreamed of them. "Yes," he said. "If someone jammed them open." "How? Aren't the shutoffs #emph[inside] the pipes?" asked the young man. The kids fresh off training knew the blueprints almost as well as Sram did. But they didn't know the job. "How long can an aetherborn hold their breath?" asked Sram. "They don't brea—" "Exactly," said Sram. Once, years ago, he'd caught an aetherborn #emph[living] in the aether pipes. He had to admire their tenacity. "Kill the pumps. Now!" That was a more drastic measure. It would take hours to start them back up. But drastic measures now seemed justified. Edificers barked acknowledgments. The subtle, omnipresent vibration of the pumps faded away. But there were other sounds, metallic squeals and low-frequency pulses. Fighting? "Commander, what's our security status?" "They're inside," said Kailash. "Can't tell you much more than that. They've got something out there snatching our relay thopters out of the sky. We're relying on runners." His people and Kailash's gave a steady stream of reports, talking over each other and the sounds of battle. "They've got some kind of pulse weapon—" "Shutdown confirmed, rerouting—" "—our own automatons turning against us—" "Security doors aren't responding!" "—gear we've never seen before." "—didn't look like she had a flamethrower, but there was fire—" "—crawling out of the pipes—" "Maulfists! Brace the doors!" Sram stared out the window. He could make out activity on the southern platform, some kind of mechanism being set up. There was a flash, and a muffled #emph[thump] , #emph[thump] — He ducked just as two grappling claws the size of ballista bolts smashed through the control room window in a spray of glass. His edificers took cover. The claw's cable pulled it back, and three articulated digits dug into the wall. There was a quick, high-pitched whine as it bolted itself on. A few feet away, the second claw did the same. Sram grabbed the claw next to him, pliers at the ready to try to disassemble the thing. It delivered a stinging shock, enough to numb his fingers and dissuade him from further tampering. There was a loud whirring sound. Sram risked a peek out the window. Looming out of the darkness, a little gondola zipped toward him, suspended between the two cables. In it were a dozen renegades brandishing weapons and tools Sram couldn't even identify. The control room's security doors gave way to the maulfist attack, and more renegades poured through, backed up by suborned Consulate security automatons. Kailash and her troops went down fighting. The gondola slammed into the wall of the control room, and the renegades poured in. Soon there were at least two weapons trained on every member of Sram's edificer crew, and three on him. Many of the renegades knew him. Knew that he was the one who'd cut off the aether flow to their neighborhoods during the current crisis. He did not begrudge them their anger. One of the renegades from the gondola stepped forward and removed her goggles—an older woman with an air of authority. Sram recognized her from the arena. He stood up straight. #figure(image("004_Revolution Begins/06.jpg", width: 100%), caption: [<NAME> | Art by <NAME>], supplement: none, numbering: none) "<NAME>," he said. "So you're in charge of all this?" She laughed at him, though not maliciously. "Nobody's in charge," she said. "But you have something that's ours. We're here to take it back." He surveyed the wrecked control room, packed with renegades. "Nalaar," he said, more quietly. "My people aren't soldiers. And I'm worried some of yours may resent us for...recent allocations." "They do," she said. "You'll be treated well. You have my word." "Then I yield," said Sram. "The Aether Hub is yours." #emph[For now] . #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) What was a reasonable amount of time to wrest control of an Aether Hub from Consulate forces? Rashmi wasn't sure, but the renegade strike team had been gone for hours; it seemed they should return to the warehouse at any moment, victorious or not. Either way, that left little time for Rashmi and Mitul to complete the skyship. Lighting in the cavernous warehouse was dim, in part to conserve aether—the renegades would soon run out unless they could secure the Hub—and in part to avoid drawing the attention of Consulate sky patrols. In the middle of the vast, shadowy space sat the massive skyship, nearly as immense as the warehouse itself: the#emph[ Tezzeret's Ruin] . #figure(image("004_Revolution Begins/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) The skyship was the next step in the renegade's plan: secure the Hub, use the aether to power the ship, and fly #emph[Tezzeret's Ruin] in an attack on the Consulate's Spire. The renegades were going to bring that monstrous man down, and they would destroy the Planar Bridge along with him. The Planar Bridge, that's what #emph[they] —the Planeswalkers, as Saheeli had introduced them to Rashmi—were calling Rashmi's matter transporter. They used the term like a curse word; whenever it was uttered, a ripple of anxiety spread through the room. They whispered to each other about the atrocities and havoc Tezzeret could wreak with Rashmi's invention in his possession. Each scenario was more dire than the last. That's why she was here. If the skyship she helped build for them led to the destruction of the Planar Bridge, she would no longer be responsible for the threat her creation might pose to all the worlds she had seen out there. And then she would be done. She would put away her tools and stop inventing. This was the last thing she would make that would be used for harm. In the soft glow of the lamp that Mitul held over the skyship's engine hatch, Rashmi twisted her wrench to secure the condenser mount. Each rotation twisted the feeling of finality further into her gut. Three more bolts. "...If you are not interested in pursuing that line of aetherlogical research, I have also been working on another proposal. This one is more theory based." Mitul's voice prodded its way into Rashmi's consciousness. He had been talking this whole time, going on about the next line of research he hoped they would pursue together. The Planeswalkers had made Rashmi and Mitul promise that they would abandon their matter transport research. Ever since he had heard, Mitul had thrown himself into finding a new project. "The notion of the progression of aether through time is vastly unexplored. I believe we could make great strides in that field. Don't you agree?" "Perhaps we could," Rashmi muttered noncommittally. She looked up into her friend's earnest eyes. Leaving him would be the hardest part of all of this. But if she wanted to find a new path, one that didn't lead to hurt and destruction, she had no choice but to leave. "Do you have a nice set of wrenches, Mitul?" "What size do you need?" He turned to the nearby workbench, as always, ready to help. "An angled grip perhaps?" "No, not for me. I mean, do you have your own set?" "Oh." Mitul cocked his head, confused. "I use yours." He cleared his throat. "I hope that is all right." "Of course it is," Rashmi said quickly. "You should keep using them." She would give him her wrenches. She'd give him all her tools. There were no other hands she would rather imagine wielding them once she was gone. One more bolt. Rashmi reached for the far corner of the mount, but her hand began to shake. She tried to steady herself, now was not the time. But it wasn't her hand that was trembling; there was a quaking coming from the floor beneath her feet. It intensified until it felt like a migrating flock of giants was about to burst through the side of the warehouse. The renegades. They were back. "The Hub is ours!" The cry rang through the rafters. With a deep groan, the immense doors were rolled open. "They have done it." Mitul's eyes widened with reverence. He'd taken to the renegade movement with passion and resolve that Rashmi admired. Rashmi nodded and forced a smile. "Renegades!" <NAME>'s voice sounded from the other side of the skyship. "Renegades, gather round." Mitul looked to Rashmi, entreating. "Go," she said. "I'll finish up here and I'll be right behind you." Mitul hesitated. "We've won the day!" Pia cried to more cheers. Rashmi could see the spark in Mitul's eyes. He wanted to be out there. "Go," she encouraged. This would be easier than saying goodbye anyway. She would slip out before they could call her up to the front. Saheeli had asked her to be part of the dedication ceremony, but that was the last thing Rashmi wanted. It was time for her to go. "I will save you a place." Mitul smiled and hurried around the tail of the skyship#emph[. ] Rashmi lifted her hand to silently wave goodbye. Across the warehouse, Pia continued, "Today, we faced those who would oppress us, and we showed them that we are stronger than they are." A roar of triumph. "But our fight isn't over. It has only just begun. What we have gained at the Hub will help us with what we have to do next." "Bring down Tezzeret!" Someone cried. More voices echoed the sentiment as, with one last turn of the wrench Rashmi finished her work. It felt very final. "Tezzeret doesn't belong here," Pia was saying to the renegades. "He's a liar and a cheat who manipulated his way into power. He's a tyrant who cannot be allowed to rule. It's up to us to take him down!" The response was deafening. "And you will," Rashmi whispered. She secured the engine hatch; #emph[Tezzeret's Ruin] was complete. She used the corner of her skirts to wipe the oil and dust off the golden filigree. "Good luck." With a final squeeze she turned to go, but she stopped short; something on the hatch caught her eye. She paused, leaning in closer, squinting to make it out. There was an engraving in the metal, visible now only after she had cleaned away the layer of grime. Two letters, carefully carved by an artistic hand: K.N. Rashmi's breath hitched. <NAME>. It had to be. Pia's late partner, and the inventor who had designed this ship so long ago. Rashmi ran her fingers over the engraving, gently cleaning away the rest of the oil and dirt, as though her tenderness could make up for the fate of his creation. #emph[I'm sorry for what has become of this] . She pressed her fingers into the letters. #emph[I know what it's like to see something you've made used to cause harm.] A wave of aetheric energy welled up from the filigree, and a bright blue swirling glow consumed Rashmi's vision. Her heart leapt. She knew this feeling. It was the most wonderful feeling. She had felt it only once before, when examining Avaati Vya's prototype aether refiner at the Museum of Invention. The display had said "Don't touch," but Rashmi couldn't help herself. She had run her hands over the metalwork, and the next thing she knew she was awash in the spirit of the inventor inside. Projects of the heart were like this; inventors who poured their souls into their work left a little bit of themselves in their creations. Kiran's were the hands that had first shaped this metal, his was the mind that had conceived of this design, and now his essence was flowing out through what he had made. Rashmi was inundated by his spirit. His love of flying. Soaring high above the city. Nothing to limit him. His passion for creating, for making something that had never been made before. His eagerness to push boundaries and take risks. And then something more, something she wasn't expecting. Kiran had a fervent desire to defend the freedom to create. To stand up to those who tried to limit innovation. To protect the spirit of invention he held so dear. It was as though she had stopped breathing, as though her heart had stopped beating, and now as feeling rushed back through her, Rashmi staggered away from the skyship. Afterimages of swirling blue danced behind her eyes, sending her off balance. A pair of arms caught her. "They're calling for you." It was Mitul. "They want you up on the platform." Rashmi tried to find her voice to protest, but her senses were still swimming and her mind reeling. Mitul guided her around the bow of the ship and urged her to walk up the steps to the platform. Pia extended her hand in welcome. "And here she is, the lead aether-engineer, Rashmi, to dedicate our skyship." As a round of cheers rang out, Pia put her arm around Rashmi's shoulder. "Rashmi has been through more than most of us can imagine," Pia said. "She was held captive by Tezzeret himself, and she fought her way out." That elicited cries of support. "I'd say she's earned the right to dedicate this ship to his ruin." Pia handed Rashmi a glass bottle of glowing aether. "Do us the honor. Let's end that monster!" Cries of "End him!" and "Down with the tyrant!" and "#emph[Tezzeret's Ruin] !" drew Rashmi's eyes out to the crowd. There were so many people, a sea of faces, and they were all looking at her. Rashmi stared back out at them, the renegades. But in that moment, that's not what she saw. She saw inventors. Every single one of them was here because they believed in the spirit of invention. The same spirit she had felt through Kiran. It still pulsed within her, passionate and bright. There was more to this skyship, more to this revolution, than she had allowed herself to see. She'd let her fear win. She'd convinced herself that all of this was only about destruction. She couldn't have been more wrong. "Go on," Pia prompted. Rashmi inched forward, clutching the bottle of aether more tightly so it wouldn't slip from her sweating fingers. "Hello." Her voice cracked, sounding small in the cold, dry vastness. She tried again, louder. "Hi." No one responded. She cleared her throat. "I'm going to dedicate this ship, like Pia asked. But I think it needs a new name first." People shifted uncomfortably, murmuring to each other. Pia caught Rashmi's eye, smiling too wide, entreating her with her eyes to do the thing she was supposed to do. This #emph[was] the thing she was supposed to do. "#emph[Tezzeret's Ruin] ," Rashmi said. "It has a nice ring to it. For me especially. Trust me." There were a few dry chuckles. "And it is accurate. It's what we have to do, end that monster's reign. And we'll do it. We will." There was a stray shout. "But in the end, that's not why any of us are here, not fully anyway. We're not here to fight, to bring down, or to destroy. We will do that because we must. Because it is necessary if we want to protect. But protecting is what we truly want to do. We're here to save our city. To defend its spirit—the spirit of invention. That's what's at stake. We're inventors. We create. We build. We add to this world; we don't take away." Scattered cries of agreement, echoed Rashmi's words. "Deep down we all know who we are. But if you need reminding, think of the man who designed this ship: the great inventor <NAME>." All at once every eye in the room turned to the woman standing next to Rashmi. Rashmi felt Pia straighten at her side. "No one embodied the spirit of invention more than Kiran. He lived to create. And he believed in the right to the freedom of expression for all. He built this ship not to destroy, but to discover. And it is my greatest hope that when this is over, when we have taken down the monster, when we have won the day, that Kiran's ship will fly for hope. That it will carry his spirit, our spirit of invention to every corner of the world. So I dedicate this skyship the #emph[Heart of Kiran,] " Rashmi raised the bottle of aether over her head. "May we never forget who we are." She broke the bottle on the bow of the skyship, and the mystical blue substance blossomed across the gleaming golden metal. Cheers boomed, and tears pressed against the corners of Rashmi's eyes. Pia took her by the shoulders. "Thank you. Thank you so very much." She clasped Rashmi's hand and raised it to uproarious applause. "For the spirit of invention!" a voice called from the crowd. Rashmi recognized the voice; she found Mitul, his fist raised in the air. Their eyes met, and she smiled at her friend, knowing that she wouldn't have to say goodbye. They were inventors, researchers in the burgeoning field of temporal aether abstraction, and they wouldn't let Tezzeret take that away from them.
https://github.com/Fabioni/Typst-TUM-Thesis-Template
https://raw.githubusercontent.com/Fabioni/Typst-TUM-Thesis-Template/main/template.typ
typst
MIT No Attribution
#import "cover.typ": * #import "titlepage.typ": * #import "disclaimer.typ": * #import "acknowledgement.typ": * #import "abstract.typ": * #let tum-exzellenz-thesis( degree: "The degree", program: "The Program", supervisor: "Your Supervisor", advisors: ("The first advisor", "The second advisor"), author: "<NAME>", startDate: "The Startdate", titleEnglish: "English Title", titleGerman: "German Title", abstract_en: [English Abstract], abstract_de: [German Abstract], acknowledgements: [The acknowledgements], submissionDate: "(Handover Date)", showTitleInHeader: true, draft: true, body, ) = { let draft_string = "" if draft{ draft_string = "DRAFT - " } set document(author: author, title: draft_string + titleEnglish) set page( numbering: "1", number-align: center, margin: (left: 25mm, right: 25mm, top: 30mm, bottom: 30mm), header: [ #set text(8pt) #if showTitleInHeader [ #author - #titleEnglish ] #h(1fr) #if draft [ DRAFT ] ], ) set page(numbering: none) set text(font: "New Computer Modern Sans") cover( title: draft_string + titleEnglish, degree: degree, program: program, author: author, ) titlepage( title: draft_string + titleEnglish, titleGerman: titleGerman, degree: degree, program: program, supervisor: supervisor, advisors: advisors, author: author, startDate: startDate, submissionDate: draft_string + submissionDate ) disclaimer( title: titleEnglish, degree: degree, author: author, submissionDate: submissionDate ) acknowledgement(acknowledgements) abstract(lang: "en")[#abstract_en] abstract(lang: "de")[#abstract_de] counter(page).update(1) body }
https://github.com/giZoes/justsit-thesis-typst-template
https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/utils/bilingual-bibliography.typ
typst
MIT License
// Authors: csimide, OrangeX4 // Tested only on GB-7714-2015-Numeric #let bilingual-bibliography( bibliography: none, title: "参考文献", full: false, style: "gb-7714-2015-numeric", mapping: (:), ) = { assert(bibliography != none, message: "请传入带有 source 的 bibliography 函数。") // Please fill in the remaining mapping table here mapping = ( //"等": "et al", "卷": "Vol.", "册": "Bk.", // "译": "tran", // "等译": "et al. tran", // 注: 请见下方译者数量判断部分。 ) + mapping let to-string(content) = { if content.has("text") { content.text } else if content.has("children") { content.children.map(to-string).join("") } else if content.has("child") { to-string(content.child) } else if content.has("body") { to-string(content.body) } else if content == [ ] { " " } } show grid.cell.where(x: 1): it => { // 后续的操作是对 string 进行的。 let ittext = to-string(it) // 判断是否为中文文献:去除特定词组后,仍有至少两个连续汉字。 let pureittext = ittext.replace(regex("[等卷册和版本章期页篇译间者(不详)]"), "") if pureittext.find(regex("\p{sc=Hani}{2,}")) != none { ittext } else { // 若不是中文文献,进行替换 // 第xxx卷、第xxx册的情况:变为 Vol. XXX 或 Bk. XXX。 let reptext = ittext reptext = reptext.replace( regex("(第\s?)?\d+\s?[卷册]"), itt => { if itt.text.contains("卷") { "Vol. " } else { "Bk. " } itt.text.find(regex("\d+")) }, ) // 第xxx版/第xxx本的情况:变为 1st ed 格式。 reptext = reptext.replace( regex("(第\s?)?\d+\s?[版本]"), itt => { let num = itt.text.find(regex("\d+")) num if num.clusters().len() == 2 and num.clusters().first() == "1" { "th" } else { ( "1": "st", "2": "nd", "3": "rd", ).at(num.clusters().last(), default: "th") } " ed" }, ) // 译者数量判断:单数时需要用 trans,复数时需要用 tran 。 /* 注: 1. 目前判断译者数量的方法非常草率,有逗号就是多个作者。但是在部分 GB/T 7714-2015 方言中,姓名中可以含有逗号。 2. 在 GB/T 7714-2015 原文中有 `等译`(P15 10.1.3 小节 示例 1-[1]),但未给出相应的英文缩写翻译。 3. CSL 社区库内的 GB/T 7714-2015 会使用 `等, 译` 和 `et al., tran` 的写法。为了保证统一性,这里会译作不带逗号的版本,即 `et al. tran` 如果工作不正常,可以考虑换为简单关键词替换,即注释这段情况,取消 13 行 mapping 内 `译` 条目的注释。 */ reptext = reptext.replace( regex("\].+?译"), itt => { // 我想让上面这一行匹配变成非贪婪的,但加问号后没啥效果? if itt.text.replace(regex(",\s?译"), "").find(",") != none { itt.text.replace(regex(",?\s?译"), " tran") } else { itt.text.replace(regex(",?\s?译"), " trans") } }, ) // `等` 特殊处理:`等`后方接内容也需要译作 `et al.`,如 `等译` 需要翻译为 `et al. trans` reptext = reptext.replace( regex("等."), itt => { "et al." // 如果原文就是 `等.`,则仅需简单替换,不需要额外处理 // 如果原文 `等` 后没有跟随英文标点,则需要补充一个空格 if not itt.text.last() in (".", ",", ";", ":", "[", "]", "/", "\\", "<", ">", "?", "(", ")", " ", "\"", "'") { " " } // 原文有英文句号时不需要重复句号,否则需要将匹配到的最后一个字符吐回来 if not itt.text.last() == "." { itt.text.last() } }, ) // 其他情况:直接替换 reptext = reptext.replace( regex("\p{sc=Hani}+"), itt => { mapping.at(itt.text, default: itt.text) // 注意:若替换功能工作良好,应该不会出现 `default` 情形 }, ) reptext } } set text(lang: "zh") bibliography( title: title, full: full, style: style, ) }
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/feebf7-2023_fall_TA/lectures/lecture_2.typ
typst
#import "../utils.typ": * = Lecture 2 & 3 ```plain Time: Week 2, 9.13 Wed & 9.15 Fri ``` == 数列极限 刻画「收敛」的方式: #definintion(name: "数列极限")[ $epsilon - N$语言: $ forall epsilon > 0, exists N, forall n > N, abs(a_n - a) < epsilon quad => quad lim_(n -> infinity) a_n = a $ ] 记号: $ cases( lim a_n = a, lim_(n -> infinity) a_n = a, a_n -> a quad (n -> infinity), ) $ === 例子 $ alpha > 0, quad lim 1 / n^alpha = 0 $ $ abs(q) < 1, quad lim q^n = 0 $ $ lim (2^n) / (n!) = 0 $ == 数列极限的性质 === 唯一性 #statement[ 若${a_n}$ 收敛, 则 ${a_n}$ 的极限唯一. 这说明数列的极限是「良定义」的. ] #proof[ 反证: $ cases( a_n -> a, a_n -> b ), quad a!=b $ 取 $epsilon = abs(a-b)/2$, 根据极限的定义, 存在 $N_1, N_2$, 使得 $ forall n > N_1, abs(a_n - a) < epsilon \ forall n > N_2, abs(a_n - b) < epsilon $ 则当$n > max{N_1, N_2}$ $ abs(a-b) = abs(a-a_n + a_n - b) <= abs(a-a_n) + abs(a_n - b) < 2*epsilon = abs(a-b) $ 矛盾. ] === 有界性 #statement[ 若${a_n}$ 收敛, 则 ${a_n}$ 有界. 即存在一个正数$M$, 使得 $forall n, quad abs(a_n) < M$. ] #proof[ 取 $epsilon = 1$, 根据极限的定义, 存在 $N$, 使得 $ forall n > N, abs(a_n - a) < 1 $ 则当$n > N$ $ abs(a_n) < 1 + abs(a) $ 取 $M = max{abs(a_1), abs(a_2), ..., abs(a_N), 1+abs(a)}$, 则 $forall n, quad abs(a_n) < M$. #caption[ 通常情况下, 不能直接取得无穷多个数的最大值, $a_n = n$ 就不存在最大值, 但是他前$N$项可以取最大值. 在一般的情况下, 正如上面证明展示的那样, 拆成有限+无限两部分, 分别控制大小, 可以得到有界的结论. ] ] === 保序性 #caption[ 「充分大」: 等于在说,存在一个$N$, 使得 $n>N$ 时,某个结论成立. 这个概念的引入, 等于说刨除了前有限项的影响, 只讨论后面无穷多项的性质. ] #statement[ - 若 $exists l, quad l<a$, 那么当$n$充分大时, 有 $l < a_n$ 特别的, 取$l=0$, 上述结论可以改写为: - 若 $exists l, quad l<0$, 那么当$n$充分大时, 有 $0 < a_n$ ] #proof[ 讨论$l<a$: 取 $epsilon = a-l$, 根据极限的定义, 存在 $N$, 使得 $ forall n > N, abs(a_n - a) < a-l quad => quad a_n > l $ ] 通过上面的命题还可推导出一个更为常用的结论: #statement[ 若$exists l$,对充分大的$n$, 有 $l <= a_n$, 则 $l <= a$ ] #caption[ 反证, 证明略. 注意, 如果将上面不等式中两个$<=$均替换为严格的$<$, 则结论并不成立. 给出一个反例: $a_n = 1/n > 0$, 但是$a=0$. ] === 四则运算 #statement[ ${a_n}, {b_n}$是两个收敛数列, 则 - $lim(a_n plus.minus b_n) = lim a_n plus.minus lim b_n$ - $lim(a_n dot b_n) = lim a_n dot lim b_n$ - $lim b_n !=0 quad => lim(a_n/b_n) = (lim a_n) / (lim b_n)$ ] === 数列间关系 #statement[ ${a_n}, {b_n}$是两个收敛数列, 则 - $a_n <= b_n$, 则 $lim a_n <= lim b_n$ - 若$lim a_n < lim b_n$, 则当$n$充分大时, $a_n < b_n$ ] #caption[ 可以考虑更简便的代换 $c_n = a_n - b_n$, 使用保序性来说明. ] #statement[ ${b_n}, {c_n}$均收敛到$a$, 且当 $n$ 充分大时存在: $ b_n <= a_n <= c_n $ 则 ${a_n}$ 收敛, 且 $lim a_n = a$ ] #proof[ 首先通过 $lim b_n = lim c_n = a$ 可以得到: $ exists N_1, n>N_1 => abs(b_n - a) < epsilon \ exists N_2, n>N_2 => abs(c_n - a) < epsilon $ 同时, $ exists N_3, forall n>N_3, b_n <= a_n <= c_n $ 取 $N = max{N_1, N_2, N_3}$, 则当$n>N$时,有: $ &a - epsilon < b_n <= a_n <= c_n < a + epsilon \ &=> forall epsilon, exists N, forall n>N, quad abs(a_n - a) < epsilon \ &=> lim a_n = a $ ] #caption[ 上述条件中未假定${a_n}$收敛, 可用作判断收敛的依据. ] === 子列 #definintion(name: "子列")[ 定义${a_n}$的子列是这样一个数列${a_(n_k)}_k$, 其中${n_k}$是一个严格递增的数列. ] #statement[ ${a_n}$收敛, 则${a_n}$的任意子列收敛, 且极限相同. ] #caption[ 注意 - 子列的编号严格递增, 因此 $n_k >= k$ - 如果${a_n}$的一个子列${a_(n_k)}_k$发散, 则${a_n}$也发散 - 如果${a_n}$的一个子列${a_(n_k)}_k$收敛到$a$, ${a_(m_k)}_k$收敛到$b$, 且$a!=b$ 则${a_n}$发散 (Why?) ] #pagebreak() == 一些问题 === 极限不存在 极限的定义: $ lim a_n = a quad <=> quad forall epsilon > 0, exists N, forall n > N, abs(a_n - a) < epsilon $ 则极限不存在的定义: $ lim a_n != a quad <=> quad exists epsilon > 0, forall N, exists n > N, abs(a_n - a) >= epsilon $ #caption[ 一些同学给出了这样的形式: $ lim a_n != a quad <=> quad exists epsilon > 0, forall N, forall n > N, abs(a_n - a) >= epsilon $ <array.limit.wrong.equation> 这个表述是错误的, 我们考虑这个例子: $ a_n = cases( 1/n quad n = 2k+1, 1 quad n = 2k ) $ 这个例子显然不满足@array.limit.wrong.equation 的条件, 但是极限不存在. ] 可以这样理解极限的定义:对于任意的$epsilon$邻域, 邻域会把${a_n}$的取值分成两部分, 如果极限存在, 那么: - 无穷多个点总是落在邻域内 - 邻域外的点至多有限 从这个角度来看, 极限的定义是这样描述的: - 对于任意的$epsilon$邻域, 邻域外的点至多有限 $=> forall epsilon$ - 那么邻域外的点的序号总存在一个上界, 我们称之为$N$ $=> exists N$ - 那么剩下的, 无穷多的点${a_n | n > N}$都应该落在邻域内 $=> forall n>N quad abs(a_n-a)<epsilon$ 而极限不存在的充要条件, 不是「存在一个邻域内只有有限多点」, 而是*「邻域外的点无穷多个」*便可说明, 应当描述为: - 对于任意的$epsilon$邻域, 邻域外总有无穷多个点 $=> exists epsilon$ - 邻域外的点无穷多个, 无法确定最大编号, 我们称之为$N$ $=> forall N$ - 也就是说, 任给一个控制的上界$N$,总有至少一个$n>N$落在邻域外面: $=> exists n>N quad abs(a_n-a)>=epsilon$ #caption[ 从上面的理解方式出发,更容易寿命:「改变数列中有限多项的值不改变收敛性及其极限」 ] === $epsilon$的任意性 很多时候分析就在研究怎样选取$epsilon$.定义中要求$forall epsilon>0$, 这个任取的作用要远比看上去的要大. #caption[ $epsilon$只是无穷小量的一个体现, 因为它是任意的, 所以其他地方定义的 $epsilon$ 经过缩放或者其他变化, 只要满足$epsilon^prime>0$, 就不影响极限定义的成立. $ exists N_(epsilon^prime), forall n>N_(epsilon^prime), quad abs(a_n - a)<epsilon^prime $ ] #pagebreak()
https://github.com/dainbow/MatGos
https://raw.githubusercontent.com/dainbow/MatGos/master/themes/35.typ
typst
#import "../conf.typ": * = Дифференцируемость функции комплексного переменного. Условия Коши-Римана. Интегральная теорема Коши. == Дифференцируемость функции комплексного переменного. Условия Коши-Римана #note[ В ТФКП используются следующие станартные оборзначения $z$ - комплексная переменная $z = x + i y : x,y in RR$ $f(z)$ - исследуемая функция $f(x+i y) = u(x,y) +i v(x, y) \: u,v in RR^2->RR$ ] #definition[ Функция $f: B_r (z_0) -> CC$ называется _дифференцируемой_ в $z_0$ если #eq[ $exists A in CC : f(z) = f(z_0) + A(z-z_0) + o(z-z_0)\, |z-z_0| -> 0$ ] ] #theorem[ $f: B_r (z_0) -> CC$ дифференцируема тогда и только тогда когда + $u(x,y), v(x,y)$ дифференцируемы в $(x_0, y_0)$ + Выполняются _условия Коши-Римана_: $cases( (partial u) / (partial x) = (partial v) / (partial y), (partial u) / (partial y) = -(partial v) / (partial x), )$ При этом $f'(z_0) = (partial u)/(partial x) (x_0, y_0) + i (partial v) /(partial x) (x_0, y_0)$ ] #proof[ ($==>$) Пусть $f$ дифференцируема. Тогда $Delta f = A Delta z + alpha(Delta z) = A Delta z + alpha_0(Delta x, Delta y) + i alpha_1(Delta x, Delta y)$ Обозначим $A = a + i b$ и распишем $Delta f$ по координатно. #eq[$ cases( Delta u = a Delta x - b Delta y + alpha_0(Delta x, Delta y), Delta v = b Delta x + a Delta y + alpha_1(Delta x, Delta y), ) $] Из того, что $alpha(Delta z) = o(Delta z)$ следует $alpha_1, alpha_2$ тожe $o(Delta x, Delta y)$ Отсюда по определению $u$, $v$ дифференцируемы. Причем $(partial u) / (partial x) = (partial v) / (partial y) = a, -(partial u) / (partial y) = (partial v) / (partial x) = b$ ($<==$) Пусть $u, v$ дифференцируемы и выполняются УКР, тогда #eq[$ Delta f = Delta u + i Delta v &= (partial u) / (partial x) Delta x + (partial u) / (partial y) Delta y + alpha_0(Delta x, Delta y) + i ((partial v) / (partial x) Delta x + (partial v) / (partial y) Delta y + alpha_1(Delta x, Delta y)) \ &= (partial u) / (partial x) Delta x - (partial v) / (partial x) Delta y + i ((partial u) / (partial x) + (partial v) / (partial x)) alpha_0(Delta x, Delta y) + i alpha_1(Delta x, Delta y) \ &= ((partial u) / (partial x) + i (partial v) / (partial x)) (Delta x + i Delta y) + alpha_0(Delta x, Delta y) + i alpha_1(Delta x, Delta y) $] Что и означает дифференцируемость. ] == Интегральная теорема Коши #lemma[ Пусть D область f голоморфна в ней. Тогда + Если $f$ полный диференциал $=> space forall gamma$ кусочно гладкая замкнутая $integral_gamma f d z = 0$ + Если интеграл по любой замкнутой ломанной 0 $=> f$ - полный диференциал ] #theorem( "<NAME>", )[ Пусть $D$ область, $f$ голоморфна в ней. Тогда #eq[ $forall "треугольника" Delta: overline(Delta) in D space integral_(partial Delta) f d z = 0$ ] ] #proof[ Обозначим $I = integral_(partial Delta) f$. Разобъем каждую сторону треугольника пополам, и получим 4 треугольника: $Delta_1, Delta_2, Delta_3, Delta_4$. Тогда $I = (integral_(partial Delta_1) + integral_(partial Delta_2) +integral_(partial Delta_3) +integral_(partial Delta_4))f d z = I_1 + I_2 + I_3 + I_4$ Тогда найдется треугольник (б.о.о. $Delta_1$), такой что $abs(I_1) >= abs(I / 4)$. Продолжая так делать получим последовательность треугольников $seq(Delta)$. Заметим, что в силу компактности $exists z_0 = sect.big_0^oo overline(Delta_n)$. В силу дифференцируемости #eq[ $forall epsilon > 0 : forall z in O_delta (z_0) : space abs(f(z) - f(z_0) - f'(z_0)(z - z_0)) < epsilon (z-z_0)$ ] Заметим, что $-f(z_0) - f'(z_0)(z - z_0)$ это полный диференциал, тогда #eq[$ integral_(Delta_n) f(z) - f(z_0) - f'(z_0)(z - z_0) d z = integral_(Delta_n) f(z) d z + 0 $] Следовательно для достаточно больших n #eq[$ |I_n| = abs(integral_(Delta_n) f(z) d z) <= integral_(Delta_n) abs(f(z) - f(z_0) - f'(z_0)(z - z_0)) |d z| <= epsilon dot (l / 2^n)^2 $] Где $l$ периметр $Delta$, и соответсвенно $l/2^n$ периметр $Delta_n$. Но по построению $abs(I_n) >= I / 4^n$, следовательно $forall epsilon > 0 space abs(I) < epsilon => I = 0$ ] #lemma[_Усиленная Лемма Гурса_ Следствие предыдущей теоремы верно и в условиях, что $f$ голоморфна в $D without {a}$, непрерывна в $D$ ] #proof[ Картиночки порисовать. ] #theorem("Коши для выпуклой области")[ Пусть $D$ выпуклая область, $f$ голоморфна в ней. Тогда $forall gamma$ - кусочно гладкой замкнутой $integral_gamma f d z = 0$. ] #proof[ Явно предъявим полный дифференциал $F(z) = integral_[a; z] f(zeta) d zeta$. #eq[$ F(z) - F(z_0) = integral_[a; z] f(zeta) d zeta - integral_[a; z_0] f(zeta) d zeta =^"Лемма Гурса" integral_[z_0; z] f(z_0) d z $] Тогда очевидно, что #eq[$ (F(z) - F(z_0)) / (z - z_0) -> f(z_0) $] ] #definition[ Пусть $gamma$ - кусочно гладкая кривая в $D$ - области. Тогда _приращением аргумента функции вдоль кривой_ $Delta_gamma f$ называется $\Im integral_gamma (f'(z) d z) / f(z)$ ] #definition[ Пусть $gamma$ - кусочно гладкая замкнутая кривая в $CC$, $a in C without gamma$. Тогда _индексом $a$ относительно $gamma$_ называется #eq[$J_gamma (a) = (Delta_gamma (z-a)) / (2 pi )$] ] #definition[ Пусть $gamma$ - кусочно гладкая кривая лежит в области $D$. Тогда говорят что $gamma space ~ space 0 space (mod D)$ _гомологично эквивалентна нулю_, если #eq[ $forall a in CC without D :space J_gamma (a) = 0$ ] ] #definition[ Циклом $Gamma$ называется формальная линейная комбинация с целыми коэфициентами кусочно-гладких замкнутых кривых. Все определения и теоремы для кривых тривиально переносятся на циклы. ] #definition[ Пусть $gamma$ кусочно гладкая кривая, $phi$ непрерывна на $gamma$. Тогда интегралом Коши называется #eq[$F_n (z, phi) = integral_gamma phi(xi) / (xi - z)^n d xi $] ] #proposition[Свойства интеграла Коши 1. $F_n$ голоморфна в $CC without gamma$ 2. $F'_n (z, phi) = n F_(n+1)(z, phi)$ ] #lemma( "Общая теорема Коши", )[ Пусть $D$ - область в $CC$, $f$ - голоморфна в $D$ Тогда 1. #eq[$ g(xi, z) = cases((f(xi)-f(z)) / (xi - z) \, xi != z, (f'(z)) \, z = xi)$] непрерывна в $D times D$ 2. Для любой кусочно гладкой $gamma in D$ #eq[$ h(z) = integral_gamma g(xi, z) d xi $] голоморфна в D ] #theorem( "Лиувиля", )[ Пусть $f$ голоморфная в $CC$ и #eq[ $exists M,m,R : forall z, |z| > R: space |f(z)| < M z^m$, ] тогда $f$ полином степени $m$. В частности, если $f$ ограничена, то она константа. ] #theorem( "Интегральная теорема + формула Коши", )[ Пусть $D$ - область в $CC$, $f$ - голоморфна в $D$. Пусть $Gamma$ - цикл в $D$, причем $Gamma space ~ space 0 space (mod D)$, тогда 1. (формула) $forall z in D without Gamma: J_Gamma (z) f(z) 1 / (2 pi i ) = integral_Gamma (f(xi) d xi) / (xi - z)$ 2. (теорема) $ integral_Gamma f(z) d z = 0$ ] #proof[ (Необязательно) Пусть $G = {z in CC without Gamma | J_Gamma (z) = 0}$ оно открытое. Рассмотрим две функции + $ 2 pi i space tilde(h)(z) = integral_Gamma (f(xi) d xi) / (xi - z)$ Она голоморфна в $G$ как интеграл Коши. + $ 2 pi i space h(z) = integral_Gamma ((f(xi)-f(z)) / (xi - z)) d xi$ Она голоморфна в $D$ по 2 пункту общей теоремы Коши Заметим, что $forall z in G sect D : space h(z) = tilde(h)(z) $ так как #eq[$ h(z) - tilde(h)(z) = 1 / (2 pi i) integral_Gamma (f(z)) / (xi - z) d xi = J_Gamma(z) f(z) = 0 $] Из того, что $Gamma space ~ space 0 (mod D) $ следует $CC without D subset G$ Тогда рассмотрим новую функцию: #eq[$ F(z) = cases(h(z)\, z in D, tilde(h)(z), z in CC without D subset G) $] Она голоморфна в каждой из компонент. А так как на границе $h$ и $tilde(h)$ равны, то голоморфна и в $CC$. Заметим, что #eq[$ |tilde(h)(z)| <= 1 / (2 pi) integral_Gamma (max_Gamma |f| |d xi|) / ( \d\i\s\t (z, Gamma)) ->_(\d\i\s\t (z, Gamma) -> infinity) 0 $] А следовательно по теореме Лиувиля $F(z) equiv 0$. Следовательно в $D without Gamma space h(z) = 0$. То есть #eq[$ f(z) / (2 pi i) integral_Gamma (d xi) / (xi - z) = integral_Gamma (f(xi) d xi) / (xi - z) \ f(z) J_Gamma(z) = integral_Gamma (f(xi) d xi) / (xi - z) $] (1 $=>$ 2) Применим 1 к $tilde(f)(z) = (z-a)(f(z))$, где $a in CC without Gamma$ (естественно в области определения f) Тогда #eq[$ 0 = J_Gamma(a) (a - a) f(a) = J_Gamma(a) tilde(f)(a) = integral_Gamma (tilde(f)(xi) d xi) / (xi - a) = integral_Gamma f(xi) d xi $] ]
https://github.com/Jollywatt/typst-fletcher
https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/label-fill/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 1em) #import "/src/exports.typ" as fletcher: diagram, node, edge #diagram( crossing-fill: gray, edge((0,0), (1,1), "->", [no fill], label-side: right), edge((1,0), (2,1), "->", [fill], label-side: center), edge((2,0), (3,1), "->", [fill], label-fill: true), ) \ #diagram( crossing-fill: gray, edge((0,0), (1,1), "->", [blue fill], label-side: right, label-fill: blue), edge((1,0), (2,1), "->", [no fill], label-side: center, label-fill: false), edge((2,0), (3,1), "->", [no fill]), )
https://github.com/ad-si/invoice-maker
https://raw.githubusercontent.com/ad-si/invoice-maker/master/examples/minimal-data.typ
typst
ISC License
#import "../invoice-maker.typ": * #show: invoice.with( hourly-rate: 1, issuing-date: "2024-03-24", // Must be set to not break tests biller: ( name: "ACME Corporation", vat-id: "GB123456789", iban: "GB29 NWBK 6016 1331 9268 19", address: ( country: "United Kingdom", city: "London", street: "Abbey Road", postal-code: "NW8 0AE", ), ), recipient: ( name: "<NAME>", vat-id: "GB987654321", address: ( country: "United Kingdom", city: "London", street: "Baker Street", postal-code: "W1U 6TJ", ) ), items: ( ( date: "2024-03-20", description: "Minimal amount of work", price: 1, ), ), styling: ( font: none ), // Explicitly use Typst's default font )
https://github.com/Julian-Wassmann/chapter-utils
https://raw.githubusercontent.com/Julian-Wassmann/chapter-utils/main/0.1.0/util/chapter-numbering.typ
typst
#let chapter-numbering( depth: 1, seperator: ".", numbering-pattern: "1", location: none, ) = { locate(loc => { if type(location) == "location" { loc = location } counter(heading).at(loc) .enumerate() .filter(((level, ..)) => depth == none or level < depth) .map(((.., heading-number)) => { numbering(numbering-pattern, heading-number) }) .join(seperator) }) }
https://github.com/jomaway/typst-bytefield
https://raw.githubusercontent.com/jomaway/typst-bytefield/main/lib/states.typ
typst
MIT License
// states #let default-row-height = state("bf-row-height", 2.5em); #let default-header-font-size = state("bf-header-font-size", 9pt); #let default-field-font-size = state("bf-field-font-size", auto); #let default-note-font-size = state("bf-note-font-size", auto); #let default-header-background = state("bf-header-bg", none); #let default-header-border = state("bf-header-border", none); // function to use with show rule #let bf-config( row-height: 2.5em, field-font-size: auto, note-font-size: auto, header-font-size: 9pt, header-background: none, header-border: none, content ) = { default-row-height.update(row-height); default-header-font-size.update(header-font-size) default-field-font-size.update(field-font-size) default-note-font-size.update(note-font-size) default-header-background.update(header-background) default-header-border.update(header-border) content } #let get-default-row-height() = { default-row-height.get() } #let get-default-header-font-size() = { default-header-font-size.get() } #let get-default-field-font-size() = { default-field-font-size.get() } #let get-default-note-font-size() = { default-note-font-size.get() } #let get-default-header-background() = { default-header-background.get() } #let get-default-header-border() = { default-header-border.get() }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/027%20-%20Conspiracy%3A%20Take%20the%20Crown/004_Proclamation%20by%20Adriana%2C%20Captain%20of%20the%20Guard.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Proclamation by Adriana, Captain of the Guard", set_name: "Conspiracy: Take the Crown", story_date: datetime(day: 16, month: 08, year: 2016), author: "<NAME>", doc ) Free Citizens of Paliano: When you fell asleep last night, you were loyal. You laid down your heads as steadfast servants of the one true king of Paliano, Brago the Eternal. Perhaps you did not love him. It is not the role of a ruler to be loved. But you obeyed him, and you respected him, as any citizen should. You awoke as unwitting traitors beneath the bloodstained banner of a usurper queen: Marchesa, the Black Rose, a known assassin and plotter, a criminal of the highest order whose veiled threats and hidden thorns have allowed her for far too long to flaunt the law of Paliano. She has made you traitors by raising her flag above the palace and placing the crown upon her treacherous brow. She has forced you to choose between loyalty to the crown and loyalty to your city. Somehow, this vile deceiver murdered King Brago, ending his immortal existence and dispersing the essence of his spirit. Somehow, she inserted herself into the sovereign's will and testament—a document forged, no doubt, from whole cloth, for why would the King Eternal have a will at all? And if he did, why would he name the murderous daughter of a fallen house to rule in his place? Somehow, she commands the loyalty of the Custodi priests who once made the king's word manifest in the world. Alongside them stand numerous servants of the throne who cannot or dare not question her right to rule, and in the shadows lurks her own existing network of thieves, spies, saboteurs, informants, and assassins. Already, the false queen raises her own sigil, the emblem of the Black Rose, above Paliano. She would quietly ignore the symbol of our city, the symbol Brago carried with him on the pommel of his own sword, an image so enduring, so emblematic of our city and its lawful ruler, that the Custodi consider it a religious icon in its own right. Oh, the Custodi wave it even now, and it means as little from them as it ever did. But the banners of the City Troops have already changed. You will not see that symbol in the halls of Marchesa's palace or on the shields of her defenders. She claims to rule legitimately, to have the interests of the city at heart, but the flag that has flown above us all these years is absent at her own command. And why? The reason is simple. Marchesa has no right to that sign of our city's history, and she knows it. She wears the crown and sits upon the throne, but she does not carry the sword of Brago—the blade that bears the symbol of our city. I know this because I now carry that sword, and with it the burden of upholding law and order in Paliano. I have been stripped of my title by the traitor queen, but I do not relinquish it. I hold this sword, this symbol, this duty to defend our city from all its enemies—even and especially an enemy who sits upon the throne. I have no wish to rule, only to unseat the usurper so that we may determine our rightful sovereign in the wake of King Brago's tragic end. Marchesa would have you stand with her, in service to a true crown that rests upon a false head, and thereby she would make you a traitor. I offer you a different path: stand with me, and with Brago, and show your loyalty to your city through your disobedience to the pretender. If her flag is not your flag, then do not bow to it. If her rule is illegitimate, then so too are her laws. If she is not truly queen, then the servants of the throne are no better than her spies and assassins, and should be treated accordingly. What say you, citizens of Paliano? Do you stand with the city, or with its self-proclaimed queen? Are you loyal rebels, or obedient traitors? Every day, as long as Marchesa sits upon the throne, you are one or the other. Make your choice! #figure(image("004_Proclamation by Adriana, Captain of the Guard/01.jpg", width: 100%), caption: [Adriana, Captain of the Guard | Art by <NAME>], supplement: none, numbering: none) —Adriana, captain of the guard
https://github.com/SkiFire13/eh-presentation-shellcode
https://raw.githubusercontent.com/SkiFire13/eh-presentation-shellcode/master/task3.typ
typst
#import "@preview/polylux:0.3.1": * #import "unipd.typ": * #new-section[ Task 3 ] #slide[ - Repeat task 1.b - but with 64 bit ] #new-section[ Task 3: Solution ] #slide[ ```asm ; The following code calls execve("/bin/sh", ...) xor rdx, rdx ; 3rd argument push rdx mov rax,'#/bin/sh' shr rax, 8 push rax mov rdi, rsp ; 1st argument push rdx push rdi mov rsi, rsp ; 2nd argument xor rax, rax mov al, 0x3b ; execve() syscall ``` ] // TODO: Show stack? #slide[ #align(center, v(-10%) + scale(x: 90%, y: 90%, image("exe3.png"))) ] #slide[ #place(center + horizon, v(18%) + scale(x: 100%, y: 100%, image("obj3.png"))) ]
https://github.com/0xPARC/0xparc-intro-book
https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/fs.typ
typst
#import("preamble.typ"):* = Making it non-interactive: Fiat--Shamir As we described it, PLONK is an interactive protocol. Peggy sends Victor some data; Victor reads that data and sends back a random challenge. Peggy sends back some more data; Victor replies with more challenges. After a few rounds of this, the protocol is complete, and Victor is convinced of the truth of Peggy's claim. We want to turn this into a non-interactive protocol. Peggy sends Victor some data once. Victor reads the data, does some calculation, and convinces himself of the truth of Peggy's claim. We will do this using a general trick, called the "Fiat--Shamir heuristic." Let us step back and philosophize for a moment. Why does Victor need to send challenges at all? This is actually what makes the whole SNARK thing work. Peggy condenses a long calculation down into a very short proof, which she sends to Victor. What keeps her from cheating is that she has to be prepared to respond to any challenge Victor could possibly send back. If Peggy knew what challenge Victor was going to send, Peggy could use that foreknowledge to create a false proof. But by sending a random challenge after Peggy's original commitment, Victor prevents her from adapting her proof to the challenge. The idea of Fiat and Shamir is to replace Victor's random number generator with a (cryptographically secure) hash function. Instead of interacting with Victor, Peggy simply runs this hash function to generate the challenge for each round. For example, consider the following (slightly simplified) version of @root-check. #algorithm[ Peggy wants to prove to Victor that two polynomials $F$ and $H$ (known only to Peggy) satisfy $F(X) = Z(X) H(X)$, where $Z(X) = product_(z in S) (X-z)$ is a fixed polynomial known to both Peggy and Victor. 1. Peggy sends $Com(F)$ and $Com(H)$. 2. Victor picks a random challenge $lambda in FF_q$ 3. Peggy opens both $Com(F)$ and $Com(H)$ at $lambda$. 4. Victor verifies $F(lambda) = Z(lambda) H(lambda)$. ] Fiat--Shamir turns it into the following noninteractive protocol. #algorithm[ Peggy wants to prove to Victor that two polynomials $F$ and $H$ (known only to Peggy) satisfy $F(X) = Z(X) H(X)$, where $Z(X) = product_(z in S) (X-z)$ is a fixed polynomial known to both Peggy and Victor. 1. Peggy sends $Com(F)$ and $Com(H)$. 2. Peggy computes $lambda in FF_q$ by $lambda = hash(Com(F), Com(H))$. 3. Peggy opens both $Com(F)$ and $Com(H)$ at $lambda$. 4. Victor verifies that $lambda = hash(Com(F), Com(H))$ and $F(lambda) = Z(lambda) H(lambda)$. ] We can apply the Fiat--Shamir heuristic to the full PLONK protocol. Now Peggy can write the whole proof herself (without waiting for Victor's challenges), and publish it. Victor can then verify the proof at leisure.
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/linear/entry-types.typ
typst
The Unlicense
#import "colors.typ": * #let entry-type-metadata = ( "identify": light-red, "brainstorm": light-yellow, "decide": light-green, "build": light-blue, "program": light-purple, "test": light-pink, "management": gray, "notebook": gray, )
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/requirements-analysis/index.typ
typst
#import "/components/glossary.typ": gls = Requirements Analysis == Functional requirements This section outlines the functional requirements for a robust language support system centered around Ungrammar, a grammar definition language. To achieve maximum flexibility and adaptability, the system is designed as a modular collection of interconnected components. The overarching goal is to create a versatile solution that can seamlessly integrate into various development environments, including both desktop and web-based editors. To accomplish this, the system is divided into the following core subsystems: - *Ungrammar Language Core*: The foundational component responsible for handling the core #gls("lsp") protocol and providing essential language features. - *Ungrammar VS Code Extension*: Integrating the language support into the #gls("vscode") editor, leveraging its extension #gls("api") for seamless user experience. - *Ungrammar Monaco*: Enabling language features within web-based applications utilizing the Monaco editor. - *Ungrammar Online Demonstration Playground*: A web-based environment showcasing the language support capabilities and serving as a development and testing platform. By adopting this modular approach, we aim to optimize code reusability, maintainability, and scalability while ensuring maximum flexibility in deployment and integration. The following sections will detail the specific functional requirements for each subsystem. Each subsystem will be broken down into use cases, use case diagrams, and use case specifications. Notably, the use case specifications will be defined in Gherkin syntax, facilitating a #gls("bdd") approach to streamline the development process. #include "core.typ" #include "vscode.typ" #include "monaco.typ" #include "playground.typ" == Non-functional requirements *Security* - *Anonymous Access*: The system does not require user authentication. - *Data Privacy*: No user data is collected or transmitted. - *Open-Source Transparency*: The system is open-source, ensuring transparency and community involvement. *Performance* - *Efficient Processing*: Handles large files with minimal processing time and delays. - *Fast Page Loading*: Ensures a quick and responsive user experience. *Availability* - *24/7 Accessibility*: The system is always available for use, without interruptions. - *Continuous Operation*: Maintains operation during maintenance periods. - *Cross-Platform Compatibility*: Accessible via both web and desktop versions. *Reliability* - *Consistent Functionality*: All features operate as expected, without errors or unexpected behavior. - *Data Integrity*: User data is protected, and no data is deleted unless explicitly requested by the user.
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/bugs/bad_show.typ
typst
Apache License 2.0
#show math.equation: i-figured.show-equation.with(level:0,numbering:"(1)") A and B
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/计算机网络/数据链路层.typ
typst
#import "../template.typ": * #show: note.with( title: "计算机网络", author: "YHTQ", date: none, logo: none, ) #let chapter3 = [ = 数据链路层 == 位置与功能 位于物理层和网络层之间,负责对下层物理层的比特流汇聚,并对上层网络层提供明确的接口。\ 在其下的数据链路层更多涉及通讯技术,本门课基本不涉及。 基本接口: + 主机、路由器统称节点 + 连续两个站点间的物理链路:信道,可能有限或无线 + 数据单位:帧 媒体访问协议 (MAC, Medium Access Control) 协议规定了帧在链路上如何传递 特点:差异性: - 不同链路上协议可能不同,包括以太网链路,中继链路,无线网络等等。 - 不同协议的服务保证也完全不同 链路层的实现通常包括: - 硬件与固件:电路模块,往往固件可以升级,硬件不行,主要集成在网络适配器(Network Interface Card, 网卡)之中,通过数据总线接入系统 - 软件:为网路层提供接口,中断处理等等 == 成帧(Framing) 物理层上常常不区分数据流的分割,这些分组操作必须由链路层解决,称为成帧。\ 关键问题:如何区分帧的开始和结尾? - 字节计数法:在头部加入该帧的字节计数,但一旦链路出现差错,会出现灾难性的后果。 - 带字节填充的定界符:在帧的开头结尾设置标志。若载荷中出现标志字符,需要进行转义(在前添加 ESC 字符)。现实中可以工作,但处理效率不高(在底层往往数据传输的单位是 bit) - 带 bit 填充的定界符:仍然设置定界符标志,这里使用一串 0 1 比特串,例如 $01111110$ 好处是可以降低转义的消耗,若在真实载荷中,可以在检测到 5 个连续 1 时,自动插入一个 0。接收方只需要将连续 5 个 1 后的 0 丢弃即可。 - 物理编码违例:由于物理层传输时总要进行一些编码,如果能使用不在编码中出现的比特串作为定界符,就可以避免转义。 == 差错控制 在物理层的数据传输中,往往会出现噪声导致传输出错。链路层也要对差错进行一定程度的控制。\ 定时重传机制成本太高,链路层往往采取添加冗余信息的方式,既要考虑信道的出错概率,也要考虑计算开销。这样的差错控制往往不是绝对正确的,如果仍然出错只能交由上层进行检查。 - 检错码:只能检测出错,不能纠正,需要进行重传。通常开销小一些,适用于错误率较低的链路,典型包括: + 奇偶校验:在添加一个奇偶校验位,保证数据中 1 的个数总为偶数/奇数个。 + 校验和:计算较简单,传输层常用,链路层由于往往使用专用硬件,因此使用更复杂的 CRC 校验。 + 循环冗余校验(CRC)利用 $(ZZ_(2))[x] \/ (p(x))$ 作为 $F_(2^(deg p(x)))$ 的代数性质。\ 设传输数据为 $f(x)$,$n = deg f(x)$ 为数据长度,$r = deg p(x)$为校验码的长度,最终发送数据为: $ x^r f(x) - (x^r f(x) mod p(x)) $ 检查时只需要检查是否被 $p(x)$ 整除即可。\ 检出率显然依赖于 $p(x)$ 的选取,CRC 标准规定了若干长度的选取,这些选取保证了任意 $r$ 位的错误都可以被检查出来。\ - 纠错码:可以检测出错,也可以纠正,但开销较大,适用于错误率较高的链路。 常用机制例如: + 二维奇偶校验:保证每行、每列的 1 的个数恰为偶数/奇数,可以纠错 - 一份数据传三份,接收方可以纠正一位出错的情况。冗余很大。\ 为了进行理论分析,可以考虑码字间的海明距离(0 - 1 位不同的个数)。假设我们的编码方案中每个有效码字之间海明距离都是 n,显然有: - 若假设至多 $⌊n/2⌋$ 个比特位出错,则可以通过找最近的合法码字纠正 - 若假设至多 $n - 1$ 个比特出错,则可以确定有效码字都是正确的,非法码字都是出错的,从而可以检错 在实际实践中,往往假设至多一位出错,此时我们若假设有效信息的个数为 $2^m$,再添加 $r$ 个校验位,则: - 总编码个数为:$2^(m+r)$ - 每个相邻有效编码间的海明距离最多为: $r+1$ (需要改变任何一位都应该改变所有校验码) - 我们希望 $⌊(r+1)/2⌋ = 1$ === 海明码 令每个校验位管理若干个信息位(具体方式是考虑 $k$ 的二进制编码,编码中为 $1$ 代表对应校验位管理此编码位 ),若出错则只需要考虑所有出错校验码的交即可 === Reed-Solomon code(RS 编码) 对海明码进行拓展,从而处理可能多位出错的情况。将二进制编码按照一定长度重组为符号,再以符号为单位,通过有限域上的线性代数进行校验。\ 具体想法为:对于 $n$ 个符号,补充 $r$ 个纠错符号,共计 $n+r$ 个。设至多 $m$ 个符号出错,只需保证 $n + r - m$ 个符号一定成为原始符号的一个基,进而通过双方约定的生成矩阵便可实现恢复。\ 此种编码一次长度往往较大,可能连续几个帧才能容纳一次完整的数据-校验信息。、 == 访问控制 局域网中,不同设备的连接方式有不同的拓扑形式,但往往需要共享同一个信道。然而同一个信道不可能同时传输多个消息,必须依次满足所有设备的要求。\ 目标: + 性能:尽可能占满所有信道带宽 + 公平:多站点同时需要传输时,希望每个站点获得的平均带宽相等 + 去中心化:不需要结点之间的协调或者全局时钟及其他全局信息 + 简单易实现 在计算机技术发展的早期,人们提出了大量多路访问控制方法,本门课程划分为三个大类: === 信道划分 将信道划分为多个部分,每个站点分配一个部分 + 静态划分频段:将频段静态划分给不同设备 + TDMA: time division multiple access\ 划分出等长时间片,均等分配给不同站点。此种方法无法处理时间片空闲的问题,效率较低。 + FDMA, frequency division multiple access\ 划分出等长频段,均等分配给不同站点。此种方法无法处理频段空闲的问题,效率较低。 + CDMA, code division multiple access\ 为每个站点分配一个编码,即使冲突发生接收方也能解码,主要用于无线通信 === 随机接入 允许冲突,但当冲突时进行恢复。\ 往往将信道状态分为三个状态: - 传输周期 - 竞争周期 - 空闲周期 + 纯 ALOHA 协议\ 不做任何同步和协调,站点立刻发出数据。一旦发生冲突,发生的数据就被全部破坏,通过设备触发的重传协议进行恢复。 + 分隙 ALOHA\ 将时间划分为 L/R 秒的时隙,节点只在时隙开始时发送数据。若发生冲突,等待下一个时隙再以概率 $p$ 发送。\ + CSMA: 载波侦听多路访问协议 Carrier Sense Multiple Access\ 特点:先听后发,如果侦听发现信道繁忙就推迟发送,经过随机等待后再次侦听 + 1-持续 CSMA:\ 若介质忙,就一直侦听。问题在于可能有两个设备同时侦听,导致同时发送。 + p-持续 CSMA:\ 若介质忙,就一直侦听。若空闲,以概率 $p$ 立刻发送,以 $1-p$ 推迟单位时间处理。 + 冲突检测 Collision detection: 先听后发,边发边听,若发现冲突就立刻停止发送,经过一段时间(例如随机时间)后再次尝试发送。\ 现代(有线)以太网中使用的访问控制方案:CSMA/CD 1-持续式 + 冲突检测 === CSMA/CD 硬件实现 现代网卡往往从硬件上支持 CSMA/CD ,具体方式为一份数据复制三份,一份发往物理链路,一份发往冲突检测模块,一份发往回环。接受模块同时接受外界的数据和回环数据,综合后发给冲突检测模块和上层。\ 此时,假设正常发送数据,链路中接受模块只接受回环数据,从而和冲突检测模块已有数据一致,说明无冲突。否则,链路中已经有数据,链路中接受模块不只接受回环数据,说明发生冲突。\ === 轮流协议 + 轮询协议\ 选择一个主节点,为其他站点分配链路使用权。主节点可以采取各种调度方式。问题:轮询占用带宽,通讯引入延迟,单点故障 + 令牌传递\ 令牌通过特殊消息进行传递,只有获得了令牌才能发送消息。令牌可以设置成各种拓扑,例如令牌环,令牌总线。一个点获得令牌时,若有数据就发送,若无就交给下一个。问题:维护代价,令牌本身的可靠性 + 位图协议\ 分为竞争期和传输期,竞争期决定资源预留,传输期进行数据传输。主要问题 :负荷高时利用率很高,但负荷低时利用率很低,且无法考虑优先级 + 二进制倒计数协议\ 站点赋予等长编号,竞争期需要发送数据的站点从高序号到低序号排队,每个站点发送一个 bit,如果发现比自己更高的站点也发送就放弃。 + 有限竞争协议\ 这是一类协议,在低负荷时采用竞争法减少延迟,高负荷时采用轮流协议保证效率。典型例子:自适应树搜索,指在一次成功传输后的第一个竞争时隙,所有站点进行竞争。如果只有一个站点就直接发送,否则下一轮仅让一半站点竞争(再下一轮另一半参与竞争) == 链路层寻址 链路层中,网络设备同样需要寻址,转发。这里使用的地址为 MAC 地址(也叫做 LAN 地址或者物理地址)。MAC 地址具有扁平寻址结构,且不受设备移动的影响。\ 链路层设备(网卡)发送数据时,将源 MAC 地址和目的 MAC 地址插入帧头部 === ARP 协议 链路层地址与网络层地址需要相互转换,这就是 ARP 协议\ ARP 协议与 DNS 有些类似,每个设备存储一个 IP $->$ MAC 的映射表,同时存储该表删除某个条目的时间(往往是二十分钟未使用删除)\ 发送数据时,若已知 MAC 地址就直接发送,否则利用 ARP 包(一个链路层封装的帧)向外广播,目标主机发送一个 ARP 回复包,包含自己的 MAC 地址。\ 注意这里的目标主机不只是子网内部设备,还可能是子网外部地址被路由器发现可达于是响应(注:路由器的不同接口有着不同的 MAC 地址) == 有线局域网 不需要网络层技术便可进行数据传输的网络,往往利用 MAC 地址而非 IP 地址进行寻址。\ IP 地址是层次化地址,从前往后依次决定位于哪个网络,但 MAC 地址是扁平化的,没有层次信息。\ === 以太网 以太网是当前最常用的有线局域网技术,也是最早使用的有线局域网提升。它的功能非常简单,成本低廉,便于扩展。\ 以太网标准是一系列标准的集合,包含不同的物理介质,不同速率等等,但帧的形式是一致的。\ 一个以太网帧由以下部分构成: + 前同步帧(物理层使用,往往不计入帧长度) + 目的地址,源地址:指 MAC 地址,各 6 字节 + 数据字段:46 ~ 1500 字节,保证总帧长位于 64 ~ 1518 字节。(最短帧长是为了发送期间占满链路,可以及时进行冲突检测。在以太网协议中,往返时间最长是 50ms ,可以发送的字节数约为 64 字节) + CRC 校验码:注意以太网并不提供传输保证,若发现 CRC 出错只会直接丢弃帧 以太网传输速度增长的速度也非常快,最早提出时仅在 10Mbps ,直到今日已经可以达到 100Gbps 以上,这个速度甚至可能已经超越了内存,对于软件和系统的设计也提出了新的挑战。\ - 经典以太网:最大 10Mbps 的传输速度,所有主机连接到一个收发器(后期集成在了主机之内),再连接到以太网线路,采用曼彻斯特编码,半双工连接。由于当时传输能力有限,要求一定距离之外必须通过中继器连接。 - 快速以太网:达到 100Mbps 的传输速度,采用了当时新诞生的双绞线,光纤。在当时相对而言快速,同时尽量兼容了经典以太网,在与经典以太网混合使用时采取协商机制。 - 千兆以太网:速度提升到了 1000Mbps ,此时理论上已经不需要最短六十四字节的载波填充,但为了兼容性仍然保留。由于传输速度过快,一段数据传输完成后仍然会占用信道一段时间,若上层没有新数据才释放信道。 - 万兆以太网:放弃了半双工的连接,此时由于链路两端可以同时通信,不再需要传输控制机制。 - 40G - 100G 以太网:主要在物理层进行优化提升,例如使用多个信道并行传输,发送方和接收方增加多路复用模块等等。 以太网的组建需要一些设备将不同链路连接起来: - 集线器:最早使用的设备,将多个链路汇总在一根总线。只做简单的 bit 合并,可能发生碰撞 - 交换机:相较于集线器提供了更复杂的功能,提供类似于路由的功能,将某个端口的数据转发至另一个端口,从而实现链路的连接。注意交换机和路由器的目的时略有差别的,路由器作为网络层的网络设备存在,而交换机希望在链路层应当完全透明,在不需要主机或者管理员干预的情况下完成转发表。\ 事实上,交换机往往使用简单的 MAC 地址进行交换,其中 MAC 地址来自于接受数据时分析数据的头部,并做记录,同时记录的还有进入的端口和此时时间。一段时间后若未被使用则删除(称为老化),发生更改则更改,这被称为逆向学习。具体的转发情况有以下三种: - 转发:找到了目的地址,直接转发 - 过滤:发现目的地址的端口就是进入的端口,直接丢弃 - 泛洪:当交换机收到未知目的地址的包时,将会发起一次广播,从所有除入境口的端口发送出去,这也与路由器不同 另一方面,交换机也支持多样的交换机制,包括: - 存储转发:可以进行校验,不会转出出错帧,但延迟很大 - 直通方式:只要知道了目的 MAC 地址,后续数据不作处理直接转发,需要依赖接收方处理错误。 - 无碎片交换:完整收到前 64 字节后,直接对其余内容进行转发。这是因为冲突造成的错误基本上一定发生在前 64 字节内,后续内容不会受到影响,这样可以过滤掉冲突产生的错误。\ 注:网络层的广播往往是通过链路层的广播实现的 一旦局域网上产生回路,交换机可能面临问题,例如: - 广播风波 - 反复修改:数据经过交换机后,通过回路又返回了交换机,导致转发表错误更新 解决方法是交换机在运行时动态构建最小生成树,不在生成树山的链路全部关闭 == 虚拟局域网 通过交换机的配置,可以在一套物理设备上运行多个虚拟局域网,每个局域网有单独的广播域 虚拟局域网的分组方式包括: + 基于端口(最常见) + 基于 MAC 地址 + 基于协议(物理局域网内可能有不同的网络层协议) + 基于子网 优点:控制广播域范围,增强安全性,灵活构建工作做,提高可管理性 == 无线网络 特点: - 无线主机可能在移动中,也可能不在 - 通过基站与有线网络连接起来,基站负责在有线网络与无线主机之间互传报文,包括无线信号塔,无线接入点等等 - 链路是无线网络(有时路由器,交换机也通过无线链路连接),对多路访问控制的要求较高,不同类型链路传输速率条件差异很大 - 核心问题包括:无线链路带来的传输复杂性,主机移动带来的网络层问题 无线网络分类的类型: - 基于基础设施的无线网络:\ 通过基站将无线设备连接向更大的网络,设备移动可能导致基站切换,这被称为切换问题 - 自组织网络\ 没有基站,节点自己组织成一个网络,相互路由、交换,例如蓝牙网络等等 - 单跳网络\ 无线设备通过单跳到达有线链路,例如蜂窝网、WiFi(基于基础设施),蓝牙(自组织) - 多跳网络\ 无线设备通过多跳到达有线链路,例如 无线网状网络 (Wireless Mesh Network)(基础设施),无线自组织网络 MANET, 车载自组织网络 VANET(自组织) == 无线链路 主要特点: - 信号随距离和穿过物体时强度递减,称为路径损耗 (path loss) - 其他信号源产生干扰,包括其他无线通讯了微波、电动机等 - 多路径传播,电磁波经过不同路径到达接收端 信噪比(Signal-to-noise Ratio):信号强度与噪声强度的比值,通常以 dB 为单位。越高表示信号越强,越容易解码。\ 比特差错率(Bit Error Rate, BER):接收方收到错误比特的比例。\ 在实际物理层中: - 若维持物理条件不变,增大传输功率,往往增加 SNR 但降低 BER - 若维持信噪比不变,往往增加传输速率会增加 BER 因此物理层可能采用自适应技术,在 BER 不太大的情况下尽可能增加传输速率 对高层的影响: - 逻辑上,没有任何影响,只是一种特殊的数据链路层和物理层实现 - 实际上会对性能造成很大影响。高错误率,移动性管理会造成很多丢包,可能对拥塞管理造成意外的影响。同时提供的延迟、带宽也往往更加糟糕 === 多路访问 特有问题: - 隐藏终端:AB, AC 之间都可以互相通信,但 BC 之间由于障碍无法通信,甚至有可能两者的信号在 B 处互相干扰 - 信号衰减:类似上面情形,BC 间信号极为微弱,且有可能在 B 处互相干扰 这造成 CSMA/CD 无法使用,因为不可能实现边发边听,需要其他的多路访问技术,典型的有: - 基于信道划分的 CDMA (码分多路服用)\ 它是扩频通信的一种,希望为不同用户分配单位正交的用户码片序列(向量),发送数据时发送: $ "数据" times "码片序列" $ 接受时点乘自身恢复。如此,若不同用户的数据发生叠加,由线性型和正交性可以保证仍能恢复正确数据 - 基于随机访问的 CSMA/CA (Collision Avoidance) 思想:发送前就尽量避免冲突,通过在信道空闲时递减计时器,防止突然空闲时多个发送者马上发送造成的冲突\ - 发送方:若发送时空闲且在接下来的一个 DIFS 都空闲,则发送整个帧,不做冲突检测。否则,选择一个随机值作为计时器,信道空闲时递减,忙时不变,减为 0 时发送并等待 ACK(链路层 ACK)。收到后若马上有数据传输,进入上一个步骤; 若未收到,则准备重传并采用更大的随机数值 - 接收方:收到正确的帧时发送 ACK。由于隐藏终端问题,ACK 是必要的 === 无线局域网 无线局域网协议:IEEE 802.11 又称 WiFi 协议,有不同版本,使用 2.4GHz, 5GHz 两个频段(不同协议允许的频段不同),允许多种不同的传输速率。使用 CSMA/CA 作为多路访问控制协议,支持基础设施模式和自组织模式。\ 网络由基础服务集(Basic Service Set, BSS)组成,包含: - 无线主机 - 接入点:也就是基站,只在基础设施 每个无线主机在能够进行网络层通信前,必须与一个 AP 相互关联,具体流程为: - 管理员为每个 AP 配置一个服务集标识符(SSID),在可选信道中选择一个信道。由于不同的 AP 可能选择相同的信道,信道之间也是重叠的,故不可能避免冲突 - 其次的连接方式可能有两种,包括: + 被动扫描 - AP 定时发送信标帧,包含 AP 的 SSID 和 MAC 地址 - 主机定时扫描,发现信标帧后,选择一个 AP 进行关联,发送关联请求帧 - AP 发送关联响应帧,包含关联成功与否的信息 + 主动扫描 - 主机发送探测请求帧 - AP 发送探测响应帧,包含 AP 的 SSID 和 MAC 地址 - 主机选择一个 AP 进行关联,发送关联请求帧 - AP 发送关联响应帧,包含关联成功与否的信息 - 关联时,需要身份验证(可选),分配 IP (通常利用 DHCP) 由于 CSMA/CA 协议较为复杂,802.11 设计了预约机制,允许网络使用(有的网络中也放弃使用): - 发送者首先按照 CSMA/CA 协议发送一个小报文 RTS(request-to-send) 给基站。此报文当然可能冲突,但冲突时进行重传 - 基站收到后,广播 CTS(clear-to-send) 消息,作为对 RTS 的回复 - 所有站点收到 CTS,之前的发送者开始发送,其余站点等待 - 发送完成后,其他站点也能收到 ACK,开始倒计时、传输 设备在同一子网下移动时,IP 地址不变,网络层没有变化。链路层上,交换机可以通过逆向学习更新转发表,确定新的 AP ,不需要人工干预。 其他功能: - 自适应传输速率:随着无线主机的移动,SNR 发生变换,基站与无线主机都将动态调整传输速率甚至物理层方案 - 功率管理:允许无线主机进入睡眠节省能耗,此时 AP 无法向主机发送帧 - 主机通知 AP 进入睡眠状态直到下一个信标帧(每隔 100ms 发送一个信标帧) - AP 在下一个信标帧之前,不再向主机发送,而是进行缓存 - 下一个信标帧将列出有帧缓存的主机,主机收到后检查是否有缓存,若有则唤醒并接收帧,否则继续睡眠 802.15 协议:个人域局域网,作为鼠标、键盘等设备的无线传输协议,由蓝牙演化而来。采用主从模式,slave 节点请求发送权限,Master 节点授权后进行传输。\ 访问控制采用时间片频段划分的方式,每个 625us 为一个时间片,选取 79 个频段其中之一发送,之后以伪随机方式跳到下一个频段,这被称为跳频扩展频谱(FHSS) === 移动性管理 移动性有不同的等级,无线局域网中移动设备不会造成网络层及以上的变化,但因为链路层逆向学习可能需要时间,可能造成一定程度的延迟。\ 为了实现终端的移动,每个终端往往有一个长期的归属网络不更换,这个网络下不变的地址称为永久地址,可以永远访问到该设备。\ 与之相对的,移动网络当前所在的网络称为被访网络(或外部网络),此网络下的地址称为转交地址。代表移动设备执行移动性功能的实体称为外部代理,他负责通知归属代理设备的所有权以及拥有的 COA\ 一般而言,具体的移动性管理过程一般如下: - 设备注册:移动设备进入访问网络时,连接外部代理,申请转交地址。外部代理通知归属代理该设备归属自己以及它的转交地址(有时也可由设备自身通知) - 设备移动:设备在新访问网络中注册,归属代理更新所有记录 - 数据路由:由于路由器不可能为所有永久地址维护转发表,往往通过代理通知,分为:(注意移动设备与通信者之间全部采用永久地址进行通信) + 间接代理:先代理到归属代理,再代理到外部代理。移动设备回复时,不需要经过归属代理,直接回复即可。 - 设备移动过程完全与网络层及以上透明,连接不会中断 - 效率较低,可能产生三角路由问题,也即实际链路比最优链路更长。极端情形下,两者位于同一外部网络,但仍然要绕行至归属代理进行通信 + 直接代理:直接代理到外部代理(注意通信者需要先通过归属代理获得转交地址,再绕过归属代理进行直接代理通信) - 通信效率高,不会产生三角路由问题 - 一旦接受者移动,发送者需要重新获取转交地址,否则无法通信 + 使用锚外部代理的直接代理:前一个被访网络中的代理称为锚外部代理。设备移动时,新的外部代理向原外部代理提供新的转交地址。原先的通信者仍将数据发给锚外部代理,由其负责转发 === 移动 IP 支持移动性的 Internet 架构,主要分为: - 代理发现\ 一个设备到达新外部网络时,必须先发现外部代理的身份。若是第一次加入还要发现归属代理,若是移动,也要确定原归属代理的身份。\ 它有两种实现: + 代理通告:借由归属代理或外部代理上周期性发送的特殊 ICMP 报文发现代理的 IP 地址 + 代理请求:设备广播一个请求报文,收到请求的代理直接向移动节点单播代理通告 - 代理注册:设备进行代理注册。注意设备离开该网络时不需要显式的取消,新注册发生时会归属代理会自动进行。 === 蜂窝网 基于基础设施的无线网络,通过移动电话网络提供数据传输,其中将无线设备连接到基站的接口称为空中接口\ 移动网络的移动性管理: - 访问者闻之注册器与被访网络的 MSC 共同构成外部代理(注意被访网络完全可能是归属网络) - 归属位置注册器(一个数据库,包含用户各种信息)以及归属 MSC(移动交换中心)共同构成归属代理,归属网络就是设备服务商的网络 蜂窝网协议有多代,包括: + 2G = GSM - 完全使用语音网络 - 组合使用 FDMA, TDMA 作为多路访问机制 - 采取间接代理机制作为移动性管理 - 没有规定何时在两个基站中切换(成为切换策略),但是规定了切换机制(如何切换),切换由旧基站发起,经过一系列信息同步后进行切换 + 3G - 语音网络与单独的数据网络并行运作 - 采用 CDMA 作为多路访问机制 + 4G LTE - 3G 到 4G 的过渡版本 - 不再有单独的语音网络,语音数据也完全封装在 IP 报文之中,控制平面与数据平面分离。 - 所有的数据通过运行在 UDP/IP 上的 GPRS 隧道协议(GTP)进行传输,同时由其解决移动性管理问题 - 用户除了闲置状态外,还有独占信道,大能耗的 DCH 和共享信道,小能耗的 FACH - 下载使用 OFDMA,上传使用 SC-FDMA(线性预编码 FDMA) - 睡眠状态为移动性管理造成了困难,需要基站定期广播寻呼报文,确认设备仍然存在 + 4G - 采用正交频分复用 OFDMA 作为多路访问机制 + 5G:非正交频分复用,MIMO ] #chapter3
https://github.com/TempContainer/typnotes
https://raw.githubusercontent.com/TempContainer/typnotes/main/sicm/lag_mech.typ
typst
#import "/book.typ": book-page #import "/templates/my-template.typ": * #show: book-page.with(title: "Lagrangian Mechanics") #show: template = 拉格朗日力学 (Lagrangian Mechanics) 系统的运动可以通过系统每个部分在每个时刻的位置给出. 这种对运动的描述称为*位形路径 (configuration path)*, 他是一个以时间为自变量的函数. 我们想要一种 path-distinguishing function, 它输入一个位形路径并产生一些输出, 当这个路径是可实现的 (realizable) ------即它是可以在现实中发生的------时, 我们希望这个函数可以具备一些特质. 例如, 我们让输出为零当且仅当路径可实现. 另外一种更强大的方法, 是利用*变分原理*: 对于每个物理系统我们搞一个 path-distinguishing funtion, 它通过让每个可实现路径相对于其他可能路径有一个平稳点来分辨可实现路径. 平稳点的意思是说, 当自变量的变化是微小的, 那么因变量的变化也是微小的. 在一般的函数中, 它通常表现为一个极值点. == 位形空间 (Configuration Spaces) 位形就是系统的各种位置状态. 这个系统可以做到的所有位置状态的总体就是它的*位形空间*. 这个位形空间的*维度*就是可以完全确定每个状态所需的最小参数数量, 也可以叫它*自由度*. 但是, 有个情况维度和自由度并不等同, 但现在不用管. 例子: 一个在 $RR^3$ 中无拘无束的刚体, 它的位形由其位置和旋转给出, 共六个自由度. == 广义坐标 (Generalized Coordinates) 考虑一个维度为 $n$ 的位形空间 $M$, 它可以被一个坐标函数 $chi$ 参数化. $chi$ 将位形空间中的元素映射为 $n$ 个实数组成的 $n$ 元组. 而 $chi$ 是由 $n$ 个相互独立的坐标函数 $chi^i, i=0,dots,n - 1$ 组成. 这里我们迁就一下物理学家, 将下标放在变量右上角. 对于一个位形 $m in M$, $chi^i (m)$ 就是这个位形的广义坐标. 因此, 每个位形空间上的点和一个广义坐标一一对应. 系统的运动被一个位形路径 $gamma$ 描述, 它将时间映射为位形空间的点. 与位形路径对应, *坐标路径* $q = chi compose gamma$ 将时间映射为广义坐标. 顺便定义 $q$ 的导数 $dD(q)$, 即 $dD(q)(t) = (dD(q)^(0) (t), dD(q)^(1) (t), dots, dD(q)^(n-1) (t)) $, 表示广义坐标的变化率. == 平稳作用量原理 (The Principle of Stationary Action) 我们对运动的经验认为: - 描述物理运动的位形路径是连续且光滑的; - 运动不依赖系统的整个历史; - 运动是可确定的 (deterministic), 这意味着, 我们有足够的参数可以确定下一时刻的状态. 我们对位形路径也有一些经验. 如果一个路径是可实现的, 则其任意一段也应是可实现的; 相对地, 若路径的每一段都是可实现的, 则整条路径也是可实现的. 因此整条路径的可实现性与其上每个点有关, 且只与这些点有关. 换言之, 可实现性是路径的局部属性. 由此我们可以初步构思我们需要的 path-distinguishing function, 它可以是对这条路径上某个局部属性的积分. 这种函数通常叫做系统的一个*作用量 (action)*. 令 $q = chi compose gamma$ 是一条坐标路径, $q(t)$ 是位形在 $t$ 时刻的坐标. 那么在时间段 $[t_1, t_2]$ 上的作用量为 $ S[q](t_1, t_2) = integral_(t_1)^(t_2) F[q]. $ 其中 $F[q]$ 是关于 $q$ 的泛函, 以时间为自变量, 它衡量了 $q$ 上的某些局部属性. 这里我们再迁就一下物理学家, 将 $integral_a^b f(x) dd(x)$ 简记为 $integral_a^b f$. 我们可以将 $F$ 分解为两部分: $ F[q] = L compose Gamma[q]. $ $Gamma$ 是一个元组, 它记录了时间, 当时的坐标, 以及其变化率和高阶导数, 即 $ Gamma[q](t) = (t, q(t), dD(q)(t), dots), $ 这个元组的个数与我们所需的导数阶数有关, 我们称它为*局部元组 (local tuple)*. $Gamma$ 只与具体的路径有关, 而与 $chi$ (即坐标系的选择) 无关. $L$ 与我们的研究物理系统相关, 但不依赖于任何具体的路径. 它将 $Gamma$ 中的某些部分挑出来, 并通过某种运算过程输出一个实数值. 以上的分解可以将我们对整个系统和具体路径的考察分离. $L$ 称为系统的一个*拉格朗日量 (Lagrangian)*, 而其对应的作用量 $ S[q](t_1, t_2) = integral_(t_1)^(t_2) L compose Gamma[q] $ 称为*拉格朗日作用量 (Lagrangian action)*. 当这个作用量只与时间, 位置和速度相关时, 可以写为 $ S[q](t_1, t_2) = integral_(t_1)^(t_2) L(t, q(t), dD(q)(t)) dd(t). $ 我们以后会发现, 许多系统的拉格朗日量都是动能和势能之差. 这类拉格朗日量只与时间, 位形和位形变化率有关. 有一点需要注意的是, 当讨论路径的作用量是否对于路径的变化是平稳值时, 必须限制路径的集合, 使得这个集合中只有一条可实现路径. *平稳作用量原理*指出, 对于每个动力系统, 都可以构造出一个拉格朗日量, 使得连接两个时间点 $t_1, t_2$ 之间的位形的可实现路径, 与所有可能路径相比, 其作用量 $S[q](t_1, t_2)$ 相对于路径的变化是平稳的. 我们在后面会看到, 对于上述只与位形和位形变化率有关的拉格朗日量, 路径的变化只需限制在保持 $t_1$ 与 $t_2$ 时刻的位形, 即所有的可能路径只需保证它们在 $t_1, t_2$ 两个时刻的位形相同即可. == 计算作用量 我们通过几个算例来解释上面的原理. 考虑一个三维空间中的自由粒子. 欧拉和拉格朗日告诉我们, 沿可实现路径的动能的积分相比这两点之间的任意其他路径都小. 只要将动能作为拉格朗日量, 那么自由粒子将遵循静止作用量原理. 我们选用一般的直角坐标系作为广义坐标. 设其拉格朗日量为 $ L(t, x, v) = 1 / 2 m (v dot v), $ 这里 $x, v$ 均为对应维度的元组. 我们用 Scheme 写出来 (对于具体的 Scheme 语法, 请参考附录): ```scheme (define ((L-free-particle mass) local) (let ((v (velocity local))) (* 1/2 mass (dot-product v v)))) ``` 这意味着 $L[m](vz(v)) = 1 / 2 m (vz(v) dot vz(v))$.
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/数理逻辑/作业/ml-2_1-hw.typ
typst
#import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark #import "../../template.typ": * #import "../main.typ": not1, True, False, infer #import "../main.typ": * #show: note.with( title: "作业2_1", author: "YHTQ", date: datetime.today().display(), logo: none, withOutlined : false, withTitle : false, withHeadingNumbering: false ) #let empty = "" #set heading(numbering: (..nums) => { let nums1 = nums.pos() nums1.insert(0, 3) numbering("1.1.(a)", ..nums1) } ) #let p1 = $p_1$ #let p2 = $p_2$ #let p3 = $p_3$ = == #empty #deduction[ + $(not1 p1 -> not1 p2) -> (p2 -> p1) := L3$ + $(1) -> ((p1 -> p2) -> (1)) := L1$ + $(p1 -> p2) -> ((not1 p1 -> not1 p2) -> (p2 -> p1)) := MPb(1, 2)$ ] == #empty #let f1 = $p1 -> (p2 -> p3)$ #let f2 = $p1 -> p2$ #let f3 = $p1 -> p3$ #deduction[ + $(f1) -> ((f2) -> (f3)) := L2$ + $((f1) -> ((f2) -> (f3))) -> (((f1) -> (f2)) -> ((f1) -> (f3))) := L2$ + $((f1) -> (f2)) -> ((f1) -> (f3)) := MPb(1, 2)$ ] == #empty #let f1 = $(p1 -> p2)$ #let f2 = $(p1 -> p1)$ #lemmaLinear[][ ${calA} tack (calA -> calB) -> calB$ ]<l1> #proof[ #deduction[ + $calA := fS$ + $((calA -> calB) -> (calA -> calB)) -> (((calA -> calB) -> calA) -> ((calA -> calB) -> calB)) := L2$ + $(calA -> calB) -> (calA -> calB) := idL$ + $((calA -> calB) -> calA) -> ((calA -> calB) -> calB) := MPb(3, 2)$ + $(calA -> calB) -> calA := MPb(1, L1)$ + $(calA -> calB) -> calB := MPb(5, 4)$ ] ] #lemmaLinear[][ ${calA -> calB, calB -> calC} tack calA -> calC$ ]<l2> #proof[ #deduction[ + $calA -> calB := fS$ + $calB -> calC := fS$ + $((calA -> calB) -> (calA -> calC)) -> (calA -> calC) := $ @l1 + $(calA -> (calB -> calC)) -> ((calA -> calB) -> (calA -> calC)) := L2$ + $calA -> (calB -> calC) := MPb(2, L1)$ + $(calA -> calB) -> (calA -> calC) := MPb(5, 4)$ + $calA -> calC := MPb(6, 3)$ ] ] #deduction[ + $(p1 -> f1) -> (f2 -> f1) := L2$ + $p1 -> p1 := idL$ + $(f2 -> f1) -> f1 :=$ @l1 + $(p1 -> f1) -> f1 := $ @l2 $(1) (3)$ ] = == <p1> #deduction[ + $not1 calA := fS$ + $not1 calB -> not1 calA := MPb(1, L1)$ + $calA -> calB := MPb(2, L3)$ ] == #lemmaLinear[][ ${calB, calA -> (calB -> calC)} tack calA -> calC$ ]<l11> #proof[ #deduction[ + $(calA -> calB) -> (calA -> calC) := MPb(fS, L2)$ + $calA -> calB := MPb(fS, L1)$ + $calA -> calC := MPb(2, 1)$ ] ] #deduction[ + $calA := fS$ + $(not1 not1 not1 calA -> not1 calA) -> (calA -> not1 not1 calA) := L3$ + $(not1 calA -> (calA -> calB)) := "课上引理" not1 calA -> (calA -> calB)$ + $(not1 calA -> calA) -> (not1 calA -> calB) := MPb(3, L2)$ + $not1 calA -> calB := MPb(MPb(1, L1), 4)$ // + $not1 not1 not1 calA -> (not1 not1 calA -> calA) -> (calB -> not1 calA) $ + $not1 not1 not1 calA -> (not1 not1 calA -> not1 calA) := "课上引理" not1 calB -> (calB -> calA)$ + $(not1 not1 calA -> not1 calA) -> (calA -> not1 calA) := L2$ + $not1 not1 not1 calA -> (calA -> not1 calA) := #transitivity-b(7, 6) "(前已证)"$ + $not1 not1 not1 calA -> not1 calA := $ @l11 + $not1 not1 A := MPb(1, MPb(9, 2))$ ] == #empty #deduction[ + $calA -> (calB -> calC) := MPb(fS, L3)$ + $(calA -> calB) -> (calA -> calC) := MPb(1, L2)$ + $calA -> calC := MPb(fS, 2)$ ] = == #empty 用演绎定理: $ tack (calB -> calA) -> (not1 calA -> not1 calB) <=> calB -> calA tack not1 calA -> not1 calB $ #deduction[ + $calB -> calA := fS$ + $not1 not1 calB -> not1 not1 calA := "课上习题" (calA -> calB) tack (not1 not1 calA -> not1 not1 calB) $ + $not1 calA -> not1 calB := MPb(2, L3)$ ] == #empty 用演绎定理: $ tack ((calA -> calB) -> calA) -> calA <=> (calA -> calB) -> calA tack calA $ #deduction[ + $(calA -> calB) -> calA := fS$ + $not1 calA -> (calA -> calB) := "课上引理" not1 calB -> (calB -> calA)$ + $not1 calA -> calA := #transitivity-b(1, 2)$ + $calA := "课上引理" not1 calA -> calA tack calA$ ] = == #empty #lemmaLinear[][ $not1 calA -> not1 calB tack not1 (calB -> calA)$ ] 定义: $ calA and calB = not1 (calA -> not1 calB) $ 用演绎定理: $ tack calA -> (calB -> (calA and calB)) = tack calA -> (calB -> not1 (calA -> not1 calB))\ <=> calA, calB tack not1 (calA -> not1 calB) $ 注意到(简单使用 MP 即可): $ calA, calB, (calA -> not1 calB) tack calB, not1 calB $ 因此有(利用引理 $calA, not1 calA tack calB$): $ calA, calB, (calA -> not1 calB) tack calB, not1 calB tack not1 (calA -> not1 calB)\ <=> calA, calB tack (calA -> not1 calB) -> not1 (calA -> not1 calB) $ 再利用 $calA -> not1 calA tack not1 calA$ 立得结论 = == #empty #let tL = $tack_L$ #let tL1 = $tack_L'$ 用演绎定理: $ tL (not1 calA -> not1 calB) -> ((not1 calA -> calB) -> calA)\ <=> not1 calA -> not1 calB tL (not1 calA -> calB) -> calA\ <=> not1 calA -> not1 calB, not1 calA -> calB tL calA\ $ 注意到 $not1 calB, calB tL calA => tL not1 calB -> calB -> calA$,有: #deduction[ + $not1 calB -> calB -> calA$ + $not1 calA -> not1 calB$ + $not1 calA -> calB$ + $not1 calA -> calB -> calA := #transitivity-b(1, 2)$ + $(not1 calA -> calB) -> (not1 calA -> calA) := MPb(4, L2)$ + $not1 calA -> calA := MPb(3, 5)$ + $calA := "引理" not1 calA -> calA tL calA $ ] 证毕 == #empty 检查演绎定理的证明事实上并未用到 $L3$,因此在 $L'$ 中演绎定理同样成立。 $ tL1 ((not1 calA -> not1 calB) -> (calB -> calA)) <=> not1 calA -> not1 calB, calB tL1 calA \ $ 有: #deduction[ + $not1 calA -> not1 calB$ + $calB$ + $(not1 calA -> calB) -> calA := MPb(1, L3')$ + $not1 calA -> calB := MPb(2, L1) $ + $calA := MPb(4, 3)$ ] 证毕 == #empty 设 $calA$ 是 $L$ 中定理,也即存在演绎序列 $calA_1, calA_2, dots, calA_n$ 使得 $calA_n = calA$。由于 $L3$ 公理在 $L'$ 中是定理,因此该序列也是 $L'$ 中有效的演绎序列,即 $calA$ 也是 $L'$ 中的定理。因此 $L$ 中的定理在 $L'$ 中也是定理。反之类似。 == #empty #definitionLinear[极大一致子集][ 设 $Gamma$ 是公式集,$Gamma'$ 是其子集。若 $Gamma'$ 是一致的(对于任何公式 $calA$ 不可能同时演绎得到 $calA, not1 calA$)且在 $Gamma$ 中是极大的($Gamma$ 中不存在更大的一致集),则称之为极大一致子集。 ] + 极大一致推理不是平凡的,对于某个定理 $calA$,设 $Gamma = {calA, not1 calA}$,不难发现它的极大一致子集是 ${calA}$。假设极大一致推理是平凡的,则 $Gamma$ 应当推出任意公式,意味着 $calA$ 可以推出任意公式。由 $calA$ 是 $L$ 中定理的假设,这将导致 $L$ 中所有公式都是定理,这与 $L$ 的一致性矛盾。 + 极大一致推理不是单调的。假设 $calA, not1 calA$ 都不是定理,则 ${calA}, {not1 calA}$ 都是一致集(否则若 ${calA}$ 不一致,则由平凡性 $calA tack not1 calA$,由引理这将导致 $not1 calA$ 成为定理,另一面类似),考虑 $Gamma = {calA, not1 calA}$ ,若它的极大一致推理得到 $calB$ ,则将满足: $ calA tack calB, not1 calA tack calB => tack {calA -> calB, not1 calA -> calB} $ 之前已经证明 $not1 calA -> calB tack not1 calB -> not1 not1 calA tack not1 calB -> calA $ 因此得到 $not1 calB -> calB$ 也即 $calB$ 将成为定理。 然而,它的子集 ${calA}$ 的极大一致子集就是本身,因此极大一致推理得到的结果与一般推理相同,至少包括 $L$ 的所有定理以及 $calA$。 因此,$Gamma$ 的子集 ${calA}$ 的极大一致推理结果比 $Gamma$ 严格更大,不满足单调性。 #remarkLinear[][ $L$ 中的原子命题 $p$ 一定满足 $p, not1 p$ 都不是定理,否则: - 若 $p$ 是定理,由于其原子性,相同的演绎过程应当应用于任何公式,这将导致所有公式都是定理,与 $L$ 的一致性矛盾。 - 若 $not1 p$ 是定理,类似的所有公式的否定都是定理,然而 $not1 not1 calA -> calA$ 导致所有公式都是定理,同样与 $L$ 的一致性矛盾。 因此上面说到的 $calA, not1 calA$ 都不是定理是可能取得的。 ]
https://github.com/senaalem/ISMIN_reports_template
https://raw.githubusercontent.com/senaalem/ISMIN_reports_template/main/README.md
markdown
# _Template_ rapport ISMIN Ce _template_ est celui que j'utilise pour écrire mes rapports à l'EMSE. Il utilise le langage Typst et est grandement inspiré de [celui de <NAME>](https://github.com/thimotedupuch/Template_Rapport_ISMIN_Typst) ainsi que du [_template_ Bubble](https://github.com/hzkonor/bubble-template). Le fichier `template_report_ISMIN.pdf` est un apercu en PDF du résultat de la compilation. J'ai essayé de montrer toutes les possibilités qu'offrait Typst, le contenu étant évidemment à ajuster à votre guise. Pour en savoir plus sur les fonctions l'utilisation de Typst, vous pouvez utiliser [la documentation](https://typst.app/docs), elle est très complète. Le Ctrl+Clic (ou Cmd+Clic) marche aussi sur les fonctions (dans l'éditeur de l'application web). ## Utilisation Je conseille d'utiliser [l'application Web Typst](https://typst.app/), mais il est possible de l'installer le compilateur en CLI sur sa machine. - Le fichier `template.typ` contient toutes les règles et fonctions d'affichage - Le fichier `main.typ` lui contient le contenu que vous souhaitez inclure dans le rapport - Le fichier `bibs.yaml` contient les références bibliographiques (au format Hayagriva, mais Typst prend aussi en charge le format BibLaTeX) - Le dossier `assets` contient les ressources graphiques pour le thème du _template_ - Le dossier `fonts` contient des polices de caractères - Le dossier `images` contient les images inclues dans le document
https://github.com/tiankaima/typst-svgs
https://raw.githubusercontent.com/tiankaima/typst-svgs/master/240930fe-demo/main.typ
typst
#set page(width: auto, height: auto, margin: 0pt) $ lim_(x->oo) (sin x) / x = 0 $
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/docs/tinymist/frontend/neovim.typ
typst
Apache License 2.0
#import "/docs/tinymist/frontend/mod.typ": * #show: book-page.with(title: "Tinymist Neovim Extension") Run and configure tinymist in neovim for Typst. == Features <features> See #link("https://github.com/Myriad-Dreamin/tinymist#features")[Tinymist Features] for a list of features. #include "common-finding-executable.typ" - (Recommended) Stable versions available with #link("https://github.com/williamboman/mason.nvim")[mason.nvim];. ```lua { "williamboman/mason.nvim", opts = { ensure_installed = { "tinymist", }, }, } ``` == Minimal Setup: LazyVim as an Example <minimal-setup-lazyvim-as-an-example> This section shows you a minimal way to setup tinymist in Neovim (LazyVim). + Copy or merge the #link("https://github.com/Myriad-Dreamin/tinymist/tree/main/editors/neovim/config/autocmds.lua")[Autocmds file] and #link("https://github.com/Myriad-Dreamin/tinymist/tree/main/editors/neovim/plugins/tinymist.lua")[Plugin file] to corresponding paths into `~/.config/nvim/`. + Check and restart Neovim. // todo: heading link support Please see #md-alter(link(<extra-settings>)[Extra Settings], () => link("#extra-settings")[Extra Settings]) for more configuration. == Tips <tips> === Working with Multiple-File Projects <working-with-multiple-file-projects> The solution is a bit internal, which should get further improvement, but you can pin a main file by command. ```lua -- pin the main file vim.lsp.buf.execute_command({ command = 'tinymist.pinMain', arguments = { vim.api.nvim_buf_get_name(0) } }) -- unpin the main file vim.lsp.buf.execute_command({ command = 'tinymist.pinMain', arguments = { nil } }) ``` There is also a plan to support multiple-file project by workspace configuration, but I don’t know whether it is neovim’s way, so it needs further discussion. #note-box[ `tinymist.pinMain` is a stateful command, and tinymist doesn't remember it between sessions (closing and opening the editor). ] == Troubleshooting <troubleshooting> === tinymist does not start on creating/opening files <tinymist-does-not-start-on-creatingopening-files> First, please check that tinymist can start with manual file association. ``` :set filetype=typst ``` If tinymist starts, that means you have not made correct file association. If not, there should be some errors in your lspconfig. Please associate `.typ` file extension to `typst` filetype to start tinymist on creating/opening file events. ```shell autocmd BufNewFile,BufRead *.typ setfiletype typst ``` == Extra Settings <extra-settings> === Configuring LSP Server <configuring-lsp-server> To configure LSP server, you can edit the `opts.servers.tinymist.settings`. For example, if you want to export PDF on typing and output files in `$root_dir/target` directory: ```lua return { -- add tinymist to lspconfig { "neovim/nvim-lspconfig", opts = { servers = { tinymist = { settings = { exportPdf = "onType", outputPath = "$root/target/$dir/$name", } }, }, }, }, } ``` See #link("https://github.com/Myriad-Dreamin/tinymist/tree/main/editors/neovim/Configuration.md")[Tinymist Server Configuration] for references. === Configuring Language Server for COC <configuring-coc-language-server> To configure language server for #link("https://github.com/neoclide/coc.nvim")[coc.nvim], you can edit the `coc-settings.json` by executing `:CocConfig`: ```json "languageserver": { "tinymist": { "command": "tinymist", "filetypes": ["typst"], "settings": { "exportPdf": "onType", "outputPath" = "$root/target/$dir/$name", } } } ``` === Configuring Folding Range for Neovim Client <configuring-folding-range-for-neovim-client> Enable LSP-based folding range with `kevinhwang91/nvim-ufo`: ```lua return { { -- configure LSP servers "neovim/nvim-lspconfig", dependencies = "kevinhwang91/nvim-ufo", -- enable LSP-based folds }, } ``` You can copy or merge #link("https://github.com/Myriad-Dreamin/tinymist/tree/main/editors/neovim/plugins/lsp-folding.lua")[lsp-folding.lua] to corresponding paths into `~/.config/nvim/` and restart Neovim. == Contributing <contributing> You can submit issues or make PRs to #link("https://github.com/Myriad-Dreamin/tinymist")[GitHub];.
https://github.com/maxgraw/bachelor
https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/0-base/0-index.typ
typst
#set page(numbering: "I", number-align: right) #counter(page).update(1) #include "1-oath.typ" #include "2-abstract.typ" #include "3-short.typ" #include "4-outline.typ" #include "5-figures.typ" #include "listing.typ" #include "6-abbreviations.typ"
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Olympiades_Groupes_Partie_2.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: "Olympiades Groupes Partie 2", authors: ( "<NAME>", ), date: "30 Octobre, 2023", ) #set heading(numbering: "1.1.") == Exercices académique n°2 <exercices-académique-n2> = Généalogie des fractions. <généalogie-des-fractions.> Dans cet exercice, on considère des fractions écrites sous la forme $a / b$ où $a$ et $b$ sont des entiers naturels non nuls. On construit un arbre généalogique de fractions en partant de la fraction $1 / 1$. Chaque fraction $a / b$ donne naissance à deux fractions : - la fille benjamine: $frac(a, a plus b)$, qu’on écrit à gauche ; - la fille aînée: $frac(a plus b, b)$, qu’on écrit à droite. $a / b$ ├── $frac(a, a plus b)$ └── $frac(a plus b, b)$ $1 / 1$ ├── $1 / 2$ │ ├── $1 / 3$ │ │ ├── $1 / 4$ │ │ │ └── … │ │ └── $4 / 3$ │ │ └── … │ └── $3 / 2$ │ ├── $3 / 5$ │ │ └── … │ └── $5 / 2$ │ └── … └── $2 / 1$ ├── $2 / 3$ │ ├── $2 / 5$ │ │ └── … │ └── $5 / 3$ │ └── … └── $3 / 1$ ├── $3 / 4$ │ └── … └── $4 / 1$ └── … En poursuivant le processus, on obtient un arbre généalogique infini. === Partie I: La famille proche. <partie-i-la-famille-proche.> + Quelles sont les deux filles de la fraction $22 / 7$ ? + Quelle est la mère de la fraction $17 / 31$ ? Et sa grand-mère ? + Quelle est la mère de la fraction $i / j$ si $i lt j$ ? Et si $i gt j$ ? + Quelle est la petite sœur de la fraction $355 / 113$ ? + Démontrer que les fractions $13 / 31$ et $23 / 5$ sont cousines. + Que peut-on dire de la succession des filles aînées de $1 / 1$ ? === Partie II: Des fractions irrédutibles. <partie-ii-des-fractions-irrédutibles.> On considère une fraction strictement positive irrédutible $a / b$. Cela signifie que le seul diviseur commun des entiers naturels non nuls $a$ et $b$ est égal à $1$. + Soit $d$ un diviseur commun de $a$ et $a plus b$. \ Montrer que $d$ est forcément égal à $1$. \ Que peut-on en déduire pour la fille benjamine de $a / b$ ? \ + Expliquer pourquoi toutes les fractions qui apparaissent dans l’arbre généalogique sont irréductibles. === Partie III: À chacun sa place. <partie-iii-à-chacun-sa-place.> Dans la partie II, on a établi que l’arbre étudié comporte uniquement des fractions irrédutibles strictement positives. On admet que toutes les fractions irréductibles strictement positives sont dans cet arbre généalogique, sans aucune répétition. On peut ainsi numéroter toutes les fractions irrédutibles strictement positives en considérant les lignes successives de l’arbre généalogique parcourues de haut en bas et de gauche à droite. On peut représenter les chosees comme sur l’arbre ci-dessous. F\_1 ├── F\_2 │ ├── F\_4 │ │ ├── F\_8 │ │ └── F\_9 │ └── F\_5 │ ├── F\_10 │ └── F\_11 └── F\_3 ├── F\_6 │ ├── F\_12 │ └── F\_13 └── F\_7 ├── F\_14 └── F\_15 On admet que dans cette situation, chaque fraction $F_n$ a pour fille benjamine $F_2 n$ et pour fille aînée $F_(2 n plus 1)$ où $n$ est un entier naturel non nul. + Calculer le produit de deux fractions soeurs. \ En déduire la valeur du produit de toutes les fractions d’une même génération. + Combien vaut $F_2023$ ? + Déterminer l’entier $n$ tel que $F_n eq 31 / 43$ + Ecris un programme qui calcule $F_n$ pour un entier $n$ donné. + Ecris un programme qui calcule $n$ pour une fraction donnée.
https://github.com/ivaquero/lang-speeches
https://raw.githubusercontent.com/ivaquero/lang-speeches/main/README.md
markdown
# Collection of Contemporary Speeches by Non-English Speakers A collection of famous contemporary speeches in typst format. ## Compilation To compile with the template, refer to the guide of this [repo](https://github.com/ivaquero/scibook).
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/spue/planung/tipps.typ
typst
Other
== Allgemeine Hinweise + Mehrere SPÜs in unterschiedlichen Fächern im selben Semester zu machen, ist zeitlich extrem fordernd und sollte vermieden werden! + Sie sind Teil einer Gruppe, es arbeitet sich einfacher gemeinsam. + Sprechen Sie mit... - ... ihren Mitstudierenden, um neue Ideen und Unterstützung zu bekommen. *Gemeinsames Brainstormen rettet Leben!* - ... ihren Dozenten, wenn Sie Probleme haben, Lektüre zu finden. - ... der Person, die sie prüft, wenn Sie zeitliche Probleme und Planungsschwierigkeiten haben. + Rechnen Sie mit mind. 1 Woche intensiver Arbeit für den schriftlichen Langentwurf. Darin ist *nicht* die Ideenfindung für die Unterrichtsstunde enthalten. + Benutzen Sie vorgestellte Planungsmethoden für den Unterricht, arbeiten Sie diese Schritt für Schritt ab. + Programme wie "Tutory" und "Canva" können bei der Erstellung von Arbeitsblättern helfen.
https://github.com/Selflocking/cdut-typst
https://raw.githubusercontent.com/Selflocking/cdut-typst/master/report.typ
typst
MIT License
#import "fonts.typ": 字体 #import "fonts.typ": 字号 #set page("a4", margin: (bottom: 150pt), footer: [ #set align(center) #set text(font: 字体.宋体, size: 字号.小三) #text("2023 年 5 月 20 日") ], ) // logo #set align(center) #image("images/cdut.png", height: 64pt) #let course="《Python 程序设计》" #let topic="论如何给母猪做产后护理" #let name="张三" #let studentid="114514" #let college="计算机学院" #let major="母猪的产后护理" #let teacher="李四" #let fieldname(name) = [ #let name = text(name, font: 字体.黑体, size: 字号.小三) #set align(right + top) #strong(name) ] #let fieldvalue(value) = [ #set align(center + horizon) #set text(font: 字体.黑体, size: 字号.小三) #grid( rows: (auto, auto), box( value, height: 字号.小三 - 2pt, ), line(length: 100%) ) ] // 距离 logo 的距离 #v(75pt) #let course_name_left = [ #set align(center + horizon) #set text(font: 字体.黑体, size: 字号.小三) #grid( rows: (auto, auto), row-gutter: 0.2em, course, line(length: 100%) ) ] #let course_name_right = [ #set text(font: 字体.黑体, size: 字号.小三) #set align(left + top) #strong("项目报告") ] #grid( columns: (字号.小三*18, 字号.小三*4), row-gutter: 3em, course_name_left, course_name_right, ) #v(3em) #grid( // 左右列宽 columns: (字号.小三*5, 字号.小三*18), // 行间距 row-gutter: 3em, fieldname("设计题目:"), fieldvalue(topic), fieldname("学院名称:"), fieldvalue(college), fieldname("专业名称:"), fieldvalue(major), fieldname("学生姓名:"), fieldvalue(name), fieldname("学生学号:"), fieldvalue(studentid), fieldname("任课老师:"), fieldvalue(teacher), fieldname("设计成绩:"), fieldvalue(text("")), ) #pagebreak()
https://github.com/kdog3682/mathematical
https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/3d-cetz-attempt-2.typ
typst
// status: works #import "@preview/cetz:0.2.2" #import cetz.draw: * #let get-cube-segments(x, y, z) = { let length = 3 let vertices = ( (x, y, z), (x + length, y, z), (x + length, y + length, z), (x, y + length, z), (x, y, z + length), (x + length, y, z + length), (x + length, y + length, z + length), (x, y + length, z + length) ) let edges = ( (0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7) ) return edges.map(edge => { let (start, end) = edge let (x1, y1, z1) = vertices.at(start) let (x2, y2, z2) = vertices.at(end) ((x1, y1, z1), (x2, y2, z2)) }) } #{ cetz.canvas({ let lines = get-cube-segments(0, 0, 0) for pos in lines { line(..pos) } }) }
https://github.com/dainbow/MatGos
https://raw.githubusercontent.com/dainbow/MatGos/master/themes/4.typ
typst
#import "../conf.typ": * = Теоремы о среднем Ролля, Лагранжа и Коши для дифференцируемых функций. == Теорема Ролля #definition[ Пусть $f$ определена в некоторой $delta_0$ окрестности точки $x_0$. Если #eq[ $exists delta in (0, delta_0) : forall x in U_delta (x_0) : space f(x) <= f(x_0)$ ] то $x_0$ -- *точка локального максимума*. Также аналогично вводятся определения *локального минимума*, а также *строгие* экстремумы, в которых неравенство строгое. ] #definition[ Пусть $f$ -- функция, $D_f$ -- ее область определения, $x_0 in D_f$. Тогда *производной* $f$ в точке $x_0$ называется #eq[ $\ f'(x_0) = lim_(h -> 0) frac(f(x_0 + h) - f(x_0), h) = lim_(x -> x_0) frac(f(x) - f(x_0), x - x_0)$. ] ] #definition[ Число $A$ называется *правосторонним пределом* функции $f$ в точке $a$, если #eq[ $forall epsilon > 0 : exists delta > 0 : forall x in (a, a + delta) : |f(x) - A| < epsilon$. ] ] #definition[ Число $A$ называется *левосторонним пределом* функции $f$ в точке $a$, если #eq[ $forall epsilon > 0 : exists delta > 0 : forall x in (a - delta, a) : |f(x) - A| < epsilon$. ] ] #definition[ *Правой производной* функции $f$ в точке $x_0$ называется #eq[ $f'_+(x_0) = lim_(h -> +0) frac(f(x_0 + h) - f(x_0), h)$. ] ] #definition[ *Левой производной* функции $f$ в точке $x_0$ называется #eq[ $f'_-(x_0) = lim_(h -> -0) frac(f(x_0 + h) - f(x_0), h)$. ] ] #theorem[ Функция $f$, определенная в некоторой окрестности точки $x_0$ имеет производную в точке $x_0$ тогда и только тогда, когда она имеет обе односторонние производные в этой точке, и эти производные равны. ] #definition[ Функция $f$ называется *дифференцируемой* в точке $x_0$, если она определена в некоторой окрестности точки $x_0$ и в этой точке имееет конечную производную. ] #theorem( "Ферма о необходимом условии локального экстремума", )[ Если $x_0$ -- точка локального экстремума функции $y = f(x)$, дифференцируемой в $x_0$, то $f'(x_0) = 0$. ] #proof[ БОО $x_0$ -- точка локального максимума. Заметим, что тогда #eq[ $\ lim_(Delta x -> +0) (f(x_0 + Delta x) - f(x_0)) / (Delta x) <= 0 ; quad lim_(Delta x -> -0) (f(x_0 + Delta x) - f(x_0)) / (Delta x) >= 0$ ] А при существовании производной оба этих предела совпадают, поэтому производной в $x_0$ остаётся лишь быть равной нулю. ] #theorem( "Ролля", )[ Если $f$ непрерывна на $[a, b]$, дифференцируема на $(a, b)$, причём $f(a) = f(b)$, то #eq[ $exists c in (a, b) : f'(c) = 0$ ] ] #proof[ Заметим, что если $f equiv "const"$, то утверждение тривиально. Иначе, $f$ непрерывна на $[a, b] => $ #eq[ $exists m, M : m < M : space m = min_(x in [a, b]) f(x) ; quad M = max_(x in [a, b]) f(x)$ ] Заметим, что либо $m != f(a)$, либо $M != f(a)$. Это значит, что существует локальный минимум или максимум в некоторой точке $c in (a, b)$, а по теореме Ферма мы знаем, что $f'(c) = 0$. ] == Теоремы Лагранжа и Коши #theorem("Обобщённая теорема о среднем")[ Если $f, g$ непрерывны на $[a, b]$, дифференцируемы на $(a, b)$, то #eq[ $exists c in (a, b) : (f(b) - f(a))g'(c) = (g(b) - g(a))f'(c)$ ] ] #proof[ Рассмотрим #eq[ $h(x) = (f(b) - f(a))g(x) - (g(b) - g(a))f(x)$ ] Заметим, что $h$ всё ещё непрерывна на отрезке и дифференцируема на интервале, причём #eq[ $h(b) = (f(b) - f(a))g(b) - (g(b) - g(a))f(b) = g(a)f(b) - f(a)g(b) = h(a)$ ] То есть $h$ удовлетворяет всем условиям теоремы Ролля. Требуемое доказано. ] #theorem("Лагранжа о среднем")[ Если $f$ непрерывна на $[a, b]$, дифференцируема на $(a, b)$, то #eq[ $exists c in (a, b) : space (f(b) - f(a)) / (b - a) = f'(c)$ ] ] #proof[ В обобщённой теореме о среднем возьмём $g(x) = x$. ] #theorem( "Коши о среднем", )[ Если $f, g$ непрерывны на $[a, b]$, дифференцируемы на $(a, b)$ и $forall x in (a, b) : g'(x) != 0$, то #eq[ $exists c in (a, b) : space (f(b) - f(a)) / (g(b) - g(a)) = (f'(c)) / (g'(c))$ ] ] #proof[ Очевидная интерпретация обобщённой теоремы о среднем. Необходимо уточнить лишь, почему $g(b) - g(a) != 0$, чтобы мы смогли поделить на него. Если бы $g(b) = g(a)$, то по теореме Ролля $exists c : space g'(c) = 0$, что противоречит с условием текущей теоремы. ]
https://github.com/YakBarber/resume
https://raw.githubusercontent.com/YakBarber/resume/master/resume.typ
typst
// document-level formatting {{{1 #set page( margin: 0.5in, paper: "us-letter", ) #set text(9pt) #show link: content => underline(text(blue)[#content]) // function definitions {{{1 #let make_header(place, role, dates) = [ #if role=="" [ == #place #h(1fr) #dates ] else [ == #place, _#role _ #h(1fr) #dates ] ] // header {{{1 #columns(2)[ = #text(size: 24pt)[<NAME>, PhD] #colbreak() #align(right)[ Phone: (845) 702-2072 \ Email: <EMAIL> \ Code: #link("https://github.com/yakbarber") ]] #line(length: 100%) // }}} // ----------- = WORK EXPERIENCE // {{{1 #make_header("More More Ai", "", "Jan 2024 to Present") // {{{2 - Took ownership of legacy codebase (Python+Pandas, Javascript+Svelte, SQL) and developed it into a successful product prototype. - Held pair programming sessions with non-technical designers to identify enhancements and rapidly iterate through potential solutions. - Debugged database, data pipeline, continuous integration issues on AWS. //- did more work on the codebase to EXPAND USABILTY or whatever #make_header("Electra Inc", "", "Sep 2023 to Jun 2024") // {{{2 - Designed and prototyped kW-scale power inverters for home appliance battery backup and grid-tied systems. - Built a prototype sine-wave generator on STM32 in Rust for PWM control of H-bridges. //- Designed, populated, and tested multiple PCBs for handling high current signals. //- Supported writing grant applications as a technical resource on battery long-term behavior and safety. #make_header("Liminal Insights Inc (formerly Feasible Inc)", "Co-founder", "Apr 2016 to Feb 2023") // {{{2 _Entrepreneurship_ - Grew the company as a founding member of leadership from two full-time employees to 37 over 7 years. - Contributed to the development of an equitable and robust hiring process for technical contributors, led team growth as a hiring manager, and participated in the hiring process for roles across the company. - Developed and nurtured a deliberate company culture built around trust, data-driven decisions, well-being, and mutual understanding. - Researched and implemented project management software (Wrike) across the company. - Remained a major technical contributor and thought leader through the growth of the company from an academic research project to a commercial success with customer contracts for in-line manufacturing equipment. _Research & Development_ - Designed, fabricated, and automated ultrasonic measurement prototype equipment for battery inspection by integrating custom electronics and software; optimizing measurement performance; and providing support during equipment deployments. - Built and maintained the production codebase for acoustic and electrochemical data acquisition, including backend data conversion and storage, hardware orchestration, microcontroller firmware, and multiple frontends intended for a range of audiences. //Since my departure, the codebase continues to be the backbone for existing commercial products. - Designed, implemented, and expanded company-wide data ingress pipelines, relational databases, and cloud-based data science tooling in AWS using Terraform to meet internal and external customer requirements. - Developed and maintained customer facing bespoke REST APIs for interacting with software and hardware products. - Regularly performed system-scale debugging across data processing and control software, microcontrollers, ultrasonic hardware, and power electronics to identify the root cause of data anomalies. - Configured, hardened, and maintained company office networking and IT infrastructure, including set up and company-wide roll-out of an on-premises VPN. - Designed and built technology demos to highlight product features and address specific customer pain points. _Technical Leadership_ - Co-invented battery analysis and inspection technologies that have resulted in seven granted patents and several additional patents pending. - Authored extensive technical documentation and taught core concepts to the broader company through talks, presentations, and demos. - Collaborated across departments to resolve hardware and software issues, develop product requirements, and develop and implement tools to reduce friction in the team's workflow. - Performed installations, training, and support for on-site prototype deployments at customer sites. - Led the successful completion of multiple government grants and projects, resulting in significant additional follow-on funding. #make_header("Princeton University", "Postdoctoral Researcher", "Oct 2015 to Apr 2016") // {{{2 - Developed high-voltage ultrasonic pulser/receivers, multiplexers, and control software for the acoustic analysis of batteries. //#make_header("Microsoft Research", "Research Intern", "Jun 2015 to Sep 2015") // {{{2 //- Designed and manufactured flexible batteries with several different chemistries. //- Designed multilayer PCBs for Bluetooth Low Energy (BLE) applications, solar energy harvesting, battery cycling, and AC-DC and DC-DC power conversion. #make_header("Princeton University", "Graduate Researcher", "Jun 2013 to May 2015") // {{{2 - Built and designed an automated, large-scale spray deposition system. - Developed a multi-material reactive spray process to synthesize arbitrary electrode materials on-surface. - Synthesized Li-ion electrode material using an adjustable combination of reactants and conductive filler. #make_header("The City College of New York", "Graduate Researcher", "Jan 2010 to May 2015") // {{{2 - Discovered a novel film treatment to prevent dewetting of a polymer dielectric film. - Developed a spray deposition process for nanoparticle dielectric materials for thin film capacitors. - Designed open-sourced hardware and software for inexpensive electrochemical testing. // #make_header("Princeton University", "Assistant in Instruction", "Jul 2013 to Jan 2014") // {{{2 //- Designed lab exercises to teach basic thermodynamics, electronics, and programming. //- Performed teaching assistant duties including hands-on teaching of basic electronics and programming. #make_header("Palo Alto Research Center (PARC)", "Research Intern", "Jan to Jun 2013") // {{{2 - Designed and authored in-house software for data acquisition, data analysis, and image analysis. - Performed a systematic analysis of gravure printed conductors, dielectrics, and semiconductors. //#make_header("SUNY Orange County Community College", "Professional Tutor", "Jan 2009 to Dec 2010") // {{{2 //- Tutored individual students in math, chemistry, and physics. //- Utilized extensive practical knowledge and patience to tailor each tutoring session to the student's learning style. //- Received ubiquitously positive feedback and reviews from students in all fields. /// }}}2 #pagebreak() #line(length: 100%) // }}}1 = EDUCATION // {{{1 #make_header("Recurse Center","","Jul to Aug 2023") // {{{2 - Extended proficiency in Python, Haskell, Rust, and JavaScript through pair-programming, discussions, and coding challenges. - Learned about binary file formats by reverse-engineering and decoding an e-ink tablet file format, and #link("https://github.com/yakbarber/remarkable-file-format")[thoroughly documenting it]. - Developed a proof-of-concept #link("https://github.com/yakbarber/rmconvert")[bi-directional conversion tool] in Rust for the decoded file format and live-demonstrated conversion to/from SVG. - Pair-programmed, participated in technical study groups, and communicated everything I learned to others. #make_header("Activate Fellowship (formerly Cyclotron Road)","Cohort 2016, as Feasible Inc","Apr 2016 to Apr 2018") // {{{2 - Pitched early-stage investors and represented my company and the fellowship program at trade shows, conferences, and events. - Attended entrepreneurial workshops and talks ranging from commercialization to hiring to business development taught by diverse leaders from across the Bay Area startup ecosystem. - Interviewed potential customers from and performed market research into the battery and EV industries. - Prepared business plans, product one-pagers and spec sheets, and grant applications. #make_header("City College of New York, CUNY","", "Sep 2009 to Apr 2015") // {{{2 - PhD in Chemical Engineering (2015) - Master of Engineering in Chemical Engineering (2011) - Research focus: Electrochemical testing, printed electronics and batteries, and depositon methods @barry@barry2. #make_header("University at Buffalo, SUNY","", "Sep 2004 to Apr 2008") // {{{2 - Bachelor of Science in Chemical Engineering (2008) #line(length: 100%) // }}}1 = CORE SKILLSET // {{{1 - Self-taught expertise in full-stack programming, electronics and circuit design, hardware hacking, and the use of software to interface with scientific equipment. - A lifetime of taking things apart and putting them back together. - A deep multidisciplinary approach to problem solving. - A curiosity-driven do-it-yourself attitude that leads to unique solutions to difficult problems. - 8 years of experience with battery inspection and performance analysis using traditional electrical methods and non-destructive acoustic inspection. - Experience in authoring and maintaining software for research and commercial audiences. - Experience building, scaling, and maintaining data pipelines in the cloud and on-device. - Academic background in chemical engineering, with a research focus on printed electronics and batteries. = PROFICIENCIES // {{{1 - *Languages:* Fluency in Rust, Python (NumPy, Pandas, Matplotlib, Flask), Haskell, C, TypeScript/JavaScript, Elm, Terraform, and SQL. Comfortable with Bash, ZSH, Perl, Elixir, Erlang, Clojure/Lisp, and others. - *Databases:* PostgreSQL, MySQL/MariaDB, SQLite3, Redis, Mongo, Aurora. - *Misc:* Linux, AWS (Console, RDS, EB, EC2, S3, etc), Docker, Wrike, Jira+Confluence+Trello, office suites, RS-232/serial, GPIO, Arduino/ATMega, STM32, REST APIs. //- Frameworks/Libaries: Python (incl. NumPy, SciPy, Pandas, scikit-learn, Flask), Rust, TypeScript, JavaScript, Elm, Haskell, Terraform, AWS, Docker, SQL (PostgreSQL, MySQL, SQLite), Linux, Bash, Erlang, RS-232, Wrike, Jira+Confluence, office suites, Arduino/ATMega, REST API use and development //#pagebreak() #line(length: 100%) = SELECTED PUBLICATIONS // {{{1 _Full list: #link("https://orcid.org/0000-0002-9696-8766")_ #bibliography("citations.bib", title: none, full:true) //#hide[@barry, @barry2, @meta, @bb, @films]
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap5/5_power_calculations.typ
typst
Other
#import "../../core/core.typ" === Power calculations When calculating the power dissipation of resistive components, use any one of the three power equations to derive the answer from values of voltage, current, and/or resistance pertaining to each component: #image("static/10021.png") This is easily managed by adding another row to our familiar table of voltages, currents, and resistances: #image("static/10084.png") Power for any particular table column can be found by the appropriate Ohm\'s Law equation (#emph[appropriate] based on what figures are present for E, I, and R in that column). An interesting rule for total power versus individual power is that it is additive for #emph[any] configuration of circuit: series, parallel, series/parallel, or otherwise. Power is a measure of rate of work, and since power dissipated #emph[must] equal the total power applied by the source(s) (as per the Law of Conservation of Energy in physics), circuit configuration has no effect on the mathematics. #core.review[ Power is additive in #emph[any] configuration of resistive circuit: $ P_"Total" = P_1 + P_2 + ... + P_n $ ]
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/src/impl/impl.typ
typst
Apache License 2.0
#import "unit.typ": unit, tothe, raiseto, qualifier #import "num/num.typ": num #import "qty.typ": qty #import "array.typ": num-list, num-product, num-range, qty-list, qty-product, qty-range #import "complex.typ": complex #import "angle.typ": ang
https://github.com/madhank93/typst-resume-template
https://raw.githubusercontent.com/madhank93/typst-resume-template/main/john_doe.typ
typst
#import "templates/template.typ": * #show: resume.with( author: ( firstname: "John", lastname: "Doe", positions: ("software engineer", "devops specialist"), contact: ( phone: "+1 123 456 7890", email: "<EMAIL>", github: "johndoe", linkedin: "johndoe" ), professional_summary: [ - Experienced software engineer with a focus on cloud technologies - Skilled in Python, JavaScript, and DevOps practices - #lorem(10) *#lorem(5)* #lorem(10) - #lorem(15) *#lorem(3)* #lorem(10) ], experience_details: ( job1: ( company: "Tech Corp", location: "New York, NY", title: "Senior Software Engineer", duration: "July, 2020 - Present", work_summary: [ - #lorem(10) *#lorem(5)* #lorem(10) - #lorem(15) *#lorem(5)* #lorem(15) - #lorem(20) *#lorem(5)* #lorem(20) ] ), job2: ( company: "DC Corp", location: "Dallas, TX", title: "Senior Software Engineer", duration: "Jan, 2010 - June, 2020", work_summary: [ - #lorem(15) *#lorem(5)* #lorem(15) - #lorem(10) *#lorem(5)* #lorem(10) - #lorem(20) *#lorem(5)* #lorem(20) ] ), job3: ( company: "Avengers Corp", location: "New Jersey, NY", title: "Senior Software Engineer", duration: "Aug, 2000 - Dec, 2010", work_summary: [ - #lorem(20) *#lorem(5)* #lorem(20) - #lorem(10) *#lorem(5)* #lorem(10) - #lorem(15) *#lorem(5)* #lorem(15) ] ), ), certifications: [ - *AWS* Certified Solutions Architect *SAA-C03* - *Google* Cloud Professional Cloud Architect - Certified Kubernetes Application Developer (*CKAD*), CNCF - Certified Kubernetes Administrator (*CKA*), CNCF ], skills: [ *Programming:* Python, JavaScript, Go \ *DevOps:* Docker, Kubernetes, Terraform \ *Cloud:* AWS, Google Cloud Platform, Azure \ ], education: [ *_Bachelor of Science in Computer Science_*, _University of Technology_ #h(1fr) _May, 1995 - July, 2000_ ] ) )
https://github.com/maxgraw/bachelor
https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/6-evaluation/discussion.typ
typst
In diesem Kapitel werden die Ergebnisse der Evaluation der Augmented Reality Konstruktionsumgebung für Möbelsysteme auf Basis von WebXR kritisch beleuchtet. Ziel der Evaluation war es, eine gute User Experience der Anwendung zu validieren. Die Evaluation wurde mithilfe des UEQ-Fragebogens durchgeführt. Hierbei muss zunächst die Skala von -3 bis +3 betrachtet werden. In der Praxis wird diese Skala oft nicht vollständig ausgeschöpft. Realistischer ist die Verwendung einer Skala von -2 bis +2 @ueq-tool. Innerhalb dieser Skala werden Werte zwischen -0,8 und 0,8 als neutral angesehen, während Werte > 0,8 eine positive und Werte < -0,8 eine negative Bewertung darstellen. Die Dimension der Attraktivität, welche den Gesamteindruck der Anwendung widerspiegelt, erreichte einen Durchschnittswert von 1,38. Im Vergleich zu den Benchmark-Daten des UEQ liegt dieser Wert über dem Durchschnitt und kann somit in den oberen 25% der Benchmark-Daten eingeordnet werden. Diese Bewertung zeigt eine grundsätzlich positive Wahrnehmung der Anwendung und dessen Nutzung. Die pragmatische Qualität der Anwendung, die Aspekte wie die Nützlichkeit und Effizienz der Anwendung bewertet, erzielte einen Durchschnittswert von 1,62. Dieser liegt deutlich über dem neutralen Wert von 0,8 und lässt darauf schließen, dass die Usability der Anwendung als positiv bewerten lässt. Die hedonische Qualität, welche die User Experience der Anwendung misst, erhielt einen Durchschnittswert von 1,33. Auch dieser Wert liegt deutlich im positiven Bereich liegt jedoch unter der Bewertung der Usability. Dieser Wert stellt zwar eine positive Bewertung dar, jedoch scheinen Probleme in Bezug auf die User Experience zu existieren. In @appendix-responseConfidence werden die Konfidenzintervalle für die verschiedene Skalen bei einem Signifikanzniveau von $p=0.05$ basierend auf einer Stichprobengröße von $N=21$ dargestellt. Die Dimension "Effizienz" weißt die geringste Standardabweichung von 0.520 auf. Die Dimensionen "Attraktivität" und "Steuerbarkeit" weisen eine moderate Streuung auf. Die Dimensionen "Durchschaubarkeit", "Stimulation" und "Originalität" weisen die größte Streuung auf. Hierbei ist insbesondere die Dimension "Originalität" hervorzuheben, die die größte Streuung aufweist. Die Gründe für die teilweise hohe Streuung können sowohl in der unterschiedlichen Wahrnehmung der Anwendung als auch in der Stichprobengröße liegen. Durch die Einbeziehung der Streuung können die zuvor gesehenen Unterschiede in der Bewertung der Usability und User Experience besser begründet werden. Die Dimensionen "Stimulation" und "Originalität" der User Experience weisen die größte Streuung auf und die niedrigsten Bewertungen mit 1.37 bei der Stimulation und 1.29 bei der Originalität. Daraus lässt sich eine gewisse Diskrepanz zwischen Usability und User Experience ableiten. Jedoch sind alle Werte im Vergleich mit den Benchmark Daten positiv zu bewerten und liegen deutlich über dem neutralen Wert von 0,8. Die Ergebnisse der Evaluation zeigen, dass die Anwendung positiv bewertet wurde. Diese Ergebnisse werden durch die Studie von <NAME> unterstützt. Der Fokus lag hierbei auf dem gesamten Shop-System, jedoch wurde auch die AR-Anwendung bewertet. Es wurden technische Probleme sowie Usability-Schwierigkeiten festgestellt. Dennoch wurde die Anwendung im Kontext der Entscheidungsunterstützung als hilfreich bewertet. Das kritische Feedback hinsichtlich der Anwendung deckt sich mit den Anmerkungen aus der Evaluation. Hierbei wurden technische Probleme wie die Stabilität des Trackings und die Registrierung der Eingaben hervorgehoben, welche die Usability und User Experience negativ beeinflussen.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/rivet/0.1.0/gallery/example2.typ
typst
Apache License 2.0
#import "../src/lib.typ": schema, config #let example = schema.load("/gallery/example2.yaml") #schema.render(example, config: config.blueprint( full-page: true, left-labels: true ))
https://github.com/lukejcollins/cv
https://raw.githubusercontent.com/lukejcollins/cv/main/README.md
markdown
MIT License
# My CV Below you can download my CV as a PDF: <table cellspacing="0" cellpadding="0"> <tr> <th> <a href="https://github.com/lukejcollins/cv/releases/download/latest/english.pdf"> CV </a> </th> </tr> <tr> <td> <a href="https://github.com/lukejcollins/cv/releases/download/latest/english.pdf"> <img src="https://github.com/lukejcollins/cv/releases/download/latest/english-thumbnail.png" alt="English CV"> </a> </td> </tr> </table> The PDF (and the thumbnail) is automatically built and deployed on each push using my GitHub Actions pipeline [here](./.github/workflows/build-cv.yaml). ## Compile it yourself Requires [Typst](https://github.com/typst/typst) to be installed, as well as the fonts [Fira Sans](https://github.com/mozilla/Fira), [Fira Code](https://github.com/tonsky/FiraCode) and [Font Awesome](https://github.com/FortAwesome/Font-Awesome). ```sh git clone https://github.com/lukejcollins/cv.git typst compile english.typ ``` ## Licence [MIT](./LICENSE)
https://github.com/r8vnhill/apunte-bibliotecas-de-software
https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/opening.typ
typst
Iniciar un proyecto requiere considerar varios _aspectos críticos_, incluyendo la selección de tecnologías y la planificación del tiempo y estructura del proyecto. Sin embargo, un factor frecuentemente subestimado es el cambio. El cambio es inevitable y debe considerarse desde el inicio para evitar que el proyecto se vuelva obsoleto antes de su finalización. Esta consideración es igualmente crucial al desarrollar un curso. Si no anticipamos los cambios, el contenido del curso podría quedar desactualizado antes de que esté completo. Por esta razón, hemos diseñado este curso para ser modular y fácil de actualizar. Cada unidad se compone de secciones independientes que pueden ser modificadas sin afectar el resto del contenido. De esta forma, podemos mantener el curso actualizado y relevante para lxs estudiantes. Al hablar de la preparación de un curso, es esencial elegir las tecnologías adecuadas. Para este proyecto, hemos seleccionado C\# y Blazor para el desarrollo del sitio web, Cloudflare Pages para el alojamiento, Kotlin como lenguaje de programación y Typst para este apunte. El sitio web puede ser encontrado en #link("https://ravenhill.pages.dev").
https://github.com/OrangeX4/typst-sympy-calculator.typ
https://raw.githubusercontent.com/OrangeX4/typst-sympy-calculator.typ/main/typst-sympy-calculator.typ
typst
MIT License
#let hidden(content) = {} // matrix #let cmat(..args) = { let mat = if (type(args.pos().at(0)) != "array") { (args.pos(),) } else { args.pos() } let mat_t = () for j in range(mat.at(0).len()) { mat_t.push(()) for i in range(mat.len()) { mat_t.at(j).push(mat.at(i).at(j)) } } math.mat(..mat_t) } #let eye(n) = { let n = if (type(n) == "content") { int(n.text) } else { int(n) } let matrix = () for i in range(n) { matrix.push(()) for j in range(n) { if (i == j) { matrix.at(i).push(1) } else { matrix.at(i).push(0) } } } math.mat(..matrix) } #let diag(..args) = { let args = args.pos() let n = args.len() let matrix = () for i in range(n) { matrix.push(()) for j in range(n) { if (i == j) { matrix.at(i).push(args.at(j)) } else { matrix.at(i).push(0) } } } math.mat(..matrix) } // functions #let derivative(expr, var) = $(dif)/(dif var) expr$ #let sign = math.op("sign") #let evalat(body) = math.lr(body + "|") #let rowswap = math.op("rowswap") #let colswap = math.op("colswap") #let rowscale = math.op("rowscale") #let colscale = math.op("colscale") // accents #let hdot(a) = math.accent(a, math.dot) #hidden[ ```typst-calculator @func_mat() def convert_cmat(matrix): return sympy.Matrix(matrix).T @func() def convert_derivative(expr, var): return sympy.Derivative(expr, var) @func() def convert_eye(n): return sympy.eye(n) @func() def convert_diag(*args): return sympy.diag(*args) @func() def convert_sign(a): return sympy.sign(a) @func() def convert_rowswap(matrix, row1, row2): row1, row2 = row1 - 1, row2 - 1 matrix[row1, :], matrix[row2, :] = matrix[row2, :], matrix[row1, :] return matrix @func() def convert_colswap(matrix, col1, col2): col1, col2 = col1 - 1, col2 - 1 matrix[:, col1], matrix[:, col2] = matrix[:, col2], matrix[:, col1] return matrix @func() def convert_rowscale(matrix, row, ratio): row = row - 1 matrix[row, :] = ratio * matrix[row, :] return matrix @func() def convert_colscale(matrix, col, ratio): col = col - 1 matrix[:, col] = ratio * matrix[:, col] return matrix ``` ]
https://github.com/GYPpro/DS-Course-Report
https://raw.githubusercontent.com/GYPpro/DS-Course-Report/main/Templete/catelog.typ
typst
#set heading( numbering: "1.1.1" ) #outline( title:[#smallcaps("Catalogue")\ #h(1fr)] );
https://github.com/sa-concept-refactoring/doc
https://raw.githubusercontent.com/sa-concept-refactoring/doc/main/chapters/glossary.typ
typst
= Glossary / AST: Abbreviation for Abstract Syntax Tree. It is a hierarchical representation of source code structure, capturing syntax and semantics. / IDE: Integrated Development Environment. Software application that provies comprehensive facilities for software development. / LLVM: Abbreviation for Low Level Virtual Machine. A set of compiler and toolchain technologies. / Tweak: In the context of the clangd language server, it is a small, context-sensitive refactoring.
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/145.%20todo.html.typ
typst
todo.html The Top of My Todo List April 2012A palliative care nurse called <NAME> made a list of the biggest regrets of the dying. Her list seems plausible. I could see myself — can see myself — making at least 4 of these 5 mistakes.If you had to compress them into a single piece of advice, it might be: don't be a cog. The 5 regrets paint a portrait of post-industrial man, who shrinks himself into a shape that fits his circumstances, then turns dutifully till he stops.The alarming thing is, the mistakes that produce these regrets are all errors of omission. You forget your dreams, ignore your family, suppress your feelings, neglect your friends, and forget to be happy. Errors of omission are a particularly dangerous type of mistake, because you make them by default.I would like to avoid making these mistakes. But how do you avoid mistakes you make by default? Ideally you transform your life so it has other defaults. But it may not be possible to do that completely. As long as these mistakes happen by default, you probably have to be reminded not to make them. So I inverted the 5 regrets, yielding a list of 5 commands Don't ignore your dreams; don't work too much; say what you think; cultivate friendships; be happy. which I then put at the top of the file I use as a todo list.Japanese Translation
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/rahmenplaene/main.typ
typst
Other
#import "/src/template.typ": * = #ix("Rahmenpläne in MV", "Rahmenplan") #author[<NAME>] #include "fragen_kant.typ" #include "kompetenzen.typ" #include "themen.typ" #include "zitieren.typ" #task(key: "philosophie-ersatzfach")[Philosophie als Ersatzfach][ Erklären Sie, wofür und warum der Philosophieunterricht in Mecklenburg-Vorpommern ein "Ersatzfach" ist. ][ Laut einer kleinen Anfrage des Abgeordneten Andreas Bluhm der Fraktion DIE LINKE im Landtag Mecklenburg-Vorpommern vom 12.9.2008 gibt die Landesregierung zu verstehen, dass der Religionsunterricht ein ordentliches Unterrichtsfach ist. Jede Schule muss das Lehrfach in jedem Schuljahr erteilen. Um die negative Religionsfreiheit, d.i. das Recht, ohne Religion zu leben, zu respektieren, können SuS vom Religionsunterricht abgemeldet werden, müssen dann jedoch ein Ersatzfach besuchen: den Philosophieunterricht. ]
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/06-fourier-series/05-fourier-misc.typ
typst
#import "../../utils/core.typ": * == Солянка а ля Фурье #ticket[Свертка функций. Свойства.] #def[ $L_(2pi)^1$ --- $2pi$ периодические функции, и $norm(f)_1 := integral_(-pi)^pi abs(f(t)) dif t < +oo$. ] #def[ Если $f, g in L_(2pi)^1$, то _сверткой функций_ $f * g$ называется функция $h$ такая, что $ h(x) := integral_(-pi)^pi f(x - t) g(t) dif t. $ ] #props[ 1. $f * g = g * f$. 2. $h in L_(2pi)^1$. 3. $c_k (f * g) = 2pi c_k (f) c_k (g)$. 4. $f in L_(2pi)^p$, $g in L_(2pi)^q$, и $1/p + 1/q = 1$. Тогда $f * g in C_(2pi)$, и $norm(f * g)_oo <= norm(f)_p norm(g)_q$. 5. Если $1 <= p <= +oo$, то $norm(f * g)_p <= norm(f)_1 norm(g)_p$. ] #proof[ 1. Доказывается. 2. Рассмотрим $F(x, t) = f(x - t) g(t)$. Это измеримая функция ($RR^2 --> RR$). $ integral_(-pi)^pi integral_(-pi)^pi abs(F(x, t)) dif t dif x &= integral_(-pi)^pi underbrace(integral_(-pi)^pi abs(f(x - t)) dif x, norm(f)_1) abs(g(t)) dif t = norm(f)_1 dot norm(g)_1. \ &>= integral_(-pi)^pi abs(integral_(pi)^pi f(x - t) g(t) dif t) dif x = integral_(-pi)^pi abs(h(x)) dif x = norm(h)_1. $ Значит функция и правда суммируема в $L_(2pi)^1$ (теорема Фубини про суммируемость сечения или что-то типа того). 3. $ c_k (h) = 1/(2pi) integral_(-pi)^pi h(x) e^(-i k x) dif x = 1/(2pi) integral_(-pi)^pi integral_(-pi)^pi f(x - t) g(t) dot e^(-i k (x - t)) e^(-i k t) dif t dif x newline(=) 1/(2pi) integral_(-pi)^pi integral_(-pi - t)^(pi - t) f(y) e^(-i k y) dif y g(t) e^(-i k t) dif t = 2pi c_k (f) dot c_k (g). $ Впрочем, мы уже знали это. Коэффициенты Фурье --- это просто значения характеристических функций в целых точках. Плотность суммы независимых случайных величин --- свертка, а характеристическая функция --- произведение. Отсюда этот же факт. 4. Рассмотрим $h = f * g$. $ abs(h(x + y) - h(x)) = abs(integral_(-pi)^pi (f(x + y - t) - f(x - t)) g(t) dif t) newline(<=) integral_(-pi)^pi abs(f(x + y - t) - f(x - t)) abs(g(t)) dif t newline(<=^"Гельдер") underbrace((integral_(-pi)^pi abs(f(x + y - t) - f(x - t))^p dif t)^(1/p), (integral_(-pi)^pi abs(f(y + t) - f(t))^p dif t)^(1/p)) underbrace((integral_(-pi)^pi abs(g(t))^q dif t)^(1/q), norm(g)_q) newline(=) (integral_(-pi)^pi abs(f(y + t) - f(t))^p dif t)^(1/p) dot norm(g)_q = norm(f_y - f)_p dot norm(g)_q -->_(y -> 0) 0 $ по непрерывности сдвига. 5. Без доказательства, но вообще делается. Надо пару раз нетривиально применить неравенство Гельдера. ] #notice[ Определение свертки $ h(x) = (f * g)(x) := integral_(-pi)^pi f(x - t) g(t) dif t $ вообще говоря уже встречалось, например, в формуле для частичных сумм ряда Фурье: $ S_n (f, x) = 1/pi integral_(-pi)^pi f(x - t) D_n (t) dif t = 1/pi f * D_n. $ А значит (по линейности свертки, которую мы не обсуждали, но которая есть) $ sigma_n (f, x) = (S_0 (f, x) + S_1 (f, x) + ... + S_n (f, x))/(n + 1) = 1/pi f * Phi_n. $ ] #ticket[Аппроксимативная единица. Теорема об аппроксимативной единице (сходимость по норме в $L^p$ без доказательства).] #def[ Пусть $D$ --- множество параметров, $h_0$ --- предельная точка $D$ (в примерах, $D = NN$, $h_0 = oo$). $K_h$ --- _аппроксимативная единица_, если 1. $K_h in L_(2pi)^1$ и $integral_(-pi)^pi K_h (t) dif t = 1$ для любого $h in D$. 2. $norm(K_h)_1 <= M$ для любого $h in D$. 3. $integral_([-pi, pi] without (-delta, delta)) abs(K_h (t)) dif t -->_(h -> h_0) 0$ для любого $delta in (0, pi)$. $K_h$ называется _усиленной аппроксимативной единицей_, если также есть свойство 4. $esssup_([-pi, pi] without (-delta, delta)) abs(K_h (t)) -->_(h -> h_0) 0$ для любого $delta in (0, pi)$. Это свойство сильнее свойства $3$. ] #example[ $1/pi Phi_n$ --- усиленная аппроксимативная единица. ] #th(name: "об аппроксимативной единице")[ $K_h$ --- аппроксимативная единица. 1. Если $f in C_(2pi)$, то $f * K_h arrows_(h -> h_0) f$. 2. Если $f in L_(2pi)^p$, $1 <= p < +oo$, то $norm(f * K_h - f)_p -->_(h -> h_0) 0$. 3. Если $K_h$ --- усиленная, а $f$ суммируема и непрерывна в $x_0$, то $f * K_h (x_0) -->_(h -> h_0) f(x_0)$. ] #proof[ Для начала распишем: $ f * K_h (x) - f(x) = integral_(-pi)^(pi) f(x - t) K_h (t) dif t - integral_(-pi)^pi f(x) K_h (t) dif t = integral_(-pi)^pi (f(x - t) - f(x)) K_h (t) dif t. $ 1. $ abs(integral_(-pi)^pi (f(x - t) - f(x)) K_h (t) dif t) <= integral_(-pi)^pi abs(f(x - t) - f(x)) abs(K_h (t)) dif t = underbrace(integral_(-delta)^delta, I_1) + underbrace(integral_([-pi, pi] without (-delta, delta)), I_2). $ Оценим $I_1$: $ integral_(-delta)^delta underbrace(abs(f(x - t) - f(x)), <= eps) abs(K_h (t)) dif t <= eps integral_(-delta)^delta abs(K_h (t)) dif t <= M eps. $ Теперь $I_2$. Так как $f in C_(2pi)$, $abs(f) <= C$. Пусть $E = [-pi, pi] without (-delta, delta)$ $ integral_E underbrace(abs(f(x - t) - f(x)), <= 2C) abs(K_h (t)) dif t <= 2C integral_E abs(K_h (t)) dif t --> 0. $ 3. Если взять $delta > 0$ по $eps > 0$ из определения непрерывности в $x$, то $I_1$ оценивается так же. $I_2$ оценим так: $ integral_E abs(f(x - t) - f(x)) abs(K_h (t)) dif t <= esssup_(t in E) abs(K_h (t)) dot underbrace(integral_E abs(f(x - t) - f(x)) dif t, <= 2 integral_(-pi)^pi abs(f(t)) dif t). $ Первый множитель стремится к нулю так как $K_h$ --- усиленная аппроксимативная единица. 2. Без доказательства. Надо рассмотреть функцию $g(t) = integral_(-pi)^pi abs(f(x - t) - f(x)) dif x$. Доказать, что $g in C_(2pi)$, затем сослаться на первый пункт, применив неравенство Гельдера, и все получится. Но в интересах времени, Храбров доказательство не привел. ] #ticket[Суммирование рядов Фурье по Чезаро. Теорема Фейера. Следствия. Теоремы Вейерштрасса о приближении непрерывных функций.] #th(name: "Фейера")[ 1. Если $f in C_(2pi)$, то $sigma_n (f) arrows f$ (где $sigma_n (f) = (S_0 (f) + ... + S_n (f))/(n + 1)$). 2. Если $f in L_(2pi)^p$, $1 <= p < +oo$, то $norm(sigma_n (f) - f)_p --> 0$. 3. Если $f in L_(2pi)^1$ и непрерывна в $x$, то $sigma_n (f, x) --> f(x)$. ] #proof[ Применим предыдущую теорему для $K_h = 1/pi Phi_n$. ] #follow(plural: true)[ 1. $f in L_(2pi)^1$, $f$ непрерывна в $x$. Если ряд Фурье для функции $f$ в точке $x$ сходится, то он сходится к $f(x)$. 2. Если $f in C_(2pi)$ и ряд Фурье для функции $f$ сходится, то он сходится к $f$. 3. (*Теорема единственности*) Если $f in L_(2pi)^1$, и все коэффициенты Фурье $f$ равны нулю, то $f = 0$ почти везде. 4. Ряд Фурье для $f in L^2_(2pi)$ сходится к $f$ по норме в $L_(2pi)^2$. Равносильно: тригонометрическая система --- базис в $L_(2pi)^2$. ] #proof[ 1. Пусть $S_n (f, x) --> a$, тогда $sigma_n (f, x) --> a$, но мы знаем, что $sigma_n (f, x) --> f(x)$. 2. Вроде верно... 3. $S_n (f) = 0$, то $sigma_n (f) = 0$, и $norm(sigma_n (f) - f)_1 = norm(f)_1 --> 0$. 4. Будем доказывать, что тригонометрическая система --- базис. Достаточно понять, что система --- полная, то есть если функция $g$ ортогональна любому элементу тригонометрической системы, то $g = 0$ почти везде. А это равносильно тому, что $c_k (g) = 1/(2pi) integral_(-pi)^pi g(x) e^(-i k x) dif x = 1/(2pi) dotp(g, e^(i k x)) = 0$. ] #th(name: "Вейерштрасса")[ Пусть $f in C_(2pi)$, $eps > 0$. Тогда существует такой тригонометрический многочлен $T$, что $abs(T(x) - f(x)) < eps$ во всех точках $x in RR$. ] #proof[ Однажды Эрнест Хемингуэй поспорил, что напишет самый короткий рассказ, способный растрогать любого. Он выиграл спор показав лишь $ sigma_n (f) arrows f. $ ] #th(name: "Вейерштрасса (другая, но на самом деле та же самая)", label: "weierstrass2")[ $f in C[a, b]$, $eps > 0$. Тогда существует многочлен $P$ такой, что $abs(P(x) - f(x)) < eps$ для любого $x in [a, b]$. ] #proof[ Пользуясь преобразованием $[0, pi] --> [a, b]$ вида $x arrow.bar.long a + (b - a)/pi x$ будем рассматривать функцию на $[0, pi]$. А потом замкнем ее до $2pi$-периодической: $ g(x) = cases(f(x)\, x in [0, pi], f(-x)\, x in [-pi, 0]). $ Приблизим $g in C_(2pi)$ тригонометрическим многочленом $T$ с точностью до $eps$: $ T(x) = a_0 + sum_(k = 0)^n (a_k cos k x + b_k sin k x). $ Разложим тригонометрические функции в ряд Тейлора, и приблизим префиксами с хорошей точностью. ] #notice[ Пусть $f in C[0, 1]$. Тогда $ B_n (f, x) = sum_(k = 0)^n f(k/n) C_n^k x^k (1 - x)^(n - k) arrows f. $ $B_n (f, x)$ называется _многочленом Бернштейна_. Вам это может напоминать какое-то распределение из теорвера... Собственно, это можно доказать в теорвере. Вот так можно явно выписывать эти многочлены. Частные случаи многочленов Бернштейна для $n = 2$ и $n = 3$ называются _кривыми Безье_. ]
https://github.com/dasayan05/typst-ai-conf-templates
https://raw.githubusercontent.com/dasayan05/typst-ai-conf-templates/master/neurips/paper.typ
typst
MIT License
#import "neurips.typ": manuscript #show: manuscript.with( title: [Formatting Instructions For NeurIPS 2023], authors: ( [ *Author 1*\ Affiliation 1\ Address 1\ `<EMAIL>` ], [ *Author 2*\ Affiliation 2\ Address 2\ `<EMAIL>` ], [ *Author 3*\ Affiliation 3\ Address 3\ `<EMAIL>` ] ), abstract: [ The abstract paragraph should be indented $1/2$~inch (3~picas) on both the left- and right-hand margins. Use 10~point type, with a vertical spacing (leading) of 11~points. The word *Abstract* must be centered, bold, and in point size 12. Two line spaces precede the abstract. The abstract must be limited to one paragraph. ] ) = Submission of papers to NeurIPS 2023 Please read the instructions below carefully and follow them faithfully. *Important:* This year the checklist will be submitted separately from the main paper in OpenReview, please review it well ahead of the submission deadline: #link("https://neurips.cc/public/guides/PaperChecklist"). == Style Papers to be submitted to NeurIPS 2023 must be prepared according to the instructions presented here. Papers may only be up to *nine* pages long, including figures. Additional pages #emph[containing only acknowledgments and references] are allowed. Papers that exceed the page limit will not be reviewed, or in any other way considered for presentation at the conference. The margins in 2023 are the same as those in previous years. Authors are required to use the NeurIPS LaTeX or #emph[Typst] style files obtainable at the NeurIPS website as indicated below. Please make sure you use the current files and not previous versions. Tweaking the style files may be grounds for rejection. == Retrieval of style files The style files for NeurIPS and other conference information are available on the website at #align(center)[ #link("http://www.neurips.cc/") ] The file `neurips_2023.pdf` contains these instructions and illustrates the various formatting requirements your NeurIPS paper must satisfy. The only supported style file for NeurIPS 2023 is `neurips_2023.sty` or `neurips.typ`. #strong[Previous style files for `\LaTeX2.09`, Microsoft Word, and RTF are no longer supported!] = General formatting instructions The text must be confined within a rectangle 5.5~inches (33~picas) wide and 9~inches (54~picas) long. The left margin is 1.5~inch (9~picas). Use 10~point type with a vertical spacing (leading) of 11~points. Times New Roman is the preferred typeface throughout, and will be selected for you by default. Paragraphs are separated by $1/2$~line space (5.5 points), with no indentation.