repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/catppuccin/typst
https://raw.githubusercontent.com/catppuccin/typst/main/src/catppuccin.typ
typst
MIT License
#import "flavors.typ": latte, frappe, macchiato, mocha #import "valkyrie/typst-schema.typ": * #import "@preview/valkyrie:0.2.1" as z /// The available flavors for Catppuccin. Given simply by the dictionary /// ```typ /// #let themes = ( /// latte: "latte", /// frappe: "frappe", /// macchiato: "macchiato", /// mocha: "mocha", /// ) ///``` /// These names are used to set the theme of the document. To access the accented names, you can use @@get-palette() and access the `name` key. /// /// -> dictionary #let themes = ( latte: "latte", frappe: "frappe", macchiato: "macchiato", mocha: "mocha", ) /// Get the color palette for the given theme. The returned dictionary has keys as defined in @flavor-schema[Flavor Schemas]. /// /// ==== Example /// #example( /// ```typ /// #let items = themes.values().map(theme => [ /// #let palette = get-palette(theme) /// #let rainbow = ( /// "red", "yellow", "green", /// "blue", "mauve", /// ).map(c => palette.colors.at(c).rgb) /// /// #let fills = ( /// gradient.linear(..rainbow), /// gradient.radial(..rainbow), /// gradient.conic(..rainbow), /// ) /// /// #stack( /// dir: ttb, /// spacing: 4pt, /// text(palette.name + ":"), /// stack( /// dir: ltr, /// spacing: 3mm, /// ..fills.map(fill => square(fill: fill)) /// ) /// ) /// ]) /// /// #grid(columns: 1, gutter: 1em, ..items) /// ```, ratio: 1.5) /// /// - theme (string): The theme to get the palette for. The dict @@themes can be used to simplify this. /// -> dictionary #let get-palette(theme) = { assert(theme in themes.values(), message: "Invalid theme: " + repr(theme)) if theme == themes.latte { latte } else if theme == themes.frappe { frappe } else if theme == themes.macchiato { macchiato } else if theme == themes.mocha { mocha } else { panic("Invalid theme: " + theme) } } #let code-block-config-schema = z.dictionary(( inset: inset-schema(default: 7pt), outset: outset-schema(default: (y: 3pt)), radius: radius-schema(default: 3pt), breakable: z.boolean(default: false), width: z.either( rel-or-length(), z.function(), sides-schema, post-transform: (self, it) => if type(it) == dictionary and it == (:) { 0pt } else { it }, default: it => measure(it).width + 1cm, ), )) #let code-box-config-schema = z.dictionary(( inset: inset-schema(default: (x: 2pt, y: 0pt)), outset: outset-schema(default: (y: 2pt)), radius: radius-schema(default: 3pt), )) #let config-code-blocks(theme, code-block: true, code-syntax: true, block-config: (:), inline-config: (:), body) = [ #let palette = get-palette(theme) #let tmTheme = "tmThemes/" + theme + ".tmTheme" #set raw(theme: tmTheme) if code-syntax #show raw.where(block: false): it => [ #let config = z.parse(inline-config, code-box-config-schema) #box(..config, it) ] #show raw.where(block: true): it => [ #let config = z.parse(block-config, code-block-config-schema) + (fill: palette.colors.crust.rgb) #if type(config.at("width")) == function { config.insert("width", (config.at("width"))(it)) } #set align(center) #block(..config, it) ] #body ] /// Configure your document to use a Catppuccin flavor. /// /// ==== Example: /// ```typ /// #import "@preview/catppuccin": catppuccin, themes /// /// #show: catppuccin.with(themes.mocha, code-block: true, code-syntax: true) /// ``` /// This should be used at the top of your document. /// /// - theme (string): The flavor to set. /// - code-block (boolean): Whether to styalise code blocks. /// - code-syntax (boolean): Whether to use Catppuccin syntax highlighting in code blocks. /// - body (content): The content to apply the flavor to. /// -> content #let catppuccin(theme, code-block: true, code-syntax: true, body) = [ #let palette = get-palette(theme) #set page(fill: palette.colors.base.rgb) #set text(fill: palette.colors.text.rgb) #show: config-code-blocks.with(theme, code-block: code-block, code-syntax: code-syntax) #body ]
https://github.com/supersurviveur/typst-math
https://raw.githubusercontent.com/supersurviveur/typst-math/main/CHANGELOG.md
markdown
MIT License
# Change Log All notable changes to the "typst-math" extension will be documented in this file. Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file. ## [v0.1.7] - Fix version number and publish on openvsx ## [v0.1.6] - Update dependencies ## [v0.1.5] - Fix fonts link - Add an option to remove unnecessary parentheses - Better doc for custom theme ## [v0.1.4] - Improve performances - Add tests - Fix rendering issues ## [v0.1.3] - Improve performances - Fix rendering issues - Start adding tests ## [v0.1.2] - Add incremental rendering ## [v0.1.1] - Add custom symbols in settings ## [v0.1.0] - Migration to a rust backend - Improve performance and rendering - Fix issues #8, #12-18 ## [v0.0.12] - Fix issue #11 - Correction of spelling mistakes ## [v0.0.11] - Fix issue #10 ## [v0.0.10] - Remove useless code - Add a symbol blacklist - Remove Typst LSP dependency ## [v0.0.9] - Fix function's font family ## [v0.0.8] - Add sqrt function - Add space symbols ## [v0.0.7] - Add 'dif' symbol - Symbols are now updated correctly ## [v0.0.6] - Add symbols - Add functions like `arrow()` in easy cases - Fix some rendering bugs ## [v0.0.5] - Add symbols - Add a math command to add a math equation - Fix some bugs ## [v0.0.4] - Refactor code - Add some math symbols - Add commands - Add a default light theme ## [v0.0.3] - Add some math symbols - Sometimes characters appeared twice, fixed ## [v0.0.2] - Fix fonts links ## [v0.0.1] - Initial release
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/for-02.typ
typst
Other
// Uniterable expression. // Error: 11-15 cannot loop over boolean #for v in true {}
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/document-06.typ
typst
Other
#box[ // Error: 4-18 page configuration is not allowed inside of containers #set page("a4") ]
https://github.com/spidersouris/touying-unistra-pristine
https://raw.githubusercontent.com/spidersouris/touying-unistra-pristine/main/example/example.typ
typst
MIT License
#import "@preview/touying:0.5.3": * #import "@preview/touying-unistra-pristine:1.1.0": * #show: unistra-theme.with( aspect-ratio: "16-9", config-info( title: [Title], subtitle: [_Subtitle_], author: [Author], date: datetime.today().display("[month repr:long] [day], [year repr:full]"), logo: image("../assets/unistra.svg"), ), ) #title-slide(logo: image("../assets/unistra.svg")) = Example Section Title == Example Slide A slide with *important information*. #pause === Highlight This is #highlight(fill: blue.C)[highlighted in blue]. This is #highlight(fill: yellow.C)[highlighted in yellow]. This is #highlight(fill: green.C)[highlighted in green]. This is #highlight(fill: red.C)[highlighted in red]. #hero( image("../assets/unistra.svg"), title: "Hero", subtitle: "Subtitle", hide-footer: false, ) #hero( image("../assets/cat1.jpg", width: 100%, height: 100%), txt: ( text: "This is an " + highlight(fill: yellow.C)[RTL#footnote[RTL = right to left. Oh, and here's a footnote!] hero with text and no title] + ".\n", enhanced: false, ), direction: "rtl", footnote: true, ) #gallery( image("../assets/cat1.jpg", width: auto, height: 50%), image("../assets/cat2.jpg", width: auto, height: 50%), image("../assets/cat1.jpg", width: auto, height: 50%), image("../assets/cat2.jpg", width: auto, height: 50%), title: "Gallery", captions: ( "Cat 1", "Cat 2", "Cat 1 again", "Cat 2 again", ), columns: 4, ) #focus-slide( theme: "smoke", [ This is a focus slide \ with theme "smoke" ], ) == Admonitions #slide[ This is a normal slide with *admonitions*: #brainstorming[ This is a brainstorming (in French). ] #definition[ This is a definition (in French). ] ] #focus-slide( theme: "neon", [ This is a focus slide \ with theme "neon" ], ) #focus-slide( theme: "yellow", [ This is a focus slide \ with theme "yellow" ], ) #focus-slide( c1: black, c2: white, [ This is a focus slide \ with custom colors \ Next: Section 2 ], text-color: yellow.D, ) = Section 2 == Hey! New Section! #lorem(30) === Heading 3 #lorem(10) ==== Heading 4 #lorem(80) #quote(attribution: [from the <NAME> literal translation of 1897])[ ... I seem, then, in just this little thing to be wiser than this man at any rate, that what I do not know I do not think I know either. ] #slide[ First column. #lorem(15) ][ Second column. #lorem(15) ]
https://github.com/kimushun1101/rengo2024-typst
https://raw.githubusercontent.com/kimushun1101/rengo2024-typst/main/sample.typ
typst
MIT No Attribution
// MIT No Attribution // Copyright 2024 <NAME> // https://github.com/kimushun1101/rengo2024-typst #import "libs/rengo/lib.typ": rengo, definition, lemma, theorem, corollary, proof #show: rengo.with( title: [自動制御連合講演会サンプル原稿], authors: [◯ 自動太郎,制御花子(連合大学),自動次郎 (連合会社)], etitle: [Sample Manuscript for the Japan Joint Automatic Control Conference], eauthors: [$ast$<NAME>, H.~Seigyo (Rengo Univ.), and <NAME> (Rengo Corp.)], abstract: [This document describes the information for authors such as paper submission and the style of manuscript. Only PDF manuscripts are acceptable. The PDF manuscripts should be uploaded on the conference homepage. This document is a template file for a paper, although it is not necessary to strictly follow this format.], keywords: ([Electrical paper submission], [The style of manuscript]), bibliography: bibliography("refs.yml", full: false) ) = はじめに 使用言語は日本語または英語です.原稿はA4版で2 $tilde.op$ 8ページとし, PDFファイルを電子投稿していただきます. アップロードするファイルサイズの制限は5MBとします. = 原稿の体裁 == 全体の体裁 A4用紙の(US Letterは不可),縦250 mm,横170 mmの枠内に収まるようにし てください. 余白は,上20 mm,下27 mm,左20 mm,右20 mmとします. 活字の大きさは, 日本語16ポイント, 日本語著者名・英語タイトル・英語著者名12ポイント, 章タイトル12ポイント, 節タイトル10ポイント, 本文の活字10ポイントを目安としてください. 原稿は, - 邦文タイトル(英文原稿の場合は不要) - 邦文著者名(登壇者に○印)と著者所属(英文原稿の場合は不要) - 英文タイトル - 英文著者名(登壇者に$$印)と英文著者所属 - 英文アブストラクト(100ワード程度) - 英文キーワード - 本文,参考文献 の順に書いてください. 英文キーワードまでを1段組,本文・参考文献を2段組にしてください. == 図と表 図と表は,Fig.~1,Table~1のように番号を振り (@fig:samplefig 参照),図説,図中の説明文は英文で記入してください. 本文で引用する場合も「Fig.~1に示す」などのようにFig.とTableを使用してください. #figure( placement: top, // svg, png, jpg, gif に対応しています. // eps, pdf などには対応していません.(2024.07.07) // https://typst.app/docs/reference/visualize/image/ image("fig1.svg", width: 80%), caption: [A sample figure.], ) <fig:samplefig> // #figure( // placement: bottom, // caption: [A sample table.], // table( // columns: 3, // stroke: none, // table.header( // [], // [Size (pt)], // [Font], // ), // table.hline(), // [Title], [16], [Gothic], // [Authors], [12], [Gothic], // [Section title], [12], [Gothic], // [Contents], [10], [Mincho], // [Reference], [9], [Mincho], // ) // ) <tab:fonts> 図や表中の文字は小さくなりすぎないよう気をつけてください. PDF原稿を作成する際,図の画質が劣化しないよう,注意してください. 特にMicrosoft Wordなどで原稿を作成する際,JPEG画像を貼り付けると,一度圧縮されている画像が再圧縮され画質が劣化するようです. 貼り付ける画像は,画質の良い(圧縮率の低い)画像を用いるか圧縮しない画像フォーマットを選ぶなど,各自工夫し,最終的なPDFファイルにおいて画質が劣化しないよう注意してください(300 dpi以上の画質を推奨します). == 数式関係 数式の使用例です. $ dot(x) (t) &= A x(t) + B u(t) $ <eq:system> $ y(t) &= C x(t) + D u(t) $ <eq:output> // 引用する場合には @eq:system と @eq:output としてください. == 定理環境 以下は,theorem 環境の使用例です. // ctheorems パッケージを使用しています. // Proxy などの関係でビルドできない場合には,libs フォルダーに手動ダウンロードしてお使いください. // + ctheorems-1.1.2 を https://typst.app/universe/package/ctheorems からダウンロードしてくる. // + `libs` フォルダーに展開する. // + `libs/rengo/lib.typ` で `"@preview/ctheorems:1.1.2"` となっている部分を `"libs/ctheorems-1.1.2/lib.typ"` と修正する. #theorem[ ここに定理の内容を記述して下さい.系や補題の場合も同様です. ] #proof[ ここには定理の証明を記述して下さい.証明の最後には□印がつきます. ] 定理などの文章は,もともとイタリック書体を使うようになってい ますが,和文との整合性を考えて,ローマン書体を使うように変更 しています. // #definition("用語 A")[ // 用語 A の定義を書きます. // ]<def:definition1> // #lemma("補題 B")[ // 補題 B を書きます.タイトルは省略することもできます. // ]<lem:lemma1> // #lemma[ // 補題を書きます.番号は定義や補題ごとに 1 からカウントします. // ]<lem:lemma2> // #corollary[ // 系を書きます.@def:definition1 のように,ラベルで参照することもできます. // ] = 参考文献 文献の引用は本文中に @web @ConferenceJP @Journal のように書き, 本文の最後にまとめて記述します.次のフォーマットを推奨します. @Book // 参考文献を [1, 2, 3] と表示する方法は今のところ見つけられていません(2024.07.07) #set enum(numbering: "a)") + 雑誌論文の場合\ $[$番号$]$ 著者:論文題目;雑誌名,Vol.~巻, No.~号, pp.~始ページ--終ページ (発行年) + 会議論文の場合\ $[$番号$]$ 著者:論文題目;会議論文誌名,pp.~始ページ--終ページ (発行年) + 単行本の場合\ $[$番号$]$ 著者:書名,pp.~始ページ--終ページ, 発行所 (発行年) + Websiteの場合\ $[$番号$]$ URL // 参考文献の情報は 15行目の `bibliography: bibliography("refs.yml", full: false)` で渡されます. // refs.yml に記載する. refs.bib に変更することもできますが,日本語論文の著者名がうまく表示分けができないため,日本語論文を含む参考文献リストの場合には yml で記載することを推奨します.(2024.07.07) // `full` を `true` に変更すると本文引用がされていない文献も出力される.出力確認のために `true` にしてもよいが,提出時には `false` に戻してください.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/tidy/0.3.0/src/parse-module.typ
typst
Apache License 2.0
#import "tidy-parse.typ" #import "styles.typ" /// Parse the docstrings of a typst module. This function returns a dictionary /// with the keys /// - `name`: The module name as a string. /// - `functions`: A list of function documentations as dictionaries. /// - `label-prefix`: The prefix for internal labels and references. /// The label prefix will automatically be the name of the module if not given /// explicity. /// /// The function documentation dictionaries contain the keys /// - `name`: The function name. /// - `description`: The function's docstring description. /// - `args`: A dictionary of info objects for each function argument. /// /// These again are dictionaries with the keys /// - `description` (optional): The description for the argument. /// - `types` (optional): A list of accepted argument types. /// - `default` (optional): Default value for this argument. /// /// See @@show-module() for outputting the results of this function. /// /// - content (string): Content of `.typ` file to analyze for docstrings. /// - name (string): The name for the module. /// - label-prefix (auto, string): The label-prefix for internal function /// references. If `auto`, the label-prefix name will be the module name. /// - require-all-parameters (boolean): Require that all parameters of a /// functions are documented and fail if some are not. /// - scope (dictionary): A dictionary of definitions that are then available /// in all function and parameter descriptions. /// - preamble (string): Code to prepend to all code snippets shown with `#example()`. /// This can for instance be used to import something from the scope. #let parse-module( content, name: "", label-prefix: auto, require-all-parameters: false, scope: (:), preamble: "" ) = { if label-prefix == auto { label-prefix = name } let parse-info = ( label-prefix: label-prefix, require-all-parameters: require-all-parameters, ) let matches = content.matches(tidy-parse.docstring-matcher) let function-docs = () let variable-docs = () for match in matches { if content.len() <= match.end or content.at(match.end) != "(" { variable-docs.push(tidy-parse.parse-variable-docstring(content, match, parse-info)) } else { function-docs.push(tidy-parse.parse-function-docstring(content, match, parse-info)) } } return ( name: name, functions: function-docs, variables: variable-docs, label-prefix: label-prefix, scope: scope, preamble: preamble ) }
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/基础/assert/assert.typ
typst
#set par( justify: true, leading: 0.52em, ) #image("1.png") #image("2.png") #image("3.png")
https://github.com/sysu/better-thesis
https://raw.githubusercontent.com/sysu/better-thesis/main/specifications/bachelor/lib.typ
typst
MIT License
#import "/specifications/bachelor/cover.typ": cover #import "/specifications/bachelor/titlepage.typ": titlepage #import "/specifications/bachelor/declaration.typ": declaration #import "/specifications/bachelor/abstract.typ": abstract, abstract-page #import "/specifications/bachelor/abstract-en.typ": abstract-en, abstract-en-page #import "/specifications/bachelor/appendix.typ": appendix, appendix-part #import "/specifications/bachelor/acknowledgement.typ": acknowledgement, acknowledgement-page #import "/utils/bilingual-bibliography.typ": bilingual-bibliography #import "/utils/custom-heading.typ": active-heading, heading-display, current-heading #import "/utils/indent.typ": fake-par #import "/utils/style.typ": 字号, 字体, sysucolor #import "@preview/numblex:0.1.1": numblex, circle_numbers #import "@preview/i-figured:0.2.4" // 中山大学本科生毕业论文(设计)写作与印制规范 // 参考规范: https://spa.sysu.edu.cn/zh-hans/article/1744 #let doc( // 毕业论文基本信息 thesis-info: ( // 论文标题,将展示在封面、扉页与页眉上 // 多行标题请使用数组传入 `("thesis title", "with part next line")`,或使用换行符:`"thesis title\nwith part next line"` title: ("中山大学本科生毕业论文(设计)", "写作与印制规范(2020-)"), title-en: ("The Specification of Writting and Printing", "for SYSU thesis"), // 论文作者信息:学号、姓名、院系、专业、指导老师 author: ( sno: "1xxxxxxx", name: "张三", grade: "2024", department: "某学院", major: "某专业", ), // 指导老师信息,以`("name", "title")` 数组方式传入 supervisor: ("李四", "教授"), // 提交日期,默认为论文 PDF 生成日期 submit-date: datetime.today(), ), // 参考文献来源 bibliography: none, // 控制页面是否渲染 pages: ( // 封面可能由学院统一打印提供,因此可以不渲染 cover: true, // 附录部分为可选。设置为 true 后,会在参考文献部分与致谢部分之间插入附录部分。 appendix: false, ), // 论文内文各大部分的标题用“一、二…… (或1、2……)”, 次级标题为“(一)、(二)……(或 // 1.1、2.1……)”,三级标题用“1、2……(或1.1.1、2.1.1……)”,四级标题用“(1)、(2)…… //(或1.1.1.1、2.1.1.1……)”,不再使用五级以下标题。两类标题不要混编。 numbering: none, // 双面模式,会加入空白页,便于打印 twoside: false, // 论文正文信息,包括绪论、主体、结论 content ) = { // 论文信息参数处理。要求必须传递,且符合规格的参数 assert(type(thesis-info) == dictionary) assert(type(thesis-info.title) == array or type(thesis-info.title) == str) assert(type(thesis-info.title-en) == array or type(thesis-info.title-en) == str ) // 论文信息默认参数。函数传入参数会完全覆盖参数值,因此需要提供默认参数补充。 // 彩蛋:如果论文参数不传递作者参数,那么论文就会被署名论文模板作者 let default-author = ( sno: "13xxxx87", name: "<NAME>", grade: "2013", department: "数据科学与计算机学院", major: "软件工程", ) thesis-info.author = thesis-info.at("author", default: default-author) let default-thesis-info = ( title: ("中山大学本科生毕业论文(设计)", "写作与印制规范"), title-en: ("The Specification of Writting and Printing", "for SYSU thesis"), supervisor: ("李四", "教授"), submit-date: datetime.today(), ) thesis-info = default-thesis-info + thesis-info // 论文渲染控制参数处理。设置可选页面的默认设置项 let default-pages = ( cover: true, appendix: false, ) pages = default-pages + pages // 文档元数据处理 if type(thesis-info.title) == str { thesis-info.title = thesis-info.title.split("\n") } if type(thesis-info.title-en) == str { thesis-info.title-en = thesis-info.title-en.split("\n") } set document( title: thesis-info.title.join(""), author: thesis-info.author.name, // keywords: thesis-info.abstract.keywords, ) // 纸张大小:A4。页边距:上边距25 mm,下边距20 mm,左右边距均为30 mm。 set page(paper: "a4", margin: (top: 25mm, bottom: 20mm, x: 30mm)) // 行距:1.5倍行距 // 行距理解为 word 默认行距(1em * 120%)的1.5倍,由于目前尚未实现 [line-height 模 // 型],故换算成行间距(leading) // // [line-height 模型]: https://github.com/typst/typst/issues/4224 set par(leading: 1em * 120% * 1.5 - 1em) // 目录内容 宋体小四号 // 正文内容 宋体小四号 // 致谢、附录内容 宋体小四号 set text(lang: "zh", font: 字体.宋体, size: 字号.小四) // 论文内文各大部分的标题用“一、二…… (或1、2……)”, 次级标题为“(一)、(二)……(或 // 1.1、2.1……)”,三级标题用“1、2……(或1.1.1、2.1.1……)”,四级标题用“(1)、(2)…… //(或1.1.1.1、2.1.1.1……)”,不再使用五级以下标题。两类标题不要混编。 set heading(depth: 4, numbering: if numbering == "一" { numblex(numberings: ("一", "(一)","1", "(1)")) } else { "1.1.1.1 "}) show heading: set text(weight: "regular") // 章和节标题段前段后各空0.5行 // 行理解为当前行距,故在 "1.5倍行距" 的基准上再算一半,也即 "0.75倍行距" show heading.where(level: 1): set block(above: 1em * 120% * 0.75, below: 1em * 120% * 0.75) show heading.where(level: 2): set block(above: 1em * 120% * 0.75, below: 1em * 120% * 0.75) // 目录标题 黑体三号居中 // 正文各章标题 黑体三号居中 // 参考文献标题 黑体三号居中 // 致谢、附录标题 黑体三号居中 show heading.where(level: 1): set text(font: 字体.黑体, size: 字号.三号) show heading.where(level: 1): set align(center) // 正文各节一级标题 黑体四号左对齐 show heading.where(level: 2): set text(font: 字体.黑体, size: 字号.四号) // 正文各节二级及以下标题 宋体小四号加粗左对齐空两格 show heading.where(level: 3): set text(font: 字体.宋体, size: 字号.小四, weight: "bold") show heading.where(level: 4): set text(font: 字体.宋体, size: 字号.小四, weight: "bold") show heading.where(level: 3): it => pad(left: 2em, it) show heading.where(level: 4): it => pad(left: 2em, it) // 遇到一级标题重置图、表、公式编号计数 show heading: i-figured.reset-counters show figure: i-figured.show-figure show math.equation: i-figured.show-equation // 图题、表题 宋体五号 show figure.caption: set text(font: 字体.宋体, size: 字号.五号) // 标题放置在表格上方 show figure.where(kind: table): set figure.caption(position: top) // 脚注、尾注 宋体小五号 show footnote.entry: set text(font: 字体.宋体, size: 字号.小五) // 注释:毕业论文(设计)中有个别名词或情况需要解释时,可加注说明。注释采用脚注或尾注, // 应根据注释的先后顺序编排序号。注释序号以“①、②”等数字形式标示在正文中被注释词条的 // 右上角,脚注或尾注内容中的序号应与被注释词条序号保持一致。 show footnote: set footnote(numbering: circle_numbers) // 毕业论文应按以下顺序装订和存档: // 封面->扉页->学术诚信声明->摘要->目录->正文->参考文献(->附录)->致谢。 if pages.cover { cover(info: thesis-info) pagebreak(weak: true, to: if twoside { "odd" }) } titlepage(info: thesis-info) pagebreak(weak: true, to: if twoside { "odd" }) declaration() pagebreak(weak: true, to: if twoside { "odd" }) // 摘要开始至绪论之前以大写罗马数字(Ⅰ,Ⅱ,Ⅲ…)单独编连续码 // 页眉与页脚 宋体五号居中 set page(header: locate(loc => { set text(font: 字体.宋体, size: 字号.五号, stroke: sysucolor.green) set align(center) let cur-heading = current-heading(level: 1, loc) let first-level-heading = heading-display(active-heading(level: 1, loc)) if cur-heading != none { thesis-info.title.join("") } else if not twoside or calc.rem(loc.page(), 2) == 1 { first-level-heading } else { thesis-info.title.join("") } line(length: 200%, stroke: 0.1em + sysucolor.green); }), ) set page(numbering: "I") counter(page).update(1) abstract-page() pagebreak(weak: true, to: if twoside { "odd" }) abstract-en-page() pagebreak(weak: true, to: if twoside { "odd" }) outline() pagebreak(weak: true, to: if twoside { "odd" }) // 绪论开始至论文结尾,以阿拉伯数字(1,2,3…)编连续码 set page(numbering: "1") counter(page).update(1) // 正文段落按照中文惯例缩进两格 set par(first-line-indent: 2em) // 通过插入假段落修复[章节第一段不缩进问题](https://github.com/typst/typst/issues/311) show heading: it => { it fake-par } show heading.where(level: 1): it => { pagebreak(weak: true) it } content pagebreak(weak: true, to: if twoside { "odd" }) // 参考文献 { // 参考文献内容 宋体五号 set text(font: 字体.宋体, size: 字号.五号) bilingual-bibliography(bibliography: bibliography, full: true) } pagebreak(weak: true, to: if twoside { "odd" }) // 附录 if pages.appendix { appendix-part() pagebreak(weak: true, to: if twoside { "odd" }) } // 致谢 acknowledgement-page() pagebreak(weak: true, to: if twoside { "odd" }) } // 以下为校对用测试 preview 页面 #show: doc.with( bibliography: bibliography.with("/template/ref.bib"), pages: ( appendix: true ) ) // 正文各部分的标题应简明扼要,不使用标点符号。 = 第某章 <chapter1> == 节标题 === 小节标题 ==== 四级标题 写一下测试的内容 @chapter1-img,章节标题 @chapter1[("第一章")] #figure( image("/template/images/sysu_logo.svg", width: 20%), caption: [图片测试], ) <chapter1-img> // #show: appendix = 第一章 <appendix> == 节标题 === 小节标题 ==== 四级标题 在附录中引用图片 @appendix-img, 以及附录章节标题 @appendix[#numbering("附录A")] #figure( image("/template/images/sysu_logo.svg", width: 20%), caption: [图片测试], ) <appendix-img>
https://github.com/duskmoon314/thu-polylux
https://raw.githubusercontent.com/duskmoon314/thu-polylux/main/lib.typ
typst
MIT License
#import "@preview/polylux:0.3.1": * #let tsinghua = rgb("#82318E") #let TITLE = state("title", []) #let SUBTITLE = state("subtitle", []) #let AUTHOR = state("author", []) #let INSTITUTE = state("institute", []) #let thu-polylux( aspect-ratio: "4-3", body ) = { set text(size: 24pt) set page( paper: "presentation-" + aspect-ratio, margin: (x: 0pt, top: 32pt, bottom: 40pt), header-ascent: 0pt, header: locate( loc => { let sections = utils.sections-state.final() let current = if utils.sections-state.at(here()).len() > 0 { utils.sections-state.at(here()).last().body } else { "" } let current_index = sections.position(section => section.body == current) + 0 let section_pages = sections.map(section => section.loc.page()) for (id, num) in section_pages.enumerate() { section_pages.at(id) = (num, section_pages.at(id + 1, default: counter(page).final().first())) } let current_page = counter(page).at(here()).first() let section_pages = section_pages.map(num_range => { let lo = num_range.first() + 1 let hi = num_range.last() + 1 stack( dir: ltr, spacing: 4pt, ..range(lo, hi).map(num => { link( (page: num, x: 0pt, y: 0pt), text(size: 8pt, stroke: 1pt + if num == current_page { white } else { white.darken(50%) })[○]) }) ) }) set text(size: 14pt, fill: white, font: "Noto Sans CJK SC") stack( dir: ttb, spacing: 0pt, block( fill: tsinghua.darken(40%), grid( rows: (20pt, 10pt), columns: sections.map(section => 1fr), align: center + horizon, // Link to each section ..sections.map(section => { set text(weight: if section.body == current { "bold" } else { "regular" }) link(section.loc, section.body) }), // Link to each page ..section_pages ) ), rect( width: 100%, height: 2pt, stroke: 0pt, fill: gradient.linear( (tsinghua.darken(40%), 0%), (tsinghua.darken(40%), (logic.logical-slide.at(here()).first() / logic.logical-slide.final().first()) * 100%), (tsinghua, 100%) ) ) ) }), footer-descent: 0pt, footer: [ #set text(font: "Noto Sans CJK SC", size: 16pt, fill: white) #grid( columns: (50%, 50%), rows: (20pt, 20pt), align: (left + horizon, right + horizon), fill: (x, y) => if calc.even(y) { tsinghua } else { tsinghua.darken(40%) }, inset: (x: 1.5em, y: 5pt), context AUTHOR.get(), context INSTITUTE.get(), context TITLE.get(), logic.logical-slide.display() + " / " + utils.last-slide-number ) ] ) set list( marker: ([•], [‣], [–]).map(marker => { set text(fill: tsinghua, size: 32pt) marker }) ) set enum( numbering: (num) => { circle(fill: tsinghua, radius: .5em)[ #set align(center + horizon) #set text(fill: white) #num ] } ) body } #let title-slide( title: [], subtitle: [], author: [], institute: [], date: datetime.today().display("[year]年[month padding:none]月[day padding:none]日") ) = { TITLE.update(title) SUBTITLE.update(subtitle) AUTHOR.update(author) INSTITUTE.update(institute) polylux-slide[ #set align(center + horizon) #rect(fill: tsinghua, width: 80%, height: 4.5em)[ #set text(fill: white, font: "Noto Sans CJK SC", size: 32pt, weight: "bold") #context { TITLE.get() } #v(-.5em) #context { SUBTITLE.get() } ] #set text(size: 24pt) #context { AUTHOR.get() } #set text(size: 16pt) #context { INSTITUTE.get() } #date #image("Tsinghua_University_Logo.svg", width: 5cm) ] } #let slide( title: [], body ) = { polylux-slide[ #if title != [] { stack( dir: ttb, rect(fill: tsinghua, width: 100%, height: 40pt, inset: (x: 1em))[ #set align(horizon) #set text(fill: white, font: "Noto Sans CJK SC", size: 32pt, weight: "bold") #title ], rect(width: 100%, height: 100% - 40pt, inset: 1.5em, stroke: 0pt)[ #set align(horizon) #body ] ) } else { rect(width: 100%, height: 100%, inset: 1.5em, stroke: 0pt)[ #set align(horizon) #body ] } ] } #let tableofcontents(title: []) = { context { slide(title: title)[ #let sections = utils.sections-state.final() #enum( ..sections.map(section => { set text(fill: tsinghua) link(section.loc, section.body) }) ) ] } } #let section(section-name, show-slide: false) = { utils.register-section(section-name) if show-slide [ #context { let sections = utils.sections-state.final() let current = utils.sections-state.at(here()).last().body let current-index = sections.position(section => section.body == current) slide()[ #show enum: it => { for (id, child) in it.children.enumerate() { block( pad(left: it.indent)[ #stack(dir: ltr, spacing: it.body-indent)[ #circle( fill: if id == current-index { tsinghua } else { tsinghua.lighten(50%) }, radius: .5em )[ #set align(center + horizon) #set text(fill: white) #int(id + 1) ] ][ #set text(if id == current-index { tsinghua } else { tsinghua.lighten(50%) }) #child.body ] ] ) } } #enum( ..sections.map(section => { link(section.loc, section.body) }) ) ] } ] }
https://github.com/LeoColomb/dotdocs
https://raw.githubusercontent.com/LeoColomb/dotdocs/main/packages/leocolomb/invoicing/1.0.0/src/lib.typ
typst
MIT License
#import "@leocolomb/logotype:1.0.0": * #let rule(margin: 1.2em) = { v(margin) line( length: 100%, stroke: 0.5pt + gray, ) v(margin) } // This function gets your whole document as its `body` // and formats it as a corporate. #let template( type: "Facture", // The name with wich the CV opens. name: none, // The links to self references/social networks. address: none, // The CV's tagline. tagline: none, // The applied position. siret: [], project: none, reference: none, date: none, // The applied company. recipient: [], pricelist: (), // The CV's content. body ) = { // Configure page and text properties. set text( lang: "fr", size: 9.9pt, font: "Source Sans Pro", ) set page( header: text(font: "The Bold Font")[ #grid( columns: (auto, auto), gutter: 5pt, text(size: 27pt)[o], par(leading: 0.4em)[Léo\ Colombaro], ) ], footer: context [ #set text( fill: gray, size: 5pt, ) #name\ #address\ Siret~: #siret #h(1fr) #counter(page).display( "1 / 1", both: true, ) ], ) v(1em) columns(2)[ #text(size: 7pt)[#upper("Exécutant")]\ *#name*\ #address\ #text(size: 7pt)[Siret : #siret] #colbreak() #set align(right) #text(size: 7pt)[#upper("Commanditaire")]\ #recipient ] rule() [ Projet *#project*\ #type n° *#reference* du *#date* à Paris ] rule() [ === Récapitulatif de mission #body ] rule() let total = pricelist.fold(0, (init, el) => init + el.at(-1)) pricelist = pricelist.map(el => { el.at(-1) = [#el.at(-1) €] return el }) table( columns: (1fr, auto), inset: 10pt, stroke: none, //0.5pt + gray, align: (x, y) => (left, right).at(x), fill: (_, row) => if calc.even(row) { luma(240) } else { white }, [*Désignation*], [*Prix HT*], ..pricelist.flatten(), align(right)[*Total*], [*#total €*] ) align(right)[ #set text(size: 8pt) TVA non applicable, art. 293B du CGI ] v(2em) if type == "Facture" { [ *Facture à payer avant 30 jours à compter de la date de facturation*\ Passée la date d'échéance, tout paiement différé entraîne l'application d'une pénalité calculée à un taux égal à 3 fois le taux d'intérêt légal en vigueur à la date de facturation (loi 2008‑776 du 04/08/2008) ainsi qu'une indemnité forfaitaire pour frais de recouvrement de 40 euros (décret 2012‑115 du 02/10/2012). *Aucun escompte pour règlement anticipé* ] rule() [ Paiement par *virement bancaire* #columns(2)[ / Titulaire: #name / IBAN: #colbreak() / RIB: / BIC: ] ] } }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/shape-square-04.typ
typst
Other
// Test that square does not overflow page. #set page(width: 100pt, height: 75pt) #square(fill: green)[ But, soft! what light through yonder window breaks? ]
https://github.com/Entoryvekum/TypstTemplate
https://raw.githubusercontent.com/Entoryvekum/TypstTemplate/main/NoteTemplate/0.1.0/template.typ
typst
#import("@local/MathBasic:0.1.0"):* #let Note( headline:none, title:none, author:none, email:none, time:datetime.today().year(), pagebreakBeforeOutline:false, body) = { //Page let Header(l,m,r)={ grid( columns: (1fr,auto,1fr), align(left,text(9pt,par(leading: 0.2em,l))), align(center,text(9pt,par(leading: 0.2em,m))), align(right,text(9pt,par(leading: 0.2em,r))), ) } set text( font: ("Times New Roman","Simsun"), size: 11pt ) set page( paper: "a4", margin: (x: 2cm, y: 1.5cm), header: locate(loc => if loc.page()==1 [] else if calc.even(loc.page()) [#Header([#loc.page()],headline,[#time])#line(length:100%)] else [#Header([#time],title,[#loc.page()])#line(length:100%)] ), ) set par( first-line-indent: 2em, justify: true, leading: 0.9em, ) set heading(numbering: "1.") show heading.where(level: 1): it => [ #set par(first-line-indent: 0em) #set text(15pt, weight: "bold") #counter(heading).display() #h(0.5em) #it.body ] show heading.where(level: 2): it => text( size: 13pt, weight: "bold", counter(heading).display()+h(0.5em)+it.body, ) //Raw show raw.where(block: false): box.with( fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) show raw.where(block: true): block.with( width: 100%, fill: luma(240), inset: 8pt, radius: 4pt, ) show raw.where(block: true): it => { let lines = it.text.split("\n") let length = lines.len() let i = 1 let index = while i < length { str(i) + "\n" i+=1 } grid( columns: (auto, 1fr), align( right, block( inset: ( top: 8pt, bottom: 8pt, left: 0pt, right: 5pt ), index ) ), align(left, it), ) } //首页 { move(dx:-2cm,dy:-1.5cm,rect(fill:luma(230), stroke:none, width: 200%, height:7cm)) move(dx:-2cm,dy:-2cm, rect(fill:rgb("#85b6b4"), stroke:none, width: 200%, height:5.5cm, move(dx:2cm,dy:1.1cm)[ #set par(first-line-indent: 0pt,leading:2em) #if title!=none {text(headline,font:("Times New Roman","Simsun"),size:35pt,weight:"bold")}\ #if title!=none {text(title,font:("Times New Roman","Simsun"),size:27pt,weight:"bold")}\ #set par(first-line-indent: 0pt,leading:1em) #if title!=none {text(author,font:("Times New Roman","Simsun"),size:15pt)}\ #if email!=none {text(email,font:("Times New Roman","Simsun"),size:13pt)} ] ) ) v(5em) } //目录 if pagebreakBeforeOutline==true [#pagebreak()] else [] { show heading: it => [ #set par(first-line-indent: 0em) #set text(15pt, weight: "bold") #it.body ] set par(first-line-indent: 0em) set text(font:("Times New Roman","Simsun"),size:12pt) outline(indent:true) pagebreak() } body }
https://github.com/vEnhance/1802
https://raw.githubusercontent.com/vEnhance/1802/main/src/paraint.typ
typst
MIT License
#import "@local/evan:1.0.0":* = Parametrized integrals #sample[ Compute the line integral of the vector field $bf(F) (x , y) = vec(2 x , 3 y)$ along the curve $C$ which is the upper half of the circle $x^2 + y^2 = 1$, oriented counterclockwise. ] #soln[ The line integral of a vector field $bf(F)$ along a curve $C$ is given by: $ int_C bf(F)(bf(r)(t)) dot bf(r)'(t) dif t $ Parametrize the curve $C$ as $bf(r) (t) = (cos t , sin t)$, where $t in [0 , pi]$. First we compute $bf(r)'(t)$ which is $ bf(r)'(t) dif t = (- sin t, cos t) $. Meanwhile, the values of $bf(F)$ along the curve rae $ bf(F) (bf(r) (t)) = bf(F) (cos t , sin t) = (2 cos t , 3 sin t) $ Hence, the dot product being integrated is $ bf(F) (bf(r) (t)) dot bf(r)'(t) &= (2 cos t) (- sin t) + (3 sin t) (cos t) \ &= - 2 cos t sin t + 3 sin t cos t = cos t sin t $ Integrate with respect to $t$ from $0$ to $pi$: $ int_0^pi cos t sin t dif t $ Using the identity $cos t sin t = 1 / 2 sin (2 t)$, we rewrite the integral: $ int_0^pi cos t sin t dif t &= 1 / 2 int_0^pi sin (2 t) dif t \ &= 1 / 2 [- 1 / 2 cos (2 t)]_0^pi \ &= 1 / 2 [- 1 / 2 cos (2 pi) + 1 / 2 cos (0)] \ &= 1 / 2 [- 1 / 2 (1) + 1 / 2 (1)] = 0. #qedhere $ ] #pagebreak()
https://github.com/Joelius300/hslu-typst-template
https://raw.githubusercontent.com/Joelius300/hslu-typst-template/main/template.typ
typst
MIT License
// TODO Check list of packages and select those you need // https://typst.app/docs/packages/ #import "@preview/i-figured:0.2.4" #import "@preview/anti-matter:0.1.1": anti-matter, fence, set-numbering #import "@preview/big-todo:0.2.0": todo // Universal underlines (used in set in template) #let underline-thickness = 0.5pt #let underline-offset = 1pt // Underline box: From https://github.com/typst/typst/issues/1716#issuecomment-1690842054 #let ubox(..box_args) = box( width: 1fr, stroke: (bottom: underline-thickness), outset: (bottom: underline-offset), ..box_args, ) // Function to get a signature template (in German) #let signature_template() = { [Ort / Datum, Unterschrift #ubox()] } // Function to write equation with a caption #let eq(body, caption) = { figure(math.equation(block: true, body), caption: caption, kind: "eq", supplement: "Gleichung") } // Function to get a checkbox symbol in the current font #let checkbox(checked: false) = { // unset font to force fallback where symbol works correctly. // this is necessary because in some fonts the checked box is smaller. set text(font: "") if checked { sym.ballot.x } else { sym.ballot } } // Function to get an image with a caption #let img(name, caption, alt: none, ..img_args) = { if alt == none and type(caption) == str { alt = caption } figure(image("img/" + name, alt: alt, ..img_args), caption: caption) } // Function to get a simple horizontal rule #let hr() = { line(length: 100%, stroke: .2em + color.rgb(20%, 20%, 20%, 15%)) } // Function to display a reminder that something here needs to be reviewed (optionally with some people). // Avoids constantly typing todo(inline: true). #let rev(..people) = { let text = "Review" if people.pos().len() > 0 { let people = people.pos().join(", ") text = text + " with " + people } todo(text, inline: true) } #let project( title: "", subtitle: "", abstract: none, logo: none, student: "", departement: [Hochschule Luzern -- Informatik], degree: "BSc Informatik oder Wirtschaftsinformatik", // could use the datetime type directly but there's no localization for displaying date: datetime.today().display(), year: str(datetime.today().year()), coach: "", expert: "", client: "", confidential: false, disable_figure_hypenation: false, body ) = { set document(author: student, title: title) show: anti-matter set-numbering(none) // disable page numbers set text(font: "STIX Two Text", size: 11pt, lang: "de") set heading(numbering: "1.1") // set math.equation(numbering: "(1)") // TODO maybe justify only after title page? set par(justify: true, leading: 0.65em * 1.5) // In a figure, you can specify the kind to be math.equation and that works // (it even has a localized supplement), BUT you cannot use math.equation here // when specifying the extra-prefixes, so we use the custom kind "eq". show heading: i-figured.reset-counters.with(level: 1, extra-kinds: ("eq",), equations: true) show figure: i-figured.show-figure.with(extra-prefixes: ("eq": "eq:")) show math.equation: i-figured.show-equation show math.equation: set text(weight: 400) show figure.caption: set text(hyphenate: not disable_figure_hypenation) // Universal underlines set underline(stroke: underline-thickness, offset: underline-offset) // Title page { set align(center) if logo != none { align(right, image(logo, width: 25%)) } v(1em) text(30pt, weight: 700, title) set text(size: 18pt, weight: 500) v(1em) text(subtitle, weight: 550) v(2em) student // TODO hier noch "arbeit von", "unter Betreuung von", "im Auftrag von"? // wenn ja mit Funktion für die verschiedenen Schriftgrössen set align(bottom) set text(size: 14pt, weight: 250) degree linebreak() departement linebreak() // date.display("[day].[month].[year]") no localization support yet date v(4em) } pagebreak() // Preamble according to requirements from HSLU [ #set heading(numbering: none, outlined: false) == Bachelorarbeit an der #departement #v(2em) #grid(columns: 2, row-gutter: 1.75em, column-gutter: 1em, strong[Titel:], title, strong[Studentin/Student:], student, strong[Studiengang:], degree, strong[Jahr:], year, // str(date.year()), strong[Betreuungsperson:], coach, strong[Expertin/Experte:], expert, strong[Auftraggeberin/Auftraggeber:], client, ) #v(3em) ==== Codierung / Klassifizierung der Arbeit #checkbox(checked: not confidential) Öffentlich (Normalfall) \ #checkbox(checked: confidential) Vertraulich \ #v(3em) ==== Eidesstattliche Erklärung Ich erkläre hiermit, dass ich die vorliegende Arbeit selbständig und ohne unerlaubte fremde Hilfe angefertigt habe, alle verwendeten Quellen, Literatur und andere Hilfsmittel angegeben habe, wörtlich oder inhaltlich entnommene Stellen als solche kenntlich gemacht habe, das Vertraulichkeitsinteresse des Auftraggebers wahren und die Urheberrechtsbestimmungen der Hochschule Luzern respektieren werde. #signature_template() #v(3em) ==== Abgabe der Arbeit auf der Portfolio Datenbank Bestätigungsvisum Studentin/Student \ Ich bestätige, dass ich die Bachelorarbeit korrekt gemäss Merkblatt auf der Portfolio Datenbank abgelegt habe. Die Verantwortlichkeit sowie die Berechtigungen habe ich abgegeben, so dass ich keine Änderungen mehr vornehmen kann oder weitere Dateien hochladen kann. #signature_template() ] pagebreak(weak: true) // If there are todos, show an outline of them here locate(loc => if query(figure.where(kind: "todo"), loc).len() > 0 [ _Diese Seite verschwindet sobald alle TODOs erledigt sind._ #outline( title: heading(text(fill: red)[TODOs], level: 1, outlined: false), target: figure.where(kind: "todo"), ) ]) pagebreak(weak: true) // Currently the pages before the abstract have no page numbers, they // are purely title pages. Then the front- and backmatter have "I" page numbers // and the rest has normal "1" page numbers. set-numbering("I") // abstract and table of contents have no heading numbering set heading(numbering: none, outlined: false) if abstract != none { [= Abstract] abstract } pagebreak(weak: true) // // Numbering for headings and equations after preamble // set heading(numbering: "1.") // set math.equation(numbering: "(1)") // Table of contents // outline(title: heading([Inhaltsverzeichnis], level: 1, outlined: true, numbering: "1."), depth: 3) [= Inhaltsverzeichnis] outline(title: v(-1.3em), depth: 3) fence() set heading(numbering: "1.1", outlined: true) pagebreak(weak: true) // actual content body }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/docs/tinymist/module/query.typ
typst
Apache License 2.0
#import "mod.typ": * #show: book-page.with(title: "Tinymist Languague Queries") == Base Analyses There are five basic analysis APIs: - _lexical hierarchy_ matches crucial lexical structures in the source file. - _def use info_ is computed based on _lexical hierarchy_\s. - _type check info_ is computed with _def use info_. - _find definition_ finds the definition based on _def use info_. - _find references_ finds the references based on _def use info_. == Extending Language Features Language features are implemented based on basic analysis APIs: - The `textDocument/documentSymbol` returns a tree of nodes converted from the _lexical hierarchy_. - The `textDocument/foldingRange` also returns a tree of nodes converted from the _lexical hierarchy_ but with a different approach. - The `workspace/symbol` returns an array of nodes converted from all _lexical hierarchy_\s in workspace. - The `textDocument/definition` returns the result of _find definition_. - The `textDocument/completion` returns a list of types of _related_ nodes according to _type check info_, matched by _AST matchers_. - The `textDocument/hover` _finds definition_ and prints the definition with a checked type by _type check info_. Or, specific to typst, prints a set of inspected values during execution of the document. - The `textDocument/signatureHelp` also _finds definition_ and prints the signature with union of inferred signatures by _type check info_. - The `textDocument/prepareRename` _finds definition_ and determines whether it can be renamed. - The `textDocument/rename` _finds defintion and references_ and renamed them all. == Contributing See #link("https://github.com/Myriad-Dreamin/tinymist/blob/main/CONTRIBUTING.md")[CONTRIBUTING.md].
https://github.com/dismint/docmint
https://raw.githubusercontent.com/dismint/docmint/main/networks/pset4.typ
typst
#import "template.typ": * #show: template.with( title: "14.15 PSET 4", subtitle: "<NAME>", pset: true ) = Problem 1 == (a) To solve, let us find the number of total possible triangles, then multiply by the probability that any given one exists. The number of triangles can be enumerated as: $ (n (n+1) (n+2)) / 6 = binom(n, 3) $ Then for any given triangle, the chance that it exists is contingent on all three edges being present, which has a $p(n)^3 = lambda^3 / n^3$ chance. Therefore our answer comes out to: $ lim_(n -> infinity) [(n (n+1) (n+2)) / 6 dot lambda^3 / n^3] = boxed(1 / 6 lambda^3) $ == (b) This result might seem odd as an increase in nodes would surely indicate an increase in the number of triangles. However, the interaction that causes this irrelevance of $n$ is the balancing of the increasing in nodes and the decreasing in the chance for a triangle. The number of *potential* triangles scales by $n^3$, but the chance for any triangle to exist scales down by $lambda^3 / n^3$. Thus to the two work against each other, and the end result becomes completely independent of $n$ for large $n$ == (c) Similar to *(a)*, the number of triangles is: $ (n (n+1) (n+2)) / 6 = binom(n, 3) $ However, the conditions are looser in this case, as we only require two out of the three edges. We can think of one edge as being irrelevant, of which there are three possible orientations. This leaves us with the probability for a given triple existing as $3 dot p(n)^2 = 3 dot lambda^2 / n^2$ $ lim_(n -> infinity) [(n (n+1) (n+2)) / 6 dot 3 dot lambda^2 / n^2] = boxed(1 / 2 n lambda^2) $ This of course, is an approximation since we count the triangle case too many times, leading to an overestimate. == (d) We compute this quantity as the number of triangles over the number of triples. This translates directly into the problem statement, which is asking for the chance that a triple is actually a triangle. $ 1 / 6 lambda^3 slash 1 / 2 n lambda^2 = (2 lambda^3) / (6 n lambda^2) = boxed(lambda / (3 n)) $ = Problem 2 = Problem 3 == (a) Recall from lecture that we were given: $ lambda = - ln(1-q) / q $ Thus we want to find $lambda$ for $q = 1 / 2$. This evaluates to around: $ -2 dot ln(1 / 2) = boxed(1.386)$ == (b) The Poisson random variable can be used here: $ PP(d) &= (e^(-lambda) lambda^d) / d!\ PP(5) &= (e^(-1.386) 1.386^5) / 5!\ PP(5) &= boxed(1.06 dot 10^(-2)) $ == (c) We already know that $Pr(d_i = 5)$ from the previous part, as well as the fact that $Pr(i "in giant component")$ is equal to $1 / 2$ from the exposition to this question. The only remaining quantity that we must calculate is the conditional. Let us approximate this by saying the chance a node with degree $5$ is not in the giant component is dependent on none of its neighbors being in the component. Thus there is a $1 - (1 / 2)^5 = 31 / 32$ chance this node is in the giant component. With this in mind, the fraction of nodes in the giant component that have degree $5$ can be approximated as: $ (1.06 dot 10^(-2) dot 31 / 32) / (1 / 2) = boxed(2.07 dot 10^(-2)) $ == (d) One might expect the giant component to look demographically like the rest of the graph when it comes to its degrees. However, the critical observation to make here is that the degree of a graph directly impacts the likelihood that a node is in the giant component. As shown in the calculations for *(c)*, it is far more likely for a node with a higher degree to be a part of the giant component, as it has more linkages, and therefore more chances to be roped into the giant component. This is the reason for the difference in values between *(b)* and *(c)* - the demographic makeup of the giant component will skew towards the higher degree nodes compared to the original graph. = Problem 4 == (a) Expanding the sum we get: $ sum_(d = 0)^infinity 2^(-(d + 1)) = 1 / 2 + 1 / 4 + ... $ This is an infinite geometric series with a starting value of $1 / 2$ and a common ratio of $1 / 2$, meaning the sum converges to $(1 / 2) / (1 - 1 / 2) = 1$ == (b) To solve for the average node degree, we can take the sum from earlier, and multiply the inside probability by the degree: $ sum_(d = 0)^infinity d dot 2^(-(d + 1)) = 0 + 1 / 4 + 2 / 8 + 3 / 16 + ... $ Let us call this series $S$. Now consider what $S - S / 2$ looks like: $ S - S / 2 = 0 + 1 / 4 + 1 / 8 + 1 / 16 $ The right side of the equation is easy to calculate as it's another geometric sum. This time, it evaluates to $(1 / 4) / (1 - 1 / 2) = 1 / 2$. Therefore we have the expected value as: $ S - S / 2 &= 0 + 1 / 4 + 1 / 8 + 1 / 16\ S / 2 &= 1 / 2\ S &= boxed(1) $ Thus our average degree on a node is equal to *1* == (c) We saw from lecture that the expected number of distance-2 neighbors from any starting node is equal to: $ angle.l d^2 angle.r - angle.l d angle.r $ Using a similar process from above, we can calculate the mean squared degree $angle.l d^2 angle.r$ to be 3. Thus we expect that there are *2* distance-2 neighbors from any starting node. == (d) A giant component exists if and only if: $ (angle.l d^2 angle.r) / (angle.l d angle.r) >= 2 $ Using the values from above, we can see that this inequality holds, as the fraction evaluates to 3. Therefore, it *is* the case that this network has a giant component.
https://github.com/Mc-Zen/quill
https://raw.githubusercontent.com/Mc-Zen/quill/main/README.md
markdown
MIT License
<h1 align="center"> <img alt="Quill" src="docs/images/logo.svg" style="max-width: 100%; width: 300pt"> </h1> <div align="center"> [![Typst Package](https://img.shields.io/badge/dynamic/toml?url=https%3A%2F%2Fraw.githubusercontent.com%2FMc-Zen%2Fquill%2Fv0.5.0%2Ftypst.toml&query=%24.package.version&prefix=v&logo=typst&label=package&color=239DAD)](https://typst.app/universe/package/quill) [![Test Status](https://github.com/Mc-Zen/quill/actions/workflows/run_tests.yml/badge.svg)](https://github.com/Mc-Zen/quill/actions/workflows/run_tests.yml) [![MIT License](https://img.shields.io/badge/license-MIT-blue)](https://github.com/Mc-Zen/quill/blob/main/LICENSE) [![User Manual](https://img.shields.io/badge/manual-.pdf-purple)][guide] </div> **Quill** is a package for creating quantum circuit diagrams in [Typst](https://typst.app/). _Note, that this package is in beta and may still be undergoing breaking changes. As new features like data types and scoped functions will be added to Typst, this package will be adapted to profit from the new paradigms._ _Meanwhile, we suggest importing everything from the package in a local scope to avoid polluting the global namespace (see example below)._ - [**Usage**](#basic-usage) _quick introduction_ - [**Cheat sheet**](#cheat-sheet) _gallery for quickly viewing all kinds of gates_ - [**Tequila**](#tequila) _building (sub-)circuits in a way similar to QASM or Qiskit_ - [**Examples**](#examples) - [**Changelog**](#changelog) ## Basic usage The function `quantum-circuit()` takes any number of positional gates and works somewhat similarly to the built-int Typst functions `table()` or `grid()`. A variety of different gate and instruction commands are available for adding elements and integers can be used to produce any number of empty cells (filled with the current wire style). A new wire is started by adding a `[\ ]` item. ```typ #{ import "@preview/quill:0.5.0": * quantum-circuit( lstick($|0〉$), $H$, ctrl(1), rstick($(|00〉+|11〉)/√2$, n: 2), [\ ], lstick($|0〉$), 1, targ(), 1 ) } ``` <div align="center"> <img alt="Bell Circuit" src="docs/images/bell.svg"> </div> Plain quantum gates — such as a Hadamard gate — can be written with the shorthand notation `$H$` instead of the more lengthy `gate($H$)`. The latter offers more options, however. Refer to the [user guide][guide] for a full documentation of this package. You can also look up the documentation of any function by calling the help module, e.g., `help("gate")` in order to print the signature and description of the `gate` command, just where you are currently typing (powered by [tidy][tidy]). ## Cheat Sheet Instead of listing every featured gate (as is done in the [user guide][guide]), this gallery quickly showcases a large selection of possible gates and decorations that can be added to any quantum circuit. <div align="center"> <img alt="Gallery" src="docs/images/gallery.svg" /> </div> ## Tequila _Tequila_ is a submodule that adds a completely different way of building circuits. ```typ #import "@preview/quill:0.5.0" as quill: tequila as tq #quill.quantum-circuit( ..tq.build( tq.h(0), tq.cx(0, 1), tq.cx(0, 2), ), quill.gategroup(x: 2, y: 0, 3, 2) ) ``` This is similar to how _QASM_ and _Qiskit_ work: gates are successively applied to the circuit which is then layed out automatically by packing gates as tightly as possible. We start by calling the `tq.build()` function and filling it with quantum operations. This returns a collection of gates which we expand into the circuit with the `..` syntax. Now, we still have the option to add annotations, groups, slices, or even more gates via manual placement. The syntax works analog to Qiskit. Available gates are `x`, `y`, `z`, `h`, `s`, `sdg`, `sx`, `sxdg`, `t`, `tdg`, `p`, `rx`, `ry`, `rz`, `u`, `cx`, `cz`, and `swap`. With `barrier`, an invisible barrier can be inserted to prevent gates on different qubits to be packed tightly. Finally, with `tq.gate` and `tq.mqgate`, a generic gate can be created. These two accept the same styling arguments as the normal `gate` (or `mqgate`). Also like Qiskit, all qubit arguments support ranges, e.g., `tq.h(range(5))` adds a Hadamard gate on the first five qubits and `tq.cx((0, 1), (1, 2))` adds two CX gates: one from qubit 0 to 1 and one from qubit 1 to 2. With Tequila, it is easy to build templates for quantum circuits and to compose circuits of various building blocks. For this purpose, `tq.build()` and the built-in templates all feature optional `x` and `y` arguments to allow placing a subcircuit at an arbitrary position of the circuit. As an example, Tequila provides a `tq.graph-state()` template for quickly drawing graph state preparation circuits. The following example demonstrates how to compose multiple subcircuits. ```typ #import tequila as tq #quantum-circuit( ..tq.graph-state((0, 1), (1, 2)), ..tq.build(y: 3, tq.p($pi$, 0), tq.cx(0, (1, 2)), ), ..tq.graph-state(x: 6, y: 2, invert: true, (0, 1), (0, 2)), gategroup(x: 1, 3, 3), gategroup(x: 1, y: 3, 3, 3), gategroup(x: 6, y: 2, 3, 3), slice(x: 5) ) ``` <div align="center"> <img alt="Gallery" src="docs/images/composition.svg" /> </div> ## Examples Some show-off examples, loosely replicating figures from [Quantum Computation and Quantum Information by <NAME> and <NAME>](https://www.cambridge.org/highereducation/books/quantum-computation-and-quantum-information/01E10196D0A682A6AEFFEA52D53BE9AE#overview). The code for these examples can be found in the [example folder](./examples/) or in the [user guide][guide]. <div align="center"> <img alt="Quantum teleportation circuit" src="docs/images/teleportation.svg"> </div> <div align="center"> <img alt="Quantum circuit for phase estimation" src="docs/images/phase-estimation.svg"> </div> <div align="center"> <img alt="Quantum fourier transformation circuit" src="docs/images/qft.svg"> </div> ## Contribution If you spot an issue or have a suggestion, you are invited to [post it](https://github.com/Mc-Zen/quill/issues) or to contribute. In [architecture.md](docs/architecture.md), you can also find a description of the algorithm that forms the base of `quantum-circuit()`. ## Tests This package uses [typst-test](https://github.com/tingerrr/typst-test/) for running [tests](tests/). ## Changelog ### v0.5.0 - Added support for multi-controlled gates with Tequila. - Switched to using `context` instead of the now deprecated `style()` for measurement. Note: Starting with this version, Typst 0.11.0 or higher is required. ### v0.4.0 - Alternative model for creating and composing circuits: [Tequila](#tequila). ### v0.3.0 - New features - Enable manual placement of gates, `gate($X$, x: 3, y: 1)`, similar to built-in `table()` in addition to automatic placement. This works for most elements, not only gates. - Add parameter `pad` to `lstick()` and `rstick()`. - Add parameter `fill-wires` to `quantum-circuit()`. All wires are filled unto the end (determined by the longest wire) by default (breaking change ⚠️). This behavior can be reverted by setting `fill-wires: false`. - `gategroup()` `slice()` and `annotate()` can now be placed above or below the circuit with `z: "above"` and `z: "below"`. - `help()` command for quickly displaying the documentation of a given function, e.g., `help("gate")`. Powered by [tidy][tidy]. - Improvements: - Complete rework of circuit layout implementation - allows transparent gates since wires are not drawn through gates anymore. The default fill is now `auto` and using `none` sets the background to transparent. - `midstick` is now transparent by default. - `setwire()` can now be used to override only partial wire settings, such as wire color `setwire(1, stroke: blue)`, width `setwire(1, stroke: 1pt)` or wire distance, all separately. Before, some settings were reset. - Fixes: - Fixed `lstick`/`rstick` when equation numbering is turned on. - Removed: - The already deprecated `scale-factor` (use `scale` instead) ### v0.2.1 - Improvements: - Add `fill` parameter to `midstick()`. - Add `bend` parameter to `permute()`. - Add `separation` parameter to `permute()`. - Fixes: - With Typst 0.11.0, `scale()` now takes into account outer alignment. This broke the positioning of centered/right-aligned circuits, e.g., ones put into a `figure()`. - Change wires to be drawn all through `ctrl()`, making it consistent to `swap()` and `targ()`. ### v0.2.0 - New features: - Add arbitrary labels to any `gate` (also derived gates such as `meter`, `ctrl`, ...), `gategroup` or `slice` that can be anchored to any of the nine 2d alignments. - Add optional gate inputs and outputs for multi-qubit gates (see gallery). - Implicit gates (breaking change ⚠️): a content item automatically becomes a gate, so you can just type `$H$` instead of `gate($H$)` (of course, the `gate()` function is still important in order to use the many available options). - Other breaking changes ⚠️: - `slice()` has no `dx` and `dy` parameters anymore. Instead, labels are handled through `label` exactly as in `gate()`. Also the `wires` parameter is replaced with `n` for consistency with other multi-qubit gates. - Swap order of row and column parameters in `annotate()` to make it consistent with built-in Typst functions. - Improvements: - Improve layout (allow row/column spacing and min lengths to be specified in em-lengths). - Automatic bounds computation, even for labels. - Improve meter (allow multi-qubit gate meters and respect global (per-circuit) gate padding).d - Fixes: - `lstick`/`rstick` braces broke with Typst 0.7.0. - `lstick`/`rstick` bounds. - Documentation - Add section on creating custom gates. - Add section on using labels. - Explain usage of `slice()` and `gategroup()`. ### v0.1.0 Initial Release [guide]: https://github.com/Mc-Zen/quill/releases/download/v0.5.0/quill-guide.pdf [tidy]: https://github.com/Mc-Zen/tidy
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/020%20-%20Prologue%20to%20Battle%20for%20Zendikar/003_Limits.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Limits", set_name: "Prologue to Battle for Zendikar", story_date: datetime(day: 15, month: 07, year: 2015), author: "<NAME>", doc ) #emph[Planeswalker Gideon Jura has a problem—there's only one of him. Zendikar is a world ravaged by otherworldly monsters known as the Eldrazi. Gideon witnessed their devastation when he first visited the plane, and vowed to return with help. No Planeswalkers heeded his call, and he refused to let Zendikar languish. On Ravnica, Gideon found kindred spirits among the disciplined Boros Legion, but the politics of the plane favor those associated with a guild, and Gideon finds that he must step in on behalf of those not under guild protection. Zendikar by day. Ravnica by night. Gideon cannot turn his back on those who need him, and trouble may be reaching boiling point on both planes.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = Zendikar Gideon's muscles ached and his breath was labored. Dust burned in his lungs. It coated his nostrils and caused his eyes to water steadily. Grit had worked its way behind his eyelids, and he blinked desperately to flush it out. He could even taste it on his tongue. What moisture he had remaining in his mouth, he gathered up and spat into the tall grass that poked up through the gathered dust all around him. He had to end this quickly. The Eldrazi monstrosity loomed over Gideon, almost twice his height, its torso rising up on a mass of thick, fleshy tendrils that slid heavily over the tall grass. Like so many others Gideon had battled these last few weeks, this one's face was encased almost entirely in a smooth, boney texture. Though eyeless, its head turned to follow Gideon's movements. It was an unsettling gesture, devoid of malice, or hate, or anger. The Eldrazi were unlike other opponents Gideon had fought, at once graceful and lurching, willful and indifferent. There was no body language to read, no tells whatsoever, and it was all Gideon could do to stay beyond this one's reach. Tendrils lashed out. But so did the four ribbon-like metal blades of his sural. Gideon yanked his arm back and the blades flicked out, severing a tendril. The gore was not blood, but a viscous, sticky muck that caught Gideon's flexible blades, interrupting the flow of his follow-through. Clumsy. Another tendril slammed into his ribs before he could angle out of its path. He saw it coming, but there was only enough time for Gideon to grit his teeth and anticipate the blow while ripples of protective light reflexively flared across his body to meet the blow, leaving him unharmed. For the moment, anyway. Littering the tall grass all around him were rough chunks of a fallen, shattered hedron—one of the countless eight-faced monolithic stones that Gideon had seen while on the plane. There was something about them that the Eldrazi reacted to. Nobody could quite explain it to him, but many of the Zendikari carried small hedrons as wards, or replaced spearheads and arrowheads with them. The kor even painted their bodies with designs that matched the hedrons' intricate carvings. To Gideon, at that moment, what mattered was that the hedron chunks were heavy and jagged. #figure(image("003_Limits/01.jpg", width: 100%), caption: [Plains | Art by Vincent Proce], supplement: none, numbering: none) He had to buy himself some time. A moment at least. More tendrils. Gideon leapt to his right, contorting his body to slip between the writhing, grasping limbs. He rolled on the ground, and the Eldrazi monstrosity reeled its tendrils back for another barrage. There it was. A moment. And in it, Gideon was on his feet. He charged flat out toward the unnerving being, and it descended on him, quicker than a being that size should move. "Enough!" Gideon roared. He sent the blades of his sural out to snare a helmet-sized, pointed piece of hedron that tapered at one end like a crude awl. As the Eldrazi swooped low, Gideon swung. Hedron connected with boney faceplate. No shriek of agony followed. No spurt of blood welled. Just a brittle snap, the combined force of Gideon's swing and the Eldrazi's own momentum driving the ancient stone deep. A moment later, the Eldrazi collapsed, unmoving. Gideon untangled his sural and sank to the ground. Blood continued to pump furiously through his veins, and he was aware of how much the pounding in his temples stood out against the sudden silence of his surroundings. His dust-caked face was streaked with lines of sweat, but the sun felt good on his face and he was smiling. To his right, something approached. Several things, moving swiftly through the tall grass in his direction. From his position, he saw a dozen or so figures nimbly making their way across the field of fallen hedrons. They were mostly kor, but Gideon noted elves, humans, and even a pair of goblins among them. At the head of the group was a particularly broad kor. Like others, his pale bare chest and bald scalp were covered in angular white tattoos, and he held a pair of hooked blades that were connected by a length of chain. He crouched as he ran, and the various climbing lines he carried at his belt bounced with each step. "Munda!" Gideon called out. At the sound, the approaching group went to ground. All except the lead kor, who stood alert but still, his brow fixed in a practiced furrow. The kor cocked his head trying to make out the source of his name among the tall grass. "Careful now, people," Munda called over a shoulder, his tone rich with amusement that struck Gideon as contrary to the kor's characteristic dourness. "A Gideon prowls these lands, and it looks to be guarding its kill." They must have had a successful hunt. The thought made Gideon's smile widen. "It's good to see you, my friend," he said. Munda, called the Spider by those who have seen him in action weaving his ropes to trap and inhibit the Eldrazi, was both cunning and bold in a fight, and Gideon had liked him immediately. Munda waved a blade at the Eldrazi corpse. "And you. Your timing couldn't be better," Munda said in what had become a running joke between them, as there was always some peril to confront. "Looks like you haven't wasted any time, either. Thank you for that. We just destroyed one as well, but there were four of them. Have you seen the others?" Gideon casually pointed over his shoulder with his thumb, indicating the direction beyond the Eldrazi carcass. Munda eyed Gideon suspiciously. "Ready yourselves," he said to the others before climbing the Eldrazi carcass for a better vantage point. Peering out over the plain, he spotted his quarry, two lifeless heaps of magenta and blue against the golden grass. "Have a look, everyone. This is how it's done." He leapt off the carcass, and his soldiers scrambled around him to admire Gideon's handiwork. Munda put a hand on Gideon's shoulder, and Gideon saw that the time for levity had passed. "We got word this morning that <NAME>, the entire continent, has be overrun and destroyed. There's nothing left." Gideon stared past Munda, watching the grass bend to the subtle wind. "Like Sejiri," he said finally. "Just like Sejiri," Munda confirmed. "Survivors will be landing on the coast. Commander Vorik sent Tazri and her band to escort them to Sea Gate, but…" "You don't think it will be enough. "There's more trouble coming, Gideon." It was a truth. Not some doomsayer's prophecy, but an inevitability that his drooping shoulders and bloodshot eyes had been screaming at him for days. "I'll be there," Gideon said. Munda held out a water skin, a small comfort that Gideon took as an act of understanding. The people of Zendikar were realists, the product of a plane where survival depended on skill and will and wit. With that came a people who knew the value of the little things. A cool gulp of water rolling down a parched throat was a joy to be recognized. Around them, Munda's warriors were setting up camp. One of the goblins knelt over the upturned shell of a scute, working to build a modest cook fire inside it, while others stood watch or took what rest they could in the cool of the grass. "How long has it been since you last slept?" Munda asked. Gideon didn't know for sure. The pleasure of closing his eyes and drifting out of consciousness had eluded him for quite some time, and the comfort of a bed suddenly seemed like a distant memory. "Days," was all he could say with any degree of certainty. "Rest for a bit," Munda said. "It looks like you could use it." "Thanks, but not yet." Trouble #emph[was] coming. It was here already, and it wasn't just on Zendikar. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = Ravnica The light drizzle that had been falling on Ravnica for more than a month did little to keep Tin Street from burning. Nor Foundry Street, when it went up the night before. #figure(image("003_Limits/02.jpg", width: 100%), caption: [Five-Alarm Fire | Art by Karl Kopinski], supplement: none, numbering: none) "A goblin gang war's a messy thing, Jura," <NAME>, a captain in the Boros Legion, had said as he and Gideon watched an empty warehouse give in to the ravages of angry flames. They had risked the inferno in search of survivors, but found only the charred bodies of six goblins. "This is the first reprisal of many," the captain continued as he wiped the film of ash from his face, "and the gutters'll carry away more than just rain water in the coming days, you mark my words." That was two days ago and, as Dars predicted, the tally of dead goblins rose. The whole thing started with a murder—Dargig, a black market weapons runner who specialized in explosives. He had a reputation for running his mouth, but he also happened to be the youngest of the notorious Shattergang Brothers. The way Dars explained it to Gideon, Dargig had been found in an alley off of Tin Street in a pool of blood, stabbed in the throat. Word spread that the goblin criminal kingpin, Krenko, did the deed himself when a weapons drop went bad. #figure(image("003_Limits/03.jpg", width: 100%), caption: [Shattergang Brothers | Art by <NAME>er], supplement: none, numbering: none) The following night, a series of explosions shook the district, and several of Krenko's warehouses went up in flames. It was the Shattergang way of declaring war. And Krenko obliged all too enthusiastically. Gideon had personally petitioned the Chamber of the Guildpact to intervene, which essentially boiled down to adding his name and guild to the bottom of a very long wait list. The Living Guildpact. <NAME>. Planeswalker. The one who solved the puzzle of the Implicit Maze and became the embodiment of a magical treaty that kept Ravnica's guilds from devouring each other. These goblins belonged to none of Ravnica's guilds. As long as it was just goblins killing goblins, most guilds were content to observe the conflict from behind the safety their guildgates. As long as the fighting continued, the unguilded population—the gateless—was in danger. Unacceptable. #figure(image("003_Limits/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) It was just after midnight when the heavy iron doors of the garrison flew open, a commotion that had a dozen Boros Legionnaires shooting up from their places at the long wooden table that stretched across chamber. Some were reaching for weapons, and Gideon stood in the tall arched doorway with his wet hair clinging to his shoulders. "At ease," called one of the soldiers, "it's Jura." "And I come bearing gifts," said Gideon, and he shoved something into the room that had been obscured by his own silhouette. A goblin, bound at the wrists, was grinning with jagged, yellowed teeth that caught the dim lamplight. Krenko. The goblin surveyed the soldiers, his surroundings, and the soldiers again, each of whom gaped at him in disbelief. "It's a fine garrison, soldiers," Krenko said, still grinning. "No Sunhome, to be sure, but it'll do." Gideon limped into the chamber, his right foot leaving splotches of blood with each step. "I'm going to assume that there's a mess somewhere out there on your account, Jura," said Dars who strode in from an adjoining chamber. "I hope you didn't like the food over at The Millennial." The Millennial was a beyond-upscale restaurant that had been built on an exclusive observation deck of the same name. Since Krenko's rise to power in Ravnica's organized crime circles, he was known to spend his evenings there. So that's where Gideon went. "Could never get a table," Dars replied. "I can't imagine you found him sitting there eating dessert by himself, though." "Not exactly." "You shouldn't have gone alone. But I have to admit that I'm impressed, and that doesn't happen very often." "Don't be too impressed." Gideon unbuckled his greaves and rolled his right pant leg up above the knee. Gideon had tied one of the Millennial's cloth napkins around his leg, but it was now soaked through, and was doing little to keep the wound bound. "That grinning stain stuck a shiv in my leg." "Twice," Krenko said, punctuating his triumph with a wheezing laugh. Gideon's anger flared. "You stand here laughing while your fellow goblins die in the streets." Dars put a hand on his shoulder. "You should get to a surgeon." "Probably," Gideon replied, but his word was swallowed up by the sound of shattering glass as a small skylight in the high ceiling burst to pieces. Gideon and Dars turned in time to see a small oblong object falling toward the ground. As it tumbled end over end, Gideon noticed a small glowing red-orange bead that dangled off of one end. A fuse. "Bomb!" Gideon yelled, shoving Dars aside. He grabbed the explosive before it could hit the floor, pulling in toward him until he was cradling against his abdomen. Whorls of magical, golden light erupted across the entire surface of his skin in anticipation of the blast. He crouched there, eyes clenched for a long moment. Nothing. Slowly, Gideon opened his eyes and looked down to find his hands gripping a glass canister topped with a brass stopper. "Secure the area!" Dars's command broke the silence. "I want answers!" Gideon righted himself, turning the canister over in his hands to examine it. "A dud?" Dars asked. "Not a bomb. Look." Gideon removed the stopper, and extracted a coiled ribbon of paper from the glass tube. He unrolled it. A message, scrawled with a practiced hand, stretched across narrow strip in a single line. It was meant to be clear, its message unmistakable. Gideon read. "Krenko murdered our brother. If justice is to be done, it is ours to exact. Turn him over to us, or we will reduce Boros territory to rubble. All of you and all you love will be fair targets if you disregard this message. Is Krenko worth that much to you? You have until this time tomorrow to decide. Kindly, Rikkig, and Gardagig, the Shattergang Brothers." There was no time for this. Not now. Gideon had to return to Zendikar. He threw the empty canister against the stone-slab floor. "Decision time," Krenko taunted. "Get him out of here," Dars barked. "I want him behind bars." "You see, Jura," Krenko said, as soldiers dragged him away, "the Boros won't turn me in to the Shattergang Brothers. What now?" #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = Zendikar Just as Munda said they would, survivors from Bala Ged landed on the coast. No more than three-hundred of them, by Gideon's cursory count. But they weren't the string of beaten and broken refugees Gideon had anticipated. They were fighters, hardened by what they had seen and by the people they had lost, but also resolved to continue. And as Munda said, they needed help. But then, Gideon probably would too. Shield scuffed, and sural unfurled, Gideon planted himself in the narrow path that twisted its way between the chalk cliffs rising up from the shore. #figure(image("003_Limits/05.jpg", width: 100%), caption: [Plains | Art by Véronique Meignaud], supplement: none, numbering: none) The ground rumbled, and the vibrations woke the wounds that buzzed in his leg. Stay focused. There would be time for Ravnica once this was finished. Behind him, the survivors followed Tazri's vanguard up the path toward the open scrubland beyond. Movement above him caught Gideon's attention, and he took his eyes from the canyon floor long enough to see Munda and some of his chosen driving heavy iron spikes into the cliffs on either side, about twenty feet below the edge. They'd have to hurry. One of the kor on the cliffs stopped hammering suddenly and let out a shrill whistle, pointing frantically in the direction of the shore. The Eldrazi were here. He had one task—buy enough time for Munda's people to do their work. Slow the Eldrazi, destroy them—it didn't matter as long as the survivors could continue being just that. Tazri said that there were Eldrazi experts among them heading for the Lighthouse at Sea Gate. If that was true, they had to get there. The first of the monsters came into view where the path straightened out below. Gideon swung his sural blades back so that lay spread out behind him, poised to lash out when called upon. Here he was, between what remained of <NAME> and a carpet of Eldrazi that raced through the canyon on countless scrabbling limbs and slick slithering tendrils. Then they were on him. Gideon let his sural fly, the steel ribbons extended to their full length, catching the air so that they hummed as a single razor sharp blade that cut several spawn down. He let the momentum of his swing bring his shield to bear, punching so the shield's toothed edge bit deep into the flesh of another Eldrazi spawn. Gideon danced away from a heavy tendril on a course to crush his skull, and he countered by sending his sural blades to coil around it. He gave his wrist a quick twist. The blades bit into the soft flesh and Gideon moved with the spawn's weight, angling for a shot with his shield. But the entire appendage fell away as though jettisoned. The sudden release pulled Gideon off balance, and the pain above his knee surged. He lost his footing, and the sural blades sprung wildly. One slid across the flesh of his cheek leaving a line of deep red from the corner of his mouth to his ear as it whipped past. #emph[Sloppy] , Gideon cursed himself for the mistake. But he was tired. As the blood ran warm along his jaw, he cursed himself for the excuse. He should have seen it coming. Just like he should have seen Krenko's shiv. He had to get back to Ravnica. This was taking too long. Where was Munda? He really had to get out of his head. The Eldrazi spawn pressed in on him, their pale faceplates filling his vision. He looked from one to the next, each one a featureless mockery of human skulls. The sheer blankness of the faces struck Gideon as somehow contrary to thoroughness with which the Eldrazi set about their destruction. It was a pure horror to behold, lacking any semblance of humanity. They were not brutes like Gruul ogres, or sadistic like Rakdos bloodwitches. They were not recklessly dangerous like Krenko's goblins. The thought fueled Gideon, it dulled the bite of his wounds, and breathed life back into his tired limbs. He didn't have to hold back. Don't hold back. The sural blades flicked out again and again, Eldrazi muck thick around Gideon's boots—where dozens of spawn lay. His muscles burned. His temples pounded. And the Eldrazi fell as fast as they approached. Gideon bared his teeth, an expression that was somewhere between grimace and grin. Three sudden sharp whistles cut through the din of the fighting. It was time, and Gideon responded with three identical whistles of his own. Above the carnage, Gideon saw a woman step off the edge of the canyon wall that rose up on the left. She floated there for a moment, and then rose gracefully above the canyon where he extended his arms out to either side. "I'm afraid this is where I leave you, vermin," Gideon said, spinning out of a spawn's grasp. #figure(image("003_Limits/06.jpg", width: 100%), caption: [Staggershock | Art by Raymond Swanland], supplement: none, numbering: none) There was a blinding flash as bolts of lightning arced from the mage's fingertips, finding the iron spikes that jutted out from canyon walls. The crackling energy rode the lengths of metal into the brittle, chalky stone, exploding in a succession of deafening pops. A sound like the splintering of an enormous bone filled the canyon, and cracks erupted from the various spikes until the tops of both cliffs gave way, and sheets of white stone tumbled toward the Eldrazi below. Gideon vaulted off the canyon wall to get clear of the Eldrazi. A heartbeat later he was sprinting up the path and out from under the falling rock. When the stone crashed, the ground jumped. Gideon couldn't keep his feet, and he was thrown hard to ground. A great cloud of pulverized stone rose up, and as it washed over him, he had to bury his face in the crook of his arm to keep from choking on it. Gideon heard skittering. Gathering himself into a crouch, he probed the haze through squinted eyes, straining to discern shapes or movement. No time for this. He had to get back to Ravnica. More skittering, accompanied by the slithering squish of Eldrazi tendrils. But other sounds as well—recognizable ones. War shouts. The ringing of blades. Munda. Gideon rose, and though the chalky dust still hung in the air, shapes and colors were reemerging. He raced forward, sural ready. But when he found Munda, the kor was tethered to a climbing line, and he was dislodging one of his hooked blades from a lifeless spawn. The whole scene was set against a backdrop of shattered stone slabs that filled the canyon floor, completely obscuring the narrow path beneath, as well as countless Eldrazi. Accompanying Munda were a dozen other kor, who were at work finishing off the remaining handful of spawn that had eluded the ambush of stone. "Your timing couldn't have been better, my friend," Gideon said through a tired smile. Now he could get back to Ravnica. There was still time to stop the Shattergang Brothers, but not much. However, when Gideon saw a grimness in Munda's face that was exceptional even for his friend, his own smile faded. "What happened, Munda?" "A great host of Eldrazi descends on Sea Gate." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = Ravnica Rain had saturated the bandage on his cheek and it sagged soggily, exposing the deep cut beneath. He'd have to take care of it later. There were prisoners down here somewhere. First things first. #figure(image("003_Limits/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Gideon crashed into the old door. The hinges gave instantly, and he followed after the splintering wood that flew into the dark chamber beyond. The pain in his leg crescendoed with the impact, and to keep from crying out Gideon inhaled sharply. A scent that was both sweet and caustic filled his nostrils. It was the same odor that he smelled on Gardagig, when the goblin had given up the location of the Shattergang hideout. Explosives. Stay sharp. "You haven't brought Krenko with you," came a voice, low and gravelly from behind a heavy, cluttered workbench. "Am I safe to assume that?" "You're not safe to do anything, Rikkig, unless you come with me right now." A staccato growl that Gideon took to be a laugh filled the chamber. He heard shuffling. A lantern that hung from the low ceiling revealed an awkward, bulky silhouette that Gideon didn't understand at first. But then a discernable shape emerged. It was a figure clad in a thick, heavily padded suit. On its head was a helmet not unlike a knight's, but with goggles fixed into the visor. "Quite arrogant, you Boros. You pick up Krenko and try to deny us satisfaction." He was holding something. Glass, by the way it picked up the lantern light. A bomb. And he was wearing protective armor. "Krenko will be ours, only now the district will burn for –" No more. This had to end. Planting his wounded leg, Gideon kicked the workbench with all the strength he could manage, sending it sliding into Rikkig with such force that the goblin's breath escaped his lungs all at once in a rattling, punctuated moan. He doubled over the workbench and the bomb flew from his grip. Gideon moved to intercept, but his limbs were heavy and slower than usual. In slow motion, the bomb sailed past his reach, and Gideon was only able to pivot so that his body was between Rikkig and the point where the delicate glass container shattered upon the floor. When the explosion came, golden light flared up all across the front of his body, shielding him from flying debris. The sound was momentarily absolute, drowning out all else until only a high hum hung in his ears. Flames had sprouted all around the room. It was difficult to focus, but he heard Rikkig coughing and struggling to unpin himself from between the workbench and the wall. Gideon spun around, jerked the workbench back, and Rikkig collapsed to the ground. Gideon stood over him. "The Boros didn't take Krenko. I did. Just like I got your brother. And now I'm here for you." There was a muffled wail that Gideon first thought belonged to Rikking, who was raising his hands defensively. But another wail confirmed otherwise. "Help!" The prisoners. Gideon glanced around the room until his eyes settled on a dark wooden bookcase that was filled with what Gideon assumed were bomb-making tools and ingredients. Fire was caressing its base, threating to grab it and ignite its volatile contents. And of course, the wail he heard had come from behind it. Reckless, he scolded himself. And stupid. Gideon left Rikkig in a heap, and raced to the bookcase. He put his shoulder against it and pushed. Sweat collected at the end of his nose and chin, and every muscle begged for rest, but the heavy bookcase refused to yield even an inch. Gideon shut his eyes to the smoke that filled the room, and he struggled to gulp the necessary breath to continue. His strength had begun to fail when, suddenly, the bookcase yielded and lurched forward. His eyes flew open, and Gideon saw Dars and another Boros legionnaire lending their strength to his efforts. Together, they pushed until the bookcase slid aside to reveal a narrow, round passage. Gideon slumped against the bookcase in a fit of coughing. "Prisoners," he managed, and Boros soldiers filed past him into the passage. Dars remained with Gideon. "Rikkig?" Gideon asked. The captain shook his head. Gideon looked across the room. Rikkig was gone. His shifted his gaze to Dars. "You followed me." "Clearly I had reason. You didn't have to do this alone, Gideon. We fight as a legion because some things are bigger than us." "I had him, Dars." "We'll find him. As a legion, we'll find him. You have a rest." Not yet. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = Zendikar When the attack on Sea Gate came, it came crashing down on the settlement with a speed and ferocity that simply overwhelmed its militia. The Eldrazi swept in from both sides of the sea wall. Some even surged from the sea to scale the face of the sea wall itself. There were simply too many. Commander Vorik had given the signal to evacuate, but it wasn't going fast enough. But then again, neither was Gideon. Four days without sleep. Or was it five? He #emph[did] manage close his eyes for a few minutes as he rode here from the Commander's camp. So why was he so tired? Not now. Gideon strained against a thick wooden beam that pinned him to the floor of a building that was crumbling around him, but it was no use. The beam had fallen across his body when an airborne Eldrazi landed a powerful swipe that sent him crashing into the building. No time for this. His left arm was free as well as his head, but that was it. With his teeth, he unfastened the leather straps of his buckler. Once he shook it free of his hand, he wedged it as best he could between his breastplate and the beam. It just had to budge a little, and he pushed with everything he could muster. A grunt erupted into a roar, and the beam moved. Gideon shifted his weight, and the beam rolled free of him. Wearily, he climbed to his feet. One of the wounds above his knee had reopened—perhaps both—and blood ran down his leg. He reached for his buckler, and as he worked it back onto his left hand he scanned the ruins around him. There were bits of broken furniture strewn about along with shattered ceramic plates. This was someone's home. And this was going to be the fate of Sea Gate. He had been told that Sea Gate was the largest settlement in all of Zendikar. It was a narrow strip of civilization clinging to the top of the ancient white dam that gave Sea Gate its name, and the Eldrazi had set about reducing the settlement, and all its people, to dust. Gideon filled his lungs and made for the crumbling doorway that led back to the carnage beyond. He was at the threshold when a figure rounded the corner, blowing past him into the building. He had to spin to one side to avoid a collision. "Quick now, I need your help," the figure said in a manner that was more command than request. A merfolk. She was bleeding from a gash above her eye and she was holding someone, a human woman, who sagged limply in her arms. Both were clad in armor—the merfolk in the shell-like scale and plate armor that was typical of her kind, and the unconscious one in cobbled steel plate. The merfolk had a spear slung across her back. These two were not new to the horrors of the Eldrazi. Gideon helped the merfolk lay the unconscious woman against the shattered remnants of a wall, and the two worked together to unfasten the crushed plates of that were supposed to protect her. Beneath the armor, the woman's skin was a desiccated, eroded husk that mirrored the spongy ash-colored, pitted bone texture of Eldrazi ruin. He'd seen it before. It's how the Eldrazi leeched energy from the world. It was not a wound. She died the moment the Eldrazi got to her. The merfolk also knew what it meant, for she stopped, and sunk to the ground beside the still body, staring blankly at the devastation. Gideon knelt. "What was her name?" "Kendrin," she said, placing her hand on the dead woman's forehead. "You'll have to grieve for Kendrin later. You have to get out of here now." "You don't understand." She looked up, shifting her gaze from Kendrin to Gideon. "There's no time. We barely made it out of Bala Ged alive. We saw its destruction." "You were among the survivors that landed yesterday." "Yes. Kendrin was on the brink of a discovery. The 'puzzle of leylines,' she called it. The hedrons. The Eldrazi. The connection—she was so close. She said it all pointed to the Eye, and that she had to come here to see the Lighthouse's records on the Eye." "You just have to get to the Lighthouse? You can get your answers there?" The merfolk shook her head. "We were just there. There's nothing left inside. We were attacked trying to get out. Besides, Kendrin was the expert, not me. I was her escort on her expeditions…and I failed." She slammed her fist against the stone wall, and a moment later, the whole wall seemed to explode outward over empty space. The merfolk would have tumbled backward with it over the side of the sea wall had Gideon not grabbed hold of her hand. Enormous tendrils appeared, yanking away the remaining masonry so that their source came into view—an Eldrazi monster, faceless and terrible, at the end of its ascent up the vertical expanse. Tendrils continued their devastating course, threshing stonework until only powder remained. #figure(image("003_Limits/08.jpg", width: 100%), caption: [Ancient Stirrings | Art by Vincent Proce], supplement: none, numbering: none) Gideon and the merfolk scrambled up a pile of rubble that had once been a second and third floor. From their position, Gideon could see the devastation that stretched out from one end of the sea wall to the other. Many of the buildings were in ruins, and many more had been pulled completely from the top of the wall so that the water on both sides ground the wreckage against the wall's smooth face. The Zendikari were a resilient lot, and even now, he saw that many continued to fight in defensive pockets. They had been destroying Eldrazi all day, but it wasn't enough. The truth of it was Sea Gate was lost. This approach was not enough. #figure(image("003_Limits/09.jpg", width: 100%), caption: [Pathrazer of Ulamog | Art by Goran Josic], supplement: none, numbering: none) But perhaps it was as she said, though—Kendrin found an answer. The puzzle of leylines. The notion smoldered within Gideon, and suddenly burst into flames. Fighting to avoid something was not the same as fighting for something. Kendrin's puzzle was a possible answer. That was enough for now. They just needed another expert. "What's your name?" Gideon asked as they leapt to either side of a tendril that smashed down between them. "Really? Now?" "I'm going to find someone who can help. But I'll need to find you after." She threw her spear at the Eldrazi as it slowly pulled itself over the edge of the wall into the broken dwelling. The spear found its mark with a crunch, sinking into the featureless faceplate. The Merfolk's eyes flash fleetingly with red energy, and the wound she opened began to hiss and steam. "I'm <NAME>," she said through gritted teeth as tendrils flailed about furiously. "<NAME>, get to Commander Vorik's camp. You have to make it. I'll find you." And the next moment Gideon's sural blades flew, grabbing hold of Jori En's spear, which had remained lodged in place. He hurled himself into the air, and at the apex of the swing he hit the toggle on his forearm to trigger the retraction mechanism of his sural. But instead reeling in his blades, the force jerked him toward Jori's spear and he rammed into the Eldrazi's face with such force that it was carried over the edge and back toward the sea below. In a tangle of tendrils, Gideon fell with it. Stay focused. He had to get free of the Eldrazi, or it would drag him beneath the surface. His hands fumbled at the sural blades, attempting to release them from spear, but the Eldrazi was tumbling through the air fast, and Gideon lost his grip. He was free falling, but still anchored to the Eldrazi, and all he could do was ready himself for impact. The Eldrazi hit first, and Gideon's entire body erupted in bands of golden light as he too crashed through the surface of the sea. The Eldrazi fell to pieces instantly, and Gideon was tossed around beneath the churning water. He struggled to orient himself in the midst of the slurry of sea water and Eldrazi bits. At last he surfaced, gulping for air. With the last of his strength, he kicked his way over to the collection of detritus that lined the base of the wall. He found the remnant of a wooden table, and clung to it. From above, the sounds of slaughter could be heard over the surf and he tilted his head up to where Eldrazi swarmed over Sea Gate like angry ants. Gideon knew he had no time to waste. He had an expert to find. He closed his eyes, and he felt the world around him melt away. The coldness of the sea faded and he felt stone beneath his feet. The sound of lapping waves gave way to the din of the city. Sounds he knew. Sounds of Ravnica. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = Ravnica Bruised and bloodied, Gideon stood at the bottom of the flight of stone steps that led to the Chamber of the Guildpact. Zendikar was still in peril. Force of arms alone would not be enough to achieve victory. There had to be some other answer. Was it, as Jori said, the puzzle of leylines? Who then was better suited for the task than the one who solved Ravnica's maze? The Living Guildpact. The Planeswalker, <NAME>. Gideon ascended the first step, tried for another, but gravity had him, and he collapsed.
https://github.com/Ofure004/Project-stuff
https://raw.githubusercontent.com/Ofure004/Project-stuff/main/Ofure's%20project.typ
typst
#import "template/bach.typ": bach, table-figure, code-figure #show: content => bach( title: "Intelligent Software Tool for Scheduling Nurses in Hospitals: A comparative study of two Ant Colony Optimisation Hyper-heuristic schemes", author: "<NAME>", matric: "20CG028069", dedication: [I dedicate this project to God, without whom none of this would have been possible. I also dedicate this work to my supervisor who has been there to help me whenever I needed it, and to my friends and family as well, for the support.], acknowledgements: [My most profound gratitude goes to Almighty God, who has kept me and sustained me right from the very start of my degree up until this point. To Him be all the glory. \ I am extremely grateful to my parents, Mr and Dr Ehiremhen for their sacrifices, contributions, and prayers towards the completion of this degree. I also want to appreciate my amazing siblings, for their pieces of advice, support and encouragements during the course of this project and degree. I am extremely privileged to have them in my life. \ My sincere gratitude also goes to my hardworking supervisor, Dr <NAME>, who is always there when I need him. Thank you so much for your excellent supervision and guidance.], supervisor: "Dr. <NAME>", reference-path: "../references.bib", content, ) = Introduction == Background Information \ The healthcare industry, particularly the management of nursing staff in hospitals, has always been a critical and challenging domain. With the increasing demand for healthcare services, efficient scheduling of nurses has become a pressing issue. Properly scheduling the nursing staff has a great impact on the quality of health care (Oldenkamp, 1996), the recruitment of nursing personnel, the development of a nursing budgets and various other functions of the nursing service (Cheang et al., 2003). Historically, nurse scheduling has been a manual and time-consuming task, often leading to suboptimal schedules and resource allocation. The advent of intelligent software tools presents a promising solution to this long-standing problem. \ Despite the critical role of nurse scheduling, various challenges persist within this domain. These challenges include the need to balance to satisfy various hard constraints such as legal requirements, staff preferences, and institutional regulations, and as many soft constraints as possible, such as minimal nurse demands, “day-off” requests, personal preferences, etc. Traditional scheduling methods often struggle to efficiently navigate these multifaceted constraints, resulting in suboptimal nurse schedules that can lead to decreased staff satisfaction, increased burnout, and ultimately, compromised patient care. Additionally, the ever-changing nature of healthcare environments exacerbates the complexity of nurse rostering, demanding adaptive and intelligent solutions capable of optimizing schedules in real-time. \ Despite the growing interest in intelligent scheduling tools, there's a notable research gap concerning the exploration and comparison of specific optimization techniques, such as Ant Colony Optimization (ACO) hyper-heuristic schemes, for nurse scheduling. While ACO has been successfully employed in various optimization domains, its application in nurse scheduling remains relatively underexplored. This project aims to address this gap by proposing an intelligent software tool that utilizes two distinct ACO hyper-heuristic schemes tailored for nurse scheduling. Drawing inspiration from successful applications in related fields, this proposed solution seeks to demonstrate its effectiveness in navigating the intricate constraints of nurse rostering and overcoming the specific challenges encountered in nurse scheduling. \ Over the years, various scheduling algorithms have been employed by researchers to solve this problem. These methods include Tabu Search (Burke, Kendall, & Soubeiga 2003), Variable Neighborhood Search (Bilgin et al., 2012), Simulated Annealing (Brusco & Jacobs, 1995), Ant Colony Optimization (Gutjahr, & Rauner, 2007), Branch-and-price Algorithm (Maenhout, & Vanhoucke, 2010), Harmony Search (Awadallah et al., 2013) and Scatter Search (Curtois & Berghe, 2010). A comprehensive analysis reveals that the existing works often fall short in effectively addressing the intricacies of nurse rostering problems, and whose main disadvantage lies in its high computational complexity which limits their application only to small size instances, and when attempted to be scaled, either cost too much computation, or have difficulty in constraint handling. Therefore, alternative optimization methods, namely heuristics and metaheuristics have been developed in order to find suboptimal solutions of good quality in a reasonable time. Existing works in this field have primarily focused on traditional scheduling methods or have explored single heuristic or metaheuristic approaches. The opportunity lies in the comparative evaluation of multiple ACO hyper-heuristic schemes, which has not been extensively addressed in the context of nurse scheduling. Methodologically, this study presents an opportunity to fill this gap by rigorously comparing the performance of distinct ACO hyper-heuristic schemes in the context of nurse scheduling. \ The hypothesis of this study is that the comparative analysis of two ACO hyper-heuristic schemes will reveal significant differences in their effectiveness for nurse scheduling. This approach is significant as it aims to provide empirical evidence to support the selection of the most suitable ACO hyper-heuristic scheme for nurse scheduling, thereby improving the efficiency and fairness of the scheduling process. In summary, this research seeks to address the existing gaps in nurse scheduling methodologies and to contribute to the advancement of intelligent software tools for nurse scheduling, ultimately enhancing both staff satisfaction and the quality of patient care. \ == Statement of the Problem \ Although the interest in intelligent scheduling tools is on the rise, there exists a research gap in the exploration and comparative analysis of specific optimization techniques, such as Ant Colony Optimisation (ACO) hyper-heuristic schemes, for nurse scheduling. While ACO has been applied to various optimization problems, its application to nurse scheduling remains relatively unexplored. This project aims to bridge this gap by proposing an intelligent software tool that utilizes two distinct ant colony optimization hyper-heuristic schemes for nurse scheduling. Drawing inspiration from successful applications of similar approaches in related domains, this proposed solution seeks to demonstrate its efficacy in handling the intricate constraints of nurse rostering and addressing the specific challenges within the nurse scheduling domain. \ To address the identified research gap, this study proposes an innovative solution through a comparative analysis of ACO hyper-heuristic schemes. By leveraging insights gained from related domains and successful applications of similar approaches, the research aims to unveil the nuanced performance differences between the identified ACO hyper-heuristic schemes, providing empirical evidence to support the selection of the most suitable ACO hyper-heuristic scheme for nurse scheduling. The objective is to develop an intelligent software tool specifically tailored for nurse scheduling, leveraging two different variations of the Ant Colony Optimization algorithm, in order to juxtapose the results gotten from both of them and prove which is best suited for the problem, thereby enhancing adaptability and efficiency within hospital settings. Through this exploration, the study seeks to contribute valuable insights and advancements that can significantly improve patient care, staff satisfaction, and the overall operational efficiency of healthcare institutions. \ == Aim and Objectives of the study \ The aim of this study is to develop an intelligent software tool to solve the Nurse Rostering Problem using two ant colony optimization hyper-heuristic schemes. The objectives of this study include: + To extensively review and study existing ACO metaheuristic schemes to get a better understanding of how the general algorithm works towards applying them as hyper-heuristics. + To implement two selected ACO hyper-heuristic schemes. + To develop an intelligent software tool for nurse scheduling using the selected ACO hyper-heuristic schemes. + To test run the ACO hyper-heuristic schemes on the NRP instances. + To evaluate and compare the results of the two ACO hyper-heuristic schemes and identify the most suitable scheme for nurse scheduling. + To compare the most suitable ACO scheme gotten from the previous evaluation with other existing heuristic schemes in literature. \ == Methodology \ The tools and techniques I intend on adopting to achieve the above objectives include: + To achieve objective 1, there is going to be a comprehensive review on existing literature related to ACO meta-heuristic schemes. + To achieve objective 2, implementing the selected ACO hyper-heuristic schemes in the Java language. + To achieve objective 3, developing the software tool on the Hyper Heuristic Flexible Framework(HyFlex) and using swing GUI for the interface. + To achieve objective 4, implementing the developed tool in a simulated environment and obtaining the objective function values of the hyper-heuristic schemes on the NRP instances. + To achieve objectives 5 and 6, employ statistical methods to compare the results obtained from the two ACO hyper-heuristic schemes, evaluating them using metrics like Formula one scoring, Box-plot visualization and average normalization and identifying the most suitable scheme for nurse scheduling. #table-figure( "Objectives-Methodology Mapping Table", table( columns: (.5fr, 2fr,2fr), align: (center, left, left), [S/N],[*OBJECTIVES*], [*METHODOLOGY*], $1$, [ Reviewing of already existing Ant Colony optimization meta-heuristic schemes, in the context of nurse scheduling. ], [*Extensive Literature Review*\ Review of literature on already Ant Colony meta-heuristic schemes in order to get a deeper understanding.], $2$, [ Implementation of two selected ACO hyper-heuristic schemes ], [*Software Development and Algorithm implementation*\ Adoption of the JAVA programming language to implement the two Ant Colony hyper-heuristic schemes. ], $3$, [ Development of an intelligent software tool for solving the nurse rostering problem using the selected and implemented ACO hyper-heuristic schemes ], [*Software Development*\ developing the software tool on the Hyper Heuristic Flexible Framework(HyFlex), using the JAVA swing UI for the interface. ], $4$, [Test-run the ACO hyper-heuristic schemes on the Nurse Rostering Problem instances.], [ implementing the developed tool in a simulated environment and obtaining the objective function values of the hyper‑heuristic schemes on the NRP instances. ], $5$, [Evaluation and comparison of the results of the two ACO hyper-heuristic schemes and identify the most suitable scheme for nurse scheduling. .], [ employ statistical methods to compare the results obtained from the two ACO hyper-heuristic schemes, evaluating them using metrics like Formula one scoring, Box-plot visualization and average normalization and identifying the most suitable scheme for nurse scheduling. ], $6$, [Comparison of the most suitable ACO scheme gotten from the previous evaluation with other existing heuristic schemes in literature .], [ Same methodology as above ], ) ) \ == Significance of the study \ The significance of this study lies in its potential to revolutionize nurse scheduling practices within hospital management, offering substantial benefits to healthcare institutions, nursing staff, and ultimately, the quality of patient care. The study is important for the following reasons: + The study is important in the sense that it will contribute to the advancement of knowledge, and help to bridge the knowledge gap in the field by comparing the performance of two ACO hyper-heuristic schemes inorder to prove which one provides a more optimal schedule, since existing works in the field have primarily focused on traditional scheduling methods or single heuristic or optimization techniques. + Healthcare managers and decision-makers stand to benefit from the study's recommendations and guidelines for implementing the intelligent software tool. The insights gained from the research can inform strategic decision-making on the applicability of advanced scheduling technologies like ACO hyper-heuristic schemes in solving the nurse rostering problem. \ == Limitation of the study \ While Ant Colony Optimization (ACO) meta-heuristics offer a powerful approach to solving Nurse Rostering Problems (NRPs), they are not without limitations. These limitations can become particularly pronounced in large-scale NRP scenarios that are heavily constrained. ACO algorithms can struggle to effectively handle these complex constraints, potentially leading to suboptimal solutions that don't fully satisfy all requirements. Additionally, achieving optimal convergence with ACO, where the absolute best solution is found, can be challenging, especially with highly constrained problems. Finally, tuning the internal parameters of ACO can be a time-consuming process. Since our proposed hyper-heuristic schemes are built upon these ACO meta-heuristics, they will inevitably inherit some of these limitations. \ == Organization of the Project \ Chapter One of the project contains an introduction to the project: an explanation of the project, the problem I am trying to solve, problems with existing solutions and methods, the method of implementation, the significance of the study, and the limitations. Chapter Two describes the existing systems and methods related to the project topic, the methodology, algorithm, and techniques used in related systems, as well as related works. Chapter Three describes the analysis and system design. Chapter Four shows the implementation of the system in detail and the results obtained. Chapter Five summarises the project and gives recommendations, suggestions, conclusions, and references. #pagebreak() = Literature Review == Preamble \ As the demand for quality healthcare services continues to rise, the need for intelligent software tools to streamline and optimize nurse scheduling processes becomes increasingly evident. \ This chapter delves into a comprehensive exploration of existing literature, theories, and methodologies relevant to nurse scheduling, with a specific focus on the application of Ant Colony Optimization (ACO) hyper-heuristic schemes. Through a comparative study of two ACO hyper-heuristic schemes, this research aims to advance scheduling practices in healthcare. By meticulously reviewing scholarly works, this chapter identifies gaps, challenges, and opportunities in nurse scheduling, paving the way for empirical investigation and evaluation of an intelligent software tool. \ == Review of the Nurse Rostering Problem(NRP) \ The Nurse Rostering Problem (NRP), also known as the Nurse Scheduling Problem (NSP), was formally introduced in its current form in 1976 through parallel publications by Miller et al. and Warner (Chong et al., 2022). This problem involves assigning shifts and holidays to nurses while considering their individual preferences and constraints, along with the hospital's requirements. Various constraints, both hard and soft, shape the scheduling process, with hard constraints leading to invalid schedules if not met. Soft constraints, on the other hand, influence the quality of solutions without rendering them invalid. Coverage requirements, like, nurse demand per day, per skill, or per shift, are normally considered as hard constraints, while constraints that involve time requirements are usually regarded as soft constraints. Usually, nursing officers spend a substantial amount of time developing rosters especially when there are many staff requests, and where even more time can be consumed in handling ad-hoc changes to current duty rosters. Because of tedious and time-consuming manual scheduling, and for various other reasons, the nurse rostering problem (NRP) or the nurse scheduling problem (NSP) has attracted much research attention (Cheang, Li, Lim, & Rodriguez, 2003). \ Nurse Rostering Problems is a complex combinatorial optimisation problem, under the variant of staff scheduling problems and is known to be NP-hard, indicating its computational challenge. This means that there are many thousands of possible schedules, and the staff members may even be unable to determine whether or not there exists a solution at all. As the number of nurses, days in the schedule, and constraints increase, the NRP experiences a combinatorial explosion that makes it challenging to produce an optimal solution (Nasiri and Rahvar, 2017). \ Hospitals typically operate with three distinct work shifts—day, evening, and night—each spanning 7-9 hours, depending on local regulations. For instance, some hospitals implement three equal time spans of 8 hours for each shift, while others have shifts of 7, 8 and 9 hours, adjusting workload distribution throughout the day. Various local rules and policies, such as minimum nurse staffing requirements per shift, limits on daily and weekly work hours, and specific skill requirements, serve as constraints. The primary objective is to devise a cost-effective nurse-to-shift assignment that adheres to these constraints, encompassing both hard and soft constraints. Hard constraints are non-negotiable conditions that must be satisfied for a feasible solution, whereas soft constraints, although not mandatory, incur penalties if violated. Given their incorporation as costs within the objective function, we predominantly prioritize addressing hard constraints over soft constraints. In real world nurse rostering settings, the problems are nearly always overconstrained, so, it is unlikely to find a single schedule that perfectly adheres to all of them. An objective function helps us choose the schedule that comes closest to achieving our desired outcomes and is usually based upon some criteria set by the hospital mamagement. Hospitals usually seek to optimize specific types of objective functions when solving the NSP. For instance, objective functions related to staff satisfaction and balanced workload have received major attention in recent years. The most common staff satisfaction objective functions are typically related to the maximization of nurses’ preferences, where each preference of a single nurse can be related to desirable working shifts and days off during the planning horizon (Otero et al., 2023). \ The mechanisms and performance of the existing solution methodologies applied to the benchmark and real world NRPs can be classified into six categories namely heuristics,metaheuristics, hyperheuristics, mathematical optimization, matheuristics and hybrid approaches. Metaheuristics are the most common choice in addressing NRPs (Chong et al., 2022). Many heuristic approaches were straightforward automation of manual practices, which have been widely studied and documented (Jelinek & Kavois, 1992). \ == Definition of related terms \ - Roster: A roster is a plan or arrangement detailing the scheduling of nurses to particular shifts, considering numerous requirements and considerations. They may be subject to some constraints. It is the end product of an attempt to solve the Nurse Rostering Problem. Rosters typically include details such as the planning period (e.g., 28 days), shift types (day shift and night shift), the number of nurses involved, and specific shift timings (e.g., day shift from 07:00 to 15:00 and night shift from 15:00 to 23:00) (Václavík, Šůcha, & Hanzálek, 2016). \ - Staffing: Staffing is essentially the allocation of nursing personnel to various shifts within a healthcare facility. It is a very critical component as it directly impacts patient care quality, staff satisfaction, and operational efficiency. Hospitals need to be staffed 24 hours a day over seven days a week (Simić, Simić, Milutinović, & Djordjević, 2014). It is usually based on various factors such as skill levels, qualifications, preferences, and constraints. Effective nurse staffing in hospitals goes beyond simply filling shifts, it's a strategic process that considers multiple factors to ensure optimal patient care, nurse satisfaction, and efficient resource allocation. \ - Shifts: These are specific work periods assigned to nurses in a hospital. They refer to the designated periods of time during which nurses are scheduled to work.It coincides with peak patient activity and administrative tasks.There are commonly three different nursing shift schedules; day shift, evening shift and night shift. (i) Day shifts typically spans the hours of early morning to late afternoon, allowing nurses to work during regular business hours. They vary from 8 to 12 hours, typically running from early morning to late afternoon. This could mean working three 12-hour shifts or four 10-hour shifts per week, depending on the schedule (“Understanding the Different Types of Nursing Shifts | CareerStaff,” 2022). (ii) Evening shifts cover the later part of the day, occuring in the late afternoon or early evening and extending into the night. It is usually an 8-hour shift, Mondays to Fridays between 3-5pm, specific times can vary based on the facility. Nurses on these shifts handle patient care during the day-to-night transition, including admissions, discharges, and ongoing needs. (iii) Night shifts handle patient care through the night, typically starting around 11 pm and ending around 7 am. There are also 12-hour shifts, which are between 7pm-7am ensure continuous monitoring and care, especially in critical situations.These shifts are crucial in critical care units like intensive care where patients require constant monitoring. \ - Planning Period: This refers to the timeframe for which a nurse staffing schedule is created. It refers to the period of time nurses are assigned to specific shifts. It may be daily, weekly, monthly, quarterly, or annually, depending on the specific needs of the organization or project. \ - Constraints: Constraints refer to the rules and limitations that must be considered when creating nurse schedules. They ensure that the schedules are feasible, fair, efficient, and and legally compliant. They can abe broadly categorized into two main types; Soft and Hard constraints. \ - Scheduling : Scheduling refers to the process of assigning specific shifts to individual nurses over a specified period, typically covering days, weeks, or months, while meeting established constraints and requirements. Its goal is to create effective schedules that ensure adequate coverage, meet operational demands, and take into consideration variables like nurse preferences, skills, and availability in addition to limitations like necessary staffing levels, restrictions on the number of consecutive workdays, and a fair distribution of the workload. Effective scheduling in nurse rostering plays a vital role in ensuring a well-functioning healthcare system by promoting nurse satisfaction and patient safety. \ == Review of relevant concepts \ === Hyper-Heuristics \ According to Cowling et. al(2001), Hyper-Heuristics can be defined as an approach that operates at a higher level of abstraction than metaheuristics and manages the choice of which low-level heuristic method should be applied at any given time, depending upon the characteristics of the region of the solution space currently under exploration. The implementation of Hyper-Heuristics search within a search space of heuristics as opposed to heuristics and Meta- Heuristics that search within a search space of problem solutions. They are, as one can say, a "heuristic which chooses heuristics"(Soubeiga, 2003). \ They aim at solving hard computational search by working on a set of heuristics to automate the process of selecting, combining, generating or adapting several simpler heuristics (or components of such heuristics). When using hyperheuristics, we are attempting to find the right method or sequence of heuristics in a given situation rather than trying to solve a problem directly. Instead, it selects at each step of the solution process the most promising simple low-level heuristic (or combination of heuristics) which is potentially able to improve the solution. On the other hand, if there is no improvement, i.e., a locally optimal solution is found, the hyperheuristic diversifies the search to another area of the solution space by selecting appropriate heuristics from the given set (Chakhlevitch & Cowling, 2008). Hyperheuristics aim at reducing the amount of domain knowledge in the search methodology, such that they can function without the need for in-depth understanding of specific low-level heuristics or the intricate workings of the problem's objective function, except for the outcome it produces. Their emphasis is on grasping the direction of the optimization process (maximization or minimization) and evaluating the values of one or more objective functions.(Chakhlevitch & Cowling, 2008). \ === Meta-Heuristics \ Almufti et al.(2023) defined Meta-Heuristics as a higher level of heuristics that function as "master strategies that direct and modify other heuristics to produce solutions beyond those that are typically generated in a quest for local optimality". They attempt to find the best solution out of all possible solutions of an optimization problem. \ Meta-heuristics can often find good solutions with less computational effort than optimization algorithms, iterative methods, or simple heuristics (Blum & Roli, 2003). They are especially used for solving sophisticated optimization problems like NP-Hard problems. Metaheuristics don't make sure that the optimal solution for a problem is given, they conduct a partial search on the solution space, and the evaluation of the results is based on a set of defined variables or an objective function. They may frequently identify good solutions in combinatorial optimization with less computing work than optimization algorithms, iterative techniques, or basic heuristics since they search through a vast range of viable alternatives. Because of this, they are effective strategies for solving optimization issue (Sadeeq etal., 2021). They are classified into three; Local Search Meta-heuristics(Simulated Annealing, Tabu Search, Viable Neighbourhood search), Constructive Meta-heuristics (Ant Colony Optimization, Large Neighbourhood search) and Population Based Meta-heuristic(Evolutionary Algorithms). \ === Ant Colony Optimization \ First proposed by Dorigo(1992), the Ant Colony Optimization algorithm is an umbrella term for a set of related constructive Meta-Heuristics that imitate the foraging patterns of ants to generate solutions. Artificial ants are used to find optimal solutions to optimization problems. The algorithm is based on how real ants could manage to establish shortest path routes from their colony to feeding sources and back(Dorigo, Maniezzo, & Colorni, 1996). The domain of application of ACO algorithms is vast. In principle, ACO can be applied to any discrete optimization problem for which some solution construction mechanism can be conceived(Dorigo & Stützle, 2010). The Ant Colony Algorithm is a pheromone-based algorithm. This means, it is based upon real ants laying down pheromones to lead other ants to the nearest food source, the shorter the path is, the stronger the intensity of the phermone trail, and the more attractive the trail becomes, hence, the shorter and more optimal the path is. The process is characterized by a positive feedback loop, where the probability with which an ant chooses a path increases with the number of ants that previously chose the same path (Dorigo, Maniezzo, & Colorni, 1996). The first ACO algorithm to be proposed was AS(Ant System) by Dorigo(1996), and since then, multiple variations have been developed, like the Ant Colony System(Dorigo & Gambardella, 1997), Elitist Ant System(Sorin et al., 2008), Max-Min Ant System(Stutzle & Hooz, 2000), Rank-Based Ant System(ASrank), Parallel ant Colony optimization, Continuous Orthogonal Ant Colony, Recursive Ant Colony Optimization(Gupta, Gupta, Arora, & Shankar, 2012). This paper will be focusing on just two of these variations. It will be comparing the performance of the Ant System and the Ant Colony System on the Nurse Rostering Problem. #figure( image("template/images/ants.jpeg", width: 80%), caption: [ Real ants looking for a shorter path when faced with an obstacle. ] ) #figure( image("template/images/tg_image_3830717059.jpeg", width: 80%), caption: [ Same example but with artificial ants. ] ) \ === Ant Colony System \ This is a prominent variation of the ACO algorithm family. Proposed by Dorigo and Gambardella(1997), it builds upon the core principles of ACO while introducing specific enhancements to improve performance. It is built upon its predecessor, the ant system, but it differs from it in three main aspects : (i) the state transition rule provides a direct way to balance between exploration of new edges and exploitation of a priori and accumulated knowledge about the problem (ii)the global updating rule is applied only to edges which belong to the best ant tour (iii) while ants construct a solution, a local pheromone-updating rule (local updating rule, for short) is applied to change the phermone level of the edges they are selecting (Dorigo and Gambardella,1997). The role of the local updating rule is to change the attractiveness of edges dynamically, so that when ants use an edge, it becomes slightly less appealing because some of its pheromone is lost. This helps ants utilize pheromone information better. Without local updating, ants would tend to explore only a small area around the best previous tour. The edge selection favours the shortest edges with the largest amount of pheromones, and only the ant that has the shortest tour at the end of each iteration is allowed to update the pheromone. === Ant System \ This is the first ACO algorithm to be proposed by Dorigo(1996). It is the foundational algorithm within the ACO family. It is the one upon which other variations of ACOs are built upon. It embodies the core principles of ACO like the artificial ants, which are based upon real ants, that explore the solution space of the optimization problem; pheromone trails, which lead the ants towards the more promising paths and helps determine which path is the shortest and more optimal route; stochastic or probablity-based decisions, which are influenced by pheromones and other factors, and the updating of these phermone trails based on the performance of all the ants that complete the tour. Although ant system was useful for discovering good or optimal solutions for small TSP’s (up to 30 cities), the time required to find such results made it infeasible for larger problems(Dorigo and Gambardella,1997), this is why improvement on this algorithm was necessary, which gave rise to the variations of ACOs we have today. \ #par([ === HYFLEX \ HyFlex, short for Hyper heuristics Flexible Framework, is a JAVA oriented framework for the implementation and comparison of different iterative general-purpose heuristic search algorithms, like Hyper-Heuristics. It features a common software interface for dealing with different combinatorial optimisation problems and provides the algorithm components that are problem specific (4). It provides six hard combinatorial problem domain modules, fully implemented, which include; maximum satisfiability, one dimensional bin packing, permutation flow shop,personnel scheduling, traveling salesman and vehicle routing. The framework allows algorithm designers and implementers to focus on creating practical, general-purpose optimization algorithms without needing in-depth knowledge of the specific problem domains. Researchers in combinatorial optimization often face limitations due to the scarcity of problem domains for testing their adaptive methods. This limitation arises from the significant effort required to implement advanced software components—such as problem models, solution representations, objective function evaluations, and search operators—for various combinatorial optimization problems. The goal of this approach is to enable a hyper-heuristic algorithm, once developed, to be applied to new problems simply by substituting the set of low-level heuristics and the evaluation function. \ At the highest level, this framework contains two abstract classes, which are the Problem Domain and the Hyper-Heuristic.\ An implementation of the Problem Domain class provides: + A user-configurable memory or a population of solutions that can be managed by the hyper-heuristic through one or more methods. + A routine to randomly initialise solutions, #emph[initializeSolution(i)], where #emph[i] is the index of the solution array in the memory. + A set of problem-specific heuristics that are used to modify solutions. They are called by the #emph[applyHeuristics(i,j,k)] method; where i is the index of the heuristic to call, j is the index of the solution in memory to modify and k is the index in memory where the resulting solution should be placed. There are four groups that each problem-specific heuristic in each problem domain can be classified under, and these are: - Mutational Heuristics: These heuristics perform modifications to a solution by making changes to its components, like a swap, change, removal or an addition. Examples: Swap Mutation, Gaussian Mutation, Insertion Mutation - Ruin-recreate Heuristics: These heuristics involve partially "ruining" or destroying a solution and then "recreating" or repairing it to explore new regions of the solution space and potentially find better solutions. They can be broken down into two phases: the ruin phase and the recreate phase. They are, however, considered as large neighbourhood structures and incorporate problem-soecific construction heuristics to rebuild the solutions. - Local Search Heuristics: These heuristics are optimization techniques that are used to iteratively improve a solution by making small, local changes. They are commonly applied to combinatorial optimization problems where the goal is to find the best solution from a finite set of possible solutions. hey incorporate an iterative improve-ment process and they guarantee that a non-deteriorating solution will be produced. - Crossover Heuristics: These heuristics combine the genetic information of two or more parent solutions to produce new offspring solutions. The goal is to combine beneficial traits from different parents to explore new areas of the solution space and potentially create better solutions. + A varied set of instances that can be loaded using the #emph[load instance] method. + A fitness function. \ The HyFlex framework, renowned for its role in the Cross-domain Heuristic Search Challenge (CHeSC) 2011, stands as a standard benchmark for evaluating cross-domain hyper-heuristics. Offering a common interface for implementing and comparing hyper-heuristics across diverse problem domains, it simplifies the implementation of ant colony hyper-heuristic schemes by abstracting low-level heuristics and providing a standardized performance metric. With its established reputation in the research community, using HyFlex for the implementation of my ant colony schemes ensures efficient development and evaluation. ]) \ == Model Description \ There is an already existing framework that contains a data file format for which each instance can select a combination of objectives and constraints from a wider choice. It has all the functions for this constraints. It also consists methods for parsing these data files, data structures(which can be used by heuristic algorithms) and libraries for visualization of instances and solutions. This software framewor Hyper-Heuristic Flexible Framework(HyFlex), has included a model. The constraints in the original problem formulation has been changed to objectives, and the only constraint is that each employee can only work one shift per day. The parameters include:\ I = Set of nurses available.\ I#sub[t] | t #sym.epsilon.alt {1,2,3}= Subset of nurses that work 20, 32, 36 hours per week respectively, I = I#sub[1] + I#sub[2] + I#sub[3].\ J = Set of indices of the last day of each week within the scheduling period = {7, 14, 21, 28, 35}.\ K = Set of shift types = {1(early), 2(day), 3(late), 4(night)}.\ K' = Set of undesirable shift type successions = {(2,1), (3,1), (3,2), (1,4), (4,1), (4,2),(4,3)}.\ d#sub[jk] =Coverage requirement of shift type k on day j\ m#sub[i] = Maximum number of working days for nurse i.\ n#sub[1] = Maximum number of consecutive night shifts.\ n#sub[2] = Maximum number of consecutive working days.\ c#sub[k] = Desirable upper bound of consecutive assignments of shift type k.\ g#sub[t] = Desirable upper bound of weekly working days for the t-th subset of nurses.\ h#sub[t] = Desirable lower bound of weekly working days for the t-th subset of nurses.\ Decision variables:\ x#sub[ijk] = 1 if nurse i is assigned shift type k for day j, 0 otherwise \ The constraints are: 1. A nurse may not cover more than one shift each day. The objectives are formulated as (weighted w#sub[i]) goals. The overall objective function is:\ #align(center)[Min $macron(G)$(x) = $sum_(i=1)^16 w#sub[i] macron(g)#sub[i]$(x)]\ Where the goals are: + Complete weekends (i.e. Saturday and Sunday are both working days or both off).\ + Minimum of two consecutive non-working days.\ + A minimum number of days off after a series of shifts.\ + A maximum number of consecutive shifts of type early and late.\ + A minimum number of consecutive shifts of type early and late.\ + A maximum and minimum number of working days per week.\ + maximum of three consecutive working days for part time nurses.\ + Avoiding certain shift successions (e.g. an early shift after a day shift).\ + Maximum number of working days.\ + Maximum of three working weekends.\ + Maximum of three night shifts.\ + A minimum of two consecutive night shifts.\ + A minimum of two days off after a series of consecutive night shifts. This is equivalent to avoiding the pattern: night shift – day off – day on.\ + Maximum number of consecutive night shifts.\ + Maximum number of consecutive working days.\ + Shift cover requirements. \ == Review of related methods \ Based on existing literature, there are several other methods and algorithms that have been employed to solve the Nurse Rostering Problem. Some of these methods include; Simulated Annealing, Tabu Search, Genetic Algorithm, and some other variations of the Ant Colony algorithm. === Ant Colony Optimization algorithms \ Ant Colony algorithms seek to find optimal solutions to optimization problems by imitating the pattern ants use to search for food from their colonies. Over the years, multiple variations of this algorithms have been implemented to solve the Nurse Rostering problem, each working to cater for the shortcomings of the other. \ Bunton, Ernst, and Krishnamoorthy (2017) proposed an ACO algorithm using an integer programming based solution construction method to ensure feasibility and select from a collection of schedules, because the NRP is heavily constrained, finding feasible solutions for it can prove difficult, which can result in a poor performance for ACOs. Their approach also used a novel solution merging step that combines the information from multiple ants to generate a better final roster. The only limitation stated in their work was that while using this approach, they were unable to compete against an integer programming software (Gurobi) in solution quality in small to medium sized instances, but despite that, they were able to outperform Gurobi and other methods in large instances. \ Achmad, Wibowo, and Diana (2021) proposed an improvement on the Ant Colony algorithm with semi-random initialization for Nurse Rostering Problem. The semi-random initialization took care of the hard contraints, improving the constrution solution phase by assigning nurses directly to the shift related to the hard constraints inorder to avoid any violation of the hard constraints from the get-go, then the rest of the scheduling process will be handled using the ant colony optimization process. This approach was found to have a minimal objective value than the native ACO algorithm, also, the adoption of the semi-random initialization concept was successful in reducing the violation of hard constraints and improving the solution constructed with ant colony, since a violation of hard constraints make a solution not feasible. Unfortunately, this method can only perform optimally with small to medium dimension data. \ Some researchers have even gone into hybridization of the algorithm, like Ramli, <NAME>, and Rohim (2019) that used a hybrid Ant Colony Optimization algorithm along with a hill-climbing technique for solving NRPs, which was aimed at fine-tuning the initial solution or roster generated by the ACO algorithm to achieve better rosters, it is proposed to do this in three phases; generating an initial roster, using the ACO to update the roster and implement the hill climbing to look for a more refined solution. However, the solution is mostly optimal with a larger value of pheromones. \ Jaradat et al. (2019) demonstrated the use of the hybrid Elitist Ant System on the Nurse Rostering Problem which employed an external memory comprising a set of solutions that assists in the preservation of balance between diversity and quality of the search. The method was found to obtain outstanding and optimal results, using an explicit memory particularly offers diverse high-quality solutions from which the proposed hybrid Elitist-AS can initiate its search process to obtain better solutions. The usage of ACO algorithms for nurse rostering problems has been explored, but not extensively, which is quite worrisome, given that ACOs have advantages over other metaheuristics for solving NRPs such that: can effectively handle the complex constraints often present in nurse rostering; they can be designed to consider multiple objectives simultaneously, for multi-objective NRPs; its dynamic nature, as a result of its phermone updating characteristics allows it to adapt to schedule changes or new constraints that arise and ACOs can be tailored to promote equitable shift assignments among nurses, unlike some metaheuristics that might prioritize efficiency over fairness. \ === Simulated annealing \ Simulated annealing is a stochastic local search algorithm for solving unconstrained and bound-constrained optimization problems. The method models the physical process of heating a material and then slowly lowering the temperature to decrease defects, thus minimizing the system energy. (“What Is Simulated Annealing? - MATLAB & Simulink,” n.d.). It draws its inspiration from the metallurgical concept of annealing, where a material undergoes heating and gradual cooling to eliminate impurities. \ In this algorithm, an initial temperature, typically set to 1, and a minimum temperature (around $10^(-4)$) are defined. The temperature decreases exponentially until it reaches the minimum. At each temperature, the optimization routine runs multiple times, involving the exploration of neighboring solutions and accepting them probabilistically based on energy differences. This stochastic approach allows the algorithm to avoid local minima and improve the chances of converging towards the global optimum. Simulated Annealing proves particularly effective in large, discrete search spaces prioritizing optimality over computational time. (“Simulated Annealing - GeeksforGeeks,” 2017; “What Is Simulated Annealing?,” n.d.). It can be aplied to a range of optimization problems, including NP-hard problems. \ A number of people have used this algorithm for nurse rostering problems like Ceschia, Guido, and Schaerf (2020), that used a local search method based on a large neighborhood to solve the static version of the problem defined for the Second International Nurse Rostering Competition (INRC-II). The search method, driven by a simulated annealing metaheuristic, used a combination of neighborhoods that either change the assignments of a nurse or swap the assignments of two compatible nurses, for multiple consecutive days. The method was able to improve on all previous approaches on some datasets, and to get close to the best ones in others. \ Knust and Xie (2017) implemented two solution methods, including a MIP (Mixed Integer Programming) model to compute good bounds for the test instances and a heuristic method using the simulated annealing algorithm for practical use. Both methods were tested on the available benchmark instances and on the real-world data. The solution methods in this work were integrated into Vivendi PEP(a staff scheduling software provided by Context Communication GmbH). The approach was found to be able to solve most of the benchmarking instances optimally, proving that the mathematical model accurately describes the benchmarking instances and finds good solutions for the test instances with the MIP model, with the simulated annealing heuristic approach, it showed that it produces good results for both the benchmarking and the test instances in a short amount of time, and it also proves that it is robust concerning different problem instances. However, it did not adapt well to a fixed given running time. On one hand, if the user wants to wait longer to get a better solution, it does not use the additional time efficiently to further enhance the quality of the solution. On the other hand, it does not adapt to situations where a solution must be produced in a very short amount of time. \ Furthermore, Ayan-Koç & Aktan, (2019), aimed at creating the best work schedule for 15 nurses working in 2 shifts at a hospital operating 24 hours a day by using Simulated Annealing (SA) Algorithm and developed a new temperature reduction technique and a new assignment technique for the annealing algorithm, which was called “multiple simulated annealing with double assignment”. It was found to be quickest when considering that the number of constraints and the number of days in the scheduling problem discussed were quite little, but might have issues generating for larger instances. Simulated annealing is quite wide-spread when it comes to solving problems, esprcially complex ones like Traveling Salesman problem, knapsack problem and so on, but it has several disadvantages, as opposed to ACOs, when applied to nurse rostering problems, including slow convergence, sensitivity to parameter choices, lack of guarantees, lack of collaboration, memory requirements, and lack of exploitation (Knust and Xie, 2017). \ === Tabu Search Originally proposed by Glover in 1986, Tabu search is a metaheuristic that guides a local heuristic search procedure to explore the solution space beyond local optimality, it is based on the premise that problem solving, in order to qualify as intelligent, must incorporate adaptive memory and responsive exploration (Glover & Laguna, 1997). It is an adaptive procedure for solving combinatorial optimization problems with the ability to make use of many other methods, like linear programming algorithms and specialized heuristics, which it directs to overcome the limitations of local optimality(Glover, 1989). \ Schrack et al. (2021) combined tabu search and genetic algorithm to optimally determine nurse's schedules for smaller scale clinics that require only two nurses per shift and two shifts per day as opposed to the conventional three. They were able to demonstrate that the order in which these meta-heuristic methods are applied can provide better solutions than initially hypothesized. They however plan to improve on the algorithm to cater for larger facilities and to take on additional soft constraints. \ Other approaches have been attempted using just Tabu Search like Ramli, Ahmad, Abdul-Rahman, and Wibowo (2020) who explored on the neighbourhoods exploitation of TS to solve the problem inorder to produce a faster and more fitted solution. Their methodology consisted of two phases, the initialization, where they used semi-random initialization to get a good initial solution that does not violate any hard constraint, and the neighbourhood phase for further improving the solution quality using the TS algorithm.Their main aim was to move sample points towards a high-quality solution while avoiding local optima by utilising a calculated force value. The rosters produced were of high quality and without bias. \ Tabu Search shares numerous similarities with simulated annealing. In fact, simulated annealing can be viewed as a specific variant of tabu search, wherein a move is designated as tabu with a specified probability. Consequently, the limitations of these two methods are quite comparable. \ === Genetic Algorithm Genetic algorithms are adaptive heuristic search algorithms inspired by the principles of natural selection and genetics. They are used to solve optimization and search problems by mimicking the process of natural evolution to improve a population of potential solutions (Kanade, 2023). The genetic algorithm iteratively modifies a population of individual solutions. In each iteration, it selects individuals from the current population as parents and uses them to generate offspring for the subsequent generation. Through successive generations, the population “evolves” towards an optimal solution. \ The genetic algorithm is applicable to various optimization challenges that conventional methods may struggle with, such as problems featuring discontinuous, nondifferentiable, stochastic, or highly nonlinear objective functions. Additionally, it can handle mixed integer programming problems, where certain components must be integer-valued (“VisibleBreadcrumbs,” 2019). It begins with an initial population of individuals, typically generated randomly. It then goes through a series of iterations, known as generations or epochs, in which the individuals undergo operations such as selection: to choose which routes will be part of the next generation; selection methods aim to favour fitter individuals,which in this case are routes with lower evaluation rates; crossover: to create new routes by combining genetic materials from two parent routes and mutation: to explore new possibilities and avoid getting stuck in local optima. The selection, crossover, and mutation process is continued for a fixed number of generations or until a termination criterion is met (Kanade, 2023). \ In recent years genetic algorithms have emerged as a useful tool for the heuristic solution of complex discrete optimisation problems like the nurse rostering problem. They have been applied to develop weekly schedules for wards of up to 30 nurses, taking into account working contracts, nurse preferences, and hard and soft constraints. However, classical genetic algorithm paradigm is not well equipped to handle constraints and successful implementations and usually needs some form of modification (Aickelin, 1998). \ OYELEYE et al. (2020) developed a modified Genetic Algorithm based upon the standard GA to get a more optimal solution to the Nurse Rostering Problrm in LAUTECH Teching hospital, Ogbomosho, Oyo State. \ Moreover, Amindoust, Asadpour, and Shirmohammadi (2021) proposed a hybrid genetic algo model for the NRP, taking the fatigue of nurses into consideration and providing a 3-shift schedule based on it. They used a real case study, real case study, a department in one of the hospitals in Esfahan, Iran, where COVID-19 patients were hospitalized to validate the efficiency of the proposed model. The model was able to significantly reduce the time it took to generate schedules, and distribute the nurses within different shifts fairly, considering the least fatigue. \ However, it's worth noting that while genetic algorithms offer promising solutions for complex optimization problems like Nurse Rostering Problems (NRPs), they are not without limitations. These algorithms may not always reach optimal solutions, particularly when dealing with highly constrained Nurse Rostering Problems (NRPs). This can result in suboptimal solutions that fail to meet all specified constraints. Additionally, genetic algorithms are highly sensitive to parameter settings such as crossover and mutation rates, population size, and selection criteria. Inaccurate or inappropriate parameter choices can greatly affect the quality of results obtained. Moreover, the algorithm's applicability in real-world scenarios is further limited by the requirement for significant processing resources to evaluate fitness functions for large-scale NRPs with enormous rosters. \ == Summary of literature review A comprehensive review of the literature reveals a surprising lack of recent and up-to-datrresearch applying Ant Colony Optimization (ACO) algorithms to nurse rostering problems. Even more scarce are comparative analyses evaluating different ACO hyper-heuristic schemes. This paper aims to bridge this gap by providing data-driven insights by comparing the performance of two selected ACO approaches to determine which is more suitable for tackling nurse rostering problems. #pagebreak() = System analysis and design == Preamble This section details the analysis and design of the proposed system. It presents the requirements for the system, the techniques taken to achieve the system as well as diagrams to model the proposed system. \ == The proposed system The proposed system is an intelligent tool that makes use of two HyperHeuristic schemes each utilizing two different variations of the Ant Colony optimization algorithm. This tool will, after a number of iterations, each generate possible solutions in the form of rosters for the Nurse Scheduling or Rostering problem. The main aim for this tool is the comparison of the implementation two Ant Colony HyperHeuristic schemes, so there will be little to no user involvement with this system. \ == The Nurse Rostering Problem The nurse rostering or nurse scheduling problem entails creating staff schedules called rosters that assign shifts to nurses over a given planning horizon, which is usaully a week or a month while considering various constraints, objectives and goals. These constraints are classified into hard and soft constraints; hard constraints being mandatory rules that must be strictly adhered to as violating them will render a solution not feasible. Examples include: ensuring a required number of nurses for each shift, required skill sets, legal and contractual regulations, and so forth, while soft constraints are preferences that can be bent, they are desirable but not mandatory, violating them just incurs a penalty, examples include: nurses preferred shifts or days off, reducing fatigue by limiting the number of consecutive shifts, ensuring fairness in shift assignments. The main goal when trying to solve this problem is to create a valid roster that adheres to all hard constraints. The nurse rostering problem can be represented using a mathematical model which consists of a set of nurses, shifts and shift types, decision variable, which is a binary variable represented by $x#sub[ijk]$, indicating if nurse #emph[i] is assigned to shift #emph[j] on day #emph[k], with the value of 1 if assigned and 0 if otherwise, the objective function which aims to minimize the overall penalty incurred by violating soft constraints or not meeting desired goals and maximize the nurse's preferences:\ $min sum_(i,j,k) C#sub[ijk] * x#sub[ijk] + sum$ penalties for soft constraints violations \ And a bunch of soft and hard constraints that should be met based on the objective function and specific hospital needs. This is just an abstracted explanation of the NRP model, it can be modified and adjusted based on the specific requirements; appropriate constraints and objectives, of the nurse rostering problem being solved. \ The Nurse Rostering Problem is usually solved by heuristics and Metaheuristics like Simulated Annealing, Tabu Search, Ant Colony Optimization, and others, mainly because they can generate good solutions in reasonable time. The process of solving this problem with heuristics is broken down into steps which begins with all the data concerning the specific NRP to be solved being gathered and prepared first. Then an iterative process which entails an initial roster being generated randomly or based on a simple rule, which is then evaluated based on the defined objective function (might involve calculating the total penalty incurred by violating soft constraints or not meeting desired goals), this roster is then looked over to identify areas for improvement, like a violation of a high-priority preference or a very desirable constraint, then, depending on the chosen heuristic, there is an attempt to improve the roster. This might involve swapping shifts between nurses, re-assigning a nurse to a different shift type, or modifying the schedule to respect a high-weight preference. This step continues until a stopping criterion is met, which can either be the algorithm reaching a pre-set maximum number of iterations or the algorithm finding an acceptable solution. A post-processing technique can be applied to the final roster if necessary, to fine-tune and ensure optimality of the solution. Then the roster is evaluated based on the objective function and constraints. \ == The HYFLEX framework The Hyflex framework (Hyper heuristics Flexible Framework) is a versatile software framework designed to facilitate the development and testing of hyper-heuristics across various problem domains. It isn't focused on solving specific problems itself, but rather provides a powerful platform for developing algorithms that tackle a wide range of combinatorial optimization problems. These are problems where you need to find the best possible arrangement from a finite set of options. This framework has six (6) problem domains which are: + Maximum Satisfiability(SAT): This is also called Boolean Satisfiability, and it is a fundamental problem in computer science and mathematical logic that involves determining whether there exists an assignment of truth values (true or false) to variables in a Boolean formula such that the entire formula evaluates to true. If there does, the formula is called satisfiable, on the other hand, if no such assignment exists, the function expressed by the formula is FALSE for all possible variable assignments and the formula is unsatisfiable. The goal is to determine if there's a way to make a complex formula true through clever assignment of truth values. This problem is NP-complete. + One-dimensional bin packing: This is a classic combinatorial optimization problem that has applications in real-world scenarios like resource allocation and logistics. It involves packing a set of items with varying sizes into a finite number of bins, each with a fixed capacity, in such a way that the number of bins used is minimized. Computationally, the problem is NP-hard. + Permutation Flow Shop Scheduling (PFSS): This is a production problem for finding the best sequence of jobs to be processed by machines in order to minimize the given objective function. It deals with efficiently scheduling jobs in a production environment with a specific flow structure. Here, a set of jobs must be processed in the same order on a series of machines. The objective is typically to minimize the total completion time (makespan), although other objectives like minimizing total tardiness or maximizing throughput can also be considered. This is also an NP-hard problem. + Travelling Salesman Problem: This is a classic combinatorial optimization problem that seeks the shortest possible route for a salesman to visit a set of #emph[n] cities exactly once and return to the original city, given a set of citiesor locations and the distances between each pair of them. The goal is to find the shortest possible route that visits each city exactly once and returns to the starting city. + Vehicle Routing: This is a combinatorial optimization and integer programming problem that seeks the optimal set of routes for a fleet of vehicles to deliver goods to a set of customers. The objective is typically to minimize the total delivery cost, which may include distance, time, or other metrics, while satisfying various constraints. It asks the question: What is the optimal set of routes for the vehicles to take such that all deliveries are completed, capacity constraints are met and total route cost is minimized. It generalizes the Travelling Salesman Problem and is an NP-hrad problem. + Personnel Scheduling: This is a type of combinatorial optimization problem where the goal is to allocate shifts or work hours to a set of employees while satisfying various constraints and optimizing one or more objectives. Essentially, it involves determining the specific times and shifts that each employee should work over a given planning period.\ The Personnel Scheduling problem is in actuality, not a problem on its own, but a title for a group of very similar problems. There is a group of problems with very similar structure but different objectives and constraints; these are personnel scheduling problems. This fact makes it challenging to implement a problem domain for personnel scheduling. The framework overcame this challenge by creating a data file format where each instance can select a combination of objectives and constraints from a wide choice, then a software framework containing all the functions for these objectives and constraints was implemented. The framework also contains methods for parsing these data files, data structures and libraries for visualisations of instances and solutions. The objectives for the Nurse Rostering Problem domain provided by this framework can be categirized into two groups: \ - Coverage Objectives which aim to make sure that the preferred number of employees, preferrably with skills, are working each shift.\ - Employee working objectives which relates to the individual work patterns for each employee. They aim to maximize the employees' satisfaction with their work schedules.\ In the Hyflex Framework, it is necessary to implement a method to initialize a new solution, and these are most usually low-level heursitics. There are four categories of heuristics; Mutation, Local Search, Ruin and Recreate and Crossover. Hyflex currently provides 1 mutation heuristic (Mutation Heuristic 1), three crossover heursitics (Crossover Heuristics 1-3), three ruin and recreate heuristics (Ruin and Recreate Heuristics 1-3) and 5 Local Search Heuristics, which are divided into two, Local Search Heuristics 1-3 are the hill-climbers(or hill-descenders, since we are dealing with minimization), that use of neighbourhood operators, and Local Search Heuristics 4 and 5 which are variants of the variable depth search. The solution for all the problems in the personnel scheduling domain is initialized using Local Search Heuristic 3, which is a hill climber that uses the #emph[new] neighbourhood operator that introduces new shifts into or deletes from the initial roster. \ #code-figure( "Pseudo-code for Local Heursitic 3", ``` 1. WHILE there are untried swaps 2. FOR BlockLength=1 up to MaxBlockLength 3. FOR each employee (E1) in the roster 4. FOR each day (D1) in the planning period 5. FOR each shift type (S1) (including day off) 6. Remove all assignments for E1 on D1 up to D1+BlockLength and assign shifts of type S1 to E1 on D1 up to D1+BlockLength 7. IF an improvement in roster penalty THEN 8. Break from this loop and move on to the next day (D1+1) 9. ELSE 10. Reverse the swap 11. ENDIF 12. ENDFOR 13. ENDFOR 14. ENDFOR 16. ENDFOR 17. ENDWHILE ``` ) #pagebreak() // #table( // columns: 6 , // inset: 10pt, // align: horizon, // table.header( // [#emph[Domain]], [#emph[Total]], [#emph[Mut]], [#emph[R&R]], [#emph[Crossover]], [#emph[LS]] // ), // [Maximum Satisfiability], // [9], // [4], // [1], // [1], // [2], // [Bin Packing], // [8], // [3], // [2], // [1], // [2], // [Permutated Flow Shop], // [15], // [5], // [2], // [3], // [4], // [Personnel Scheduling], // [12], // [1], // [3], // [3], // [5], // [Travelling Salesman], // [15], // [5], // [1], // [3], // [6], // [Vehicle Routing], // [12], // [4], // [2], // [2], // [4], // ) #table-figure( "The Total Heuristics Provided by Hyflex for each Heuristic Type ", [#table( columns: 6 , inset: 10pt, align: horizon, table.header( [#emph[Domain]], [#emph[Total]], [#emph[Mut]], [#emph[R&R]], [#emph[Crossover]], [#emph[LS]] ), [Maximum Satisfiability], [9], [4], [1], [1], [2], [Bin Packing], [8], [3], [2], [1], [2], [Permutated Flow Shop], [15], [5], [2], [3], [4], [Personnel Scheduling], [12], [1], [3], [3], [5], [Travelling Salesman], [15], [5], [1], [3], [6], [Vehicle Routing], [12], [4], [2], [2], [4], )] ) \ == The Ant System This is a type of algorithm that is a part of a broader class of algorithms known as Ant Colony Optimization (ACO). The main idea is to use artificial ants to simulate the way real ants find the shortest paths between their nest and food sources by laying down pheromones, which guide other ants towards the discovered path. Originally proposed by Dorigo in 1996, it was first applied to the Travelling Salesman Problem and is the progenitor of all further research work on Ant Colony algorithms. \ It is a set of algorithms inspired by the foraging behaviour of ants specifically designed for solving combinatorial optimization problems. Real ants find the shortest path to a food source by something called 'Pheromone Trails', this concept is one of the core mechanisms of the Ant System. Ants lay pheromones on the paths they traverse, and the amount of pheromone deposited depends on the quality of the solution, like, shorter paths have much thicker pheromones because more ants would have traversed it. Over time, pheromone trails evaporate, preventing the system from converging too quickly to a suboptimal solution and encouraging exploration. The ants are endowed with a working memory $M_i^k$, that stores nodes or vertices already visited; at initialization, $M_i^k$ is an empty set, for every ant i($1<= i <= k$),where k is the total number of vertices, then as ant $i$ visits vertex $v$, it is added to memory $M_i^k$. In the original work by Dorigo,Maniezzo,& Colorni(1996), a tabu list was used as a memory to store the already visited cities. The ants begin at a particular node or location and the choice of the next node to visit is based on a probability that is a function of the intensity of the phermone on the trail($tau_(i j)$) between the start node and the destination node and a heuristic value ($eta_(i j)$) which is often based on an inverse of the distance between the two nodes. The formula is usually given as: $P_(i j)^k (t) = ([tau_(i j)(t)]^alpha . [eta_(i j)]^beta) / (sum_(k in N_k (i)) [tau_(i k)(t)]^alpha . [eta_(i k)]^beta) $ where $N_k (i)$ is the set of nodes that ant #emph[k] has not yet visited, $alpha$ and $beta$ are parameters that control the relative importance of trail versus visibility, so the transition probability $P_(i j)^k (t)$ is a trade-off between visibility, which says that closer nodes should have more preference thereby implementing a greedy constructive heuristic and trail intensity, which says that the edge between nodes that has had more traffic is more desirable, thereby implementing the autocatalytic process. After every #emph[n] iterations of the algorithm (which is also called a cycle), the pheromone trail intensity is updated using this formula:\ $tau_(i j)(t+n) = (1-rho)tau_(i j)(t) + sum_(k = 1)^m Delta tau_(i j) ^ k $ where:\ $(1-rho)$ represents the evaporation of trail between time t and t+n,\ $Delta tau_(i j) ^ k$ is the quantity per unit length of pheromones laid on the edge(i,j) by the k-th ant between time t and t+n and is given by:\ $Delta tau_(i j) ^ k = Q/L_k$; if the k-th ant uses edge (i,j) in its tour (between time t and t + n)\ where Q is a constant and $L_k$ is the tour length of the k-th ant.\ This is called the Global Pheromone Update, where a greater amount of pheromones are allocated to shorter tours. The coefficient $rho$ must be a value less than 1 to avoid saturation of trail and encourage exploration (if the $rho$ value is < 1, pheromone values decay gradually overtime, thus reducing the influence of previously deposited pheromones, which allows ants explore new paths instead of only following the most reinforced ones, to avoid premature convergence to suboptimal solutions). #figure( image("template/images/pseudocode.jpeg", width: 80%), caption: [ Pseudocode of the ant cycle algorithm in the Ant System for TSP.// cite this, do not forget ] ) \ == The Ant Colony System This is another variation of the Ant Colony Optimization algorithm. It, like its parent algorithm is inspired by the foraging behaviour of ants. The Ant Colony System algorithm is built upon the Ant system, with only a few changes to improve its effectiveness. It was noted by Dorigo &Gambardella(1997) that for larger problems, the time given to the Ant System made infeasible to find good or optimal solutions. It was also discovered that even when given more time, the algorithm still suffered from slow convergence and had the tendency to get stuck in local optima instead of converging to the global optimum. So, the Ant Colony System was developed to accelerate convergence, while still searching the solution space effectively, and also to balance exploration and exploitation inorder to avoid suboptiomal solutions. The Ant Colony System differs from the Ant System in these ways: + While the Ant System uses a purely probabilistic approach for selection of the next path to be taken by the ant, this algorithm has a state transition rule that ensures there is a way to balance between exploration of new paths and exploitation of already reinforced paths to help avoid convergence of solution to local optima. + The Global Pheromone Update rule, which is only applied to the edges that belong to the tour of the best ant, which is the ant that constructed the best solution. In Ant System, however, all the ants contribute to the global pheromone update. + The Local Pheromone Update rule, which happens while ants construct a solution, and every ant has completed a tour. This is done only in Ant Colony System, and not in Ant System, to encourage exploration. + The Ant System applies evaporation of pheromones uniformly after each iteration, while the Ant Colony System uses a slower pheromone evaporation rate and combines global updates with evaporation to focus on the best solutions. The #pagebreak() *REFERENCES* <NAME>. (2015). NURSE SCHEDULING PROBLEM. European Scientific Journal, 2, 1857–7881. Retrieved from https://eujournal.org/index.php/esj/article/download/6481/6221. <NAME>., & <NAME>. (2010). The nurse rostering problem: A critical appraisal of the problem structure. European Journal of Operational Research, 202(2), 379–389. https://doi.org/10.1016/j.ejor.2009.05.046. <NAME>., <NAME>., <NAME>., & <NAME>. (2004). The State of the Art of Nurse Rostering. Journal of Scheduling, 7(6), 441–499. https://doi.org/10.1023/b:josh.0000046076.75950.0b <NAME>., <NAME>., & <NAME>. (2016). Roster evaluation based on classifiers for the nurse rostering problem. Journal of Heuristics, 22(5), 667–697. https://doi.org/10.1007/s10732-016-9314-9 <NAME>., & <NAME>. (1992). Nurse staffing and scheduling: past solutions and future directions. PubMed, 3(4), 75–82. <NAME>., <NAME>., <NAME>., & <NAME>. (2014). CHALLENGES FOR NURSE ROSTERING PROBLEM AND OPPORTUNITIES IN HOSPITAL LOGISTICS. JOURNAL of MEDICAL INFORMATICS & TECHNOLOGIES, 23(1642-6037). Understanding the Different Types of Nursing Shifts | CareerStaff. (2022, January 25). Retrieved from CareerStaff Unlimited website: https://www.careerstaff.com/clinician-life-blog/nursing/understanding-different-nursing-shifts/ <NAME>., <NAME>., <NAME>.: A hyperheuristic approach to scheduling a sales summit. In: <NAME>., <NAME>. (eds.) PATAT 2000. LNCS, vol. 2079, pp. 176–190. Springer, Heidelberg (2001) Soubeiga, E.: Development and application of hyperheuristics to personnel scheduling. PhD Thesis, Department of Computer Science, University of Nottingham, UK (2003) <NAME>., & <NAME>. (2008). Hyperheuristics: Recent Developments. In <NAME>, <NAME>, & <NAME> (Eds.), Adaptive and Multilevel Metaheuristics (pp. 3–29). Berlin, Heidelberg: Springer Berlin Heidelberg. https://doi.org/10.1007/9783540794387_1 <NAME>, <NAME>, and <NAME>, "A tabu-search hyperheuristic for timetabling and rostering," Journal of Heuristics, vol. 9, pp. 451-470, 2003. <NAME>, <NAME>, <NAME>, and <NAME>, "Local search neighbourhoods for dealing with a novel nurse rostering model," Annals of Operations Research, vol. 194, pp. 33-57, 2012. <NAME> and <NAME>, "Cost analysis of alternative formulations for personnel scheduling in continuously operating organizations," European Journal of Operational Research, vol. 86, pp. 249-261, 1995. <NAME> and <NAME>, "An ACO algorithm for a dynamic regional nurse-scheduling problem in Austria," Computers & Operations Research, vol. 34, pp. 642-666, 2007. <NAME> and <NAME>, "Branching strategies in a branchand-price approach for a multiple objective nurse scheduling problem," Journal of Scheduling, vol. 13, pp. 77-93, 2010. <NAME>, <NAME>, <NAME>, and <NAME>, "Global best Harmony Search with a new pitch adjustment designed for Nurse Rostering," Journal of King Saud University-Computer and Information Sciences, vol. 25, pp. 145-162, 2013. <NAME>, <NAME>, <NAME>, and <NAME>, "Harmony search with greedy shuffle for nurse rostering," International Journal of Natural Computing Research (IJNCR), vol. 3, pp. 22-42, 2012 <NAME>, <NAME>, <NAME>, and <NAME>, "A scatter search methodology for the nurse rostering problem," Journal of the Operational Research Society, vol. 61, pp. 1667-1679, 2010 <NAME>, <NAME>, <NAME>, and <NAME>, "Nurse rostering problems––a bibliographic survey," European Journal of Operational Research, vol. 151, pp. 447-460, 2003. <NAME>, Quality in Fives: On the Analysis, Operationalization and Application of Nursing Schedule Quality, University of Groningen, 1996. <NAME>., <NAME>, <NAME>, & <NAME>. (2023). Overview of Metaheuristic Algorithms. Polaris Global Journal of Scholarly Research and Trends, 2(2), 10–32. https://doi.org/10.58429/pgjsrt.v2n2a144 <NAME>., & <NAME>. (2003). Metaheuristics in combinatorial optimization. ACM Computing Surveys, 35(3), 268–308. https://doi.org/10.1145/937503.937505 <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2021). A New Hybrid Methodfor Global Optimization Based on the Bird Mating Optimizer and the Differential Evolution. 2021 7thInternational Engineering Conference “Research & Innovation amid Global Pandemic" (IEC), 54–60.https://doi.org/10.1109/IEC52205.2021.9476147 <NAME>., <NAME>., & <NAME>. (1996). Ant system: optimization by a colony of cooperating agents. IEEE Transactions on Systems, Man and Cybernetics, Part B (Cybernetics), 26(1), 29–41. https://doi.org/10.1109/3477.484436 <NAME>., & <NAME>. (2010). Ant Colony Optimization: Overview and Recent Advances. Handbook of Metaheuristics, (781-3794), 227–263. https://doi.org/10.1007/978-1-4419-1665-5_8 <NAME>., & <NAME>. (1997). Ant colony system: a cooperative learning approach to the traveling salesman problem. IEEE Transactions on Evolutionary Computation, 1(1), 53–66. https://doi.org/10.1109/4235.585892 T. Stützle et H.H. Hoos, MAX MIN Ant System, Future Generation Computer Systems, volume 16, pages 889-914, 2000 <NAME>., <NAME>., <NAME>., & <NAME>. (2012). Recursive ant colony optimization: a new technique for the estimation of function parameters from geophysical field data. Near Surface Geophysics, 11(3), 325–340. https://doi.org/10.3997/1873-0604.2012062 <NAME>., <NAME>., & <NAME>. (2017). An Integer Programming based Ant Colony Optimisation Method for Nurse Rostering. Computer Science and Information Systems (FedCSIS), 2019 Federated Conference On, 11(2300-5963). https://doi.org/10.15439/2017f237 <NAME>., <NAME>., & <NAME>. (2021). Ant colony optimization with semi random initialization for nurse rostering problem. International Journal for Simulation and Multidisciplinary Design Optimization, 12, 31–31. https://doi.org/10.1051/smdo/2021030 <NAME>., <NAME>., & <NAME>. (2019). A hybrid ant colony optimization algorithm for solving a highly constrained nurse rostering problem. Journal of Information and Communication Technology, 18(3), 305-326. <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2019). Hybrid Elitist-Ant System for Nurse-Rostering Problem. Journal of King Saud University - Computer and Information Sciences, 31(3), 378–384. https://doi.org/10.1016/j.jksuci.2018.02.009 What Is Simulated Annealing? - MATLAB & Simulink. (n.d.). Retrieved from www.mathworks.com website: https://www.mathworks.com/help/gads/what-is-simulated-annealing.html Simulated Annealing - GeeksforGeeks. (2017, August 11). Retrieved from GeeksforGeeks website: https://www.geeksforgeeks.org/simulated-annealing/ What is Simulated Annealing? (n.d.). Retrieved from www.cs.cmu.edu website: https://www.cs.cmu.edu/afs/cs.cmu.edu/project/learn-43/lib/photoz/.g/web/glossary/anneal.html <NAME>., <NAME>., & <NAME>. (2020). Solving the static INRC-II nurse rostering problem by simulated annealing based on large neighborhoods. Annals of Operations Research, 288(1), 95–113. https://doi.org/10.1007/s10479-020-03527-6 <NAME>., & <NAME>. (2017). Simulated annealing approach to nurse rostering benchmark and real-world instances. Annals of Operations Research, 272(1-2), 187–216. https://doi.org/10.1007/s10479-017-2546-8 <NAME>., & <NAME>. (2019). The Solution of Nurse Scheduling Problem with Simulated Annealing Algorithm. Journal of Scientific and Engineering Research, 6(4), 153–160. www.jsaer.com <NAME>., & <NAME>. (1997). Tabu Search. Boston, MA: Springer US. https://doi.org/10.1007/978-1-4615-6089-0 <NAME>. (1989). Tabu Search—Part I. ORSA Journal on Computing, 1(3), 190–206. https://doi.org/10.1287/ijoc.1.3.190 <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2021, September 1). Combining Tabu Search and Genetic Algorithm to Determine Optimal Nurse Schedules. https://doi.org/10.1109/CCECE53047.2021.9569111 <NAME>., <NAME>., <NAME>., & <NAME>. (2020). A tabu search approach with embedded nurse preferences for solving nurse rostering problem. International Journal for Simulation and Multidisciplinary Design Optimization, 11, 10. https://doi.org/10.1051/smdo/2020002 VisibleBreadcrumbs. (2019). Retrieved from Mathworks.com website: https://www.mathworks.com/help/gads/what-is-the-genetic-algorithm.html <NAME>. (2023, September 6). Genetic Algorithms - Meaning, Working, and Applications. Retrieved from Spiceworks website: https://www.spiceworks.com/tech/artificial-intelligence/articles/what-are-genetic-algorithms/ <NAME>. (1998). Nurse Rostering with Genetic Algorithms.ArXiv (Cornell University). <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2020). MODIFIED GENETIC ALGORITHM FOR SOLVING NURSE SCHEDULING PROBLEM. International Research Journal of Computer Science, 07(04), 33–41. https://doi.org/10.26562/irjcs.2020.v0704.002 <NAME>., <NAME>., & <NAME>. (2021). A Hybrid Genetic Algorithm for Nurse Scheduling Problem considering the Fatigue Factor. Journal of Healthcare Engineering, 2021, 1–11. https://doi.org/10.1155/2021/5563651 <NAME>., <NAME>., & Jaharuddin. (2017). The nurse scheduling problem: a goal programming and nonlinear optimization approaches. IOP Conference Series Materials Science and Engineering, 166, 012024. https://doi.org/10.1088/1757899X/166/1/012024 <NAME>., & <NAME>. (2017). A two-step multi-objective mathematical model for nurse scheduling problem considering nurse preferences and consecutive shifts. International Journal of Services and Operations Management, 27(1), 83. https://doi.org/10.1504/ijsom.2017.083338 (4) (PDF) HyFlex: A Benchmark Framework for Cross-Domain Heuristic Search. Available from: https://www.researchgate.net/publication/258836405_HyFlex_A_Benchmark_Framework_for_Cross-Domain_Heuristic_Search [accessed May 24 2024].
https://github.com/saimnaveediqbal/thesis-NTNU-typst
https://raw.githubusercontent.com/saimnaveediqbal/thesis-NTNU-typst/main/README.md
markdown
MIT License
# NTNU thesis template Port of [thesis-NTNU](https://github.com/COPCSE-NTNU/thesis-NTNU) template to Typst. [main.pdf](https://github.com/saimnaveediqbal/thesis-NTNU-typst/blob/main/template/main.typ) contains a full usage example, see [example.pdf](https://github.com/saimnaveediqbal/thesis-NTNU-typst/blob/main/example.pdf) for a rendered pdf. # Usage To use this template you need to import it at the beginning of your document: ```typ #import "@preview/nifty-ntnu-thesis:0.1.0": * ``` The template has many arguments you can specify: | Argument | Default Value | Type | Description | | --- | --- | --- | --- | | `title` | `Title` | [content] | The title of the thesis. | | `short-title` | `Title` | [content] | Short form of the title. If specified, will show up in the header | | `author` | `Author` | [array] | An array of authors | | `short-author` | `` | [string] | Short form version of the authors. If specified, will show up in header | | `paper-size` | `a4` | [string] | Specify a [paper size string] to change the page size. | | `date` | `datetime.today()` | [datetime] | The date that will be displayed on the cover page. | | `date-format` | `[day padding:zero]/[month repr:numerical]/[year repr:full]` | [string] | The format for the date that will be displayed on the cover page. By default, the date will be displayed as `DD/MM/YYYY`. | | `abstract-en` | `none` | [content] | English abstract shown before main content. | | `abstract-no` | `none` | [content] | Norwegian abstract shown before main content. | | `preface` | `none` | [content] | The preface for your work. The preface content is shown on its own separate page after the abstracts. | | `table-of-contents` | `outline()` | [content] | The table of contents. Setting this to `none` will disable the table of contents. | | `titlepage` | `false` | [bool] | Whether to display the titlepage or not. | | `bibliography` | `none` | [content] | The bibliography function or none. Specifying this will configure numeric, IEEE-style citations. | | `chapter-pagebreak` | `true` | [bool] | Setting this to `false` will prevent chapters from starting on a new page. | | `chapters-on-odd` | `false` | [bool] | Setting this to `false` will prevent chapters from only starting on an odd page. | | `figure-index` | `(enabled: true, title: "Figures")` | [dictionary] | Setting this to `true` will display a index of image figures at the end of the document. | | `table-index` | `(enabled: true, title: "Tables")` | [dictionary] | Setting this to `true` will display a index of table figures at the end of the document. | | `listing-index` | `(enabled: true, title: "Listings")` | [dictionary] | Setting this to `true` will display a index of listing (code block) figures at the end of the document. | # Todo: - [ ] Styling for: - [x] Code blocks - [x] Tables - [x] Header and footer - [x] Lists - [x] Subfigures - [x] Abstract - [x] Preface - [x] Code block captions - [x] Bibliography - [ ] Norwegian language support - [x] Proper figure numbering - [x] Short title in header - [x] Multiple authors - [x] Start chapters on only odd pages # Acknowledgements Thanks to: - The creator of the [ILM template](https://github.com/talal/ilm/blob/main/lib.typ) which I used as the basis for this. - The creators of the original [NTNU thesis template](https://github.com/COPCSE-NTNU/thesis-NTNU) - The creators of the [elsearticle template](https://github.com/maucejo/elsearticle) for their implementation of subfigures and appendix environment
https://github.com/SillyFreak/typst-pre-plantuml
https://raw.githubusercontent.com/SillyFreak/typst-pre-plantuml/main/README.md
markdown
MIT License
# pre-plantuml This package provides a [prequery](https://typst.app/universe/package/prequery) for UML diagrams specified using [PlantUML](https://www.plantuml.com/) syntax. The diagrams can be extracted either as source code, or as URLs to a specific PlantUML Webservice. ## Getting Started To add this package to your project, use this: ```typ #import "@preview/pre-plantuml:0.1.0": * ... ``` ## Usage See the [manual](docs/manual.pdf) for details.
https://github.com/LuminolT/SHU-Bachelor-Thesis-Typst
https://raw.githubusercontent.com/LuminolT/SHU-Bachelor-Thesis-Typst/main/body/context.typ
typst
= 绪论 == #lorem(1) 嘉人们,谁懂啊@jiaran2021。公式@eq-1 // [ ] Todo: 公式引用为中文 $ sum_(n=1)^infinity 1/n^2 = pi^2/6 $ <eq-1> === #lorem(2) #lorem(200) = 第二章 == #lorem(1) #lorem(100) === #lorem(2) #lorem(200)
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/patterns/weeks/week14.typ
typst
#import "../../utils.typ": * #section("Shepherding Process") #align( center, [#image("../../Screenshots/2023_12_22_10_14_32.png", width: 80%)], ) - Three Iterations - How to budget your time and effort to make shepherding effective - The Shepherd Knows the Sheep - How to establish a productive relationship between you and the author - Half a loaf - How to make sure that shepherding continues to move forward - Big Picture - How to grasp the gist of the pattern right off the bat. - Author as Owner - How to keep from writing the pattern for the author - Forces Define Problem - How to understand the problem at a deeper level #subsection("Writers' Workshop") #align( center, [#image("../../Screenshots/2023_12_22_10_17_35.png", width: 80%)], ) - Used to improve patterns - Primary focus of PLoP conference - Each writers' worksjop contains 5 to 8 papers - Authors must read before the conference - Give eac hother feedback on their work in a peer review session - *The authors of the paper under discussion remain silent* #subsection("Practices") #align( center, [#image("../../Screenshots/2023_12_22_10_21_09.png", width: 80%)], ) #align( center, [#image("../../Screenshots/2023_12_22_10_21_36.png", width: 80%)], ) #align( center, [#image("../../Screenshots/2023_12_22_10_21_49.png", width: 80%)], ) #align( center, [#image("../../Screenshots/2023_12_22_10_21_58.png", width: 80%)], ) #align( center, [#image("../../Screenshots/2023_12_22_10_22_07.png", width: 80%)], ) #align( center, [#image("../../Screenshots/2023_12_22_10_22_16.png", width: 80%)], ) #align( center, [#image("../../Screenshots/2023_12_22_10_22_23.png", width: 80%)], )
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/SA/concept_questionnaire/concept_questionnaire.typ
typst
#import "../style.typ": * #show heading.where(level: 1): it => { text(it, size: 1.3em); v(2em); } #set page(footer: sa_footer((authors-short: [<NAME>, <NAME>]))) #set text(size: 1.2em) #let concept(data) = [ #set page( margin: (bottom: 2cm, top: 1cm, left: 1cm, right: 1cm)) #let scenario(title, content) = block( inset: 8pt, radius: 6pt, width: 100%, stroke: .5pt, height: 7cm)[ === #title #line(length: 100%, stroke: .5pt) #align(center + horizon, content) ] = #data.title #v(-2em) #let gutter = .5cm #columns(2, gutter: gutter)[ #scenario("Simple Addition Function")[ #data.simple_addition ] #colbreak() #scenario("Even Numbers from 1 to 10")[ #data.even_one_to_ten ] ] #v(gutter) #v(-1em) #columns(2, gutter: gutter)[ #scenario("Product of Numbers")[ #data.product_of_numbers ] #colbreak() #scenario("Map Add 5 Function")[ #data.map_add_5_function ] ] #let question(text) = [ #v(.7em) #text #box(width: 1fr, repeat[.]) ] #if data.show-questions [ #question("Were you able to understand the meaning of the boxes and arrows?") #question("Do you find the concept nice to look at?") #question("Could you imagine teaching functional programming using this vizualization?") #question("Could you imagine how the concept scales to more complex expressions?") #question("Do you have any suggestions for improvement or general comments on the concept?") ] ] = VisualFP Concept Questionnaire Hi there, In the context of our SA, we are currently searching for a new way to visualize functional programming concepts. Before we start to flesh out our ideas, we would like to get some feedback on a few visualization concepts we came up with. We'll then decide which one we'll develop further based on the received feedback. In the end, we will have designed a concept, along with a proof of concept of some of its functionality, that fullfills the following criteria: 1. It can be used to teach functional programming concepts 2. It is able to visualize Haskell code On the next page you'll find a few Haskell snippets that we prepared as example scenarios. Then we used the concepts to visualize the scenarios, and added a few questions at the bottom of each. It would be great if you could take a few minutes to answer them. Please note that: - These concept are in early stages of development, so there can be bugs and inconsistencies in the examples. If you find any, feel free to point them out. - We've consciously decided to not give more textual explanations of the concepts, as we want to see how well they can stand on their own. - Some visualizations barely fit into the boxes. We regard this as a downside of these concepts, since this indicates that they don't scale well. We tried to provide high resultion images though, so you should be able to zoom in to see the details. Thank you very much for your time! #v(1em) <NAME> & <NAME> #pagebreak() #concept(( title: "Scenarios", show-questions: false, simple_addition: [ ```haskell addition :: Num a => a -> a -> a addition a b = (+) a b ``` ], even_one_to_ten: [ ```haskell evenOneToTen :: Integral a => [a] evenOneToTen = filter even (takeWhile ((<= 10)) (iterate (+1) 1)) ``` ], product_of_numbers: [ ```haskell product :: Num a => [a] -> a product [] = 1 product (n : ns) = (*) n (product ns) ``` ], map_add_5_function: [ ```haskell mapAdd5 :: Num a => [a] -> [a] mapAdd5 = map (+ 5) ``` ] )) #concept(( title: "Flo inspired", show-questions: true, simple_addition: [ #image("static/flo-inspired-addition.png", width: 80%) ], even_one_to_ten: [ #image("static/flo-inspired-evenOneToTen.png", width: 80%) ], product_of_numbers: [ #image("static/flo-inspired-product.png", width: 105%) ], map_add_5_function: [ #image("static/flo-inspired-mapAdd5.png", width: 80%) ] )) #concept(( title: "Scratch inspired", show-questions: true, simple_addition: [ #set text(font: "Ubuntu") #image("static/scratch_addition.svg", width: 60%) ], even_one_to_ten: [ #set text(font: "Ubuntu") #image("static/scratch_evenOneToTen.svg") ], product_of_numbers: [ #set text(font: "Ubuntu") #image("static/scratch_product.svg", width: 99%) ], map_add_5_function: [ #set text(font: "Ubuntu") #image("static/scratch_mapAdd5.svg", width: 50%) ] )) #concept(( title: "Haskell Function-Notation inspired", show-questions: true, simple_addition: [ #image("static/funcnotation_addition.png", height: 40%) ], even_one_to_ten: [ #image("static/funcnotation_evenOneToTen.png", width: 105%) ], product_of_numbers: [ #image("static/funcnotation_product.png", height: 85%) ], map_add_5_function: [ #set text(font: "Ubuntu") #image("static/funcnotation_mapAdd5.png", width: 75%) ], count_words: [ ] )) If you have an own idea for a visualization concept, we would be happy to see it!
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/复习/补考/补考.typ
typst
#set text(font: "STSong") = 基础 二极管的正向电流大,反向 == 半导体基本方程 由麦克斯韦方程组结合固体物理特性给出 #align(center,image("./1.png",width: 50%)) - 能带:容纳电子的一系列能级 - 禁带:不容na电子的能级 - 价带:0K最高能级 #align(center,image("./2.png",width: 40%)) 假象的例子为空穴,没有真实存在。 == 半导体 导体 绝缘体 #align(center,image("./3.png",width: 60%)) #align(center,image("./4.png",width: 80%)) // #set terms(font("STSong")) / *本征半导体*: 无杂质,纯度高,具有晶体结构的半导体。 电子和空穴成对出现,称为电子-空穴对。 电子和空穴不断产生,成动态平衡,称为载流子。其浓度与温度密切相关。 2、施主杂质:向硅半导体提供一个自由电子而本身带正电的粒子杂质,此时电子为多数载流子,称为n型半导体。 3、受主杂质:向硅半导体提供一个空穴而本身带负点的杂质,主要靠受主提供空穴导电,空穴为多数载流子,称为p型半导体。 施点恩,受点骗。 #import "@preview/pyrunner:0.1.0" as py #let compiled = py.compile( ```python def find_emails(string): import re return re.findall(r"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b", string) def sum_all(*array): return sum(array) ```) #let txt = "My email address is <EMAIL> and my friend's email address is <EMAIL>." #py.call(compiled, "find_emails", txt) #py.call(compiled, "sum_all", 1, 2, 3) 11111 #import "@preview/quick-maths:0.1.0": shorthands #show: shorthands.with( ($+-$, $plus.minus$), ($|-$, math.tack), ($<=$, math.arrow.l.double) // Replaces '≤' ) $ x^2 = 9 quad <==> quad x = +-3 $ $ A or B |- A $ $ x <= y $
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/align_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test start and end alignment. #rotate(-30deg, origin: end + horizon)[Hello] #set text(lang: "de") #align(start)[Start] #align(end)[Ende] #set text(lang: "ar") #align(start)[يبدأ] #align(end)[نهاية]
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/regexes.typ
typst
let dashed-line = "^-{10,}"
https://github.com/rabotaem-incorporated/algebra-conspect-1course
https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/04-linear-algebra/08-linear-dep-and-indep.typ
typst
Other
#import "../../utils/core.typ": * == Линейная зависимость и независимость #ticket[Линейно зависимые семейства, свойства] #def[ Набор $v_1, ..., v_n in V$ называется _линейно зависимым семейством_ (ЛЗС), если $exists alpha_1, ..., alpha_m in K space.quad alpha_1 v_1 + ... + alpha_m v_m = 0$ и не все $alpha$ равны 0. Иначе такой набор называется _линейно независимым семейством_ (ЛНС). ] #notice[ $Lin(empty) = {0}$. ] #pr[ $v_1, ..., v_m in V$, тогда равносильны: + $v_1, ..., v_m$ --- ЛЗС + $exists j: 1 <= j <= m space.quad v_j in Lin(v_1, ..., hat(v)_j, ..., v_m)$ + $exists j: 1 <= j <= m space.quad v_j in Lin(sq(v, j - 1))$ ] #proof[ - "$3 => 2$": Очевидно. - "$2 => 1$": Пусть $v_j = alpha_1 v_1 + ... + hat(alpha_j v_j) + ... + alpha_m v_m$. Тогда $alpha_1 v_1 + ... + (-1) mul v_j + ... + alpha_m v_m = 0$ и это нетривиальная линейная комбинация. - "$1 => 3$": $alpha_1 v_1 + ... + alpha_m v_m = 0$. Существует $j : alpha_j != 0$. Возьмем максимальное такое $j$. Выкинем все слагаемые с индексом больше $j$ и поделим на $alpha_j$: $ alpha_(1) / alpha_j v_1 + ... + v_j = 0 ==> v_j = -alpha_(1) / alpha_j v_(1) - ... - alpha_(j - 1) / alpha_j v_(j - 1). $ Получилось что $v_j in Lin(v_(1), ..., v_(j - 1))$. ] #pr[ Пусть $sq(v)$ --- ЛЗC, тогда $sq(v), v$ --- тоже ЛЗC. ] #proof[ Очевидно. ] #follow[ Набор векторов, содержащий $0$ --- ЛЗС ] #proof[ Пусть $v_j = 0$, тогда поставим $a_j eq.not 0$, а остальные $a_i = 0$. ] #ticket[Теорема о линейной зависимости линейных комбинаций] #th(name: "О линейной зависимости линейных комбинаций")[ Пусть $sq(v, m) in V$, $sq(w) in Lin(sq(v, m))$. Тогда если $n > m$, то $sq(w)$ --- ЛЗС. ] #proof[ Индукция по $m$. "База": $m = 0$: $w_1 = Lin(empty) ==> w_1 = 0 ==> sq(w)$ --- ЛЗС. "Переход": $m - 1 ~~> m$: Знаем, что $sq(w) in Lin(sq(v, m))$, значит: $ w_1 = alpha_(1 1) v_1 + ... + alpha_(1 m) v_(m) \ w_2 = alpha_(2 1) v_1 + ... + alpha_(2 m) v_(m) \ dots.v \ w_n = alpha_(n 1) v_1 + ... + alpha_(n m) v_(m) \ $ Рассмотрим случаи. Если $alpha_(1 m) = alpha_(2 m) = ... = alpha_(n m) = 0$, то $sq(w) in Lin(sq(v, m - 1))$ и по предположению индукции, $sq(w)$ --- ЛЗС. Иначе найдется $j$ такой что $a_(j m) != 0$. Не умаляя общности, считаем $j = n$. Тогда $ w_i - alpha_(i m) / alpha_(n m) w_n in Lin(sq(v, m - 1)), space i in {1, ..., n - 1}, $ так как мы занулили коэфицент при $v_m$. $n - 1 > m - 1$, поэтому по индукционному предположению, ${w_i - alpha_(i m) / alpha_(n m) w_n bar i in {1, ..., n - 1}}$ --- ЛЗС. Тогда найдутся $beta_1, ..., beta_(n - 1) in K$, (среди которых не все равны 0), такие, что $ sum_(i = 1)^(n - 1) beta_i (w_i - alpha_(i m) / alpha_(n m) w_n) = 0. $ Значит $w_1, ..., w_n$ --- ЛЗС (т.к. если раскрыть скобки в формуле выше, то получатся коэфициенты для всех $w_i$). ]
https://github.com/linhduongtuan/BKHN-Thesis_template_typst
https://raw.githubusercontent.com/linhduongtuan/BKHN-Thesis_template_typst/main/template/template.typ
typst
Apache License 2.0
#import "font.typ": * //#import "tablex.typ": * #import "tablex.typ": tablex, cellx, rowspanx, colspanx, hlinex, vlinex, gridx, default-if-auto #let Thesis( // File path to Reference bib ) = { set page(paper: "a4", margin: ( top: 2.54cm, bottom: 2.54cm, left: 2.5cm, right: 2cm), footer: [ #set align(center) #set text(size: font_size.scriptsize, baseline: -3pt) #counter(page).display( "1 / 1") ] ) show raw: it => if it.block { v(1.5em, weak: true) it } else { it } show raw.where(block: true): it => { set par(justify: false) block(inset: (left: 1em), grid(columns: (100%, 100%), column-gutter: -100%, block(width: 100%, inset: 1em, { let lines = it.text.split("\n").rev() let _i = 0 while _i < lines.len() and lines.at(_i).trim() == "" and _i < 2 { _i += 1 } let lines = lines.slice(_i).rev() for (i, line) in lines.enumerate() { hide(box(width: 0pt, align(right, str(i + 1) + h(2em)))) set text(fill: rgb("#5e5e5e"), size: 0.75em) box(width: 0pt, align(right, str(i + 1) + h(2em))) hide(line) linebreak() } }), block(stroke: (left: 0.025cm + rgb("#8e8e8e")), fill: luma(246), width: 100%, inset: 1em, it), )) } show raw.where(block:true): block.with( width: 100%, ) // import the cover page include "cover.typ" // import acknowledgement include "acknowledgement.typ" set page( header: { set text(font: arial, 10pt, baseline: 8pt, spacing: 3pt) table( columns: (1fr, auto, auto), stroke: none, align: (x, y) => (left, center, right).at(x), [How to use ChatGPT to improve the quality of a thesis written in English?], [], [<NAME>] ) line(length: 100%, stroke: 0.1pt) } ) // import abstract include "abstract.typ" // import tables of contents, lists of tables and figures include "toc.typ" // import body include "body.typ" // import References include "reference.typ" // import appendices include "appendix.typ" }
https://github.com/ShapeLayer/ucpc-solutions__typst
https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/lib/i18n.typ
typst
Other
#import "./i18n/en-us.typ" #import "./i18n/ko-kr.typ" #let supports = ( // Insert locales here ("en-us", en-us), ("ko-kr", ko-kr) )
https://github.com/PeiPei233/typst-template
https://raw.githubusercontent.com/PeiPei233/typst-template/main/zju-exp-report/report-template.typ
typst
#let song = ("Times New Roman", "SimSun") // #let song = "Source Han Serif SC" #let san = 16pt #let xiaosan = 15pt #let si = 14pt #let xiaosi = 12pt #let fake-par = { v(-1em) show par: set block(spacing: 0pt) par("") } #let update_arg(dict1, dict2) = { for (k,v) in dict2 { if k in dict1{ dict1.insert(k,v) } } dict1 } #let cover_default = ( course: "", name: "", college: "", department: "", major: "", id: "", advisor: "", date: datetime.today(), ) #let cover( ..args ) = { let info = args.named() let info-key(body) = { block( inset: (top: 5pt), align(right)[#body], ) } let info-value(body) = { block( inset: (top: 8pt), stroke: (bottom: 0.5pt), body ) } set align(center) set text(font: song, size: si, lang: "zh") set block(width: 100%, height: 23pt) pagebreak(weak: true) v(60pt) image("logo.svg", width: 50%) v(20pt) text(font: "Source Han Serif SC", size: san, weight: "bold")[本科实验报告] v(50pt) table( columns: (75pt, 300pt), row-gutter: 13pt, stroke: none, info-key("课程名称:"), info-value(info.course), info-key("姓 名:"), info-value(info.name), info-key("学 院:"), info-value(info.college), info-key("系:"), info-value(info.department), info-key("专 业:"), info-value(info.major), info-key("学 号:"), info-value(info.id), info-key("指导教师:"), info-value(info.advisor), ) v(50pt) info.date pagebreak(weak: true) } #let report_title_default = ( course: " ", type: " ", title: " ", name: " ", major: " ", id: " ", collaborator: " ", advisor: " ", location: " ", year: " ", month: " ", day: " ", ) #let report-title( ..args ) = { pagebreak(weak: true) let info = args.named() let info-key(body) = { block( inset: 3pt, body ) } let info-value(body) = { block( inset: 4pt, stroke: (bottom: 0.5pt), body ) } set align(center) set text(font: song, size: xiaosi, lang: "zh") set block(width: 100%) set table(inset: 0pt,stroke: none) show table: set block(spacing: 0.8em) text(font: "Source Han Serif SC", size: xiaosan, weight: "bold")[浙江大学实验报告] v(15pt) table( columns: (1fr, 51%, 1fr, 21%), inset: 0pt, stroke: none, info-key("课程名称:"), info-value(info.course), info-key("实验类型:"), info-value(info.type), ) // v(-1em) table( columns: (1fr, 81%), info-key("实验项目名称:"), info-value(info.title), ) // v(-1em) table( columns: (5fr, 15%, 3fr, 33%, 3fr, 21%), info-key("学生姓名:"), info-value(info.name), info-key("专业:"), info-value(info.major), info-key("学号:"), info-value(info.id), ) // v(-1em) table( columns: (7fr, 47%, 5fr, 20%), info-key("同组学生姓名:"), info-value(info.collaborator), info-key("指导教师:"), info-value(info.advisor), ) // v(-1em) table( columns: (4fr, 43%, 4fr, 9%, 1fr, 5%, 1fr, 5%, 1fr), info-key("实验地点:"), info-value(info.location), info-key("实验日期:"), info-value(info.year), info-key("年"), info-value(info.month), info-key("月"), info-value(info.day), info-key("日"), ) } #let project( title: " ", course: " ", name: " ", id: " ", collaborator: " ", advisor: " ", college: " ", department: " ", major: " ", location: " ", type: " ", year: str(datetime.today().year()), month: str(datetime.today().month()), day: str(datetime.today().day()), ) = { let info = ( title: title, course: course, name: name, id: id, collaborator: collaborator, advisor: advisor, college: college, department: department, major: major, location: location, type: type, year: year, month: month, day: day, date: year + " 年 " + month + " 月 " + day + " 日 ", ) ( cover: (..args) => { cover(..update_arg(cover_default,info),..args) }, report-title: (..args) => { report-title(..update_arg(report_title_default,info),..args) }, doc: (body) => { set page(numbering: (..numbers) => { if numbers.pos().at(0) > 1 { numbering("1", numbers.pos().at(0) - 1) } }) set text(font: "Linux Libertine", lang: "en") set par( first-line-indent: 1em, justify: true ) set heading(numbering: "1.1 ") set list(indent: 1em, body-indent: 1em) set enum(indent: 1em, body-indent: 1em) show heading: it => { it v(5pt) fake-par } show terms: it => { set par(first-line-indent: 0pt) set terms(indent: 10pt, hanging-indent: 9pt) it fake-par } show raw: it => { set text(font: ("Lucida Sans Typewriter", "Source Han Sans HW SC")) if it.lines.len() > 1 [ #it #fake-par ] else [ #it ] } show enum: it => { it fake-par } show list: it => { it fake-par } show figure: it => { it fake-par } show table: it => { it fake-par } body } ) }
https://github.com/vEnhance/1802
https://raw.githubusercontent.com/vEnhance/1802/main/src/ints.typ
typst
MIT License
#import "@local/evan:1.0.0":* = Double integrals One common theme from 18.02 that you might have noticed in part Foxtrot is that, unlike in 18.01 where you were hyper-focused on the function $f$ you were optimizing, in 18.02 the _region_ you're working with deserves a lot of attention. This will be true for the material in this section too --- you ought to paying most attention to the region before you even look at the function $f$ that's being integrated. == [RECIPE] Integrating over rectangles If you want to integrate over a rectangle, this is super easy. It's basically like partial derivatives, where you pretend some variables are constant and only one variable is going to vary at once. It's easier to see an example before the recipe. #warning(title: [Warning: Some sources might not write the variables in the $int$'s for you])[ Rather than writing just $int_a^b f(t) dif t$, I will usually prefer to write $int_(t=a)^b f(t) dif t$, to make it easier to see which variable is integrated over. Not all sources will be nice enough to do this and will actually make you read the $dif x$ and $dif y$ backwards; e.g. if you see $ int_0^6 int_0^1 x y^2 dif x dif y $ then this actually means $ int_0^6 (int_0^1 x y^2 dif x) dif y $ so $0 <= x <= 1$ and $0 <= y <= 6$. For me reading backwards like this is annoying as hell, so I think it's just much easier to write $ int_(y=0)^6 int_(x=0)^1 x y^2 dif x dif y $ and I recommend you use that notation instead. The advantage is that then you pretty much don't have to look at the $dif x dif y$ at the far right anymore; the information you need is all in one place at the far left. ] #sample[ Integrate $int_(y=0)^6 int_(x=0)^1 x y^2 dif x dif y. $ ] #soln[ 1. The first step is to compute the inner integral with respect to $x$, treating $y$ as a constant. The inner integral is: $ int_(x=0)^1 x y^2 dif x . $ Since $y^2$ is treated as a constant with respect to $x$, we can factor it out of the integral: $ y^2 int_(x=0)^1 x dif x . $ Now, compute $int_(x=0)^1 x dif x$: $ int_(x=0)^1 x dif x = [x^2 / 2]_0^1 = 1^2 / 2 - 0^2 / 2 = 1 / 2 . $ Thus, the result of the inner integral is: $ y^2 dot 1 / 2 = y^2 / 2 . $ 2. Now, substitute the result of the inner integral into the outer integral: $ int_(y=0)^6 y^2 / 2 dif y &= 1 / 2 int_(y=0)^6 y^2 dif y \ &= 1/2 int_(y=0)^6 y^2 dif y = 1/2 [y^3 / 3]_0^6 = 1/2( 6^3 / 3 - 0^3 / 3) &= 36. $ ] Easy, right? The general recipe is the same. #recipe(title: [Recipe for integrating over a rectangle])[ To integrate something of the form $int (int dif y) dif x$: 1. Evaluate the inner integral as in 18.01, treating $x$ as constant. This should give you some expression in $x$ with no $y$'s left. 2. Replace the inner integral with the result from the previous step to get an 18.01 integral with only $x$ in it. Integrate that. ] Here's another example. #sample[ Evaluate the double integral: $ int_(x=0)^pi int_(y=0)^1 x cos (x y) dif y dif x . $ ] #soln[ 1. The first step is to compute the inner integral with respect to $y$, treating $x$ as a constant. The inner integral is: $ int_(y=0)^1 x cos (x y) dif y . $ Since $x$ is treated as a constant with respect to $y$, we can factor $x$ out of the integral: $ x int_(y=0)^1 cos (x y) dif y . $ Now, we compute $int_(y=0)^1 cos (x y) dif y$. $ int_(y=0)^1 cos (x y) dif u = [1/x sin (x y)]_0^1 = sin(x) / x. $ Thus, the result of the inner integral is: $ x dot sin(x) / x = sin (x) . $ 2. Now, substitute the result of the inner integral into the outer integral: $ int_(x=0)^pi sin (x) dif x . $ We know that $integral sin (x) dif x = - cos (x)$. Therefore: $ int_(x=0)^pi sin (x) dif x = [- cos (x)]_0^pi = - cos (pi) + cos (0) . $ Using $cos (pi) = - 1$ and $cos (0) = 1$, we get: $ - (- 1) + 1 = 1 + 1 = 2 . $ ] == [RECIPE] Doing $x y$-integration without a rectangle In general, a lot of 2-D regions $cal(R)$ can still be done with $x y$ integration, even when they aren't rectangles. In that case, the integral is notated $ iint_(cal(R)) f(x,y) dif x dif y := "integral of " f " over " cal(R) $ for whatever function $f$ you're integrating. If the region is given by a few inequalities you can also write the region directly in, i.e. $iint_(x^2+y^2<=1) f(x,y) dif x dif y$ would mean the integral of $f$ over the unit disk. Here's how you do it. #warning(title: [Warning: We won't use all the other $dif$ variants like $dif A$, $dif bf(n)$, etc. in LAMV])[ A lot of other sources might write this as $iint_(cal(R)) f(x,y) dif A$ instead, which is shorter; it's understood that the area element $dif A$ is shorthand for $dif x dif y$. However, I'll usually explicitly write $dif x dif y$, because I don't want to hide the integration variables. Reason: in the future, if you use different coordinate systems, $dif A$ can look different. For example, in polar coordinates $(r, theta)$ defined later, you'll have $dif A = r dif r dif theta$ instead (so $dif A != dif r dif theta$). So rather than hide these all in "$dif A$", I'll actually write out what it is each time. That said, if you know what you're doing and want to write $dif A$ to save time, go for it! ] #recipe(title: [Recipe for converting to $x y$-integration])[ 1. Draw a picture of the region as best you can. 2. Write the region as a list of inequalities.#footnote[I don't think other sources always write the inequalities the way I do. But I think this will help you a lot with making sure bounds go the right way.] 3. Pick _one_ of $x$ and $y$, and use your picture to describe all the values it could take. 4. Solve for the _other_ variable in all the inequalities. ] #remark(title: [Remark: This recipe works fine for rectangles, too!])[ You can do this recipe even with a rectangle. If you do, what the recipe tells you that for a rectangle you can integrate in either order: given the rectangle of points $(x,y)$ with $a <= x <= b$ and $c < y <= d$, we have $ int_(x=a)^b int_(y=c)^d f(x,y) dif y dif x = int_(y=c)^d int_(x=a)^b f(x,y) dif x dif y. $ Sometimes this will be easier. One shape of exam question will to be choose $f$ such that the left-hand side is annoying to calculate directly but the right-hand side is easy to calculate, and ask for the left-hand side. So this is meant to test your ability to recognize when the other order is better ] For example, let's take the region in Poonen's example 13.1: #sample[ Show both ways of setting up an integral of a function $f(x,y)$ over the region bounded by $y-x=2$ and $y=x^2$. ] #figure( image("figures/ints-pararegion.png", width: auto), caption: [The region between $y=x^2$ and $y-x=2$.], ) <fig-pararegion> #soln[ See @fig-pararegion. There are two intersection points that it's pretty clear we'll want to know, so we can solve for those intersection points by solving the system and add them to our picture: $ cases(y-x=2, y=x^2) &==> x+2 = x^2 ==> x = -1 " or " x = 2 \ &==> (x,y) = (-1,1) " or " (x,y) = (2,4). $ I'll also mark $(0,0)$, the bottom of the parabola. So we want the part of the plane that lies _above_ the parabola $y=x^2$ but _below_ the line $y-x=2$. So I think you'll find things easier to think about if you consider the region as the system of inequalities $ y >= x^2 \ y - x &<= 2. $ Now there are two ways to do the slicing, depending on which of $x$ and $y$ you want outside. / If $x$ is outer: First, let's imagine we let $x$ be the outer integral. Then from the picture, you can see $-1 <= x <= 2$. If we solve for $y$, we find its region is $ x^2 <= y <= x+2. $ See @fig-pararegion-vert. #figure( image("figures/ints-para-vert.png", width: auto), caption: [Dissecting @fig-pararegion vertically, which is pretty nice. There's a single top lid (blue) and a bottom lip (purple) so that for each given $x$ the slice of $y$ (drawn in green) is easy to describe.], ) <fig-pararegion-vert> Hence, we get the double integral as $ int_(x=-1)^2 int_(y=x^2)^(x+2) f(x,y) dif y dif x. $ / If $y$ is outer: On the other hand, let's imagine we used $y$ first. From the picture, we see that $y$ ranges from $0$ all the way up to $4$. (So in what follows I'll write $y >= 0$ to make notation better.) But $x$ is gnarly. The issue is that when you solve for $x$ you get _three_ inequalities: - $y <= x^2$ solves to $-sqrt(y) <= x <= sqrt(y)$ - $y - x <= 2$ solves to $y-2 <= x$. See @fig-pararegion-horiz. #figure( image("figures/ints-para-horiz.png", width: auto), caption: [Dissecting @fig-pararegion horizontally, which is less nice: there are cases. Above the line $y=1$, you have a blue wall to the left and a curved arc to the right. But below $y=1$, you instead have a red arc of the parabola to the left, and a blue arc of the parabola to the right.], ) <fig-pararegion-horiz> If you know how the max function works, you could even write this as $ max(y-2, -sqrt(y)) <= x <= sqrt(y). $ The main issue is that the lower endpoint for $x$ behaves differently with cases. For $y <= 1$, the bound of $-sqrt(y)$ triumphs over the bound of $y-2$. But for $y >= 1$, the bound of $y-2$ is the more informative inequality. So if we wanted to write this as a double integral, we would actually have to split into two: $ int_(y=0)^1 int_(x=-sqrt(y))^(sqrt(y)) f(x,y) dif x dif y + int_(y=1)^4 int_(x=y-2)^(sqrt(y)) f(x,y) dif x dif y. $ ] == [TEXT] Example with a concrete function $f$ In the previous example we showed how one would integrate a random function $f$ over the region between the line $y-x=2$ and the parabola $y=x^2$. Again, this process is only based on the region --- it doesn't depend on $f$. To flesh things out, let's pick an example function $ f(x,y) = 2x+4y $ as Poonen did, and show how we would find the integral. #sample[ Consider the region $cal(R)$ we just described, the set of points between bounded between $y-x=2$ and $y=x^2$. Integrate $iint_(cal(R)) (2x+4y) dif x dif y$ over this region. ] #soln[ As we saw, there are two different ways to set it up. We'll do the one that's nice (and show the worse one afterwards for comparison), where we have $x$ on the outside. We are given the integral $ int_(x = - 1)^2 int_(y = x^2)^(x + 2) (2 x + 4 y) dif y dif x. $ 1. The first step is to compute the inner integral with respect to $y$, treating $x$ as a constant. The inner integral is: $ int_(y = x^2)^(x + 2) (2 x + 4 y) dif y . $ We can split this integral into two parts: $ int_(y = x^2)^(x + 2) 2 x dif y + int_(y = x^2)^(x + 2) 4 y dif y . $ - The first term is: $ 2 x int_(y = x^2)^(x + 2) 1 dif y = 2 x [y]_(y = x^2)^(y = x + 2) = 2 x ((x + 2) - x^2). $ - The second term is: $ 4 int_(y = x^2)^(x + 2) y dif y = 4 [y^2 / 2]_(y = x^2)^(y = x + 2) = 4 ((x + 2)^2 / 2 - (x^2)^2 / 2) = 2(x^2 + 4x + 4 - x^4). $ Thus, the inner integral is: $ 2 x (x + 2 - x^2) + 2 (x^2 + 4 x + 4 - x^4) = - 2 x^4 - 2 x^3 + 4 x^2 + 12 x + 8 . $ 2. Now, we compute the outer integral: $ & int_(x = - 1)^2 (- 2 x^4 - 2 x^3 + 4 x^2 + 12 x + 8) dif x \ &= lr([-2 x^5 / 5 - 2 dot x^4/4 + 4 x^3/3 + 12 dot x^2/2 + 8x])_(x=-1)^2. $ This is a lot of arithmetic, sorry. One way is to work term by term: $ -2 [x^5 / 5]_(x = - 1)^(x = 2) &= - 2 (32 / 5 - (- 1)^5 / 5) = - 2 dot 33 / 5 = - 66 / 5 \ -2 [x^4 / 4]_(x = - 1)^(x = 2) &= - 2 (16 / 4 - 1 / 4) = - 2 dot 15 / 4 = - 15 / 2 \ 4 [x^3 / 3]_(x = - 1)^(x = 2) &= 4 (8 / 3 - (- 1)^3 / 3) = 4 dot 9 / 3 = 12 \ 12 [x^2 / 2]_(x = - 1)^(x = 2) &= 12 dot 3 / 2 = 18 \ 8 dot (2 - (- 1)) &= 8 dot 3 = 24. $ Add these to get the answer: $ -66/5 -15/2 + 12 + 18 + 24 = 333/10. $ ] == [SIDENOTE] What it looks like if you integrate the hard way In the previous sample question, we picked $x$ to be the outer integral so that we didn't have to do cases or deal with square roots. This was pretty clearly a good choice. For contrast, I'll show you what happens if you have $y$ in the outer integral instead --- just to make a point that things can get ugly. (You can read it if you want the practice with iterated integrals, or skip it if you believe me.) To reiterate, we will directly calculate $ int_(y=0)^1 int_(x=-sqrt(y))^(sqrt(y)) (2x+4y) dif x dif y + int_(y=1)^4 int_(x=y-2)^(sqrt(y)) (2x+4y) dif x dif y. $ - We calculate the first hunk $ int_(y=0)^1 int_(x=-sqrt(y))^(sqrt(y)) (2x+4y) dif x dif y. $ 1. The first step is to compute the inner integral with respect to $x$, treating $y$ as a constant. The inner integral is: $ int_(x = - sqrt(y))^(sqrt(y)) (2 x + 4 y) dif x . $ We can split this into two integrals: $ int_(x = - sqrt(y))^(sqrt(y)) 2 x dif x + int_(x = - sqrt(y))^(sqrt(y)) 4 y dif x . $ - The first term is: $ 2 int_(x = - sqrt(y))^(sqrt(y)) x dif x = 2 [x^2 / 2]_(x = - sqrt(y))^(x = sqrt(y)) = 2 dot ((sqrt(y))^2 / 2 - (- sqrt(y))^2 / 2) . $ - The second term is: $ 4 y int_(x = - sqrt(y))^(sqrt(y)) 1 dif x = 4 y [x]_(x = - sqrt(y))^(x = sqrt(y)) = 4 y (sqrt(y) - (- sqrt(y))) = 4 y dot 2 sqrt(y) = 8 y^(3 / 2) . $ Thus, the inner integral is: $ 0 + 8 y^(3 / 2) = 8 y^(3 / 2) . $ 2. Now, we compute the outer integral: $ int_(y = 0)^1 8 y^(3 \/ 2) dif y . $ We use the power rule for integration: $ integral y^(3 \/ 2) dif y = y^(5 \/ 2) / 5 / 2 = 2 / 5 y^(5 \/ 2) . $ Thus, the outer integral becomes: $ 8 int_(y = 0)^1 y^(3 / 2) dif y = 8 dot 2 / 5 [y^(5 / 2)]_(y = 0)^(y = 1) = 8 dot 2 / 5 dot (1^(5 / 2) - 0^(5 / 2)) = 8 dot 2 / 5 = 16/5 . $ Hence the first hunk is $ int_(y=0)^1 int_(x=-sqrt(y))^(sqrt(y)) (2x+4y) dif x dif y = 16/5 = 3.2. $ - We calculate the second hunk $ int_(y=0)^1 int_(x=y-2)^(sqrt(y)) (2x+4y) dif x dif y. $ 1. The first step is to compute the inner integral with respect to $x$, treating $y$ as a constant. The inner integral is: $ int_(x = y - 2)^(sqrt(y)) (2 x + 4 y) dif x . $ We can split this into two integrals: $ int_(x = y - 2)^(sqrt(y)) 2 x dif x + int_(x = y - 2)^(sqrt(y)) 4 y dif x . $ - The first term is: $ int_(x = y - 2)^(sqrt(y)) 2 x dif x = 2 [x^2 / 2]_(x = y - 2)^(x = sqrt(y)) = ((sqrt(y))^2 - (y - 2)^2) . $ Simplifying: $ (y - (y^2 - 4 y + 4)) = y - (y^2 - 4 y + 4) = y - y^2 + 4 y - 4 = - y^2 + 5 y - 4 . $ - The second term is: $ 4 y int_(x = y - 2)^(sqrt(y)) 1 dif x = 4 y (sqrt(y) - (y - 2)) = 4 y (sqrt(y) - y + 2) = 4 y (sqrt(y) - y + 2) . $ Thus, the inner integral is: $ (- y^2 + 5 y - 4) + 4 y (sqrt(y) - y + 2) = - y^2 + 5 y - 4 + 4 y sqrt(y) - 4 y^2 + 8 y . $ Simplifying we get the inner integral to be $ - 5 y^2 + 13 y + 4 y sqrt(y) - 4 . $ 2. Now, we compute the outer integral: $ int_(y = 1)^4 (- 5 y^2 + 13 y + 4 y sqrt(y) - 4) dif y . $ To keep things organized, we integrate each term individually: $ int_(y = 1)^4 - 5 y^2 dif y &= - 5 [y^3 / 3]_(y = 1)^(y = 4) = - 5 dot (64 / 3 - 1 / 3) = - 5 dot 63 / 3 = - 105 \ int_(y = 1)^4 13 y dif y &= 13 [y^2 / 2]_(y = 1)^(y = 4) = 13 dot (16 / 2 - 1 / 2) = 13 dot 15 / 2 = 97.5 \ int_(y = 1)^4 4 y sqrt(y) dif y &= 4 int_(y = 1)^4 y^(3 \/ 2) dif y = 4 dot [2 / 5 y^(5 \/ 2)]_(y = 1)^(y = 4) = 4 dot 2 / 5 (32 - 1) = 248 / 5 = 49.6 \ int_(y = 1)^4 - 4 dif y &= - 4 [y]_(y = 1)^(y = 4) = - 4 (4 - 1) = - 12. $ Now, add up the integrals: $ - 105 + 97.5 + 49.6 - 12 = 30.1 . $ - The final answer is $3.2 + 30.1 = 33.3$ as expected. So we got the same answer, no surprise, but it took a lot more work to get it. == [TEXT] A few physical interpretations of integrals Depending on what function $f$ is chosen, the integral may have some physical meaning. We give a few examples here: === Area If you choose $f = 1$ you get area. #recipe(title: [Recipe for area])[ To find the area of a region $cal(R)$, use $ op("Area")(cal(R)) = iint_(cal(R)) 1 dif x dif y. $ ] #sample[ Consider the region $cal(R)$ we just described, the set of points between bounded between $y-x=2$ and $y=x^2$. Compute its area. ] #soln[ We'll write this as $ int_(x = - 1)^2 int_(y = x^2)^(x + 2) 1 dif y dif x. $ The inner integral is easy $int_(y=x^2)^(x+2) dif y = (x+2)-x^2$. So the answer is $ int_(x = - 1)^2 (x+2-x^2) dif x = lr([x^2/2 + 2x - x^3/3])_(x=-1)^(x=2) = (2+4-8/3) - (1/2-2+1/3) = 9/2. #qedhere $ ] === Mass and center of mass If you imagine your region $cal(R)$ as a blob of some substance (concrete, wood, water, etc.), then you could also imagine it has a _density_ at each point in the region (say, in grams per square meter). In 18.02 we usually denote the density by $rho$, which is a function taking each point $P$ in the region $cal(R)$ and outputting its density. In that case, the total mass of $cal(R)$ is the integral of the densities: $ op("mass")(cal(R)) = iint_(cal(R)) rho(x,y) dif x dif y. $ Given a region you can also consider the _center of mass_. The idea/definition is that the $x$-coordinate of the center of mass should be the weighted average of the $x$-coordinates of the points in the region: $ x"-coord of the center of mass" = 1/(op("mass")(cal(R))) iint_(cal(R)) x dot rho(x,y) dif x dif y. $ And the same for the others. Let's repeat this in recipe form. #recipe(title: [Recipe for total mass and center of mass])[ Suppose $cal(R)$ is a region and $rho$ is a density function for the region. 1. The total mass is given by $op("mass")(cal(R)) = iint_(cal(R)) rho(x,y) dif x dif y. $ 2. The center of mass is given by the point $ lr(( (iint_(cal(R)) x dot rho(x,y) dif x dif y) / (op("mass")(cal(R))), (iint_(cal(R)) y dot rho(x,y) dif x dif y) / (op("mass")(cal(R))))). $ ] (It took considerable self-restraint to not title the recipe "Mass Tech".) #typesig[ If $cal(R)$ is a region in $RR^2$, - Then a density function $rho : cal(R) -> RR_(>= 0)$ should take on nonnegative values. (For physicists: in SI units, you might imagine it as grams per square meter.) - The mass is a nonnegative real number (grams). - The center of mass is also a _point_ inside $cal(R)$. (Draw this as a dot, not an arrow.) ] #todo[Write some example] #remark[ Unsurprisingly if $rho = 1$ is constant (imagine 1 gram per square meter), then the mass of the region $cal(R)$ is just $iint_(cal(R)) dif x dif y$, i.e. the area. (So a region whose area is $17$ square meters and where the density is 1 gram per square meter in the whole substance should be $17$ grams.) ] == [SIDENOTE] What's the analogy to "area under the curve" from 18.01? In 18.01, you were told that the integral $int_(x=a)^b f(x) dif x$ denotes the area under the curve $y = f(x)$ from $x = a$ to $x = b$. In 18.02, if you have $iint_(cal(R)) f(x,y) dif x dif y$, and you want to interpret it analogously, what you would do is look at the surface $z = f(x,y)$ in an $x y z$-plane, where you imagine the $x y$-plane and the region $cal(R)$ at the bottom, and $z$ being a height. Then the double integral analogously calculates the volume underneath the surface. However, we won't actually use this interpretation much in 18.02. As I said before, in 18.02 we usually prefer to draw pictures where all the axis variables are treated with equal respect. (Whereas the 18.01 picture I just mentioned uses $x$ as input and $y$ as output; the two axes don't play the same role.) So picturing the double integral with things like mass or center of mass is more in line with the 18.02 spirit, even though there is no 18.01 analog. == [EXER] Exercises #exer[ Let $cal(R)$ be the region between the curves $y = sqrt(x)$ and $y = x^3$. Compute $iint_(cal(R)) x^(100) y^(200) dif x dif y$ in both ways. ] #exer[ Let $cal(R)$ be all the points on or inside the triangle with vertices $(0,0)$, $(1,2)$ and $(2,1)$. Compute $iint_(cal(R)) x y dif x dif y$. ] #exer[ Let $cal(R)$ be the region between the curves $y = sqrt(x)$ and $y = x^2$. Assume $cal(R)$ has constant density. Calculate its center of mass. ]
https://github.com/Trebor-Huang/HomotopyHistory
https://raw.githubusercontent.com/Trebor-Huang/HomotopyHistory/main/beginnings.typ
typst
#import "common.typ": * = 开端 本章主要参考 Poincaré 的 _Analysis Situs_ 英译 @AnalysisSitusTranslation. 数学在很长一段时间中都依赖于直觉和不严谨的论证. Weierstrass 对分析学的重建是数学走向严格的开端. 尽管这在 1880 年代就已经在分析学中确立了标准, 在拓扑学的研究中仍然有许多凭借直觉的部分. 一部分原因是十九世纪晚期的数学各分支间的交流仍然不多. @ATDTHistory 因此, 对于这部分历史, 无需过分纠结具体定义上的不严格之处. == Poincaré 前的拓扑学 在 Poincaré 之前, 可以说拓扑中唯一重要的成果就是 Euler 的多面体公式. 对于一个多面体, 如果将其顶点数记作 $V$, 棱数为 $E$, 面数为 $F$, 那么有 $ V - E + F = 2. $ Euler 无法给出公式的严格证明. 对于凸多面体的情况, Legendre 首先给出了一个利用球面几何的证明. 不过对于有“洞”的多面体, 这个公式是不成立的. 这一点是由一位不见经传的数学家 <NAME> 注意到的. 他把 Euler 的公式修正为 $ V - E + F = 2 - 2g. $ 其中 $g$ 是多面体“洞”的个数, 称为*亏格* (genus). 由于 $n$ 边形的内角和是 $(n - 2)pi$, 这个公式也可以用角度来表达. 多面体每个顶点处的角度和与 $pi$ 的差称作*角亏* (angular defect), 做一些简单的代数变换就能看出, 角亏的总和就是 Euler 特征的 $2pi$ 倍. 类似的概念在连续的曲面中也有体现. 对于三维空间中的曲面, 如果对它每一点处的 Gauss 曲率积分, 就会得到 Euler 特征的 $2pi$ 倍. 这就是 Gauss–Bonnet 公式, 由此可以将 Gauss 曲率看作是角亏的微元, 或者说角亏是曲率的离散版本. “Genus” 这个词是在 Abel 考虑代数曲线的分类时提出的, 来源于拉丁文单词, 意为 “种类”. Riemann 革命性地将代数曲线与它的 Riemann 曲面联系在一起. 这样, 亏格就有了拓扑上的解释, 即 Riemann 曲面的 “洞” 的个数, $chi = 2 - 2g$. Möbius 在 1863 年证明了所有 $RR^3$ 中的曲面都同胚于某个标准的亏格 $g$ 可定向曲面 $Sigma_g$. 换句话说所有可定向曲面都可以完全被洞的个数所分类. 1888 年, Dyck 分类了不可定向的曲面. 以上很多成果在都有恰当的高维推广. 其中最重要的是 Betti 的贡献. Riemann 定义了曲面的 “连通性” —— 与现在的含义不同 —— 即曲面能够画出多少条闭曲线而不将其分割成不连通的部分. 对于三维流形, 自然可以考虑其中能画出多少个闭曲面而不将其分割成不连通的部分, 但是这就仅仅给出了其二维的信息. Betti 转而考虑三维流形中能画出多少条曲线, 而不形成某个二维流形的边界. 这就是最早的 *Betti 数*的概念. 一个几何体中最多能画出多少个 $n$ 维曲面而不构成 $(n+1)$ 维曲面的边界, 称作第 $n$ Betti 数. 可以看出二维曲面的第一 Betti 数就退化到原先的连通性的概念. 由此, Betti 指出了几何体的边界在拓扑研究中的重要性. == _Analysis Situs_ Poincaré 在 1895 年发表了论文 _Analysis Situs_. 这个词本意是“位置的分析学”, 是早期对拓扑学的称呼. 这篇论文以及之后的几篇补充奠定了代数拓扑的基础, 也是同伦这个概念的发端. 其一, 他将 Betti 数的概念放在了一个初步的同调论框架下. Poincaré 在 @AnalysisSitusTranslation[§5] 中这样引入了同调: 如果在空间中有子流形 $W$ 使得其边界由流形 $v_1, dots, v_n$ 构成, 就记作 $ v_1 + dots.c + v_n tilde 0. $ 重要的是, Poincaré 规定这些式子可以自由地相加减, 并且 $-v_1$ 表示与 $v_1$ 定向相反的子流形. 用当代的数学语言, 就是考虑这些子流形生成的自由交换群, 商去由边界生成的子群. Poincaré 将 Betti 数定义成 $tilde$ 关系下极大线性独立集的大小. 从当代的视角看, 这就是整数系数同调群的无挠秩. (事实上 Poincaré 定义的 Betti 数和这相差 $1$. 由于这样它满足的恒等式比较复杂, 当代修改了这个定义.) 不过, Betti 数的同胚不变性暂时没有证明. 其二, Poincaré 也注意到了 Betti 数满足的对偶性质, 即对于 $n$ 维流形来说, 它的 Betti 数满足 $P_k = P_(n-k)$. 这就是今天的 Poincaré 对偶的雏形. Poincaré 通过对流形相交数的讨论证明了这一点. 不过数学家 Heegaard 发现证明有问题, 为此 Poincaré 将 Betti 数的计算方法修改为利用多面体剖分, 类似当今的胞腔链复形. 在新的计算方法中, 取定了流形的一个剖分, 并且只考虑剖分中的子流形. 例如可以将球面按照正四面体的形状分割成 4 个三角形, 6 条边与 4 个顶点. 三角形 $A B C$ 的边界就是 $A B + B C - A C$. 由于取边界操作是线性映射, 将剖分的多面体看成基底, 就能用矩阵描述这些多面体的位置关系. 其三, Poincaré 提出了基本群的概念. 对 ($n$ 维) 闭曲面, 他是这样定义基本群的: 先考虑曲面上的一个多值函数 $F$, 例如某种微分方程的解. 那么在某个点出发经过一个环路之后, $F$ 的值就会出现某种变换. 所有可能出现的变换被定义为曲面的*基本群*. 他也定义了道路的拼接与同伦. Poincaré 发现通过粘接基本多边形得到的曲面, 基本群可以根据粘接方式写出一个表现. 例如 Klein 瓶是一个正方形一对边同向粘接, 另一对边反向粘接得到. 将这两对边分别记作 $a, b$, 则如果沿着边界顺时针移动就会经过 $a, b, a^(-1), b$ 四条边, 其中 $a^(-1)$ 表示方向相反. 其基本群就是 $⟨a, b | a b a^(-1) b⟩$. 对于更高维的情况也有类似的现象. Poincaré 立即注意到如果将基本群交换化, 就会得到同调, 从而可以计算第一 Betti 数. 因此可以说 Poincaré 也发现了第一同调群. 对于二维可定向闭流形 $Sigma_g$, Betti 数就足够区分所有的情况. Poincaré 构造了一个例子, 说明 Betti 数不能完全区分高维的流形. 现代将这个例子称作环面丛 (torus bundle). 考虑任何一个矩阵 $M in "SL"(2, ZZ)$. 则它定义了一个连续函数 $TT^2 -> TT^2$. 将 $TT^2 times [0,1]$ 边界两个环面按照 $M$ 粘合起来, 就得到了一个三维可定向闭流形. 学习过同调论的读者不难算出它的 1, 2 维同调群是 $ZZ plus.circle "coim"(1 - M)$. 因此对应的 Betti 数就是 $1,2,3$ 之一. 其基本群 $pi_M$ 满足 $ pi_inline(#math.mat(gap: 1pt, ($alpha$, $beta$), ($gamma$, $delta$))) = lr(⟨x, y, z mid(|) x y = y x, z x = x^alpha y^beta z, z y = x^gamma y^delta z⟩) $ Poincaré 分类了这些群, 得到了无穷多个不同构的基本群. 因此这些流形中有无穷多个不同胚的, 但是它们的 Betti 数却只取到有限多不同的值. Poincaré 随即提出了一些问题. 给定维数的流形能否被基本群完全完全分类? 给定一个群, 它是否是某个流形的基本群? 这些问题都会在后续代数拓扑与几何拓扑的发展中得到解答. 在第五篇补充中, Poincaré 构造了一个三维流形, 其同调与 $SS^3$ 相同, 但是基本群非平凡. 这个空间被称作 *Poincaré 同调球*, 在当代有非常优美的构造方法. 考虑一个实心正 12 面体, 将其相对的面按一个方向旋转 $pi/5$ 之后粘合. 利用这个描述不难算出其基本群的一个表现, 化简后可以得到基本群是一个 120 阶群, 称作二元正 12 面体群. 它的交换子生成的群是它本身, 因此交换化之后得到 $H_1 = 0$. 由 Poincaré 对偶得到同调群和三维球面相同. 这否定了 Poincaré 之前的猜测. 他由此提出了 Poincaré 猜想: 三维球面是唯一一个单连通的闭三维流形. == 拓扑空间的出现 尽管当今学习代数拓扑总是以点集拓扑为前置, 本章介绍的许多概念提出时, 点集拓扑都还没有出现. Poincaré 用了几种不同的方法定义流形: - 一是作为方程 (包括不等式) 的解集, 即将流形定义成一些 $C^1$ 函数的等式与不等式组的解集, 使得等式部分的 Jacobi 矩阵满秩. - 二是利用坐标参数化定义流形, 即给出一个函数 $RR^n -> RR^m$. 不过, 对于单组坐标无法覆盖的情况, Poincaré 利用解析延拓的办法得到了几组相容的坐标卡. - 第三则是利用粘接已有的流形. 对于拓扑性质的构造来说, 这种方式是最灵活的. 不过 Poincaré 没有验证粘接得到的流形仍然光滑. 这三种定义方法并没有被 Poincaré 统一起来, 而是并列出现在论文中. 这也导致某些拓扑上的论证不够严谨, 例如证明所有流形都可以划分为多面体的粘接. 1907 年, 在 Klein 整理的数学百科全书中, Dehn 与 Heegaard 为 _Analysis Situs_ 编写了条目, 其中给出了流形的一种组合定义, 以三角剖分作为流形的基础. 那么为了证明这种定义下 Betti 数的同胚不变性, 一个自然的猜测是证明任意两个三角剖分都有共同的加细. 这被称作 Hauptvermutung, 即德语的 “主要猜想”. 在之后的发展中, 会用另外的办法证明同调的同胚不变性, 并且给出 Hauptvermutung 的反例. 当代对拓扑空间的定义非常简洁. 一个拓扑空间是点集 $X$, 其中 $X$ 的一部分子集被称作 “开集”. 这些子集需要对有限交和任意并封闭. 但是这个定义起初是从各式各样的定义中脱颖而出, 最终沉淀得来的. 对此可以参考 @TopologyHistory, @HistoryOfTopology. 首先是 Fréchet 提出的极限空间 (1904) 与度量空间 (1906). *极限空间*是一个点集 $X$, 为其无穷点列集 $X^NN$ 与 $X$ 之间定义一个关系 ${x_n} arrow.squiggly x$, 表达 “点列收敛到 $x$”. 常点列 $x_n = x$ 收敛到 $x$, 并且如果某个点列收敛, 则其子列也收敛到同一极限. 这样, 就能定义 $X$ 中子集的极限点、列紧性等等概念. 极限空间在当时被称作 L-空间. 度量空间则通过定义两点之间的距离, 使得经典的 $epsilon$-$delta$ 证明能够推广到一般的空间中. 点集 $X$ 上的*度量*是一个函数 $d : X times X -> RR_(>=0)$, 使得其满足自反性 $d(x,x) = 0$, 对称性 $d(x,y) = d(y,x)$ 与三角不等式 $d(x,y) + d(y,z) >= d(x,z)$. 这样简洁的公理就能支撑许多重要定理的证明, 因此这个概念直到今天都在分析学和拓扑学中有要地位. 接下来 Hausdorff 在 1914 年以邻域的方式定义了拓扑. 他为每个点都赋予了一些集合, 称作这些点的*邻域*. - 每个点都属于它的所有邻域, 并且每个点至少有一个邻域. - 如果 $x$ 有两个邻域 $U, V$, 那么它也有一个包含于 $U sect V$ 的邻域. - 如果点 $y$ 在 $x$ 的邻域 $U$ 中, 那么 $y$ 也有一个包含于 $U$ 的邻域. - (Hausdorff 性质) 两个不同的点有相离的邻域. 这种对邻域的刻画, 相当于今天的拓扑空间中对*邻域基*的刻画. 除此之外, 还有许许多多的试图描述空间的定义, 分别以不同的操作作为基础, 例如 Kuratowski 以闭包为基本概念定义了一种空间, Sierpiński 以导集为基本概念定义了空间, 等等. 这时候, 开集的概念已经为人所知. 1928 年, Sierpiński 撰写了一本书, 其中以开集作为基础概念发展了拓扑学, 并且发现这是一种比较简洁的做法. 这本书讨论了一系列公理, 其中的一个子集就是我们今天熟悉的拓扑空间的定义, 除此之外还有 $T_1, T_2, T_3$ 分离公理与第二可数公理等等. 这也是今天习惯上将它们称作公理而非性质的原因. 最终, Bourbaki (几位数学家组成的学派, 以同一笔名撰写文章) 著书《数学原理》第三卷, 与美国数学家 <NAME> 著《一般拓扑学》, 以开集为基础发展拓扑学. 这些书非常有影响力, 最终奠定了当今的拓扑空间理论基础. 有了这些基础, 于 1930 年代, Whitney 等人为流形给出了严谨的理论发展, 也证明了 Whitney 嵌入定理: 只要 $n$ 足够大, 任何流形都可以嵌入 $RR^n$ 中. 这最终统一了 Poincaré 对流形的几种构造方式, 补充了留下的缺憾.
https://github.com/Mc-Zen/zero
https://raw.githubusercontent.com/Mc-Zen/zero/main/src/rounding.typ
typst
MIT License
#import "assertations.typ": * #let count-leading-zeros(integer-string) = { integer-string.len() - integer-string.trim("0", at: start).len() } /// Rounds an integer given as a string of digits to a given digit place. /// The rounding direction may be `"nearest"`, `"up"`, or `"down"`. #let round-integer(num-string, digit, dir: "nearest") = { if digit == 0 { return "" } if dir == "down" { return num-string.slice(0, digit) } else if dir == "up" { let x = float(num-string.slice(0, digit) + "." + num-string.slice(digit)) num-string = str(int(calc.ceil(x))) } else if dir == "nearest" { let x = float(num-string.slice(0, digit) + "." + num-string.slice(digit)) num-string = str(int(calc.round(x))) } if digit > num-string.len() { num-string = "0" * (digit - num-string.len()) + num-string } return num-string } #assert.eq(round-integer("123", 2, dir: "down"), "12") #assert.eq(round-integer("123", 1, dir: "down"), "1") #assert.eq(round-integer("9989823", 7, dir: "down"), "9989823") #assert.eq(round-integer("123", 0, dir: "down"), "") #assert.eq(round-integer("120", 2, dir: "up"), "12") #assert.eq(round-integer("123", 2, dir: "up"), "13") #assert.eq(round-integer("1200000000002", 2, dir: "up"), "13") #assert.eq(round-integer("999000003", 3, dir: "up"), "1000") #assert.eq(round-integer("2234", 1, dir: "nearest"), "2") #assert.eq(round-integer("2234", 0, dir: "nearest"), "") #assert.eq(round-integer("0022", 3, dir: "nearest"), "002") #assert.eq(round-integer("0395", 3, dir: "nearest"), "040") #assert.eq(round-integer("999", 2, dir: "nearest"), "100") /// Rounds or pads a number given by an integer part and a fractional part /// to a given number of total digits (including the integer digits). The /// rounding direction may be `"nearest"`, `"up"`, or `"down"`. /// The number `total-digits` cannot be negative. If it exceeds the number /// of available digits and `pad` is set to `true`, the number is padded /// with zeros. #let round-or-pad(int, frac, total-digits, dir: "nearest", pad: true) = { total-digits = calc.max(0, total-digits) let number = int + frac if total-digits < number.len() { number = round-integer(number, total-digits, dir: dir) let new-int-digits = int.len() + number.len() - total-digits if total-digits < int.len() { number += "0" * (int.len() - total-digits) } int = number.slice(0, new-int-digits) frac = number.slice(new-int-digits) } else if pad { frac += "0" * (total-digits - number.len()) } return (int, frac) } /// Rounds (or pads) a number given by an integer part and a fractional part. /// Different modes are supported. #let round( /// Integer part. -> str int, /// Fractional part. -> str frac, /// Rounding mode. /// - `"places"`: The number is rounded to the number of places after the /// decimal point given by the `precision` parameter. /// - `"figures"`: The number is rounded to a number of significant figures. /// - `"uncertainty"`: Requires giving the uncertainty. The uncertainty is rounded /// to significant figures given by the `precision` argument and then the number /// is rounded to the same number of places as the uncertainty. mode: none, /// The precision to round to. See parameter `mode` for the different modes. -> int precision: 2, /// Rounding direction. /// - `"nearest"`: Rounding takes place in the usual fashion, rounding to the nearer /// number, e.g., 2.34 -> 2.3 and 2.36 -> 2.4. /// - `"down"`: Always rounds down, e.g., 2.38 -> 2.3, 2.30 -> 2.3. /// - `"up"`: Always rounds up, e.g., 2.32 -> 2.4, 2.30 -> 2.3. /// -> str direction: "nearest", /// Determines whether the number should be padded with zeros if the number has less /// digits than the rounding precision. /// -> boolean pad: true, /// Uncertainty pm: none ) = { if mode == none { return (int, frac, pm) } if mode == "uncertainty" and pm == none { return (int, frac, pm) } assert-option(mode, "round-mode", ("places", "figures", "uncertainty")) assert-option(direction, "round-direction", ("nearest", "up", "down")) let round-digit = precision if mode == "places" { round-digit += int.len() } else if mode == "figures" { let full-number = int + frac let leading-zeros = full-number.len() - full-number.trim("0", at: start).len() round-digit += leading-zeros } if mode == "uncertainty" { let round-digit-pm let is-symmetric = type(pm.first()) != array if is-symmetric { round-digit-pm = count-leading-zeros(pm.join()) + precision pm = round-or-pad(..pm, round-digit-pm, dir: direction, pad: true) round-digit = round-digit-pm + int.len() - pm.first().len() } else { let place = calc.max( ..pm.map(u => count-leading-zeros(u.join()) + precision - u.first().len()) ) round-digit = place + int.len() pm = pm.map(u => round-or-pad(..u, place + u.first().len(), dir: direction, pad: true)) } } return (..round-or-pad(int, frac, round-digit, dir: direction, pad: pad), pm) } #let round-places = round.with(mode: "places") #let round-figures = round.with(mode: "figures") #assert.eq(round("23", "5", mode: none), ("23", "5", none)) #assert.eq(round-places("1", "234", precision: 3), ("1", "234", none)) #assert.eq(round-places("1", "234", precision: 2), ("1", "23", none)) #assert.eq(round-places("1", "234", precision: 1), ("1", "2", none)) #assert.eq(round-places("1", "234", precision: 0), ("1", "", none)) #assert.eq(round-places("23", "534", precision: -1), ("20", "", none)) #assert.eq(round-places("12345", "534", precision: -3), ("12000", "", none)) #assert.eq(round-places("2", "234", precision: -3), ("0", "", none)) #assert.eq(round-places("", "0022", precision: 3), ("", "002", none)) #assert.eq(round-places("1", "1", precision: 0), ("1", "", none)) #assert.eq(round-places("1", "1", precision: 3), ("1", "100", none)) #assert.eq(round-places("1", "1", precision: 5), ("1", "10000", none)) #assert.eq(round-places("1", "1", precision: 5), ("1", "10000", none)) #assert.eq(round-places("1", "1", precision: 5, pad: false), ("1", "1", none)) #assert.eq(round-figures("1", "234", precision: 4), ("1", "234", none)) #assert.eq(round-figures("1", "234", precision: 3), ("1", "23", none)) #assert.eq(round-figures("1", "234", precision: 2), ("1", "2", none)) #assert.eq(round-figures("1", "234", precision: 1), ("1", "", none)) #assert.eq(round-figures("1", "234", precision: 0), ("0", "", none)) #assert.eq(round-figures("1", "234", precision: -1), ("0", "", none)) #assert.eq(round-figures("1", "2", precision: 4), ("1", "200", none)) #assert.eq(round-figures("1", "2", precision: 4, pad: false), ("1", "2", none)) #assert.eq(round-figures("0", "00126", precision: 2), ("0", "0013", none)) #assert.eq(round-figures("0", "000126", precision: 3), ("0", "000126", none)) #assert.eq(round-places("99", "92", precision: 2), ("99", "92", none)) #assert.eq(round-places("99", "92", precision: 0), ("100", "", none)) #assert.eq(round-places("99", "99", precision: 1), ("100", "0", none)) #assert.eq(round-places("99", "99", precision: -1), ("100", "", none)) #assert.eq(round-places("1", "299995", precision: 5), ("1", "30000", none)) #assert.eq(round-places("1", "299994", precision: 5), ("1", "29999", none)) #assert.eq(round-places("523", "", precision: -2), ("500", "", none)) #assert.eq(round("42", "3734", pm: ("", "0025"), precision: 2, mode: "uncertainty"), ("42", "3734", ("", "0025"))) #assert.eq(round("42", "3734", pm: ("", "0025"), precision: 1, mode: "uncertainty"), ("42", "373", ("", "003"))) #assert.eq(round("42", "3734", pm: ("2", "2"), precision: 1, mode: "uncertainty"), ("42", "", ("2", ""))) #assert.eq(round("42", "3734", pm: ("2", "2"), precision: 2, mode: "uncertainty"), ("42", "4", ("2", "2"))) #assert.eq(round("42", "3734", pm: ("2", "2"), precision: 3, mode: "uncertainty"), ("42", "37", ("2", "20"))) #assert.eq(round("4211", "3734", pm: ("230", "2"), precision: 1, mode: "uncertainty"), ("4200", "", ("200", ""))) #assert.eq(round("1", "23", pm: ("0", "2"), precision: 1, mode: "uncertainty"), ("1", "2", ("0", "2"))) #assert.eq(round("123", "9", pm: ("020", ""), precision: 1, mode: "uncertainty"), ("120", "", ("020", ""))) #assert.eq( round("1", "23", pm: (("0", "2"), ("0", "3")), precision: 1, mode: "uncertainty"), ("1", "2", (("0", "2"), ("0", "3"))) ) #assert.eq( round("123", "9", pm: (("020", ""), ("30", "")), precision: 1, mode: "uncertainty"), ("120", "", (("020", ""), ("30", ""))) ) #assert.eq( round("1", "23", pm: (("0", "24"), ("0", "3")), precision: 1, mode: "uncertainty"), ("1", "2", (("0", "2"), ("0", "3"))) ) #assert.eq( round("1", "23", pm: (("0", "04"), ("0", "3")), precision: 1, mode: "uncertainty"), ("1", "23", (("0", "04"), ("0", "30"))) )
https://github.com/mrtz-j/typst-thesis-template
https://raw.githubusercontent.com/mrtz-j/typst-thesis-template/main/modules/abstract.typ
typst
MIT License
#let abstract-page(body) = { pagebreak(weak: true, to: "even") // --- Abstract --- align(left)[ = Abstract #v(1em) #body ] }
https://github.com/qujihan/typst-cv-template
https://raw.githubusercontent.com/qujihan/typst-cv-template/main/README.md
markdown
# Quick Start ```shell # Add this project as a git submodule git submodule add https://github.com/qujihan/typst-cv-template.git typst-cv-template git submodule update --init --recursive # Real-time preview python typst-cv-template/op.py w # Compile python typst-cv-template/op.py c # Format typst code python typst-cv-template/op.py f ```
https://github.com/mkhoatd/Typst-CV-Resume
https://raw.githubusercontent.com/mkhoatd/Typst-CV-Resume/main/CoverLetter/example_Coverletter.typ
typst
MIT License
#import "typstcoverletter.typ": * // Remember to set the fonttype in `typstcv.typ` #show: mainbody => main( name: [#lorem(2)], //name:"" or name:[] address: [#lorem(4)], contacts: ( (text:"08856",link:""), (text:"example.com",link:"https://www.example.com"), (text:"github.com",link:"https://www.github.com"), (text:"<EMAIL>",link:"mailto:<EMAIL>"), ), mainbody, ) #recepient[ #datetime.today(offset: auto).display("[day] [month repr:long] [year]") // display today in the format "day month year" or you can show the date directly ][ Department ][ Institution ][ City, Country ][ Postcode ] #align(left, text(12pt,font: "Helvetica", fill: primary_colour,weight: "medium", )[#upper([Job Application for Research Fellow])]) #v(0.1em) #set text(11pt,font: "Helvetica", fill: primary_colour, weight: "regular", ) Dear Application Committee, #set par(justify: true,first-line-indent: 2em,) #lorem(300) #lorem(100)
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/006%20-%20Magic%202014/003_The%20Path%20of%20Bravery.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Path of Bravery", set_name: "Magic 2014", story_date: datetime(day: 10, month: 07, year: 2013), author: "<NAME>", doc ) They stood in silence. Zaala watched the squire strap and buckle her father's armor onto his body, plate by plate. At some point, she got the sickening feeling he was being covered in a steel sarcophagus, but she drew her mind back. #emph[Focus, Zaala,] she thought. Her father looked like a statue, deep in contemplation. His face was impassive, resolute, and yet the kindness she had known since a child was still there below the surface. It gave her comfort on some deep level to see that; it took her mind off of what awaited them. Then it was her turn. The chainmail weighed on her as the squire strapped on her breastplate, gauntlets, and greaves. They had never felt this heavy before. The squire ministered to her like a cleric solemnly dressing and anointing the dead. She wished he would softly sing like he always did. She noticed his hands shook a bit. #figure(image("003_The Path of Bravery/01.jpg", width: 100%), caption: [Divine Favor | Art by Allen Williams], supplement: none, numbering: none) The squire finished, bowed, and left to bring the horses. Zaala's father turned to face her. "To this point, all your training has been physical. The sword, the lance, the field of combat, all those have trained your body and mind." Zaala's father reached over and took her helm off the oak table and handed it to her, but held it for a moment. "You have freely chosen this path, Zaala. It is the most difficult of all paths to walk and the rewards are not of this world. As your father, there were times where I wanted you to choose otherwise, to seek a less challenging life, but you have opened every door I have set before you. Now is the time for you open the final door to face something that will transform you from a warrior into a knight." #figure(image("003_The Path of Bravery/02.jpg", width: 100%), caption: [Door of Destinies | Art by Larry MacDougall], supplement: none, numbering: none) He released her helm and set his hands on her shoulders. Zaala looked at her father's face; the gravity of the moment made her see things within him she had never seen before, notice details that had escaped her eyes for all these years. As he turned and walked out of the tent, she wondered what he meant. Were they going into battle, to ride against the marauding hordes of Kalgor or Valkas? Yes, it had to be. Finally, it was here. Her final test. She put on her helm and followed him out. "I'm ready father," she called after him. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The stars glittered in the night sky like jewels, and Zaala could hear the crickets as they called to one another in the dark. She could faintly smell the river, figured they must have ridden quite far, and wondered where their destination lay. Then her father spoke. "Zaala, our quest is to slay a dragon." #figure(image("003_The Path of Bravery/03.jpg", width: 100%), caption: [Shivan Dragon | Art by Donato Giancola], supplement: none, numbering: none) Zaala's heart dropped. "A what?" Her father continued. "You have never seen a dragon and there is nothing I can say that can prepare you for it." He stirred the fire of their camp with a stick as he spoke. "It won't be a normal fight. This is not a fight of steel and sinew but of faith and bravery. This fight will mostly take place within you." He stirred the fire again and sparks jumped into the night air. "I thought we were fighting barbarians, or goblin hordes. I am ready for that, but a dragon..." Zaala hoped that everything her father had said about dragons was another test. "The path of bravery is beyond what we are ready for. It is beyond what we think is possible. The path of bravery begins at the impossible. You will never know what power you possess, nor will you know the strength of your bond with those who have trusted you with their lives, until you move beyond the limits of your own self-concern." Zaala listened intently to her father as her heart thudded within her chest like a grain hammer. All she could feel was the cold grip of fear within her as it squeezed the life from her limbs and crushed her confidence. She felt cold. Her father saw Zaala's reaction even in the firelight. "The fear born of self-concern is the gate that you must pass through, Zaala, and the dragon is the gatekeeper. The dragon holds the keys to knowing yourself, to transforming you into a knight. In this way, dragons are bound to us. They are our sacred allies. That is why they have our utmost respect. Without them, we could never attain true knighthood." #figure(image("003_The Path of Bravery/04.jpg", width: 100%), caption: [Scourge of Valkas | Art by Lucas Graciano], supplement: none, numbering: none) "It's the dragon that's been seen near Telfer Peak, isn't it? Is that the one we are going after?" "Yes. And you will lead those who have survived against it." "No, father, please," Zaala pleaded. "This is too important of a quest. I'm not ready." Her father looked at her. "Any fool can wear a suit of armor, pick up a sword, and call herself a knight. By leading, you will learn to use both your head and your heart. A warrior who is all heart is a barbarian. A warrior who is all head is a calculating killer." He tossed the stick in the fire. "To be a knight, you must unite your head and your heart." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("003_The Path of Bravery/05.jpg", width: 100%), caption: [Plains | Art by <NAME>], supplement: none, numbering: none) As they followed the river, <NAME> grew on the horizon and Zaala began to see signs of the dragon's devastation. Villages lay burned to the earth, blackened support beams sticking up from foundations like rotted teeth. Off in the distance, Zaala saw plumes of smoke, each a village that once was. She was horrified at the power of the dragon and imagined in her mind what must have happened as she rode past the charred corpses, some of which still lay huddled together. "They didn't even have a chance." It was meant to be a thought, but Zaala said it out loud. "Think of them when your courage wavers," her father said, as he picked a path through the wreckage. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) At the dawn of the next day, they rode into Valkas and came upon a stone keep scorched by dragon fire. A haggard band of warriors met them at the gate. Zaala could see their spirits return to their eyes at the sight of her father and her. She felt unworthy at the gazes of hope the men and women bestowed upon her and averted her eyes. If they only they knew how unsure she was, how hollow her armor felt at that moment. "<NAME>." A stern, gray-bearded warrior built like a barrel addressed her father. "It is good to see you both. We gathered as many of us as we could." Zaala looked around. There couldn't be more than thirty warriors. Her father spoke to the band. "Zaala will lead us to fight this dragon. She has prepared her whole life for such a task." #figure(image("003_The Path of Bravery/06.jpg", width: 100%), caption: [Dawnstrike Paladin | Art by <NAME>], supplement: none, numbering: none) Zaala felt the attention shift to her. As her heart pounded she slowly reached up and took off her helm, pulled off her gauntlets, and ran her fingers through her short-cropped hair. The breeze felt good against her scalp. "There are things in this world that seek only to destroy. They can never be satisfied. They are a reflection of what is inside of us—greed, malice, fear. I have seen it all my life, on this journey, and even within myself." Zaala could feel something arise within her, an aliveness like she had never felt before. "But in this moment, I realize something. I realize that in spite of these challenges I am an unshakable stand. I know and I have always known that my life is a commitment to free our world from suffering. To my last breath I vow to defeat evil wherever it lurks. I vow to never stop creating a world in which good can flower and grow." She looked at the faces that surrounded her. "I cannot do this alone. I need all of you to make this possible. Will you do me the honor of fighting alongside me?" There was a resounding cheer. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) They marched through the night and, at dawn, Zaala and her father rode out onto the charred wasteland of the dragon's domain. The small band of warriors stood behind them, their weapons at the ready. Zaala could hear the dragon's wing beats far overhead. It knew they were there and they could feel its wrath. "I'll be right at your side," Zaala's father said. The dragon's silhouette could be seen as it descended, larger and larger through the yellowish smoke, with great gouts of flame spraying from its jaws that illuminated the sky like lightning in a thunderstorm. Zaala raised her lance as the band of warriors chanted a war song passed down from generation to generation. They sang with all their hearts to drown out the fear that arose within them as the dragon loomed larger. Zaala urged her horse forward and she focused only on the dragon as the war song, her heartbeat, and the hoof beats of her horse became one pulsing rhythm. Zaala's horse broke into a gallop as the dragon came through the haze. Immense, terrifying, impossible to defeat. #figure(image("003_The Path of Bravery/07.jpg", width: 100%), caption: [Path to Bravery | Art by <NAME>], supplement: none, numbering: none) Zaala dug in her spurs and lowered her lance. She felt a spiritual energy run through her body as she came within a few jousting lengths of the dragon. She didn't even notice the white mist as it began to form all over her. Her lance had burst into white fire. As if forced by an invisible hand, the dragon was pulled from the sky onto the ground and the earth shook with its weight. As Zaala charged in, the dragon unleashed a plume of blazing fire that engulfed Zaala and her horse. For a moment her only awareness was the war song as it filled every nerve and fiber of her being. A path of light stretched before her. Even within the dragon fire, its light was a brilliance of a higher order. Suddenly, her lance plunged deep into the dragon's heart and she was on her back, looking up at the dragon above her as it sprayed fire and blood. She could make out the band of warriors as they swarmed over its writhing body, their swords and spears stabbing at it as it collapsed in a thunder of flesh and scales. The exhausted band stood around her as her father helped her to her feet. "Well done, Daughter," <NAME> said, as she stood before him. "Well done, indeed." #figure(image("003_The Path of Bravery/08.png", height: 40%), caption: [], supplement: none, numbering: none)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/pad_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Use for indentation. #pad(left: 10pt, [Indented!]) // All sides together. #set rect(inset: 0pt) #rect(fill: conifer, pad(10pt, right: 20pt, rect(width: 20pt, height: 20pt, fill: rgb("eb5278")) ) ) Hi #box(pad(left: 10pt)[A]) there
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-11BC0.typ
typst
Apache License 2.0
#let data = ( ("SUNUWAR LETTER DEVI", "Lo", 0), ("SUNUWAR LETTER TASLA", "Lo", 0), ("SUNUWAR LETTER EKO", "Lo", 0), ("SUNUWAR LETTER IMAR", "Lo", 0), ("SUNUWAR LETTER REU", "Lo", 0), ("SUNUWAR LETTER UTTHI", "Lo", 0), ("SUNUWAR LETTER KIK", "Lo", 0), ("SUNUWAR LETTER MA", "Lo", 0), ("SUNUWAR LETTER APPHO", "Lo", 0), ("SUNUWAR LETTER PIP", "Lo", 0), ("SUNUWAR LETTER GIL", "Lo", 0), ("SUNUWAR LETTER HAMSO", "Lo", 0), ("SUNUWAR LETTER CARMI", "Lo", 0), ("SUNUWAR LETTER NAH", "Lo", 0), ("SUNUWAR LETTER BUR", "Lo", 0), ("SUNUWAR LETTER JYAH", "Lo", 0), ("SUNUWAR LETTER LOACHA", "Lo", 0), ("SUNUWAR LETTER OTTHI", "Lo", 0), ("SUNUWAR LETTER SHYELE", "Lo", 0), ("SUNUWAR LETTER VARCA", "Lo", 0), ("SUNUWAR LETTER YAT", "Lo", 0), ("SUNUWAR LETTER AVA", "Lo", 0), ("SUNUWAR LETTER AAL", "Lo", 0), ("SUNUWAR LETTER DONGA", "Lo", 0), ("SUNUWAR LETTER THARI", "Lo", 0), ("SUNUWAR LETTER PHAR", "Lo", 0), ("SUNUWAR LETTER NGAR", "Lo", 0), ("SUNUWAR LETTER KHA", "Lo", 0), ("SUNUWAR LETTER SHYER", "Lo", 0), ("SUNUWAR LETTER CHELAP", "Lo", 0), ("SUNUWAR LETTER TENTU", "Lo", 0), ("SUNUWAR LETTER THELE", "Lo", 0), ("SUNUWAR LETTER KLOKO", "Lo", 0), ("SUNUWAR SIGN PVO", "Po", 0), (), (), (), (), (), (), (), (), (), (), (), (), (), (), ("SUNUWAR DIGIT ZERO", "Nd", 0), ("SUNUWAR DIGIT ONE", "Nd", 0), ("SUNUWAR DIGIT TWO", "Nd", 0), ("SUNUWAR DIGIT THREE", "Nd", 0), ("SUNUWAR DIGIT FOUR", "Nd", 0), ("SUNUWAR DIGIT FIVE", "Nd", 0), ("SUNUWAR DIGIT SIX", "Nd", 0), ("SUNUWAR DIGIT SEVEN", "Nd", 0), ("SUNUWAR DIGIT EIGHT", "Nd", 0), ("SUNUWAR DIGIT NINE", "Nd", 0), )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/ascii-ipa/1.0.0/test.typ
typst
Apache License 2.0
#import("lib.typ"): * #let run-tests = (tests, translator, name) => { for test in tests { assert( translator(test.at(0)) == test.at(1), message: name + ": " + test.at(0) + " -> " + test.at(1) ) assert( translator(test.at(1), reverse: true) == test.at(0), message: name + " " + test.at(1) + " -> " + test.at(0) ) } } #let xsampa-tests = ( ("Ii:Uu:O:eE:@3:Q{VA:", "ɪiːʊuːɔːeɛːəɜːɒæʌɑː"), ("mnN", "mnŋ"), ("pttSkbddZg", "pttʃkbddʒɡ"), ("fTsSxvDzZh", "fθsʃxvðzʒh"), ("lrjw", "lrjw"), ("i1ueoa", "iɨueoa"), ("mm_jnn_j", "mmʲnnʲ"), ("pp_jtt_jkk_jbb_jdd_jgg_j", "ppʲttʲkkʲbbʲddʲɡɡʲ"), ("tsts_jts\\", "tstsʲtɕ"), ("ff_jss_js`s\\:xx_jvv_jzz_jz`z\\:G", "ffʲssʲʂɕːxxʲvvʲzzʲʐʑːɣ"), ("5l_jj", "ɫlʲj"), ("r_jr", "rʲr"), ("iui:u:aa:awaj", "iuiːuːaaːawaj"), ("ptt_?\\kq?bdd_?\\dZg", "pttˤkqʔbddˤdʒɡ"), ("fTss_?\\SxXX\\hvDzD_?\\z_?\\GR?\\", "fθssˤʃxχħhvðzðˤzˤɣʁʕ"), ("mn", "mn"), ("r", "r"), ("l5jw", "lɫjw"), ) #let praat-tests = ( ("\\ici\\:f\\hsu\\:f\\ct\\:fe\\ef\\:f\\sw", "ɪiːʊuːɔːeɛːə"), ("\\er\\:f\\ab\\ae\\vt\\as\\:f", "ɜːɒæʌɑː"), ("mn\\ng", "mnŋ"), ("ptt\\shkbdd\\zh\\gs", "pttʃkbddʒɡ"), ("f\\tfs\\shxv\\dhz\\zhh", "fθsʃxvðzʒh"), ("lrjw", "lrjw"), ("i\\i-ueoa", "iɨueoa"), ("mm\\^jnn\\^j", "mmʲnnʲ"), ("pp\\^jtt\\^jkk\\^jbb\\^jdd\\^j\\gs\\gs\\^j", "ppʲttʲkkʲbbʲddʲɡɡʲ"), ("tsts\\^jt\\cc", "tstsʲtɕ"), ("ff\\^jss\\^j\\s.\\cc\\:fxx\\^jvv\\^j", "ffʲssʲʂɕːxxʲvvʲ"), ("zz\\^j\\z.\\zc\\:f\\gf", "zzʲʐʑːɣ"), ("\\l~l\\^jj", "ɫlʲj"), ("r\\^jr", "rʲr"), ("iui\\:fu\\:faa\\:fawaj", "iuiːuːaaːawaj"), ("ptt\\^9kq\\?gbdd\\^9d\\zh\\gs", "pttˁkqʔbddˁdʒɡ"), ("f\\tfss\\^9\\shx\\cf\\h-hv\\dh", "fθssˁʃxχħhvð"), ("z\\dh\\^9z\\^9\\gf\\ri\\9e", "zðˁzˁɣʁʕ"), ("mn", "mn"), ("r", "r"), ("l\\l~jw", "lɫjw"), ) #let branner-tests = ( ("Ii:Uu:c&:eE:@E&:a\"&ae)v&a\":", "ɪiːʊuːɔːeɛːəɜːɒæʌɑː"), ("mnng)", "mnŋ"), ("pttSkbdd3\"g", "pttʃkbddʒɡ"), ("fO-sSxvd-z3\"h", "fθsʃxvðzʒh"), ("lrjw", "lrjw"), ("ii-ueoa", "iɨueoa"), ("mmj^nnj^", "mmʲnnʲ"), ("ppj^ttj^kkj^bbj^ddj^ggj^", "ppʲttʲkkʲbbʲddʲɡɡʲ"), ("tstsj^tci)", "tstsʲtɕ"), ("ffj^ssj^sr)ci):xxj^vvj^zzj^zr)zi):g\"", "ffʲssʲʂɕːxxʲvvʲzzʲʐʑːɣ"), ("l~)lj^j", "ɫlʲj"), ("rj^r", "rʲr"), ("iui:u:aa:awaj", "iuiːuːaaːawaj"), ("ptt&g^kq?bdd&g^d3\"g", "pttˤkqʔbddˤdʒɡ"), ("fO-ss&g^SxXh-hvd-zd-&g^z&g^g\"R%?&", "fθssˤʃxχħhvðzðˤzˤɣʁʕ"), ("mn", "mn"), ("r", "r"), ("ll~)jw", "lɫjw"), ) #let sil-tests = ( ("i=i:u<u:o<:ee<:e=e>:o=a<u>a=:", "ɪiːʊuːɔːeɛːəɜːɒæʌɑː"), ("mnn>", "mnŋ"), ("ptts=kbddz=g<", "pttʃkbddʒɡ"), ("ft=ss=xvd=zz=h", "fθsʃxvðzʒh"), ("lrjw", "lrjw"), ("iI=ueoa", "iɨueoa"), ("mmj^nnj^", "mmʲnnʲ"), ("ppj^ttj^kkj^bbj^ddj^g<g<j^", "ppʲttʲkkʲbbʲddʲɡɡʲ"), ("tstsj^tc<", "tstsʲtɕ"), ("ffj^ssj^s<c<:xxj^vvj^zzj^z<z>:g=", "ffʲssʲʂɕːxxʲvvʲzzʲʐʑːɣ"), ("l~~lj^j", "ɫlʲj"), ("rj^r", "rʲr"), ("iui:u:aa:awaj", "iuiːuːaaːawaj"), ("ptt?<^kq?=bdd?<^dz=g<", "pttˤkqʔbddˤdʒɡ"), ("ft=ss?<^s=xx=h>hvd=zd=?<^z?<^g=R>?<", "fθssˤʃxχħhvðzðˤzˤɣʁʕ"), ("mn", "mn"), ("r", "r"), ("ll~~jw", "lɫjw"), ) #run-tests(branner-tests, branner, "Branner") #run-tests(praat-tests, praat, "Praat") #run-tests(sil-tests, sil, "SIL") #run-tests(xsampa-tests, xsampa, "X-SAMPA")
https://github.com/MultisampledNight/flow
https://raw.githubusercontent.com/MultisampledNight/flow/main/src/lib.typ
typst
MIT License
// Feel free to import this file's contents via a glob! // See `doc/manual.typ` for an example of how usage in practise looks like! #import "callout.typ": question, remark, hint, caution #import "cfg.typ" #import "checkbox.typ" #import "gfx.typ" as gfx: invert, fxfirst #import "info.typ" #import "keywords.typ" #import "palette.typ": * #import "presentation.typ" #import "track.typ" #import "tyck.typ" #import "util.typ": * #import "template.typ" as template: note
https://github.com/philipsd6/typst-yearly-planner
https://raw.githubusercontent.com/philipsd6/typst-yearly-planner/main/README.md
markdown
MIT License
# Typst Remarkable Calendar Inspired by https://github.com/kudrykv/latex-yearly-planner
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/construct-11.typ
typst
Other
#assert(range(2, 5) == (2, 3, 4))
https://github.com/s1syph0s/cv
https://raw.githubusercontent.com/s1syph0s/cv/main/template.typ
typst
#import "imprecv/cv.typ": * #let cvdata = yaml("template.yml") #let uservars = ( headingfont: "Linux Libertine", bodyfont: "Linux Libertine", fontsize: 10pt, // 10pt, 11pt, 12pt linespacing: 6pt, sectionspacing: 0pt, showAddress: true, // true/false show address in contact info showNumber: true, // true/false show phone number in contact info showTitle: true, // true/false show title in heading headingsmallcaps: false, // true/false use small caps for headings sendnote: false, // set to false to have sideways endnote ) // setrules and showrules can be overridden by re-declaring it here // #let setrules(doc) = { // // add custom document style rules here // // doc // } #let customrules(doc) = { // add custom document style rules here set page( paper: "us-letter", // a4, us-letter numbering: "1 / 1", number-align: center, // left, center, right margin: 1.25cm, // 1.25cm, 1.87cm, 2.5cm ) doc } #let cvinit(doc) = { doc = setrules(uservars, doc) doc = showrules(uservars, doc) doc = customrules(doc) doc } // each section body can be overridden by re-declaring it here // #let cveducation = [] // ========================================================================== // #show: doc => cvinit(doc) #cvheading(cvdata, uservars) #cvwork(cvdata) #cveducation(cvdata) #cvaffiliations(cvdata) #cvskills(cvdata) #cvawards(cvdata) #cvcertificates(cvdata) #cvpublications(cvdata) #cvprojects(cvdata) #cvreferences(cvdata) #endnote(uservars)
https://github.com/MasiarNovine/typst_resume_template
https://raw.githubusercontent.com/MasiarNovine/typst_resume_template/main/template.typ
typst
MIT License
#let template(fontsize: 11pt, fonttype: "Fira Sans", doc ) = { set page( paper: "a4", margin: (left: 2.5cm, right: 2.5cm, top: 2cm, bottom: 3cm), number-align: center, numbering: "1", footer: context [ #counter(page).display("1/1", both: true) ] ) set par(justify: true) set text(font: fonttype, size: fontsize, weight: "light") show heading.where(level: 1): it => block(width: 100%)[ #grid( columns: (0.35fr, 1fr), gutter: 15pt, [#align(horizon, line(length: 100%, stroke: 4pt + white.lighten(10%)))], [ #set align(left) #set text(14pt, weight: "regular", fill: eastern.lighten(10%)) #smallcaps(it.body) ] ) #v(10pt) ] columns(1, doc) } #let iconbox(field: none, icon: none, sep: none) = { box(height: 10pt, image(icon), baseline: 20%) + " " + field + sep } #let headerblock(foto: none, firstname: none, lastname: none, address: none, phone: (field: none, icon: none), email: (field: none, icon: none), github: (field: none, icon: none), orcid: (field: none, icon: none), linkedin: none ) = { v(-40pt) block( fill: gradient.linear(eastern.lighten(20%), olive.lighten(60%)), outset: (x: 100pt, y: 20pt), [ #grid( columns: (0.35fr, 1.2fr), // First column align(left + top)[ #box(image(foto, width: 100%), radius: 100%, clip: true) ], // Second column [ #align(right + horizon)[ #text(size: 42pt, fill: white, weight: 300)[#firstname ] #text(size: 42pt, fill: white, weight: 400)[#lastname]\ #v(6pt) #text(size: 10pt, fill: white, weight: 400)[#address]\ #text(size: 10pt, fill: white, weight: 400)[ #iconbox( field: phone.field, icon: phone.icon, sep: " | " ) ] #text(size: 10pt, fill: white, weight: 400)[ #iconbox( field: email.field, icon: email.icon, ) ] #text(size: 10pt, fill: white, weight: 400)[ #iconbox( field: github.field, icon: github.icon, sep: " | " ) ]\ #text(size: 10pt, fill: white, weight: 400)[ #iconbox( field: orcid.field, icon: orcid.icon ) ] ] ] ) ] ) v(22pt) } #let cventry(year: "", title: "", institution: "", city: "", country: "", optional: none, description: none, descriptionlabel: "Description" ) = { grid( columns: (0.35fr, 1fr), gutter: 15pt, align(right + top)[#year], align(left + bottom)[ #text(title, weight: "regular"), #text(institution, style: "italic"), #city, #if (optional != none) { [#country, ] [#optional] } else { [#country#linebreak()] } #if (description != none) { [#text([#descriptionlabel: ], size: 10pt, style: "italic") #text(description, size: 10pt)] } ] ) } #let cvitem(key: "", value: "", ) = { grid( columns: (0.35fr, 1fr), gutter: 15pt, align(right + top)[#key], align(left + bottom)[#value] ) }
https://github.com/piepert/typst-hro-iph-seminar-paper
https://raw.githubusercontent.com/piepert/typst-hro-iph-seminar-paper/main/example1/example1.typ
typst
#import "@local/hro-iph-seminar-paper:0.1.0": seminar-paper // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: seminar-paper.with( title: "Abhandlung über das Schreiben einer Hausarbeit", authors: ( "<NAME>", ), date: datetime.today(), faculty: "Fakultät für Exemplarität", institute: "Institut für Beispielarbeit", docent: "Prof. Dr. rer. nat. <NAME>professor", course: "Seminar Angewandte Exemplarwissenschaft", matnr: "0123456789", address: [Musterweg 28, \ Musterstadt 12345], mail: "<EMAIL>" ) = Einleitung und Motivation #lorem(200) = Hauptteil #lorem(300) == Herkunft des Lorem Ipsum #lorem(300) #lorem(200) #lorem(400) == Verwendung des Lorem Ipsum #lorem(300) #lorem(100) #lorem(200) = Schluss #lorem(300)
https://github.com/cetz-package/cetz-venn
https://raw.githubusercontent.com/cetz-package/cetz-venn/master/tests/venn2/test.typ
typst
Apache License 2.0
#set page(width: auto, height: auto) #import "/src/lib.typ": venn2 #import "/tests/helper.typ": * #import cetz.draw: content, set-style #test-case({ venn2(name: "v") content("v.a", [A]) content("v.b", [B]) content("v.ab", [AB]) content("v.not-ab", [not AB], anchor: "south-west") }) #test-case({ venn2(a-fill: red) }) #test-case({ venn2(b-fill: red) }) #test-case({ venn2(ab-fill: red) }) #test-case({ venn2(not-ab-fill: red) }) #test-case({ set-style(venn: (stroke: blue, fill: gray, padding: (top: 1, bottom: .5, rest: .25))) venn2(name: "v", a-stroke: black, b-fill: green) })
https://github.com/pluttan/os
https://raw.githubusercontent.com/pluttan/os/main/lab1/lab1.typ
typst
#import "@docs/bmstu:1.0.0":* #import "@preview/tablex:0.0.8": tablex, rowspanx, colspanx, cellx #show: student_work.with( caf_name: "Компьютерные системы и сети", faculty_name: "Информатика и системы управления", work_type: "лабораторной работе", work_num: 1, study_field: "09.03.01 Информатика и вычислительная техника", discipline_name: "Операционные системы", theme: "Исследование установки ОС Linux", author: (group: "ИУ6-52Б", nwa: "<NAME>"), adviser: (nwa: "<NAME>"), city: "Москва", table_of_contents: true, ) = Введение == Цель работы Цель работы - исследование процесса установки Linux на примере дистрибутива Debian на виртуальную машину. == Задание Согласно данному пособию: - Создать виртуальную машину - Установить на неё ОС Debian Включить в отчёт: - Основные этапы установки - Соответствующие им снимки экрана с заданными вами параметрами - Снимок экрана с таблицей разделов. = Выполнение лабораторной работы == Установка программы виртуализации Чтобы не повредить данные на реальном компьютере будем тренироваться на виртуальном. Для этого надо установить программу виртуализации. Для macbook на arm чипах хорошо подойдет `parallels desktop`. Скачиваем и устанавливаем эту программу. == Поиск и загрузка образа Далее необходим образ. Раньше операционки продавались в магазинах и поэтому концепция реального накопителя с отдельной ненастроенной операционной системой в рамках распространения ОС довольно популярна. Сейчас при установки ОС необходимо сбросить образ на отдельную флеш-карту, а после перезагрузить компьютер. Причем в настройках загрузки необходимо указать, что компьютер должен грузить операционную систему именно с этой флешки. Так как операционную систему мы будем устанавиливать виртуально, то программа `parallels desktop` сама создаст подобный загрузочный накопитель, и предложит нам пройти первичную установку, сделанную производителем ОС. Образ же возьмем с зеркала официального сайта (с первой страницы по запросу `debian-testing-arm64-netinst.iso download`). == Установка Итак, после загрузки образа перетаскиваем его в меню `parallels desktop` и начинаем установку ОС. Для удобства ее будем выполнять в графическом режиме. === Общее #img(image("img/1.png", width:90%), [Выбираем графическую установку]) Выберем русский язык, российскую федерацию и русскую раскладку. #img(image("img/2.png", width:90%), [Выбираем язык]) #img(image("img/3.png", width:90%), [Выбираем страну]) #img(image("img/4.png", width:90%), [Выбираем раскладку клавиатуры]) Переключение оставим по умолчанию. #img(image("img/5.png", width:90%), [Выбираем переключение раскладки клавиатуры]) В качестве имени компьютера зададим мою фамилию -- plutto. #img(image("img/6.png", width:90%), [Задаем имя компьютера]) Домен задавать не будем, оставим это поле пустым. #img(image("img/7.png", width:90%), [Пустое поле для домена]) Далее установщик предлагает ввести пароль суперпользователя «root». Суперпользователь в linux имеет права абсолютно на любую операцию в системе, поэтому рекомендуется задать ему сложный пароль и использовать как можно реже, но поскольку в наших лабораторных работах для подавляющего большинства операций требуются права суперпользователя, а лабораторная работа, в которой мы будем изучать права доступа имеет номер «6», нарушим все правила и будем работать от имени пользователя «root». В качестве пароля зададим один символ -- пробел. #img(image("img/8.png", width:90%), [Пароль root]) Далее установщик предлагает ввести имя простого пользователя. Для лабораторных работ зададим «user». #img(image("img/9.png", width:90%), [Имя пользователя]) Пароль так же зададим пробелом. #img(image("img/10.png", width:90%), [Пароль user]) Выберем часовой пояс +3 и перейдем к разметке диска. === Разметка диска В первом окне выберем пункт «Авто — использовать весь диск». #img(image("img/11.png", width:90%), [Использование диска]) После выбора возникает плашка о том, что все данные будут стерты при форматировании. ОС не знает что эмулируется, поэтому предупреждает об этом, но `parallels desktop` специалььно выделил для ОС только свободное место на диске, ан котором машина устанавливалась, поэтому она ничего не затрет при форматировании. #img(image("img/13.png", width:90%), [Предупреждение о форматировании и выбор раздела]) Далее установщик предлагает варианты разметки диска - В варианте «Отдельный раздел для /home» будут созданы системный раздел и раздел для данных пользователей. Недостатком такой разметки является то, что в будущем может не хватить выделенного места для установки новых программ в системный раздел. - Для лабораторной будет достаточно хранения «Все файлы в одном разделе» #img(image("img/14.png", width:90%), [Выбор сохранять ли все в один раздел диска]) После нас попросят подтвердить все ли правильно мы настроили. Перепроверяем и запускаем разметку. #img(image("img/16.png", width:90%), [Проверка]) #img(image("img/17.png", width:90%), [Предуплеждение о том что раздел будет отформатирован]) === Менеджер пакетов По окончании разметки нам предложат настроить менеджер пакетов эта утилита позвояет устанавливать скомпилированные проекты с открытым или закрытым кодом, как пакеты. Так же такие пакеты можно установить с внешних носителей, но у нас таких нет, поэтому в соответствующем окне выбираем нет. #img(image("img/18.png", width:90%), [Выбор о сканировании внешних носителей]) Далее нам предложат выбрать зеркало по стране. Выбираем зеркало наиболее близкое к нам (т.е. из РФ). Так пакеты будут скачиваться быстрее. Само зеркало выберем по умолчанию -- `deb.debian.org`. #img(image("img/19.png", width:90%), [Выбор зеркала]) #img(image("img/20.png", width:90%), [Выбор зеркала]) Прокси задавать не будем. Так же оставим пустым. #img(image("img/21.png", width:90%), [Прокси оставляем пустым]) Учавствовать в опросе популярности пакетов не будем. #img(image("img/22.png", width:90%), [Не учавствуем в опросе популярности пакетов]) Из утилит необходимо выбрать только стандартные, все остальное из необходимого будет установлено позже нами при помощи пакетного менеджера. #img(image("img/24.png", width:90%), [Только стандартные утилиты]) Псоле уставновим системный загрузчик. Просто выбираем раздел и он сам установится. На этом установка завершена. == Подключение пользователя и проверка разделов После загрузки системы нам предложат ввести логин и пароль. Как и было описано ранее, хотя так делать не рекомендуется дальнейшие действия будем производить под пользователем root. #img(image("img/26.png", width:90%), [Вошли в систему под root'ом]) При помощи комманды ```sh fdisk -l``` проверим разметку диска: #img(image("img/28.png", width:90%), [Разметка диска]) Как видно тут есть раздел загрузщика, основной раздел и раздел, предназначенный для swap-данных -- временных малоиспользуемых данных, которые не помещаются в оперативную память. Завершим работу при помощи комманды ```sh shutdown –h now```. #img(image("img/29.png", width:90%), [Завершение работы])
https://github.com/mem-courses/linear-algebra
https://raw.githubusercontent.com/mem-courses/linear-algebra/main/note/4.矩阵的迹和秩.typ
typst
#import "../template.typ": * #show: project.with( title: "Linear Algebra #4", authors: ( (name: "<NAME>", email: "<EMAIL>", phone: "3230104585"), ), date: "November 13, 2023", ) #let AA = math.bold("A") #let BB = math.bold("B") #let CC = math.bold("C") #let DD = math.bold("D") #let EE = math.bold("E") #let XX = math.bold("X") #let II = math.bold("I") #let OO = math.bold("O") #let TT = math.upright("T") #let alpha = math.bold(math.alpha) #let beta = math.bold(math.beta) #let theta = math.bold(math.theta) = 矩阵的迹 矩阵 $AA$ 的主对角线的所有元素之和称为矩阵的迹,记为 $tr(bold(AA))$。 = 矩阵的秩 矩阵 $AA$ 的不等于 $0$ 的子式的最大阶数称为矩阵的秩,记为 $r(AA)$. == 矩阵的相抵(等价) 设 $AA,BB in PP^(m times n)$,如果 $AA$ 经过一系列初等变换化为 $BB$,即存在可逆矩阵 $bold(P),bold(Q)$ 使得 $bold(P) AA bold(Q) = BB$,则称 $AA$ 与 $BB$ *相抵*(*等价*). == 矩阵的相抵(等价)标准形 设 $r(bold(A_(m times n)))=r$,则 $AA$ 与 $display(mat(bold(E_r),bold(O);bold(O),bold(O)))$ 相抵(等价),将其称为 $AA$ 的 *相抵(等价)标准形*. == 基本性质 #def[性质1] $r(AA_(m times n)) <= min{m,n}$ #def[性质2] (1) $AA_(m times n)$ 中存在一个 $k$ 阶子式不等于 $0$ $=>$ $r(AA_(m times n))>=k$;\ #deft[性质2] (2) $AA_(m times n)$ 中所有 $k+1$ 阶子式都等于 $0$ $=>$ $r(AA_(m times n))<=k$. #def[性质3] 当 $AA$ 为 $n$ 阶方阵时:\ #deft[性质3] $|AA|!=0 <=> r(AA_(n times n))=n$(称 $AA$ 为满秩矩阵 / 非奇异矩阵)\ #deft[性质3] $|AA|=0 <=> r(AA_(n times n))<n$(称 $AA$ 为降秩矩阵 / 奇异矩阵) #def[性质4] $r(AA_(m times n))=k <=>$ $AA$ 中至少存在一个 $k$ 阶子式不为 $0$ 且 $AA$ 中所有 $k+1$ 阶子式均为 $0$. #def[性质5] 矩阵的初等变换不改变矩阵的秩. #def[性质6] 矩阵增加一行或一列,矩阵的秩不变或增加 $1$. #def[性质2]当 $bold(P),bold(Q)$ 可逆时,$r(AA) = r(bold(P A)) = r(bold(A Q)) = r(bold(P A Q))$. #def[性质3]$r(AA BB) <= min{r(AA),r(BB)}$. #prof[ #def[证明](充分利用相抵标准型)先证 $r(AA_(m times s) BB_(s times n)) <= r(AA)$.设 $r(AA) = r$,则有可逆矩阵 $bold(P)_(m times m), bold(Q)_(s times s)$,使得 $AA = bold(P) display(mat(EE_r, OO;OO, OO))bold(Q)$. 所以 $r(AA BB) = r(bold(P) display(mat(EE_r, OO;OO, OO)) bold(Q) BB) = r(display(mat(EE_r, OO;OO, OO)) bold((Q B))_(s times n))$, 设 $bold(Q B) = display(mat(CC_(r times n);bold(H)_((s-r)times n)))$,那么 $display(mat(EE_r, OO;OO, OO)) display(mat(CC_(r times n);bold(H)_((s-r)times n))) = display(mat(CC_(r times n)))$. 所以 $r(AA BB) <= r = r(AA)$,同时 $r(AA BB) = r(AA BB)^TT = r(BB^TT AA^TT) <= r(BB^TT) = r(BB)$.故命题得证. ] #def[性质4]设 $bold(G) = display(mat(AA_(M times n),OO;OO,BB_(s times t)))$(或 $bold(G) = display(mat(OO,AA_(m times n);BB_(s times t),OO))$)则 $r(bold(G)) = r(AA) + r(BB)$. #prof[ #def[证明]由已知,存在可逆矩阵 $bold(P)_i,bold(Q)_i sp (i,j=1,2)$ 使 $AA=bold(P)_1 display(mat(EE_r,OO;OO,OO)) bold(Q)_1,sp BB=bold(P)_2 display(mat(EE_s,OO;OO,OO)) bold(Q)_2$. 则有:$bold(P G Q) = display(mat(bold(P)_1^(-1),OO;OO,bold(P)_2^(-1))) display(mat(AA,OO;OO,BB)) display(mat(bold(Q)_1^(-1),OO;OO,bold(Q)_2^(-1))) = display(mat(bold(P)_1^(-1) AA bold(Q)_1^(-1),OO; OO,bold(P)_2^(-1) BB bold(Q)_2^(-1))) = display(mat(EE_r,OO,OO,OO;OO,OO,OO,OO;OO,OO,EE_s,OO;OO,OO,OO,OO))$. 所以 $r(bold(G)) = r(AA) + r(BB)$. ] #def[性质5]设 $AA,BB in PP^(m times n)$,则 $r(AA) - r(BB) <= r(AA+BB) <= r(AA) + r(BB)$. #prof[ #def[证明(一)]利用相抵标准型. 设 $r(AA) = r$,则有可逆矩阵 $bold(P),bold(Q)$ 使得 $bold(P A Q) = display(mat(EE_r,OO;OO,OO))$. 因为 $r(bold(P A B)) = r(bold(A B))$.考察: $ bold(P A B) &= (bold(P A Q))(bold(Q)^(-1) BB) = display(mat(EE_r,OO;OO,OO))_(s times n) (bold(Q)^(-1) BB)_(n times m)\ &= display(mat(EE_r,OO;OO,OO)) display(mat(CC_(r times m);bold(F)_((n-r) times m))) = display(mat(CC_(r times m);OO)) $ 所以 $r(bold(A B)) = r(bold(P A B)) = r(CC)$.又, $ r(BB) &= r(bold(Q)^(-1) BB) = r mat(CC;bold(F)) <= r mat(CC,OO;bold(F),bold(F)) = r mat(CC,OO;OO,bold(F))\ &= r(CC) + r(bold(F)) <= r(AA BB) + n - r = r(AA BB) + n - r(AA) $ 即可得到 Sylvester 不等式. ] #prof[ #def[证明(二)]利用分块矩阵作初等变换. $ mat(EE_n,;,AA BB) -> mat(EE_n,;AA,AA BB) -> mat(EE_n,-BB;AA,) -> mat(EE_n,BB;AA,) $ 考虑: $ r(AA BB) + n = r mat(EE_n,;,AA BB) = r mat(EE_n,BB;AA,) >= r mat(,BB;AA,) = r(AA) + r(BB) $ ] #def[性质7](Frobenius不等式)设 $AA in PP^(m times n),sp BB in PP^(n times t),sp CC in PP^(t times s)$,则 $ r(AA BB CC) >= r(AA BB) + r(BB CC) - r(BB) $
https://github.com/donRumata03/aim-report
https://raw.githubusercontent.com/donRumata03/aim-report/master/lib/split-box.typ
typst
#let counter-family(id) = { let parent = counter(id) let parent-step() = parent.step() let get-child() = counter(id + str(parent.get().at(0))) return (parent-step, get-child) } #let default-border = ( // The starting and ending lines above: line(length: 100%), below: line(length: 100%), // Lines to put between the box over multiple pages btwn-above: line(length: 100%, stroke: (dash:"dotted")), btwn-below: line(length: 100%, stroke: (dash:"dotted")), // Left/right lines // These *must* use `grid.vline()`, otherwise you will get an error. // To remove the lines, set them to: `grid.vline(stroke: none)`. // You could probably configure this better with a rowspan, but I'm lazy. left: grid.vline(), right: grid.vline(), ) // Create a box for content which spans multiple pages/columns and // has custom borders above and below the column-break. #let split-box( // Set the border dictionary, see `default-border` above for options border: default-border, // The cell to place content in, this should resolve to a `grid.cell` cell: grid.cell.with(inset: 5pt), // The last positional arg or args are your actual content // Any extra named args will be sent to the underlying grid when called // This is useful for fill, align, etc. ..args ) = { // See `utils.typ` for more info. let (parent-step, get-child) = counter-family("split-box-unique-counter-string") parent-step() // Place the parent counter once. // Keep track of each time the header is placed on a page. // Then check if we're at the first placement (for header) or the last (footer) // If not, we'll use the 'between' forms of the border lines. let border-above = context { let header-count = get-child() header-count.step() context if header-count.get() == (1,) { border.above } else { border.btwn-above } } let border-below = context { let header-count = get-child() if header-count.get() == header-count.final() { border.below } else { border.btwn-below } } // Place the grid! grid( ..args.named(), columns: 3, border.left, grid.header(border-above , repeat: true), ..args.pos().map(cell), grid.footer(border-below, repeat: true), border.right, ) }
https://github.com/jrihon/multi-bibs
https://raw.githubusercontent.com/jrihon/multi-bibs/main/chapters/01_chapter/results.typ
typst
MIT License
#import "../../lib/multi-bib.typ": * #import "bib_01_chapter.typ": biblio == Results #lorem(50) In terms of formalisms, the Cremer-Pople formalism is top notch #mcite(("Cremer1975general"), biblio). but still, this thing is also fine #mcite(("Iupac1983nucleicacids", "Cremer1975general"), biblio).
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/page_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test page fill. #set page(width: 80pt, height: 40pt, fill: eastern) #text(15pt, font: "Roboto", fill: white, smallcaps[Typst]) #page(width: 40pt, fill: none, margin: (top: 10pt, rest: auto))[Hi]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/features-02.typ
typst
Other
// Test alternates and stylistic sets. #set text(font: "IBM Plex Serif") a vs #text(alternates: true)[a] \ ß vs #text(stylistic-set: 5)[ß]
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/05-complex-functions/04-logarithm.typ
typst
#import "../../utils/core.typ": * == Логарифм #ticket[Теорема о существовании логарифма голоморфной функции. Логарифм. Полная аналитическая функция Ln z и ее свойства. Следствия.] #th[ Пусть $f in H(Omega)$, $Omega$ --- односвязна и $f != 0$ в $Omega$. Тогда существует $g in H(Omega)$ такая, что $e^g = f$. ] #proof[ Рассмотрим $ h(z) = (f'(z)) / (f(z)) in H(Omega). $ У этой функции есть первообразная $g$. Подберем такую из них, что $e^g(z_o) = f(z_0)$. Так можно делать, так как все первообразные отличаются на константу, и можно корректировать значения функции с помощью множителя $e^C$. Такое $C$ подбирается по аргументу и модулю. Проверим, что такая $g$ подходит. Пусть $k(z) = f(z) e^(-g(z))$. Тогда $k(z_0) = 1$. Проверим производную $k(z)$: $ k'(z) = (f e^(-g))' = f' e^(-g) + f dot e^(-g) dot (-g') = e^(-g) dot (f' - g' f) = 0. $ Значит $k$ --- константа, в какой-то точке равная $1$, то есть тождественная единица. Получили что хотели, $f(z) = e^(g(z))$. ] #follow[ Если $Omega$ односвязная и $0 in.not Omega$, то существует $g in H(Omega)$ такая, что $e^(g(z)) = z$ для любого $z in Omega$. Иными словами, существует комплексный логарифм. ] #notice[ $ e^(u + i v) = e^u dot e^(i v) = e^u (cos v + i sin v) $ Это вещественное число, умноженное на число на единичной окружности, причем $v$ не определено однозначно от значения экспоненты. Можно сдвигать $v$ на $2pi k$. Получается наш комплексный логарифм определен неоднозначно, так как если все значения сдвинуть на $2pi k$, получится другой логарифм, для которого тоже $e^(g(z)) = z$. С другой стороны, разумно положить, что это полная аналитическая функция. ] #def[ _Логарифм_, $Ln z$ --- такая голомофная на $Omega$ функция, как выше, где $Omega$ односвязная, не содержащая $0$. Эта функция определяется областью определения и значением в одной точке. $ Ln z = ln abs(z) + i Arg z, $ где $Arg$ выбирается так, что он непрерывно зависит от точки, чтобы была голоморфность. ] #notice[ Все такие $Ln$ из одного класса эквивалентности. ] #proof[ #figure( cetz.canvas({ let std-square = square import cetz.draw: * let size = 1.5 let picture(cut-angle, shift) = { let colors = ( color.hsv(cut-angle / 3 + 00deg, 100%, 100%, 30%), color.hsv(cut-angle / 3 + 60deg, 100%, 100%, 30%), color.hsv(cut-angle / 3 + 120deg, 100%, 100%, 30%), ) group({ translate(shift) content( (0, 0), std-square( size: 2 * size * 1cm, stroke: none, fill: gradient.conic( ..colors, relative: "self", angle: cut-angle, ) ) ) line((0, -size), (0, size), mark: (end: ">")) line((-size, 0), (size, 0), mark: (end: ">")) content((size + 0.3, 0), "Re") content((0, size + 0.25), "Im") line((0, 0), (rel: (angle: cut-angle, radius: size)), stroke: (paint: red, thickness: 3pt), mark: (start: "o")) }) } picture(-270deg, (-4, 0)) picture(-90deg, (0, 0)) picture(90deg, (4, 0)) picture(270deg, (8, 0)) }), caption: [ Цветом обозначена мнимая часть логарифма. Мы строим логарифмы так, чтобы значения мнимой части на какой-то из полуплоскостей совпадали. Например, на первой картинке мнимая часть принимает значения от $-(3pi)/2$ до $pi / 2$, и совпадает со значениями на второй картинке на полуплоскости $Re > 0$, где мнимая часть принимает значения от $-pi / 2$ до $(3pi) / 2$. ] ) Зафиксируем значение в единице. Скажем, пусть $Ln 1 = 0$. Рассмотрим такую $Omega$, что аргумент будет лежать от $-pi/2$ до $(3pi) / 2$. Затем рассмотрим такой же логарифм, определнный от $-(3pi) / 2$ до $pi/2$. Они совпадают на коплексной полуплоскости. Продолжаем строить логарифмы по индукции, пока не продолжим на все возможные значения аргумента. ] #notice[ В каждой точке полная аналитическая функция $Ln$ принимает счетное число значений. ] #props[ 1. $Ln$ --- полная аналитическая функция, значения которой равны $ Ln z = {omega in CC : e^omega = z}. $ 2. Для полной аналитической функции, $ Ln (z omega) = Ln z + Ln omega, $ но это свойство нарушается, если говорить об отдельных представителях. Например, если рассмотреть такой $Ln$, что $Ln (-1) = pi i$, а $Ln 1 = 0$, то $ Ln ((-1)^2) = Ln 1 = 0 != Ln (-1) + Ln (-1) = 2pi i. $ Они всегда будут отличаться на число кратное $2pi i$ (следует из свойства для полной функции), но они не обязаны быть равны. ] #def[ _Степень_: $ z^p = e^(p Ln z). $ ] #notice[ Рассмотрим случаи: 1. $p in ZZ$: $ z^n = e^(n Ln z) = e^(Ln z + ... + Ln z) = e^(Ln z) dot ... dot e^(Ln z) = z^n. $ Значит для $p in NN$ новых значений нет (разве что мы немного подпортили область определения: испортили $0$), короче соответсвие есть, все ок. Для отрицательных тоже все будет нормально. 2. $p in QQ$. Пусть $p = m/n$, и это несократимая дробь. Тогда $ z^p = e^(m/n Ln z) = e^(m/n (ln abs(z) + i arg z + 2pi i k)) = e^(m/n (ln abs(z) + i arg z)) dot e^(2pi i k m/n). $ Здесь $k$ может быть любым, так как $arg z$ определен неоднозначно, с точностью до кратности $2pi$. Из-за этого последний множитель позволяет управлять значением степени. Сколько значений она может принять? Так как $m$ и $n$ взаимно просты, $k m mod n$ принимает любые значения от $0$ до $n - 1$, и получается, что степень может принимать $n$ различных значений. Получилась полная аналитическая функция, которая может принимать любое конечное число значений: $z^(1/n)$. 3. $p in CC without QQ$. Можно рассмотреть счетное число $k$ таких, что $e^(2pi i p k) = e^(2pi i p tilde(k))$, так как равенство есть если $2 pi i p (k - tilde(k)) = 2 pi i l$. ] #exercise(plural: true)[ 1. $i^i = ?$. 2. Доказать, что $(z^p)' = (p z^p)/z$. 3. $z^p dot w^p = (z w)^p$ как полные аналитические функции, но для конкретных представителей равенства нет. ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/tiaoma/0.1.0/lib.typ
typst
Apache License 2.0
#let zint-wasm = plugin("./zint_typst_plugin.wasm") #let ean(data, ..args) = image.decode(zint-wasm.ean_gen(bytes(data)), format: "svg", ..args) #let code128(data, ..args) = image.decode(zint-wasm.code128_gen(bytes(data)), format: "svg", ..args) #let code39(data, ..args) = image.decode(zint-wasm.code39_gen(bytes(data)), format: "svg", ..args) #let upca(data, ..args) = image.decode(zint-wasm.upca_gen(bytes(data)), format: "svg", ..args) #let data-matrix(data, ..args) = image.decode(zint-wasm.data_matrix_gen(bytes(data)), format: "svg", ..args) #let qrcode(data, ..args) = image.decode(zint-wasm.qrcode_gen(bytes(data)), format: "svg", ..args) #let channel(data, ..args) = image.decode(zint-wasm.channel_gen(bytes(data)), format: "svg", ..args) #let msi-plessey(data, ..args) = image.decode(zint-wasm.msi_plessey_gen(bytes(data)), format: "svg", ..args) #let micro-pdf417(data, ..args) = image.decode(zint-wasm.micro_pdf417_gen(bytes(data)), format: "svg", ..args) #let aztec(data, ..args) = image.decode(zint-wasm.aztec_gen(bytes(data)), format: "svg", ..args) #let code16k(data, ..args) = image.decode(zint-wasm.code16k_gen(bytes(data)), format: "svg", ..args) #let maxicode(data, ..args) = image.decode(zint-wasm.maxicode_gen(bytes(data)), format: "svg", ..args) #let planet(data, ..args) = image.decode(zint-wasm.planet_gen(bytes(data)), format: "svg", ..args) #let barcode(data, type, ..args) = image.decode( zint-wasm.gen_with_options( cbor.encode( (symbology: (type: type),) ), bytes(data) ), format: "svg", ..args)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/multiline-08.typ
typst
Other
// Test multiple trailing line breaks. $ "abc" &= c \ \ \ $ Multiple trailing line breaks.
https://github.com/jamesrswift/musicaux
https://raw.githubusercontent.com/jamesrswift/musicaux/main/src/commands/common.typ
typst
#import "basic-content.typ": basic-content #import "../symbols.typ": * // Clefs // TO DO: Move to separate service that handles tune's key #let trebble = basic-content.with(pitch: 3, symbols.clef) #let bass = basic-content.with(pitch: 3, symbols.bass) // Key Signature // TO DO: Move to separate service that handles tune's key #let key-signatures = ( 0, 2, -1, 1, -2, 0, -3, -1, -4, -2, 0, -3) #let key-signature(pitch: 0) = { for i in range(7, pitch+7, step: int(pitch / calc.abs(pitch)) ) { basic-content( pitch: key-signatures.at(i), (if (pitch > 0 ) [#symbols.sharp] else [#symbols.flat]) ) } }
https://github.com/N3M0-dev/Notes
https://raw.githubusercontent.com/N3M0-dev/Notes/main/Math/Probability/Ch_1/note.typ
typst
#import "@local/note_template:0.0.1": * #set page(numbering: "1", number-align: center) #set heading(numbering: "1.1") #set par(justify: true) #set text(12pt) #set outline(indent: true) #frontmatter(authors: ("Nemo",), title: "Sample Space and Probability", date: "2023.7.10") #outline() #pagebreak() // #let authors=("Nemo",) // #let title="Sample Space and Probability" // #let date="2023.7.10-" // #set document(author: authors, title: title) // #set page(numbering: "1", number-align: center) // #set heading(numbering: "1.1") // // // Title row. // #align(center)[ // #block(text(weight: 700, 1.75em, title)) // #v(1em, weak: true) // #date // ] // // // Author information. // #pad( // top: 0.5em, // bottom: 0.5em, // x: 2em, // grid( // columns: (1fr,) * calc.min(3, authors.len()), // gutter: 1em, // ..authors.map(author => align(center, strong(author))), // ), // ) // // // Main body. // #set par(justify: true) // #set text(12pt) // // #outline(indent: true) = Sets (Quick Review) #emph()[Set, element, empety set $nothing$, finit set, countably finit set, uncountable set, sub set, equal, universal set $Omega$] == Set opeartions: + Complement of a set $S$, with respect it the universe $Omega$, denoted by $S^c$ + Union of two sets $S,T$, $S union T$ + Intersection of two sets $S,T$, $S sect T$ + Union of several, $union.big^infinity_(n=1) S_n=S_1 union S_2 union dots$ + Intersection of several, $sect.big^infinity_(n=1) S_n=S_1 sect S_2 sect dots$ + Sets are Disjoint if they share no element + A collection of sets is a partition of set $S$, if they are disjoint and the union of them are $S$ == The Algrebra of Sets: #heading(level: 3,numbering: none)[De Morgan's laws:] $ (union.big_n S_n)^c=sect.big_n S^c_n\ (sect.big_n S_n)^c=union.big_n S^c_n $ #pagebreak() = Probabilistic Models #align(center)[ #rect(width: 95%)[#align(left)[ #heading(level: 3,numbering: none)[Elements of a Probabilistic Model] - The sample space $Omega$, the set of all possiable outcomes - The probability law, which assigns any event $A$ a non-negative number $P(A)$ ]]]#footnote(numbering: "*")[ Insight of Probability: The term "probability" should come with an event, like the probability of event $A $ $P(A)$, which is further a outcome of the probability law and a part of the probabilistic model. And a valid probabilistic model should contain a sample space and a probability law which agree with the probability axioms.] == Choosing an Appropriate Sample Space The element of the sample space should be distinct and #emph()[mutually exclurive], and the sample space should be collectively exhaustive. == Probability Axioms #align(center)[ #rect(width: 95%)[#align(left)[ + *(Nonnegativity)* $P(A) gt.eq 0$, for every event $A$ + *(Additivity)* $A,B$ are disjoint, then $P(A union B)=P(A)+P(B)$ + *(Normalization)* $P(Omega)=1$ ]]] == Discrete Models / e.g. *The toss of a coin several times*: #text(style: "italic")[ Like {HHH,HHT,HTH,HTT,THH,THT,TTH,TTT}(3 times) and the probability stuff] #align(center)[ #rect(width: 95%)[#align(left)[ #heading(level: 3,numbering: none)[Discrete Probability Law] The sample space $S={s_1,s_2,s_3,dots,s_n}$ consists of finite number of elements, we have:$ P(S)=P({s_1,s_2,s_3,dots,s_n})=P(s_1)+P(s_2)+P(s_3)+dots+P(s_n) $ ]]] #align(center)[ #rect(width: 95%)[#align(left)[ #heading(level: 3,numbering: none)[Discrete Uniform Probability Law] Ii the outcomes are equally likely, then the Probability of any single outcome A becomes: $ P(A)=("number of elements of" A)/n $ ]]] == Continuous Models Like throughing a dart on a certian area or sth else ... == Properties of Probability Laws + If $A in B$, then $P(A) lt.eq P(B)$ + $P(A union B)=P(A)+P(B)-P(A sect B)$ + $P(A union B) lt.eq P(A)+P(B)$ + $P(A union B union C)=P(A)+P(A^c sect B)+P(A^c sect B^c sect C )$ = Conditional Prabability Conditional probability provides us with a way to reason about the outcome of an ekperiment, based on *parcial information*. (The experiment is done and the only have some parcial information about it.) / e.g.: The experiment involving two successive rolls of a die, you are toled that the sum of the two rolls are 9. What's the probability of the first roll is a 6? In precise terms, the conditional probability is when we know the is with in a given event $B$, we wish to know the probability of the event $A$. We call this #emph()[conditional probability of $A$ given $B$], denoted by $P(A bar B)$ *Definition*#sub()[#text(style: "italic")[conditional probability]]: $P(A bar B)=P(A sect B)/P(B)$ == Verification of the Prabability Laws + Nonnegativity is clear since the original probability is nonnegative. + Additivity: $ P(A_1 union A_2 bar B) &= P((A_1 union A_2) sect B)/P(B)\ &= (P(A_1 sect B) + P(A_2 sect B))/P(B)\ &= P(A_1 bar B)+P(A_2 bar B) $\ + Normalization: $ P( Omega bar B)=P(Omega sect B)/P(B)=P(B)/P(B)=1 $ == Properties of Conditional Probability #align(center)[ #rect(width: 95% )[#align(left)[#pad(y: 5pt)[ - Conditional probability can be viewed as a normal probability on a new universe $B$. - Furthermore, if all outcomes are equally likely, then $P(A bar B)=("num of elements of" A union B)/("num of elements of" B)$ ]]]] == Using Conditional Probability for Modeling A restatement of the definition of the conditional probability is $P(A union B)=P(B)P(A bar B)$, which can be used to calculate a non-conditional probability. #align(center)[ #rect(width: 95% )[#align(left)[#heading(level: 3,numbering: none)[Multiplication Rule] #pad(y: 5pt)[ By definition, it's easy to get $ P(union.big^n_(i=1)A_i)=P(A_1)P(A_2 bar A_3)P(A_3 bar A_1 sect A_2) dots.h P(A_n bar union.big^(n-1)_(i=1)A_i) $ ]]]] == Total Probability Theorem and Bayes' Rule #align(center)[ #rect(width: 95% )[#align(left)[#heading(level: 3,numbering: none)[Total Probability Theorem] #pad(y: 5pt)[ Let $A_1, A_3, dots, A_n$ be disjoint events that #emph()[form a partition] of the sample space, and assume that $P(A_i)>0$ for all $i$. Then far any event $B$, we have $ P(B)&= P(A_n union B)+dots.h+P(A_n union B)\ &= sum^n_(i=1) P(A_i)P(B bar A_i) $ ]]]] #align(center)[ #rect(width: 95% )[#align(left)[#heading(level: 3,numbering: none)[Bayes' Rule] #pad(y: 5pt)[ Let $A_1, A_2, dots, A_n$ be disjoint events that form a partition of the sample space, and assume that $P(A_i) gt 0$ for all $i$. Then, for any event $B$ such that $B$ that $P(B) gt 0$, we have $ P(A_i bar B) &= (P(A_i)P(B bar A_i))/P(B)\ &=(P(A_i)P(B bar A_i))/(P(A_1)P(B bar A_1)+dots.h+P(A_n)P(B bar A_n)) $ ]]]] The Bayes' Rule reveals the relation between conditional probability of form $P(A bar B)$ and $P(B bar A$), in which the order of conditioning is reversed. / e.g. An example in medicine: \ If there is a shade in someone's x-ray, and there are 3 possibilities: \ 1. It's a malignant tumor\ 2. It's a nonmalignant tumor\ 3. Not a tumor\ Calculate the probability of each situation. / Ans: Let $A_1, A_2, A_3$ be the three events, and $B$ be the probability of there being a shade. Assume that we know the probabilities $P(A_i)$ and $P(B bar A_i)$ (these data can be actually found in practise). So we due to Bayes' Rule, we have $ P(A_i bar B)=(P(A_i)P(B bar A_i))/(P(B))=(P(A_i)P(B bar A_i))/(P(A_1)P(A_1 bar B)+P(A_2)P(A_2 bar B)+P(A_3)P(A_3 bar B)) $ As above, the Bayes Rule is often used for inference where we need to infer the "causes" from "effects". The events $A_1, A_2, A_3$ are the causes and the shade event $B$ is the effect by the causes. In a lot of situations, we have already collected the data of the effects, and we want to evaulate the probability of the cause $A_i$ is present, that's when Bayes' Rule come into use. And just like the example above, the $A_i$ stands for the cause, the $B$ stands for the effect, we give the definition of #emph()[posterior probability] and #emph()[prior probability]: / Posterior probability: $P(A_i bar B)$ / Prior probability: $P(A_i)$ / e.g. The False-Positive Puzzle: \ A test for a certian rare disease is assumed to be 95% correct, and a random person drawn from a cortain population has the probability 0.001 of having the disease. Then, if a person tested positive, what is the probability of the person having the disease? / Ans: Now we know the effect, we want to evaulate the probability of the cause is present -- Apply the Bayes' Rule! Let $A$ be the event the person have the disease, $B$ be the event of tested positive. So we want $P(A bar B)$, and we have $P(A)=0.001, P(B bar A)=0.95$. So $ P(A bar B)=(P(A)P(B bar A))/P(B)= (P(A)P(B bar A))/(P(A)P(B bar A)+P(A^c)P(B bar A^c))=0.0187 $\ Less than 2%!!! == Independence *Definition*#sub()[#text(style: "italic")[independence]]: If $P(A sect B)=P(A)P(B)$, then we say that $A$ is #emph()[independent] of $B$. The equation above is also equivalent to $P(A bar B)=P(A)$. == Conditional Independence *Definition*#sub()[#text(style: "italic")[conditional independence]]: If $P(A sect B bar C)=P(A bar C)P(B bar C)$, we say thar events $A$ and $B$ are conditionally independent (given $C$). #align(center)[ #rect(width: 95% )[#align(left)[#heading(level: 3,numbering: none)[Summary] #pad(y: 5pt)[ - Two events $A,B$ are independent if $P(A sect B)=P(A)P(B)$. In addition, if $P(B) gt 0$, independence is equivalent to $P(A bar B)=P(A)$ - If $A,B$ are independent, so are $A$ and $B^c$ - Two events $A,B$ are conditionally independent if $P(A sect B bar C)=P(A bar C)P(B bar C)$. In addition, if $P(B) gt 0$, independence is equivalent to $P(A bar B sect C)=P(A bar C)$. - Independence does not imply conditional independence and vice versa. ]]]] #align(center)[ #rect(width: 95% )[#align(left)[#heading(level: 3,numbering: none)[Independence of a collection of events] #pad(y: 5pt)[ Events $A_1,A_2,dots,A_n$ are independent if $ P(sect.big_(i in S)A_i)=product_(i in S)P(A_i), "for every subset" S "of" {1,2,dots,n} $ ]]]] == Reliability / e.g. Network connectivity: \ The following graph is a network with the prabability of link of the connected nodes is up. Evaulate the probability of the successful connection from $A$ to $B$.(Classic problem ,omitting ans) #figure( grid( columns: 2, image("./net.svg"), image("./series_parallel.svg") )) #pagebreak() == Independent Trials and the Binomial Probabilities
https://github.com/MatheSchool/typst-g-exam
https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/src/g-option.typ
typst
MIT License
#import"./global.typ": * /// Define a new block of options. /// /// *Example:* /// ``` /// #g-subquestion(points:2)[This is a sub-question] /// ``` /// /// - body (string, content): Body of option label. #let g-option( body) = { body }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/editors/vscode/CHANGELOG.md
markdown
Apache License 2.0
# Change Log All notable changes to the "tinymist" extension will be documented in this file. Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file. ## v0.12.0 - [2024-10-19] ### Document Link * Identifying static path references in documents in https://github.com/Myriad-Dreamin/tinymist/pull/658 ### Compiler * Improved code quality of `sync-lsp` in https://github.com/Myriad-Dreamin/tinymist/pull/632 * Removed some unwraps that some editors may not love. * Using `DETACHED_ENTRY` if no entry is provided in https://github.com/Myriad-Dreamin/tinymist/pull/647 * Caching `dirs::data_dir` and `dirs::cache_dir` in https://github.com/Myriad-Dreamin/tinymist/pull/659 ### Editor * Supported drag and drop of files into the typst editor in https://github.com/Myriad-Dreamin/tinymist/pull/635 * Added configuration to open exported file by system default app in https://github.com/Myriad-Dreamin/tinymist/pull/636 ### Profiling * Sending trace data via http instead of lsp stdio in https://github.com/Myriad-Dreamin/tinymist/pull/660 ### Definition * Recording and using span where the label is attached in https://github.com/Myriad-Dreamin/tinymist/pull/641 * Make go to definition more accurate. * Added support to go to definition of module members in https://github.com/Myriad-Dreamin/tinymist/pull/644 ### Rename * Added support to rename modules by path in https://github.com/Myriad-Dreamin/tinymist/pull/645 * Issuing import changes request during `willRenameFiles` in https://github.com/Myriad-Dreamin/tinymist/pull/648 ### Preview * (Fix) Checking existence of `requestIdleCallback` before uses in https://github.com/Myriad-Dreamin/tinymist/pull/643 ### On Enter * Adding indent on entering in empty block maths in https://github.com/Myriad-Dreamin/tinymist/pull/646 ### Hover (Tooltip) * Made star import tooltip more human readable in https://github.com/Myriad-Dreamin/tinymist/pull/682 * Rendering hover docs with converted result in https://github.com/Myriad-Dreamin/tinymist/pull/701 * Providing parameter docs in hover tips in https://github.com/Myriad-Dreamin/tinymist/pull/702 ### Syntax/Semantic Highlighting * Passing `to_multiline_tokens2` checking by copilot in https://github.com/Myriad-Dreamin/tinymist/pull/639 * (Fix) Parsing `for` clause correctly in https://github.com/Myriad-Dreamin/tinymist/pull/642 ### Type Checking * Implemented ord for `Ty` in https://github.com/Myriad-Dreamin/tinymist/pull/667 * Made elementary select checker in https://github.com/Myriad-Dreamin/tinymist/pull/668 * Made elementary tuple method checker in https://github.com/Myriad-Dreamin/tinymist/pull/669 * Checking call types with default bindings in https://github.com/Myriad-Dreamin/tinymist/pull/671 and https://github.com/Myriad-Dreamin/tinymist/pull/675 * Performing type induction on runtime values in https://github.com/Myriad-Dreamin/tinymist/pull/694 ### Type Checking (Docstring) * Reading and checking type annotations in docstring in https://github.com/Myriad-Dreamin/tinymist/pull/679, https://github.com/Myriad-Dreamin/tinymist/pull/680, and https://github.com/Myriad-Dreamin/tinymist/pull/681 ### Misc * Refactored analysis structure in https://github.com/Myriad-Dreamin/tinymist/pull/674 * Fixed typos in readme by @hougesen in https://github.com/Myriad-Dreamin/tinymist/pull/662 * Incorporated with static function signature analysis in https://github.com/Myriad-Dreamin/tinymist/pull/688, https://github.com/Myriad-Dreamin/tinymist/pull/692, https://github.com/Myriad-Dreamin/tinymist/pull/696, and https://github.com/Myriad-Dreamin/tinymist/pull/699 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.32...v0.12.0 ## v0.11.32 - [2024-10-10] * Fix accidentally released nightly version. ## v0.11.28 - [2024-10-05] ### Compiler * (Fix) Allowing keeping garbage directories in the package directory in https://github.com/Myriad-Dreamin/tinymist/pull/622 * The previous code asserts all directories in the package directory are typst packages, but this is not always true. Prints errors once and skips these directories. ### Misc * Printing version information when starting lsp server in https://github.com/Myriad-Dreamin/tinymist/pull/614 * Open server log to see the version information of the server. It is usually the first line of the log. **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.22...v0.11.28 ## v0.11.22 - [2024-09-20] ## (New) Tinymist Nightly This is a new release channel for Tinymist, which uses *main branch of typst*. Currently it is only available at [nightly branch,](https://github.com/Myriad-Dreamin/tinymist/tree/nightly), but we will set up nightly release in soon future. * Added compatibility layer for Typst stable and nightly APIs by @ParaN3xus in https://github.com/Myriad-Dreamin/tinymist/pull/573 * Added compatibility for `typst_syntax::LinkedNode.leaf_at` by @ParaN3xus in https://github.com/Myriad-Dreamin/tinymist/pull/582 ### Compiler * (Fix) Deadlock when iterating dependencies in https://github.com/Myriad-Dreamin/tinymist/pull/568 * This could happen when you are triggering workspace-level requests, like `symbol` or `reference` requests. * (Fix) Ignoring system fonts correctly in https://github.com/Myriad-Dreamin/tinymist/pull/597 * Supported CA certificate customization by @ricOC3 in https://github.com/Myriad-Dreamin/tinymist/pull/592 ### Editor * Providing label view in https://github.com/Myriad-Dreamin/tinymist/pull/570 * Providing package view and local documentation in https://github.com/Myriad-Dreamin/tinymist/pull/596 ### Preview * Listening data plane socket and serve frontend html on same address in https://github.com/Myriad-Dreamin/tinymist/pull/577 * Added gitpod layer for previewing from remote host by @tani in https://github.com/Myriad-Dreamin/tinymist/pull/575 ### Syntax/Semantic Highlighting * (Fix) Ignoring invalid tokens in typst's syntax tree in https://github.com/Myriad-Dreamin/tinymist/pull/605 * Improved theme settings for raw blocks in https://github.com/Myriad-Dreamin/tinymist/pull/606 ### Completion * (Fix) Refined label types to remove hacking citation filter in https://github.com/Myriad-Dreamin/tinymist/pull/603 * (Fix) Deduplicating value completion correctly in https://github.com/Myriad-Dreamin/tinymist/pull/604 ### Folding Range * (Fix) Processing overlapping cases in line folding only mode (3ab4fa62) in https://github.com/Myriad-Dreamin/tinymist/pull/588 * (Fix) Creating function scopes for nest symbols in https://github.com/Myriad-Dreamin/tinymist/pull/589 ### Document Symbol * (Fix) Showing symbols when pattern is not provided in https://github.com/Myriad-Dreamin/tinymist/pull/569 ### Commands/Tools * Showing first occurrence locations for used fonts by @hooyuser in https://github.com/Myriad-Dreamin/tinymist/pull/598 ### Misc * Added shell completions for Fig and Nushell by @T1mVo in https://github.com/Myriad-Dreamin/tinymist/pull/578 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.20...v0.11.22 ## v0.11.20 - [2024-08-26] * Bumped typstyle to v0.11.32 by @Enter-tainer in https://github.com/Myriad-Dreamin/tinymist/pull/551 * Bumped typst.ts to v0.5.0-rc7 in https://github.com/Myriad-Dreamin/tinymist/pull/554 ### Compiler * Performing simple rate limit on heavy dynamic analysis in https://github.com/Myriad-Dreamin/tinymist/pull/532 ### Editor * Provide contextual action to export text in range as ansi highlighted code in https://github.com/Myriad-Dreamin/tinymist/pull/526 and https://github.com/Myriad-Dreamin/tinymist/pull/544 * Fixed invalid merged command options in https://github.com/Myriad-Dreamin/tinymist/pull/564 ### Commands/Tools * Added local package manager by @OrangeX4 in https://github.com/Myriad-Dreamin/tinymist/pull/458 ### Preview * Removed useless `tinymist.preview.showInActivityBar` in https://github.com/Myriad-Dreamin/tinymist/pull/543 ### Hover (Tooltip) * (Fix) Removed feature texmath by @Eric-Song-Nop in https://github.com/Myriad-Dreamin/tinymist/pull/535 * Displaying all imported definitions for wildcard imports in https://github.com/Myriad-Dreamin/tinymist/pull/565 ### References * Finding references for `Ref` and `Label` by @Eric-Song-Nop in https://github.com/Myriad-Dreamin/tinymist/pull/527 ### Syntax/Semantic Highlighting * (Fix): parse dot issue 492 again in https://github.com/Myriad-Dreamin/tinymist/pull/557 * Improved numeric literal parsers in https://github.com/Myriad-Dreamin/tinymist/pull/558 * (Fix): parse quotes near the atomic hash expression in https://github.com/Myriad-Dreamin/tinymist/pull/559 ### Misc * Added test for `goto_definition` for label by @Eric-Song-Nop in https://github.com/Myriad-Dreamin/tinymist/pull/510 * Generating shell completion by @Eric-Song-Nop in https://github.com/Myriad-Dreamin/tinymist/pull/525 * Added installation and configuration instruction for Emacs by @Ziqi-Yang in https://github.com/Myriad-Dreamin/tinymist/pull/538 * Added document preview feature documentations for non-vscode clients in https://github.com/Myriad-Dreamin/tinymist/pull/560 * Added root path hints in documentation for neovim users in https://github.com/Myriad-Dreamin/tinymist/pull/561 * Added notes to stateful pin commands in documentation in https://github.com/Myriad-Dreamin/tinymist/pull/562 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.19...v0.11.20 ## v0.11.19 - [2024-08-10] * Bumped typstyle v0.11.31 by @Enter-tainer in https://github.com/Myriad-Dreamin/tinymist/pull/512 ### Compiler * (Fix) Tested and fixed initialization of formatter configuration in https://github.com/Myriad-Dreamin/tinymist/pull/523 ### Editor * (Fix) Using plural for 0 items by @Nerixyz in https://github.com/Myriad-Dreamin/tinymist/pull/507 ### Hover (Tooltip) * Showing target of label and con tent of metadata when hovering in https://github.com/Myriad-Dreamin/tinymist/pull/517 ### Preview * (Fix) Two small bugs in tasks feature in https://github.com/Myriad-Dreamin/tinymist/pull/499 * deactivating task provider when the extension is deactivated * don't write args variable when exporting pdfpc task ### Syntax/Semantic Highlighting * Injecting typst{,-code} syntaxes into markdown syntax highlighting in https://github.com/Myriad-Dreamin/tinymist/pull/504 and https://github.com/Myriad-Dreamin/tinymist/pull/518 * (Fix) Parsing dot operation on atomic expression correctly in https://github.com/Myriad-Dreamin/tinymist/pull/497 * Identifying more context for bracket colorization in https://github.com/Myriad-Dreamin/tinymist/pull/522 * (Fix) Allowing underline in url link in https://github.com/Myriad-Dreamin/tinymist/pull/520 ### Misc * Linked sublime text support to [sublimelsp](https://github.com/sublimelsp/LSP/blob/main/docs/src/language_servers.md#tinymist) in https://github.com/Myriad-Dreamin/tinymist/pull/519 * Fixed bad configuration documentation in https://github.com/Myriad-Dreamin/tinymist/pull/521 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.18...v0.11.19 ## v0.11.18 - [2024-08-05] ### Compiler * Cherry picked concurrent id error in https://github.com/Myriad-Dreamin/tinymist/pull/472 * This affects lsp since the server parallelized the requests. * (Fix) Retrieving environments even if `typstExtraArgs` is unspecified in https://github.com/Myriad-Dreamin/tinymist/pull/482 * For example, the env variable `SOURCE_DATE_EPOCH` is not used when `typstExtraArgs` is not specified. ### Commands/Tools * Supported vscode tasks for exporting pdf, svg, and png in https://github.com/Myriad-Dreamin/tinymist/pull/488 * Supported vscode tasks for exporting html, md, and txt in https://github.com/Myriad-Dreamin/tinymist/pull/489 * Supported vscode tasks for exporting query and pdfpc in https://github.com/Myriad-Dreamin/tinymist/pull/490 ### Preview * Added normal-image option for `tinymist.preview.invertColor` feature by @SetsuikiHyoryu in https://github.com/Myriad-Dreamin/tinymist/pull/464 and https://github.com/Myriad-Dreamin/tinymist/pull/473 * People may love inverted color for preview, but not for images. This feature helps them. * Removed `typst-preview.showLog` and added `tinymist.showLog` in https://github.com/Myriad-Dreamin/tinymist/pull/476 * (Fix) Processing task id correctly when executing scroll command in https://github.com/Myriad-Dreamin/tinymist/pull/477 ### Completion * (Fix) Applying label instead of bib title name in `at` completion by @kririae in https://github.com/Myriad-Dreamin/tinymist/pull/485 ### Syntax/Semantic Highlighting * (Fix) Allowing hyphenate in url link in https://github.com/Myriad-Dreamin/tinymist/pull/481 * It was not highlighted correctly. ### Misc * Added documentation about installing nightly prebuilts in https://github.com/Myriad-Dreamin/tinymist/pull/480 * Improved contribution guide and added sections for syntaxes in https://github.com/Myriad-Dreamin/tinymist/pull/471 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.17...v0.11.18 ## v0.11.17 - [2024-07-27] ### Editor * Added a `$(file-pdf)` icon for `showPdf` to navigation bar in https://github.com/Myriad-Dreamin/tinymist/pull/462 * It is a shorter way to export and open documents as PDF. * It now has a different icon from the `preview` command. * Note: This function is suitable to help perform your final checks to documents. For previewing, please uses `preview` command for better experience. * Interned vscode-variable package in https://github.com/Myriad-Dreamin/tinymist/pull/460 * Fixed some bugs in the vscode-variable package. * Improving the performance of replacing variables a bit. ### Compiler * (Fix) Processing lagged compile reason in https://github.com/Myriad-Dreamin/tinymist/pull/456 * Causing last key strokes not being processed correctly. ### Preview * Modified static host to send Content-Type: text/html by @cskeeters in https://github.com/Myriad-Dreamin/tinymist/pull/465 * Causing that GitHub Codespaces and the browser just showed the text of the HTML. ### Completion * Supported querying label with paper name in bib items by @kririae in https://github.com/Myriad-Dreamin/tinymist/pull/365 * Added documentation about completion in https://github.com/Myriad-Dreamin/tinymist/pull/466 ### Syntax/Semantic Highlighting * Added syntax highlighting for raw blocks in https://github.com/Myriad-Dreamin/tinymist/pull/450 * To ensure 100% correctness of grammar, only the raw block with number fence ticks less than 6 is highlighted. ### Misc * Handling unwrap for the args in compile command by @upsidedownsweetfood in https://github.com/Myriad-Dreamin/tinymist/pull/445 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.16...v0.11.17 ## v0.11.16 - [2024-07-20] * Adding editor-side e2e testing in https://github.com/Myriad-Dreamin/tinymist/pull/441 and https://github.com/Myriad-Dreamin/tinymist/pull/442 ### Compiler * Making compilation not block most snapshot requests in https://github.com/Myriad-Dreamin/tinymist/pull/432 and https://github.com/Myriad-Dreamin/tinymist/pull/435 * Making cache evicting shared in https://github.com/Myriad-Dreamin/tinymist/pull/434 * To make more sensible cache eviction when you are previewing multiple documents (running multiple compilers). * (Fix) Changing entry if pinning again in https://github.com/Myriad-Dreamin/tinymist/pull/430 * This was introduced by https://github.com/Myriad-Dreamin/tinymist/pull/406 * (Fix) Tolerating client changing source state badly in https://github.com/Myriad-Dreamin/tinymist/pull/429 * Sometimes the client sends a request with a wrong source state, which causes a panic. ### Editor * Showing views only if tinymist extension is activated in https://github.com/Myriad-Dreamin/tinymist/pull/420 * This is a slightly improvement on https://github.com/Myriad-Dreamin/tinymist/pull/414 * (Fix) Removed dirty preview command changes in https://github.com/Myriad-Dreamin/tinymist/pull/421 * It also adds dev kit to avoid this stupid mistake in future. The kit contains a convenient command for previewing document on a fixed port for development. * Added hint documentation about configuring rootless document in https://github.com/Myriad-Dreamin/tinymist/pull/440 * You can set the rootPath to `-`, so that tinymist will always use parent directory of the file as the root path. ### Commands/Tools * Supported creation-timestamp configuration for exporting PDF in https://github.com/Myriad-Dreamin/tinymist/pull/439 * It now start to provide creation timestamp for the PDF export. * You can disallow it to embed the creation timestamp in your document by `set document(..)`. * You can also configure it by either [Passing Extra CLI Arguments](https://github.com/Myriad-Dreamin/tinymist/blob/9ceae118480448a5ef0c41a1cf810fa1a072420e/editors/vscode/README.md#passing-extra-cli-arguments) or the environment variable (`SOURCE_DATE_EPOCH`). * For more details, please see [source-date-epoch](https://reproducible-builds.org/specs/source-date-epoch/) ### Preview * Allowing multiple-tasked preview in https://github.com/Myriad-Dreamin/tinymist/pull/427 * Provided `sys.inputs.x-preview` in https://github.com/Myriad-Dreamin/tinymist/pull/438 * It could be used for customizing the templates when you are previewing documents. ### Completion * (Fix) Check string's quote prefix correctly when completing code in https://github.com/Myriad-Dreamin/tinymist/pull/422 ### Misc * Fixed description for exportPdf setting by @Otto-AA in https://github.com/Myriad-Dreamin/tinymist/pull/431 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.15...v0.11.16 ## v0.11.15 - [2024-07-15] * Bumped typstyle to v0.11.30 by @Enter-tainer in https://github.com/Myriad-Dreamin/tinymist/pull/416 ### Compiler * (Fix) Noting `formatter_print_width` change on changed configuration in https://github.com/Myriad-Dreamin/tinymist/pull/387 * Keeping entry on language query in https://github.com/Myriad-Dreamin/tinymist/pull/406 * Allowed deferred snapshot event processing in https://github.com/Myriad-Dreamin/tinymist/pull/408 ### Editor * (Fix) Showing views in activity bar whenever the extension is activated in https://github.com/Myriad-Dreamin/tinymist/pull/414 ### Hover (Tooltip) * Rendering example code in typst docs as typst syntax in https://github.com/Myriad-Dreamin/tinymist/pull/397 ### Preview * Using `requestIdleCallback` to wait for updating canvas pages when editor is in idle in https://github.com/Myriad-Dreamin/tinymist/pull/412 * Improve performance when updating document quickly. * (Fix) Fixed some corner cases of serving preview in https://github.com/Myriad-Dreamin/tinymist/pull/385 * (Fix) Scrolling source correctly when no text editor is active in https://github.com/Myriad-Dreamin/tinymist/pull/395 * (Fix) Updating content preview incrementally again in https://github.com/Myriad-Dreamin/tinymist/pull/413 * (Fix) wrong serialization of `task_id` v.s. `taskId` in https://github.com/Myriad-Dreamin/tinymist/pull/417 ### Misc * Added typlite for typst's doc comments in https://github.com/Myriad-Dreamin/tinymist/pull/398 * Documented tinymist crate in https://github.com/Myriad-Dreamin/tinymist/pull/390 * (Fix) Performing cyclic loop dependence correctly when checking def-use relation across module in https://github.com/Myriad-Dreamin/tinymist/pull/396 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.14...v0.11.15 ## v0.11.14 - [2024-07-07] ## Compiler This bug is introduced by [Preparing for parallelizing lsp requests](https://github.com/Myriad-Dreamin/tinymist/pull/342). * (Fix) Lsp should respond errors at tail in https://github.com/Myriad-Dreamin/tinymist/pull/367 ### Commands/Tools * Supported single-task preview commands in https://github.com/Myriad-Dreamin/tinymist/pull/364, https://github.com/Myriad-Dreamin/tinymist/pull/368, https://github.com/Myriad-Dreamin/tinymist/pull/370, and https://github.com/Myriad-Dreamin/tinymist/pull/371 * Typst Preview extension is already integrated into Tinymist. It . Please disable Typst Preview extension to avoid conflicts. * Otherwise, you should disable the tinymist's embedded preview feature by `"tinymist.preview": "disable"` in your settings.json. ### Preview * Persisting webview preview through vscode restarts and @noamzaks in https://github.com/Myriad-Dreamin/tinymist/pull/373 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.13...v0.11.14 ## v0.11.13 - [2024-07-02] ## Compiler These bugs are introduced by [Preparing for parallelizing lsp requests](https://github.com/Myriad-Dreamin/tinymist/pull/342). * (Fix) diagnostics is back in https://github.com/Myriad-Dreamin/tinymist/pull/354 * (Fix) Checking main before compilation in https://github.com/Myriad-Dreamin/tinymist/pull/361 ## Misc * Optimized release profile in https://github.com/Myriad-Dreamin/tinymist/pull/359 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.12...v0.11.13 ## v0.11.12 - [2024-06-27] * Bumped typstyle to v0.11.28 * Added base documentation website in https://github.com/Myriad-Dreamin/tinymist/pull/344 and https://github.com/Myriad-Dreamin/tinymist/pull/345 ### Compiler * Preparing for parallelizing lsp requests in https://github.com/Myriad-Dreamin/tinymist/pull/342 ### Commands/Tools * Added font list export panel in summary tool by @7sDream in https://github.com/Myriad-Dreamin/tinymist/pull/322 ### Syntax/Semantic Highlighting * Disabling bracket colorization in markup mode in https://github.com/Myriad-Dreamin/tinymist/pull/346 * (Fix) Terminating expression before math blocks in https://github.com/Myriad-Dreamin/tinymist/pull/347 ### Completion * (Fix) Avoided duplicated method completion in https://github.com/Myriad-Dreamin/tinymist/pull/349 * Fixed a bad early return in param_completions in https://github.com/Myriad-Dreamin/tinymist/pull/350 * Fixed completion in string context a bit in https://github.com/Myriad-Dreamin/tinymist/pull/351 * It can handle empty string literals correctly now. * The half-completed string literals still have a problem though. ### Misc * Moved typst-preview to tinymist and combined the binary and compiler in https://github.com/Myriad-Dreamin/tinymist/pull/323, https://github.com/Myriad-Dreamin/tinymist/pull/332, and https://github.com/Myriad-Dreamin/tinymist/pull/337 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.11...v0.11.12 ## v0.11.11 - [2024-06-17] * Bumped typstyle to v0.11.26 by @Enter-tainer in https://github.com/Myriad-Dreamin/tinymist/pull/326 ### Compiler * (Fix): Handling the conversion of offset at the EOF in https://github.com/Myriad-Dreamin/tinymist/pull/325 * (Fix) Accumulating export events correctly in https://github.com/Myriad-Dreamin/tinymist/pull/330 ### Document Highlighting (New) * Highlighting all break points for that loop context in https://github.com/Myriad-Dreamin/tinymist/pull/317 ### On Enter (New) * Implemented `experimental/onEnter` in https://github.com/Myriad-Dreamin/tinymist/pull/328 ### Completion * Generating names for destructuring closure params by @wrenger in https://github.com/Myriad-Dreamin/tinymist/pull/319 ### Misc * Combined CompileClient and CompileClientActor by @QuarticCat in https://github.com/Myriad-Dreamin/tinymist/pull/318 * Simplified pin_entry by @QuarticCat in https://github.com/Myriad-Dreamin/tinymist/pull/320 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.10...v0.11.11 ## v0.11.10 - [2024-05-26] * Bumped typstyle to v0.11.23 by @Enter-tainer in https://github.com/Myriad-Dreamin/tinymist/pull/315 ### Editor * Transparentized the background of typst icon in https://github.com/Myriad-Dreamin/tinymist/pull/313 * Made more consistent font configuration in https://github.com/Myriad-Dreamin/tinymist/pull/312 ### Completion * Completing CSL paths in https://github.com/Myriad-Dreamin/tinymist/pull/310 ### Code Action * Checking and moving the exactly single punctuation after the math equation to refactor in https://github.com/Myriad-Dreamin/tinymist/pull/306 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.9...v0.11.10 ## v0.11.9 - [2024-05-18] * Bumped typst to 0.11.1 in https://github.com/Myriad-Dreamin/tinymist/pull/301 * Bumped to typstyle v0.11.21 by @Enter-tainer in https://github.com/Myriad-Dreamin/tinymist/pull/303 * Upgraded rust and set MSRV to 1.75 in https://github.com/Myriad-Dreamin/tinymist/pull/261 * Documented overview of tinymist in https://github.com/Myriad-Dreamin/tinymist/pull/274, https://github.com/Myriad-Dreamin/tinymist/pull/276, and https://github.com/Myriad-Dreamin/tinymist/pull/295 ### Editor * (Fix) Implicitly focusing entry on no focus request sent in https://github.com/Myriad-Dreamin/tinymist/pull/262 * Linking documentation to typst.zed for zed users in https://github.com/Myriad-Dreamin/tinymist/pull/268 ### Compiler * (Fix) Corrected order of def-and-use for named params in https://github.com/Myriad-Dreamin/tinymist/pull/281 ### AST Matchers * (Fix) Searching newline character in utf-8 bytes sequence with tolerating unaligned access in https://github.com/Myriad-Dreamin/tinymist/pull/299 * (Fix) Gets targets to check or deref without skip trivia node in non-code context in https://github.com/Myriad-Dreamin/tinymist/pull/289 * (Fix) Determining `is_set` for checking targets in https://github.com/Myriad-Dreamin/tinymist/pull/286 ### Commands/Tools * Resolved symbols for Symbol View Tool in compile-based approach in https://github.com/Myriad-Dreamin/tinymist/pull/269 * It is more robust and flexible than the previous approach. ### Completion * (Fix) properly stops call expressions in https://github.com/Myriad-Dreamin/tinymist/pull/273 * (Fix) completion path with ctx.leaf in https://github.com/Myriad-Dreamin/tinymist/pull/282 * (Fix) filter unsettable params when making a set rule in https://github.com/Myriad-Dreamin/tinymist/pull/287 * Removed literal themselves for completion in https://github.com/Myriad-Dreamin/tinymist/pull/291 - e.g. `#let x = (1.);`. it was completing `1.0`, which is funny. * Completing both open and closed labels in https://github.com/Myriad-Dreamin/tinymist/pull/302 ### Signature Help * (Fix) Matching labels in signature help correctly in https://github.com/Myriad-Dreamin/tinymist/pull/288 ### Code Action * Added simple code actions to manipulate equations in https://github.com/Myriad-Dreamin/tinymist/pull/258 ### Formatting * Fixed suffix computation by @QuarticCat in https://github.com/Myriad-Dreamin/tinymist/pull/263 ### Misc * Installing detypify service from npm in https://github.com/Myriad-Dreamin/tinymist/pull/275 and https://github.com/Myriad-Dreamin/tinymist/pull/277 * Implemented naive substitution for types (β-reduction) in https://github.com/Myriad-Dreamin/tinymist/pull/292 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.8...v0.11.9 ## v0.11.8 - [2024-05-07] ### Hover * Improved open document tooltip in https://github.com/Myriad-Dreamin/tinymist/pull/254 ### Completion * Inserting commas in argument context for completing before identifiers in https://github.com/Myriad-Dreamin/tinymist/pull/251 * Improved identifying literal expressions in https://github.com/Myriad-Dreamin/tinymist/pull/252 * Identifying let context completely in https://github.com/Myriad-Dreamin/tinymist/pull/255 * To help complete after equal marker in `let b = ..` * Restoring left parenthesis and comma as trigger characters in https://github.com/Myriad-Dreamin/tinymist/pull/253 * This is needed for completion on literal expressions. ### Type Checking * (Fix) Avoiding infinite loop in simplifying recursive functions in https://github.com/Myriad-Dreamin/tinymist/pull/246 * Fix a stack overflow in `ty.rs` * (Fix) Instantiating variable before applying variable function in https://github.com/Myriad-Dreamin/tinymist/pull/247 * Fix a deadlock in `ty.rs` * (Fix) Simplifying all substructure in https://github.com/Myriad-Dreamin/tinymist/pull/248 * Fix a panic in `ty.rs` * Improved join type inference in https://github.com/Myriad-Dreamin/tinymist/pull/249 * Weakening inference from outer use in https://github.com/Myriad-Dreamin/tinymist/pull/250 * to reduce noise slightly for completion **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.7...v0.11.8 ## v0.11.7 - [2024-05-05] ### Editor * Improved icons in https://github.com/Myriad-Dreamin/tinymist/pull/242 * Conditionally opening activity icon when lang id is typst by @Enter-tainer in https://github.com/Myriad-Dreamin/tinymist/pull/222 * (Fix) Symbol view issues in https://github.com/Myriad-Dreamin/tinymist/pull/224 * Disable inlay hints by default in https://github.com/Myriad-Dreamin/tinymist/pull/225 ### Completion * Triggering parameter hints instead of suggest on pos args in https://github.com/Myriad-Dreamin/tinymist/pull/243 * Showing label descriptions for labels in https://github.com/Myriad-Dreamin/tinymist/pull/228 and https://github.com/Myriad-Dreamin/tinymist/pull/237 * Showing graphic label descriptions for symbols in https://github.com/Myriad-Dreamin/tinymist/pull/227 and https://github.com/Myriad-Dreamin/tinymist/pull/237 * Showing label descriptions according to types in https://github.com/Myriad-Dreamin/tinymist/pull/237 * Filtering completions by module import in https://github.com/Myriad-Dreamin/tinymist/pull/234 * Filtering completions by surrounding syntax for elements/selectors in https://github.com/Myriad-Dreamin/tinymist/pull/236 ### Code Action (New) * Provided code action to rewrite headings in https://github.com/Myriad-Dreamin/tinymist/pull/240 ### Definition * Finding definition of label references in https://github.com/Myriad-Dreamin/tinymist/pull/235 ### Hover * Handled/Added link in the hover documentation in https://github.com/Myriad-Dreamin/tinymist/pull/239 ### Signature Help * Reimplemented signature help with static analyses in https://github.com/Myriad-Dreamin/tinymist/pull/241 ### Misc * Added template for feature request in https://github.com/Myriad-Dreamin/tinymist/pull/238 * Improved Dynamic analysis on import from dynamic expressions in https://github.com/Myriad-Dreamin/tinymist/pull/233 * Performing Type check across modules in https://github.com/Myriad-Dreamin/tinymist/pull/232 * Bumped to typstyle v0.11.17 by @Enter-tainer in https://github.com/Myriad-Dreamin/tinymist/pull/223 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.6...v0.11.7 ## v0.11.6 - [2024-04-27] ### Editor * Added more auto closing pairs, surrounding pairs, and characters that could make auto closing before in https://github.com/Myriad-Dreamin/tinymist/pull/209 * Hiding Status bar until the recent focus file is closed in https://github.com/Myriad-Dreamin/tinymist/pull/212 ### Compiler * (Fix) Removed a stupid debugging which may cause panic in https://github.com/Myriad-Dreamin/tinymist/pull/215 ### Commands/Tools * Completed symbol view in https://github.com/Myriad-Dreamin/tinymist/pull/218 * Not all symbols are categorized yet. If not, they are put into the "Misc" category. * It is now showing in the activity bar (sidebar). Feel free to report any issues or suggestions for improvement. **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.5...v0.11.6 ## v0.11.5 - [2024-04-20] ### Completion * Fixed wrong check of param completion position at comma in https://github.com/Myriad-Dreamin/tinymist/pull/205 * Completing text.lang/region in https://github.com/Myriad-Dreamin/tinymist/pull/199 * Completing array/tuple literals in https://github.com/Myriad-Dreamin/tinymist/pull/201 * New array types completed: columns/ros/gutter/column-gutter/row-gutter/size/dash on various functions * Completing function arguments on signatures inferred by type checking in https://github.com/Myriad-Dreamin/tinymist/pull/203 * Completing function arguments of func.where and func.with by its method target (this) in https://github.com/Myriad-Dreamin/tinymist/pull/204 * Completing functions with where/with snippets in https://github.com/Myriad-Dreamin/tinymist/pull/206 ### Inlay Hint * Checking variadic/content arguments rules of inlay hints correctly in https://github.com/Myriad-Dreamin/tinymist/pull/202 ### Syntax/Semantic Highlighting * (Fix) Corrected parsing on reference names of which trailing dots or colons cannot be followed by space or EOF in https://github.com/Myriad-Dreamin/tinymist/pull/195 * (Fix) Identifying string literals in math mode in https://github.com/Myriad-Dreamin/tinymist/pull/196 ### Misc * Bumped to typstyle v0.11.14 by @Enter-tainer in https://github.com/Myriad-Dreamin/tinymist/pull/200 * Preferring less uses of `analzer_expr` during definition analysis in https://github.com/Myriad-Dreamin/tinymist/pull/192 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.4...v0.11.5 ## v0.11.4 - [2024-04-14] This version is published with mostly internal optimizations. ### Editor * (Change) Renamed trace feature to profile feature in https://github.com/Myriad-Dreamin/tinymist/pull/185 ### Compiler * (Fix) Set entry state on changing entry in https://github.com/Myriad-Dreamin/tinymist/pull/180 * will cause incorrect label completion. ### Completion * Autocompleting with power of type inference in https://github.com/Myriad-Dreamin/tinymist/pull/183, https://github.com/Myriad-Dreamin/tinymist/pull/186, and https://github.com/Myriad-Dreamin/tinymist/pull/189 * See full list at https://github.com/Myriad-Dreamin/tinymist/blob/878a4146468b2a0e7a4435d7d0636df4f2133907/crates/tinymist-query/src/analysis/ty/builtin.rs * (Fix) slicing at an offset that is not char boundary in https://github.com/Myriad-Dreamin/tinymist/pull/188 ### Formatting * Bumped typstyle to v0.11.13 by @Enter-tainer in https://github.com/Myriad-Dreamin/tinymist/pull/181 ### Syntax/Semantic Highlighting * Provided better grammar on incomplete heading in https://github.com/Myriad-Dreamin/tinymist/pull/187 ### Misc * (Fix) Improved release profile & fix typos by @QuarticCat in https://github.com/Myriad-Dreamin/tinymist/pull/177 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.3...v0.11.4 ## v0.11.3 - [2024-04-06] ### Editor * (Fix) Skipped tabs that have no URIs for reopening pdf in https://github.com/Myriad-Dreamin/tinymist/pull/147 ### Compiler * ~~Evicting cache more frequently in https://github.com/Myriad-Dreamin/tinymist/pull/161~~ * Reverted in https://github.com/Myriad-Dreamin/tinymist/pull/173. * (Fix) Collecting warning diagnostics correctly in https://github.com/Myriad-Dreamin/tinymist/pull/169 ### Commands/Tools * Introduced summary page in https://github.com/Myriad-Dreamin/tinymist/pull/137, https://github.com/Myriad-Dreamin/tinymist/pull/154, https://github.com/Myriad-Dreamin/tinymist/pull/162, and https://github.com/Myriad-Dreamin/tinymist/pull/168 * Introduced symbol picker in https://github.com/Myriad-Dreamin/tinymist/pull/155 * Introduced periscope mode previewing in https://github.com/Myriad-Dreamin/tinymist/pull/164 * Introduced status bar for showing words count, also for compiling status in https://github.com/Myriad-Dreamin/tinymist/pull/158 * Supported tracing execution in current document in https://github.com/Myriad-Dreamin/tinymist/pull/166 ### Color Provider (New) * Added basic color providers in https://github.com/Myriad-Dreamin/tinymist/pull/171 ### Completion * (Fix) Performed correct dynamic analysis on imports in https://github.com/Myriad-Dreamin/tinymist/pull/143 * (Fix) Correctly shadowed items for completion in https://github.com/Myriad-Dreamin/tinymist/pull/145 * (Fix) Completing parameters in scope in https://github.com/Myriad-Dreamin/tinymist/pull/146 * Completing parameters on user functions in https://github.com/Myriad-Dreamin/tinymist/pull/148 * Completing parameter values on user functions in https://github.com/Myriad-Dreamin/tinymist/pull/149 * Triggering autocompletion again after completing a function in https://github.com/Myriad-Dreamin/tinymist/pull/150 * Recovered module completion in https://github.com/Myriad-Dreamin/tinymist/pull/151 ### Syntax/Semantic Highlighting * (Fix) Improved grammar on incomplete AST in https://github.com/Myriad-Dreamin/tinymist/pull/140 * (Fix) Correctly parsing label and reference markup in https://github.com/Myriad-Dreamin/tinymist/pull/167 ### Definition * Supported go to paths to `#include` statement in https://github.com/Myriad-Dreamin/tinymist/pull/156 ### Formatting * Bumped to typstyle v0.11.11 by @Enter-tainer in https://github.com/Myriad-Dreamin/tinymist/pull/163 * Added common print width configuration for formatters in https://github.com/Myriad-Dreamin/tinymist/pull/170 ### Hover (Tooltip) * Joining array of hover contents by divider for neovim clients in https://github.com/Myriad-Dreamin/tinymist/pull/157 ### Internal Optimization * Analyzing lexical hierarchy on for loops in https://github.com/Myriad-Dreamin/tinymist/pull/142 * depended by autocompletion/definition/references/rename APIs. **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.2...v0.11.3 ## v0.11.2 - [2024-03-30] ### Editor * (Fix) Passed correct arguments to editor tools in https://github.com/Myriad-Dreamin/tinymist/pull/111 * (Fix) exposed pin/unpin commands for vscode in https://github.com/Myriad-Dreamin/tinymist/pull/121 ### Compiler * (Fix) Converting out of bounds offsets again in https://github.com/Myriad-Dreamin/tinymist/pull/115 * Supported entry configuration in https://github.com/Myriad-Dreamin/tinymist/pull/122 * Supported untitled url scheme for unsaved text buffer in https://github.com/Myriad-Dreamin/tinymist/pull/120 and https://github.com/Myriad-Dreamin/tinymist/pull/130 ### Commands/Tools * Allowed tracing typst programs in subprocess in https://github.com/Myriad-Dreamin/tinymist/pull/112 * This is part of backend for tracing tool, and we may finish a tracing tool in next week. ### Formatting * Supported formatters in https://github.com/Myriad-Dreamin/tinymist/pull/113 * Use `"formatterMode": "typstyle"` for `typstyle 0.11.7` * Use `"formatterMode": "typstfmt"` for `typstfmt 0.2.9` * feat: minimal diff algorithm for source formatting in https://github.com/Myriad-Dreamin/tinymist/pull/123 ### Completion * Fixed wrong completion kind in https://github.com/Myriad-Dreamin/tinymist/pull/124 and https://github.com/Myriad-Dreamin/tinymist/pull/127 * Supported import path completion in https://github.com/Myriad-Dreamin/tinymist/pull/134 * Not completing on definition itself anymore in https://github.com/Myriad-Dreamin/tinymist/pull/135 ### Syntax/Semantic Highlighting * (Fix) Corrected identifier/keyword boundaries in https://github.com/Myriad-Dreamin/tinymist/pull/128 * Improved punctuation and keyword token kinds in https://github.com/Myriad-Dreamin/tinymist/pull/133 ### Hover (Tooltip) * (Fix) parse docstring dedents correctly in https://github.com/Myriad-Dreamin/tinymist/pull/132 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.1...v0.11.2 ## v0.11.1 - [2024-03-26] ### Editor * Integrated neovim support in https://github.com/Myriad-Dreamin/tinymist/pull/91 * docs: mention how to work with multiple-file projects in https://github.com/Myriad-Dreamin/tinymist/pull/108 * feat: add minimal helix support in https://github.com/Myriad-Dreamin/tinymist/pull/107 ### Compiler * (Fix) Always uses latest compiled document for lsp functions in https://github.com/Myriad-Dreamin/tinymist/pull/68 * (Fix) Converts EOF position correctly in https://github.com/Myriad-Dreamin/tinymist/pull/92 * Allowed running server on rootless files and loading font once in https://github.com/Myriad-Dreamin/tinymist/pull/94 * Uses positive system font config in https://github.com/Myriad-Dreamin/tinymist/pull/93 and https://github.com/Myriad-Dreamin/tinymist/pull/97 ### Syntax/Semantic Highlighting * Provided correct semantic highlighting in https://github.com/Myriad-Dreamin/tinymist/pull/71 * Provided correct syntax highlighting in https://github.com/Myriad-Dreamin/tinymist/pull/77, https://github.com/Myriad-Dreamin/tinymist/pull/80, https://github.com/Myriad-Dreamin/tinymist/pull/85, and https://github.com/Myriad-Dreamin/tinymist/pull/109 * Colorizes contextual bracket according to textmate scopes in https://github.com/Myriad-Dreamin/tinymist/pull/81 ### Commands/Tools * Fixed two bugs during initializing template in https://github.com/Myriad-Dreamin/tinymist/pull/65 * Added svg and png export in code lens context in https://github.com/Myriad-Dreamin/tinymist/pull/101 * Added tracing frontend in https://github.com/Myriad-Dreamin/tinymist/pull/98 * The frontend is implemented but there is trouble with the backend. ### Hover (Tooltip) * Provided hover tooltip on user functions in https://github.com/Myriad-Dreamin/tinymist/pull/76 * Parses comments for hover tooltip in https://github.com/Myriad-Dreamin/tinymist/pull/78 and https://github.com/Myriad-Dreamin/tinymist/pull/105 ### Misc * Provided dhat instrumenting feature for heap usage analysis in https://github.com/Myriad-Dreamin/tinymist/pull/64 * Disabled lto in https://github.com/Myriad-Dreamin/tinymist/pull/84 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.11.0...v0.11.1 ## v0.11.0 - [2024-03-17] ### Commands/Tools * Fixed [Template gallery index.html is not included in packaging](https://github.com/Myriad-Dreamin/tinymist/issues/59) in https://github.com/Myriad-Dreamin/tinymist/pull/60 ### Commands/Tools (New) * Added favorite function in template gallery in https://github.com/Myriad-Dreamin/tinymist/pull/61 * favorite or unfavorite by clicking a button. * filter list by favorite state. * get persist favorite state. * run `initTemplate` command with favorite state. * Initializing template in place is allowed in https://github.com/Myriad-Dreamin/tinymist/pull/62 * place the content of the template entry at the current cursor position. **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.10.3...v0.11.0 ## v0.10.3 - [2024-03-16] ### Commands/Tools (New) * support rest code lens in https://github.com/Myriad-Dreamin/tinymist/pull/45 * Preview * Preview in .. * `doc` or `slide` mode * `tab` or `browser` target * Export as .. * PDF format * add init template command in https://github.com/Myriad-Dreamin/tinymist/pull/50 * add template gallery as template picker in https://github.com/Myriad-Dreamin/tinymist/pull/52 ### References (New) * support find/goto syntactic references in https://github.com/Myriad-Dreamin/tinymist/pull/34 and https://github.com/Myriad-Dreamin/tinymist/pull/42 ### Autocompletion * upgrade compiler for autocompleting package in https://github.com/Myriad-Dreamin/tinymist/pull/30 ### Definition * dev: reimplements definition analysis in https://github.com/Myriad-Dreamin/tinymist/pull/43 ### Inlay Hint * implement inlay hint configuration in https://github.com/Myriad-Dreamin/tinymist/pull/37 * disable inlay hints on one line content blocks in https://github.com/Myriad-Dreamin/tinymist/pull/48 * dev: change position of inlay hint params in https://github.com/Myriad-Dreamin/tinymist/pull/51 ### Misc * supports vscode variables in configurations, more testing, and validation in https://github.com/Myriad-Dreamin/tinymist/pull/53 * You can set root/server/font path(s) with vscode variables. The variables are listed in https://www.npmjs.com/package/vscode-variables. ### Internal Optimization * deferred root resolution in https://github.com/Myriad-Dreamin/tinymist/pull/32 * allow fuzzy selection to deref targets in https://github.com/Myriad-Dreamin/tinymist/pull/46 * implements def-use analysis in https://github.com/Myriad-Dreamin/tinymist/pull/17, https://github.com/Myriad-Dreamin/tinymist/pull/19, https://github.com/Myriad-Dreamin/tinymist/pull/25, and https://github.com/Myriad-Dreamin/tinymist/pull/26 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.10.2...v0.10.3 ## v0.10.2 - [2024-03-12] * use implicit autocomplete in https://github.com/Myriad-Dreamin/tinymist/pull/3 * add the new context keyword in https://github.com/Myriad-Dreamin/tinymist/pull/6 * correctly drop sender after the server shutting down in https://github.com/Myriad-Dreamin/tinymist/pull/7 * support more foldable AST nodes in https://github.com/Myriad-Dreamin/tinymist/pull/11 **Full Changelog**: https://github.com/Myriad-Dreamin/tinymist/compare/v0.10.1...v0.10.2 ## v0.10.1 - [2024-03-11] Initial release corresponding to Typst v0.11.0-rc1.
https://github.com/lucifer1004/leetcode.typ
https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/problems/p0010.typ
typst
#import "../helpers.typ": * #import "../solutions/s0010.typ": * = Regular Expression Matching Given an input string s and a pattern p, implement regular expression matching with support for `'.'` and `'*'` where: - `'.'` Matches any single character.​​​​ - `'*'` Matches zero or more of the preceding element. The matching should cover the *entire* input string (not partial). #let regular-expression-matching(s, p) = { // Solve the problem here } #testcases( regular-expression-matching, regular-expression-matching-ref, ( (s: "aa", p: "a"), (s: "aa", p: "a*"), (s: "ab", p: ".*"), (s: "aab", p: "c*a*b"), (s: "mississippi", p: "mis*is*p*."), (s: "ab", p: ".*c"), (s: "ab", p: ".*c*"), (s: "香蕉x牛奶", p: "香.*牛.") ) )
https://github.com/skriptum/diatypst
https://raw.githubusercontent.com/skriptum/diatypst/main/README.md
markdown
MIT License
# Diatypst *easy slides in typst* Features: - easy delimiter for slides and sections (just use headings) - sensible styling - dot counter in upper right corner (like LaTeX beamer) - adjustable color-theme - default show rules for terms, code, lists, ... that match color-theme Example Presentation | Title Slide | Section | Content | Outline | | ----------------------------------------------- | --------------------------------------------------- | ----------------------------------------------- | ----------------------------------------------- | | ![Example-Title](screenshots/Example-Title.jpg) | ![Example-Section](screenshots/Example-Section.jpg) | ![Example-Slide](screenshots/Example-Slide.jpg) | ![Example-Section](screenshots/Example-TOC.jpg) | can be found in `example/example.typ`in the GitHub Repo ## Usage To start a presentation, initialize it in your typst document: ```typst #show: slides.with( title: "Diatypst", // Required subtitle: "easy slides in typst", date: "01.07.2024", authors: ("<NAME>"), ) ... ``` Then, insert your content. - Level-one headings corresponds to new sections. - Level-two headings corresponds to new slides. ```typst ... #outline() = First Section == First Slide #lorem(20) ``` ## Options all available Options to initialize the template with | Keyword | Description | Default | | ------------- | ------------------------------------------------------------ | -------------------- | | *title* | Title of your Presentation, visible also in footer | `none` but required! | | *subtitle* | Subtitle, also visible in footer | `none` | | *date* | a normal string presenting your date | `none` | | *authors* | either string or array of strings | `none` | | *layout* | one of "small", "medium", "large", adjusts sizing of the elements on the slides | `"medium"` | | *ratio* | aspect ratio of the slides, e.g 16/9 | `4/3` | | *title-color* | Color to base the Elements of the Presentation on | `blue.darken(50%)` | | *counter* | whether to display the dots for pages in upper right corner | `true` | | *footer* | whether to display the footer at the bottom | `true` | | *toc* | whether to display the table of contents | `true` | | *code-styling*| whether to style code elements in the presentation | `true` | ## Inspiration this template is inspired by [slydst](https://github.com/glambrechts/slydst), and takes part of the code from it. If you want simpler slides, look here! The word *Diatypst* is inspired by the ease of use of a [**Dia**-projektor](https://de.wikipedia.org/wiki/Diaprojektor) (German for Slide Projector) and the [Diatype](https://en.wikipedia.org/wiki/Diatype_(machine))
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/image-07.typ
typst
Other
// Error: 8-21 unknown image format #image("./image.typ")
https://github.com/Ttajika/class
https://raw.githubusercontent.com/Ttajika/class/main/seminar/lib/useful_package.typ
typst
#import "@preview/showybox:2.0.1": showybox
https://github.com/pku-typst/PKU-typst-template
https://raw.githubusercontent.com/pku-typst/PKU-typst-template/main/templates/通用/作业/example.typ
typst
MIT License
#import "@local/PKU-Typst-Template:0.1.0": 通用作业 #set text(lang: "zh") #show: 通用作业.config.with( course_name: "实验测试中的测试方法", student_id: 2200011001, student_name: "张测试", hw_no: 14, ) #let QED = sym.square.stroked #通用作业.hw_prob("习题 11.4")[ 已知若 $p$ 为真则 $q$ 为真, 给定 $q$ 为假求证 $p$ 为假 ][ 显然 #QED ]
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Research/Summer%202024/Geometry%20School/Minimal%20cones.typ
typst
#import "/Templates/generic.typ": latex #import "/Templates/notes.typ": chapter_heading #import "@preview/ctheorems:1.1.0": * #import "/Templates/math.typ": * #show: latex #show: chapter_heading #show: thmrules #show: symbol_replacing //#show: equation_references //#show: equation_numbering #set pagebreak(weak: true) #set page(margin: (x: 2cm, top: 2cm, bottom: 2cm), numbering: "1") #set enum(numbering: "(1)", indent: 1em) #set heading(supplement: "Lecture") #show heading: it => { if (it.numbering == none or it.level > 1) { return it } let numbers = counter(heading).at(it.location()) let body = it.body block([*#body*]) } #outline() = Lecture 1 Let $Omega$ be an open set in $RR^(n+1)$ and let $V$ be a compactly supported vector field on $Omega$. Let $Phi_t^V : Omega -> Omega$ be the flow generated by $V$. Now let $Sigma$ be a hypersurface in $Omega$ and assume that $iota : Sigma -> Omega$ is proper. We say that $Sigma$ is minimal if $ d / (d t) Area(Phi_t^V (Sigma)) = 0 $ for any admissable $V$ as above. In other words, $Sigma$ is a critical point of the area functional. One can check that $ d / (d t) Area(Phi_t^V (Sigma)) = integral_Sigma div_Sigma V dif mu $ where at any point $p$, $div_Sigma V = sum_(i = 1)^n D_(e_i) V dot e_i$ for any orthonormal frame centered at $p$. Now we have $ integral_Sigma div_Sigma V dif mu = integral_Sigma div_Sigma (V^top + V^perp) = integral_Sigma div_Sigma V^top + integral_Sigma div_Sigma V^perp = integral_Sigma div_Sigma V^perp $ since the first integral vanishes by divergence theorem. On the other hand we have $ div_Sigma V^perp = div_Sigma ((V dot nu) nu) = sum_i^n (D_e_i nu dot e_i) ( V dot nu ) = - arrow(H)_Sigma dot V $ so $Sigma$ is minimal if and only if $arrow(H)_Sigma = 0$. == Monotonicity of Area Ratios Assume that $Sigma$ is a proper minimal hypersurface in $Omega seq RR^(n+1)$, we will call $ Psi_(Sigma,x_0) (R) = (|Sigma sect B_R (x_0)|) / (R^n) $ the _area ratio_, and its importance is due to its Monotonicity: For $R_2 > R_1$ $ Psi_(Sigma, x_0) (R_2) - Psi_(Sigma, x_0) (R_1) = integral_(B_R_2 ( x_0 ) backslash B_R_1 (x_0) sect Sigma) (|(x-x_0)^perp|^2) / (|x-x_0|^(n+2)) $ as long as $ov(B_R_2 (x_0)) seq Omega$. In particular, if $Psi_(Sigma, X_0) (R)$ is independent of $R$ then $(x - x_0)^perp = 0$ in $Sigma$, which is equivalent to $Sigma$ being a cone with vertex at $x_0$. Let $rho_i -> infinity$ and $Sigma_i = rho_i (Sigma - x_0)$, clearly $Sigma_i$ is also a minimal hypersurface. Then up to passing to a subsequence, this sequence converges weakly (in the sense of measures) to a hypersurface $Sigma_infinity$ which is minimal in $RR^n$ and $ Psi_(Sigma_infinity, 0) (R) = lim_(i -> infinity) Psi_(Sigma_i, 0) (R) = lim_(i -> infinity) Psi_(Sigma, x_0) (rho_i^(-1) R) $ which always exists and is independent of $R$, so $Sigma_infinity$ is a minimal cone. The density of a minimal cone $phi$ is defined by $ Theta(phi) := Psi_(phi, 0) (1) omega_n^(-1) $ where $omega_n$ is the volume of a ball in $RR^n$. This normalization is picked so that $Theta(RR^n) = 1$. #lemma[ The hyperplane $RR^n$ minimizes density, in the sense that $ Theta(Sigma) >= 1 $ for all hypersurfaces $Sigma$, and equality holds iff $Sigma$ is a hyperplane. ] #exercise[ Prove this. ] A natural question then is, which minimal cone has the second least density? It is non obvious that such a cone exists, but in fact we have a regularity theorem that implies this. #theorem("Allard's Regularity")[ There's an $epsilon(n) > 0$ so that if $C$ is a minimal cone in $RR^(n+1)$ and if $C != RR^n$ then $ Theta(C) > 1 + epsilon. $ ] Now an important characterization of minimal cones is the following. #lemma[ If $C$ is a minimal cone iff the link $L(C) = C sect S^n$ is a minimal hypersurface in $S^n$. ] This gives us a natural family of minimal cones arising from the family of minimal hypersurfaces in $S^n$, called the Clifford Tori, defined as $ Gamma_(m,ell) = S^n (sqrt(m/(m + ell))) times S^n (sqrt(ell/(m + ell))). $ #conjecture("Solomon")[ The minimal cones $C_(m, ell)$ which are the cones over $Gamma_(m, ell)$, minimize the density of non-flat minimal cones. ]<conj-solomon> The density of these cones is given by $ Theta(C_(m, ell)) = (sigma_m sigma_ell) / (sigma_(m + ell)) ( m / (m+ell) )^(m / 2) (ell / (m+ell))^(ell / 2) $ where $sigma_k$ is the volume of a unit $k$-sphere. One can check that $lim_(ell "or" m -> infinity) Theta(C_(m, ell)) = sqrt(2)$. @conj-solomon is true for $n = 3$. By a result of Almgren, If $C seq RR^4$ is a minimal cone with $L(C)$ a smooth embedded surface of genus $0$ then $C = RR^3$. By a result of Marques–Neves, in the other case we have $Theta(C) >= Theta(C_(1,1)) = pi/2$, equality if and only if $C = C_(1,1)$ = Lecture 2 We will now start exploring the connection between minimal cones and mean curvature flow, first notice that minimal cones are static solutions to mean curvature flow. Another important property of minimal cones is that the density we defined earlier coincides with the limit of Gaussian area introduced in the other lecture. In fact to better get a handle on this area we can also define the Colding-Minicozzi entropy $ lambda(Sigma) = sup_(x_0 in RR^(n+1), t_0>0) (4pi t_0)^(- n / 2) integral_sigma e^(- (|x-x_0|^2) / (4 t_0)) dif mu (x) $ #proposition[ + For any hypersurface we have $lambda(Sigma) >= 1$ + For any $y in RR^(n+1)$ we have $lambda(Sigma + y) = lambda(Sigma)$. + $lambda(Sigma times RR) = lambda(Sigma)$. + If $t |-> Sigma_t$ is a MCF then $t -> lambda(Sigma_t)$ is non-increasing. ] A hypersurface $sigma$ is called a self-shrinker if $arrow(H)_sigma + x^perp/2 = 0$. Any minimal cone is a self-shrinker. The hyperplane, spheres and cylinders are all self-shrinkers. Angenent's torus and min-max shrinkers are other examples. We also construct them by desingularization. #theorem[ The entropy stable shrinkers are $RR^n, S^n, S^r times RR^(n - r)$. ] = Lecture 3 We will now begin discussing asymptotically conical shrinkers. These are MCFs with $M_t = sqrt(-t) Sigma$ and $M_t -> C$ as $t -> 0$ where $C$ is a cone. The first thing we want to think is how to continue the flow at $t = 0$. We will define $Gamma_tau = 1/(sqrt(t)) Sigma_t$ where $tau = log t$ and we have $ (diff_tau X)^perp = H_(Gamma_tau) - x^perp / 2. $<eqn-rescaled_mcf> This is in fact the gradient flow for $ E(Gamma) = integral_Gamma e^((|x|^2) / 4) $ and the critical points of $E$ are static solutions to the evolution equation above, namely $ H_(Gamma_t) - x^perp / 2 = 0. $ Such solutions are called expanders. Clearly every minimal cone is an expander. #remark[ There do not exist any compact expanders, one can see this by deriving the equation for $x^2$ (??) on an expander and apply maximum principle. ] #theorem("Bernstein-W")[ There's an open set of cones in $RR^3$ so that for each cone $C$ in the set there are at least 3 expanders asymptotic to $C$. ] #theorem("Ding-Ilmanen")[ For $n <= 6$, given a cone $C seq RR^(n+1)$ with smooth embedded link, there is an expander asymptotic to $C$. ] #theorem[ For $n <= 6$, given a minimal cone $C$ with smooth embedded link, there are two expanders $Sigma_+$ and $Sigma_-$ both asymptotic to $C$ lying on either side of $C$, and both have a sign. ] #remark[ Since they both have a sign, and since they both have $ x^perp / 2 = H_(Sigma_(plus.minus)) $ then they are both radial over a sphere. ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/040_Zendikar%20Rising.typ
typst
#import "@local/mtgset:0.1.0": conf #show: doc => conf("Zendikar Rising", doc) #include "./040 - Zendikar Rising/001_Episode 1: In the Heart of the Skyclave.typ" #include "./040 - Zendikar Rising/002_Red Route.typ" #include "./040 - Zendikar Rising/003_Episode 2: Race to the Murasa Skyclave.typ" #include "./040 - Zendikar Rising/004_The Magosi Steps.typ" #include "./040 - Zendikar Rising/005_Episode 3: The Dangerous Climb, the Long Fall.typ" #include "./040 - Zendikar Rising/006_Beneath Riverroot Tree.typ" #include "./040 - Zendikar Rising/007_Episode 4: Of Haunting Songs and Whispered Warnings.typ" #include "./040 - Zendikar Rising/008_Hunger.typ" #include "./040 - Zendikar Rising/009_Episode 5: The Two Guardians.typ"
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/zalmy/Z103.typ
typst
Dobroreč, duša moja, Pánovi; \* Pane, Bože môj, ty si nesmierne veľký. Odel si sa do slávy a veleby, \* do svetla si sa zahalil ako do rúcha. Nebesia rozpínaš ako stan, \* nad vodami si buduješ komnaty. Po oblakoch vystupuješ ako po schodoch, \* na krídlach vánku sa prechádzaš. Vetry sú tvojimi poslami, \* ohnivé plamene tvojimi služobníkmi. Zem si postavil na jej základoch, \* nevychýli sa nikdy, nikdy. Oceán ju prikryl sťa odev, \* nad vrchmi vody zastali. Pred tvojou hrozbou odtiekli, \* zhrozili sa pred tvojím hlasom hromovým. Vybehli na vrchy, stiekli do údolia, \* na miesto, ktoré si im vyhradil. Položil si hranicu a neprekročia ju \* ani viac nepokryjú zem. Prameňom dávaš stekať do potokov, \* čo tečú pomedzi vrchy a napájajú všetku poľnú zver \* aj divým oslom hasia smäd. Popri nich hniezdi nebeské vtáctvo, \* spomedzi konárov zaznieva ich pieseň. Zo svojich komnát zvlažuješ vrchy, \* plodmi svojich diel sýtiš zem. Tráve dávaš rásť pre ťažný dobytok \* a byli, aby slúžila človeku. Zo zeme vyvádzaš chlieb i víno, \* čo obveseľuje srdce človeka; olejom rozjasňuješ jeho tvár \* a chlieb dáva silu srdcu človeka. Sýtia sa stromy Pánove \* aj cédre Libanonu, čo on zasadil. Na nich si vrabce hniezda stavajú \* a na ich vrcholcoch bývajú bociany. Vysoké štíty patria kamzíkom, \* v skalách sa skrývajú svište. Na určovanie času si Mesiac utvoril; \* Slnko vie, kedy má zapadať. Prestieraš tmu a nastáva noc, \* a povylieza všetka lesná zver. Levíčatá ručia za korisťou \* a pokrm žiadajú od Boha. Len čo vyjde slnko, utiahnu sa \* a ukladajú sa v svojich dúpätách. Vtedy sa človek ponáhľa za svojím dielom, \* za svojou prácou až do večera. Aké mnohoraké sú tvoje diela, Pane! \* Všetko si múdro urobil. Zem je plná tvojho stvorenstva. Tu more veľké, dlhé a široké, \* v ňom sa hemžia plazy bez počtu, živočíchy drobné i obrovské. Po ňom sa plavia lode \* i Leviatan, ktorého si stvoril, aby sa v ňom ihral. Všetko to čaká na teba, \* že im dáš pokrm v pravý čas. Ty im ho dávaš a ony ho zbierajú; \* otváraš svoju ruku, sýtia sa dobrotami. Len čo odvrátiš svoju tvár, už sa trasú; \* odnímaš im dych a hneď hynú, a vracajú sa do prachu. Keď zošleš svojho ducha, sú stvorené, \* a obnovuješ tvárnosť zeme. Pánova chvála nech trvá naveky; \* zo svojich diel nech sa teší Pán. Pozrie sa na zem a rozochvieva ju, \* dotkne sa vrchov a ony chrlia dym. Po celý život chcem spievať Pánovi \* a svojmu Bohu hrať, kým len budem žiť. Kiež sa mu moja pieseň zapáči; \* a ja sa budem tešiť v Pánovi. Nech zo zeme zmiznú hriešnici a zločincov nech už niet. \* Dobroreč, duša moja, Pánovi. Slnko vie, kedy má zapadať, \* prestieraš tmu a nastáva noc. Aké mnohoraké sú tvoje diela, Pane! \* Všetko si múdro urobil.\
https://github.com/valentinvogt/npde-summary
https://raw.githubusercontent.com/valentinvogt/npde-summary/main/src/chapters/09.typ
typst
#import "../setup.typ": * #show: thmrules = Second-Order Linear Evolution Problems <ch:9> #counter(heading).update((9, 1)) == Parabolic Initial-Boundary Value Problems <sub:parabolic-ivps> === Heat Equation <sub:heat-equation> In local form the heat equation is given by #neq( $ frac(partial, partial t) (rho u) - div (kappa (bx) grad u) = f quad upright("in ") tilde(Omega) = Omega times openint(0, T) $, ) <eq:heat-local> where $u$ is the temperature, $rho$ the heat capacity, $kappa$ the heat conductivity and $f$ a (time-dependent) heat source/sink. Without the time derivative, this looks very similar to standard PDEs, for which we know the transformation into a nice variational problem. To solve it we still need boundary conditions. Besides the boundary conditions of the spatial domain --- which are now required for all times --- one also needs initial conditions over the whole domain at time 0. #neq( $ u (bx , t) & = g (bx , t) quad upright("for ") (bx , t) in partial Omega times openint(0, T)\ u (bx , 0) & = u_0 (bx) quad upright("for all ") bx in Omega $, ) <eq:heat-bc-ic> Testing with time-independent test functions $v$ and assuming $rho$ to be time-independent as well, we get to #neq( $ integral_Omega rho (bx) dot(u) v dif bx + integral_Omega kappa (bx) med grad u dot.op grad v dif bx = integral_Omega f (bx , t) thin v dif bx quad forall v in H_0^1 (Omega)\ u (bx , 0) = u_0 (bx) in H_0^1 (Omega) $, ) <eq:heat-integral-form> with the shorthand notation $ m (dot(u) , v) & = integral_Omega rho (bx) med dot(u) med v dif bx\ a (u , v) & = integral_Omega kappa (bx) med grad u dot.op grad v dif bx\ ell (v) & = integral_Omega f (bx , t) med v dif bx $ and the realization that $m (dot(u) , v) = frac(dif, dif t) m (u , v)$ because only $u$ depends on time (note that importantly, the domain $Omega$ also stays constant) we can rewrite @eq:heat-integral-form as #neq($ frac(dif, dif t) m (u , v) + a (u , v) = ell (v) $) <eq:heat-short> which looks like something we know how to solve from NumCSE. #pagebreak() #counter(heading).update((9, 2, 2)) === Stability #lemma( number: "9.2.3.8.", "Decay of solutions of parabolic evolutions", )[ $colMath("If " f equiv 0, accentcolor)$, the solution $u (t)$ of the heat equation @eq:heat-integral-form satisfies $ norm(u (t))_m lt.eq e^(- gamma t) norm(u_0)_m , quad norm(u (t))_a lt.eq e^(- gamma t) norm(u_0)_a quad forall t in openint(0, T) $ where $gamma = upright("diam") (Omega)^(- 2)$. ] Note that this lemma also tells us that if $f$ is time-independent, the solution $u (t)$ converges exponentially (in time) to the stationary solution (the solution of @eq:heat-short without the $m (dot.op , dot.op)$ part). === Method of Lines Now let's look into how we can solve @eq:heat-short. First, we apply the Galerkin discretization. As $u$ is now also time-dependent, we let the coefficients of $u$ (and not the basis) depend on time. $ u_h (t) = sum_(i = 1)^N mu_i (t) b_h^i $ Combining this with @eq:heat-short, we get #neq( $ bold(M) {frac(dif, dif t) arrow(mu) (t)} + bA arrow(mu) (t) & = arrow(phi) (t)\ arrow(mu) (0) & = arrow(mu)_0 $, ) <eq:heat-galerkin> where $bold(M)_(i , j) = m (b_h^j , b_h^i)$, $bA_(i , j) = a (b_h^j , b_h^i)$ and $[arrow(phi) (t)]_i = ell (b_h^i)$. This is now an ODE with respect to time and can be solved by time-stepping, learned in NumCSE. #strong[Recall ODEs] An ODE is given as $ bold(dot(u)) = bold(f \() t , bold(u) \) $ and is called linear if $bold(f \() t , bold(u) \) = bA (t) bold(u)$. There is an evolution operator associated with the ODE, defined as $Phi^(t_0 , t) u_0 = u (t)$. There are some methods to approximate the evaluation operator with a discrete evolution operator $Psi$. - explicit Euler: $Psi^(t , t + tau) bu = bu + tau bold(f) \( t , bu \)$ - implicit Euler:$Psi^(t , t + tau) bu = bw \, bw = bu + tau bold(f) \( t + tau , bold(w) \)$ - implicit midpoint: $Psi^(t , t + tau) bu = bw \, bw = bu + tau bold(f) \( t + 1 / 2 tau , 1 / 2 (bold(w + u \)))$ Hence we can calculate the time evolution by the sequence $ bold(u)^((0)) = bold(u)_0 , quad bold(u)^((j)) = Psi^(t_(j - 1) , t_j) bold(u)^((j - 1)) , quad j = 1 , dots.h , M $ As $Psi$ is the discrete approximation, the question about the error is immediate. One usually considers - the error at final time: $eps_M = norm(bold(u) (T) - bold(u)^((M)))$ - maximum error in the sequence: $eps_oo = max_j norm(bold(u)^((j)) - bold(u) (t_j))$ #theorem( number: "9.2.6.14", "Convergence of single-step methods", )[ Given the above sequence of solutions, obtained by a single-step method of order $q in bb(N)$, then $ eps_oo = max_j norm(bold(u)^((j)) - bold(u) (t_j)) lt.eq C tau^q $ with $tau = max_j lr(|t_j - t_(j - 1)|)$. ] #strong[Runge--Kutta Single-Step Methods] #definition( number: "7.3.3.1", [General Runge--Kutta single-step method], )[ For coefficients $b_i , a_(i , j) in bb(R) , c_i = sum_(j = 1)^s a_(i , j)$, the discrete evolution operator $Psi^(s , t)$ of an #strong[s-stage Runge--Kutta single-step method] (RK-SSM) for the ODE $bold(dot(u)) = bold(f \() t , bold(u) \)$ is defined by $ bold(k)_i = bold(f) (t + c_i tau , bold(u) + tau sum_(j = 1)^s a_(i , j) bold(k)_j) , quad i = 1 , dots.h , s , quad Psi^(t , t + tau) bold(u) = bold(u) + tau sum_(j = 1)^s b_j bold(k)_j $ with $bold(k)_j$ the increments. ] The RK-SSM methods can be written down in compact form (the butcher scheme) as #set math.mat(gap: 1em) #neq( $ mat( bold(c), bold(frak(A));"", bold(b);delim: #none, augment: #(hline: 1, vline: 1, stroke: 1pt), ) $, ) <eq:butcher> where $bold(c)$ is a vector containing the coefficients $c_i$, $bold(b)$ the coefficients $b_i$ and $bold(frak(A))$ a matrix containing the coefficients $a_(i , j)$. So continuing from @eq:heat-galerkin with different time-stepping schemes, we get - explicit Euler: $ arrow(mu)^((j)) = arrow(mu)^((j - 1)) + tau_j bold(M)^(- 1) (arrow(phi) (t_(j - 1)) - bA arrow(mu)^((j - 1))) $ - implicit Euler: $ arrow(mu)^((j)) = (tau_j bA + bold(M))^(- 1) (bold(M) arrow(mu)^((j - 1)) + tau_j arrow(phi) (t_(j - 1))) $ - implicit midpoint (Crank-Nicolson) $ arrow(mu)^((j)) = (bold(M) + 1 / 2 bA)^(- 1) tau_j ((bold(M) - 1 / 2 bA) arrow(mu)^((j - 1)) + 1 / 2 (arrow(phi) (t_j) + arrow(phi) (t_(j - 1)))) $ These all involve solving a linear system of equations each time-step. However, note that the matrices to invert stay constant with respect to time, so need to calculate the decomposition just once. Using a general RK-SSM method for time-stepping, we get the following system of equations $ bold(M) arrow(kappa)_i + sum_(m = 1)^s tau a_(i , m) bA arrow(kappa)_m & = arrow(phi) (t_j + c_i tau) - bA arrow(mu)^((j))\ arrow(mu)^((j + 1)) & = arrow(mu)^((j)) + tau sum_(m = 1)^s b_m arrow(kappa)_m $ With the Kronecker product, this can be rewritten as $ (bold(I)_s times.circle bold(M) + tau bold(frak(A)) times.circle bA) mat(delim: "[", arrow(kappa)_1;dots.v;arrow(kappa)_s) = mat( delim: "[", arrow(phi) (t_j + c_1 tau) - bA arrow(mu)^((j));dots.v;arrow(phi) (t_j + c_s tau) - bA arrow(mu)^((j)), ) $ which can be used to solve for the increments $arrow(kappa)_i$. Recall stiff initial value problems: #mybox( "Stiffness", )[ An initial value problem is called stiff if stability imposes much tighter time-step constraints on explicit single-step methods than the accuracy requirements. ] To study the stiffness of the method of lines, we first diagonalize it. For @eq:heat-galerkin let $arrow(psi)_1 , dots.h , arrow(psi)_N$ denote the $N$ linearly independent generalized eigenvectors satisfying $ bA arrow(psi)_i = lambda_i bold(M) arrow(psi)_i , quad (arrow(psi)_j)^top bold(M) arrow(psi)_i = delta_(i j) $ with positive eigenvalues $lambda_i$. With $bold(T) = [arrow(psi)_1 , dots.h , arrow(psi)_N]$ and $bold(D) = upright("diag") (lambda_1 , dots.h , lambda_N)$, this can be rewritten as $ bold(A T = M T D \, quad T^top M T = I) $ The existence of eigenvectors with positive eigenvalues is guaranteed, as $bold(A \, M)$ are positive (semi)definite. Thus with a change of basis to the eigenvector basis, one can diagonalize @eq:heat-galerkin. $ arrow(mu) (t) = sum_k eta_k (t) arrow(psi)_k arrow.l.r.double arrow(mu) (t) = bold(T) arrow(eta) (t) arrow.l.r.double bold(T^top M) arrow(mu) (t) = arrow(eta) (t)\ arrow.r bold(M T) frac(dif, dif t) arrow(eta) (t) + bold(M T D) arrow(eta) (t) = arrow(phi) (t)\ arrow.r frac(dif, dif t) arrow(eta) (t) + bold(D) arrow(eta) (t) = bold(T)^top arrow(phi) (t) $ As $bold(D)$ is diagonal, this amounts to $N$ decoupled scalar ODEs. On those, we can perform our analysis more easily. In NumCSE you have seen that both Euler and Crank-Nicolson can be rewritten as a RK-SSM with appropriate coefficients, so we can study the stability of the general RK-SSM for the scalar case. For $dot(u) = - lambda u$, with the butcher scheme @eq:butcher we obtain $Psi_lambda^(t , t + tau) u = S (- lambda tau) u$, with the stability function $ S (z) = 1 + z bold(b)^top (I - z bold(frak(A)))^(- 1) bold(1) = frac( upright("det") (bold(I) - z bold(frak(A)) + z bold(b 1)^top), upright("det") (bold(I) - z bold(frak(A))), ) $ #strong[Unconditional stability of single-step methods] A necessary condition for unconditional stability of a single-step method, is that the discrete evolution operator $Psi_lambda^t$ applied to the scalar ODE $dot(u) = - lambda u$ satisfies $ lambda > 0 arrow.r lim_(j arrow.r oo) (Psi_lambda^tau)^j u_0 = 0 , quad forall u_0 , forall tau > 0 $ #definition( number: "9.2.7.46", "L-stability", )[ An RK-SSM satisfying the above condition, is called L-stable if its stability function satisfies $ lr(|S (z)|) < 1 , forall z < 0 upright(" and ") S (- oo) = lim_(z arrow.r - oo) S (z) = 0 $ ] Plugging $- oo$ int $S$ we obtain $S (- oo) = 1 - bold(b)^top bold(frak(A))^(- 1) bold(1)$, which is equal to zero if $bold(b)$ is equal to the last row of $bold(frak(A))$. #theorem( number: "9.2.8.5", [Meta-theorem --- Convergence of fully discrete evolution], )[ Assume that - the solution of the parabolic IBVP is "sufficiently smooth" - its spatial Galerkin finite element discretization relies on degree $p$ Lagrangian finite elements on uniformly shape-regular families of meshes - time-stepping is based on an L-stable single-step method of order $q$, then we can expect an asymptotic behavior of the total discretization error according to $ (tau sum_(j = 1)^M lr(|u (tau j) - u_h^((j))|)_(H^1 (Omega))^2)^(1 / 2) lt.eq C (h_(msh)^p + tau^q) $ ] Hence the total error is the spatial error plus the temporal error. == Linear wave equations <sub:linear-wave-equations> In local form, the (linear) wave equation is given by #neq( $ rho (bx) frac(partial^2, partial t^2) u - div (sigma (bx) grad u) = f quad upright("in ") tilde(Omega) $, ) <eq:wave-strong> Note the similarity to the heat equation @eq:heat-local. Since the wave equation is a second order ODE $accent(bold(u), dot.double) = bold(f (u))$, two initial conditions are needed. In addition to the initial conditions @eq:heat-bc-ic, the initial velocity $ frac(partial, partial t) u (bx , 0) = v_0 (bx) quad upright("for all ") bx in Omega $ is also needed. We want to use the time-stepping schemes we already know. To apply them, the wave function can be converted into a first order ODE: $ dot(u) & = v\ rho dot(v) & = div (sigma (bx) grad u) $ Remember from calculus that the particular wave equation $frac(partial^2, partial t^2) u - c^2 frac(partial^2, partial x^2) u = 0$ in 1D results in the d'Alembert solution: $ u (x , t) = 1 / 2 (u_0 (x + c t) + u_0 (x - c t)) + frac(1, 2 c) integral_(x - c t)^(x + c t) v_0 (s) dif s $ with $u_0$ and $v_0$ the initial conditions. Hence there is again the concept of domain of dependence and domain of influence. This will be important later. Furthermore, in the absence of a source term, as in the simple case above, the solution will stay undamped. This corresponds to #emph[conservation of total energy];. We can formulate the variational problem: #neq($ m (accent(u, dot.double) , v) + a (u , v) = 0 quad forall v in V_0 $) <eq:wave-variational> #theorem( number: "9.3.2.16", "Energy conservation in wave propagation", )[ If $u$ solves @eq:wave-variational, then its energy is conserved, in the sense that $ 1 / 2 m (frac(partial, partial t) u , frac(partial, partial t) u) + 1 / 2 a (u , u) equiv upright("const") $ where $1 / 2 m (frac(partial, partial t) u , frac(partial, partial t) u)$ can be understood as the 'kinetic' energy and $1 / 2 a (u , u)$ as the 'potential' energy. ] #counter(heading).update((9, 3, 2)) === Method of Lines <sub:method-of-lines> The method of lines gives rise to $ bold(M) {frac(d^2, d t^2) arrow(mu) (t)} + bA arrow(mu) (t) & = arrow(phi) (t)\ arrow(mu) (0) = arrow(mu)_0 , frac(dif, dif t) arrow(mu) (0) & = arrow(nu)_0 $ Using $arrow(nu) = dot(arrow(mu))$, we can rewrite it to be a first order ODE. $ frac(dif, dif t) arrow(mu) & = arrow(nu)\ bold(M) frac(dif, dif t) arrow(nu) & = arrow(phi) (t) - bA arrow(mu)\ arrow(mu) (0) & = arrow(mu)_0 , arrow(nu) (0) = arrow(nu)_0 $ Remember that in the case of $arrow(phi) equiv 0$, energy is conserved: $ E_h (t) = 1 / 2 frac(dif, dif t) arrow(mu)^top bold(M) frac(dif, dif t) arrow(mu) + 1 / 2 arrow(mu)^top bA arrow(mu) equiv upright("const") $ So we would like a time-stepping that preserves this. Such time-stepping schemes are called #emph[structure preserving];. One such time-stepping scheme is the #strong[Crank–Nicolson] one: $ bold(M) frac(arrow(mu)^((j + 1)) - 2 arrow(mu)^((j)) + arrow(mu)^((j - 1)), tau^2) = - 1 / 2 bA (arrow(mu)^((j - 1)) + arrow(mu)^((j + 1))) + 1 / 2 (arrow(phi) (t_j - 1 / 2 tau) + arrow(phi) (t_j + 1 / 2 tau)) $ #pagebreak() Another one would be the #strong[Störmer scheme];: $ bold(M) frac(arrow(mu)^((j + 1)) - 2 arrow(mu)^((j)) + arrow(mu)^((j - 1)), tau^2) = - bA arrow(mu)^((j)) + arrow(phi) (t_j) $ For both of these #emph[second order] time-stepping schemes, we need $arrow(mu)^((- 1))$ to get $arrow(mu)^((1))$. Now the question is, where do we get this from? It can be obtained with a special initial step, using a symmetric (first order) difference quotient: $ frac(dif, dif t) arrow(mu) (0) = arrow(nu)_0 arrow.r frac(mu^(\(1\)) - mu^((- 1)), 2 tau) = arrow(nu)_0 $ And finally there is the #strong[Leapfrog] time-stepping. Using the auxiliary variable $arrow(nu)^((j + 1 \/ 2)) = frac(arrow(mu)^((j + 1)) - arrow(mu)^((j)), tau)$ and inserting this into the Störmer scheme results in $ bold(M) frac(arrow(nu)^((j + 1)) - arrow(nu)^((j)), tau) & = - bA arrow(mu)^((j)) + arrow(phi) (t_j)\ frac(arrow(mu)^((j + 1)) - arrow(mu)^((j)), tau) & = arrow(nu)^((j + 1 \/ 2)) $ with the initial step $arrow(nu)^((- 1 \/ 2)) + arrow(nu)^((1 \/ 2)) = 2 arrow(nu)_0$.
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas3/3_Streda.typ
typst
#let V = ( "HV": ( ("", "Vélija krestá tvojehó", "Tvár izminísja Slóve, raspjátijem tvojím, sólnce lučý sprjáta stráchom, i chráma zavísa razdrásja, i vsják vírnyj spasésja. Ťímže slávim tvojé bezmírnoje bohátstvo."), ("", "", "Íže plóť nášu za milosérdije vosprijím, Bóh že i Vladýka, na drévi prihvozdísja, i voznesé ny nizvérženyja, voznéssja, ťílom, jákože blahovolí, za blahoutróbije mílosti."), ("", "", "Kápľami Bohotóčnyja króve i vodý vozsozdásja mír, prolijánnyja ot rébr tvojích, vodóju úbo omýješi jáko ščédr, vsích hrichí Hóspodi, króviju že proščénije píšeši."), ("", "", "Na odrí sležjá nebrežénija mojehó, životá mojehó vrémja ľínostno skončách, i bojúsja ischóda mojehó časá: no tvojéju molítvoju vozdvíhnuvši k pokajániju, spasí mja otrokovíce."), ("", "", "Boľízni sérdca mojehó čístaja iscilí, i ustávi umá mojehó prélesť, i spodóbi čístym ťá vospiváti sérdcem, i isprosíti blahodáť, i obristí mílosť v déň súdnyj."), ("", "", "Otloží smirénnaja dušé mojá, neudobonosímaja bremená zlóby, i pristupí slezjášči i vopijúšči: ího čístaja Ďívo spodóbi mjá léhkoje nosíti Sýna i Bóha tvojehó."), ("Krestobohoródičen", "", "Orúžije sérdce tvojé prójde prečístaja, jehdá Sýna tvojehó na kresťí víďila jesí, i vopijála jesí: ne bezčádnu mjá pokaží Sýne mój i Bóže mój, sobľudýj mjá po roždeství Ďívu."), ), "S": ( ("", "", "Krestú tvojemú poklaňájusja, Christé, čestnómu, chraníteľu míra, spaséniju nás hríšnych, velíkomu očiščéniju, pochvaľí vsejá vselénnyja."), ("", "", "Drévo preslušánija míru smérť prozjabé: drévo že krestá živót i netľínije. Ťímže tí poklaňájemsja raspénšemusja Hóspodu: da známenajetsja na nás svít licá tvojehó."), ("", "", "Prorócy, i apóstoli Christóvy, i múčenicy, naučíša píti Tróicu jedinosúščnuju, i prosvitíša jazýki zablúždšyja, i óbščniki ánhelom sotvoríša sýny čelovíčeskija."), ("Krestobohoródičen", "Vélija krestá tvojehó", "Na kresťí ťa vozdvížena Christé mój, jáko víďi áhnica róždšaja ťá i neporóčnaja, i Máti tvojá, rydáše s pláčem i vopijáše: ne pokaží mja bezčádnu, júže sochraníl jesí čístu i po roždeství."), ), ) #let P = ( "1": ( ("", "", "Vódy drévle, mánijem božéstvennym, vo jedíno sónmišče sovokupívyj, i razďilívyj móre Izráiľteskim ľúdem, séj Bóh náš, preproslávlen jésť: tomú jedínomu poím, jáko proslávisja."), ("", "", "Jáko istóčnik milosérdija i mílosti, vídyj ťá Bóžiju Máter, pristúpľ moľúsja tvojéj bláhosti, dáti mí umilénije: jáko da sítuju i pláčusja prehrišénij mojích, vsečístaja Vladýčice."), ("", "", "Dušévnych mí sléz dážď kápľu, omyvájušču skvérnu vsjú mojích ďijánij, i lukávaja pomyšlénija, i očiščájuščuju duší mojejá nečistotú, i cérkov tvorjáščuju mjá Bóžija Dúcha."), ("", "", "Oburevájem volnóju, i trevolnénijem mojích prehrišénij, i ľúťi vsehdá borcá rabótami potopľájem, i vo hlubinú pohíbeli nýňi otpuščén, vopijú ti preneporóčnaja: spasí mja."), ("", "", "Milosérdija rádi mílosti Vladýčice vsích, pomíluj okajánnuju mojú dúšu, i ohňá izbávi mjá víčnujuščaho, i bisóvskaho napádanija, pod króv tvój Bohoródice nýňi pribihájuščaho."), ), "3": ( ("", "", "Íže ot nesúščich vsjá privedýj, slóvom sozidájemaja, soveršájemaja Dúchom, vsederžíteľu výšnij, v ľubví tvojéj utverdí mené."), ("", "", "Svítom božéstvennym ozarí vsepítaja, omračénnyj úm mój zlými pómysly: tý bo svít rodilá jesí, vozsijávšij ot Otcá prisnosúščnyj."), ("", "", "Zapén duší mojéj stopý, íže právednych vráh k zemlí prirazí: no tvojéju desníceju Vladýčice čístaja vozstávi mjá."), ("", "", "Mytarévymi hlásy, okajánnyj áz zovú ti: očísti mjá Vladýčice i prehrišénij ostavlénije, tvojéju molítvoju, podážď rabú tvojemú."), ("", "", "Iscilí jázvy dušévnyja, i mnohomútnoje pomyšlénij volnénije, Vladýčice, utiší: i mírnoje mí ustrojénije dážď."), ), "4": ( ("", "", "Položíl jesí k nám tvérduju ľubóv Hóspodi, jedinoródnaho bo tvojehó Sýna za ný na smérť dál jesí. Ťímže tí zovém blahodarjášče: sláva síľi tvojéj Hóspodi."), ("", "", "Plóť slasťmí, i sladostrástijem oskverních, i duší mojejá čistotú skvérnymi mýsľmi okaľách, i úm pomračích, ne prézri úbo Vladýčice rabá tvojehó."), ("", "", "Izbavlénije mí búdi, i pribížišče i deržáva, róh že spasénija čístaja, i zastúpnica, vsjákija mjá skórbi izbavľájušči vsehdá, i vrahí mojá vsjá posramľájušči."), ("", "", "Mnóhimi napásťmi nýňi oderžím jésm okajánnyj, i bisóvskimi kovárstvy prísno pohružájem, pribiháju tí nýňi: téploju tvojéju molítvoju spasí mja rabá tvojehó."), ("", "", "Nóšč mjá nesvitlá strastéj oderžít okajánnaho: no svítom tvojím blahája, duší mojejá óblaki razžení, i k svítu nastávi poveľínij Bóžijich, vseneporóčnaja."), ), "5": ( ("", "", "Jáko víďi Isáia obrázno na prestóľi prevozneséna Bóha, ot ánhel slávy dorinosíma, o okajánnyj, vopijáše, áz: províďich bo voploščájema Bóha, svíta nevečérňa, i mírom vladýčestvujušča."), ("", "", "Vrémja životá mojehó jáko dým isčezé, i k smértnym dvérem priblížichsja, i užasájusja bisóvskaho napádanija: ďilá bo ťích ďijach vsehdá, vseneporóčnaja uščédri i spasí mja."), ("", "", "Izsušájušči Ďívo, zól mojích bézdnu, podážď mí ríki sléz, i uhasí vés strastéj mojích plámeň otrokovíce, i spodóbi izbávitisja ohňá, i próčich mučénij v déň súdnyj."), ("", "", "Boľívšuju dúšu mojú hrichí, prečístaja, iscilí tvojím mílovanijem, i spodóbi mjá tvoríti vo smiréniji Sýna tvojehó poveľínija prísno, jáko da vosprijimú sehó bláhosť."), ("", "", "Ovdovívšaja Sýne mój, nevístnyja odéždy, božéstvennaja cérkov tvojá, ot rébr svjatýja króve oďíjasja. Áz že boľíznuju, vsjá boľízni tvojá zrjášči na kresťí, jáže Slóva Máti rydájušči hlahólaše."), ), "6": ( ("", "", "Bézdna posľídňaja hrichóv obýde mjá, i isčezájet dúch mój: no prostrýj Vladýko vysókuju tvojú mýšcu, jáko Petrá mja upráviteľu spasí."), ("", "", "Velíkoje ťá Bóžij Sýn hríšnikom pribížišče pokazá, voplóščsja Bohonevísto, ot čístych krovéj tvojích: ťím mílostiva tvojím rabóm búdi."), ("", "", "Prosvití zaréju tvojéju blahája, omračénnyja sérdca mojehó óči pómysly nepodóbnymi: i svítu Sýna sotvorí, i v místo svítlo mjá vselí."), ("", "", "Vólny strástnych pomyšlénij vsehdá mja smuščájut prečístaja, lukávych že duchóv búrja pohružájet: no utverdí mja na kámeni bezstrástija."), ("", "", "Usnúch k smérti dušévňij, i vo hróbi ležú otčájanija: no dážď mí rúku, i vozdvíhni, moľúsja k pokajániju žízni nastavľájušči mjá."), ), "S": ( ("", "", "Žézl síly sťažávšiji, krest Sýna tvojehó Bohoródice, ťím nizlahájem vrahóv šatánija, ľubóviju ťá neprestánno veličájušče."), ), "7": ( ("", "", "Préžde óbrazu zlatómu, persídskomu čtílišču ótroki ne pokloníšasja, trijé pojúšče posreďí péšči: otcév Bóže blahoslovén jesí."), ("", "", "Krípostiju prepojáši čístaja, dúšu mojú iznemóhšuju hrichí, i vopijúšča Sýnu tvojemú spasí mja: otéc nášich Bóže, blahoslovén jesí."), ("", "", "Smértnaho časá ubojávsja, bezsmértnaho rádi i víčnaho mučénija, tebí pripádaju: spasí mja otrokovíce ot síti lovjáščich, Bohorodíteľnice."), ("", "", "Jáže nevmistímaho Bóha vo črévo vmistívšaja, mnóhimi prehrišéniji uťisňájemyj úm mój Bohoródice, svobodí sích osuždénija."), ("", "", "Ród čelovíčeskij ťá mólit Bohoródice: Vladýčice pomíluj rabý tvojá, víroju Sýnu tvojemú vopijúščyja: otéc nášich Bóže, blahoslovén jesí."), ), "8": ( ("", "", "Nesterpímomu ohňú sojedinívšesja, Bohočéstija predstojášče júnoši, plámenem že nevreždéni, božéstvennuju písň pojáchu: blahoslovíte vsjá ďilá Hospódňa Hóspoda, i prevoznosíte vo vsjá víki."), ("", "", "Pozavíďiv blúdnomu voístinnu, i žitijé mojé vsé skončáv vo hrisích, nýňi zovú: sohriších tí, sotvorí mja otrokovíce, jáko jedínaho ot najémnik Sýna i ziždíteľa tvojehó, da ťá slávľu vo vsjá víki."), ("", "", "Napólnisja zól dušá mojá, i privminén bých so vsími v róv nizchoďáščymi: no tý mja Bohoródice Ďívo, izvedí iz jámy strástnyja, i ot brénija timínna zól mojích."), ("", "", "Molísja Christú, róždšaja sehó ot svjatých tvojích črésl Bohoródice, mnóhich mí prehrišénij dáti proščénije, da pojú: vsjá ďilá Hospódňa Hóspoda pójte, i prevoznosíte jehó vo víki."), ("", "", "Jehdá Bóžijim poveľínijem chóščet dušá mojá ot žitijá sehó otití, ot síti lovjáščich ischití prečístaja, tebí vopijúščich: vsjá ďilá Hospódňa Hóspoda pójte, i prevoznosíte jehó vo víki."), ), "9": ( ("", "", "V zakóňi síni i pisánij óbraz vídim vírniji, vsják múžeskij pól ložesná razverzája, svját Bóhu: ťím pervoroždénnoje Slóvo Otcá beznačáľna, Sýna pervoroďáščasja Máteriju neiskusomúžno, veličájem."), ("", "", "Ród čelovíčeskij vseneporóčnaja, tvojéju nepobidímoju molítvoju nýňi oboháščsja, vopijét déň i nóšč: ne prestáj vsehdá moľáščisja tvorcú i Sýnu tvojemú, uščédriti pojúščyja ťá."), ("", "", "Stríly strastéj bezmístnych dúšu mojú ujazvíša bisóvskimi prilóhi, soprotívnymi strilámi pomyšlénij, vsehdá úm mój smuščájut: ťímže iscilí otrokovíce, neiscíľnyja mojá jázvy."), ("", "", "Otimí čístaja Bohonevísto ot mené borjúščich vráh rány vskóri, vostánija bo ťích, i mnóhaho lukávstva i náhlosti ktomú ne terpľú okajánnyj: no potščísja izbáviti mjá."), ("", "", "Tý nemožénije vísi smirénnaho mojehó ťilesé, jázvy duší mojejá, sérdca mojehó stenánije, i umá mojehó zabluždénije i prélesti: ťímže tvojím milosérdijem obojúdu dážď iscilénije."), ), ) #let U = ( "S1": ( ("", "", "Krest vodruzísja na zemlí, i kosnúsja nebesé: ne jáko drévu dosjáhšu vysotú, no tebí na ném ispolňájuščemu vsjáčeskaja: Hóspodi sláva tebí."), ("", "", "Na kiparísi, i pévki, i kédri, voznéslsja jesí Áhnče Bóžij, da spáséši íže víroju poklaňájuščyjasja vóľnomu tvojemú raspjátiju, Christé Bóže, sláva tebí."), ("Krestobohoródičen", "", "Žézl síly sťažávšiji krest Sýna tvojehó Bohoródice, ťím nizlahájem vrahóv šatánija, ľubóviju ťá neprestánno veličájušče."), ), "S2": ( ("", "", "Zaušívyjsja za ród čelovíčeskij, i ne prohňívavyjsja, svobodí iz istľínija živót náš Hóspodi, i spasí nás."), ("", "Krasoťí ďívstva", "Neisčétňij vlásti tvojéj, i vóľnomu raspjátiju, ánheľskaja vójinstva divľáchusja zrjášče: káko nevídimyj plótiju uraňášesja, choťá izbáviti ot istľínija čelovíčestvo? Ťímže jáko žiznodávcu vopijém tí: sláva Christé blahoutróbiju tvojemú."), ("Múčeničen", "", "Vooružívšesja vo vseorúžije Christóvo, i obólkšesja vo orúžije víry, opolčénija vrážija stradáľčeski nizložíste: usérdno bo nadéždeju žízni, preterpíste vsjá mučíteľskaja drévle preščénija že i rány. Ťímže i vincý prijáste, múčenicy Christóvy terpilivodúšniji."), ("Krestobohoródičen", "Podóben", "Neiskusobráčnaja čístaja i Máti tvojá Christé, víďašči ťá mértva vísjašča na kresťí, máterski pláčušči hlahólaše: čtó tebí vozdadé jevréjskij bezzakónnyj sobór i neblahodárnyj, íže mnóhich i velíkich tvojích, Sýne mój, daróv nasladívyjsja? Pojú tvojé božéstvennoje snizchoždénije."), ), "S3": ( ("", "Krasoťí ďívstva", "Raspjátije i smérť prijém, živót bezsmértnyj istočíl jesí nám Christé Spáse, i ot tlí mír svobodíl jesí. Ťímže tvojá slávim žiznodávče čelovikoľúbče strásti spasíteľnyja, ímiže vsí spasájemsja, čestnáho krestá tvojehó mír i nepobidímoje orúžije imúšče."), ("", "", "Krest preterpíl jesí bezčéstno Vladýko, íže prevýše vsejá tvári, jáko da počtíši mjá préžde ľúťi obezčéstvovana: kopijém že v rébra tvojá probodén býl jesí dolhoterpilíve, choťá izbáviti iz istľínija mjá sozdánije tvojé. Pojú tvojé mnóhoje blahoutróbije i bláhosť, čelovikoľúbče."), ("Krestobohoródičen", "Podóben", "Vozdvížena ťá jáko víďi na drévi Vladýko, neiskusobráčnaja i preneporóčnaja, čístaja Ďíva že i Máti tvojá, uvý mňí vzyváše, o Sýne mój sladčájšij! Káko ťá bezzakónňijšij sobór na drévi osudí, vsích tvorcá i Vladýku: pojú tvojú krájňuju bláhosť."), ), "K": ( "P1": ( "1": ( ("", "", "Vódy drévle, mánijem božéstvennym, vo jedíno sónmišče sovokupívyj, i razďilívyj móre Izráiľteskim ľúdem, séj Bóh náš, preproslávlen jésť: tomú jedínomu poím, jáko proslávisja."), ("", "", "Mnohoboľíznennyja strásti ustávil jesí Slóve, strasťmí čestnýja plóti tvojejá, i čelovíki spásl jesí, íchže ujazví drévle soprotivobórec, blahočéstno poklaňájuščichsja nedomýslennomu smotréniju tvojemú."), ("", "", "Íže svjazávyj v rají léstiju čelovíka, zápovidi prestuplénijem, úzami svjázan jésť nerišímymi Hóspodi, ímiže voploščájem vóleju svjázan býl jesí, razrišája prehrišénija náša čelovikoľúbče."), ("Múčeničen", "", "Bídstvujuščuju potoplénijem zrjášče strastotérpcy tvár, démonov prélesťmi, vírnym javíšasja pristánišča blahotíšnaja, vsjú hórdaho sílu strujámi króvnymi pohruzívše velikoimenítiji."), ("Múčeničen", "", "Lík múčeničeskij, likostojánijem hórnim svítlo sočetájem, blistáňmi vsehdá ozarjájetsja nesozdánnaho Božestvá, i súščyja na zemlí ozarjájet, tohó čudesá víroju slávjaščyja."), ("Bohoródičen", "", "Prevýšši hórnich javílasja jesí činóv, róždši na zemlí Bóha Slóva prečístaja, nás k nebésnym svoími strasťmí, i krestóm čestným vozvédšaho bláhosti rádi."), ), "2": ( ("", "", "Vódy drévle, mánijem božéstvennym, vo jedíno sónmišče sovokupívyj, i razďilívyj móre Izráiľteskim ľúdem, séj Bóh náš, preproslávlen jésť: tomú jedínomu poím, jáko proslávisja."), ("", "", "Priosinénnuju hóru ťá províďi Dúchom Avvakúm prorók, moľú prečístaja, osiní mja strástiju probodájema, i v síni smértňij ot stužájuščich mjá strastéj svobodítisja."), ("", "", "Priosinénnuju hóru ťá províďi Dúchom Avvakúm prorók, moľú prečístaja, osiní mja strástiju probodájema, i v síni smértňij ot stužájuščich mjá strastéj svobodítisja."), ("", "", "Okroplénijem božéstvennyja strují istočívšyjasja ot božéstvennaho rebrá Sýna tvojehó, mojá omýj serdéčnyja jázvy: jáko da veličáju ťá, i po dólhu slávľu prisnoblažénnuju i preneporóčnuju."), ("", "", "Ravnoďíteľa róždšemu rodilá jesí Slóva, obožívšaho čelovíčeskoje suščestvó: no tohó molí nedoumivájema i iznemóhša mjá vrážijimi kovárstvy, božéstvennaho uťišénija spodóbiti čístaja."), ), ), "P3": ( "1": ( ("", "", "Íže ot nesúščich vsjá privedýj, slóvom sozidájemaja, soveršájemaja Dúchom, vsederžíteľu výšnij, v ľubví tvojéj utverdí mené."), ("", "", "Tebé jestestvóm Božestvá bezstrástna, strástna bývša plótiju bláhosti rádi, drévom umertvíl jésť jevréjskij sobór, nás obezsmértstvujušča."), ("", "", "Na vodách povísivyj Slóve zémľu, na dréve vóleju býl jesí povíšen, vozvoďá mja k nebésnym v zlóby róv pádšaho."), ("Múčeničen", "", "Preispeščréni ránami, Christóvy vsechváľniji múčenicy, Hóspodevi predstoité ot nehó prijémľušče bohaťíjšeju rukóju vozdajánija."), ("Múčeničen", "", "Rádostnoju dušéju k ránam vmiščáchusja múčenicy, posľídňuju zmíjevi pečáľ tvorjášče, i ánheľskija líki rádosti ispolňájušče."), ("Bohoródičen", "", "Vozdvížena zrjášči na kresťí, Christá neiskusobráčnaja pláčušči hlahólala jesí: zašél jesí slávy sólnce ot óčiju mojéju, prosviščájaj vo ťmí súščyja."), ), "2": ( ("", "", "Íže ot nesúščich vsjá privedýj, slóvom sozidájemaja, soveršájemaja Dúchom, vsederžíteľu výšnij, v ľubví tvojéj utverdí mené."), ("", "", "Íže v mílosti neizrečénňij, i ščedrótach súšča bohátaho, mílostiva súšči vsesvjatája, molí jéže uščédriti nás ozlóblennych."), ("", "", "Dóm vsích súšči tvorcá, obitáti molí vo mňí Uťíšiteľu, bývšem vertépi dušetľínnych razbójnik, čístaja Ďívo."), ("", "", "Mánijem vsjá nosjáščaho božéstvennym, vo objátijich jáko nosjášči Bohoródice, prízri na mjá, i izbávi mjá ot íže k strastém rázuma bezmístnaho."), ), ), "P4": ( "1": ( ("", "", "Položíl jesí k nám tvérduju ľubóv Hóspodi, jedinoródnaho bo tvojehó Sýna za ný na smérť dál jesí. Ťímže tí zovém blahodarjášče: sláva síľi tvojéj Hóspodi."), ("", "", "Dosaždénije voístinnu, íže čésti vsjákija prevýššij Vladýko, preterpíl jesí Christé, po hlaví tróstiju bijém: jáko da prestuplénijem mjá obezčéstvovana počtíši čelovikoľúbče."), ("", "", "Vincém ternóvym vinčán býl jesí choťá dolhoterpilíve, jákože cár ístinnyj, i ternonósnyj částnyj hrích iz kórene ustávil jesí: pisnoslóvľu tvojá Spáse, stradánija."), ("Múčeničen", "", "Ne sokrušéni tomléňmi rán prebýste múčenicy, sokrušájušče prélesť vrážiju, i nohámi vášimi popirájušče, bezmírno chváľaščasja, i bezúmijem vsehó uvjadájema."), ("Múčeničen", "", "Ťilesý tľínnymi netľínije božéstvenno sťažáste, strasťmí strásť čestnúju bezstrástnaho tvérdo podražávše vsechváľniji múčenicy, bezplótnym vsím sčíslenniji."), ("Bohoródičen", "", "Svítok ťá inohdá prorók otrokovíce zrjáše, v némže pérstom Ótčim napisásja Slóvo voploščájemo, i práotčeje rukopisánije kopijém razdrá, prečístaja."), ), "2": ( ("", "", "Položíl jesí k nám tvérduju ľubóv Hóspodi, jedinoródnaho bo tvojehó Sýna za ný na smérť dál jesí. Ťímže tí zovém blahodarjášče: sláva síľi tvojéj Hóspodi."), ("", "", "Jázvy Christé i zakolénije vóleju jáko preterpíl jesí, ujázvlennuju mojú dúšu razbójničeskimi démonov ozlobléňmi, molítvami iscilí róždšija ťá, jedíne mnohomílostive."), ("", "", "Ťílo tvojéju rukú sozdáteľu jésm i tvorénije, zlóboju že zmiínoju Christé, ot slastéj žitéjskich sokrušíchsja. Ťímže mjá vozsozidáj róždšija ťá božéstvennymi umoléňmi."), ("", "", "Slóvo Ótčeje páče slóva rodilá jesí, razrišívšeje vsjákaho bezslovésija čelovíki: jehóže priľížno molí, bezslovésnymi mjá strasťmí pľiňájema svobodíti, jedína prisnoďívo."), ("", "", "Iscilénije nám iz dláni tóčiši vsehdá, vsjá svjatýni síň, vsjá svíta súšči ispólnena, vsjá kápľušči míro blahouchánija, prečístaja Bohonevísto."), ), ), "P5": ( "1": ( ("", "", "Na zemlí nevídimyj javílsja jesí, i čelovíkom vóleju sožíl jesí nepostižímyj, i k tebí útreňujušče, vospivájem ťá čelovikoľúbče."), ("", "", "Jákože áhnec vozdvíhlsja jesí na drévo, i Otcú žértva prinéslsja jesí o nás bláže, i žértvy ídoľskija ustávil jesí vsesíľne."), ("", "", "Probódsja v rébra živodávče kopijém, dvá istóčnika spasénija proliváješi, ot Tróicy ťá jedínaho vozviščájuščym, ďíjstva dvá nosjášča."), ("Múčeničen", "", "Utverždénije krípkoje, i nepokoléblemyj kámeň, ťá Iisúse krípcyji strastotérpcy víroju obrítše, jákože kámenije čestnóje sebé nazdáša."), ("Múčeničen", "", "Síloju Bóžijeju ukripľájemi víroju, vsjú ľútuju sílu preléstnika poboríli jesté, strastotérpcy múčenicy, i svítlo vinčástesja."), ("Bohoródičen", "", "Istľívšeje préžde prestuplénijem jestestvó jéže po nám, jáko netľínno róždši Christá, vozsozdalá jesí presvjatája Vladýčice, predstáteľstvo dúš nášich."), ), "2": ( ("", "", "Jáko víďi Isáia obrázno na prestóľi prevozneséna Bóha, ot ánhel slávy dorinosíma, o okajánnyj, vopijáše, áz: províďich bo voploščájema Bóha, svíta nevečérňa, i mírom vladýčestvujušča."), ("", "", "Plóti mojejá boľízni, i dušévnuju boľízň pretvorí, i ľínosti óblaki othoní Ďívo, svíta óblače, i zdrávije, i ľútych preminénije dážď mí prosjáščemu, i ľubóviju ťá slávjaščemu."), ("", "", "Chodátaicu ťá i molítvennicu, iz tebé róždšemusja nýňi predlaháju, vsjákaho hrichá sýj ispólň Ďívo, porúčnica mí i žitijá ispravlénije búdi, i rukovoždénije k stezjám božéstvennaho víďinija."), ("", "", "Osvjatí úm mój, i dúšu Ďívo svitovodí, i božéstvennyja slávy pričástnika sotvorí: sé bo zól ispólnichsja, i vsjákim poraboščén bých slastém, i oskvernénu prinošú sóvisť."), ), ), "P6": ( "1": ( ("", "", "Bézdna posľídňaja hrichóv obýde mjá, i isčezájet dúch mój, no prostrýj Vladýko, vysókuju tvojú mýšcu, jáko Petrá mja upráviteľu spasí."), ("", "", "Zmíj mjá izvedé iz Jedéma, ľstívoju sňídiju preľstívyj ľstívyj: Christós že na drévo vozdvíhsja vóleju, drévnij mňí páki dajét vchód."), ("", "", "Ujazvísja, íže nás ujazvívyj, i neiscílen prebýsť, ujazvlénym tvojím rébrom blahodáteľu Hóspodi: vírniji že iscilíchomsja tvojími jázvami, ímiže vóleju ujazvílsja jesí."), ("Múčeničen", "", "Javístesja posreďí ohňá, premúdriji Christóvy orúžnicy, jákože áhncy ispecájemi, i Bóhu vsích carjú na trapézu prinosími, i neizrečénnoje vesélije nasľídujušče."), ("Múčeničen", "", "Podavájete iscilénija ríki, ot neistoščímych sokróvišč počerpájušče, i strastéj vréd strastotérpcy izsušájete, i napajájete vírnych sobránija."), ("Bohoródičen", "", "Umerščvlénije zrjášči, ot tvojích krovéj Slóva voplóščšahosja vseneporóčnaja, Máterski vosklicála jesí: i žízni súšča vinóvnaho vozvelíčila jesí, Máti Ďívo Vladýčice."), ), "2": ( ("", "", "Íže v koncý vikóv došédšyja čelovikoľúbče, i trevolnéňmi napástej pohíbnuti bídstvujuščyja, vopijúščyja ne prézri: spasí Spáse, jákože spásl jesí ot zvírja proróka."), ("", "", "Fariséja prevoznesénnoju mýsliju prevoschodích, horďásja prísno, i k própastem porivájasja bezmírnych sohrišénij, jedína čístaja smirívšahosja mjá ľúťi uščédri."), ("", "", "Fariséja prevoznesénnoju mýsliju prevoschodích, horďásja prísno, i k própastem porivájasja bezmírnych sohrišénij, jedína čístaja smirívšahosja mjá ľúťi uščédri."), ("", "", "Jáže prečúdnoje začátije imívši i roždénije, tvojá mílosti na mňí okajánňim nýňi udiví: íbo v bezzakónijich i začáchsja i roždéjsja slastém poraboščén bých."), ("", "", "Vosklicáju, pláču i rydáju, jehdá sudíšče strášnoje vospomináju: lukáva bo ďilá ímam, neiskusomúžnaja Ďívo Máti Bóžija, v čás strášnyj predstáni mí."), ), ), "P7": ( "1": ( ("", "", "Préžde óbrazu zlatómu, persídskomu čtílišču, ótroki ne pokloníšasja, trijé pojúšče posreďí péšči: otcév Bóže, blahoslovén jesí."), ("", "", "Boľízňmi tvojími ustávil jesí náša boľízni čelovikoľúbče, i nýňi k žízni neboľíznenňij privél jesí íže tvojím čestným strastém poklaňájuščyjasja blahočéstno, Bóže vsích."), ("", "", "Jehdá ťa uzrí Christé tvár raspinájema, izmiňášesja i trepetáše: zemľá trjasášesja, raspadésja že kámenije, i sokryváše svít sólnečnoje tečénije."), ("Múčeničen", "", "Zakónom pokarjájuščesja Christóvym, bezzakónnych ukloníšasja laskánij múčenicy, i zakónno posreďí sudíšča stradáľčestvujušče, slávno vinčaváchusja."), ("Múčeničen", "", "Ne opalístesja ohném, ohňá tepľíjše proizvolénije sťažávše, strastotérpcy Hospódni vincenóscy, vopijúšče: Bóže blahoslovén jesí."), ("Bohoródičen", "", "Stojála jesí zrjášči Christá na kresťí vozdvížena, jehóže rodilá jesí prečístaja, i vopijála jesí: ne bezčádnu javí mja, júže sobľúl jesí čístu i po roždeství."), ), "2": ( ("", "", "Trijé ótrocy v peščí Tróicu proobrazívše, preščénije óhnennoje popráša, i pojúšče vopijáchu: blahoslovén jesí Bóže otéc nášich."), ("", "", "Ot ďíl spasénija ňísť mí Vladýčice, hrichí vo prilaháju ko hrichóm, i k zlóbi zlóbu: molítvoju úbo tvojéju čístaja uščédri, i spasí mja."), ("", "", "Ot ďíl spasénija ňísť mí Vladýčice, hrichí vo prilaháju ko hrichóm, i k zlóbi zlóbu: molítvoju úbo tvojéju čístaja uščédri, i spasí mja."), ("", "", "Súd pri dvérech, sudíšče hotóvo, uhotóvisja smirénnaja dušé, i vozopíj: vnehdá sudíti tí Slóve, ne osudí mené, molítvami róždšija ťá."), ("", "", "Objém hrichóvnyja plodý umertvíchsja, i prinosjá dúšu neplódnu, zovú ti: plodonósnu pokaží, jáže plodóm tvojím tľínije potrebívšaja."), ), ), "P8": ( "1": ( ("", "", "Vavilónskaja péšč ótroki ne opalí, nižé Božestvá óhň Ďívu rastlí. Ťím so ótroki vírniji vozopijém: blahoslovíte ďilá Hospódňa Hóspoda."), ("", "", "Tebí raspénšusja, otvérzesja páki ráj, i obraščájuščejesja na ný orúžije pleščí dajét, kopijá ustyďívsja probódšaho svjatája rébra tvojá, Christé mnohomílostive."), ("", "", "Kopijém tí boréc ujazvísja, i padésja, padýj že Adám k žízni vozvraščájetsja, vopijá tebí vóleju zaklávšemusja Christé: blahoslovľájaj ťá slávľu, Bóže mój mnohomílostive."), ("Múčeničen", "", "Mír prosviščájetsja boréňmi vášimi, i izrjádstvy stradáľcy, i neisčétnymi čudesý i ťmý boľíznej izbavľájetsja, víroju vopijá: blahoslovíte ďilá Hospódňa Hóspoda."), ("Múčeničen", "", "Smích zrítsja ležjá pod nohámi vášimi svjatíji, íže préžde chvaľájsja zémľu potrebíti i móre: Christós že živonósnoju ukrašájet desníceju, neuvjadájuščimi vincý, vás prisnoslávniji."), ("Bohoródičen", "", "V ľíto porodilá jesí ľít výššaho, razrišájuščaho ľítnyja soúzy, úzami svojími prečístaja, Adáma pervozdánnaho, i sosvjazújušča jehó úzami sládkija svojejá ľubvé."), ), "2": ( ("", "", "Nesterpímomu ohňú sojedinívšesja, Bohočéstija predstojášče júnoši, plámenem že nevreždéni, božéstvennuju písň pojáchu: blahoslovíte vsjá ďilá Hospódňa Hóspoda, i prevoznosíte vo vsjá víki."), ("", "", "Vsjá jáko dobrá i blížňaja vsích carjá bývšaja Bohoródice, ispólni mjá blahích ďíl, zlóbi spožívšaho, i ľínostno vsé žitijé skončávšaho: jáko da ťá slávľu vo vsjá víki."), ("", "", "Ot kítova čréva jáko izbávil jesí drévle proróka Bóžij Slóve preslávno: táko izbávi mojú dúšu vo hlubinú popólzšujusja pohíbeli, imíjaj Spáse moľáščujusja tebí neiskusobráčno róždšuju ťá Ďívu."), ("", "", "V krásnuju odéždu oblékšahosja mjá Bohoroždénija, obrítše Bohoródice, íže zlóbu soďílovajuščiji, tojá obnažíša: no tý mja božéstvennymi odéždami ujasní pokajánijem, molítvami tvojími Ďívo."), ), ), "P9": ( "1": ( ("", "", "Kupinóju i ohném propísanuju v Sináji zakonopolóžniku Moiséju, i Bóžij vo črévi neopáľno začénšuju óhň, vsesvítluju i nehasímuju sviščú, súščuju Bohoródicu písňmi čtúšče veličájem."), ("", "", "Da obrjáščeši dráchmu, júže pohubíl jesí Christé, vžéh na kresťí tvojú plóť bláže, i óbščniki sotvoríši rádosti, síly tvojá hórnija živodávče, s nímiže ťá jáko blahoďíteľa pojúšče, písňmi veličájem."), ("", "", "Jáko vozdvíhl jesí Christé tvojí rúci na kresťí, osláblennyja mojí préžde rúci strasťmí mnóhimi, ukripíl jesí síloju tvojéju, i koľína k tečéniju božéstvennomu, voístinnu osláblenaja utverdíl jesí: ťímže ťá veličájem."), ("Múčeničen", "", "Sharájušče plámenem, bezmírnymi ránami, rósu ťá obritóša Christé prochlaždénija, tvojí tvérdiji i čúdniji stradáľcy. Ťímže rádujuščesja iďáchu putém, želánijem póčestej, písňmi ťá neprestánno veličájušče."), ("Múčeničen", "", "Mnóžestvo stradálec, svjatých lík mólit ťá Christé za sobór ľudéj, mnóho preohorčevájuščich: mnóžestvom tvojejá ščédre mílosti, očísti mnóžestvo bezzakónij nášich, jáko čelovikoľúbec."), ("Bohoródičen", "", "Nosjáščeje zemných zrák, sijánije Ótčeje Ďívo rodilá jesí, jehóže vozdvížena na kresťí sólnce na terpjášči zríti omračášesja, i mrák umaľášesja idoloneístovstva: ťímže s ním ťá veličájem."), ), "2": ( ("", "", "V zakóňi síni i pisánij óbraz vídim vírniji: vsják múžeskij pól ložesná razverzája, svját Bóhu. Ťím pervoroždénnoje Slóvo Otcá beznačáľna, Sýna pervoroďáščasja Máteriju neiskusomúžno, veličájem."), ("", "", "Rastľínna umóm, rastľínna dušéju i sóvistiju, zlóboju oskvernéna, i náha vsjákich bláh javlénna, Ďívo netľínnaja, neporóčnaja, ne prézri mené, no ďíly blahočéstija ukrasí."), ("", "", "Ispólnichsja zól, ispólnichsja pomyšlénij otčuždájuščich mjá ot tebé čelovikoľúbca. Sehó rádi i steňú i vopijú: kájuščahosja mjá prijimí, i ne otríni mené róždšija ťá molítvami, blahoďíteľu mnohomílostive."), ("", "", "Da izbávľusja tvojími vseneporóčnaja otrokovíce molítvami, ot vsjákaho hňíva, strastéj smertonósnych, ľútyja hejénny i ohňá, ot čelovíkov neprávednych, ot vrahóv lukávych, pribíhnuvyj k tvojemú pokróvu, i prizyvájaj ťá na pómošč."), ("", "", "Jáko Máti Bóžija, molí iz tebé róždšahosja Hóspoda Bóha i carjá: jéže izbávitisja vsjákaho preščénija, i lukávaho obýčaja tvojemú rabú čístaja, na ťá naďíjavšemusja iz čréva mátere mojejá, Vladýčice."), ), ), ), "ST": ( ("", "", "Závistiju sládosti izhnán bých, padénijem pádsja ľútym: no ne prezríl jesí Vladýko, vosprijím mené rádi jéže po mňí, raspináješisja, i spasáješi mjá, v slávu vvódiši mjá, izbáviteľu mój, sláva tebí."), ("", "", "Krestojavlénno Moiséj na horí rúci prostér k vysoťí, Amalíka pobidí: tý že Spáse, dláni prostrýj na kresťí čestňím, objál jesí mjá, spasýj ot rabóty vrážija: i dál jesí známenije žízni, ot lúka bižáti protívnych mojích. Sehó rádi Slóve, poklaňájusja krestú tvojemú čestnómu."), ("Múčeničen", "", "Jáko svitíla v míri sijájete i po smérti svjatíji múčenicy, pódvihi dóbrymi podvizávšesja: ťímže imúšče derznovénije, Christá molíte pomílovatisja dušám nášym."), ("Krestobohoródičen", "", "Zrjášči ťá vísjašča na drévi vseneporóčnaja, Christé mój preblahíj, rydájušči vopijáše Máterski: Sýne mój vseľubézňijšij, káko sobór bezzakónnyj na drévi ťá osudí?"), ) ) #let L = ( "B": ( ("", "", "Otvérhša Christé zápoviď tvojú práotca Adáma iz rajá izhnál jesí: razbójnika že ščédre, ispovídavša ťá na kresťí, vóň vselíl jesí zovúšča: pomjaní mja Spáse vo cárstviji tvojém."), ("", "", "Raspjálsja jesí mené rádi, i probodén jesí Iisúse mój v rébra, dvá istóčnika istočívyj mňí spasíteľnaja: ťímže spássja strástiju tvojéju Christé, vospiváju i slávľu blahoutróbije tvojé: pomjaní mja vopijúšča vo cárstviji tvojém."), ("", "", "So bezzakónnyma vminívsja, bezzakónija vsích nás Iisúse vzjál jesí, i térnijem vinčávsja jáko cár vsích, hrichá térnije práotca iz kórene Christé, izsikáješi: ťímže víroju tvojú strásť nýňi slávim."), ("", "", "Íže stradánija Christóva podražávše dóbliji stradáľcy, vseslávniji múčenicy, i vrážiju prélesť nizložívše síloju božéstvennoju, nebésnuju slávu polučíste, o vsích nás svjatíji moľáščesja."), ("", "", "Triipostásnaja jedínice, i nerazďíľnaja Tróice vseďíteľnaja, suščestvó jedíno, i síla, pivcý tvojá pokrýj ot vsjákaho vréda vrážija, i cárstvija tvojehó spodóbi, jéže polučíša, íže dóbri požívšiji."), ("", "", "Zrjášči na kresťí, jehóže ot krovéj čístych voplotíla jesí, pláčušči vzyvála jesí Bohorodíteľnice otrokovíce: čtó sijá čádo, sónm lukávyj vozdadé tebí, umertvívyj ťá životá vírnych vsích i voskresénije?"), ) )
https://github.com/Duolei-Wang/modern-sustech-thesis
https://raw.githubusercontent.com/Duolei-Wang/modern-sustech-thesis/main/template/lib.typ
typst
MIT License
// Construct the sections as aranged. #import "./configs/cover.typ": cover #import "./configs/commitment.typ": commitment #import "./configs/abstract.typ": abstract #import "./configs/outline.typ": toc #import "configs/mathstyle.typ": mathstyle #let std-bibliography = bibliography #let sustech-thesis( isCN: true, information: ( title: ( [第一行], [第二行], ), subtitle: [subtitle], abstract-body: ( [#lorem(40)], [#lorem(40)], ), keywords: ( [Keyword1], [关键词2], [啦啦啦], [你好] ), author: [慕青QAQ], department: [数学系], major: [数学], advisor: [木木], ), information-EN: ( title: ( [第一行], [第二行], ), subtitle: [subtitle], abstract-body: ( [#lorem(40)], [#lorem(40)], ), keywords: ( [Keyword1], [关键词2], [啦啦啦], [你好] ), author: [慕青QAQ], department: [数学系], major: [数学], advisor: [木木], ), toc-title: [目录], body, ) = { // 设置中文字体 Setting Style of Text which is Chinese Character (or CJK?) // 中英文封面页 Cover cover( isCN: isCN, title: information.title, subtitle: information.subtitle, author: information.author, department: information.department, major: information.major, advisor: information.advisor, ) pagebreak() // 设定目录编号格式 set heading(numbering: "1.1.1.") // 设定非正文部分页码 set page(numbering: "I") counter(page).update(0) if(isCN){ commitment( isCN: true, ) commitment( isCN: false, ) } pagebreak() if(isCN){ // 插入摘要页 abstract( isCN: true, information: information, body: information.abstract-body, ) // Abstract-EN abstract( isCN: false, information: information-EN, body: information-EN.abstract-body, ) }else{ // Abstract-EN abstract( isCN: false, information: information-EN, body: information-EN.abstract-body, ) } // 设定正文部分页码 // 插入目录页 toc( isCN: isCN, toc-title: toc-title, ) set page(numbering: "1") counter(page).update(1) pagebreak() // body style import "./configs/font.typ" as fonts // headings show heading.where(level: 1): it =>{ set text( font: fonts.HeiTi, size: fonts.No3, weight: "regular", ) align(center)[ // #it #strong(it) ] text()[#v(1em)] } show heading.where(level: 2): it =>{ set text( font: fonts.HeiTi, size: fonts.No4, weight: "regular" ) text()[#v(0.5em)] it text()[#v(1em)] } show heading.where(level: 3): it =>{ set text( font: fonts.HeiTi, size: fonts.No4-Small, weight: "regular" ) it text()[#v(1em)] } // paragraph set block(spacing: 1.5em) set par( justify: true, first-line-indent: 2em, leading: 1.5em) set text( font: fonts.SongTi, size: fonts.No4-Small, ) show std-bibliography: it => { show heading: title => { set text( font: fonts.HeiTi, size: fonts.No3, ) title } set text( size: fonts.No5, font: fonts.SongTi, ) it } body }
https://github.com/jamesrswift/ionio-illustrate
https://raw.githubusercontent.com/jamesrswift/ionio-illustrate/main/dist/0.2.0/src/util.typ
typst
MIT License
/// Merge dictionary a and b and return the result /// Prefers values of b. /// /// - a (dictionary): Dictionary a /// - b (dictionary): Dictionary b /// -> dictionary #let merge-dictionary(a, b, overwrite: true) = { if type(a) == dictionary and type(b) == dictionary { let c = a for (k, v) in b { if not k in c { c.insert(k, v) } else { c.at(k) = merge-dictionary(a.at(k), v, overwrite: overwrite) } } return c } else { return if overwrite {b} else {a} } }
https://github.com/spherinder/ethz-infk-thesis
https://raw.githubusercontent.com/spherinder/ethz-infk-thesis/master/pages/declaration-of-originality.typ
typst
#import "@preview/cheq:0.2.1": checklist #let declaration-of-originality( author: "", author-email: "", title: "", document-type: "", supervisor: "", tutor: "", semester: "", student-nr: "", sans-font: "CMU Sans Serif", declaration-of-originality-choice: none, ..rest ) = { set page(header: context { set text(size: 11.5pt) grid( rows: 2, gutter: 5pt, emph("Declaration of Originality"), line(length: 100%, stroke: 0.7pt), ) }) set text(size: 10pt) align(center)[ #text(font: sans-font, 14pt, weight: 700, "Declaration of Originality") ] set par(leading: 3pt) text("The signed declaration of originality is a component of every written paper or thesis authored during the course of studies. In consultation with the supervisor, one of the following three options must be selected:") show: checklist set list(tight: false, spacing: 6pt, indent: 10pt) let checklist-item(i, content) = list.item( [#if declaration-of-originality-choice == i [\[x\] ] else [\[ \] ]] + content) checklist-item(1, [I confirm that I authored the work in question independently and in my own words, i.e. that no one helped me to author it. Suggestions from the supervisor regarding language and content are excepted. I used no generative artificial intelligence technologies #footnote[E.g., ChatGPT, DALL E 2, Google Bard.]<fn_ai>.]) checklist-item(2, [I confirm that I authored the work in question independently and in my own words, i.e. that no one helped me to author it. Suggestions from the supervisor regarding language and content are excepted. I used and cited generative artificial intelligence technologies @fn_ai.]) checklist-item(3, [I confirm that I authored the work in question independently and in my own words, i.e. that no one helped me to author it. Suggestions from the supervisor regarding language and content are excepted. I used generative artificial intelligence technologies @fn_ai. In consultation with the supervisor, I did not cite them.]) let custom_title(title) = { text(title, weight: "bold") } set par(justify: true) v(2pt) custom_title("Title of Work:") v(8pt, weak: true) text(title) v(3pt) custom_title("Thesis type and date:") v(8pt, weak: true) text(document-type + ", " + datetime.today().display("[day] [month repr:long] [year]")) v(3pt) custom_title("Supervision:") v(8pt, weak: true) text(supervisor) v(6pt, weak: true) text(tutor) v(3pt) custom_title("Student:") v(8pt, weak: true) grid( columns: 2, column-gutter: 20pt, row-gutter: 5pt, "Name:", author, "E-mail:", author-email, "Stud.-Nr.:", student-nr, "Study Semester:", semester ) v(10pt) [ With my signature I confirm the following: - I have committed none of the forms of plagiarism described in the citation etiquette #footnote(link("https://ethz.ch/content/dam/ethz/main/education/rechtliches-abschluesse/leistungskontrollen/plagiarism-citationetiquette.pdf")). - I have documented all methods, data, and processes truthfully. - I have not manipulated any data. - I have mentioned all persons who were significant facilitators of the work. I am aware that the work may be screened electronically for originality. ] v(30pt) grid( columns: 2, column-gutter: 40pt, row-gutter: 10pt, line(length: 160pt, stroke: 0.5pt), line(length: 200pt, stroke: 0.5pt), text("Place, Date", size: 9pt), text(author, size: 9pt), ) }
https://github.com/dainbow/MatGos
https://raw.githubusercontent.com/dainbow/MatGos/master/themes/27.typ
typst
#import "../conf.typ": * = Приведение квадратичных форм в линейном пространстве к каноническому виду. Положительно определённые квадратичные формы. <NAME>. == Приведение квадратичных форм в линейном пространстве к каноническому виду. #definition[ Пусть $b in cal(B)^plus.minus (V)$. - Векторы $bold(u), bold(v) in V$ называются *ортогональными относительно $b$*, если $b(bold(u), bold(v)) = 0$ - *Ортогональным дополнением* подпространства $U <= V$ относительно $b$ называется подпространство #eq[ $U^bot := {bold(v) in V | forall bold(u) in U : b(bold(u), bold(v)) = 0} <= V$ ] ] #definition[ Пусть $FF$ -- поле. Его *характеристикой* называется наименьшее число $k in NN$ такое, что в полне выполнено равенство $underbrace(1 + ... + 1, k) = 0$. Если такого $k$ не существует, то характеристикой поля считается $0$. Обозначение -- $"char" FF$ ] #definition[ Пусть $"char" FF != 2, h in cal(Q)(V)$. Симметрическая билинейная форма $b in cal(B)^+ (V)$ называется *полярной* к $h$, если #eq[ $forall bold(v) in V : space h(bold(v)) = b(bold(v), bold(v))$ ] *Матрицей* квадратичной формы $h$ в базисе $e$ называется матрица $B$ полярной к ней формы $b$ в базисе $e$. Обозначение $h <->_e B$. ] #theorem( "<NAME>", )[ Пусть $h in cal(Q)(V), h <->_e B$, причём все главные миноры матрицы $B$ отличны от нуля. Тогда существует такой базис $e' = e S$, что матрица перехода $S$ -- верхнетреугольная с единицами на главной диагонали, $h <->_(e') B'$ и $B'$ диагональна. Более того, тогда $B' = "diag"(Delta_1 (B), (Delta_2(B)) / (Delta_1(B)), ..., (Delta_n (B)) / (Delta_(n - 1)(B)))$ ] #proof[ Докажем индукцией по $n := dim V$, что матрица формы $h$ приводится к диагональному виду в базисе $e'$ с матрицей перехода из условия. База, $n = 1$, тривиальна: подходит исходный базис $e$. Пусть теперь $n > 1$, тогда $(U := angle.l bold(e_1), ..., bold(e_(n - 1)) angle.r) sect "Ker" h = {bold(0)}$, так как $Delta_(n - 1) (B) != 0$. Значит $V = U plus.circle U^bot$. Представим $bold(e_n)$ в виде $bold(e_n) = bold(u) + bold(e'_n), bold(u) in U, bold(e'_n) in U^bot, bold(e'_n) != bold(0)$. По предположению индукции, в $U$ можно выбрать подходящий базис $(bold(e'_1), ..., bold(e'_(n - 1)))$, тогда его объединение с $bold(e'_n)$ будет искомым. Матрица перехода $S$ действительно будет верхнетреугольной с единицами на главной диагонали: для первых $n - 1$ столбцов это верно в силу предположения индукции, а для последнего -- в силу $bold(e'_n) = bold(e_n) - bold(u)$ Заметим, что, поскольку базис $e'$ получен описанным выше способом: #eq[ $forall i in overline("1, n") : space bold(e'_i) in angle.l bold(e_1), ..., bold(e_i) angle.r, quad angle.l bold(e_1), ..., bold(e_i) angle.r = angle.l bold(e'_1), ..., bold(e'_i) angle.r $ ] Пусть $B_i$ -- подматрица $B$ в левом верхнем углу, а $B'_i$ -- аналогичная подматрица $B'$. Тогда $B'_i = S^T_i B_i S_i$, где $S_i$ -- соответствующая подматрица $S$, также являющаяся верхнетреугольной с единицами на диагонали, поэтому #eq[ $Delta_i (B') = det B'_i = det(S^T_i B_i S_i) = det B_i = Delta_i (B)$ ] Значит #eq[ $forall i in overline("1, n") : space Delta_i (B) = Delta_i (B')$ ] Откуда, в силу диагональности $B'$, поскольку его $i$-й главный минор равен произведению $i$ диагональных элементов: #eq[ $B' = "diag"(Delta_1 (B), (Delta_2(B)) / (Delta_1(B)), ..., (Delta_n (B)) / (Delta_(n - 1)(B)))$ ] ] == <NAME> #definition[ Пусть $V$ -- линейное пространство над $FF$. Отображение $g : V^n -> FF$ называется *полилинейным*, если оно линейно по каждому из $n$ аргументов. ] #definition[ Пусть $V$ -- линейное пространство над $FF$. Отображение $g: V^n -> FF$ называется *кососимметричным*, если для любых позиций аргументов $i, j in overline("1,n"), i < j$ выполнены следующие условия: + $forall bold(v_i), bold(v_j) in V : g(..., underbrace(bold(v_i), i), ..., underbrace(bold(v_j), j), ...) = -g(..., underbrace(bold(v_j), i), ..., underbrace(bold(v_i), j), ...)$ + $forall bold(v) in V : g(..., underbrace(bold(v), i), ..., underbrace(bold(v), j), ...) = 0$ ] #definition[ *Группой перестановок* $S_n$ называется следующее множество: #eq[ $S_n := {sigma: overline("1, n") -> overline("1, n") | sigma - "биекция"}$ ] Данной множество является группой с операцией композиции $compose$. Элементы группы $S_n$ называются *перестановками*. ] #definition[ *Беспорядком*, или *инверсией* в перестановке $sigma in S_n$ называется пара индексов $(i, j); i,j in overline("1, n")$ такая, что, $i < j$, но $sigma(i) > sigma(j)$. Числа беспорядков в $sigma$ обозначается через $N(sigma)$. *Знаком* перестановки $sigma in S_n$ называется величина $(-1)^(N(sigma))$. Обозначения -- $"sgn" sigma, (-1)^sigma$ ] #definition[ Пусть $A = (a_(i j)) in M_n (FF)$. *Определителем*, или *детерминантом*, матрицы $A$ называется следующая величина: #eq[ $det A := sum_(sigma in S_n) (-1)^sigma a_(1 sigma(1))a_(2 sigma(2))...a_(n sigma(n))$ ] ] #definition[ Пусть $B in M_n(RR)$ -- симметричная матрица. Её *главным минором порядка $i$* называется $Delta_i (B)$ -- определитель подматрицы размера $i times i$, расположенной в левом верхнем углу $B$. ] #definition[ Пусть $B in M_n (RR)$ -- симметрическая матрица. $B$ называется *положительно* или *отрицательно* определённой, если она задаёт квадратичную форму, обладающую этим свойством. ] #definition[ Матрица $A in M_n (FF)$ называется *невырожденной*, если $"rk" A = n$ ] #definition[ Пусть $FF$ -- поле, $n in NN$ - Группа невырожденных матриц порядка $n$ над $FF$ обозначается через $"GL"_n (FF)$ ] #proposition[ $B in M_n (RR)$ положительно определена $<=> exists A in "GL"_n (RR): B = A^T A$ ] #theorem( "<NAME>", )[ Пусть $h in cal(Q)(V), h <->_e B$. Тогда #eq[ $h "положительно определена" <=> forall i in overline("1, n") : space Delta_i (B) > 0$ ] ] #proof[ Пусть $n := dim V$ $=>$ Если $h$ положительно определена, то $exists A in "GL"_n (RR) : B = A^T A$. Тогда $Delta_n (B) = det B = (det A)^2 > 0$. Поскольку главному минору порядка $i in overline("1, n - 1")$ соответствует ограниче $h$ на $U := angle.l bold(e_1), ..., bold(e_i) angle.r$, которое тоже положительно определено, то аналогично $Delta_i (B) > 0$ $arrow.l.double$ Согласно методу Якоби, существует базис $e'$ в $V$ такой, что матрица $h$ в нём диагональна, причём $h <->_(e') (Delta_1 (B), (Delta_2(B)) / (Delta_1(B)), ..., (Delta_n (B)) / (Delta_(n - 1)(B)))$. Все элементы на главной диагонали положительны, поэтому $h$ положительно определена. ]
https://github.com/kimushun1101/typst-jp-conf-template
https://raw.githubusercontent.com/kimushun1101/typst-jp-conf-template/main/main.typ
typst
MIT No Attribution
// MIT No Attribution // Copyright 2024 <NAME> #import "libs/rsj-conf/lib.typ": rsj-conf, gothic #show: rsj-conf.with( title: [Typst を使った国内学会論文の書き方 \ - 国内学会予稿集に似せたフォーマットの作成 - ], authors: [◯ 著者姓1 著者名1,著者姓2 著者名2(○○○大学),著者姓3 著者名3 (□□□株式会社)], abstract: [#lorem(80)], bibliography: bibliography("refs.yml", full: false) ) // #import "libs/rengo/lib.typ": rengo, gothic // #show: rengo.with( // title: [Typst を使った国内学会論文の書き方 \ - 国内学会予稿集に似せたフォーマットの作成 - ], // authors: [◯ 著者姓1 著者名1,著者姓2 著者名2(○○○大学),著者姓3 著者名3 (□□□株式会社)], // etitle: [How to Write a Conference Paper in Japanese], // eauthors: [\*A. First, B. Second (○○○ Univ.), and C. Third (□□□ Corp.)], // abstract: [#lorem(80)], // keywords: ([Typst], [conference paper writing], [manuscript format]), // bibliography: bibliography("refs.yml", full: false) // ) // #import "libs/mscs/lib.typ": mscs, gothic // #show: mscs.with( // title: [Typst を使った国内学会論文の書き方 \ - 国内学会予稿集に似せたフォーマットの作成 - ], // authors: [◯ 著者姓1 著者名1,著者姓2 著者名2(○○○大学),著者姓3 著者名3 (□□□株式会社)], // etitle: [How to Write a Conference Paper in Japanese], // eauthors: [\*<NAME>, <NAME> (○○○ University), and C. Third (□□□ Corporation)], // abstract: [#lorem(80)], // keywords: ([Typst], [conference paper writing], [manuscript format]), // bibliography: bibliography("refs.yml", full: false) // ) // ソースコードブロックを表示するためのパッケージ #import "@preview/sourcerer:0.2.1": code // #import "libs/sourcerer-0.2.1/src/lib.typ": code // 2.3.1 を参照 // 定理環境 #import "@preview/ctheorems:1.1.2": thmplain, thmproof, thmrules // #import "libs/ctheorems-1.1.2/lib.typ": thmplain, thmproof, thmrules // 2.3.1 を参照 #let thmjp = thmplain.with(base: {}, separator: [#h(0.5em)], titlefmt: strong, inset: (top: 0em, left: 0em)) #let definition = thmjp("definition", text(font: gothic)[定義]) #let lemma = thmjp("lemma",text(font: gothic)[補題]) #let theorem = thmjp("theorem", text(font: gothic)[定理]) #let corollary = thmjp("corollary",text(font: gothic)[系]) #let proof = thmproof("proof", text(font: gothic)[証明], separator: [#h(0.9em)], titlefmt: strong, inset: (top: 0em, left: 0em)) // Theorem environment #show: thmrules.with(qed-symbol: $square$) = はじめに #text("これは非公式のサンプルです.", fill: rgb(red), weight: "bold") 適宜投稿先の規定をご確認ください. 発表論文原稿を PDF でご執筆いただき,学会のホームページにアップロードしてください. このファイルはこのテンプレートの使い方を示しており,同時に発表論文の見本でもあります. 執筆の時は以下の説明をよく読み,執筆要項に従ったフォーマットでご提出ください. アップロードした PDF がそのまま公開されます. というような説明が書かれるであろうテンプレートを作ってみました. 本稿では,このテンプレートファイルの使い方および Typst による執筆作業の概要について解説します. この原稿のソースコードは https://github.com/kimushun1101/typst-jp-conf-template で公開しております. Typst の概要についてお知りになりたい方は,https://github.com/kimushun1101/How-to-use-typst-for-paper-jp にもスライド形式の資料を用意しておりますので,ぜひこちらもご覧ください. = テンプレートファイルの使い方 GitHub に慣れていればテンプレートリポジトリを使用して,新しいリポジトリを作成してクローン.不慣れであれば zip ダウンロードして展開してください. テンプレートファイルは以下の2つの方法で実行できることを確認しています. + VS Code とその拡張機能を使う + 好みのエディターで編集した後 CLI (Command Line Interface) でビルドする == Visual Studio Code による執筆 コマンドライン入力に忌避感のある方は(またそうでない方も) Visual Studio Code (VS Code) の使用をオススメします. VS Code の拡張機能である Tinymist Typst をインストールすれば,編集中においても現在の出力結果を常に確認することができます. また,`.vscode/settings.json` にて保存と同時に PDF ファイルが作成される設定にしております. == Typst CLI によるビルド === インストール - Windows の場合\ Windows PowerShell から以下のコマンドでインストールできる. #code( ```sh winget install --id Typst.Typst ``` ) - Mac の場合\ Homebrew を使ってインストールできる. #code( ```sh # Homebrew のインストール /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" # Typst のインストール brew install typst ``` ) - Rust からインストール\ たとえば Ubuntu の場合は,Rust の cargo を使ってインストールする方法が簡単と思われます. #code( ```sh # Rust のインストール curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Typst のインストール cargo install --git https://github.com/typst/typst --locked typst-cli ``` ) === ビルド シェルで対象のディレクトリに移り #code( ```sh typst compile main.typ ``` ) とコマンドすれば main.pdf をビルドできます. == このパッケージが使えない場合 ビルドができない場合などのトラブルがございましたら,https://github.com/kimushun1101/typst-jp-conf-template/issues でご相談ください. 以下に対応方法を記載します. === パッケージの自動インストールができない場合 大学や会社などのプロキシ環境によっては,パッケージの自動インストールがブロックされてしまう可能性がある. その場合には Tyspt Universe から圧縮ファイルを手動でダウンロードする. 本サンプルで使用しているパッケージを入手できるリンクは以下のとおりである. - https://typst.app/universe/package/sourcerer - https://typst.app/universe/package/ctheorems これらの圧縮ファイルを main.typ と同じフォルダーにある libs フォルダーの中に展開した後,以下のようにコメントアウトを付け替えて,それぞれの lib.typ ファイルへのパスを指定する. #code( ```typst // ソースコードブロックを表示するためのパッケージ // #import "@preview/sourcerer:0.2.1": code #import "libs/sourcerer-0.2.1/src/lib.typ": code // 2.3.1 を参照 // 定理環境 // #import "@preview/ctheorems:1.1.2": thmplain, thmproof, thmrules #import "libs/ctheorems-1.1.2/lib.typ": thmplain, thmproof, thmrules // 2.3.1 を参照 ``` ) = 原稿の体裁 == レイアウトとフォント 用紙サイズは A4,縦250 mm,横170 mm の枠内に収まるようにしてください. 余白は,上 20 mm,下27 mm,左20 mm,右20 mm とします. タイトル,著者,アブストラクトはシングルコラム,本文はダブルコラムです. アブストラクトは左右に 0.7 cm 余白を取っています. フォントの設定は @tab:fonts の通りです. ここで,ゴシック体とは "BIZ UDPGothic", "MS PGothic", "Hiragino Kaku Gothic Pro", "IPAexGothic", "Noto Sans CJK JP" のいずれか,明朝体とは "BIZ UDPMincho", "MS PMincho", "Hiragino Mincho Pro", "IPAexMincho", "Noto Serif CJK JP" のいずれかで見つかるものが採用されます. これらのフォントがお使いのコンピュータになければインストールするか,代わりに使いたいフォントがあればソースコードの方に追加してください. 以下のコマンドで使用可能なフォント一覧を確認できます. #code( ```sh typst fonts ``` ) #figure( placement: bottom, caption: [フォントの設定], table( columns: 3, stroke: none, table.header( [項目], [サイズ (pt)], [フォント], ), table.hline(), [#text(18pt, "タイトル", font: gothic)], [18], [ゴシック体], [#text(12pt, "著者名", font: gothic)], [12], [ゴシック体], [#text(12pt, "章タイトル")], [12], [ゴシック体], [節,小節,本文], [10], [明朝体], [#text(9pt, "参考文献")], [9], [明朝体], ) ) <tab:fonts> 今回使用しているテンプレートは "rsj-conf/lib.typ" に記載されています. このテンプレートのソースコードは charge-ieee と abiding-ifacconf というテンプレートを参考にして,第41回日本ロボット学会学術講演会のフォーマットに近づけて作成しました. テンプレートの検索は Typst Universe https://typst.app/universe ででき,そこで掲載されているテンプレートのソースコードは https://github.com/typst/packages/tree/main/packages/preview で見ることができます. == 数式・図・表 数式番号は @eq:system のように数式の右側に, 図のタイトルは "@fig:quadratic タイトル名"のように図の下部に,表のタイトルは "@tab:fonts タイトル名" のように図の上部につきます. 投稿先に応じてキャプションの言語は日本語や英語で指定されるかと思いますので,指示に従ってください. == 定理環境 以下は,theorem 環境の使用例です. 現バージョンでは日本語に太字が使えない変わりに,フォントをゴシックにすることでそれっぽく見せています. #definition("用語 A")[ 用語 A の定義を書きます. ]<def:definition1> #lemma[ 補題を書きます.タイトルは省略することもできます. ]<lem:lemma1> #lemma("補題 C")[ 補題を書きます.番号は定義や補題ごとに 1 からカウントします. ]<lem:lemma2> #theorem("定理 D")[ ここに定理を書きます. ]<thm:theorem1> #corollary[ 系を書きます.@def:definition1 のように,ラベルで参照することもできます. ] #proof([@thm:theorem1 の証明])[ 証明を書きます.証明終了として□印をつけています. ] == 特殊な章 謝辞と参考文献は他の章とは異なり,章番号が自動でつかないように設定しています. また,参考文献は "参 考 文 献" とスペースで区切り,中央揃えにしています. = 編集の仕方 == 論文情報の編集 main.typ の文頭にある以下のコードを解説します. #code( ```typ #import "libs/rsj-conf/lib.typ": rsj-conf #show: rsj-conf.with( title: [Typst を使った国内学会論文の書き方 \ - 国内学会予稿集に似せたフォーマットの作成 - ], authors: [◯ 著者姓1 著者名1,著者姓2 著者名2(○○○大学),著者姓3 著者名3 (□□□株式会社)], abstract: [#lorem(80)], bibliography: bibliography("refs.yml", full: false) ) ``` ) 1 行目はこの原稿の体裁を設定するためのソースコードを import しています. これは "libs" ディレクトリ以下にあります. 2 行目は,ソースコードやコマンドなどを綺麗に表示するための "code" 関数を呼び出すために import しています. こちらは "libs" ディレクトリにはありません. Typst Universe から自動でインストールされたものを使っております. その他,Typst Universe で使いたい packages があるとここで同様に import しておくとよいでしょう. // 今回 rsj-conf という論文体裁手元のファイルを使用しておりますが,テンプレートファイルも登録することができます. // 将来的には Typst Universe に登録しようと思います. 4 行目では,1行目で読み込んだ関数を使用して,原稿体裁を作成しています. 5 行目ではタイトルを,6行目では著者一覧を,7 行目ではアブストラクトを記載します. 各内容の中で改行をしたい場合には,`\` で改行してください. `lorem` 関数は英文のダミーテキストを作成してくれる関数です. 8 行目の参考文献については本章の最後の節で説明します. また,異なるテンプレートも用意してみました. コメントアウトで切り替えてみてください. #code( ```typ #import "libs/rengo/lib.typ": rengo #show: rengo.with( title: [Typst を使った国内学会論文の書き方 \ - 国内学会予稿集に似せたフォーマットの作成 - ], authors: [◯ 著者姓1 著者名1,著者姓2 著者名2(○○○大学),著者姓3 著者名3 (□□□株式会社)], etitle: [How to write a conference paper in Japanese], eauthors: [\*A. First, B. Second (○○○ Univ.), and C. Third (□□□ Corp.)], abstract: [#lorem(80)], keywords: ([Typst], [conference paper writing], [manuscript format]), bibliography: bibliography("refs.yml", full: false) ) ``` ) このフォーマットですと,`etitle`, `eauthors`, `keywords` が追加されており,それぞれ英語タイトル,英語著者名,キーワードを意味しています. `keywords` は`()` のリスト形式で指定されていることに注意してください. `#import` でテンプレートの関数を持ってくるところと,その関数を使用するところ以外の本文部分のコードはテンプレートの変更に応じて変更する必要はありません. == 基本的な文法 章は `=`,節は `==`,小節は `===` で始めます. 改段落は LaTeX と同じく改行を 2 つ以上挟みます. 数字つき箇条書きは `+` で,数字なしの箇条書きは `-` を文頭につけて書くことができます. テキストの装飾は text 関数で行えます. LaTeX に慣れている方は,Typst 公式ページの https://typst.app/docs/guides/guide-for-latex-users/ を読むと雰囲気がつかめると思います. == 数式 数式番号をつけるような中央揃えの数式は,最初の`$` の後ろと閉じの`$` の前にスペースを挟み #code( ```typ $ dot(x) &= A x + B u \ y &= C x $ <eq:system> ``` ) のように書き,文中に書く数式は,`$` の前後にスペースを挟まず #code( ```typ $x in RR^n$ ``` ) というように書きます. ここで `<eq:system>` は引用するときのラベルになります. 出力例はつぎの通りです. 以下のシステムを考える. $ dot(x) &= A x + B u \ y &= C x $ <eq:system> ここで $x in RR^n$ は状態,$u in RR^m$ は入力,$y in RR^l$ は出力,$A in RR^(n times n)$,$B in RR^(n times m)$.および $C in RR^(l times n)$ は定数行列である. このシステムに対して,目標値 $r(t)$ に対する偏差を $e = r - y$ とした以下の PI 制御器を使用する. $ u = K_P e + K_I integral_0^t e d t $ <eq:PI-controller> ただし,$K_P$ と $K_I$ はそれぞれ比例ゲイン,積分ゲインとする. == 図と表 本稿を執筆時のバージョン Typst 0.11.0 では,PNG, JPEG, GIF, SVG の形式のイメージデータを挿入することができます. 例としては以下の通りです. #code( ```typ #figure( placement: bottom, image("figs/quadratic.svg", width: 90%), caption: [$x^2$ のグラフ], ) <fig:quadratic> #figure( placement: bottom, image("figs/sqrt-and-sin.png", width: 90%), caption: [$sqrt(x)$ と $sin x$ のグラフ], ) <fig:sqrt-sin> ``` ) ここで placement は,紙面の上 (top) に寄せるか下 (bottom) に寄せるかを決められます.言及している文章に近い方に調整してください. #figure( placement: bottom, image("figs/quadratic.svg", width: 90%), caption: [$x^2$ のグラフ], ) <fig:quadratic> #figure( placement: bottom, image("figs/sqrt-and-sin.png", width: 90%), caption: [$sqrt(x)$ と $sin x$ のグラフ], ) <fig:sqrt-sin> @tab:fonts は以下で記述されております. #code( ```typ #figure( placement: top, caption: [フォントの設定], table( columns: 3, stroke: none, table.header( [項目], [サイズ (pt)], [フォント], ), table.hline(), [#text(18pt, "タイトル", font: gothic)], [18], [ゴシック体], [#text(12pt, "著者名", font: gothic)], [12], [ゴシック体], [#text(12pt, "章タイトル")], [12], [ゴシック体], [節,小節,本文], [10], [明朝体], [#text(9pt, "参考文献")], [9], [明朝体], ) ) <tab:fonts> ``` ) table の columns の数に応じて,文字列の配列が自動的に整列されます. `stroke: none` は枠線を消しています.`table.hline()` を挟むとその位置に横線を引けます. ここで,`gothic` は `lib.typ` で定義されています. 他のテンプレートを使用する場合には注意をしてください. #code( ```typ #import "libs/rsj-conf/lib.typ": rsj-conf, gothic ``` ) == 定理環境 @def:definition1 や @lem:lemma1 などは以下で記述されております. #code( ```typ #definition("用語 A")[ 用語 A の定義を書きます. ]<def:definition1> #lemma[ 補題を書きます.タイトルは省略することもできます. ]<lem:lemma1> #lemma("補題 C")[ 補題を書きます.番号は定義や補題ごとに 1 からカウントします. ]<lem:lemma2> #theorem("定理 D")[ ここに定理を書きます. ]<thm:theorem1> #corollary[ 系を書きます.@def:definition1 のように,ラベルで参照することもできます. ] #proof([@thm:theorem1 の証明])[ 証明を書きます.証明終了として□印をつけています. ] ``` ) ここで,`definition`, `lemma`, `theorem`, `corollary`, `proof` は `gothic` と同様に `lib.typ` で定義されています. 他のテンプレートを使用する場合には注意をしてください. #code( ```typ #import "libs/rsj-conf/lib.typ": rsj-conf, gothic ``` ) さらに元をたどると `lib.typ` で ctheorems パッケージ (https://typst.app/universe/package/ctheorems) をインポートして使用しております. #code( ```typ // Theorem environment #import "@preview/ctheorems:1.1.2": thmplain, thmproof, thmrules #let thmjp = thmplain.with(base: {}, separator: [#h(0.5em)], titlefmt: strong, inset: (top: 0em, left: 0em)) #let definition = thmjp("definition", text(font: gothic)[定義]) #let lemma = thmjp("lemma",text(font: gothic)[補題]) #let theorem = thmjp("theorem", text(font: gothic)[定理]) #let corollary = thmjp("corollary",text(font: gothic)[系]) #let proof = thmproof("proof", text(font: gothic)[証明], separator: [#h(0.9em)], titlefmt: strong, inset: (top: 0em, left: 0em)) ``` ) == 参考文献 参考文献は `refs.yml` に記載してください. Hayagriva という YAML 形式のフォーマットに従っています. 編集するだけであれば特に解説する必要はないと思います. 詳細が気になる方は https://github.com/typst/hayagriva をご参照ください. 参考文献の体裁は `libs/rsj-conf/bib.csl` で制御しています. これは Citation Style Language という XML 形式で記述されております. CSL ファイルは著者が編集する必要はありませんが,詳細が気になる方は https://citationstyles.org/ をご参照ください. 日本語論文として重要な点は,CSL ファイルでは Hayagriva で記述された `language` の属性を見て,著者表示を"カンマ区切りのみ"にするか"カンマ区切り+最終著者の前にand" にするかを決定している点です. したがって,英語文献だけでしたら YAML ファイルの代わりに bib ファイルも使用することができます. 文献内で引用された順番にフォーマットを整えて自動で参考文献の章が作られます. 引用の方法については後述します. 完成原稿では推奨されませんが,引用されていない論文も記載したい場合には full: true にすれば,すべての文献が出力されます. == 引用 引用は "\@label" と記述することで,数式であれば @eq:system,図であれば @fig:quadratic,表であれば @tab:fonts,参考文献であれば @kimura2015asymptotic のように表示されます. 参考文献は連続して引用すると @kimura2017state @kimura2021control @kimura2020facility @khalil2002control @sugie1999feedback @shimz2022visually と繋げられて表示されます. 文法上では特に規則はありませんが,個人的にはラベルの命名規則として,図の場合には "fig:" から,表の場合には"tab:" から始めるようにラベル名を設定しており,参考文献のラベルは "著者名発行年タイトルの最初の単語"で名付けております. = おわりに 筆者の理解や表現が誤っている箇所もあるかと思います. #link("https://github.com/kimushun1101/typst-jp-conf-template")[GitHub] を通して,Issues や Pull Reqests を歓迎しております. 日本語での投稿で構いません. 誤字脱字や文法,表現など細かい修正でも大変ありがたいです. 筆者は,Typst が普及するためには学会のフォーマットで配布されることが不可欠だと感じています. 異なる学会のフォーマットも随時 `libs` ディレクトリに追加していこうと思っております. これらのファイルがTypst が普及の一助となれば幸いです. = 謝辞 謝辞には章番号が振られないように設定しております. 「この研究は☆☆☆の助成を受けて行われました.」や「〇〇〇大学との共同研究です.」 みたいな文章が書かれることを想定しています. 最後までお読みいただき誠にありがとうございました.
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/017.%20desres.html.typ
typst
desres.html Design and Research January 2003(This article is derived from a keynote talk at the fall 2002 meeting of NEPLS.)Visitors to this country are often surprised to find that Americans like to begin a conversation by asking "what do you do?" I've never liked this question. I've rarely had a neat answer to it. But I think I have finally solved the problem. Now, when someone asks me what I do, I look them straight in the eye and say "I'm designing a new dialect of Lisp." I recommend this answer to anyone who doesn't like being asked what they do. The conversation will turn immediately to other topics.I don't consider myself to be doing research on programming languages. I'm just designing one, in the same way that someone might design a building or a chair or a new typeface. I'm not trying to discover anything new. I just want to make a language that will be good to program in. In some ways, this assumption makes life a lot easier.The difference between design and research seems to be a question of new versus good. Design doesn't have to be new, but it has to be good. Research doesn't have to be good, but it has to be new. I think these two paths converge at the top: the best design surpasses its predecessors by using new ideas, and the best research solves problems that are not only new, but actually worth solving. So ultimately we're aiming for the same destination, just approaching it from different directions.What I'm going to talk about today is what your target looks like from the back. What do you do differently when you treat programming languages as a design problem instead of a research topic?The biggest difference is that you focus more on the user. Design begins by asking, who is this for and what do they need from it? A good architect, for example, does not begin by creating a design that he then imposes on the users, but by studying the intended users and figuring out what they need.Notice I said "what they need," not "what they want." I don't mean to give the impression that working as a designer means working as a sort of short-order cook, making whatever the client tells you to. This varies from field to field in the arts, but I don't think there is any field in which the best work is done by the people who just make exactly what the customers tell them to.The customer is always right in the sense that the measure of good design is how well it works for the user. If you make a novel that bores everyone, or a chair that's horribly uncomfortable to sit in, then you've done a bad job, period. It's no defense to say that the novel or the chair is designed according to the most advanced theoretical principles.And yet, making what works for the user doesn't mean simply making what the user tells you to. Users don't know what all the choices are, and are often mistaken about what they really want.The answer to the paradox, I think, is that you have to design for the user, but you have to design what the user needs, not simply what he says he wants. It's much like being a doctor. You can't just treat a patient's symptoms. When a patient tells you his symptoms, you have to figure out what's actually wrong with him, and treat that.This focus on the user is a kind of axiom from which most of the practice of good design can be derived, and around which most design issues center.If good design must do what the user needs, who is the user? When I say that design must be for users, I don't mean to imply that good design aims at some kind of lowest common denominator. You can pick any group of users you want. If you're designing a tool, for example, you can design it for anyone from beginners to experts, and what's good design for one group might be bad for another. The point is, you have to pick some group of users. I don't think you can even talk about good or bad design except with reference to some intended user.You're most likely to get good design if the intended users include the designer himself. When you design something for a group that doesn't include you, it tends to be for people you consider to be less sophisticated than you, not more sophisticated.That's a problem, because looking down on the user, however benevolently, seems inevitably to corrupt the designer. I suspect that very few housing projects in the US were designed by architects who expected to live in them. You can see the same thing in programming languages. C, Lisp, and Smalltalk were created for their own designers to use. Cobol, Ada, and Java, were created for other people to use.If you think you're designing something for idiots, the odds are that you're not designing something good, even for idiots. Even if you're designing something for the most sophisticated users, though, you're still designing for humans. It's different in research. In math you don't choose abstractions because they're easy for humans to understand; you choose whichever make the proof shorter. I think this is true for the sciences generally. Scientific ideas are not meant to be ergonomic.Over in the arts, things are very different. Design is all about people. The human body is a strange thing, but when you're designing a chair, that's what you're designing for, and there's no way around it. All the arts have to pander to the interests and limitations of humans. In painting, for example, all other things being equal a painting with people in it will be more interesting than one without. It is not merely an accident of history that the great paintings of the Renaissance are all full of people. If they hadn't been, painting as a medium wouldn't have the prestige that it does.Like it or not, programming languages are also for people, and I suspect the human brain is just as lumpy and idiosyncratic as the human body. Some ideas are easy for people to grasp and some aren't. For example, we seem to have a very limited capacity for dealing with detail. It's this fact that makes programing languages a good idea in the first place; if we could handle the detail, we could just program in machine language.Remember, too, that languages are not primarily a form for finished programs, but something that programs have to be developed in. Anyone in the arts could tell you that you might want different mediums for the two situations. Marble, for example, is a nice, durable medium for finished ideas, but a hopelessly inflexible one for developing new ideas.A program, like a proof, is a pruned version of a tree that in the past has had false starts branching off all over it. So the test of a language is not simply how clean the finished program looks in it, but how clean the path to the finished program was. A design choice that gives you elegant finished programs may not give you an elegant design process. For example, I've written a few macro-defining macros full of nested backquotes that look now like little gems, but writing them took hours of the ugliest trial and error, and frankly, I'm still not entirely sure they're correct.We often act as if the test of a language were how good finished programs look in it. It seems so convincing when you see the same program written in two languages, and one version is much shorter. When you approach the problem from the direction of the arts, you're less likely to depend on this sort of test. You don't want to end up with a programming language like marble.For example, it is a huge win in developing software to have an interactive toplevel, what in Lisp is called a read-eval-print loop. And when you have one this has real effects on the design of the language. It would not work well for a language where you have to declare variables before using them, for example. When you're just typing expressions into the toplevel, you want to be able to set x to some value and then start doing things to x. You don't want to have to declare the type of x first. You may dispute either of the premises, but if a language has to have a toplevel to be convenient, and mandatory type declarations are incompatible with a toplevel, then no language that makes type declarations mandatory could be convenient to program in.In practice, to get good design you have to get close, and stay close, to your users. You have to calibrate your ideas on actual users constantly, especially in the beginning. One of the reasons <NAME>'s novels are so good is that she read them out loud to her family. That's why she never sinks into self-indulgently arty descriptions of landscapes, or pretentious philosophizing. (The philosophy's there, but it's woven into the story instead of being pasted onto it like a label.) If you open an average "literary" novel and imagine reading it out loud to your friends as something you'd written, you'll feel all too keenly what an imposition that kind of thing is upon the reader.In the software world, this idea is known as Worse is Better. Actually, there are several ideas mixed together in the concept of Worse is Better, which is why people are still arguing about whether worse is actually better or not. But one of the main ideas in that mix is that if you're building something new, you should get a prototype in front of users as soon as possible.The alternative approach might be called the Hail Mary strategy. Instead of getting a prototype out quickly and gradually refining it, you try to create the complete, finished, product in one long touchdown pass. As far as I know, this is a recipe for disaster. Countless startups destroyed themselves this way during the Internet bubble. I've never heard of a case where it worked.What people outside the software world may not realize is that Worse is Better is found throughout the arts. In drawing, for example, the idea was discovered during the Renaissance. Now almost every drawing teacher will tell you that the right way to get an accurate drawing is not to work your way slowly around the contour of an object, because errors will accumulate and you'll find at the end that the lines don't meet. Instead you should draw a few quick lines in roughly the right place, and then gradually refine this initial sketch.In most fields, prototypes have traditionally been made out of different materials. Typefaces to be cut in metal were initially designed with a brush on paper. Statues to be cast in bronze were modelled in wax. Patterns to be embroidered on tapestries were drawn on paper with ink wash. Buildings to be constructed from stone were tested on a smaller scale in wood.What made oil paint so exciting, when it first became popular in the fifteenth century, was that you could actually make the finished work from the prototype. You could make a preliminary drawing if you wanted to, but you weren't held to it; you could work out all the details, and even make major changes, as you finished the painting.You can do this in software too. A prototype doesn't have to be just a model; you can refine it into the finished product. I think you should always do this when you can. It lets you take advantage of new insights you have along the way. But perhaps even more important, it's good for morale.Morale is key in design. I'm surprised people don't talk more about it. One of my first drawing teachers told me: if you're bored when you're drawing something, the drawing will look boring. For example, suppose you have to draw a building, and you decide to draw each brick individually. You can do this if you want, but if you get bored halfway through and start making the bricks mechanically instead of observing each one, the drawing will look worse than if you had merely suggested the bricks.Building something by gradually refining a prototype is good for morale because it keeps you engaged. In software, my rule is: always have working code. If you're writing something that you'll be able to test in an hour, then you have the prospect of an immediate reward to motivate you. The same is true in the arts, and particularly in oil painting. Most painters start with a blurry sketch and gradually refine it. If you work this way, then in principle you never have to end the day with something that actually looks unfinished. Indeed, there is even a saying among painters: "A painting is never finished, you just stop working on it." This idea will be familiar to anyone who has worked on software.Morale is another reason that it's hard to design something for an unsophisticated user. It's hard to stay interested in something you don't like yourself. To make something good, you have to be thinking, "wow, this is really great," not "what a piece of shit; those fools will love it."Design means making things for humans. But it's not just the user who's human. The designer is human too.Notice all this time I've been talking about "the designer." Design usually has to be under the control of a single person to be any good. And yet it seems to be possible for several people to collaborate on a research project. This seems to me one of the most interesting differences between research and design.There have been famous instances of collaboration in the arts, but most of them seem to have been cases of molecular bonding rather than nuclear fusion. In an opera it's common for one person to write the libretto and another to write the music. And during the Renaissance, journeymen from northern Europe were often employed to do the landscapes in the backgrounds of Italian paintings. But these aren't true collaborations. They're more like examples of <NAME>'s "good fences make good neighbors." You can stick instances of good design together, but within each individual project, one person has to be in control.I'm not saying that good design requires that one person think of everything. There's nothing more valuable than the advice of someone whose judgement you trust. But after the talking is done, the decision about what to do has to rest with one person.Why is it that research can be done by collaborators and design can't? This is an interesting question. I don't know the answer. Perhaps, if design and research converge, the best research is also good design, and in fact can't be done by collaborators. A lot of the most famous scientists seem to have worked alone. But I don't know enough to say whether there is a pattern here. It could be simply that many famous scientists worked when collaboration was less common.Whatever the story is in the sciences, true collaboration seems to be vanishingly rare in the arts. Design by committee is a synonym for bad design. Why is that so? Is there some way to beat this limitation?I'm inclined to think there isn't-- that good design requires a dictator. One reason is that good design has to be all of a piece. Design is not just for humans, but for individual humans. If a design represents an idea that fits in one person's head, then the idea will fit in the user's head too.Related:Japanese TranslationTaste for MakersRomanian TranslationSpanish Translation
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/literature-review/preact.typ
typst
#import "/components/glossary.typ": gls == Preact <sec-preact> Preact is a popular JavaScript library that serves as a lightweight alternative to React. Designed to be smaller and faster, Preact offers many of the same features and benefits while maintaining a minimal footprint. This section will explore the key characteristics, advantages, and considerations of using Preact in your web development projects. Preact is a compelling choice for developers seeking a lightweight and high-performance alternative to React. Its focus on simplicity, speed, and compatibility with React's #gls("api") makes it a valuable tool for building modern web applications. While there may be some considerations and limitations to keep in mind, Preact's benefits often outweigh the challenges, making it a strong contender for your next project @bib-preact. === Key Features of Preact - *Virtual DOM*: Preact utilizes a virtual #gls("dom"), similar to React, for efficient updates and rendering. - *JSX Support*: Preact supports #gls("jsx") syntax, making it easy to write declarative components. - *Small Footprint*: Preact has a significantly smaller bundle size compared to React, leading to faster load times and improved performance. - *API Compatibility*: Preact maintains a high degree of compatibility with React's #gls("api"), making it easier for developers to migrate from React or use both libraries together. - *Community and Ecosystem*: Preact has a growing community and ecosystem of tools and resources, supporting its development and adoption. === Benefits of Using Preact - *Improved Performance*: Preact's smaller bundle size and efficient rendering engine contribute to faster page load times and better user experience. - *Lightweight and Minimalistic*: Preact's focus on simplicity and minimalism makes it suitable for projects that prioritize performance and maintainability. - *Compatibility with React*: The similarity between Preact and React's #gls("apis") allows for easier migration and the potential to use both libraries together in larger projects. - *Active Community*: Preact benefits from a growing community of developers and contributors, ensuring ongoing development and support.
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/VerbaliInterni/VerbaleInterno_240322/content.typ
typst
MIT License
#import "meta.typ": inizio_incontro, fine_incontro, luogo_incontro #import "functions.typ": glossary, team #let participants = csv("participants.csv") = Partecipanti / Inizio incontro: #inizio_incontro / Fine incontro: #fine_incontro / Luogo incontro: #luogo_incontro #table( columns: (3fr, 1fr), [*Nome*], [*Durata presenza*], ..participants.flatten() ) = Sintesi Elaborazione Incontro /*************************************/ /* INSERIRE SOTTO IL CONTENUTO */ /*************************************/ Nell'incontro si è discussa l'organizzazione del lavoro futuro sotto un punto di vista più tecnico del solito, in quanto il gruppo è in procinto di consegna per la seconda revisione e di conseguenza cerca di raffinare il prodotto secondo quanto enunciato dalla documentazione. Di seguito se ne riportano i momenti salienti. == Nuovi ruoli Vengono stabiliti i seguenti i nuovi incarichi relativi allo sprint corrente: - <NAME>: Verificatore, Programmatore; - <NAME>: Responsabile, Programmatore; - <NAME>: Programmatore, Verificatore; - <NAME>: Analista, Progettista, Verificatore; - <NAME>: Progettista, Verificatore; - <NAME>: Responsabile, Programmatore. == Analisi dei Requisiti Il team si è reso conto che il prodotto non rispecchia appieno quanto enunciato all'interno dell'_Analisi dei Requisiti_, per funzionalità o modalità di funzionamento. Di conseguenza si è deciso di allocare risorse nella correzione del prodotto ove necessario e nella chiarificazione del documento _Analisi dei Requisiti_ dove la chiarezza non risulta sufficiente. == Manuale Utente Sono state rilevate alcune mancanze nel processo di installazione illustrato all'interno del documento _Manuale Utente_ e che dunque non consentirebbero all'utente di poter installare e utilizzare il prodotto. Perciò sono state allocate risorse nell'ampiamento delle sezioni di installazione e uso, al fine di rimuovere queste lacune. == Specifica Tecnica Il team ha rilevato alcune ambiguità nella sezione relativa al tracciamento dei requisiti soddisfatti. Viene creata una task in modo tale da poter risolvere tali ambiguità. == Grafana Sono stati rilevati alcuni problemi relativi alla componente Grafana: il primo relativo alla tabella dei dati grezzi, il secondo relativo alla componente di notifica. La dashboard dei dati grezzi infatti risulta al momento troppo caotica e di difficile consultazione. Se ne occupa <NAME>. La componente di notifica di Grafana invece risulta particolarmente ostica e sta richiedendo più risorse di quanto previsto. Alla luce del fatto che tale componente sia comunque il frutto di un requisito desiderabile permette al team di non preoccuparsene eccessivamente. Se ne occupa <NAME>.
https://github.com/FlyinPancake/bsc-thesis
https://raw.githubusercontent.com/FlyinPancake/bsc-thesis/main/thesis/pages/abstract.typ
typst
#import "@preview/big-todo:0.2.0": todo #page[ #set text(lang: "hu") = Kivonat A szakdolgozat célja a virtuális Kubernetes klaszterekkel kapcsolatos jelenlegi állapot felmérése. A virtuális klaszterek ebben az összefüggésben egyetlen Kubernetes klaszteren belül létrehozott elszigetelt Kubernetes klaszterekre utalnak. Ez a megközelítés előnyösnek bizonyul tesztelési célokra, különböző felhasználók számára elszigetelt környezetek létrehozására és verziókonfliktusok kezelésére. A vcluster egy virtuális Kubernetes klaszter implementáció, amelyet ez a szakdolgozat részletesen vizsgál. A szakdolgozat első része egy átfogó irodalomkutatást tartalmaz a Kubernetes ökoszisztémáról, különös figyelemmel a vcluster funkcióira és képességeire. Ezen ismeretek alapul szolgálnak a vcluster-el kapcsolatos elvárások meghatározásához, és biztosítja a szélesebb Kubernetes ökoszisztéma alapos megértését. Az irodalomkutatást követő szakasz részletesen ismerteti a virtuális klaszterek teljesítmény és funkcionalitás értékeléséhez végzett tesztek tervezését. Ez magában foglalja a teszteléshez használt eszközökkel való megismerkedést, a tesztesetek ismertetését és a kiválasztásuk mögötti indoklást, valamint a tesztelési környezet részletes leírását. A szakdolgozat ezután bemutatja a tesztelési fázis során szerzett tapasztalatokat, kiemelve az összes felmerülő problémát és a kialakított megoldásokat. Fontos megjegyezni, hogy a kezdeti módszertan módosítására is sor került, amelynek célja a releváns és megbízható eredmények elérése. Végül a szakdolgozat felvázol vcluster-hez kapcsolódoó jövőbeli kutatási lehetőségeket, és betekintést nyújt azokba a területekbe, amelyek további felfedezést igényelnek. A kutatás eredményeinek részletes megvitatása, valamint a kutatás következményeinek értékelése zárja a szakdolgozatot. ] #page[ = Abstract The primary objective of this thesis is to evaluate the current state of the art in the realm of virtual Kubernetes clusters. Virtual clusters, in this context, refer to the creation of isolated Kubernetes clusters within a single Kubernetes cluster. This approach proves beneficial for testing purposes, establishing isolated environments for various use-ceses, and mitigating version conflicts. In particular, this thesis examines vcluster, a virtual Kubernetes cluster implementation. The initial section of the thesis comprises of a comprehensive literature review covering the Kubernetes ecosystem and specifically delving into the features and capabilities of vcluster. This review serves as a foundation for establishing expectations related to vcluster and ensures a thorough understanding of the broader Kubernetes landscape. Following the literature review, the subsequent section provides a detailed account of the tests conducted to assess the performance and functionality of virtual clusters. This involves familiarizing ourselves with the testing tools employed, outlining the chosen test cases, and explaining the rationale behind their selection, along with a thorough description of the testing environment. The thesis then proceeds to review the findings gathered in the testing phase, highlighting any encountered issues and detailing the corresponding solutions devised. Importantly, adjustments to the initial methodology are presented, uderscoring the necessity for modifications to attain meaningful and reliable results. Lastly, the thesis outlines potential avenues for future research on vcluster, offering insights into areas that merit further exploration. A comprehensive discussion of the findings, along with reflections on the implications of the research, concludes the thesis. ]
https://github.com/remggo/cookbook-typst
https://raw.githubusercontent.com/remggo/cookbook-typst/main/README.md
markdown
MIT License
# Cookbook Typst A recipe template for [Typst](https://typst.app). ## Features - Nice Layout for recipes - Use YAML to separate your recipe data from the presentation - Very configurable **Note**: The package only creates the layout of a recipe. Page setup and margins are left intentionally untouched. ## Screenshots ![Example Recipe Page](images/example1.png)
https://github.com/yasemitee/Teoria-Informazione-Trasmissione
https://raw.githubusercontent.com/yasemitee/Teoria-Informazione-Trasmissione/main/2023-10-10.typ
typst
#import "@preview/lemmify:0.1.4": * #let ( theorem, lemma, corollary, remark, proposition, example, proof, rules: thm-rules ) = default-theorems("thm-group", lang: "it") #show: thm-rules #show thm-selector("thm-group", subgroup: "proof"): it => block( it, stroke: green + 1pt, inset: 1em, breakable: true ) = Codici Come detto nella scorsa lezione, andiamo a considerare dei codici non singolari per risolvere la problematica dei due _codici banali_, che minimizzavano sì il valore atteso delle lunghezze delle parole di codice $l_c (x)$, ma rendevano impossibile la decodifica. Andiamo ora a raffinare ulteriormente i codici singolari presi in considerazione. == Codice univocamente decodificabile Come detto nella scorsa lezione, siamo interessati alle parole che vengono generate dalla mia sorgente, e non ai singoli caratteri. Andiamo a definire: - $Chi = {suit.heart, suit.diamond, suit.club, suit.spade}$ insieme dei simboli sorgente; - $c : Chi arrow.long.r {0,1}^+$ funzione di codifica; - $c(suit.heart) = 0$; - $c(suit.diamond) = 01$; - $c(suit.club) = 010$; - $c(suit.spade) = 10$. La codifica $c$ scelta è sicuramente non singolare, però abbiamo delle problematiche a livello di decodifica: infatti, possiamo scrivere $01001$ come $c(suit.club, suit.diamond)$, $c(suit.diamond, suit.heart, suit.diamond)$ o $c(suit.heart, suit.spade, suit.diamond)$, e lato ricevente questo è un problema, perché "unendo" tutte le singole codifiche non otteniamo una parola che è generabile in modo unico. Introduciamo quindi l'*estensione* di un codice $c$: essa è un codice $C : Chi^+ arrow.long.r DD^+$ definito come $C(x_1, dots, x_n) = c(x_1) dots c(x_n)$ che indica la sequenza ottenuta giustapponendo le parole di codice $c(x_1), dots, c(x_n)$. L'estensione $C$ di un codice $c$ non eredita in automatico la proprietà di non singolarità di $c$. Un codice $c$ è *univocamente decodificabile* quando la sua estensione $C$ è non singolare. Tramite l'*algoritmo di Sardinas-Patterson* siamo in grado di stabilire se un codice è univocamente decodificabile in tempo $O(\m\L)$, dove $m = abs(Chi)$ e $L = limits(sum)_(x in Chi) l_c (x)$ == Codice istantaneo I codici univocamente decodificabili sono ottimali? Sto minimizzando al meglio $EE[l_c]$? Prima di chiederci questo vogliamo creare un codice che rispetti un'altra importante proprietà: permetterci di decodificare _subito_ quello che mi arriva dal canale senza dover aspettare tutto il flusso. Andiamo a definire: - $Chi = {suit.heart, suit.diamond, suit.club, suit.spade}$ insieme dei simboli sorgente; - $c : Chi arrow.long.r {0,1}^+$ funzione di codifica; - $c(suit.heart) = 10$; - $c(suit.diamond) = 00$; - $c(suit.club) = 11$; - $c(suit.spade) = 110$. Supponiamo di spedire sul canale la stringa $11000 dots 00$, e poniamoci lato ricevente. In base al numero di $0$ inviati abbiamo due possibili decodifiche: - $\#0$ pari: decodifichiamo con $suit.club suit.diamond dots suit.diamond$; - $\#0$ dispari: decodifichiamo con $suit.spade suit.diamond dots suit.diamond$. Nonostante si riesca perfettamente a decodificare, e questo è dato dal fatto che $c$ è un codice univocamente decodificabile, dobbiamo aspettare di ricevere tutta la stringa per poterla poi decodificare, ma in ambiti come lo _streaming_ questa attesa non è possibile. Un altro problema lo riscontriamo a livello di memoria: supponiamo che lato sorgente vengano codificati dei dati dell'ordine dei terabyte, per il ricevente sarà impossibile tenere in memoria una quantità simile di dati per fare la decodifica alla fine della ricezione. Introduciamo quindi i *codici istantanei*, particolari codici che permettono di decodificare quello che arriva dal canale, appunto, in modo _istantaneo_ senza aspettare. Un codice si dice istantaneo se nessuna parola di codice è _prefissa_ di altre. Andiamo a definire: - $Chi = {suit.heart, suit.diamond, suit.club, suit.spade}$ insieme dei simboli sorgente; - $c : Chi arrow.long.r {0,1}^+$ funzione di codifica; - $c(suit.heart) = 0$; - $c(suit.diamond) = 10$; - $c(suit.club) = 110$; - $c(suit.spade) = 111$. Il seguente codice è istantaneo, e lo notiamo osservando l'_albero_ che dà origine a questo codice. #v(12pt) #figure( image("assets/2023-10-10_albero-istantaneo.svg", width: 25%) ) #v(12pt) Quello che otteniamo è un albero molto sbilanciato. == Gerarchia dei codici Cerchiamo infine di definire una *gerarchia* tra i codici analizzati fin'ora: se siamo sicuri che i codici non singolari siano sotto-insieme di tutti i codici (_banale_), e che i codici univocamente decodificabili siano sotto-insieme dei codici non singolari (_banale_), siamo sicuri che i codici istantanei siano un sotto-insieme dei codici univocamente decodificabili? #lemma(numbering: none)[ Se $c$ è istantaneo allora è anche univocamente decodificabile. ]<thm> #proof[ \ Andiamo a dimostrare che se $c$ non è univocamente decodificabile allora non è istantaneo. Visto che $c$ è non decodificabile (supponiamo sia almeno non singolare) esistono due messaggi distinti $x_1, x_2 in Chi^+$ tali che $C(x_1) = C(x_2)$. Ci sono solo due modi per avere $x_1$ e $x_2$ distinti: + un messaggio è prefisso dell'altro: se $x_1$ è formato da $x_2$ e altri $m$ caratteri, vuol dire che i restanti $m$ caratteri di $x_1$ devono essere codificati con la parola vuota, che per definizione di codice non è possibile, e soprattutto la parola vuota sarebbe prefissa di ogni altra parola di codice, quindi il codice $c$ non è istantaneo; + esiste almeno una posizione in cui i due messaggi differiscono: sia $i$ la prima posizione dove i due messaggi differiscono, ovvero $x_1[i] eq.not x_2[i]$ e $x_1[j] = x_2[j]$ per $1 lt.eq j lt.eq i - 1$, ma allora $c(x_1[i]) eq.not c(x_2[i])$ e $c(x_1[j]) = c(x_2[j])$ perché $c$ è non singolare, quindi sto dicendo che $x_1$ deve avere $x_2$ come prefisso (o viceversa), ma, come al punto precedente, otteniamo che $c$ non è istantaneo. Quindi il codice $c$ non è istantaneo. ]<proof> Abbiamo quindi stabilito una gerarchia di questo tipo: $ "codici istantanei" subset "codici univocamente decodificabili" subset "codici non singolari" $ Una cosa che possiamo notare è come, aumentando di volta in volta le proprietà di un codice, e quindi passando di "classe" in "classe", il valore atteso $EE[l_c]$ che vogliamo minimizzare peggiora, o al massimo rimane uguale: questo perché aggiungendo delle proprietà al nostro codice imponiamo dei limiti che aumentano in modo forzato la lunghezza delle nostre parole di codice. #pagebreak() = Disuguaglianza di Kraft == Definizione I codici istantanei soddisfano la *disuguaglianza di Kraft*, che ci permette, solo osservando le lunghezze delle parole di codice $l_c (x)$, di dire _se esiste_ un codice istantaneo con quelle lunghezze. #theorem(name: "Disuguaglianza di Kraft", numbering: none)[ Dati $Chi = {x_1, dots, x_n}$, $D > 1$ e $n$ valori interi positivi $l_1, dots, l_n$, esiste un codice istantaneo $c : Chi arrow DD^+$ tale che $l_c (x_i) = l_i$ per $i = 1, dots, n$ se e solo se $ sum_(i=1)^(n) D^(-l_i) lt.eq 1. $ ]<thm> #proof[ \ ($arrow.long.double.r$) Sia $l_(max)$ la lunghezza massima delle parole di $c$, ovvero $l_(max) = limits(max)_(i = 1, dots, n) (l_c (x_i))$. \ Si consideri l'albero $D$-ario completo di profondità $l_(max)$ nel quale posizioniamo ogni parola di codice di $c$ su un nodo dell'albero, seguendo dalla radice il cammino corrispondente ai simboli della parola. Dato che il codice è istantaneo, nessuna parola apparterrà al sotto-albero avente come radice un'altra parola di codice, altrimenti avremmo una parola di codice prefissa di un'altra. Andiamo ora a partizionare le foglie dell'albero in sottoinsiemi disgiunti $A_1, dots, A_n$, dove $A_i$ indica il sottoinsieme di foglie associate alla radice contenente la parola $c(x_i)$. \ Nel seguente esempio consideriamo un albero binario di altezza $3$, e in rosso sono evidenziate le parole di codice $1$, $00$, $010$, e $011$. \ #v(12pt) #figure( image("assets/2023-10-10_albero-dimostrazione.svg", width: 100%) ) #v(12pt) Il numero massimo di foglie di un sotto-albero di altezza $l_i$ è $D^(l_(max) - l_i)$, ma il numero massimo di foglie nell'albero è $D^(l_(max))$, quindi $ underbracket(sum_(i=1)^n abs(A_i) = sum_(i=1)^n D^(l_(max) - l_i), "#foglie coperte") = sum_(i=1)^n D^(l_(max)) dot D^(-l_i) = D^(l_(max)) sum_(i=1)^n D^(-l_i) lt.eq D^(l_(max)). $ Dividendo per $D^(l_(max))$ entrambi i membri otteniamo la disuguaglianza di Kraft. \ \ ($arrow.long.double.l$) Assumiamo di avere $n$ lunghezze positive $l_1, dots, l_n$ che soddisfano la disuguaglianza di Kraft e sia $l_(max) = limits(max)_(i = 1, dots, n) (l_i)$ la profondità dell'albero $D$-ario ordinato e completo usato prima. \ Associamo ad ogni simbolo $x_i in Chi$ la parola di codice $c(x_1)$, e la inseriamo al primo nodo di altezza $l_i$ che troviamo in ordine lessicografico. Durante l'inserimento delle parole $c(x_i)$ dobbiamo escludere tutti i nodi che appartengono a sotto-alberi con radice una parola di codice già inserita o che includono un sotto-albero con radice una parola di codice già inserita. \ Il codice così costruito è istantaneo, e visto che rispetta la disuguaglianza di Kraft, la moltiplichiamo da entrambi i membri per $D^(l_(max))$ per ottenere $ sum_(i=1)^m D^(l_(max) - l_i) lt.eq D^(l_(max)), $ ovvero il numero di foglie necessarie a creare il codice non eccede il numero di foglie disponibili nell'albero. ]<proof> == Applicazione Andiamo a definire: - $Chi = {suit.heart, suit.diamond, suit.club, suit.spade}$ insieme dei simboli sorgente; - $c : Chi arrow.long.r {0,1}^+$ funzione di codifica; - $l_c (suit.heart) = 3$; - $l_c (suit.diamond) = 1$; - $l_c (suit.club) = 3$; - $l_c (suit.spade) = 2$. Vogliamo sapere se esiste un codice istantaneo, definito come $c$, aventi le lunghezze sopra definite: controlliamo quindi se esse soddisfano la disuguaglianza di Kraft. $ sum_(x in Chi) 2^(-l_c (x)) = 2^(-3) + 2^(-1) + 2^(-3) + 2^(-2) = 1 / 8 + 1 / 2 + 1 / 8 + 1 / 4 = 1 lt.eq 1. $ Andiamo a costruire quindi un codice istantaneo con queste lunghezze costruendo il suo albero. #v(12pt) #figure( image("assets/2023-10-10_albero-kraft-1.svg", width: 100%) ) #v(12pt) Il codice ottenuto è l'unico possibile? #v(12pt) #figure( image("assets/2023-10-10_albero-kraft-2.svg", width: 100%) ) #v(12pt) Come vediamo, "specchiando" il sotto-albero sinistro con radice ad altezza $1$ otteniamo un codice istantaneo diverso dal precedente, ma comunque possibile. Possiamo concludere quindi che, date $n$ lunghezze positive $l_1, dots, l_n$ che soddisfano la disuguaglianza di Kraft, in generale non è _unico_ il codice istantaneo che si può costruire.
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/math/equation.typ
typst
// Test alignment of block equations. // Test show rules on equations. --- math-equation-numbering --- #set page(width: 150pt) #set math.equation(numbering: "(I)") We define $x$ in preparation of @fib: $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio> With @ratio, we get $ F_n = round(1 / sqrt(5) phi.alt^n) $ <fib> --- math-equation-font --- // Test different font. #show math.equation: set text(font: "Fira Math") $ v := vec(1 + 2, 2 - 4, sqrt(3), arrow(x)) + 1 $ --- math-equation-show-rule --- This is small: $sum_(i=0)^n$ #show math.equation: math.display This is big: $sum_(i=0)^n$ --- math-equation-align-unnumbered --- // Test unnumbered #let eq(alignment) = { show math.equation: set align(alignment) $ a + b = c $ } #eq(center) #eq(left) #eq(right) #set text(dir: rtl) #eq(start) #eq(end) --- math-equation-align-numbered --- // Test numbered #let eq(alignment) = { show math.equation: set align(alignment) $ a + b = c $ } #set math.equation(numbering: "(1)") #eq(center) #eq(left) #eq(right) #set text(dir: rtl) #eq(start) #eq(end) --- math-equation-number-align --- #set math.equation(numbering: "(1)") $ a + b = c $ #show math.equation: set align(center) $ a + b = c $ #show math.equation: set align(left) $ a + b = c $ #show math.equation: set align(right) $ a + b = c $ #set text(dir: rtl) #show math.equation: set align(start) $ a + b = c $ #show math.equation: set align(end) $ a + b = c $ --- math-equation-number-align-start --- #set math.equation(numbering: "(1)", number-align: start) $ a + b = c $ #show math.equation: set align(center) $ a + b = c $ #show math.equation: set align(left) $ a + b = c $ #show math.equation: set align(right) $ a + b = c $ #set text(dir: rtl) #show math.equation: set align(start) $ a + b = c $ #show math.equation: set align(end) $ a + b = c $ --- math-equation-number-align-end --- #set math.equation(numbering: "(1)", number-align: end) $ a + b = c $ #show math.equation: set align(center) $ a + b = c $ #show math.equation: set align(left) $ a + b = c $ #show math.equation: set align(right) $ a + b = c $ #set text(dir: rtl) #show math.equation: set align(start) $ a + b = c $ #show math.equation: set align(end) $ a + b = c $ --- math-equation-number-align-left --- #set math.equation(numbering: "(1)", number-align: left) $ a + b = c $ #show math.equation: set align(center) $ a + b = c $ #show math.equation: set align(left) $ a + b = c $ #show math.equation: set align(right) $ a + b = c $ #set text(dir: rtl) #show math.equation: set align(start) $ a + b = c $ #show math.equation: set align(end) $ a + b = c $ --- math-equation-number-align-right --- #set math.equation(numbering: "(1)", number-align: right) $ a + b = c $ #show math.equation: set align(center) $ a + b = c $ #show math.equation: set align(left) $ a + b = c $ #show math.equation: set align(right) $ a + b = c $ #set text(dir: rtl) #show math.equation: set align(start) $ a + b = c $ #show math.equation: set align(end) $ a + b = c $ --- math-equation-number-align-center --- // Error: 52-58 expected `start`, `left`, `right`, or `end`, found center #set math.equation(numbering: "(1)", number-align: center) --- math-equation-number-align-center-bottom --- // Error: 52-67 expected `start`, `left`, `right`, or `end`, found center #set math.equation(numbering: "(1)", number-align: center + bottom) --- math-equation-number-align-monoline --- #set math.equation(numbering: "(1)") $ p = sum_k k ln a $ #set math.equation(numbering: "(1)", number-align: top) $ p = sum_k k ln a $ #set math.equation(numbering: "(1)", number-align: bottom) $ p = sum_k k ln a $ --- math-equation-number-align-multiline --- #set math.equation(numbering: "(1)") $ p &= ln a b \ &= ln a + ln b $ --- math-equation-number-align-multiline-top-start --- #set math.equation(numbering: "(1)", number-align: top+start) $ p &= ln a b \ &= ln a + ln b $ $ q &= sum_k k ln a \ &= sum_k ln A $ --- math-equation-number-align-multiline-bottom --- #show math.equation: set align(left) #set math.equation(numbering: "(1)", number-align: bottom) $ p &= ln a b \ &= ln a + ln b $ $ q &= sum_k ln A \ &= sum_k k ln a $ --- math-equation-number-align-multiline-expand --- // Tests that if the numbering's layout box vertically exceeds the box of // the equation frame's boundary, the latter's frame is resized correctly // to encompass the numbering. #box() below delineates the resized frame. // // A row with "-" only has a height that's smaller than the height of the // numbering's layout box. Note we use pattern "1" here, not "(1)", since // the parenthesis exceeds the numbering's layout box, due to the default // settings of top-edge and bottom-edge of the TextElem that laid it out. #let equations = [ #box($ - - - $, fill: silver) #box( $ - - - \ a = b $, fill: silver) #box( $ a = b \ - - - $, fill: silver) ] #set math.equation(numbering: "1", number-align: top) #equations #set math.equation(numbering: "1", number-align: horizon) #equations #set math.equation(numbering: "1", number-align: bottom) #equations --- math-equation-number-align-multiline-no-expand --- // Tests that if the numbering's layout box doesn't vertically exceed the // box of the equation frame's boundary, the latter's frame size remains. // So, in the grid below, frames in each row should have the same height. #set math.equation(numbering: "1") #grid( columns: 4 * (1fr,), column-gutter: 3 * (2pt,), row-gutter: 2pt, align: horizon, [ #set math.equation(number-align: horizon) #box($ - - \ a \ sum $, fill: silver) ], [ #set math.equation(number-align: bottom) #box($ - - \ a \ sum $, fill: silver) ], [ #set math.equation(number-align: horizon) #box($ sum \ a \ - - $, fill: silver) ], [ #set math.equation(number-align: top) #box($ sum \ a \ - - $, fill: silver) ], [ #set math.equation(number-align: horizon) #box($ - - $, fill: silver) ], [ #set math.equation(number-align: top) #box($ - - $, fill: silver) ], [ #set math.equation(number-align: bottom) #box($ - - $, fill: silver) ], ) --- math-equation-number-empty --- // Test numbering on empty equations. #math.equation(numbering: "1", block: true, []) --- issue-4187-alignment-point-affects-row-height --- // In this bug, a row of "-" only should have a very small height; but // after adding an alignment point "&", the row gains a larger height. // We need to test alignment point "&" does not affect a row's height. #box($ - - $, fill: silver) #box($ - - $, fill: silver) \ #box($ a \ - - $, fill: silver) #box($ &- - \ &a $, fill: silver) #box($ &a \ &- - $, fill: silver) --- issue-numbering-hint --- // In this bug, the hint and error messages for an equation // being reference mentioned that it was a "heading" and was // lacking the proper path. #set page(height: 70pt) $ Delta = b^2 - 4 a c $ <quadratic> // Error: 14-24 cannot reference equation without numbering // Hint: 14-24 you can enable equation numbering with `#set math.equation(numbering: "1.")` Looks at the @quadratic formula. --- issue-3696-equation-rtl --- #set page(width: 150pt) #set text(lang: "he") תהא סדרה $a_n$: $[a_n: 1, 1/2, 1/3, dots]$
https://github.com/AHaliq/CategoryTheoryReport
https://raw.githubusercontent.com/AHaliq/CategoryTheoryReport/main/chapters/chapter4/notes.typ
typst
#import "../../preamble/lemmas.typ": * #import "../../preamble/catt.typ": * #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge #definition(name: "Subobjects")[@sa[Definition 5.1, Remark 5.2, Example 5.3] - A subobject of an object $X$ is a monomorphism $mono(m, M, X)$ in $bold(C)$ - $"Sub"_bold(C)(X)$ is a category of subobjects of $X$ with morphisms arrows in $slice(bold(C), X)$ - the morphisms between any two objects in $"Sub"_bold(C)(X)$ are unique (by mono $m$) - thus $"Sub"_bold(C)(X)$ is a *preorder category* - thus if theres a morphism both ways, it is an isomorphism modelling $equiv$ - if we quotient the isomorphic objects into equivalence classes, we get a *poset category* - in this interpretation $"Sub"_Set(X) iso P(X)$; powerset; objects are subsets - thus morphisms $mono(f, M, M')$ is also monic since composites of monos are also monos - thus we have a functor $"Sub"(M') -> "Sub"(X) = [f |-> m' comp f]$ - _local set membership_ $m in_X M' <=> exists f. m = m' comp f$ #figure( table( columns: 2, align: (center + horizon, center + horizon), [preorder], [poset], figure( diagram( cell-size: 10mm, $ M edge("r", f, "-->") #edge("dr", $m$, ">->", label-anchor: "east", label-sep: 0em) & M' #edge("d", $m'$, ">->", label-anchor: "west", label-sep: 0em) \ &X $, ), ), figure( diagram( cell-size: 10mm, $ M' edge("r", m', >->) & X #edge("r", $g$, "->", shift: 3pt) #edge("r", $h$, "->", shift: -3pt, label-anchor: "north", label-sep: 0em) & Y \ M edge("u", f, "-->") edge("ur", m, >->) $, ), ), ), ) - since equalizers are monos they are subobjects too $m in_X M' <=> g(m) = g(h)$ - we can then regard $M'$ as the subobject of generalized elements $m$ such that $g(m) = h(m)$ ]<defn-subobject> #definition(name: "Pullbacks")[@sa[Definition 5.4, Proposition 5.5, Corollary 5.6] #figure( grid( columns: (auto, 1fr), align: (left, left), figure( diagram( cell-size: 5mm, $ Z edge("dddr", p_1, ->) #edge("dr", $u$, "-->") edge("drrr", p_2, ->) \ & P edge("rr", pi_2, ->) edge("dd", pi_1, ->) && B edge("dd", g, ->) \ \ & A edge("rr", f, ->) && C $, ), ), [ - a pullback is a $"UMP"(f,g)=(pi_1,pi_2)$ - $P = A times_C B = {angle.l p_1,p_2 angle.r in A times B | f comp z_1 = g comp z_2}$ - making $u$ an equalizer of $f comp pi_1$ and $g comp pi_2$ - $P$ is a subobject of $Z$ that makes it commute in the square - if $pi_1$ is monic, $g$ is monic too #figure( table( columns: 2, align: (right, left), [UMP], [definition], [existence], $forall p_1, p_2. exists! u. f comp pi_1 comp u = g comp pi_2 comp u$, [uniqueness], $pi_1 comp u = p_1 and pi_1 comp u' = z_1 => u = u'$, ), ) ], ), ) - in $Set$ the square made by $arr(f, A, B)$ and $arr(overline(f), f^(-1)(V), V)$; its inverse images to images with inverses, form a pullback, generalizing inverses - horizontally composed squares $arrow.b arrows.rr arrow.b arrows.rr arrow.b$ - if the two squares are pullbacks, so is the outer rectangle - if the right square and outer rectangle are pullbacks, so is the left square - the pullback of a commutative triangle is a commutative triangle; prism diagram - a pullback is a functor, fix $arr(g, B, C)$, the functor is $arr(g^*, slice(bold(C),C), slice(bold(C),C')) = [f |-> pi_2]$ - for $arr(f,A,B)$ the $arr(f^(-1), "Sub"(B), "Sub"(A))$ and $arr(f^*, slice(bold(C), B), slice(bold(C),A))$ form a pullback too ]<defn-pullback> #definition(name: "Diagram")[@sa[Definition 5.15] - a diagram is a functor $arr(D, bold(J), bold(C))$ where $bold(J)$ is an index category - a cone is an object $C$ and family of arrows $arr(c_j, C, D_j)$ - any arrows $arr(alpha,i,j)$ makes the triangle $arr(D_alpha, D_i, D_j), c_i, c_j$ commute - a cone morphisms $arr(theta.alt, (C,c_j), (C',c_j'))$, maps the object and family of arrows to another - the triagle $theta.alt, c_j, c_j'$ also commutes - this forms a category $Cone(D)$ ]<defn-diagram> #definition(name: "Limits")[@sa[5.16-5.25] - a limit of a diagram $D$ is a terminal object in $Cone(D)$ with $"UMP"(C, c_j, D) = u$ - the limit is notated as $arr(p_i, lim(j) D_j, D_i)$; the arrrows from the limit cone object to the diagram - a limit exists if for all cones, there exists a unique morphism to the limit cone #figure( grid( columns: (1fr, auto), align: (center + horizon, center + horizon), figure( table( columns: 2, align: (right, left), [UMP], [definition], [existence], $forall (C,c_j), D. exists! (arr(u, C, lim(j) D_j)). forall j. p_j comp u = c_j$, [uniqueness], [if there are two there will be an iso], ), ), figure( diagram( cell-size: 5mm, $ & C edge("d", u, "-->") #edge("ddl", $c_i$, "->", bend: -30deg) #edge("ddr", $c_j$, "->", bend: 30deg) \ & lim(j)D_j edge("dl", p_i, ->) edge("dr", p_j, ->) \ D_i edge("rr", D_alpha, ->) & & D_j $, ), ), ), ) #figure( table( columns: 3, align: (center + horizon, center + horizon, center + horizon), [diagram; $bold(J)$], [limit], [diagram], $circle.filled.small circle.filled.small$, [product], figure( diagram( cell-size: 10mm, $ D_1 & lim(j) D_j edge("l", p_1, ->) edge("r", p_2, ->) & D_2 $, ), ), $circle.filled.small arrows.rr circle.filled.small$, [equalizer], figure( diagram( cell-size: 10mm, $ lim(j) D_j edge("r", c_1, ->) #edge("rr", $c_2$, "->", bend: -40deg, label-anchor: "south", label-sep: -0.5em) & D_1 #edge("r", $D_alpha$, "->", shift: 3pt) #edge("r", $D_beta$, "->", shift: -3pt, label-anchor: "north", label-sep: 0em) & D_2 $, ), ), $emptyset$, [terminal object], $lim(j) D_j$, $circle.filled.small -> circle.filled.small <- circle.filled.small$, [pullback], figure( diagram( cell-size: 10mm, $ lim(j) D_j edge("r", pi_2, ->) edge("d", pi_1, ->) & D_2 edge("d", g, ->) \ D_1 edge("r", f, ->) & C $, ), ), ), ) #figure( caption: "lhs iff rhs", table( columns: 2, align: (right, left), [lhs], [rhs], [binary products, equalizers], [pullbacks], [finite products, equalizers], [pullbacks, terminal object], [finite products, equalizers], [finite limits], [finite products and equalizers of a cardinality], [finite limits of the cardinality], ), ) ]<defn-limit> #definition(name: "Contravariant Functors")[@sa[Definition 5.26] a functor of the form $arr(F, op(bold(C)), bold(D))$ ]<defn-contravariant-functor> #definition(name: "Functor preserving Limits")[@sa[Definition 5.24-5.25] - a functor $arr(F, bold(C), bold(D))$ preserves limits of type $bold(J)$ if $arr(p_j, L, D_j)$ is a limit, then the cone $arr(F p_j, F L, F D_j)$ is a limit for the diagram $arr(F D, bold(J), bold(D))$ - a functor preserving limits is said to be *continuous* $ F(lim("") D_j) iso lim("") F (D_j) $ - representable functor $Hom(,s: C, t: -)$ preserves all limits - contravariant representable functors i.e. $Hom(,s: -, t: C)$, map colimits to limits ]<defn-functor-limit> #definition(name: "Pushouts")[@sa[Definition 5.6] dual of a pullback; where the pushout quotients $forall a. f(a) ~ g(a)$ ]<defn-pushout> #definition(name: "Colimits")[@sa[Definition 5.6] dual of a limit ]<defn-colimits>
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/ConsuntivoSprint/OttavoSprint.typ
typst
MIT License
#import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost #import "../../functions.typ": rendicontazioneOreAPosteriori, rendicontazioneCostiAPosteriori, glossary == Ottavo #glossary[sprint] *Inizio*: Venerdì 12/01/2024 *Fine*: Giovedì 18/01/2024 #rendicontazioneOreAPosteriori(sprintNumber: "08") #rendicontazioneCostiAPosteriori(sprintNumber: "08") === Analisi a posteriori Lo #glossary[sprint] 8 si è concluso con la candidatura alla prima parte della revisione #glossary[RTB] e con l'ultimo diario di bordo effettuato in presenza. Durante quest'ultimo il team ha appreso che il costo del preventivo presentato inizialmente in sede di candidatura non può e non deve essere aumentato in vista del preventivo aggiornato a finire per la revisione #glossary[RTB]. Di conseguenza, si è reso necessario rivedere il nuovo preventivo (descritto in dettaglio nel verbale interno dell'11/01) in modo da mantenerne il costo al di sotto del budget iniziale di 11,070€, pur cambiando la ripartizione delle ore per ruolo in modo coerente con le motivazioni delineate precedentemente. Il cambiamento maggiore è stato apportato alle ore da Progettista, le quali non erano state cambiate nel preventivo precedente rispetto alle 84 preventivate all'inizio poiché il team non ne ha utilizzate fino ad oggi; nel nuovo preventivo, tuttavia, le ore sono state diminuite da 84 a 60 per poterne dedicare di più al ruolo di Amministratore (anche perché si stima che 60 ore distribuite lungo i 6 #glossary[sprint] che precedono la revisione #glossary[PB] siano sufficienti) senza variare il costo, che rimane dunque di 11,070€. In seguito a ciò le ore dedicate ai vari ruoli nel preventivo aggiornato e definitivo sono: - Responsabile: 63 ore (contro le 60 iniziali); - Amministratore: 87 ore (contro le 48 iniziali); - Analista: 54 ore (uguali a quelle iniziali); - Progettista: 60 ore (contro le 84 iniziali); - Programmatore: 139 ore (contro le 162 iniziali); - Verificatore: 167 ore (contro le 162 iniziali). I fattori che motivano tali cambiamenti rimangono quelli delineati nel verbale interno menzionato sopra, con l'eccezione delle ore da Progettista che vengono scalate fondamentalmente per rispettare il costo iniziale. Ora che il team ha a disposizione un preventivo aggiornato in base alle ore effettivamente utilizzate nei primi 8 #glossary[sprint] che precedono la revisione #glossary[RTB], è possibile confrontare in dettaglio le ore effettive con le ore preventivate e aggiustare i preventivi futuri di conseguenza. In particolare, è evidente che il team non ha sempre tenuto conto delle ore effettivamente utilizzate da ogni componente nel preventivare ore e ruoli all'inizio di ogni #glossary[sprint], il che ha portato più membri ad utilizzare più ore da Amministratore di quante non ce ne fossero effettivamente a disposizione; dopo la revisione #glossary[RTB], il team ha intenzione di effettuare una pianificazione più attenta, guardando sempre alla somma delle ore delineate nei consuntivi (ora automatizzati) per evitare che questo fenomeno si ripeta in futuro. Le ore preventivate per i periodi che precedono le prossime revisioni riflettono quelle che il team ha effettivamente a disposizione d'ora in avanti, per cui i prossimi preventivi si baseranno su quelle. Nonostante l'imprevisto, il resto della #glossary[documentazione] e il #glossary[PoC] sono sostanzialmente pronti affinché il team possa sostenere la revisione #glossary[RTB] dopo la conclusione di questo #glossary[sprint].
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/quote_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Text direction affects author positioning And I quote: #quote(attribution: [<NAME>])[cogito, ergo sum]. #set text(lang: "ar") #quote(attribution: [عالم])[مرحبًا]
https://github.com/jassielof/IT425-P1
https://raw.githubusercontent.com/jassielof/IT425-P1/main/Documento%20de%20Parcial.typ
typst
MIT License
#import "template/apa7/lib.typ": * #show: apa7.with( title: [Documento de Parcial: Preguntas sobre el «Caso El Periódico Parte B» y 14 puntos de Deming para la gestión de la calidad], custom-authors: [<NAME>], custom-affiliations: [Facultad de Ingeniería, Universidad de Santa Cruz de la Sierra], course: [IT425: Gestión de la Calidad Total], instructor: [Mgs.<NAME>], due-date: [Miércoles, 25 de septiembre de 2024], language: "es", region: "bo", font-family: "New Computer Modern", font-size: 10pt, paper-size: "a4", toc: true, ) = Preguntas sobre el «Caso El Periódico Parte B»~@Caso_B == Pregunta 1 *Pregunta 1: ¿Cuáles fueron las posibles causas que podrían haber provocado una falla de TQM en la empresa?* Las posibles causas que podrían haber provocado una falla en la implementación de la Gestión de la Calidad Total (TQM) en El Periódico S.A. son varias, y están relacionadas con aspectos tanto internos como de gestión. Entre las posibles causas de la falla de TQM en la empresa, se puede mencionar una combinación de la falta de compromiso real, problemas de comunicación, conflictos internos no resueltos y un enfoque reactivo en lugar de preventivo. Como solución a poder lograr los beneficios de TQM, l empresa podría adoptar una cultura organizacional completamente diferente, con un enfoque proactivo en la mejora continua, colaboración interdepartamental y empoderamiento del personal. === Falta de compromiso real de los líderes Si bien Fernando y demás gerentes mostraron un compromiso inicial con TQM, este no parece haber sido lo suficientemente profundo/fuerte/constante. La ausencia de un seguimiento riguroso a las acciones propuestas sugiere una falta de liderazgo y compromiso real con la implementación de TQM. Los líderes deben estar completamente involucrados, además de dar el ejemplo para que el cambio se produzca de manera efectiva. === Resistencia al cambio La empresa ya tenía conflictos internos entre departamentos, lo que pudo haber causado una *resistencia natural al cambio*. Los empleados, acostumbrados a sus métodos habituales, probablemente no adoptaron de manera efectiva las nuevas prácticas de Calidad Total. La ausencia de una cultura de mejora continua dentro de la empresa pudo haber dificultado la aceptación de esta nueva filosofía. === Comunicación ineficaz La estrategia de Calidad Total fue comunicada y se inició una campaña para concienciar a los empleados, pero _la comunicación interna no fue clara ni efectiva_. Los conflictos y quejas entre departamentos no se resolvieron correctamente, lo que resultó en una falta de colaboración y compromiso. Sin una comunicación transparente y colaborativa, el cambio no puede tener éxito. === Falta de un plan de implementación claro Si bien se habló de los tres principios clave (_mejora continua, trabajo en equipo y enfoque en el cliente_), parece que *no existió un plan de acción detallado* que guiara a los departamentos en la implementación de TQM. Un plan de implementación estructurado, con objetivos claros y medibles, es crucial para el éxito de la Calidad Total. Sin una guía concreta, las acciones pueden quedarse en palabras y no en hechos. === Carencia de indicadores de desempeño (KPIs) No se mencionan en el caso *indicadores clave de desempeño (KPIs)* ni mecanismos de medición para evaluar si los cambios propuestos lograron mejorar la calidad. Para que la TQM funcione, es esencial monitorear continuamente el desempeño y hacer ajustes cuando sea necesario. Sin datos objetivos, es difícil saber si se están alcanzando los objetivos de calidad. === Conflictos interdepartamentales Los conflictos entre departamentos fueron señalados como un problema constante. La *falta de colaboración y el trabajo en silos* habrían sido grandes obstáculos para implementar TQM, que requiere una colaboración fluida entre todas las áreas. Si los equipos no trabajan juntos y comparten una visión común de la calidad, la implementación de TQM está destinada a fallar. === Falta de empoderamiento del personal Aunque se les pidió a los empleados que hicieran listas de mejoras, *no se menciona si se les brindaron los recursos o el apoyo necesario* para implementar esas mejoras. Sin el empoderamiento adecuado, los empleados pueden sentirse desmotivados o incapaces de hacer cambios significativos. El TQM requiere que cada miembro de la organización se sienta responsable de la calidad, lo que probablemente no ocurrió en este caso. === Cultura organizacional enfocada en la resolución de problemas en lugar de la prevención La empresa estaba acostumbrada a operar en un entorno de "alta intensidad" resolviendo problemas día a día. Esto sugiere una *falta de enfoque en la prevención* de problemas de calidad, lo cual es un principio fundamental del TQM. Para que este enfoque funcione, la empresa debe cambiar su mentalidad de reacción a una de anticipación y prevención de problemas. === Falta de recursos para implementar TQM No se menciona si se asignaron *recursos financieros, tecnológicos o humanos* para implementar las mejoras de calidad. La implementación de TQM puede requerir nuevas tecnologías, formación continua, y a veces, inversiones en infraestructura o procesos. Sin estos recursos, cualquier plan de mejora está destinado a fallar. === Tiempo insuficiente para ver resultados Fernando y los demás gerentes dieron plazos muy cortos (20-30 días) para presentar listas de mejoras. Aunque estas listas podrían haber sido un buen primer paso, el cambio hacia la Calidad Total requiere *tiempo para que las iniciativas den resultados visibles*. Los empleados y líderes probablemente no vieron mejoras inmediatas, lo que puede haber causado desmotivación y una percepción de que TQM no estaba funcionando. == Pregunta 2 *Pregunta 2: ¿Fernando como gerente y líder de la empresa en qué falló y cómo debería haberlo hecho? (si realmente fallo), ¿Cómo podría lograrse los beneficios de TQM en esa empresa?* Fernando, como gerente y líder de la empresa, falló en varios aspectos clave al implementar la Gestión de la Calidad Total (TQM) en El Periódico S.A. === Fallos de Fernando Principalmente, falta de seguimiento y ejecución del plan, problemas de comunicación y coordinación, y un cambio cultural insuficiente. ==== Implementación apresurada Dar plazos de 20-30 días para presentar listas de mejoras puede haber sido un *enfoque apresurado* que no permitió a los empleados comprender completamente la filosofía de TQM. ==== Enfoque top-down Fernando impuso la decisión sin involucrar a los empleados de todos los niveles en el proceso. ==== Falta de planificación estratégica No se presentó un plan detallado ni una hoja de ruta clara para la implementación de TQM. ==== Ausencia de formación adecuada No se mencionó programas de capacitación para que los empleados entendieran los principios de TQM. ==== Falta de seguimiento No se estableció mecanismos de seguimiento para evaluar el progreso y los resultados de las mejoras propuestas. === Cómo debería haberlo hecho Fernando debería haber adoptado un enfoque más colaborativo y proactivo para implementar TQM en la empresa. ==== Desarrollo de una visión clara Definir y comunicar una visión clara de cómo TQM beneficiará a la empresa, empelados y clientes. ==== Planificación a largo plazo Desarrollar un plan estratégico a largo plazo con objetivos claros y medibles, referente a la implementación del TQM. ==== Formación integral Proporcionar formación exhaustiva sobre TQM a todos los empleados, desde los líderes hasta el personal de línea. ==== Involucramiento de los empleados Los empleados deben ser involucrados en el proceso de mejora continua y sentirse parte de la solución (desde el principio). ==== Liderazgo visible Demostrar un compromiso constante y visible con TQM, liderando con el ejemplo y fomentando una cultura de calidad. ==== Establecimiento de sistemas de medición Implementar sistemas para medir y monitorear el progreso de la calidad. ==== Abordar problemas existentes Tratar los conflictos interdepartamentales y otros problemas internos antes de implementar TQM. ==== Comunicación efectiva Establecer canales de comunicación abiertos y transparentes para fomentar la colaboración y el intercambio de ideas. === Cómo lograr los beneficios de TQM Para lograr los beneficios de la Gestión de la Calidad Total en El Periódico S.A., la empresa debe adoptar un enfoque holístico y sostenido hacia la calidad. ==== Cultura de calidad Fomentar un entorno donde la calidad sea una prioridad en todos los niveles de la organización. ==== Enfoque en el cliente Implementar sistemas para la recopilación y análisis regular de la retroalimentación del cliente. ==== Mejora continua Establecer procesos para la identificación y solución constante de problemas. ==== Trabajo en equipo Fomentar la colaboración interdepartamental y el intercambio de conocimientos. ==== Toma de decisiones basada en datos Implementar sistemas para recopilar y analizar datos relevantes para la toma de decisiones. ==== Gestión de procesos Mapear, analizar y mejorar continuamente los procesos clave de la empresa. ==== Desarrollo de proveedores Trabajar estrechamente con los proveedores para mejorar la calidad de los insumos. ==== Reconocimiento y recompensas Implementar un sistema para reconocer y recompensar los esfuerzos y logros en calidad. ==== Benchmarking Comparar las prácticas de la empresa con las mejores de la industria y aprender de ellas. ==== Herramientas de calidad Introducir y capacitar al personal en el uso de herramientas de calidad como diagramas de Pareto, diagramas de causa-efecto, etc. ==== Auditorías de calidad Realizar auditorías internas regulares para evaluar el progreso y identificar áreas de mejora. = 14 puntos de Deming~#cite(<Permana_Purba_Rizkiyah_2021>, form: "prose") Deming propuso 14 puntos de mejora para lograr un éxito en la gestión de la calidad. ¿Cómo podrían contribuir la implementación de todos o algunos de esos puntos de Deming con TQM en el caso de la empresa? == 14 puntos de Deming~ Los 14 puntos de Deming son principios fundamentales para la mejora de la calidad y la gestión eficaz de una organización. Mencionado por el Dr. Deming, #quote([My 14 Points for Management follow naturally as application of the System of Profound Knowledge for transformation from the present style of management to one of optimization.], attribution: [The New Economics]) Se definen los siguientes puntos~@Deming_14, de parte de <NAME>. _Out of The Crisis (MIT Press) (pp. 23--24)_. + Crear constancia de propósito hacia la mejora de productos y servicios, con el objetivo de volverse competitivos, mantenerse en el negocio y proporcionar empleos. + Adoptar la nueva filosofía. Estamos en una nueva era económica. La gestión occidental debe despertar al desafío, aprender sus responsabilidades y asumir el liderazgo para el cambio. + Cesar la dependencia de la inspección para lograr calidad. Eliminar la necesidad de inspección en masa construyendo la calidad en el producto desde el principio. + Terminar con la práctica de adjudicar negocios basándose en el precio. En su lugar, minimizar el costo total. Moverse hacia un solo proveedor para cualquier artículo, en una relación a largo plazo de lealtad y confianza. + Mejorar constantemente y para siempre el sistema de producción y servicio, para mejorar la calidad y la productividad, y así disminuir constantemente los costos. + Instituir la capacitación en el trabajo. + Instituir el liderazgo. El objetivo de la supervisión debe ser ayudar a las personas, máquinas y dispositivos a hacer un mejor trabajo. La supervisión de la gestión necesita una revisión, al igual que la supervisión de los trabajadores de producción. + Eliminar el miedo, para que todos puedan trabajar de manera efectiva para la empresa. + Romper las barreras entre departamentos. Las personas en investigación, diseño, ventas y producción deben trabajar como un equipo, para prever problemas de producción y uso que puedan encontrarse con el producto o servicio. + Eliminar eslóganes, exhortaciones y objetivos para la fuerza laboral que piden cero defectos y nuevos niveles de productividad. Tales exhortaciones solo crean relaciones adversariales, ya que la mayoría de las causas de baja calidad y baja productividad pertenecen al sistema y, por lo tanto, están más allá del poder de la fuerza laboral. + Eliminar los estándares de trabajo (cuotas) en el piso de la fábrica. Sustituir el liderazgo. + Eliminar la gestión por objetivos. Eliminar la gestión por números, objetivos numéricos. Sustituir el liderazgo. + Eliminar las barreras que roban al trabajador por horas su derecho al orgullo por su trabajo. La responsabilidad de los supervisores debe cambiar de números puros a calidad. + Eliminar las barreras que roban a las personas en la gestión y en la ingeniería su derecho al orgullo por su trabajo. Esto significa, entre otras cosas, la abolición de la calificación anual o de mérito y de la gestión por objetivos. + Instituir un programa vigoroso de educación y auto-mejora. + Poner a todos en la empresa a trabajar para lograr la transformación. La transformación es tarea de todos. == Contribución a TQM - *Mejora continua*: Los puntos de Deming enfatizan la mejora continua, un principio central de TQM. - *Calidad integrada*: Al dejar de depender de la inspección masiva y mejorar los procesos, se asegura que la calidad esté integrada desde el inicio. - *Capacitación y liderazgo*: La capacitación constante y el liderazgo efectivo son esenciales para una implementación exitosa de TQM. - *Colaboración y eliminación de barreras*: Fomentar la colaboración y eliminar barreras internas mejora la eficiencia y la calidad del trabajo. Implementar estos puntos proporcionaría una base sólida para TQM, abordando aspectos críticos como el liderazgo, la cultura organizacional, la participación de los empleados, la mejora continua y el enfoque en el cliente. Esto ayudaría a superar muchas de las barreras para la implementación de TQM identificadas en la revisión de literatura, como la falta de compromiso de la gerencia, la resistencia cultural y la falta de participación de los empleados. Ultimadamente, esto conduciría a mejoras en la calidad, la satisfacción del cliente y el rendimiento organizacional, que son los principales beneficios de TQM destacados en la revisión. #pagebreak() #bibliography( "ref.bib", title: [Referencias], )
https://github.com/MattiaOldani/Informatica-Teorica
https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/calcolabilità/01_richiami_matematici.typ
typst
#import "../alias.typ": * = Richiami matematici: funzioni e prodotto cartesiano == Funzioni e insiemi di funzioni Una *funzione* da un insieme $A$ a un insieme $B$ è una legge, spesso indicata con $f$, che definisce come associare agli elementi di $A$ un elemento di $B$. Una funzione può essere di due tipi differenti: - *generale*: la funzione è definita in modo generale come $f: A arrow.long B$, in cui $A$ è detto *dominio* di $f$ e $B$ è detto *codominio* di $f$; - *locale/puntuale*: la funzione è definita solo per singoli valori $a in A$ e $b in B$, e scriviamo: $ f(a) = b quad bar.v quad a arrow.long.bar^f b, $ in cui $b$ è detta *immagine* di $a$ rispetto a $f$ e $a$ è detta *controimmagine* di $b$ rispetto a $f$. Le funzioni possono essere categorizzate in base ad alcune proprietà: - *iniettività*: una funzione $f: A arrow.long B$ si dice _iniettiva_ se e solo se: $ forall a_1, a_2 in A quad a_1 eq.not a_2 arrow.long.double f(a_1) eq.not f(a_2). $ In sostanza, elementi diversi sono _mappati_ ad elementi diversi. - *suriettività*: una funzione $f: A arrow.long B$ si dice _suriettiva_ se e solo se: $ forall b in B quad exists a in A bar.v f(a) = b, $ quindi ogni elemento del codominio ha almeno una controimmagine. - *biettività*: una funzione $f: A arrow.long B$ si dice _biiettiva_ se e solo se: $ forall b in B quad exists! a in A bar.v f(a) = b, $ che equivale a dire che è sia iniettiva sia suriettiva. Definendo l'*insieme immagine*: $ immagine(f) = {b in B bar.v exists a in A text("tale che") f(a) = b} = {f(a) bar.v a in A} subset.eq B $ possiamo dare una definizione alternativa di funzione suriettiva: essa è tale se e solo se $immagine(f) = B$. Se $f: A arrow.long B$ è una funzione biiettiva, si definisce *inversa* di $f$ la funzione $f^(-1): B arrow.long A$ tale che: $ f(a) = b arrow.long.double.l.r f^(-1)(b) = a. $ Se $f$ non fosse biiettiva, l'inversa avrebbe problemi di definizione. Un'operazione definita su funzioni è la *composizione*: date $f: A arrow.long B$ e $g: B arrow.long C$, la funzione _f composto g_ è la funzione $g composizione f: A arrow.long C$ definita come: $ (g composizione f)(a) = g(f(a)). $ La composizione _non è commutativa_, ovvero $g composizione f eq.not f composizione g$ in generale, ma è _associativa_, quindi $(f composizione g) composizione h = f composizione (g composizione h)$. Dato l'insieme $A$, la *funzione identità* su $A$ è la funzione $i_A: A arrow.long A$ tale che: $ forall a in A quad i_A (a) = a, $ quindi è una funzione che mappa ogni elemento in se stesso. Grazie a questa, diamo una definizione alternativa di funzione inversa: data $f: A arrow.long B$ biiettiva, la sua inversa è l'unica funzione $f^(-1): B arrow.long A$ che soddisfa la relazione: $ f composizione f^(-1) = f^(-1) composizione f = id_A. $ Introduciamo la notazione $f(a) arrow.b$ per indicare che la funzione $f$ è definita per l'input $a$, mentre la notazione $f(a) arrow.t$ per indicare la situazione opposta. Vediamo una seconda categorizzazione per le funzioni. Data $f: A arrow.long B$, diciamo che $f$ è: - *totale* se è definita per _ogni_ elemento di $A$, ovvero $forall a in A quad f(a) arrow.b$; - *parziale* se è definita per _qualche_ elemento di $A$, ovvero $exists a in A bar.v f(a) arrow.t$. Chiamiamo *dominio* (o _campo_) *di esistenza* di $f$ l'insieme: $ dominio(f) = { a in A bar.v f(a) arrow.b} subset.eq A. $ Notiamo che: - se $dominio(f) subset.neq A$ allora $f$ è una funzione parziale; - se $dominio(f) = A$ allora $f$ è una funzione totale. È possibile *totalizzare* una funzione parziale $f$ definendo una funzione a tratti $overline(f): A arrow.long B union {bot}$ tale che: $ overline(f)(a) = cases(f(a) quad & a in op("Dom")_f (a), bot & text("altrimenti")) quad . $ Il simbolo $bot$ è il _simbolo di indefinito_ e viene utilizzato per tutti i valori per cui la funzione di partenza $f$ non è appunto definita. Da qui in avanti utilizzeremo $B_bot$ come abbreviazione di $B union { bot }$. L'insieme di tutte le funzioni da $A$ in $B$ si indica con: $ B^A = { f : A arrow.long B }. $ Viene utilizzata questa notazione in quanto la cardinalità di $B^A$ è esattamente $|B|^(|A|)$, se $A$ e $B$ sono insiemi finiti. Dato che vogliamo che siano presenti anche tutte le funzioni parziali da $A$ in $B$, scriviamo: $ B^A_bot = { f : A -> B_bot }, $ mettendo in evidenza il fatto che tutte le funzioni che sono presenti sono totali oppure parziali, ma che sono state totalizzate. Le due definizioni coincidono, ovvero $ B^A = B_bot^A $. == Prodotto cartesiano Chiamiamo *prodotto cartesiano* l'insieme: $ A times B = { (a,b) bar.v a in A and b in B }, $ che rappresenta l'insieme di tutte le _coppie ordinate_ di valori in $A$ e in $B$. In generale, il prodotto cartesiano *non è commutativo*, a meno che $A = B$. Possiamo estendere il concetto di prodotto cartesiano a $n$-uple di valori: $ A_1 times dots times A_n = { (a_1, dots , a_n) bar.v a_i in A_i }. $ Per comodità chiameremo $ underbracket(A times dots times A, n) = A^n . $ L'operazione "opposta" è effettuata dal *proiettore* $i$-esimo: esso è una funzione che estrae l'$i$-esimo elemento di un tupla, quindi è una funzione $pi_i : A_1 times dots times A_n arrow.long A_i$ tale che: $ pi_i (a_1, dots, a_n) = a_i. $ == Funzione di valutazione Dati $A, B$ e $B_bot^A$ si definisce *funzione di valutazione* la funzione: $ omega : B_bot^A times A arrow.long B $ tale che $ omega(f,a) = f(a). $ In poche parole, è una funzione che prende una funzione $f$ e la valuta su un elemento $a$ del dominio. Esistono due tipi di analisi che possiamo effettuare su questa funzione: - si tiene fisso $a$ e si provano tutte le funzioni $f$: otteniamo un _benchmark_, ognuno dei quali è rappresentato dal valore $a$; - si tiene fissa $f$ e si provano tutte le $a$ nel dominio: otteniamo il _grafico_ di $f$.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/supercharged-dhbw/1.0.0/lib.typ
typst
Apache License 2.0
#import "@preview/codelst:2.0.1": sourcecode #import "titlepage.typ": * #import "confidentiality-statement.typ": * #import "declaration-of-authorship.typ": * #import "acronyms-list.typ": * #import "template/appendix.typ": * // Workaround for the lack of an `std` scope. #let std-bibliography = bibliography #let supercharged-dhbw( title: "", authors: (:), at-dhbw: false, show-confidentiality-statement: true, show-declaration-of-authorship: true, show-table-of-contents: true, show-acronyms: true, show-list-of-figures: true, show-list-of-tables: true, show-code-snippets: true, show-appendix: false, show-abstract: true, abstract: "", course-of-studies: "", university: "", university-location: "", supervisor: "", date: datetime.today(), bibliography: none, logo-left: none, logo-right: none, body, ) = { // set the document's basic properties set document(title: title, author: authors.map(author => author.name)) // save heading and body font families in variables let body-font = "Open Sans" let heading-font = "Montserrat" // customize look of figure set figure.caption(separator: [ --- ], position: bottom) // set body font family set text(font: body-font, lang: "en", 12pt) show heading: set text(font: heading-font) //heading numbering set heading(numbering: (..nums) => { let level = nums.pos().len() // only level 1 and 2 are numbered let pattern = if level == 1 { "1." } else if level == 2 { "1.1." } else if level == 3 { "1.1.1." } if pattern != none { numbering(pattern, ..nums) } }) // set link style show link: it => underline(text(it)) show heading.where(level: 1): it => { pagebreak() v(2em) + it + v(1em) } show heading.where(level: 2): it => v(1em) + it + v(0.5em) show heading.where(level: 3): it => v(0.5em) + it + v(0.25em) titlepage(authors, title, date, at-dhbw, logo-left, logo-right, course-of-studies, university, university-location, supervisor, heading-font) set page( margin: (top: 8em, bottom: 8em), header: { stack(dir: ltr, spacing: 1fr, box(width: 180pt, emph(align(center,text(size: 9pt, title))), ), stack(dir: ltr, spacing: 1em, if logo-left != none { set image(height: 1.2cm) logo-left }, if logo-right != none { set image(height: 0.8cm) logo-right } ) ) line(length: 100%) } ) // set page numbering to roman numbering set page( numbering: "I", number-align: center, ) counter(page).update(1) if (not at-dhbw and show-confidentiality-statement) { confidentiality-statement(authors, title, university, university-location, date) } if (show-declaration-of-authorship) { declaration-of-authorship(authors, title, date) } show outline.entry.where( level: 1, ): it => { v(18pt, weak: true) strong(it) } context { let elems = query(figure.where(kind: image), here()) let count = elems.len() if (show-list-of-figures and count > 0) { outline( title: [#heading(level: 3)[List of Figures]], target: figure.where(kind: image), ) } } context { let elems = query(figure.where(kind: table), here()) let count = elems.len() if (show-list-of-tables) { outline( title: [#heading(level: 3)[List of Tables]], target: figure.where(kind: table), ) } } context { let elems = query(figure.where(kind: raw), here()) let count = elems.len() if (show-code-snippets) { outline( title: [#heading(level: 3)[Code Snippets]], target: figure.where(kind: raw), ) } } if (show-table-of-contents) { outline(title: "Table of contents", indent: auto, depth: 3) } if (show-acronyms) { acronyms-list() } set par(justify: true) context { let has-content = abstract.len() > 0 if (show-abstract and has-content) { align(center + horizon, heading(level: 1, numbering: none)[Abstract]) text(abstract) } } // reset page numbering and set to arabic numbering set page( numbering: " 1 of 1", number-align: center, ) counter(page).update(1) body // Display bibliography. if bibliography != none { set std-bibliography(title: [References], style: "ieee") bibliography } if (show-appendix) { heading(level: 1, numbering: none)[Appendix] appendix } }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/closure-17.typ
typst
Other
// Error: 7-17 expected identifier, named pair or argument sink, found keyed pair #((a, "named": b) => none)
https://github.com/tingerrr/chiral-thesis-fhe
https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/src/core/component/appendix.typ
typst
// TODO: is the numbering here and for headings in general correct? is the trailing dot expected? #let number-appendices(..args) = if args.pos().len() == 1 { numbering("A", ..args.pos()) } else { numbering("1.", ..args.pos().slice(1)) } #let make-appendix( body: lorem(100), ) = { set heading(numbering: number-appendices, supplement: [Anhang]) // TODO: ideally we shouldn't need the explicit page break allow for these to be more easily composed show heading.where(level: 1): it => { pagebreak(weak: true) block({ it.body [ ] counter(heading).display(it.numbering) }) } // TODO: figures must be numbered differently here heading(level: 1)[Anhang] body }
https://github.com/OrangeX4/typst-test-sync-repo
https://raw.githubusercontent.com/OrangeX4/typst-test-sync-repo/main/packages/local/mytemplate/0.1.0/mytemplate.typ
typst
#import "@preview/tablex:0.0.6": * #import "@preview/quick-maths:0.1.0": shorthands #import "@preview/showybox:2.0.1": showybox #let theorem-box(title: "", it) = { showybox( frame: ( border-color: orange.darken(10%), title-color: orange.lighten(0%), body-color: orange.lighten(90%), ), title-style: ( color: white, weight: "bold", ), title: title, it, ) } #let conclusion-box(title: "", it) = { showybox( frame: ( border-color: green.darken(40%), title-color: green.darken(20%), body-color: green.lighten(90%), ), title-style: ( color: white, weight: "bold", ), title: title, it, ) } #let question-box(title: "", it) = { showybox( frame: ( border-color: navy.darken(20%), title-color: navy.lighten(10%), body-color: navy.lighten(90%), ), title-style: ( color: white, weight: "bold", ), title: title, it, ) } #let info-box(title: "", it) = { showybox( frame: ( border-color: blue.darken(20%), title-color: blue.lighten(10%), body-color: blue.lighten(90%), ), title-style: ( color: white, weight: "bold", ), title: title, it, ) } #let emph-box(it) = { showybox( frame: ( dash: "dashed", border-color: yellow.darken(30%), body-color: yellow.lighten(90%), ), sep: ( dash: "dashed" ), it, ) } #let argmax = math.op("argmax", limits: true) #let argmin = math.op("argmin", limits: true) #let indent() = { box(width: 2em) } #let indent_par(body) = { box(width: 1.8em) body } #let empty_par() = { v(-1em) box() } // Answer box #let answer(body) = rect(width: 100%, stroke: 0.5pt, inset: 10pt, body) // Heading Numbering #let Numbering(base: 1, first-level: none, second-level: none, third-level: none, format, ..args) = { if (first-level != none and args.pos().len() == 1) { if (first-level != "") { numbering(first-level, ..args) } return } if (second-level != none and args.pos().len() == 2) { if (second-level != "") { numbering(second-level, ..args) } return } if (third-level != none and args.pos().len() == 3) { if (third-level != "") { numbering(third-level, ..args) } return } // default if (args.pos().len() >= base) { numbering(format, ..(args.pos().slice(base - 1))) return } } // three-line-table #let three-line-table(columns: 1, ..options) = tablex( columns: columns, align: center + horizon, auto-lines: false, ..options.named(), hlinex(), ..options.pos().slice(0, columns), hlinex(), ..options.pos().slice(columns), hlinex(), ) // Chinese in Math #let zh(it) = { set text(font: ("IBM Plex Serif", "Source Han Serif SC")) it } #let report(size: 12pt, screen-size: 14pt, subject: "", title: "", date: "", author: "", show-outline: false, par-indent: false, media: "print", theme: "Light", display-inline-equation: true, body) = { // Save heading and body font families in variables. let font-set = ( title: ("IBM Plex Serif", "Times New Roman", "Source Han Serif SC", "Songti SC"), body: ("IBM Plex Serif", "Times New Roman", "Source Han Serif SC", "Songti SC"), mono: ("IBM Plex Mono", "Menlo", "Source Han Sans", "Source Han Sans SC", "PingFang SC"), ) let page-margin = if (media == "screen") { (x: 35pt, y: 35pt) } else { auto } let text-size = if (media == "screen") { screen-size } else { size } let bg-color = if (theme == "Dark" or theme == "dark") { rgb("#1f1f1f") } else { rgb("#ffffff") } let text-color = if (theme == "Dark" or theme == "dark") { rgb("#ffffff") } else { rgb("#000000") } let raw-color = if (theme == "Dark" or theme == "dark") { rgb("#27292c") } else { luma(240) } let quota-bg-color = if (theme == "Dark" or theme == "dark") { rgb(255, 255, 255, 15) } else { rgb(0, 0, 0, 15) } // Set the document's basic properties. set document(author: author, title: subject + title + author) set page(numbering: "1", number-align: center, fill: bg-color, margin: page-margin) // Set body font family. set text(text-size, font: font-set.body, fill: text-color, lang: "zh", region: "cn") // scale cjk font show regex("[^\\x00-\\xff]+"): set text(0.9em) show heading: it => { set block(below: 1em) it } + if (par-indent) { empty_par() } show heading.where(level: 1): it => { v(0.5em) it v(0.2em) } set par(justify: true, first-line-indent: if (par-indent) {2em} else {0em}) show par: set block(spacing: 1.5em) // spacing between paragraphs // Image set image(width: 80%) show image: align.with(center) // Quota show quote: it => pad(x: 0pt, top: -15pt, bottom: -10pt, rect(width: 100%, fill: quota-bg-color, stroke: (left: 0.25em), it.body)) // Code Block show raw.where(block: false): body => box( fill: raw-color, inset: (x: 3pt, y: 0pt), outset: (x: 0pt, y: 3pt), radius: 2pt, { set text(font: font-set.mono) set par(justify: false) body }, ) show raw.where(block: true): body => block( width: 100%, fill: raw-color, inset: 10pt, radius: 4pt, { set text(font: font-set.mono) set par(justify: false) body }, ) if (subject != "") { // Title page align(center + top)[ #v(20%) #text(font: font-set.title, 2em, weight: 500, subject) #v(2em, weak: true) #text(font: font-set.title, 2em, weight: 500, title) #v(2em, weak: true) #text(author) ] pagebreak() } // Page Header set page( header: { set text(font: font-set.body, 0.9em) stack( spacing: 0.2em, grid( columns: (1fr, auto, 1fr), align(left, date), align(center, subject), align(right, title), ), v(0.1em), line(length: 100%, stroke: 1pt + text-color), line(length: 100%, stroke: 0.5pt + text-color) ) // reset footnote counter counter(footnote).update(0) } ) if (show-outline) { set par(first-line-indent: 0em) align(center)[ #heading(level: 1, numbering: none, outlined: false)[ 目录 ] ] show outline: set box(height: 1.2em, baseline: 0.5em) outline(depth: 2, indent: true, title: none) pagebreak() } // Links show link: it => { if type(it.dest) == str { [#underline(it)#footnote(it.dest)] } else { underline(it) } } // shorthands for math equations show: shorthands.with( ($+-$, $plus.minus$), ($...$, $dots.c$), ($|-$, math.tack), ($::=$, $eq.delta$), ($~~$, $approx$), ($~$, $tilde$), ) // display inline equation show math.equation.where(block: false): it => { if not display-inline-equation or (it.has("label") and it.label == label("displayed-inline-math-equation")) { it } else { [$display(it)$<displayed-inline-math-equation>] } } body }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/elsearticle/0.1.0/src/elsearticle.typ
typst
Apache License 2.0
// elsearticle.typ // Author: <NAME> // Github: https://github.com/maucejo // License: MIT // Date : 07/2024 #let font-size = ( script: 7pt, footnote: 8pt, small: 10pt, normal: 11pt, author: 12pt, title: 17pt, ) #let linespace = ( preprint: 1em, review: 1.5em, ) #let indent-size = 2em #let margins = ( review: (left: 105pt, right: 105pt, top: 130pt, bottom: 130pt), preprint: (left: 105pt, right: 105pt, top: 130pt, bottom: 130pt), one_p: (left: 105pt, right: 105pt, top: 140pt, bottom: 140pt), three_p: (left: 64pt, right: 64pt, top: 110pt, bottom: 110pt), five_p: (left: 37pt, right: 37pt, top: 80pt, bottom: 80pt) ) #let isappendix = state("isappendix", false) // Equations #let nonumeq(body) = { set math.equation(numbering: none) body } // Figures #let subfigure = figure.with( kind: "subfigure", supplement: [], numbering: "(a)", ) // Appendix #let appendix(body) = { set heading(numbering: "A.1.") // Reset heading counter counter(heading).update(0) // Equation numbering let numbering-eq = n => { let h1 = counter(heading).get().first() numbering("(A.1)", h1, n) } set math.equation(numbering: numbering-eq) // Figure and Table numbering let numbering-fig = n => { let h1 = counter(heading).get().first() numbering("A.1", h1, n) } show figure.where(kind: image): set figure(numbering: numbering-fig) show figure.where(kind: table): set figure(numbering: numbering-fig) isappendix.update(true) body } #let elsearticle( // The article's title. title: none, // An array of authors. For each author you can specify a name, // department, organization, location, and email. Everything but // but the name is optional. authors: (), // Your article's abstract. Can be omitted if you don't have one. abstract: none, // Journal name journal: none, // Keywords keywords: none, // For integrating future formats (1p, 3p, 5p, final) format: "review", // Number of columns numcol: 1, // Bibliography bibliography-file: none, // The document's content. body, ) = { // Text set text(size: font-size.normal, font: "New Computer Modern") // Conditional formatting let els-linespace = if format == "review" {linespace.review} else {linespace.preprint} let els-margin = if format == "review" {margins.review} else if format == "preprint" {margins.preprint} else if format == "1p" {margins.one_p} else if format == "3p" {margins.three_p} else if format == "5p" {margins.five_p} else {margins.review} let els-columns = if format == "1p" {1} else if format == "5p" {2} else {if numcol > 2 {2} else {if numcol <= 0 {1} else {numcol}}} // Heading set heading(numbering: "1.") show heading: it => block(above: els-linespace, below: els-linespace)[ #if it.numbering != none { if it.level == 1 { set par(leading: 0.75em, hanging-indent: 1.25em) set text(font-size.normal) numbering(it.numbering, ..counter(heading).at(it.location())) text((" ", it.body).join()) // Update math counter at each new appendix if isappendix.get() { counter(math.equation).update(0) counter(figure.where(kind: image)).update(0) counter(figure.where(kind: table)).update(0) } } else { set text(font-size.normal, weight: "regular", style: "italic") numbering(it.numbering, ..counter(heading).at(it.location())) text((" ", it.body).join()) } } else { text(size: font-size.normal, it.body) } ] // Equations set math.equation(numbering: "(1)", supplement: [Eq.]) // Figures, subfigures, tables // Updates reference counter properly show ref: it => { let el = it.element if el != none and el.func() == figure and el.kind == "subfigure" { context{ let fignum = counter(figure.where(kind: image)).at(here()).first() + 1 let subfignum = numbering("a", counter(figure.where(kind: "subfigure")).at(el.location()).first()) if isappendix.get(){ let heading-counter = numbering("A.1", counter(heading).get().first()) link(it.target, [Fig. #heading-counter.#fignum#subfignum]) } else { link(it.target, [Fig. #fignum#subfignum]) } } } else if el != none and el.func() == figure and repr(el.kind) == "image" { let fignum = counter(figure.where(kind: image)).at(el.location()).first() if isappendix.get() { let heading-counter = numbering("A.1", counter(heading).get().first()) link(it.target, [Fig. #heading-counter.#fignum]) } else { link(it.target, [Fig. #fignum]) } } else { it } } // Formatting figures and tables properly show figure: it => align(center)[ #if repr(it.kind) == "table" { block( [ #text(it.caption, top-edge: 0.15em, size: font-size.small) #it.body ] ) } else { if repr(it.kind).slice(0, 5) == "\"subf" { block( [ #it.body #it.supplement #it.counter.display(it.numbering) #it.caption ] ) } else { block( [ #it.body #v(0.5em) #align(left)[#text(it.caption, top-edge: 0.15em, size: font-size.small)] ] ) counter(figure.where(kind: "subfigure")).update(0) } } ] // Paragraph set par(justify: true, first-line-indent: indent-size, leading: els-linespace) // Page set page( paper: "a4", numbering: "1", margin: els-margin, // Set journal name and date footer: context{ let i = counter(page).at(here()).first() if i == 1 { set text(size: font-size.small) emph(("Preprint submitted to ", journal).join()) h(1fr) emph(datetime.today().display("[month repr:long] [day], [year]")) } else {align(center)[#i]} }, ) // Set authors and affiliation let names = () let names_meta = () let affiliations = () let coord = none for author in authors { let auth = (author.name, super(author.id)) if author.corr != none { if author.id != none { auth.push(super((",", text(baseline: -1.5pt, "*")).join())) } else { auth.push(super(text(baseline: -1.5pt, "*"))) } coord = ("Corresponding author. E-mail address: ", author.corr).join() } names.push(auth.join()) names_meta.push(author.name) if author.affiliation == none { continue } else { affiliations.push((super(author.id), author.affiliation, v(font-size.script)).join()) } } let author-string = if authors.len() == 2 { names.join(" and ") } else { names.join(", ", last: " and ") } // Set document metadata. set document(title: title, author: names_meta) // Display title and affiliation align(center,{ par(leading: 0.75em, text(size: font-size.title, title)) v(0pt) text(size: font-size.author, author-string) v(font-size.small) par(leading: 1em, text(size: font-size.small, emph(affiliations.join()), top-edge: 0.5em)) v(1.5em) }) // Corresponding author v(-2em) hide(footnote(coord, numbering: "*")) counter(footnote).update(0) // Display the abstract if abstract != none { line(length: 100%) text(weight: "bold", [Abstract]) v(1pt) h(-indent-size); abstract linebreak() if keywords !=none { let kw = () for keyword in keywords{ kw.push(keyword) } let kw-string = if kw.len() > 1 { kw.join(", ") } else { kw.first() } text((emph("Keywords: "), kw-string).join()) } line(length: 100%) } // bibliography set bibliography(title: "References") show bibliography: set heading(numbering: none) show bibliography: set text(size: font-size.normal) show: columns(els-columns, body) }
https://github.com/An-314/Notes-of-DSA
https://raw.githubusercontent.com/An-314/Notes-of-DSA/main/binary_tree.typ
typst
= 二叉树Binary Tree - 树是有层次结构的表示: - 表达式 - 文件系统 - URL - 树是综合性的数据结构 - 兼具Vector和List的优点 - 兼顾高效的查找、 插入、 删除 - 树是半线性的结构 - 不再是简单的线性结构,但在确定某种次序之后,具有线性特征 == 二叉树Binary Tree === 图论基础 ==== 有根树Rooted tree 树是极小连通图、极大无环图$T(V,E)$,节点数$n=|V|$,边数$e=|E|$。 指定一个节点$r in V$作为根节点,其他节点到根节点有唯一路径,称为有根树。 若$T_1,T_2,...T_d$为有根树,则$T =( (union.big_i T_i) union {r}, ((union.big_i E_i ))union {<r,r_i>|1<= i <= d})$为有根树。相对于$T$,$T_i$被称为以$r_i$为根的子树。 ==== 有序树Ordered Tree 有根树中,节点的子树有次序,称为有序树。 可以证明树的结点和边满足$n=e+1$。 ==== 连通+无环 连通与无环意味着任意两个节点只有一条路径,即不存在环。 从而可以从根出发,对树进行深度的等价类划分。 ==== 深度+层次 节点$v$的深度定义为$"depth"(v) = |"path"(v)|$,其中$"path"(v)$为从根到$v$的路径。 根节点和叶子的深度为0,其他节点的深度为其父节点的深度加1,空树的深度为-1。 所有叶子深度的最大者叫作树的高度,即$"height"(T) = max{"depth"(v)|v in V}$。 === 树的表示 树提供接口: #table( columns: (auto, auto, auto, auto, auto, auto, auto,), align: horizon, [`root()`], [`parent()`], [`firstChild()`], [`nextSibling()`], [`insert(i, e)`], [`remove(i)`], [`traverse()`], [根节点], [父节点], [第一个孩子], [下一个兄弟], [插入], [删除], [遍历], ) 树可以用线性结构储存: + 利用父节点的信息 除了根节点,每个节点都有一个父节点,可以用线性结构储存。在一个数组`data`存储树节点的值;另开一个数组`parent`存储每个节点的父节点的下标,根节点的父节点下标为其本身。 + 利用孩子节点的信息 除了叶子节点,每个节点都有一个孩子节点,可以用线性结构储存。在一个数组`data`存储树节点的值;另开一个数组`children`存储每个节点的第一个孩子节点的下标,如果有多个孩子就用链表储存所有的孩子。 + 父节点+孩子节点 前面的方法要么只能访问孩子节点,要么只能访问父节点。三个数组同时使用就能双向访问。 === 二叉树Binary Tree 二叉树是所有节点的(出)度数都不超过2的树。是有根、有序的树。 ==== 二叉树和多叉树的等价变换 有根、有序的多叉树和二叉树可以相互转换。 #figure( image("fig\树\1.png",width: 80%), caption: "多叉树和二叉树的等价变换", ) 只要是多叉树中,一个节点的长子,成为二叉树的左儿子,其他的兄弟顺延成为右儿子。也就是说在二叉树中每个节点的右儿子们都是原来的兄弟,左儿子是原来的长子。 ==== 满二叉树 ==== 真二叉树 引入$n_1+2n_0$个外部节点`null`,使得每个节点都有两个儿子,称为真二叉树。 对于红黑树之类的结构,真二叉树可以用来简化描述、理解、实现、分析。 === 二叉树的实现 用节点`BinNode`表示二叉树的节点,用`BinTree`表示二叉树。 ```cpp template <typename T> using BinNodePosi = BinNode<T>*; //节点位置 template <typename T> struct BinNode { BinNodePosi<T> parent, lc, rc; //父亲、孩子 T data; Rank height, npl; Rank size(); //高度、 npl、子树规模 BinNodePosi<T> insertAsLC( T const & ); //作为左孩子插入新节点 BinNodePosi<T> insertAsRC( T const & ); //作为右孩子插入新节点 BinNodePosi<T> succ(); //(中序遍历意义下)当前节点的直接后继 template <typename VST> void travLevel( VST & ); //层次遍历 template <typename VST> void travPre( VST & ); //先序遍历 template <typename VST> void travIn( VST & ); //中序遍历 template <typename VST> void travPost( VST & ); //后序遍历 }; ``` 并且直接实现引入新节点 ```cpp template <typename T> BinNodePosi<T> BinNode<T>::insertAsLC( T const & e ) { return lc = new BinNode( e, this ); } template <typename T> BinNodePosi<T> BinNode<T>::insertAsRC( T const & e ) { return rc = new BinNode( e, this ); } ``` 用`BinNode`实现`BinTree`,并且实现`BinTree`的接口 ```cpp template <typename T> class BinTree { protected: Rank _size; //规模 BinNodePosi<T> _root; //根节点 virtual Rank updateHeight( BinNodePosi<T> x ); //更新节点x的高度 void updateHeightAbove( BinNodePosi<T> x ); //更新x及祖先的高度 public: Rank size() const { return _size; } //规模 bool empty() const { return !_root; } //判空 BinNodePosi<T> root() const { return _root; } //树根 /* ... 子树接入、删除和分离接口;遍历接口 ... */ } ``` 引入新节点,用顺序直接重载函数,表示左右插入 ```cpp BinNodePosi<T> BinTree<T>::insert( BinNodePosi<T> x, T const & e ); //作为右孩子 BinNodePosi<T> BinTree<T>::insert( T const & e, BinNodePosi<T> x ) { //作为左孩子 _size++; x->insertAsLC( e ); updateHeightAbove( x ); //及时维护高度 return x->lc; } ``` 接入子树 ```cpp BinNodePosi<T> BinTree<T>::attach( BinTree<T>* &S, BinNodePosi<T> x ); //接入左子树 BinNodePosi<T> BinTree<T>::attach( BinNodePosi<T> x, BinTree<T>* &S ) { //接入右子树 if ( x->rc = S->_root ) //去除插入空树的情况 x->rc->parent = x; _size += S->_size; updateHeightAbove(x); //及时维护高度 S->_root = NULL; S->_size = 0; release(S); S = NULL; return x; } ``` 用`if`中的赋值大大化简了代码量,其中实时更新高度的函数为 ```cpp #define stature(p) ( (int) ( (p) ? (p)->height : -1 ) ) //空树高度-1,以上递推 template <typename T> //勤奋策略:及时更新节点x高度,具体规则因树不同而异 Rank BinTree<T>::updateHeight( BinNodePosi<T> x ) //此处采用常规二叉树规则, O(1) { return x->height = 1 + max( stature( x->lc ), stature( x->rc ) ); } template <typename T> //更新节点及其历代祖先的高度 void BinTree<T>::updateHeightAbove( BinNodePosi<T> x ) //O( n = depth(x) ) { while (x) { updateHeight(x); x = x->parent; } } //可优化 ``` 分离子树 ```cpp template <typename T> BinTree<T>* BinTree<T>::secede( BinNodePosi<T> x ) { FromParentTo( * x ) = NULL; updateHeightAbove( x->parent ); // 以上与BinTree<T>::remove()一致;以下还需对分离出来的子树重新封装 BinTree<T> * S = new BinTree<T>; //创建空树 S->_root = x; x->parent = NULL; //新树以x为根 S->_size = x->size(); _size -= S->_size; //更新规模 return S; //返回封装后的子树 } ``` == 二叉树的遍历 #figure( image("fig\树\2.png",width: 80%), caption: "二叉树的遍历", ) 树的遍历是按照一定顺序,访问树中的每个节点,且每个节点仅访问一次。 如果采用最直接的递归方式 ```cpp /* 先序遍历 */ template <typename T, typename VST> void traverse( BinNodePosi<T> x, VST & visit ) { if ( ! x ) return; visit( x->data ); traverse( x->lc, visit ); traverse( x->rc, visit ); } //O(n) /* 中序遍历 */ template <typename T, typename VST> void traverse( BinNodePosi<T> x, VST & visit ) { if ( !x ) return; traverse( x->lc, visit ); visit( x->data ); traverse( x->rc, visit ); //tail } /* 后序遍历 */ template <typename T, typename VST> void traverse( BinNodePosi<T> x, VST & visit ) { if ( ! x ) return; traverse( x->lc, visit ); traverse( x->rc, visit ); visit( x->data ); } ``` 则会导致栈溢出,因为递归深度与树的高度成正比。 === 先序遍历 按照$x|L|R$的顺序进行遍历,如下图 #figure( image("fig\树\3.png",width: 80%), caption: "先序遍历", ) 观察图,发现,可以理解为藤缠树。先顺着左儿子构成的藤爬下去,再顺着右儿子构成的藤爬上去;每个右儿子都是一棵子树,在子树中递归地调用先序遍历即可。 沿着左侧藤,整个遍历过程可分解为: - 自上而下访问藤上节点,再 - 自下而上遍历各右子树 各右子树的遍历彼此独立自成一个子任务 爬藤而下: ```cpp template <typename T, typename VST> static void visitAlongVine ( BinNodePosi<T> x, VST & visit, Stack < BinNodePosi<T> > & S ) { //分摊O(1) while ( x ) { //反复地 visit( x->data ); //访问当前节点 S.push( x->rc ); //右孩子(右子树)入栈(将来逆序出栈) x = x->lc; //沿藤下行 } //只有右孩子、 NULL可能入栈——增加判断以剔除后者,是否值得? } ``` 先序遍历: ```cpp template <typename T, typename VST> void travPre_I2( BinNodePosi<T> x, VST & visit ) { Stack < BinNodePosi<T> > S; //辅助栈 while ( true ) { //以右子树为单位, 逐批访问节点 visitAlongVine( x, visit, S ); //访问子树x的藤蔓,各右子树(根)入栈缓冲 if ( S.empty() ) break; //栈空即退出 x = S.pop(); //弹出下一右子树(根) } //#pop = #push = #visit = O(n) = 分摊O(1) } ``` 用栈记录沿藤而下的节点,再向上去访问右子树。如果右子树还需要爬藤,就继续进栈出栈。 先序遍历是在向下爬藤时,就把左儿子遍历的。而下面的中序遍历在向下爬藤时,只进栈,等到向上爬藤时才遍历(,随即立刻遍历其右儿子)。 === 中序遍历 按照$L|x|R$的顺序进行遍历,如下图 #figure( image("fig\树\4.png",width: 80%), caption: "中序遍历", ) 沿着左侧藤,遍历可*自底而上*分解为$d+1$步迭代:访问藤上节点,再遍历其右子树。各右子树的遍历彼此独立,自成一个子任务。 自藤底向上爬: ```cpp template <typename T> static void goAlongVine(BinNodePosi<T> x, Stack < BinNodePosi<T> > & S){ while ( x ) { S.push( x ); x = x->lc; } } //逐层深入,沿藤蔓各节点依次入栈 ``` 中序遍历: ```cpp template <typename T, typename V> void travIn_I1( BinNodePosi<T> x, V& visit ) { Stack < BinNodePosi<T> > S; //辅助栈 while ( true ) { //反复地 goAlongVine( x, S ); //从当前节点出发,逐批入栈 if ( S.empty() ) break; //直至所有节点处理完毕 x = S.pop(); //x的左子树或为空,或已遍历(等效于空),故可以 visit( x->data ); //立即访问之 x = x->rc; //再转向其右子树(可能为空,留意处理手法) } } ``` 和先序遍历的区别是,读取藤的时机。先序遍历向下爬藤时读取,中序遍历向上爬藤时读取。 其复杂度是$O(n)$的,因为一共执行$O(n)$次`pop`和`push`,每次`pop`和`push`都是$O(1)$的。 ==== 前驱和后继 考虑一个节点的后继:如果有右子树,直接后继是最靠左的右后代:相当于沿着该节点的右儿子爬藤而下到底。如果没有右子树,需要找最低的左祖先:相当于辅助栈中的下一个节点,寻找的方法是一直寻找父亲,直到访问的这条路成为了某一个父亲的左儿子。 ```cpp //在中序遍历意义下的直接后继 //稍后将被BST::remove中的removeAt()调用 template <typename T> BinNodePosi<T> BinNode<T>::succ() { BinNodePosi<T> s = this; if ( rc ) { //若有右孩子,则 s = rc; //直接后继必是右子树中的 while ( HasLChild( * s ) ) s = s->lc; //最小节点 }else { //否则 //后继应是“以当前节点为直接前驱者” while ( IsRChild( * s ) ) s = s->parent; //不断朝左上移动 //最后再朝右上移动一步 s = s->parent; //可能是NULL } return s; //两种情况下,运行时间分别为 } //当前节点的高度与深度,不过O(h) ``` === 后序遍历 子树的删除和`BinNode::size()`和` BinTree::updateHeight()`维护,就是一个后序遍历的例子。 按照$L|R|x$的顺序进行遍历,如下图 #figure( image("fig\树\5.png",width: 80%), caption: "后序遍历", ) 从根出发下行尽可能沿左分支,实不得已才沿右分支,这样找到*leftmost leaf*。最后一个节点必是叶子,而且是按中序遍历次序最靠左者,也是递归版中`visit()`首次执行处。 #figure( image("fig\树\6.png",width: 40%), caption: "后序遍历", ) 在沿着这条曲折的藤向上爬时,如果有右儿子,就对右子树进行递归,没有就向上走。这条藤事实上在右子树封装的情况下实现了后序遍历,只需要把封装的右子树展开。 寻找`leftmost leaf` ```cpp template <typename T> static void gotoLeftmostLeaf( Stack <BinNodePosi<T>> & S ) { while ( BinNodePosi<T> x = S.top() ) //自顶而下反复检查栈顶节点 if ( HasLChild( * x ) ) { //尽可能向左。在此之前 if ( HasRChild( * x ) ) //若有右孩子,则 S.push( x->rc ); //优先入栈 S.push( x->lc ); //然后转向左孩子 } else //实不得已 S.push( x->rc ); //才转向右孩子 S.pop(); //返回之前,弹出栈顶的空节点 } ``` 后序遍历: ```cpp template <typename T, typename V> void travPost_I( BinNodePosi<T> x, V & visit ) { Stack < BinNodePosi<T> > S; //辅助栈 if ( x ) S.push( x ); //根节点首先入栈 while ( ! S.empty() ) { //x始终为当前节点 if ( S.top() != x->parent ) //若栈顶非x之父(而为右兄),则 gotoLeftmostLeaf( S ); //在其右兄子树中找到最靠左的叶子 x = S.pop(); //弹出栈顶(即前一节点之后继)以更新x visit( x->data ); //并随即访问之 } } ``` 也可以分析得到复杂度是$O(n)$的。 ==== 表达式 一个运算表达式可以存储在一个树种,每个节点是一个运算符,每个叶子是一个操作数。括号的层级就是树的深度。 #figure( image("fig\树\8.png",width: 80%), caption: "表达式", ) #figure( image("fig\树\9.png",width: 80%), caption: "表达式", ) 可以看出这些红色和绿色的节点构成一棵树,就是下面的表达式树。 #figure( image("fig\树\7.png",width: 80%), caption: "表达式树", ) 而先序、中序、后序遍历就是表达式的前缀、中缀、后缀表示。 === 层次遍历 层次遍历是按照层次进行遍历。可以用一个队列实现: 在取出一个节点时,把它的左右儿子入队,这样达到的效果是按照顺序,将每一层的节点从左向右遍历。 ```cpp template <typename T> template <typename VST> void BinNode<T>::travLevel( VST & visit ) { //二叉树层次遍历 Queue< BinNodePosi<T> > Q; Q.enqueue( this ); //引入辅助队列,根节点入队 while ( ! Q.empty() ) { //在队列再次变空之前,反复迭代 BinNodePosi<T> x = Q.dequeue(); visit( x->data ); //取出队首节点并随即访问 if ( HasLChild( *x ) ) Q.enqueue( x->lc ); //左孩子入队 if ( HasRChild( *x ) ) Q.enqueue( x->rc ); //右孩子入队 } } ``` == 二叉树的重构 二叉树的重构是指,已知二叉树的遍历序列,重构出二叉树。 === [先序|后序]+中序 已知先序和中序,可以重构出二叉树。 先序序列:$x|L|R$ 中序序列:$L|x|R$ 先序序列的第一个节点是根节点,中序序列中根节点左边的是左子树,右边的是右子树。 后序同理。 === 先序+后序 不能重构,因为无法确定左右子树。 === 增强序列 在输出遍历序列时,将`NULL`也输出,这样就可以重构出二叉树。 可归纳证明:在增强的先序、后序遍历序列中 1. 任一子树依然对应于一个子序列,而且 2. 其中的`NULL`节点恰比非`NULL`节点多一个 == Huffman编码树 如何对各字符编码,使文件最小? === PFC编码 将字符集$Sigma$中的字符组织成一棵二叉树,以0/1表示左/右孩子,各字符$x$分别存放于对应的叶子$v(x)$中。 字符$x$的编码串$"rps"(v(x))="rps"(x)$由根到$v(x)$的通路(root path)确定 字符编码不必等长,而且不同字符的编码互不为前缀,故不致歧义(Prefix-Free Code)。 #figure( image("fig\树\10.png",width: 40%), caption: "PFC编码", ) 按照这样的方法可以分析编码长度。 平均编码长度 $ "ald"(T) = sum_(x in Sigma) "depth"(v(x)) / (|Sigma|) $ 定义对于特定的字符集$Sigma$,$"ald"(T)$最小的二叉树$T_("Opt")$为$Sigma$的最优编码树(Optimal Code Tree)。 === 最优编码树 最优编码树的性质: $ forall v in T_("Opt") : "deg"(v)=0 <=> "depth"(v) >= "depth"(T_("Opt")) -1 $ 亦即,叶子只能出现在倒数两层以内——否则,通过节点交换即可调整到更优的编码树。 #figure( image("fig\树\11.png",width: 80%), caption: "最优编码树", ) === 最优带权编码树 已知各字符的期望频率,此时的最优编码树称为最优带权编码树(Optimal Weighted Code Tree)。 文件长度 $prop$ 平均带权深度 $"wald"(T) = sum_(x in Sigma) "rps"(x) times w(x)$。此时,完全树未必就是最优编码树。 同样,频率高/低的(超)字符,应尽可能放在高/低处,通过适当交换,同样可以缩短$"wald"(T)$。 === Huffman的贪心策略 频率低的字符优先引入,其位置亦更低。 #figure( image("fig\树\12.png",width: 50%), caption: "最优编码树", ) ```cpp 为每个字符创建一棵单节点的树,组成森林F 按照出现频率,对所有树排序 while ( F中的树不止一棵 ) 取出频率最小的两棵树: T1和T2 将它们合并成一棵新树T,并令: lc(T) = T1 且 rc(T) = T2 w( root(T) ) = w( root(T1) ) + w( root(T2) ) //尽管贪心策略未必总能得到最优解, 但非常幸运,如上算法的确能够得到最优编码树之一 ``` 将树合成子树,每次比较根节点的权重,取出最小的两棵树,合成一棵新树,再放回去。可以用优先队列优化。 可以证明,Huffman编码树是最优带权编码树。 下面是代码实现。 先定义Huffman(超)字符 ```cpp #define N_CHAR (0x80 - 0x20) //仅以可打印字符为例 struct HuffChar { //Huffman(超)字符 char ch; unsigned int weight; //字符、频率 HuffChar ( char c = '^', unsigned int w = 0 ) : ch ( c ), weight ( w ) {}; bool operator< ( HuffChar const& hc ) { return weight > hc.weight; } //比较器 bool operator== ( HuffChar const& hc ) { return weight == hc.weight; } //判等器 }; ``` 再定义Huffman编码树 ```cpp using HuffTree = BinTree< HuffChar >; //Huffman编码树 using HuffForest = List< HuffTree* >; //Huffman森林 /* 可以替换接口... */ using HuffForest = PQ_List< HuffTree* >; //基于列表的优先级队列 using HuffForest = PQ_ComplHeap< HuffTree* >; //完全二叉堆 using HuffForest = PQ_LeftHeap< HuffTree* >; //左式堆 ``` 构造编码树:反复合并二叉树 ```cpp HuffTree* generateTree( HuffForest * forest ) { //Huffman编码算法 while ( 1 < forest->size() ) { //反复迭代,直至森林中仅含一棵树 HuffTree *T1 = minHChar( forest ), *T2 = minHChar( forest ); HuffTree *S = new HuffTree(); //创建新树,然后合并T1和T2 S->insert( HuffChar('^', T1->root()->data.weight + T2->root()->data.weight) ); S->attach( T1, S->root() ); S->attach( S->root(), T2 ); forest->insertAsLast( S ); //合并之后,重新插回森林 } //assert: 森林中最终唯一的那棵树,即Huffman编码树 return forest->first()->data; //故直接返回之 } ``` 查找最小超字符:遍历List/Vector ```cpp HuffTree* minHChar( HuffForest* forest ) { //此版本仅达到O(n),故整体为O(n2) ListNodePosi<HuffTree*> m = forest->first(); //从首节点出发,遍历所有节点 for ( ListNodePosi<HuffTree*> p = m->succ; forest->valid( p ); p = p->succ ) if( m->data->root()->data.weight > p->data->root()->data.weight ) //不断更新 m = p; //找到最小节点(所对应的Huffman子树) return forest->remove( m ); //从森林中取出该子树,并返回 } //Huffman编码的整体效率,直接决定于minHChar()的效率 ``` 构造编码表:遍历二叉树 ```cpp #include "Hashtable.h" //用HashTable实现 using HuffTable = Hashtable< char, char* >; //Huffman编码表 static void generateCT //通过遍历获取各字符的编码 ( Bitmap* code, int length, HuffTable* table, BinNodePosi<HuffChar> v ) { if ( IsLeaf( * v ) ) //若是叶节点(还有多种方法可以判断) { table->put( v->data.ch, code->bits2string( length ) ); return; } if ( HasLChild( * v ) ) //Left = 0,深入遍历 { code->clear( length ); generateCT( code, length + 1, table, v->lc ); } if ( HasRChild( * v ) ) //Right = 1 { code->set( length ); generateCT( code, length + 1, table, v->rc ); } } //总体O(n) ``` === Huffman树的改进 1. 基于向量或者列表 基于向量或数组的森林每次插入树都要寻找合适的位置以保证有序,这导致查找需要$O(n)$的时间,从而使得整体的复杂度为$O(n^2)$。 2. 基于堆 可以将所有树组成一个优先级队列,每次取出最小的两棵树,合并成一棵新树,再放回去。这样可以将复杂度降低到$O(n log n)$。 3. 基于栈+队列 还有一个小技巧是,先经过$O(n log n)$的预排序。再将 - 所有字符按频率非升序入栈 $O(n log n)$ - 维护另一(有序) 队列 $O(n)$ 每次看栈顶两个元素与队首元素,取两个最小的,合并成一棵新树,入队。这样可以将复杂度降低到$O(n log n)$。 #figure( image("fig\树\13.png",width: 80%), caption: "基于栈+队列的Huffman编码树", )
https://github.com/eliapasquali/typst-thesis-template
https://raw.githubusercontent.com/eliapasquali/typst-thesis-template/main/appendix/bibliography/bibliography.typ
typst
Other
#pagebreak(to: "odd") // Hayagriva format #bibliography("bibliography.yml") // Biblatex // #bibliography("bibliography.bib")
https://github.com/mumblingdrunkard/mscs-thesis
https://raw.githubusercontent.com/mumblingdrunkard/mscs-thesis/master/src/computer-architecture-fundamentals/high-performance-processor-architecture.typ
typst
#import "../utils/utils.typ": * == High-Performance Processor Architecture <sec:high-performance-processor-architecture> With the basics covered, we can move on to the state of the art of processing: out-of-order (OoO) processors. In-order (InO) processors execute instructions in program order and later instructions cannot start until earlier instructions have progressed past some point, even if their dependencies are ready. OoO processors attempt to exploit all available ILP by executing multiple instructions in parallel, allowing instructions to execute as soon as their dependencies are resolved. Later instructions can complete before earlier ones. For example, a load instruction that misses in the L1d may not finish for several tens of cycles. Instructions that are not dependent on that load instruction can progress as normal and finish before it; i.e.: out-of-order. === Available Instruction-Level Parallelism We should specify what we mean when we say that there is available ILP even when the parallelisation of a program across many cores is difficult or impossible. Any program, can be represented as a graph where later instructions can depend on earlier instructions, but they do not depend on all of them. There are different types of dependencies, of which only one kind is really important in modern OoO processors. ==== Read-After-Write Dependencies _Read-after-write_ (RAW) dependencies arise when an instruction depends on the result of a previous instruction. I.e.: when an earlier instruction writes to a register and a later instruction uses the result as one of its operands. These are termed _true dependencies_. ==== Write-After-Write and Write-After-Read Dependencies The two other types of dependencies are _write-after-write_ (WAW) and _write-after-read_ (WAR). These are termed _false dependencies_ and arise when a later instruction writes to a register that is used---read, or written---by an earlier instruction. Naively allowing the later instruction to execute first would leave the value in the register mangled as the earlier value would eventually overwrite the later value, or the earlier instruction would use a value produced by a later instruction. === A High-Level Overview @fig:ooo-architecture shows a high-level overview of the various pieces that go into an OoO processor. #figure( ```monosketch ┌────────┬───┐ │ │ROB├───────┐ │ ┌────▶──▲┘ │ │ ┌ ┼ ─ ─ ─ ┼ ─ ─ ─ ┐│ ┌──┐ ┌──┐ ┌──┐ ┌─▼┐ │┌──┐ ┌─┴┐ ┌───┐ │ │I$├─▶IF├─▶ID├─▶RR├┼─┴▶IQ├─▶FU◀─▶MEM│││ └──┘ └─▲┘ └──┘ └──┘ └─▲┘ └┬┬┘ └───┘ │ └───────────┼────┼───┘│ ││ │ ┌─▼─┐ │ │ └──┤PRF◀─────┼┘ └───┘ └ ─ ─ ─ ─ ─ ─ ─ ─ ┘ Out-of-order ```, caption: [High-level overview of an out-of-order processor architecture], kind: image, )<fig:ooo-architecture> The different parts are - the instruction-cache `I$`, - instruction fetch `IF` and instruction decode `ID` as seen earlier, - register-rename `RR`, - issue-queue `IQ`, - re-order buffer `ROB`, - functional units `FU`, - physical register file `PRF`, and - the memory `MEM`. The various components are described in more detail further on. This overview hides a lot of complexity---especially in the FUs. One important FU is the unit for managing memory accesses. === Register Renaming _Register renaming_ (RR) is an important piece of the puzzle that enables OoO execution. Register renaming removes false dependencies from the instruction stream by using a new physical location each time an instruction would write to a register. Register renaming uses a _physical register file_ (PRF) that is different from the register file defined by the ISA. The registers defined by the ISA are called _architectural registers_ and the register file is the _architectural register file_ (ARF). Every time an instruction enters the processor and is going to write to some target architectural register, the instruction is given an unused physical register that it should write to instead. Later instructions that read from that same architectural register will similarly read from the physical register that was assigned earlier. The status of registers in the PRF can be used or unused, and the value within the register can be ready or not ready. If two instructions $a$ and $b$ write to the same architectural register, they each receive a physical register to write to instead. The physical register destination of $a$ can be _released_ (set to unused) when no more instructions between $a$ and $b$ depend on the result from $a$. Intuitively, no instructions after $b$ can depend on the result of $a$ as $b$ overwrites the value in the architectural register. The PRF must be at least as large as the ARF plus one to ensure the entire architectural state can be tracked at any time and that there is at least one unused physical register to map an incoming architectural register to. Often, the PRF is several times larger than the ARF, depending on how many instructions can be tracked at once. === Frontend, Backend, and Commit OoO processors are usually discussed in terms of an InO _frontend_ that fetches instructions, decodes them, renames the architectural registers, and dispatches them to the OoO _backend_ as uOPs. The backend consists of one or more IQs, FUs, the PRF, and the ROB. The ROB contains the instructions/uOPs in the order they entered the frontend. The IQs contain _slots_ in which the uOPs wait. For example, the physical registers that a uOP depends upon may not yet have its value written; the value is not ready. The job of the IQ slot is to wait for the dependencies to become ready, possibly fetching and storing the values temporarily. When all dependencies are available, the uOP is ready to be _issued_ (sent) to one or more appropriate FUs. There are several FUs in an OoO processor just like there are in an InO processor. The difference is that FUs in InO processors are all in the same stage and thus cannot be utilised in the same cycle. Thus, most of the FUs in an InO processor go unused for most of the cycles. There may multiple ALU-like units containing various circuits for performing arithmetic. There may be _address generation units_ (AGU) whose sole purpose is to calculate the addresses used by memory operations. FUs can produce results instantly (in the same cycle), or they can take many cycles for a single uOP. FUs that take many cycles may re-use the same inner parts in multiple of the cycles, meaning the FU cannot process more than one uOP at a time, or it may itself be pipelined, using new components in each cycle. When FUs produce results, the results may be passed on to other units for further processing, or they may be completed, in which case they are written back to the PRF and the corresponding entry in the ROB is marked as completed. The ROB has a _head-_ and a _tail_-end. uOPs enter the ROB at the tail-end. As uOPs at the head-end finish, they _commit_ and the head moves toward the tail. When instructions commit, the It is only after committing that instructions are truly reflected in the architectural state. Commit happens in-order because the ROB is in-order. Up until that point, their results may be _rolled back_ (undone), which can be necessary in the case of exceptions or mispredictions. In practice, the ROB is implemented as a circular buffer. === Memory Access Unit As mentioned, the FU for accessing memory is hidden in the high-level overview of @fig:ooo-architecture. This unit will usually manage structures like the L1d and the _translation look-aside buffer_ (TLB). The TLB is responsible for translating virtual addresses to physical addresses. It is essentially a small cache for address translations. The tables used for translation are stored in memory and the processor would need to make additional memory requests for all virtual memory accesses were it not for the TLB. In addition to these structures, the memory access unit contains structures for tracking requests to the L1d like loads and stores. === Unlocking Memory-Level Parallelism One of the biggest advantages of OoO execution is that it easily unlocks _memory-level parallelism_ (MLP). As long as memory instructions do not depend on each other's results, they can make progress in parallel. Properly exploiting MLP requires certain optimisations to the L1d like _hit-under-miss_ which allows later memory instructions to make progress even while the L1d is processing a memory instruction that missed. ==== Latency Hiding By unlocking and properly exploiting MLP, the apparent latency of memory instructions is reduced. Even whithout certain optimisations to the L1d, memory instructions can usually start execution earlier than they would be able to in an InO processor, thus reducing their apparent latency. In large designs, the processor often has enough available work to perform to completely hide the impact of a miss in the L1d. === Speculative Execution Processors rely on branch predictors to keep the frontend from stalling and keep the backend fed with instructions. Branch instructions may take a lot of time to resolve, for example if they depend on the result of a load instruction that misses in the L1d. The nature of OoO execution means later instructions will continue executing while waiting for the branch to resolve. If the prediction turns out to be wrong, the processor state will be rolled back to just after the branch and the frontend will be redirected to the correct path of execution. All the work between a branch prediction being made and a branch resolving is _speculative_. When the prediction is incorrect, the speculative work is squashed and is called _transient execution_. The Merriam-Webster dictionary defines "transient" as "passing especially quickly into and out of existence", which is a fitting description of work that has been performed only to be squashed. Speculation happens in InO processors too, but as branches are resolved in order, incorrectly fetched instructions do not get to affcet microarchitectural state such as caches. This is not the case in OoO processors where a load instruction fetched after a speculated branch is allowed to access memory before it is known whether it really is part of proper execution. === Performance and Metrics When discussing the performance of modern processors, there are several important metrics to consider. The total work performed by a processor is the _instructions per second_ (IPS), commonly given as _millions of instructions per second_ (MIPS). IPS is a product of the average number of _instructions per cycle_ (IPC) and _cycles per second_ (which is just called the frequency, denoted by Hz). The inverse of IPC is _cycles per instruction_ (CPI). Consider that not all instructions are created equal. An IPS of 1'000'000 in one ISA may not be equivalent to an IPS of 1'000'000 in another ISA if one of them performs less "real work" per instruction. It is still a useful metric when comparing micro-architectures for the same ISA, but can be misleading when comparing microarchitectures for different ISAs. Lastly, _performance per watt_ (PPW) and _energy per instruction_ (EPI) are useful metrics. When operating at the limit of heat dissipation, the only way to improve performance is to do so in tandem with improvements in PPW. ==== Predictions As we discuss predictions in this thesis, we should cover some of the metrics used when discussing predictors of various sorts. Various metrics affect the efficacy of cache prefetching such as _accuracy_, _coverage_, and _timeliness_. Accuracy is the number of useful prefetches compared to the number of performed prefetches. Coverage is the fraction of misses that instead become hits due to prefetching. Timeliness is a metric that says something about the usefulness of the data that are prefetched. If a prefetch request goes out too late, the next request may come in before the data are fully in cache. Timeliness is a yes-or-no answer, while accuracy and coverage are metrics with tradeoffs. Issuing more prefetches when the prediction is uncertain but there is available capacity may increase coverage at the cost of reducing accuracy and wasting more power. Issuing more prefetches might also have the adverse effect of reducing performance by taking up limited bandwidth, or it might cause useful data to be _evicted_ (pushed out) from the cache to make space for prefetched data that aren't useful. Branch predictors have an accuracy measurement which is the ratio of correct predictions to the number of branch instructions fetched. Branch predictors do not have coverage as they have to cover 100% of branches, lest fetching stall completely. When branch predictors fail to make predictions using advanced algorithms, they fall back on heuristics like "always jump" or "never jump" based on good guesses about how normal programs are written #footnote[ Branches that jump back in the program are associated with loops and are usually always taken in the first few iterations. ]. Whether branch predictors can be "timely" in the same manner is perhaps up for debate. When fetching multiple instructions per cycle, a branch prediction can be "late" without affecting performance as long as the processor is not completing instrucitons faster than they can be fetched. In fact, processors will commonly have several branch predictors where a fast predictor redirects instruction fetch quickly. If a more accurate but slower predictor later disagrees with the prediction, instruction fetch is redirected to use the higher accuraly prediction.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/raw-syntaxes_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(width: 180pt) #set text(6pt) #set raw(syntaxes: "/assets/files/SExpressions.sublime-syntax") ```sexp (defun factorial (x) (if (zerop x) ; with a comment 1 (* x (factorial (- x 1))))) ```
https://github.com/v411e/optimal-ovgu-thesis
https://raw.githubusercontent.com/v411e/optimal-ovgu-thesis/main/acknowledgement.typ
typst
MIT License
#import "components.typ": body-font, variable-pagebreak #let oot-acknowledgement(heading: "Acknowledgements", is-doublesided: none, body) = { set align(center) v(0.1fr) if heading.len() > 0 { text(font: body-font, 1em, weight: "semibold", heading ) v(1em) } text(body) v(1fr) variable-pagebreak(is-doublesided) }
https://github.com/Dherse/masterproef
https://raw.githubusercontent.com/Dherse/masterproef/main/masterproef/parts/preface.typ
typst
#import "../ugent-template.typ": * #show: ugent-preface = Remark on the master's dissertation and the oral presentation This master's dissertation is part of an exam. Any comments formulated by the assessment committee during the oral presentation of the master's dissertation are not included in this text. = Acknowledgements <sec_ack> I would like to express my deepest gratitude to Prof. dr. ir. <NAME> and Prof. dr. ir. <NAME> for their time, guidance, patience, and trust in applying for an #emph[FWO] proposal to extend this Master Thesis. Through their advice and guidance, I have gained a breadth of knowledge and understanding that I have done my best to share in this thesis. It is with great pleasure that I write this document to share these findings and insights with them and others within the scientific community. I would also like to give my most heartfelt thanks to the best friend one could ever ask for: ir. <NAME>, for his patience, friendship, guidance and all of the amazing moments we spent throughout our studies. I would also like to thank him for his help in proofreading this thesis and his advice on the PHÔS programming language. I also would like to thank <NAME> for his help and advice for the creation of the formal grammar of the PHÔS programming language and being a great friend for over a decade. I must also thank the incredible people that helped me proofread and improve my thesis: <NAME> and <NAME> for their time, advice and support. And <NAME> for his help on programmatic visualisation of hexagonal lattices and his advice regarding typesetting. Finally, my parents, <NAME> and <NAME>, were also there for me every step of the way and I deeply thank them for their support and listening to my endless rambling about photonics and programming. #align(right)[ -- <NAME> #linebreak() Wavre BE, 16th of June 2023 ] = Permission of use on loan The author gives permission to make this master dissertation available for consultation and to copy parts of this master dissertation for personal use. In the case of any other use, the copyright terms have to be respected, in particular with regard to the obligation to state expressly the source when quoting results from this master dissertation. #align(right)[ -- <NAME> #linebreak() Wavre BE, 16th of June 2023 ] = Abstract In this thesis, a novel way of programmatically designing photonic circuits is introduced, using a new programming language called PHÔS. This thesis' primary goal is to research which paradigms, techniques, and languages are best suited for the programmatic description of photonic circuits, with a special emphasis on programmable photonics as it is being researched at Ghent University. This involves an in-depth analysis of existing programming languages and paradigms, followed by a careful analysis of the functional requirements of photonic circuit design. This analysis highlights the need for a new language dedicated to photonic circuit design that is able to concisely and effectively express photonic circuits. The design of this language is then shown, with all of the steps for its implementation carefully detailed. Parts of this language are implemented in a prototype compiler. One of its components, the constraint-solver, was the primary focus of this development effort, which has shown to be capable of simulating many photonic circuits based on simple constraints and operations. Finally, meaningful demonstrations of the capabilities of the language and the constraint-solver are shown. == Keywords Programmable photonic, photonic circuit design, programming language, photonic circuit simulation. #ugent-outlines( // Whether to include a table of contents. heading: true, // Whether to include a list of acronyms. acronyms: true, // Whether to include a list of figures. figures: true, // Whether to include a list of tables. tables: true, // Whether to include a list of equations. equations: false, // Whether to include a list of listings (code). listings: true, )