repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/01-history/ttf-to-otf.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/components.typ": note #import "/lib/glossary.typ": tr #show: web-page-template // ## From TrueType to OpenType == 从TrueType到OpenType // But it was to no avail. There were many reasons why TrueType ended up winning the font wars. Some of these were economic in nature: the growing personal computer market meant that Microsoft and Apple had tremendous influence and power while Adobe remained targeting the high-end market. But some were technical: while PostScript fonts never really advanced beyond their initial capabilities, TrueType was constantly being developed and extended. 但这都无济于事。TrueType最终赢得字体大战的原因有很多。一些是经济上的:不断增长的个人计算机市场意味着微软和苹果有着巨大的影响和力量,而Adobe却仍将目标对准高端市场。另一些则是技术上的:PostScript 字体从未真正超出其初始功能,但TrueType则一直在不断开发和扩展。 // Apple extended TrueType, first as "TrueType GX" (to support their "QuickDraw GX" typography software released in 1995) and then as Apple Advanced Typography (AAT) in 1999. TrueType GX and AAT brought a number of enhancements to TrueType: ligatures which could be turned on and off by the user, complex contextual substitutions, alternate glyphs, and font variations (which we will look at in the next section). AAT never hit the big time; it lives on as a kind of typographic parallel universe in a number of OS X fonts (the open source font shaping engine Harfbuzz recently gained support for AAT). Its font variation support was later to be adopted as part of OpenType variable fonts, but the rest of its extensions were to be eclipsed by another development on top of TrueType: OpenType. 苹果扩展了TrueType。首先是TrueType GX(以支持其1995年发布的QuickDraw GX印刷软件),然后是1999年的Apple Advanced Typography(AAT)。TrueType GX和AAT大幅扩充了TrueType的功能:允许用户决定是否启用的#tr[ligature]、复杂的#tr[contextual]#tr[substitution]、#tr[alternate glyph]和字体变体(我们将在下一节中介绍)。但AAT也没有大获成功,它仅以几个OS X字体的形式存在于#tr[typography]的平行宇宙中(开源的字体#tr[shaping]引擎HarfBuzz最近支持了AAT)。它其中大部分扩展被基于TrueType开发的OpenType所彻底掩盖,字体变体则被吸收为OpenType#tr[variable font]功能的一部分。 // In 1997, Microsoft and Adobe made peace. They worked to develop their own set of enhancements to TrueType, which they called TrueType Open (Microsoft's software strategy throughout the 1990s was to develop software which implemented a public standard and extend it with their own feature enhancements, marginalizing users of the original standard. TrueType Open was arguably another instance of this...); the renderer for TrueType Open, Uniscribe, was added to the Windows operating system in 1999. 1997年,微软和Adobe达成了和解。他们致力于开发自己的TrueType扩展集,称为TrueType Open(Microsoft在1990年代的软件战略是开发符合公共标准的软件,并加入自己的增强功能以对其进行扩展,从而使原始标准的用户处于边缘地位。TrueType Open可以说是这种策略的一个例子)。TrueType Open的渲染器Uniscribe于1999年集成进Windows操作系统。 // Later called OpenType, the development of this new technology was led by <NAME> of Adobe and <NAME> of Microsoft,[^12] and had the design goal of *interoperability* between TrueType fonts and Adobe Type 1 PostScript fonts. In other words, as well as being an updated version of TrueType to allow extended typographic refinements, OpenType was essentially a *merger* of two very different font technologies: TrueType and PostScript Type 1. As well as being backwardly compatible with TrueType, it allowed PostScript Type 1 fonts to be wrapped up in a TrueType-like wrapper - one font format, containing two distinct systems. 这项新技术后来被称为OpenType,由Adobe的<NAME>和微软的<NAME>领导开发#footnote[ // When Microsoft were working on TrueType Open before the tie-up with Adobe, the technical development was led by <NAME> and <NAME>. 在微软和Adobe的合作开始前,TrueType Open由<NAME>和<NAME>领导开发。 ],其设计目标是在TrueType字体和Adobe PostScript Type 1 字体之间实现*互通*。换句话说,OpenType不仅是添加了高级#tr[typography]功能的TrueType改进版,而且本质上是TrueType 和 PostScript Type 1这两种非常不同的字体技术的*并集*。除了向后兼容TrueType之外,它还允许将PostScript Type 1字体封装在类似TrueType的容器中——一种字体格式,包含两个不同的系统。 // OpenType is now the *de facto* standard and best in class digital font format, and particularly in terms of its support for the kind of things we will need to do to implement global scripts and non-Roman typography, and so that's what we'll major on in the rest of this book. OpenType现在是数字字体的事实标准,也是最优秀的一种格式,尤其是考虑到对#tr[global scripts]和非拉丁#tr[typography]的支持。这也是在本书剩余部分中我们要重点讨论的内容。
https://github.com/protohaven/printed_materials
https://raw.githubusercontent.com/protohaven/printed_materials/main/common-policy/covid_protocols.typ
typst
= Covid Protocols <covid-protocols> == Before Coming to Protohaven <covid-before-coming> Before coming to Protohaven, we ask everyone to verify that you: + Pass a self-screen for common Covid symptoms, meaning: - No fever - No cough or shortness of breath - No change in sense of taste or smell, and + Have not had close contact with someone who has tested positive for Covid in the last 10 days + Use the online calendar to schedule a time to visit the shop, so we have a record of all visitors If someone has had symptoms or contact, we ask that they not return to the shop until they either receive a negative Covid test result, or wait 10 days after their last symptoms or contact. == While at Protohaven <covid-at-protohaven> While using the shop, we ask you to: - Wear a face mask (N95 if possible) if you are not vaccinated - Maintain six feet social distance from others - Regularly wash their hands - Carry a supplied cleaning kit and wipe down commonly-touched surfaces before and after use == After Leaving Protohaven <covid-after-leaving> If, after leaving the shop, a visitor develops common Covid symptoms, we ask that they get tested for Covid-19 and share the results with us. This allows us to take the appropriate cleaning, testing, and notification measures if the test comes back positive.
https://github.com/yangyangdy/mycv
https://raw.githubusercontent.com/yangyangdy/mycv/main/README.md
markdown
MIT License
# Chi CV template ![GitHub top language](https://img.shields.io/github/languages/top/matchy233/chi-cv-template) ![GitHub](https://img.shields.io/github/license/matchy233/chi-cv-template) Rip-off of [<NAME> (cxs/skyzh)](https://github.com/skyzh)'s [CV](https://skyzh.github.io/files/cv.pdf) as a LaTeX template called `chicv`. Suggestions and PRs are welcome. Honestly, I'm not a master in LaTeX. 照着迟先生的简历扒的模板。祝大家都能成功得令人震惊。 Note to `chi-cv-template` users: according to [Chi's twitter](https://twitter.com/iskyzh/status/1639139679235633153), he's planning to switch to a new typesetting app: [typst](https://typst.app/), which is also recommended by several of my friends. It's currently (as of March 2023) in beta, but it's worth a try. ## Sample Output ![Sample output of Chi-CV template](./img/chi-cv-preview.png) [PDF file](resume.pdf) ## To-Dos ### Chores - [ ] Instructions on how to compile - [ ] Intro to custom environments and commands - [ ] (Probably) publish to CTAN as a proper `.cls`. ### Additional ideas I personally need an academic curriculum vitae. - [ ] Publication list ## Acknowledgement Heavily referred to the code of [billryan/resume](https://github.com/billryan/resume) and [ice1000/resume](https://github.com/ice1000/resume).
https://github.com/maxlambertini/troika-srd-typst
https://raw.githubusercontent.com/maxlambertini/troika-srd-typst/main/main.typ
typst
#import "template.typ": * #import "chap01.typ": * #import "chap02.typ": * #import "chap03.typ": * #import "chap04.typ": * #import "chap05.typ": * #import "chap06.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "Troika!", authors: ( "<NAME>", ), date: "November 15, 2023", logo: "fortle.svg", cover: "troika_cover.png" ) #show heading.where( level: 1 ): it => block(width: 100%)[ #set align(center) #set par(justify: false) #set text(size:40pt, hyphenate: false, weight: 700 , font: "Bokor") #it.body ] #show heading.where( level: 2 ): it => block(width: 100%)[ #set align(left) #set par(justify: false) #set text(size:1.4em,hyphenate: false, weight: 700, font: "Bokor") #it.body #v(6pt) ] #show heading.where( level: 3 ): it => block(width: 100%)[ #set align(left) #set par(justify: false) #set text(size:1.2em,hyphenate: false, weight: 700, font: "Bokor") #it.body ] #show heading.where( level: 4 ): it => block(width: 100%)[ #set align(left) #set par(justify: false) #set text(size:1.1em,hyphenate: false, weight: 400, style: "italic", font: "Averia Serif Libre") #it.body ] #set page(header: locate(loc => { let elems = query( selector(heading).after(loc), loc, ) let academy = smallcaps[ Troika! ] if elems == () { align(right, academy) } else { let body = elems.first().body academy + h(1fr) + emph(body) } })) #show outline.entry.where( level: 1 ): it => { v(10pt, weak: true) strong(it) } #show outline.entry.where( level: 1 ): it => { v(6pt, weak: true) text(size: 1.1em, weight:700,it) } #set page( background: locate(loc => if calc.even(loc.page()) { if loc.page() > 6 { image( "troika-left-border.png", ) } } else { if loc.page() > 6 { image( "troika-right-border.png", ) }// odd page })) #pagebreak() #chapterLayout(chap01_title, 1, chap01) #pagebreak() #chapterLayout([ = Contents], 3, outline( indent: 3mm, depth: 3, title: none)) #pagebreak() #chapterLayout(chap02_title, 2, chap02) // #pagebreak() #chapterLayout(chap03_title, 2, chap03) #pagebreak() #chapterLayout(chap04_title, 2, chap04) // #pagebreak() #chapterLayout(chap05_title, 2, chap05) #pagebreak() #chapterLayout(chap06_title, 1, chap06)
https://github.com/SkiFire13/eh-presentation-shellcode
https://raw.githubusercontent.com/SkiFire13/eh-presentation-shellcode/master/task1.a.typ
typst
#import "@preview/polylux:0.3.1": * #import "unipd.typ": * #new-section[ Task 1.a ] #slide[ TODO: Task ]
https://github.com/maxgraw/bachelor
https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/5-implementation/architecture-project.typ
typst
Im Folgenden wird auf die grundlegenden Technologien eingegangen, die zur Entwicklung der Anwendung verwendet wurden. Hierbei wird auf die verwendeten Frameworks und Bibliotheken eingegangen, die die Grundlage für die Entwicklung der Anwendung bilden. Zunächst wird Node.js als Laufzeitumgebung für JavaScript verwendet. Node.js ermöglicht die Ausführung von JavaScript-Code außerhalb des Browsers und unterstützt die Entwicklung von Webanwendungen @nodejs. Um externe und interne Pakete zu verwalten und zu installieren, wird pnpm als Package-Manager verwendet. Pnpm stellt eine Alternative zu npm dar, dem Standard-Package-Manager für Node.js, bietet jedoch Vorteile in Bezug auf Geschwindigkeit und das Verwalten von Paketen @pnpm-motivation. Für die Verwaltung und Orchestrierung von Paketen und Build-Prozessen innerhalb der Monorepo wird Turborepo verwendet. Turborepo dient hierbei nicht als tatsächliches Build-Tool, welches Pakete kompiliert, sondern ermöglicht das Erstellen von Pipelines, wodurch Entwicklungs- oder Build-Prozesse paketübergreifend ausgeführt werden können. Zum Erstellen eines Produktions-Builds wird Vite verwendet @turborepo. Vite bietet hierbei die Möglichkeit, Code zu bündeln sowie weitere Eigenschaften, die bei der Entwicklung von Webanwendungen relevant sind @vite. Bis jetzt wurden nur Technologien vorgestellt, welche die Entwicklungsumgebung betreffen. Im Folgenden wird genauer auf externe Packete eingegangen, welche für die Anwendung direkt relevant sind. Wie zuvor in der Konzeption festgelgt wird zunächst Three.js als Framework verwendet @three-js. Als zusätzliches Packet wird "three-mesh-ui" verwendet, um Interfaces innerhalb von Three.js zu erstellen und zu verwalten @three-mesh-ui. Die Anwendung wurde in einer Monorepo Architektur entwickelt. Hierbei wurden insgesamt vier Pakete erstellt, welche Teile der Anwendung darstellen. Das Paket "player" stellt die eigentliche Anwendung dar. Es bündelt verschiedene Pakte und exportiert die fertigen Web Components. Im Paket "components" finden sich 3D Objekte wie der zuvor vorgestellte Cursor sowie die Menüs der Anwendung. Das Paket "utils" beinhaltet Funktionen, welche in mehreren Paketen und Klassen verwendet werden. Durch die separate Strukturierung wird es ermöglicht, dass Funktion aus diesem Paket in anderen Paketen verwendet werden können. Abschließend gibt es das Paket "example", welches eine Beispielanwendung darstellt. Im Folgenden wird genauer auf die einzelnen Pakete eingegangen @github-project.
https://github.com/deadManAlive/ui-thesis-typst-template
https://raw.githubusercontent.com/deadManAlive/ui-thesis-typst-template/master/primer/intro.typ
typst
#import "../config.typ":cfg #let intro = [ #show par: set block(spacing: 1.5em) = Kata Pengantar #include "../intro.typ" #[ #set align(right) #grid( columns: 1, align: center, [#cfg.location, #cfg.time], [#v(2.5em) Penulis, #v(0.5em)], [#cfg.name] ) ] ]
https://github.com/simon-isler/zhaw-summaries
https://raw.githubusercontent.com/simon-isler/zhaw-summaries/main/Template/sections/1-template.typ
typst
= Heading 1 #lorem(5) == Heading 2 #lorem(50) === Heading 3 #lorem(50)
https://github.com/crd2333/Astro_typst_notebook
https://raw.githubusercontent.com/crd2333/Astro_typst_notebook/main/src/components/TypstTemplate/utils.typ
typst
// 导入本地包 #import "fonts.typ":* // 导入 preview 包 // 树、图文包裹、图标、真值表 #import "@preview/syntree:0.2.0": syntree, tree #import "@preview/treet:0.1.0": tree-list #import "@preview/wrap-it:0.1.0": wrap-content, wrap-top-bottom #import "@preview/cheq:0.1.0": checklist #import "@preview/pinit:0.1.4": * #import "@preview/indenta:0.0.3": fix-indent #import "@preview/numbly:0.1.0": numbly // 假段落 #let fake_par = style(styles => { let b = par[#box()] let t = measure(b + b, styles) b v(-t.height * 0.9) }) // 中文缩进 #let indent = h(2em) #let noindent(body) = { set par(first-line-indent: 0em) body } #let tab = indent // alias #let notab = noindent // alias // 封装 tree-list,使其无缩进、视为整体且支持根节点;选用这个字体使线段连续 #let tree-list = (root: "", breakable: false, body) => { let root = if root != "" {[#root\ ]} block(breakable: breakable)[ #noindent()[ #root #tree-list( marker-font: "MesloLGS NF", marker: [├──#h(0.3em)], // modify as you like indent: [│#h(1.5em)], last-marker: [└──#h(0.3em)], empty-indent: h(2.2em), body ) ] ] } #let date_format( date: (2023, 5, 14), lang: "en", size: "四号", font: 字体.宋体, ) = { if type(size) != length {size = 字号.at(size)} set text(font: font, size: size); if lang == "zh" { [#date.at(0)年#date.at(1)月#date.at(2)日] } else { // 美式日期格式,月日年 [#date.at(1).#date.at(2).#date.at(0)] } } // 目录 #let toc( depth: 4, toc_break: true ) = { set par(first-line-indent: 0pt) set text(font: (字体.ntl, 字体.思源黑体), size: 字号.小四) outline( indent: true, depth: depth ) if toc_break {pagebreak()} } #let toc_note( depth: 4, toc_break: true ) = { set text(font: (字体.ntl, 字体.思源黑体), size: 字号.小四) set par(first-line-indent: 0pt) pad(y: -25pt)[ #outline( indent: true, depth: depth ) ] if toc_break {pagebreak()} } #let colors = ( gray: luma(240), blue: rgb(29, 144, 208), green: rgb(102, 174, 62), red: rgb(237, 32, 84), yellow: rgb(255, 201, 23), purple: rgb(158, 84, 159), ) // 双下划线 #let double-line(body) = style(styles => { let size = measure(body, styles) stack( body, v(1pt), line(length: size.width), v(2pt), line(length: size.width), ) }) // 一条水平横线,类似与 markdown 里的 *** #let hline() = { line(length: 100%) } // 快捷文字着色,实现了红色蓝色,黑色则为粗体,两个 * 即可 #let redt(body) = text(fill: colors.red, body) // red-text #let bluet(body) = text(fill: colors.blue, body) // blue-text // 快捷 grid #let grid2(body1, body2) = grid( columns: 2, grid.cell(align: center+horizon)[#body1], grid.cell(align: center+horizon)[#body2] ) #let grid3(body1, body2, body3) = grid( columns: 3, grid.cell(align: center+horizon)[#body1], grid.cell(align: center+horizon)[#body2], grid.cell(align: center+horizon)[#body3] ) // pinit 的公式高亮指针 #let pinit-highlight-equation-from(height: 2em, pos: bottom, fill: rgb(0, 180, 255), highlight-pins, point-pin, body) = { pinit-highlight(..highlight-pins, dy: -0.6em, fill: rgb(..fill.components().slice(0, -1), 40)) pinit-point-from( fill: fill, pin-dx: -0.6em, pin-dy: if pos == bottom { 0.8em } else { -0.6em }, body-dx: 0pt, body-dy: if pos == bottom { -1.7em } else { -1.6em }, offset-dx: -0.6em, offset-dy: if pos == bottom { 0.8em + height } else { -0.6em - height }, point-pin, rect( inset: 0.5em, stroke: (bottom: 0.12em + fill), { set text(fill: fill) body } ) ) } #let clorem(len) = "你说的对,但是《原神》是由米哈游自主研发的一款全新开放世界冒险游戏。游戏发生在一个被称作「提瓦特」的幻想世界,在这里,被神选中的人将被授予「神之眼」,导引元素之力。你将扮演一位名为「旅行者」的神秘角色,在自由的旅行中邂逅性格各异、能力独特的同伴们,和他们一起击败强敌,找回失散的亲人。一个不玩原神的人,无非只有两种可能性。一种是没有能力玩原神。因为买不起高配的手机和抽不起卡等各种自身因素,他的人生都是失败的,第二种可能:有能力却不玩原神的人,在有能力而没有玩原神的想法时,那么这个人的思想境界便低到了一个令人发指的程度。一个有能力的人不付出行动来证明自己,只能证明此人行为素质修养之低下。是灰暗的,是不被真正的社会认可的。 原神怎么你了,我现在每天玩原神都能赚150原石,每个月差不多5000原石的收入,也就是现实生活中每个月5000美元的收入水平,换算过来最少也30000人民币,虽然我只有14岁,但是已经超越了中国绝大多数人(包括你)的水平,这便是原神给我的骄傲的资本。这恰好说明了原神这个IP在线下使玩家体现出来的团结和凝聚力,以及非比寻常的脑洞,这种氛围在如今已经变质的漫展上是难能可贵的,这也造就了原神和玩家间互帮互助的局面,原神负责输出优质内容,玩家自发线下宣传和构思创意脑洞整活,如此良好的游戏发展生态可以说让其他厂商艳羡不已。玩游戏不玩原神,就像四大名著不看红楼梦,说明这人文学造诣和自我修养不足,他理解不了这种内在的阳春白雪的高雅艺术.,他只能看到外表的辞藻堆砌,参不透其中深奥的精神内核,只能度过一个相对失败的人生你说得对,但是毫不夸张地说,《原神》是 miHoYo 迄今为止规模最为宏大,也是最具野心的一部作品。即便在经历了 8700 个小时的艰苦战斗后,游戏还有许多尚未发现的秘密,错过的武器与装备,以及从未使用过的法术和技能。尽管游戏中的战斗体验和我们之前在烧机系列游戏所见到的没有多大差别,但游戏中各类精心设计的敌人以及 Boss 战已然将战斗抬高到了一个全新的水平。就和几年前的《塞尔达传说》一样,《原神》也是一款能够推动同类游戏向前发展的优秀作品。适可而止矣?夫原神者,乃国产之光,米哈游者,原神之宗首也。辱我原神及米哈游者,皆腾刺舟师。哈游欲兴文繁于全世,劳费心力,使腾食不惧,腾刺舟师辱之游,不能禁哈步,汝曹腾食水军之谋必败矣!你说得对,但这是一个原神的时代,我想,我是不是我真的太贪心了?于是今天我调整了心态开始玩原神。 锄大地时我爆了蓝面具。众所周知蓝面具=3绿面具=45尘辉=3抽的副产物。即使是副产物也足显米哈游的慷慨,于是我原地跪下跪了五分钟。以此类推绿面具就是一抽的副产物。也有相当的价值,由于锄地爆率还不错,我把桌子腿全锯了方便我一直跪在地上玩游戏也能够到电脑。 走到半路发现了以前漏了的箱,开箱得了2原石,原石是付费代币,付费代币等于人民币,这是米哈游在慷慨的给我发钱,我一时难忍激动,当场给米哈游了磕个头。 开了esc菜单发现昨天邮件没领,点开就是100原石,100原石!我要开50个箱子!就是需要我磕50个头!我觉得单纯磕头已经不能表达我的感激了,于是我沐浴更衣给米哈游上了香郑重的磕了三个头。 凌晨来了,一封新的邮件。200原石!!!!!!!!!?!200!!!!!我从未想到米哈游能这么慷慨!算上前4天加起来一共达到了700原石!!米哈游非亲非故的白送了我70元,然后我又转念一想,打开了米游社手账,发现我以前的原石收益竟然有好几万。这表示米哈游,白送了我好几千人民币!然后我一时气血上涌晕了过去。 我舍友给我打的120,而我现在是躺在急救病床上,医生说我大概熬不过今晚了,但我临走之前一定要把我对米哈游的感激之情表达出来,“原神”我引以为傲,带给我无数荣耀的游戏,我终究还是要离它而去,在我的心目中这已经不在是一款游戏了,它更向是我的家人,我的父母,每天晚上我想着它入睡,早晨梦到它笑醒。我的父亲曾用一根直径20cm粗的实心钢管打我,钢管都抽断了,打的我蜷缩在地上不停的抽搐,那时能够支撑我在这个世界上活下去的信念就是原神!!!!!! 原之巅,傲世间,有我原神便有天;罪州前,双膝下,原神救我传天下;语之巅,劝世间,看我原神劝翻天,坟之巅,葬世间,待我原神挖穿天,3A尽头谁为峰,一身荣耀是原神,谁在称扣,哪个敢言你大可过来一试,纵使我需背负骂名,一只手拖住腾讯水军,我原神,一样不无敌于世间!字打到这里我哭的泣不成声,最后我想说这个世界不能没有原神!!!你怎能不爱原神!!!呜呜呜今早一玩原神,我便昏死了过去,现在才刚刚缓过来。在昏死过去的短短数小时内,我的大脑仿佛被龙卷风无数次摧毁。 在原神这一神作的面前,我就像一个一丝不挂的原始人突然来到了现代都市,二次元已如高楼大厦将我牢牢地吸引,开放世界就突然变成那喇叭轰鸣的汽车,不仅把我吓个措手不及,还让我瞬间将注意完全放在了这新的奇物上面,而还没等我稍微平复心情,纹化输出的出现就如同眼前遮天蔽日的宇宙战舰,将我的世界观无情地粉碎,使我彻底陷入了忘我的迷乱,狂泄不止。 原神,那眼花缭乱的一切都让我感到震撼,但是我那贫瘠的大脑却根本无法理清其中任何的逻辑,巨量的信息和情感泄洪一般涌入我的意识,使我既恐惧又兴奋,既悲愤又自卑,既惊讶又欢欣,这种恍若隔世的感觉恐怕只有艺术史上的巅峰之作才能够带来。 梵高的《星空》曾让我感受到苍穹之大与自我之渺,但伟大的原神,则仿佛让我一睹高维空间,它向我展示了一个永远无法理解的陌生世界,告诉我,你曾经以为很浩瀚的宇宙,其实也只是那么一丁点。加缪的《局外人》曾让我感受到世界与人类的荒诞,但伟大的原神,则向我展示了荒诞文学不可思议的新高度,它本身的存在,也许就比全世界都来得更荒谬。 而创作了它的米哈游,它的容貌,它的智慧,它的品格,在我看来,已经不是生物所能达到的范畴,甚至超越了生物所能想象到的极限,也就是“神”,的范畴,达到了人类不可见,不可知,不可思的领域。而原神,就是他洒向人间,拯救苍生的奇迹。 人生的终极意义,宇宙的起源和终点,哲学与科学在折磨着人类的心智,只有玩了原神,人才能从这种无聊的烦恼中解脱,获得真正的平静。如果有人想用“人类史上最伟大的作品”来称赞这部作品,那我只能深感遗憾,因为这个人对它的理解不到万分之一,所以才会作出这样肤浅的判断,妄图以语言来描述它的伟大。而要如果是真正被它恩泽的人,应该都会不约而同地这样赞颂这奇迹的化身:“数一数二的好游戏”无知时诋毁原神,懂事时理解原神,成熟时要成为原友! 越了解原神就会把它当成在黑夜一望无际的大海上给迷途的船只指引的灯塔,在烈日炎炎的夏天吹来的一股风,在寒风刺骨的冬天里的燃起的篝火!这便是原神给我的骄傲的资本。这恰好说明了原神这个IP在线下使玩家体现出来的团结和凝聚力,以及非比寻常的脑洞,这种氛围在如今已经变质的漫展上是难能可贵的,这也造就了原神和玩家间互帮互助的局面,原神负责输出优质内容,玩家自发线下宣传和构思创意脑洞整活,如此良好的游戏发展生态可以说让其他厂商艳羡不已。反观腾讯的英雄联盟和王者荣耀,漫展也有许多人物,但是都难成气候,各自为营,更没有COS成水晶和精粹的脑洞,无论是游戏本身,还是玩家之间看一眼就知道原来你也玩原神的默契而非排位对喷,原神的成功和社区氛围都是让腾讯游戏难以望其项背的。一个不玩原神的人,有两种可能性。一种是没有能力玩原神。因为买不起高配的手机和抽不起卡等各种自身因素,他的人生都是失败的 ,第二种可能:有能力却不玩原神的人,在有能力而没有玩原神的想法时,那么这个人的思想境界便低到了一个令人发指的程度。是不被真正的上流社会认可的。你说得对,但是差不多得了,屁大点事都要拐上原神,原神一没招你惹你,二没干伤天害理的事情,到底怎么你了让你一直无脑抹黑,米哈游每天费尽心思的文化输出弘扬中国文化,你这种喷子只会在网上敲键盘诋毁良心公司,中国游戏的未来就是被你这种人毁掉的。 叫我们原批的小心点 老子在大街上亲手给打过两个 我在公共座椅上无聊玩原神,有两个B就从我旁边过,看见我玩原神就悄悄说了一句:又是一个原批,我就直接上去一拳呼脸上,我根本不给他解释的机会,我也不问他为什么说我是原批,我就打,我就看他不爽,他惹我了,我就不给他解释的机会,直接照着脸和脑门就打直接给那B呼出鼻血,脸上青一块,紫一块的我没撕她嘴巴都算好了你们这还不算最狠的,我记得我以前小时候春节去老家里,有一颗核弹,我以为是鞭炮,和大地红一起点了,当时噼里啪啦得,然后突然一朵蘑菇云平地而起,当时我就只记得两眼一黑,昏过去了,整个村子没了,幸好我是体育生,身体素质不错,住了几天院就没事了,几个月下来腿脚才利落,现在已经没事了,但是那种钻心的疼还是让我一生难忘, 令人感叹今早一玩原神,我便昏死了过去,现在才刚刚缓过来。在昏死过去的短短数小时内,我的大脑仿佛被龙卷风无数次摧毁。 在原神这一神作的面前,我就像一个一丝不挂的原始人突然来到了现代都市,二次元已如高楼大厦将我牢牢地吸引,开放世界就突然变成那喇叭轰鸣的汽车,不仅把我吓个措手不及,还让我瞬间将注意完全放在了这新的奇物上面,而还没等我稍微平复心情,纹化输出的出现就如同眼前遮天蔽日的宇宙战舰,将我的世界观无情地粉碎,使我彻底陷入了忘我的迷乱,狂泄不止。 原神,那眼花缭乱的一切都让我感到震撼,但是我那贫瘠的大脑却根本无法理清其中任何的逻辑,巨量的信息和情感泄洪一般涌入我的意识,使我既恐惧又兴奋,既悲愤又自卑,既惊讶又欢欣,这种恍若隔世的感觉恐怕只有艺术史上的巅峰之作才能够带来。 梵高的《星空》曾让我感受到苍穹之大与自我之渺,但伟大的原神,则仿佛让我一睹高维空间,它向我展示了一个永远无法理解的陌生世界,告诉我,你曾经以为很浩瀚的宇宙,其实也只是那么一丁点。加缪的《局外人》曾让我感受到世界与人类的荒诞,但伟大的原神,则向我展示了荒诞文学不可思议的新高度,它本身的存在,也许就比全世界都来得更荒谬。 而创作了它的米哈游,它的容貌,它的智慧,它的品格,在我看来,已经不是生物所能达到的范畴,甚至超越了生物所能想象到的极限,也就是“神”,的范畴,达到了人类不可见,不可知,不可思的领域。而原神,就是他洒向人间,拯救苍生的奇迹。 人生的终极意义,宇宙的起源和终点,哲学与科学在折磨着人类的心智,只有玩了原神,人才能从这种无聊的烦恼中解脱,获得真正的平静。如果有人想用“人类史上最伟大的作品”来称赞这部作品,那我只能深感遗憾,因为这个人对它的理解不到万分之一,所以才会作出这样肤浅的判断,妄图以语言来描述它的伟大。而要如果是真正被它恩泽的人,应该都会不约而同地这样赞颂这奇迹的化身:“数一数二的好游戏”无知时诋毁原神,懂事时理解原神,成熟时要成为原友! 越了解原神就会把它当成在黑夜一望无际的大海上给迷途的船只指引的灯塔,在烈日炎炎的夏天吹来的一股风,在寒风刺骨的冬天里的燃起的篝火!你的素养很差,我现在每天玩原神都能赚150原石,每个月差不多5000原石的收入,也就是现实生活中每个月5000美元的收入水平,换算过来最少也30000人民币,虽然我只有14岁,但是已经超越了中国绝大多数人(包括你)的水平,这便是原神给我的骄傲的资本。这恰好说明了原神这个IP在线下使玩家体现出来的团结和凝聚力,以及非比寻常的脑洞,这种氛围在如今已经变质的漫展上是难能可贵的,这也造就了原神和玩家间互帮互助的局面,原神负责输出优质内容,玩家自发线下宣传和构思创意脑洞整活,如此良好的游戏发展生态可以说让其他厂商艳羡不已。反观腾讯的英雄联盟和王者荣耀,漫展也有许多人物,但是都难成气候,各自为营,更没有COS成水晶和精粹的脑洞,无论是游戏本身,还是玩家之间看一眼就知道原来你也玩原神的默契而非排位对喷,原神的成功和社区氛围都是让腾讯游戏难以望其项背的。一个不玩原神的人,有两种可能性。一种是没有能力玩原神。因为买不起高配的手机和抽不起卡等各种自身因素,他的人生都是失败的,第二种可能:有能力却不玩原神的人,在有能力而没有玩原神的想法时,那么这个人的思想境界便低到了一个令人发指的程度。一个有能力的人不付出行动来证明自己,只能证明此人行为素质修养之低下。是灰暗的,是不被真正的上流社会认可的。原神真的特别好玩,不玩的话就是不爱国,因为原神是国产之光,原神可惜就在于它是国产游戏,如果它是一款国外游戏的话,那一定会比现在还要火,如果你要是喷原神的话那你一定是tx请的水军我很难想象一个精神状态正常的人会喷".clusters().slice(0, len).join("")
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/decide-auton-movement/entry.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #show: create-body-entry.with( title: "Decide: Autonomous Movement", type: "decide", date: datetime(year: 2023, month: 9, day: 11), author: "<NAME>", witness: "<NAME>", ) We rated all of our choices by the following criteria: - Simplicity on a scale of 0 to 3. This is how simple the algorithm is to implement. - Accuracy on a scale of 0 to 3. This is how closely the algorithm can follow the intended path. - Robustness on a scale of 0 to 3. This is the amount of use cases that the algorithm covers. #decision-matrix( properties: ((name: "Simplicity"), (name: "Accuracy"), (name: "Robustness")), ("Bang Bang", 3, 1, 1), ("PID", 2, 3, 3), ("Pure Pursuit", 1, 3, 2.5), ) #admonition( type: "decision", )[ We decided to use the PID controller for most of our movements, however we might still use Pure Pursuit for a few of them. This is mainly because they cover different use cases. Pure Pursuit would primarily be used for long movements that span the field, with a long complex path. PID is much better for shorter movements. Its likely that we'll only ever need PID, but we'll keep Pure Pursuit in mind. ] #heading([Implementation], level: 1) LemLib provides a movement implementation using PID which already integrates with the Odometry it provides, so we'll use that. #heading([PID], level: 2) The most important part of LemLib's moveToPoint algorithm is it's PID implementation. As mentioned before, PID is a closed loop controller, which means that it corrects for external forces. The output of the loop is calculated every 20 ms with the following equation: Assuming the following variables: - $P$ is the proportional term of the loop - $I$ is the integral term of the loop - $D$ is the derivative term of the loop - $K_p$ is the proportional constant - $K_i$ is the integral constant - $K_d$ is the derivative constant #admonition(type: "equation")[ $ P = K_p * e(t) $ $ I = K_i * attach(#sym.integral, t: t, b: 0)e(tau)d tau $ $ D = K_d * (d e(t)) / (d t) $ ] Each term is added together to form the output. While the raw output of a controller is not suitable for moving a motor, the output can be tuned with the three constants. We will need to find the correct constants for our robot through trial and error. LemLib calculates PID output with the following code: ```cpp float lemlib::FAPID::update(float target, float position, bool log) { // calculate output float error = target - position; // Calculate P term float deltaError = error - prevError; // Calculate D term float output = kF * target + kP * error + kI * totalError + kD * deltaError; if (kA != 0) output = lemlib::slew(output, prevOutput, kA); // Limit rate of change, if applicable prevOutput = output; prevError = error; totalError += error; // Calculate I term return output; } ``` The PID loop cannot run forever and needs an exit condition. We could naively assume that if error (distance from the target) is zero, then we exit, but this fails to account for overshooting. Instead, we say that the PID loop will exit after being within a certain acceptable error range for a certain amount of time. LemLib actually has two of these ranges, largeError and smallError respectively. LargeError has a larger time required and a larger acceptable range, while smallError has a smaller timeout and smaller acceptable range. There's also a global timeout which defines the maximum amount of time the robot is allowed to spend settling. The code for this is found below: ```cpp bool lemlib::FAPID::settled() { if (startTime == 0) { // if maxTime has not been set startTime = pros::c::millis(); return false; } else { // check if the FAPID has settled if (pros::c::millis() - startTime > maxTime) return true; // maxTime has been exceeded if (std::fabs(prevError) < largeError) { // largeError within range if (!largeTimeCounter) largeTimeCounter = pros::c::millis(); // largeTimeCounter has not been set else if (pros::c::millis() - largeTimeCounter > largeTime) return true; // largeTime has been exceeded } if (std::fabs(prevError) < smallError) { // smallError within range if (!smallTimeCounter) smallTimeCounter = pros::c::millis(); // smallTimeCounter has not been set else if (pros::c::millis() - smallTimeCounter > smallTime) return true; // smallTime has been exceeded } // if none of the exit conditions have been met return false; } } ``` LemLib uses two PID controllers to move the robot, one for linear movement, and one for angular movement. The output of the two is added together and then passed into the motor's `move()` method. ```cpp float angularPower = -angularPID.update(radToDeg(angularError), 0, log); float linearPower = linearPID.update(linearError, 0, log); float leftPower = linearPower + angularPower; float rightPower = linearPower - angularPower; // move the motors drivetrain.leftMotors->move(leftPower); drivetrain.rightMotors->move(rightPower); ``` `AngularPower` and `LinearPower` are simply the output of the two PID loops. LemLib calculates the error with some simple trigonometry. ```cpp float lemlib::angleError(float angle1, float angle2, bool radians) { float max = radians ? 2 * M_PI : 360; float half = radians ? M_PI : 180; angle1 = fmod(angle1, max); angle2 = fmod(angle2, max); float error = angle1 - angle2; if (error > half) error -= max; else if (error < -half) error += max; return error; } float angularError = angleError(pose.angle(carrot), pose.theta, true); // angular error float linearError = pose.distance(carrot) * cos(angularError); // linear error ``` `angularError`'s calculation is simple enough, but `linearError` is worth looking into. Instead of taking the raw distance, it multiplies by $cos("angularError")$ to find the distance that the robot can actually achieve while moving in a straight line. #image("./linear-error.svg", height: 25%) This will reduce linear error if the robot is not facing the target point, prioritizing angular movement. LemLib uses a boomerang controller in order to be able to move the robot to a specified rotation. It does this by following an intermediary carrot point. Assuming the following variables: - $d_"lead"$ is a constant set by us that dictates how far away the carrot point - $x_"current"$ is the x value of the robot's current position. - $y_"current"$ is the y value of the robot's current position. - $x_"carrot"$ is the x value of the carrot point's position. - $y_"carrot"$ is the y value of the carrot point's position. - $x_"target"$ is the x value that the robot is moving to. - $y_"target"$ is the y value that the robot is moving to. - $theta_"target"$ is the rotation that the robot is moving to. - $d_"lead"$ is a constant set by the user that controls how far away the carrot point is from the target point. #admonition(type: "equation")[ $ h = sqrt(x_"current" - x_"target" + y_"current" - y_"target") $ $ x_"carrot" = x_"target" - h sin(theta_"target") * d_"lead" $ $ y_"carrot" = y_"target" - h cos(theta_"target") * d_"lead" $ ] #v(100pt) As the robot gets closer to the carrot point, the carrot point gets closer to the target point, moving the robot along the projected path. Eventually the points will overlap, and the movement will be complete. #figure( image("./boomerang-controller.svg"), caption: "Projected boomerang path", ) Overall this has a lot of advantages over a simple move to point. It means that the system only has to settle once, and it also means that the system knows what angle it should end at, giving it more certainty at the end of movements.
https://github.com/JarKz/math_analysis_with_typst
https://raw.githubusercontent.com/JarKz/math_analysis_with_typst/main/README.md
markdown
MIT License
# Математический анализ Все вопросы, собранные со всех сборников по предмету "Математический анализ для студентов-заочников", предназначенные для подготовки к экзамену. ## Использование Вам необходимо воспользоваться либо онлайн сервисом [Typst](https://typst.app), либо закачать typst (Rust приложение) на свой компьютер, после чего с помощью командной строки скомпилировать в PDF-файл: ```bash tyspt compile main.typ ``` ## Помощь/Contributions Сделайте fork к этому репозиторию, после чего отправьте pull-request.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fh-joanneum-iit-thesis/1.2.0/template/chapters/global.typ
typst
Apache License 2.0
// // About the fh-joanneum-iit-thesis package used: // // Note 1: // following is an (indirect) import of the 'lib.typ' file // The file lib.typ (and others) will be downloaded and cached // by your system. The location of the @preview cache directory // is explained in // https://github.com/typst/packages?tab=readme-ov-file#downloads // e.g. %APPDATA% on Windows on Windows // ~/.local/share or $XDG_DATA_HOME on Linux // ~/Library/Application Support on macOS // // Note 2: // If you like to modify "lib.typ", copy the file from the cache directory // or get it from the 'official' Typst Universe package git repo // (i.e. from proper 'version number subdir' of // https://github.com/typst/packages/tree/main/packages/preview/fh-joanneum-iit-thesis) // Copy the lib.typ to a (sub)folder of this project and // set the path accordingly. #import "@preview/fh-joanneum-iit-thesis:1.2.0": * // Anytime you might simply override custom macros, such as: // #let quote(message, by) = { // block( // radius: 3em, width: 75%, // inset: (x: 2em, y: 0.5em), // [ // #message, // #par( // first-line-indent: 15em, // text(font: "Inria Serif", size: 9pt, style: "italic", [ // #by // ]) // ) // ] // ) // } // // Other packages used: // // See https://github.com/typst/packages/tree/main/packages/preview/glossarium #import "@preview/glossarium:0.4.1": make-glossary, print-glossary, gls, glspl
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/布局/fraction/fraction.typ
typst
= fraction 定义布局中剩余空间的分布方式。 每个分数大小的元素根据其分数与所有分数之和的比率获得空间。 有关详细信息,另请参阅 h 和 v 函数以及 grid 函数。 #image("屏幕截图 2024-04-16 151921.png")
https://github.com/Tiggax/famnit_typst_template
https://raw.githubusercontent.com/Tiggax/famnit_typst_template/main/examples/attachments.typ
typst
MIT No Attribution
#let a = [ #lorem(800) ]
https://github.com/An-314/Notes-of-DSA
https://raw.githubusercontent.com/An-314/Notes-of-DSA/main/main.typ
typst
#import "template.typ": * #show: project.with( title: "数据结构与算法 复习笔记", authors: ( "Anzreww", ), time: "癸卯隆冬于清华园", ) #pagebreak(weak: true) #include "introduction.typ" #pagebreak(weak: true) #include "vector.typ" #pagebreak(weak: true) #include "list.typ" #pagebreak(weak: true) #include "stack&queue.typ" #pagebreak(weak: true) #include "binary_tree.typ" #pagebreak(weak: true) #include "binary_search_tree.typ" #pagebreak(weak: true) #include "BST.typ" #pagebreak(weak: true) #include "advanced_BST.typ" #pagebreak(weak: true) #include "hash.typ" #pagebreak(weak: true) #include "priority_queue.typ" #pagebreak(weak: true) #include "string.typ" #pagebreak(weak: true) #include "sort.typ"
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fh-joanneum-iit-thesis/1.1.0/template/chapters/6-implementation.typ
typst
Apache License 2.0
#import "global.typ": * = Implementation <implementation> #lorem(35) #todo([ Describe what is relevant and special about your working prototype. State how single features help to solve problem(s) at hand. You might implement only the most relevant features. Features you select from your prioritised feature list assembled in Chapter 4. Focus novel, difficult, or innovative aspects of your prototype. Add visuals such as architectures, diagrams, flows, tables, screenshots to illustrate your work. Select interesting code snippets, e.g. of somewhat complicated algorithms, to present them as source code listings. ]) #todo([ *For example*, you might explain your backand and your frontend development in subsections as shown here: == Backend <backend> We implemented a minimal #emph[script] in Python to manage a secure `Message`s in object oriented ways. The way to include source code in your document is discussed and shown in #link("https://typst.app/docs/reference/text/raw/"). See @lst:Message and @lst:SecureMessage for a minimal `SecureMessage` class. #figure( align(left, // we use a custom template (style), defined in fh.typ // the files are expected in subfolder "source" // optionally, specify firstline/lastline fhjcode(code: read("/code-snippets/msg.py"), lastline:5) ), // we use a custom flex-caption), to allow long and short captions // (the short one appears in the outline List of Figures). // This is defined in `lib.typ`. caption: flex-caption( [Defining a base class in Python. Here, the base class is named _Message_.], [Base class _Message_.] ), ) <lst:Message> #figure( align(left, fhjcode(code:read("/code-snippets/msg.py"), firstline:7, lastline:17) ), caption: flex-caption( [For inheritance we might define a specialised class based on another class. Here, the specialised class _SecureMessage_ is based on the class _Message_.], [Specialised class _SecureMessage_.] ), ) <lst:SecureMessage> == Frontend <frontend> ... ])
https://github.com/kokkonisd/typst-phd-template
https://raw.githubusercontent.com/kokkonisd/typst-phd-template/main/src/colors.typ
typst
The Unlicense
#let MAIN_COLOR = rgb(138, 15, 29) #let SECONDARY_COLOR = luma(240) #let INTENSE_COLOR = rgb(255, 157, 28) #let SYMPATHETIC_COLOR_1 = rgb(36, 181, 118) #let CODE_SNIPPET_COLOR = luma(210) #let WARN_PRIMARY_COLOR = INTENSE_COLOR #let WARN_SECONDARY_COLOR = INTENSE_COLOR.darken(20%) #let NOTE_PRIMARY_COLOR = SYMPATHETIC_COLOR_1 #let NOTE_SECONDARY_COLOR = SYMPATHETIC_COLOR_1.darken(20%)
https://github.com/freundTech/typst-typearea
https://raw.githubusercontent.com/freundTech/typst-typearea/main/tests/basic.query.typ
typst
MIT License
#import "../typearea.typ": * #show: typearea.with( width: 100pt, height: 100pt, div: 10, ) #context [ #layout(size => [ #metadata(here().position() + size)<result> ]) ] #metadata(( page: 1, x: 10pt, y: 10pt, width: 70pt, height: 70pt, ))<expected>
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/01-history/decasteljau.typ
typst
Other
#import "/template/theme.typ": theme #import "/lib/draw.typ": * #let start = (0, 0) #let end = (1000, 600) #let graph = with-unit((ux, uy) => { // mesh(start, end, (100, 100)) let p1 = (22, 166) let p2 = (148, 576) let p3 = (977, 274) let p4 = (742, 16) let main-point = point.with(radius: 18, thickness: 4 * ux) main-point(p1) main-point(p4) main-point(p2, fill: false) main-point(p3, fill: false) let line-stroke = stroke( paint: theme.main, thickness: 4 * ux, cap: "round", ) bezier(p1, p2, p3, p4, stroke: line-stroke) segment(p1, p2, stroke: line-stroke) segment(p4, p3, stroke: line-stroke) let f = t => { let ((p1x, p1y), (p2x, p2y), (p3x, p3y), (p4x, p4y)) = (p1, p2, p3, p4) let qt = 1 - t let a1 = qt * qt * qt let a2 = 3 * qt * qt * t let a3 = 3 * qt * t * t let a4 = t * t * t ( a1 * p1x + a2 * p2x + a3 * p3x + a4 * p4x, a1 * p1y + a2 * p2y + a3 * p3y + a4 * p4y, ) } let (inp1, inp2, inp3) = range(1, 4).map(a => f(a / 4)) let points = (p1, inp1, inp2, inp3, p4) for (i, (from, to)) in points.zip(points.slice(1)).enumerate() { if i != 0 { point(from, radius: 18, thickness: 4 * ux, dash: "dashed", fill: false) } segment(from, to,stroke: stroke( paint: theme.main, thickness: 3 * ux, dash: "dotted", )) } }) #canvas(end, start: start, width: 100%, graph)
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/04-parametric-and-curves/!sec.typ
typst
#import "../../config.typ" #import "../../utils/core.typ": * = Интегралы с параметром и криволинейные интегралы #include "01-parametric-integral.typ" #include "02-improper-integral.typ" #include "03-euler-integrals.typ" #include "04-hypergeometric-function.typ" #include "05-line-integrals.typ" #include "06-closed-and-exact-diff-forms.typ"
https://github.com/giZoes/justsit-thesis-typst-template
https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/pages/bachelor-abstract-en.typ
typst
MIT License
#import "../utils/custom-cuti.typ": fakebold #import "../utils/style.typ": 字号, 字体 #import "../utils/indent.typ": fake-par #import "../utils/invisible-heading.typ": invisible-heading // 本科生英文摘要页 #let bachelor-abstract-en( // documentclass 传入的参数 anonymous: false, twoside: false, fonts: (:), info: (:), // 其他参数 keywords: (), outline-title: "ABSTRACT", outlined: false, anonymous-info-keys: ("author-en", "supervisor-en", "supervisor-ii-en"), leading: 1.28em, spacing: 1.38em, body, ) = { // 1. 默认参数 fonts = 字体 + fonts info = ( title-en: "NJU Thesis Template for Typst", author-en: "<NAME>", department-en: "XX Department", major-en: "XX Major", supervisor-en: "<NAME>", ) + info // 2. 对参数进行处理 // 2.1 如果是字符串,则使用换行符将标题分隔为列表 if type(info.title-en) == str { info.title-en = info.title-en.split("\n") } // 3. 内置辅助函数 let info-value(key, body) = { if (not anonymous or (key not in anonymous-info-keys)) { body } } // 4. 正式渲染 [ #pagebreak(weak: true, to: if twoside { "odd" }) #set page( header: { grid( columns: (1fr), align: center, [#text(font: fonts.宋体, size: 字号.五号, baseline: -4pt)[江苏科技大学苏州理工学院毕业设计(论文)]], [#line(length: 100%, stroke: 0.5pt)] ) } ) #set text(font: fonts.宋体, size: 字号.小四) #set par(leading: leading, justify: true) #show par: set block(spacing: spacing) // // 标记一个不可见的标题用于目录生成 // #invisible-heading(level: 1, outlined: outlined, outline-title) #align(center)[ #set text(size: 字号.三号, weight: "bold") = Abstract #v(1em) ] #[ #set par(first-line-indent: 2em) #fake-par #body ] #v(1em) #text(weight: "bold")[Keywords:] #(("",)+ keywords.intersperse("; ")).sum() ] }
https://github.com/bennyhandball/PA1_LoB_Finance
https://raw.githubusercontent.com/bennyhandball/PA1_LoB_Finance/main/PA/supercharged-dhbw/2.1.0/confidentiality-statement.typ
typst
#let confidentiality-statement( authors, title, confidentiality-statement-content, university, university-location, date, language, many-authors, date-format ) = { v(2em) text(size: 20pt, weight: "bold", if (language == "de") { "Sperrvermerk" } else { "Confidentiality Statement" }) v(1em) if (confidentiality-statement-content != none) { confidentiality-statement-content } else { text(if (language == "de") { "Die vorliegende Arbeit mit dem Titel" } else { "The Thesis on hand" }) v(1em) align(center, text(weight: "bold", title) ) v(1em) let insitution let companies if (language == "de") { if (authors.map(author => author.company.name).dedup().len() == 1) { insitution = "Ausbildungsstätte" } else { insitution = "Ausbildungsstätten" } companies = authors.map(author => author.company.name).dedup().join(", ", last: " und ") } else { if (authors.map(author => author.company.name).dedup().len() == 1) { insitution = "insitution" } else { insitution = "insitutions" } companies = authors.map(author => author.company.name).dedup().join(", ", last: " and ") } par(justify: true, [#if (language == "de") { [enthält unternehmensinterne bzw. vertrauliche Informationen der #companies, ist deshalb mit einem Sperrvermerk versehen und wird ausschließlich zu Prüfungszwecken am Studiengang #authors.map(author => author.course-of-studies).dedup().join(" | ") der #university #university-location vorgelegt. Der Inhalt dieser Arbeit darf weder als Ganzes noch in Auszügen Personen außerhalb des Prüfungsprozesses und des Evaluationsverfahrens zugänglich gemacht werden, sofern keine anders lautende Genehmigung der #insitution (#companies) vorliegt.] } else { [contains internal respective confidential data of #companies. It is intended solely for inspection by the assigned examiner, the head of the #authors.map(author => author.course-of-studies).dedup().join(" | ") department and, if necessary, the Audit Committee at the #university #university-location. The content of this thesis may not be made available, either in its entirety or in excerpts, to persons outside of the examination process and the evaluation process, unless otherwise authorized by the training #insitution (#companies).] }]) } let end-date = if (type(date) == datetime) { date } else { date.at(1) } v(2em) text([#if (language == "de") { [#authors.map(author => author.company.city).dedup().join(", ", last: " und "), #end-date.display(date-format)] } else { [#authors.map(author => author.company.city).dedup().join(", ", last: " and "), #end-date.display(date-format)] }]) v(0.5em) if (many-authors) { grid( columns: (1fr, 1fr), gutter: 20pt, ..authors.map(author => { v(3.5em) line(length: 80%) author.name }) ) } else { for author in authors { v(4em) line(length: 40%) author.name } } }
https://github.com/pku-typst/PKU-typst-template
https://raw.githubusercontent.com/pku-typst/PKU-typst-template/main/README.md
markdown
MIT License
# PKU Typst 模板库 ## 使用指南 安装 [just](https://github.com/casey/just) 并克隆本项目到本地, 运行以下命令即可安装 ```bash just install ``` 嫌麻烦也可以直接去 [scripts](./scripts/) 文件夹里运行 `install.sh` 脚本 > Q: 如何更新? > A: 重新拉取 (`git pull`) 仓库源代码并重新执行 `just install` 即可
https://github.com/YDX-2147483647/herglotz
https://raw.githubusercontent.com/YDX-2147483647/herglotz/main/cantor.typ
typst
#import "template.typ": project, remark, pseudonyms, example, table-header #show: project.with(title: "既连续又本质间断", date: "2023年10月23–24日,11月7、13–14、16–20日,12月16日,2024年1月3日") #quote( block: true, attribution: [_Profiles of the Future_ (1962) ch. 2, <NAME>], )[ The only way of discovering the limits of the possible is to venture a little way past them into the impossible. ] $RR -> RR$ 函数中,存在完全连续的,存在某一点不连续的,存在处处不连续的,存在几乎处处连续又几乎处处不连续的;存在完全连续但好像又会跳变的;存在连续但又无限振荡的;…… 连续性的边界在哪里?这显然取决于你如何定义“连续”,并且这些定义可按“$=>$”排成一串或几串。 #figure( image("fig/Functions_between_metric_spaces.svg", width: 40%), caption: [ 各种各样的“连续” | #link("https://commons.wikimedia.org/wiki/File:Functions_between_metric_spaces.svg")[Wikimedia Commons `Functions between metric spaces.svg`] ] ) 不过这里只谈最基础的那种连续,我们要构造这样一个例子: #[ #show list: set align(center) #show par: set align(start) - 几乎处处连续,且几乎处处不连续; - 所有不连续点都是本质间断点。 ] #remark[本质间断][ 所谓“本质间断”,是指 $lim_(x -> c) f(x)$ 根本不存在,而非仅仅与 $f(c)$ 不同(如可去奇点、跳变)。 ] 之所以这么想,是因为若干著名反例恰好都不是本质间断,而逻辑似乎允许这样的函数存在。 = 一些著名反例 - *Dirichlet函数* $ x |-> cases( 1 &space.quad x in QQ, 0 &space.quad x in.not QQ, ) $ 在整个 $RR$ 上处处不连续。#footnote[ 若把定义域限制到 $QQ$,仍然可以定义极限,这时 Dirichlet 函数恒取 $1$,从而连续。——要区分“在□□内连续”和“在□□上处处连续”,我们后面都指后者。 ] - *Thomae爆米花函数*(又名Riemann函数、Stars over Babylon) $ x |-> cases( 1/q &space.quad x = p/q in QQ "其中" p\,q "互质", 0 &space.quad x in.not QQ, ) $ 在 $QQ$ 上处处不连续,在 $RR without QQ$ 上处处连续但不可导。#footnote[ Dirichlet 函数的两条规定可以交换,但Thomae函数不能。后面将证明不存在 $QQ$ 上处处连续、$RR without QQ$ 上处处不连续的函数。 ] - *Cantor三分阶梯函数*(又名Lebesgue函数、魔鬼的阶梯) $c: [0,1] -> [0,1]$ 可用如下方法构造。 1. 将 $x in [0,1]$ 表示为三进制,若包含 $1$,则只保留到首个 $1$(将后面所有位改为 $0$)。 2. 将剩下的所有 $2$ 改为 $1$。 3. 这时结果只含 $0,1$,将它按二进制解释即为 $c(x)$。 它在 $[0,1]$ 上处处连续但并不绝对连续。#footnote[ 并且几乎处处有零导数。不过这次不谈导数,上面也不再列Weierstrass函数等。 ] #figure( image("fig/cantor.png", width: 50%), caption: [Cantor函数] ) // Mathematica: // Plot[CantorStaircase[x], {x, 0, 1}, AspectRatio -> 1, // GridLines -> {Nest[Join[#/3, (# + 2)/3] &, {0, 1}, 4], // Range[0, 1, 2^-4]}, // Ticks -> {Nest[Join[#/3, (# + 2)/3] &, {0, 1}, 2], Range[0, 1, 2^-2]} // ] #remark[Dirichlet函数作为连续函数序列的极限][ Dirichlet函数也可表示为 $ x |-> lim_(k -> +oo) lim_(j -> +oo) cos^(2j) (k! pi x). $ #figure( image("fig/baire-1.png", width: 40%), caption: $cos^(2j) (k! pi x)$ ) // Mathematica: // With[{js = {1, 2, 3, 5, 10, 20, 30}}, // Plot[Cos[\[Pi] x]^(2 js) // Evaluate, {x, 0, 4}, // GridLines -> Automatic, Ticks -> None, // PlotLegends -> Map[HoldForm[j = #] &, js]] // ] 1. $x |-> cos^(2j) (k! pi x)$ 是连续函数。 2. $x |-> lim_j cos^(2j) (k! pi x)$ 在 $abs(cos(k! pi x)) = 1$ 时取 $1$,其余取 $0$。注意取 $1$ 的点是压缩过的整点: $ abs(cos(k! pi x)) = 1 space<==>space k! pi x in pi ZZ space<==>space x in 1/k! ZZ. $ 于是取极限后函数不连续了。 3. $x |-> lim_k lim_j cos^(2j) (k! pi x)$ 仍然只取 $0,1$,并且取 $1$ 的条件是 $ exists k_0 forall k >= k_0, space x in 1/k! ZZ. $ 由于 $1/k! = 1/(k_0 !) times 1/((k_0+1) (k_0+2) dots.c (k-1) k)$,所以 $1/(k_0 !) ZZ subset 1/k! ZZ$,故取 $1$ 的条件就是 $exists k_0, x in 1/(k_0 !) ZZ$,即 $x in QQ$。 像上面这样考虑连续函数序列的累次极限,可以给函数分层级: 1. Baire class 0 是所有连续函数。 2. Baire class $alpha$ 是能用 Baire class $(alpha-1)$ 中函数序列的逐点极限表示的函数。可以论证 Baire class $alpha$ 总比 Baire class $(alpha-1)$ 大。 3. 除此以外,还存在不属于任意 Baire class 的函数。 根据 $x |-> lim_k lim_j cos^(2j) (k! pi x)$,我们说明了Dirichlet函数至少属于 Baire class 2;它不连续,从而不属于更小的 Baire class 0;那它是否属于介于其间的 Baire class 1 呢?并不属于,因为Dirichlet函数处处不连续,超出了 Baire class 1 所能容忍的不连续性。具体的论证将在后文提到。 ] #remark[Thomae函数与最大公约数][ 考虑最大公约数函数 $gcd: NN^2 -> NN$ 的三维图象,把定义域、值域缩放到 $([0,1] sect QQ)^2 -> [0,1] sect QQ$,然后取个坐标面(因为自相似,取哪个都一样),截出来的二维图象就是Thomae函数在 $[0,1]$ 上的图象。 具体来说,如果规定 $(x,y) in.not NN^2$ 时,$gcd(x,y) = 0$,那么 $ x |-> limsup_(N -> +oo) gcd(N x, N) / N $ 就是Thomae函数。 #figure( image("fig/gcd.png", width: 80%), caption: [ $6,30,100$ 以内数的 $gcd$ 第 $y$ 行第 $x$ 列的颜色表示 $gcd(x,y)$。如图例所示,越深越大(线性对应),但直接比较不同图的颜色无意义。 (2020年8月11日有动图) ] ) // Mathematica: // Table[Table[GCD[x, y], {x, n}, {y, n}] // // MatrixPlot[#, PlotLegends -> Placed[Automatic, Bottom], // ImageSize -> Small] &, {n, {6, 30, 100}}] // Row ] #remark[Thomae函数与Euclid果园][ 在 $RR^2$ 平面内,在 $ZZ^2$ 种上高为 $1$ 的树。从原点看去,有些树直接可见(如 $(3,4)$),有些树会被挡住(如 $(6,8)$ 被 $(3,4)$ 挡住)。这称作Euclid果园。 #figure( image("fig/Euclid_orchard_trimetric.svg", width: 60%), caption: [ Euclid果园 | #link("https://en.wikipedia.org/wiki/File:Euclid_orchard_trimetric.svg")[Wikimedia Commons `Euclid orchard trimetric.svg`] 站在原点,只能看到蓝色的树,看不到橙色的树。 ] ) 在 $RR^3$ 内,将这些树关于原点投影到平面 $x+ y = 1$ 上(即 $(x,y,z) |-> ((x,y,z))/(x+y)$),也能得到Thomae函数的图象。 #figure( image("fig/Euclid%27s_Orchard_%28perspective%29.svg", width: 60%), caption: [ Euclid果园的投影#footnote[ 此图并非投影到 $x+y=1$,而是投影到 $x^2+y^2=1$,因此与Thomae函数相比略有变形。 ] | #link("https://en.wikipedia.org/wiki/File:Euclid%27s_Orchard_(perspective).svg")[Wikimedia Commons `Euclid's Orchard (perspective).svg`] 正中央的树位于 $y = x$,红色的树位于 $y = x plus.minus 2$。 ] ) ] #remark[Cantor函数的构造方法][ 上面给出的构造方法中,最关键的是“三进制 → 二进制”,其它手续基本是细枝末节。 - 将所有 $2$ 改为 $1$ 只是乘了个系数 $1/2$。 - 如果 $x$ 的三进制表示包含 $1$,则可暂时不定义 $c(x)$;先定义那些不含 $1$ 的,最后再按单调性补充。 具体来说,设 $x$ 的首个 $1$ 是第 $n$ 位,即 $ x = underbrace((2triangle.t)/3^1 + (2 space square)/3^2 + dots.c + (2circle)/3^(n-1), "前"n-1"位只含" 0\,2) + underbrace(1/3^n, "第"n"位是"1) + underbrace(diamond/3^(n+1) + dots.c, "后面怎样不再重要"). $ 记 $x$ 保留到第 $n-1$ 位是 $overline(x)$,那么交错使用有限小数的两种表示方法, $ c(overline(x) + 1/3^n) &= c(overline(x) + 2/3^(n+1) + 2/3^(n+2) + dots.c) \ &= (triangle.t/2^1 + dots.c + circle/2^(n-1)) + (1/2^(n+1) + 1/2^(n+2) + dots.c) \ &= (triangle.t/2^1 + dots.c + circle/2^(n-1)) + 1/2^n \ &= c(overline(x) + 2/3^n). $ 而 $x in [overline(x) + 1/3^n, overline(x) + 2/3^n]$,于是 $c(x)$ 只好也取这个值。 整理一下,设 $overline(x) + 1/3^n, overline(x) + 2/3^n$ 这种三进制只含 $0,2$ 的数的集合是 $cal(C)$(这正是后文的 Cantor 集),那么 $ c(x) = cases( sum_n a_n/2^n &space.quad x = sum_n (2a_n)/3^n in cal(C), sup c([0,x] sect cal(C)) &space.quad x in.not cal(C), ). $ ] = Baire 空间 为了让目前不懂或曾经懂过的人理解什么是“几乎处处”“连续”“本质间断”,需要明确若干概念。 == 点 $X$ 内有一点 $x$,考查 $x$ 的邻域 $U$ 和去心邻域 $U^0 := U without {x}$ 与集合 $S subset X$ 及其补集 $S^complement$ 的相交情况。 #place( right, dx: 1.5em, dy: 2.5em, grid( columns: (auto, auto), column-gutter: 0.25em, $cases(reverse: #true, #v(5em))$, [ #set align(left + horizon) *聚点*(accumulation,导集,derived) $U^0 sect S != emptyset$ ] ) ) - 附着点(*闭包*,closure):$U sect S != emptyset$ - *内*点(内部,interior):$U subset S$ - 边界点(*边界*,boundary):$U sect S^complement != emptyset and U sect S != emptyset$ - $U^0 sect S != emptyset and U sect S^complement != emptyset$ - *孤立*点(isolated):$U^0 subset S^complement and x in S$ - 外点(外部,exterior):$U subset S^complement$ #figure( image("fig/Interior_illustration.svg", width: 30%), caption: [ $x$ 是 $S$ 的内点,$y$ 是 $S$ 的边界点 | #link("https://commons.wikimedia.org/wiki/File:Interior_illustration.svg")[Wikimedia Commons `Interior illustration.svg`] ] ) #figure( image("fig/synapse.svg", width: 30%), caption: [ 闭包等概念的Euler图 | 删改自 #link("https://commons.wikimedia.org/wiki/File:SynapseSchematic_lines.svg")[Wikimedia Commons `SynapseSchematic lines.svg`] 虚线以上代表 $S$。有凹窝区域(贝壳颜色)代表 $S$ 的内部(即 $S^complement$ 的外部),与之相对区域(紫)代表 $S$ 的外部(即 $S^complement$ 的内部),其余代表边界($S, S^complement$ 共享边界)。六边形(绿)代表 $S$ 的孤立点,三角形(红)代表 $S^complement$ 的孤立点。边界和内部之并是闭包,闭包中孤立点以外部分是聚点。 ] ) 由定义形式可知: - 闭包可划分为内部、边界,也可划分为聚点、孤立点,这是两组概念; - $S$ 的边界也是 $S^complement$ 的边界,所以前一种划分更为对称。 #remark[$forall$ 还是 $exists$,$U^0 attach(=, t: ?) emptyset$][ 所有“$!= emptyset$”都是“$forall U$”,其余都是“$exists U$”。 不过即使补上量词,上述分类也有瑕疵:假设了 $forall U, U^0 != emptyset$。这在 $RR^n$ 确实成立,但在一般拓扑空间(如最精细的离散拓扑空间),就不成立。 无论假设是否成立,以下命题都成立。 - $X$ 可划分为闭包、外部。 - 闭包可划分为“内部、边界”和“聚点、孤立点”。 - 一点既是边界点又是聚点。$<==> forall U, space U^0 sect S != emptyset and U sect S^complement != emptyset.$ 唯一可能错误的是下面这组等价命题。(照例省略 $forall$ 和 $exists$) - 内点 $=>$ 聚点。 - $U subset S => U^0 sect S != emptyset.$ - $U^0 subset S^complement => U sect S^complement != emptyset.$ - 孤立点 $=>$ 边界点。($U^0 subset S^complement and x in S ==> U sect S^complement != emptyset and U sect S != emptyset.$) 中间两行互为逆否,它们也等价于 $U^0 sect S != emptyset or U sect S^complement != emptyset$。分类讨论可知它等价于 $U^0 != emptyset or x in.not S$: - $x in.not S$ 时,$U sect S^complement supset {x} sect S^complement = {x} != emptyset$,原命题后半部分恒真。 - $x in S$ 时,整个命题化为 $U^0 sect S != emptyset or U^0 sect S^complement != emptyset$,即 $U^0 = U^0 sect (S union S^complement) != emptyset$。 于是这只有 $S$ 中所有点的所有去心邻域都非空时才成立。事实上,若 $x in S$ 存在 $U^0 = emptyset$,那么按定义 $U subset S, U^0 subset S^complement$,于是 $x$ 既是内点又孤立,立即构成反例。 ] #figure( image("fig/final_frontier.png", width: 60%), caption: [ $RR^2$ 内的一个点集(黑灰点),以及它的导集(橙虚线)#footnote[ 橙虚线的导集是其自身,所以它是黑灰点集反复取导集的最终结果。又,代数拓扑、流形中有其它boundary概念,为避免混淆,点集拓扑中的边界有时改称frontier。综合两点,橙虚线是名副其实的 _final frontier_。 ] 这个点集由 $ZZ times NN times {-1} subset RR^3$ 关于 $(0,0,0)$ 投影而成。 它所有点都是孤立的边界点,没有内点;聚点都不在其中,但都是边界点。 ] ) // Mathematica: // With[{a = 2.2, yMax = 50}, Graphics[{ // Table[{GrayLevel[1 - 1/y], // Point@Map[{#/y, -2/y} &, // With[{e = Ceiling[y a]}, Range[-e, e]]]}, {y, yMax}], // Dashed, Orange, Line@{{-a, 0}, {a, 0}} // }, PlotRange -> {{-a, a}, {-a, 0}} // ]] == 集合 理解了点的性质,就可以进一步谈集合的性质了。 #footnote[ 这里涉及开、闭、孤立。(open, closed, isolated)有趣的是,热学中系统刚好有开放、封闭、孤立的说法:开放系统允许与外界交换物质、能量,封闭系统不交换物质,孤立系统两者都不交换。 ] 例如,若一个集合等于其导集,则称它*perfect*,这等价于它是无孤立点的闭集。更多定义如@tab:def-pairs。 #figure( table( columns: 2, table-header[原集合的性质][补集相应性质], [开 open #h(1fr)——边界全无], [闭 closed #h(1fr)——边界全管], [稠密 dense #h(1fr)——闭包取满#footnote[稠密必须谈背景,这里默认在 $RR$ 中。]], [无内点 has empty interior], [内点稠密 has dense interior], [无处稠密 nowhere dense #h(1fr)——闭包也无内点], [$G_delta$ #h(1fr)——开集的可数交], [$F_sigma$ #h(1fr)——闭集的可数并], [comeagre#footnote[我尝试了多种翻译服务,大多原样返回,仅DeepL和必应有时会翻译:前者给出`""`(一对引号)或“蔚为大观”,后者给出“科马格雷”。]], [疏朗 meagre#footnote[又叫first category,意思是按meagre与否将集合分为两类。不过取“第一”“第二”这种名字,还不如随机地叫“元伶外夜承”“承夜外伶元”,那样既强调仅有两类,又不会与其它术语混淆。另外,这个category常译作“纲”(→界门纲目科属种),但容易误以为提纲、纲领,所以我们也不采用。] #h(1fr)——无处稠密集的可数并], ), caption: [Baire空间涉及的若干性质] ) <tab:def-pairs> #remark[$F_sigma, G_delta$ 定义的反面][ 开集的任意并仍是开集,而 $F_sigma$(闭集的可数并)就未必是闭集了,例如 $union.big_(n in NN) [0, 1-1/n] = [0,1)$。 ] #example[$QQ$ 的性质][在 $RR$ 中,$QQ$ 有如下性质。 #show "❌": text.with(fill: red) #show "✅": text.with(fill: green) #show regex("[❌✅]"): set text(font: "Segoe UI Emoji") #figure( table( columns: 2, table-header[一种性质][另一种性质], [❌开], [❌闭], [✅稠密], [✅无内点], [❌内点稠密], [❌无处稠密], [❌$G_delta$], [✅$F_sigma$], [❌comeagre], [✅meagre], ), caption: [$QQ$ 在 $RR$ 中的性质] ) 由 $RR$ 的构造过程、$QQ$ 可数,立即得到大部分结论;剩下的由可数集之并仍可数,可转为 $RR$ 的性质。 - 假设 $QQ$ 是 $G_delta$ 集,结合 $RR without QQ$ 是 $G_delta$ 集,得 $emptyset = QQ sect (RR without QQ)$ 也 $G_delta$。 $emptyset$ 确实 $G_delta$,不过注意 $QQ, RR without QQ$ 都稠密,这不仅导出 $emptyset$ 是开集的可数交,还导出 $emptyset$ 是稠密开集的可数交,这可能吗? - 假设 $QQ$ comeagre,则 $RR without QQ$ meagre。结合 $QQ$ meagre,得 $RR = QQ union (RR without QQ)$ 也 meagre。 $RR$ 不可数、稠密,它可能meagre吗? 以上两点在Baire空间中都不可能。后面就将介绍这种空间。 ] #remark[$F_sigma$ 与meagre][ $F_sigma$ 被嵌入了meagre的定义——无内点的 $F_sigma$ 集必定meagre。原因如下。 1. 由内点和并集的定义,$A_n$ 的内点也是 $union.big_n A_n$ 的内点,于是“$union.big_n A_n$ 无内点 $=> A_n$ 均无内点”。 2. 若无内点的 $A_n$ 是闭集,则 $A_n$ 无处稠密,于是“$A_n$ 均无内点 $=> union.big_n A_n$ 符合meagre的定义”。 正命题“无内点 $=>$ meagre”成立,那反命题“meagre $=>$ 无内点”成立吗?这正是Baire空间要讨论的。 ] #remark[Dirichlet函数不属于Baire class 1][ #let diam = math.op("diam") 1. *任何函数的间断点集合都 $F_sigma$。* 1. 函数 $f$ 在 $x$ 的*振荡*(oscillation) $omega_f (x) := inf_(delta > 0) diam f(U_delta (x))$#footnote[这也是 $lim_(delta->0)$。(单调递减,非负,必存在极限)],其中 $diam$ 表示集合的直径(其中点间的最大距离)。 2. $f$ 在 $x$ 连续的定义是 $forall epsilon > 0, exists delta > 0, space f(U^0_delta (x)) subset U_epsilon (f(x))$,必要条件是 $diam f(U_delta (x)) < 2epsilon$,充分条件是 $diam f(U_delta (x)) < epsilon/2$,于是可知 $f$ 在 $x$ *连续等价于 $omega_f (x) = 0$*。 3. $forall x in U_delta (x_0), space U_(2 delta) (x_0) supset U_delta (x)$。于是若 $omega(x_0) < Omega$,则 $exists delta > 0, diam f(U_(2delta) (x_0)) < Omega$,故 $forall x in U_delta (x_0), omega(x) < Omega$。换句话说,${x: omega(x) < Omega}$ 总是开集,故 *${x: omega(x) >= Omega}$ 总是闭集*。 4. $f$ 的*间断点集合*是 ${x: omega(x) > 0}$,它也可写成 $ union.big_(n in NN) {x: omega(x) >= 1/n} $ 这样可数个闭集之并,于是 *$F_sigma$*。#footnote[ 这是集合的极限 $lim_n {x: omega(x) >= 1/n}$。 ] Thomae函数的间断点集合是 $QQ$,确实 $F_sigma$;但不存在一个函数,它的间断点集合是 $RR without QQ$,因为它并不 $F_sigma$(前面刚论证了Baire空间中 $QQ$ 不 $G_delta$)。 2. *Baire class 1函数的间断点集合 meagre $F_sigma$。* Wikipedia给出的来源是 Kechris, <NAME>. _Classical Descriptive Set Theory_ (1995) 定理24.14,不过我查到一个足以排除Dirichlet函数的更弱的定理,它是 #link("https://www.whitman.edu/Documents/Academics/Mathematics/huh.pdf")[Baire one functions - Johnny Hu (`whitman.edu`)] 的第15页的定理4的一半。 1. 连续性的拓扑学定义是“开集的原像总是开集”。具体到 $RR -> RR$ 函数,只需说明 $(-oo, r), (r,+oo)$ 这两种开集的原像总是开集。 例如Dirichlet函数不连续,$(-oo, 1/2)$ 的原像是 $RR without QQ$,并不是开集。 2. 现在考察Baire class 1函数。设 $f_k$ 均连续且逐点收敛到 $f$,那么 $ {x: f(x) < r} &= lim_(n -> +oo) {x: f(x) <= r - 1/n} \ &= lim_(n -> +oo) op("lim inf", limits: #true)_(k -> +oo) {x: f_k (x) <= r - 1/n} \ &= union.big_(n in NN) union.big_(k in NN) sect.big_(k' >= k) {x: f_k' (x) <= r - 1/n}. $ 第一个等号是 $union.big_n (-oo, r-1/n] = (-oo, r)$ 两边套 $f^(-1)$,第二个等号是极限的局部保号性,第三个等号是按集合极限的定义重写了一下。 - 因为 $f_k'$ 连续,$(r-1/n, +oo)$ 的原像总是开集,故 ${x: f_k' (x) <= r - 1/n}$ 总是闭集。作为闭集的任意交,$sect.big_(k' >= k) {x: f_k' (x) <= r - 1/n}$ 仍是闭集。 - $NN^2$ 可数,$union.big_n union.big_k$ 仍然是可数并。 于是 ${x: f(x) < r}$ 写成了闭集的可数并,$F_sigma$。 3. Dirichlet函数 $(-oo, 1/2)$ 的原像是 $RR without QQ$,并不 $F_sigma$,所以它不属于Baire class 1。 4. 上面说明了“*$(-oo, r)$ 的原像总 $F_sigma$*”是Baire class 1的必要条件。其实那个定理4证明了“$(-oo, r), (r, +oo)$ 的原像总 $F_sigma$”也是充分条件。不过构造过程相对繁琐,这里不再叙述;也许存在更直接的证明吧。 ] == Baire category theorem Baire空间有如下等价定义。 #figure( image("fig/baire_space-no_context_strokes.svg", width: 80%), caption: [Baire空间的若干等价定义] ) Baire category theorem指出 $RR$ 是Baire空间,我们从“稠密开集的可数交 $=>$ 稠密”入手证明这一点。 0. 设 $A_n$ 均是稠密开集,要证 $A = sect.big_n A_n$ 稠密,即对任意开集 $O$,$O sect A != emptyset$。 1. 先考虑 $O sect A_1$。由 $A_1$ 稠密、开,$O sect A_1$ 是非空开集。于是可构造非空闭球 $overline(B_1) subset O sect A_1$。注意 $overline(B_1)$ 的内部 $B_1$ 也是开集,可进一步构造 $overline(B_2) subset B_1 sect A_2$。以此类推,$overline(B_n) subset B_(n-1) sect A_n$。 2. 选取 $B_n$ 时,可让 $B_n$ 的直径小于 $1/n$,保证 $B_n$ 的直径趋于零,从而这些球的中心构成Cauchy列。由 $RR$ 完备,存在极限 $x$。 3. $O sect A supset sect.big_n overline(B_n) supset {x} != emptyset$,命题得证。 #remark[选择公理][ 选取 $B_n$ 的过程需要axiom of dependent choice,可以证明ZF公理体系中,完备度量空间上的Baire category theorem与axiom of dependent choice等价。 ] #remark[真正的Baire category theorem][ 上述证明只用到了“直径趋于零的闭集套交集非空”,可以推广到更抽象的空间。真正的Baire category theorem给出了下面两个没有蕴含关系的充分条件。 1. 完备的伪度量空间。(从Cauchy列出发) 2. 局部紧空间。(从闭区间套出发) (直径趋于零是必要的:$sect.big_n [n,+oo) = emptyset$) ] = 这就是现实 现在回顾最初的目标,要构造一个函数 $f$,满足以下两点。 - 几乎处处连续,且几乎处处不连续——将 $f$ 的间断点的集合记作 $A$,要求 $A,A^complement$ 都在 $RR$ 中稠密,即 $A$ 稠密且无内点。 - 所有不连续点都是本质间断点——$forall a in A, space lim_(x->a) f(x)$ 不存在。 我们的计划如下。 0. 将 $A$ *拆*为一系列互不相交的集合 $A_n$ ($n in NN$),取 $ f(x) = cases( 1/n &space x in A_n, 0 &space x in.not A ). $ 1. *构造*时让 $A = union.big_(n in NN) A_n$ 稠密,而每个 $A_n$ 又足够稀松且补集性质优良。 2. *证明* $A$ 中都是间断点,$A^complement$ 中都是连续点。 == 构造 1. 由于 $QQ^2$ 可数,可*构造 $I_n$* 遍历所有“两端点是有理数的开区间”。 2. 逐一*构造 $A_n$* $subset I_n without union.big_(m < n) A_m$ 并且 $A_n$ 是*无处稠密*的 *perfect* 集。 因为先构造的 $A_m$ 都无处稠密,故补集 $RR without union.big_(m < n) A_m$ 的内点稠密,于是 $I_n without union.big_(m < n) A_m$ 总有内点。在这内点的邻域内,总有段区间可自由发挥来继续满足要求,例如平移缩放Cantor集。 3. 论证 *$A$ 稠密*。 任取 $x in RR$ 及其邻域 $U$,必存在 $I_n subset U$(因为 $QQ$ 稠密),因而 $U sect A supset U sect A_n != emptyset$。 4. 再论证*补集 $A^complement$ 也稠密*。 $A$ 是可数个无处稠密集 $A_n$ 之并,即 $A$ meagre,于是 $A^complement$ comeagre,而Baire空间中comeagre集都稠密。 #remark[Cantor集][ 原版Cantor集 $cal(C)$ 是 $[0,1]$ 中三进制只含 $0,2$ 的数的集合,它也是不含“中间 $1/3$ 开区间”的自相似分形。 #figure( image("fig/Cantor_set_binary_tree.svg", width: 50%), caption: [ 不断去掉中间部分可得到Cantor集 | #link("https://commons.wikimedia.org/wiki/File:Cantor_set_binary_tree.svg")[Wikimedia Commons `Cantor set binary tree.svg`] ] ) - 闭:迭代构造时,每一阶段都是闭集,$cal(C)$ 是这些闭集的交集,也闭。 - 无内点:迭代 $n$ 次后,不再存在长于 $1/3^n$ 的区间。 - 无孤立点:迭代 $n$ 次时,可确定此时每段闭区间的端点属于 $cal(C)$,并且这些点与此时整个集合任意点的最大距离是 $1/(2 times 3^n)$。 综合以上各点,$cal(C)$ 是无处稠密的perfect集。 ] == 证明 - 证明 $A$ 中都是*间断*点。 设 $x in A_n$。 - $A^complement$ 稠密,所以 $x$ 是 $A^complement$ 的聚点,而 $f(A^complement) = {0}$。 - $A_n$ 闭,所以 $x$ 也是 $A_n$ 的聚点,而 $f(A_n) = {1/n}$。 我们构造了两个趋于 $x$ 的子列,极限分别是 $0,1/n$,不一致,故极限不存在。 - 证明 $A^complement$ 中都是*连续*点。 设 $x in A^complement$,要证明 $f$ 在 $x$ 处的极限等于 $f(x) = 0$。 1. 任取 $epsilon$,$union.big_(1/n >= epsilon) A_n$ 是有限个闭集之并,仍闭。 2. $x in.not A$,故不属于 $union.big_(1/n >= epsilon) A_n$,从而是这个闭集的外点,从而 $exists delta$, $ U_delta^0 &subset RR without union.big_(1/n >= epsilon) A_n = A^complement union union.big_(1/n < epsilon) A_n. $ 3. 代入 $f$ 的定义,得 $ f(U_delta^0) subset {0} union {1/n: 1/n < epsilon} subset U_epsilon (0). $ #set heading(numbering: none) = 他典等 - #link("https://en.wikipedia.org/wiki/Thomae%27s_function")[Thomae's function - Wikipedia] - #link("https://en.wikipedia.org/wiki/Baire_function")[Baire function - Wikipedia] - #link("https://en.wikipedia.org/wiki/Baire_space")[Baire space - Wikipedia] - #link("https://mp.weixin.qq.com/s/Km8iIghIn-aAKT0YQKHWAw")[解题的策略 - 陶哲轩教你学数学] - #link("https://en.wikipedia.org/wiki/Boundary_(topology)")[Boundary (topology) - Wikipedia] - #link("https://www.ucl.ac.uk/~ucahad0/3103_handout_7.pdf")[Handout \#7: The Baire category theorem and its consequences - Mathematics 3103 (Functional Analysis), Year 2012–2013, Term 2 (`ucl.ac.uk`)] - #link("https://en.wikipedia.org/wiki/Axiom_of_dependent_choice")[Axiom of dependent choice - Wikipedia] = 致谢 华歆在群里提出了这个问题,原始表述大致如下。 #quote(block: true)[ $A,B$ 是 $RR$ 的一个划分,并且它们的闭包都是 $RR$。 证明或证伪:不存在在 $A$ 上处处连续、在 $B$ 上处处本质间断的函数。 ] 我当时认为命题成立,尝试证明未果,到 Math.SE 上提问。 #quote(block: true)[ #link("https://math.stackexchange.com/questions/4792247/essentially-discontinuous-on-a-dense-subset-of-mathbbr-but-continuous-on-t")[real analysis - Essentially discontinuous on a dense subset of $RR$, but continuous on the complement which is also dense - Mathematics Stack Exchange (q/4792247)] ] 几位网友帮助明确了问题(那些评论后来已按惯例删除),不久 #link("https://math.stackexchange.com/users/111012/bof")[bof] 构造出了反例。 然而我只看懂了验证,没理解括号中的构造过程。项羽帮忙查了些资料,共工在群里给出了完整解释。 #pseudonyms("pseudonym", subset: ("华歆", "共工", "项羽"))
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/051%20-%20March%20of%20the%20Machine/017_Episode%209%3A%20The%20Old%20Sins%20of%20New%20Phyrexia.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 9: The Old Sins of New Phyrexia", set_name: "March of the Machine", story_date: datetime(day: 28, month: 04, year: 2023), author: "<NAME>", doc ) Centuries ago, the angels staved off the oil of unlife on New Capenna. For centuries, the people on New Capenna have been safe from the encroachment of the enemy. They lent this knowledge of the enemy to their sisters on other planes—thus, the Multiverse remained vigilant about the coming threat. It was good. It is no longer enough. Their safeguards have failed. Now, the Multiverse cries out for help. Another angel—corrupted and dark—has come to New Capenna to reap the rewards sown by its people's sin. She cuts her way through the city's defenses as a farmer threshing wheat. Buildings that stood for generations collapsed in moments; glass and blood line the gutters; war machines rumble through streets that once bustled with cars. Stone springs to life. Angels that have waited centuries to serve again hear the clarion call to battle. What have they waited for, if not this? Radiant weapons slice through the hulls of towering monstrosities. Wings shield those fleeing from the porcelain onslaught of the enemy. For hours they lend their strength. Those shattered by Phyrexian weaponry dematerialize at the last—as Halo, that glimmering angelic essence, they may still serve. But Phyrexia's armies are teeming ten thousand, and there are far fewer angels on New Capenna than there once were. Fortunate that they are not its only protectors. Where angels beat back the enemy and shield the Capennan forces, there are demons and devils to take the offensive. Here a seraph infuses a tower with Halo; there, a demon severs the heads of those climbing it. Few things are more repugnant than demons, and there will be a price for all this later—but it is a price the angels of New Capenna are willing to pay if it keeps their charges safe. The youngest among those angels, Giada, wants to help. But she's too small to join the melee, too newly formed for the battlefront. All she can do is watch from the towers and shout to the others where they're most needed. Despite this, she can't help but feel there's something she's missing. She's certain she'll know it when she sees it. Angels are all about certainty, her older siblings told her. Deeper into the city goes Atraxa, her army in her wake. The intricate workings of Park Heights do not impede the swing of her scythe. Riveteers slicked with sweat hide in whatever rafters they can find. Their quick hands disassemble the work of their forefathers. Tools used to forge connections are now used to sever them violently in gouts of flame. The corrupted angel does not see them at this work—they are too small, too many, too disparate. They are beneath her notice. In the end, that is her undoing. An explosion rips through the structures of the city. Deep within the structure of the Mezzio as she is, she does not notice that it's begun to topple until it's already too late. In the end it is not the shield of the angels that kills her, nor the machinations of the demons: it is the city itself. The gleaming glass and steel tower of New Capenna collapses atop her, cut free from its mighty pylons and suspension systems. From their perch, the angels watch centuries of mortal work crash into the earth. Giada's essence fizzes with excitement, but it isn't yet right for her to intervene. There's someone she's waiting to hear from. The others waste no time. The defenses of New Capenna must not be confined to the city alone. If the Multiverse is to survive, the angels must watch over it and fight against Phyrexia with all they have. Atraxa's death has changed New Phyrexia—and the Invasion Tree is changing with it. The angels feel it as the mortals might feel the earth trembling beneath their feet. The barbs are retracting back to their home, leaving the pathway open for attack. Their view of New Phyrexia beyond the portals changes to a view of somewhere else—a place with a wine-dark sea, a place where the sky shimmers with the beliefs of its people. And though there are no angels on Theros, they can't deny it's desperately in need of help. To do the just thing without regard for your own safety, to see beyond the needs of the few: this is what it means to guard the Multiverse. Giada grins. This is the start of things—the start of what she's been waiting for. She hurriedly shouts at the others: #emph[this is where we're needed, this is where we've got to go! Help them out if you can!] Angels soar through the air, hurtling at unimaginable speed toward the portal. On the other side, they burst high above the sea. The angels displaced in this way feel no fear, no hesitation, no regret—they simply do as they've always done. They protect. Like motes of dust, they travel the winds toward their destination. Some wrap about the throat of a thrashing sea monster, holding it in place long enough for a crew of sailors to sever its heads. Others make their way to temples. The gods who call it home matter not; supplicants in need of protection soon find it. The black oil smeared across a fleeing woman's arm miraculously avoids her wounds; a javelin thrower turns the second before he would have found himself skewered. #figure(image("017_Episode 9: The Old Sins of New Phyrexia/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) There is one god who notices their arrival. Bright as the morning sun the befouled Heliod shines, the ethereal angels threatening to burn within his sight. Yet they venture closer, and closer, and closer, for clambering up behind him is a woman who needs help as much as she hates asking for it. So distracted is the god that he does not notice Kaya's violet-wreathed form upon his corrupted carapace. When at last she drives a dagger into his throat—well, the angels see to it that the spray of black oil never touches her. As the god fades, the woman lands once more on the temple. Ajani is there to meet her—but what does a godkiller have to fear from a mere mortal? Giada's formless heart beats faster. Every step is a step closer to her old friend. Once more the portals of New Capenna shift, this time to myriad planes, some new to the angels, some familiar—all in the desperate throes of a fight they cannot win alone. Good thing they are no longer alone. "#emph[Charge] !" Giada shouts. Warhorns echo throughout New Capenna, and the angels spread where they are needed most. On planes where they are worshipped, on planes where they are hated, on planes where they are completely unknown—they do what they have always done. When at last the portals turn to New Phyrexia, Giada knows precisely what to do. The moment has finally arrived. There in plain view is Elspeth Tirel. #emph[I'm so happy to see you] , she calls. Elspeth Tirel is too busy to do more than glance toward the portal: there are thousands of Phyrexians charging the platform before her. Fighting takes most of her attention. Even so, when her gaze skims toward the surface, there's a small smile on her lips. #emph[Giada. I'm happy to see you, too.] She's already learned to speak the proper way, hasn't she? It warms Giada's spirit to see Elspeth shining so brightly. #emph[You've done so well.] #emph[Thank you] , Elspeth answers. She drives her sword through a winged blade-serpent, splitting it down the center. #emph[But there's still work to be done.] #emph[That's just what I wanted to tell you. Some of us are coming to help.] The serpent falls to the ground, but Elspeth remains in flight. A copper vine wraps around her sword arm. She severs it with a weighty chop. #emph[Whatever aid you can send, I'll accept gladly.] Giada remembers what it is like to grin. Though she cannot in this form, she feels it in her spirit. She readies another call. Those who go to New Phyrexia will not return. It is a small price to pay. Someone must watch over them—someone must stanch the bleeding. #emph["Charge!"] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) On Dominaria it was often said that Zhalfirins did not know fear, but the Zhalfirins said otherwise. So far as they were concerned, they knew fear better than anyone else. You could find fear sitting by the fires near nightfall. Every parent who sent a child to war chatted with fear in the mornings and at night. Fear was with you when you surveyed your fields and wondered if there'd be enough for the coming season. The truth of the matter is this: when you know fear and invite fear into your house, when you treat fear as you'd treat anyone else, fear can no longer frighten you. Your community will look after your fears, and you will look after theirs. The Multiverse is afraid of New Phyrexia. Very well. Let Zhalfir look after that. #figure(image("017_Episode 9: The Old Sins of New Phyrexia/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Armed to the teeth, smiling and eager as they face the enemy—the warclans are only too happy to meet the Phyrexians. As Koth's barricade comes tumbling down, the Zhalfirins charge ahead. Teferi catches Koth staring down at them with confusion. "Wait, where'd you come from? What's going on?" Teferi smiles at him. Pride swells in his chest. "Zhalfir. Wrenn found us. We're here to help." All around them the ceiling is starting to crumble, the ground is atremble. Teferi isn't bothered. "The two planes are swapping places—New Phyrexia's being flung out into the abyss, and Zhalfir is~ finally coming home. She will welcome you and yours, if you let her." Koth looks out onto the gathered forces. His expression is hard to read—determination, relief, and sorrow all carve their marks upon his iron. "Then let's make sure Phyrexia never forgets us. Mirrans, make your marks!" There aren't many Mirrans left—but those who can fight are only too happy to join the charge. A veil of multicolored light settles over the army's vibrant garments like the blessing of a distant god. Power prickles along their skin. They know what danger the black oil presents them. They know how to counter it. Lances pierce Phyrexian serpents and nail them to the platform's surface; hurled stones crush them underfoot. Rains of fire melt the enemy in place; breath of ice makes them brittle; the blow of a great hammer shatters them into hundreds of pieces. For years, Zhalfir has awaited the chance to prove their mettle against these argent slags. Now that they are in the thick of the fight there is a prideful joy in the air. Sidars start their chants, calls and responses echoing along from the mouths of Askari, Akinji, and Altali: "You cannot break—" "—what is woven together!" Bravado is as potent as any armor. After only minutes on the field, the Zhalfirins drive a wedge into the Phyrexian army's forces, while their healers tend to the wounded Mirrans on the platform. At the vanguard rides Teferi, his staff aglow, magic swirling about him. The spears that fly, the bladed insect swarms, the shards of the dead blown asunder—all slow as they near him. His companions snatch weapons from the air and hurl them back at their owners. And though Teferi's rarely known exertion such as this, he meets it with a glad heart and centuries of skill. Rushing to catch up with him are the other Mirrans—those that can still fight. Chandra points him out to Koth. "You see? That's him! That's Teferi! I told you he was—" She's cut off when Praetor Vorinclex leaps toward Teferi's vanguard. A moment of hesitation stops Chandra's breath, but Vorinclex does not get far before he hits the wall of Teferi's magic. Everyone—no matter how fearsome—looks foolish moving in slow motion. Even Koth breaks into a smile at the sight. "All right. Maybe you were onto something." But he, too, is busy. Koth drives both fists into the ground. Two cracks spread out toward the Zhalfirins, one on each side. "Give me a hand." Chandra doesn't know exactly what he wants, but she assumes he needs fire. She sends some shooting down each of the cracks. Flames rise to fend off the incoming blows of the Phyrexian army—and turn the Askari's burning weaponry into bladed infernos. Only a few seconds later Koth whips his arms up. Incandescent metal shards fall like the condemnation of the Multiverse on the backs of the Phyrexian army. Yet not all meet their fate so easily. Even Teferi's concentration can flicker. Vorinclex's struggle against it at last finds purchase; he tears the jaws from Teferi's mount and sends him tumbling to the ground. In no time at all the praetor is atop his prey. Vorinclex's roar has heralded the death of many warriors—but fear is an old friend of Teferi's, and he does not feel its pull now. "Look behind you." The praetor turns, snarling. A blazing sword severs Vorinclex's head from his body. One of the Askari—a woman named Shella, who often drank her comrades under the table—offers Teferi a hand up. He takes it, thanks her, and then she is gone. On a battlefield there is always more work to be done. It's then he sees the angel, hovering only a little overhead. The serenity of her expression belies the concern in her eyes. "You'll need to be more careful." "Elspeth~ ?" he asks. But the confusion on his face changes to acceptance, and he offers her a smile in the middle of the battlefield. "I'm happy you're here." There's something foreign in the way she looks back at him, as if she doesn't entirely understand how it is she's meant to respond. In the end, she doesn't. Teferi understands. Sometimes people change. She's still his friend—and a skilled soldier. "Any tactical advice?" A copper root flies toward Elspeth; she severs it with a single cut. She doesn't spare Teferi a glance. "Leave Nissa to me. Your forces will need to hold off Jin-Gitaxias and Norn. My sisters have given us a gift. The infection cannot take hold so long as they are with us. Don't waste it." Elspeth speaks in a strikingly normal voice, as if she's discussing what to wear at an outing rather than plans vital to the survival of life on all planes. "Understood," he says—but by then she's already left. Up above them the roof of the sanctum cracks. Wrenn's work, Teferi wagers: as Zhalfir moves to take New Phyrexia's place in the Multiverse, New Phyrexia is cracking under the pressure. Structures tear and break. Slabs of metal plummet down. Zhalfirin wizards conjure the winds to redirect the boulders out toward the enemy. No amount of Phyrexian armor can protect against the forces of mass and gravity—smears of black oil are all that remain of those squashed beneath. Distant towers topple, monuments shatter, vats crack and oil slicks the walkway. The ground rumbles beneath Teferi's feet. These are the death throes of Phyrexia. And there is its keening death wail: flinging aside soldiers with ease, consigning them to the abyss, is <NAME>. Her porcelain armor is pitted in places and outright sundered in others, revealing her weak, torn sinew beneath. Towering over the army—even the war machines—she strikes Teferi as a lion with a sour wound. "What we've done~ what I've built will last forever!" she screams. "Phyrexia will never die. You're only delaying the inevitable. Why can't you understand that? Why won't you accept your fates?!" Teferi sends word through the ranks to focus fire on the giant praetor. A volley of magic—lightning, ice, fire, bolts of verdant energy, withering dark—beat her back. Norn staggers, swaying on her feet. Norn's oil-slicked mouth hangs open in shock; she clutches a talon to the cluster of wounds on her chest. When she surveys the army once more she lets out another scream. "Why aren't any of you protecting me!? I #emph[am] Phyrexia!" The army hears her, and the army stops—but only long enough for their own general to speak up. Jin-Gitaxias rides atop a massive war machine. Long and narrow, it is bedecked with all manner of weaponry: blades, spikes, a great ram at its head. All this to protect its precious cargo: a vat filled with his own progeny. Writhing newt-like creatures nearly ready to be born press their featureless faces against the glass. When he speaks, the vat flickers with light. "Your ego is a tumor on whatever talent you may have had. New Phyrexia has evolved beyond you. But your scraps may serve some use." To see them turn against one another both surprises and relieves Teferi. As does the familiar boom of a Planeswalker's arrival—until he sees Ajani, badly wounded, joining the fray. "You?" Jin-Gitaxias sneers. "Out of the way. That thing behind you is Phyrexia's true enemy." "No," Ajani booms. "Phyrexia stands united, or not at all." Teferi's had no time to decide what to do before Jin-Gitaxias's legions descend on Norn and Ajani. Centurions hack at her armor, pulling off sheets in chunks, as she crushes however many of them she can. It is as if she is being assailed by a massive swarm of beetles—all of whom have sharp teeth and sharper weapons. Ajani rips and slashes at them, first with his axe and then, when it's torn from his grasp, with his claws and teeth. He cannot stop them all. Let them weaken Norn. Ajani leaps in front of her only to catch a disorienting blast of magic that leaves him on his back. Ropes and nets are cast over him, and Zhalfirin warriors surge forward with spears. On an instinct he can't name, Teferi shouts "Wait! Take that one alive!" Ajani thrashes against his bonds, leaking blood and oil into the ropes, until another spell freezes him solid. Obediently, the warriors drag the subdued leonin out of the fight. In the meantime, Jin-Gitaxias has given Norn so much of his attention he's left himself open. Zhalfirins understood the dangers of infighting as few did. That left them in a unique position to capitalize on the failings of their foes—and save what they could of their friends. While Jin-Gitaxias oversees his army's attack on Elesh Norn, Teferi and the vanguard head straight for him. Claws rend through steel and iron; swords and axes cleave skull and sternum. Always the Zhalfirin war chants and drums lend them vigor. As Phyrexia dies around them, the Zhalfirins are more alive than they've ever been. When the praetor turns to behold the splendor of their valor, he laughs, for he does not know fear. "Is this the best you can muster? #emph[Organics] ?" He gestures with his claw. Spikes shoot from the flanks of his war machine, impaling the beasts who strive to break it. Blood spurts onto the glass as the animals howl. "Look around," Teferi calls. "It seems to me New Phyrexia's the one getting left behind." #figure(image("017_Episode 9: The Old Sins of New Phyrexia/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Jin-Gitaxias gestures once more. Blades emerge from the joints of the war machine. Another gesture and they begin to spin. Teferi's heart sinks. Many of their mounts aren't going to make it out of this. But it'll be worth if it the rest can survive—there will be time to mourn their old friends later. Teferi ducks the oncoming swing of a centurion. Blades, tendrils, and barbs all slow as he weaves his way through the melee toward the war machine. While Zhalfir's prowess is legendary, this is something only he can do. Sucking in a breath, he lays a hand on the flat of the spinning blades. For a precious second they come to a stop. It is enough. "You won't hurt Teferi!" a woman shouts. Teferi looks up to see her: one of the warclan's very own, a massive warhammer lifted high over her head as she soars toward Jin-Gitaxias. When she brings it down upon him the war machine's glass cracks. Foul-smelling liquid gushes out, bathing Teferi in its filth. New clothing will be a small price to pay to see Jin-Gitaxias plummet into his own creation. Even smaller when his own creations start eating him. Teferi wipes his face clean. He looks back toward the Invasion Tree. Koth is overseeing the portal. Most of them have already crossed over into Zhalfir—but some linger. Koth, Chandra, and Karn all remain. And judging by the jagged edges of the portal, there won't be much time left to return. It's time to call for a retreat; the warclans have done enough here. Teferi signals to the drummers. The vital rhythm beneath their feet shifts to something far more dour. Zhalfir knows what this means. For the whole to prosper, the individuals must be kept safe. New Phyrexia is fading—but that doesn't mean the Mirrans have to fade away along with it. So long as they live, they can forge a new home. "Clear a path for the Mirrans!" comes the war-leader's shout. Phyrexia does not let them go easily. The Zhalfirins at the front fend off what blows they can while the rear of the army retreats through the portal. With every step back they take, they leave scores of dead Phyrexians behind. There are Zhalfirins, too, among the dead—but they are treated with reverence. There are those among the army whose sole job it is to see these bodies returned home—fleetfooted Altali who weave between the tangles of the melee clad in bright white. The Zhalfirins part at the sight of their uniforms to allow them through. By the time Teferi makes it back to the platform, nearly everyone has gone ahead. He can see his home waiting to welcome him on the other side—and he can see Wrenn, too, jutting from the tree's surface. His old friend has become a delicate ashen statue. Precious little of her bark remains intact. Teferi swallows at the sight. When he looks over the armies once more the thought is loud in his mind: none of this would have happened without her intervention. There must be something he can do to help. And there, as he studies her, he can see it: an acorn hidden within the ash. It will grow strong as she did on Zhalfir. As he carefully plucks it from the ash, Koth shouts from behind him. "I'd get to leaving if I were you." Teferi pockets the acorn and turns. He shakes his head. "I ran once before my plane was safe. Never again." His eyes fall on his old friend, Karn—still alive, though torn asunder by Phyrexian experimentation. Teferi lays a hand on Karn's shoulder as he looks to Koth. "You go on ahead." But the young man is as stubborn as the metal that dots his skin. He's not going anywhere. And perhaps that's for the best: as a copper spear shoots toward Chandra, it is Koth who raises a shield to protect them. Strange. It isn't like Chandra to let something like that happen. She took whatever excuse she could to melt things. When the shield sinks back to the ground, the picture's clearer. Nissa's on the other side. "You ruined #emph[everything] ." "You're not yourself—" Chandra starts. "There isn't time," Koth says. "Go back through the portal." "No. I'm not leaving without her. She's still in there, I know she is." Nissa hurls another boulder at them, forcing Chandra to blast it away. She steps in front of Koth and opens her arms toward Nissa. "If you want to kill me, here I am. But I know you won't." Teferi bites his lip. Chandra's optimism knows no bounds—but it might get her killed here. "She'll be all right." It's Karn who speaks from Teferi's side. "Elspeth is looking after them. May I ask a favor, Teferi?" As if to punctuate the point, a flash of light heralds Elspeth's arrival. A second later, she drives the pommel of her golden sword into the back of Nissa's head. The elf drops like a stone out of her armor, and out of the sky. And Chandra, of course, is there to catch her. "Of course, old friend," Teferi says. "What can I do?" "Buy me a moment more," Karn says. There's a wobbly tone to his voice, one Teferi hasn't heard before. "I want to walk out of this place under my own power." Teferi can hardly deny him that. As he watches, Karn forms himself a new body, building it layer by layer. On the horizon, Norn's torn through most of her own army. No longer does she stand tall and proud above the other New Phyrexians, for they have taken her legs. Crawling toward them is a skinless abomination. Even her headpiece has been shattered, yet still she pulls herself forward. Clawing through the fields of dead she reaches for the portal. "We don't have long," says Teferi. "No, we don't," agrees Karn. He flexes his new hand—a roughly hewn thing without any of his usual artistry. "You should leave." "What about you?" Karn looks out toward Norn. "There is something that needs to be done. Go. Tell the others that we won't be long." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Karn feels heavy. It isn't a new feeling. In the most objective sense, as a golem, he's always been heavier than anything around him. In the subjective ones, things often haven't been much better. Since Urza's death, Karn's felt heavy every day in one way or another. Some days, the weight of the Multiverse paled in comparison to what he felt. And some days what he feels #emph[is ] the weight of the Multiverse. This is one of the latter days. Watching Elesh Norn crawl toward the platform, he's more aware than ever of the burdens he's chosen to bear. Mirrodin was his creation. Everything that's befallen it is his fault. What began as simple ignorance of his own composition—bringing glistening oil to Mirrodin—evolved into a willful ignorance of his failures. For a long time, he'd consigned this place to oblivion. After Venser gave his life to save Karn's, the best thing to do seemed to be to live it in atonement. Back then he thought there must be some way to repair Mirrodin—some way to undo all his mistakes. He understands differently now. Karn glances at Teferi. The mage is aglow with magic, straining to keep the portal open. After centuries of struggle, Teferi had finally righted the wrongs of his youth. It's the same for Elspeth. All that time running away from Phyrexia, all that time trying to find a new home elsewhere, and here she'd been only moments ago resplendent in the righteousness of her new path. You can't run away from your mistakes. You have to fix them. That starts with confronting your wrongs. Karn steps forward. In the dilation of Teferi's time bubble, Norn's screeching is the booming bray of an unseen warhorn. What's left of her is pitiable and small. If he leaves now, she may well die from her injuries. But he can't be sure that she will. And if Norn lives, then so does her ambition. Many years ago, Karn vowed never to bring harm to the living. He had seen the horrors of war and wanted no part of them. The first Phyrexian invasion changed that, but those decisions never sat well in his core. What right did he have to end the life of another? He, whose life was so artificial? He hated it. He's always hated it. Whenever possible he's tried to find other solutions. There are no other solutions to an evil as pernicious as this. To save the lives of many, it must be exterminated completely. How heavy this knowledge is. Karn lays a hand on what remains of Norn's head. To assemble something is a delight—a puzzle that pleases him in a way few things do. The interplay of connected gears and axles is as exquisite to him as any song. Music, he's found, is quite like building a machine: every piece of an orchestra must function in respect to and in tandem with its fellows. A conductor oversees the processes much as an engineer oversees his creation. In music and in creation there is unity. In destruction there can only be solitude. He hates it. As his magic works on Norn's body, tearing porcelain from wire, he is filled with an animal revulsion. He wants to look away. He wants to stop. Violence, even in the service of the greater good, should never be easily wrought. #figure(image("017_Episode 9: The Old Sins of New Phyrexia/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) He forces himself to look. To watch the metal disintegrate. He burns the sight of Norn's corpse into his memory. He could have asked Teferi. He could have asked Koth. Certainly, he could have asked Elspeth. But he is tired of others fixing his problems for him, and asking them to do it would be the same as killing her himself in the end. This is the smallest way he can take responsibility. When it is done—when <NAME> is a red smear against the white platform—Karn walks to the gate. Teferi relents, and time resumes. Concern shadows his expression when he sees the carnage. "Let's go," Karn says. It is another weight to bear, another heaviness upon him. But it's the first step toward a lighter future. Zhalfir welcomes him.
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CU/minea/1_generated/00_all/11_jul.typ
typst
#import "../../../all.typ": * #show: book = #translation.at("M_11_jul") #include "../11_jul/20.typ" #pagebreak()
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/grid-styling_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(height: 70pt) #set grid(fill: (x, y) => if calc.even(x + y) { rgb("aaa") }) #grid( columns: (1fr,) * 3, stroke: 2pt + rgb("333"), [A], [B], [C], [], [], [D \ E \ F \ \ \ G], [H], )
https://github.com/piepert/logik-tutorium-wise2024-2025
https://raw.githubusercontent.com/piepert/logik-tutorium-wise2024-2025/main/src/packages/goals.typ
typst
Creative Commons Zero v1.0 Universal
#import "@preview/grape-suite:1.0.0": colors #import colors: * #let goal-list = ( // Grundlagen definieren-logik: ["Logik" definieren], wissen-phil-argumente: [wissen, was philosophische Argumente sind], erkennen-phil-argumente: [philosophische Argumente erkennen], definieren-argument: ["Argument" definieren], definieren-gültigkeit: [Gültigkeit definieren], definieren-schlüssigkeit: [Schlüssigkeit definieren], kennen-aufbau-beweis: [kennen den formalen Aufbau eines Beweises], beweise-metasprache: [durch metasprachliche Begründung einfache Beweise über deduktiv-gültige Argumente führen], identifizieren-aussagesätze: [Aussagesätze unter anderen Sätzen identifizieren], definieren-logische-folgerung: ["logische Folgerung" definieren], // AL identifizieren-al-strukturen: [aussagenlogische Strukturen der deutschen Sprache identifizieren], identifizieren-hinr-notw-bed: [notwendige und hinreichende Bedingungen im Wenn-Dann-Satz identifizieren], entwickeln-gefühl-al-syntax: [ein Gefühl für die Struktur und Bildungsregeln von AL entwickeln], erkennen-suchen-schemata: [Schemata suchen und erkennen], bilden-ausdrücke-schemata: [Schemata zur Bildung neuer Ausdrücke benutzen], identifizieren-junktoren: [Junktoren in der natürlichen Sprache erkennen], formalisieren-al: [Sätze der natürlichen Sprache aussagenlogisch formalisieren], formalisieren-wd-gdw-nur: ["nur" und "genau dann, wenn" adäquat formalisieren], bilden-notw-hinr-äquivalenz: [Äquivalenzumformulierungen für notwendige und hinreichende Bedingungen identifizieren und bilden], erkennen-wahrheitsbedingungen: [Wahrheitsbedingungen von Sätzen erkennen], // weiß nicht mehr, wie das gemeint ist definieren-semantik-junktoren: [die Semantik der Junktoren definieren], // Wahrheitstabelle darstellen-junktoren-wahrheitstabelle: [die semantische Definition der Junktoren in der Wahrheitstabelle darstellen], auswerten-ausdrücke-wahrheitstabelle: [Ausdrücke mit der Wahrheitstabelle auswerten], beweisen-logische-wahrheit: [logische Wahrheit und Falschheit in der Wahrheitstabelle beweisen], beweisen-logische-folgerung: [logische Folgerung in der Wahrheitstabelle bweisen], beweisen-logische-äquivalenz: [logische Äquivalenz in der Wahrheitstabelle bweisen], korrekte-beweisform: [schreiben für jeden Beweis QED und einen Antwortsatz], // KdnS aufbauen-kdns: [KdnS korrekt aufbauen können], verstehen-direkte-regeln: [verstehen das Muster der direkten Regelanwendung], beweise-kdns-einfach: [einfache bis mittelkomplexe direkte Beweise führen], wissen-raa-verfahren: [wissen, dass man für RAA standardmäßig das Gegenteil der Konklusion annimmt], bilden-linke-beweisspalte: [die linke Beweisspalte bilden], beweisen-mittels-raa: [Beweis mittels RAA durchführen], erkennen-konditionalisierung: [erkennen, wann $->$-Einf. gefordert ist], prüfen-abhängigkeiten: [wissen, dass sie beim Einführen einer ZA die Abhängigkeiten der Zeilen prüfen müssen], beweisen-verzweigt: [verzweigen Beweis durchführen], // PL wissen-unterschied-al-pl: [verstehen den Unterschied zwischen der reinen Satzlogik AL und der u.a. Begriffslogik PL], formalisieren-pl-unquantifiziert: [einfache prädikatenlogische unquantifizierte Sachverhalte formalisieren], formalisieren-pl-quantifiziert: [einfache prädikatenlogische quantifizierte Sachverhalte formalisieren], umrechnen-quantoren: [Quantoren ineinander umrechnen], benennen-begriffe-log-quad: [die Begriffe des logischen Quadrats nennen], finden-beispiele-log-quad: [eigene Beispiele für das logische Quadrat finden], // PL KdnS variablen-spezialisieren: [quantifizierte Ausdrücke spezialisieren und die spezialisierten Variablen korrekt ersetzen], konstanten-generalisieren: [Ausdrücke, die Konstanten beinhalten, generalisieren und die Konstanten korrekt binden], kennen-einschränkung-allq-einf: [kennen die Einschränkungen der $forall$-Einf. und beachten sie bei der Ableitung], kennen-einschränkung-exq-bes: [kennen die Einschränkungden der $exists$-Bes. und beachten sie bei der Ableitung], ) #let set-all-goals() = state("sequence-goals").update(( current-key: "Z", goals: ( "LG": ( "definieren-logik", "wissen-phil-argumente", "erkennen-phil-argumente", "identifizieren-aussagesätze", "definieren-argument", "definieren-gültigkeit", "definieren-schlüssigkeit", "kennen-aufbau-beweis", "beweise-metasprache", "definieren-logische-folgerung", ), "AL": ( "identifizieren-al-strukturen", "identifizieren-hinr-notw-bed", "entwickeln-gefühl-al-syntax", "erkennen-suchen-schemata", "bilden-ausdrücke-schemata", "identifizieren-junktoren", "formalisieren-al", "formalisieren-wd-gdw-nur", "bilden-notw-hinr-äquivalenz", "erkennen-wahrheitsbedingungen", "definieren-semantik-junktoren", ), "WT": ( "darstellen-junktoren-wahrheitstabelle", "auswerten-ausdrücke-wahrheitstabelle", "beweisen-logische-wahrheit", "beweisen-logische-folgerung", "beweisen-logische-äquivalenz", "korrekte-beweisform", ), "KS": ( "aufbauen-kdns", "verstehen-direkte-regeln", "beweise-kdns-einfach", "wissen-raa-verfahren", "bilden-linke-beweisspalte", "beweisen-mittels-raa", "erkennen-konditionalisierung", "prüfen-abhängigkeiten", "beweisen-verzweigt", ), // PL "PL": ( "wissen-unterschied-al-pl", "formalisieren-pl-unquantifiziert", "formalisieren-pl-quantifiziert", "umrechnen-quantoren", "benennen-begriffe-log-quad", "finden-beispiele-log-quad", ), // PL KdnS "PK": ( "variablen-spezialisieren", "konstanten-generalisieren", "kennen-einschränkung-allq-einf", "kennen-einschränkung-exq-bes", ), ) )) #let get-goal(key, loc) = { let s = state("sequence-goals", (:)).final(loc) if s == none { return none } let zero-padding = str(calc.max(..s.goals .values() .map(e => e.len()) .flatten()) ).len() for k in s.goals.keys() { if key in s.goals.at(k) { let num = s.goals.at(k).position(e => e == key)+1 num = ("0" * (zero-padding - str(num).len())) + str(num) return ( k + str(num), goal-list.at(key) ) } } return none } #let set-sequence-goals-key(key) = state("sequence-goals", (:)).update(k => { k.current-key = key k }) #let get-all-goals(loc) = { let list = () for k in goal-list.keys() { list.push(k) } return list.map(e => { let goal = get-goal(e, loc) if goal != none { goal.at(0) } }) } #let format-goal-key(..keys) = text(fill: purple, math.equation(block: true, $mat(delim: "[", #block(width: 0.5cm, align(center, text(font: "Atkinson Hyperlegible", size: 0.6em, strong(keys.pos().join([\ ]))) ) ) )$)) #let print-goals-for-sequence() = locate(loc => { style(sty => { let s = state("sequence-goals", ()).at(loc) if s == none { return none } let goals = () let max-goal-size = calc.max(..get-all-goals(loc).map(e => measure(format-goal-key(e)+[,], sty).width)) for key in s.goals.at(s.current-key) { let goal = get-goal(key, loc) let goal-key = if goal != none { goal.at(0) } else { return text(fill: red, strong("\""+key+"\" NOT FOUND")) } goals.push(format-goal-key(goal-key)) goals.push(goal.at(1)) } grid(columns: (max-goal-size, 1fr), column-gutter: 0.5em, row-gutter: 1.5em, ..goals) })}) #let ref-goals(body) = { show ref: it => { let key = str(it.target) if key in goal-list { locate(loc => { style(s => { let max-goal-size = calc.max(..get-all-goals(loc).map(e => measure(format-goal-key(e+[,]), s).width)) let goal = get-goal(key, loc) let goal-key = if goal != none { goal.at(0) } else { return text(fill: red, strong("\""+key+"\" NOT FOUND")) } if it.supplement == none or it.supplement == auto { goal-key } else { grid(columns: (max-goal-size, 1fr), column-gutter: 1em, row-gutter: 1em, format-goal-key(goal-key), it.supplement) } })}) } else { it } } body } #let multi-goal-ref(body, ..goals) = locate(loc => { style(s => { let list = () let max-goal-size = calc.max(..get-all-goals(loc).map(e => measure(format-goal-key(e+[,]), s).width)) for key in goals.pos() { if key in goal-list { let goal = get-goal(key, loc) let goal-key = if goal != none { goal.at(0) } else { return text(fill: red, strong("\""+key+"\" NOT FOUND")) } list.push(goal-key) } } grid(columns: (max-goal-size, 1fr), column-gutter: 1em, row-gutter: 1em, format-goal-key(..list), body) })})
https://github.com/talal/ilm
https://raw.githubusercontent.com/talal/ilm/main/CHANGELOG.md
markdown
MIT No Attribution
# Changelog All notable changes to 'Ilm will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). <!--- The changes should be grouped using the following categories (in order of precedence): - Added: for new features. - Changed: for changes in existing functionality. - Fixed: for any bug fixes. - Deprecated: for soon-to-be removed features. - Removed: for now removed features. --> [unreleased]: https://github.com/talal/ilm/compare/v1.2.1...HEAD ## [Unreleased] ## 1.2.1 - 2024-08-06 ### Fixed - Avoid line break between link text and indicator (circle). ## 1.2.0 - 2024-08-01 ### Added - `external-link-circle` option for disabling circle next to external links. ## 1.1.3 - 2024-07-23 ### Fixed - Chapter page breaks when using headings inside of a page container. ## 1.1.2 - 2024-06-18 ### Changed - Improved template and `example.pdf`. ## 1.1.1 - 2024-05-04 ### Added - Language setting definition in template. ### Fixed - Removed hardcoded heading for table of contents so that the heading is defined as per Typst's language settings. ## 1.1.0 - 2024-04-11 ### Changed - Use _Libertinus Serif_ font, if available, otherwise fall back to _Linux Libertine_. ## 1.0.0 - 2024-04-09 ### Added - `date-format` argument for specifying custom date format. - `table-of-contents` argument for specifying custom `outline` function for the table of contents. ### Changed - Use dictionary for `figure-index`, `table-index`, and `listing-index` arguments and add title field for specifying custom title. - Create chapter page breaks inside `body` context. ## 0.1.3 - 2024-04-07 ### Fixed - Level 1 headings not being displayed on preface page due to page break inside heading `show` rule. ## 0.1.2 - 2024-03-25 ### Fixed - Check if a heading's `body` has a `text` field before using it. ## 0.1.1 - 2024-03-23 ### Added - Running footer demo in template and example. ### Changed - Footer chapter size from `0.65em` to `0.68em`. - Start bibliography on a new page regardless of whether `chapter-pagebreak` is set to `true` or not. ### Fixed - Use kebab-case for variable and function names. - Unnecessary `here()` parameter in `query()` usage. ## 0.1.0 - 2024-03-22 Initial Release.
https://github.com/Critik-V/resume-tmpl-typst
https://raw.githubusercontent.com/Critik-V/resume-tmpl-typst/main/links.typ
typst
MIT License
// for Link #let Link(l, label) = link(l)[#text(fill: black, underline(offset: 4pt,label))] // for Email #let Email(l) = link("mailto:" + l)[#text(fill: black, underline(offset: 4pt,l))]
https://github.com/xrarch/books
https://raw.githubusercontent.com/xrarch/books/main/documents/a4xmanual/chapintro.typ
typst
#import "@preview/tablex:0.0.6": tablex, cellx, colspanx, rowspanx = Overview The *A4X* firmware forms the contents of the boot ROM of XR/computer platforms.#footnote([See the _XR/computer Systems Handbook_ for more information.]) This is the first code that executes in the system after processor reset, and is responsible for initializing the integral devices and enabling the user to select a boot device. It is designed to be very simple. It executes entirely out of ROM, using a small region in low memory for volatile data. Virtual addressing is disabled and polling is used for all I/O. This document describes the user interface of the *A4X* firmware, and the fundamentals of its boot protocol, including an overview of the A3X partition table (APT) format. Implementation details of the firmware are not described here; they are best defined by the source code of the firmware itself.
https://github.com/Hobr/njust_thesis_typst_template
https://raw.githubusercontent.com/Hobr/njust_thesis_typst_template/main/page/content.typ
typst
MIT License
// 正文 #let showContent(content) = columns( 2, align(left, content), )
https://github.com/jomaway/typst-teacher-templates
https://raw.githubusercontent.com/jomaway/typst-teacher-templates/main/ttt-utils/README.md
markdown
MIT License
# ttt-utils `ttt-utils` is the core package of the [typst-teacher-tools collection](https://github.com/jomaway/typst-teacher-templates). ## Modules It contains several modules: - `assignments` contains functions for creating exams. - `components` contains useful visual components such _lines_ or _caro pattern_, _tags_, etc ... - `grading` contains functions for grading exams. - `helpers` contains some utility functions. - `layout` contains some layout functions such as _side-by-side_, etc... - `random` contains a function to shuffle an array. ## Usage You can import the modules you need with: ```typst #import "@preview/ttt-utils:0.1.0": components ``` then you can access the modules function with: `#components.lines(4)` or `#components.caro(5)`, ... or import the wanted functions: ```typst #import "@preview/ttt-utils:0.1.0": components, assignments #import assignments: assignment, question, answer #import components: caro as grid_pattern // Add a question. #assignment[First assignment #question[ #answer(field: grid_pattern(5)) ] ] ``` ## Similar projects - [scrutinize](https://github.com/SillyFreak/typst-packages/tree/main/scrutinize) by [SillyFreak](https://github.com/SillyFreak): Package to create exams, very similar to the `assignment` module, but only questions without assignments, and a bit more low level. I adopted a few of his ideas. ## CHANGELOG See [CHANGELOG.md](../CHANGELOG.md)
https://github.com/hash-roar/typst-math-template
https://raw.githubusercontent.com/hash-roar/typst-math-template/main/typst_simple_thesis/main.typ
typst
#import "./template.typ": * #show: project.with( title: "A Simple Template For Homework", authors: ( (name: "<NAME>", email: "<EMAIL>"), ), // Insert your abstract after the colon, wrapped in brackets. // Example: `abstract: [This is my abstract...]` date: "April 2, 2023", ) #let inline_code(text)={ box( fill: luma(230), outset: 2pt, radius: 2pt, text, ) } // We generated the example code below so you can see how // your document will look. Go ahead and replace it with // your own content! = Introduction #lorem(60) == In this paper #lorem(20) #incline_code("hello world") === Contributions #lorem(40) = Related Work #lorem(50) #block( fill: luma(230), outset: 4pt, radius: 4pt, lorem(30), )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/optimal-ovgu-thesis/0.1.0/abstract.typ
typst
Apache License 2.0
#import "components.typ": body-font, variable-pagebreak #let oot-abstract(lang: "en", is-doublesided: none, body) = { set text(lang: lang) v(0.1fr) align(center, text( font: body-font, 1em, weight: "semibold", if lang == "de" [Zusammenfassung] else [Abstract], )) linebreak() text(body) v(1fr) variable-pagebreak(is-doublesided) }
https://github.com/evgenymng/pl-exam
https://raw.githubusercontent.com/evgenymng/pl-exam/main/paper.typ
typst
MIT License
#set page( paper: "a4", margin: (x: 1.5cm, y: 1.5cm), ) #set par( justify: true, ) #set text( size: 12pt ) #set heading( numbering: "1.", supplement: [Разделе] ) #show raw: set block( above: 1em, below: 2em, ) #let clr-caption = rgb("777777") #let que = [*(?)*] #let cred(url) = link( url, text( fill: blue )[ \[cred\] ], ) #let caption(body) = text(fill: clr-caption)[ #par[ #body ] ] #align(center)[ #text(18pt)[*Материалы по языкам программирования*] Январь 2024 ] = Динамическое окружение #caption[ Понятие динамического окружения. Порядок формирования и использования динамического окружения. ] *Динамическое окружение* #sym.dash.em окружение, в котором присутствует структура данных, связывающая имена переменных с их значением во время выполнения очередной инструкции. Рассмотрим пример формирования динамического окружения на языке _SML_. В примере упростим представление динамического окружения до массива, содержащего пару "имя переменной" #sym.arrow.l.r "значение". Функции будем связывать с их замыканиями: ```sml val x = 2 (* [(x, 2)] *) val y = x + 3 (* [(y, 5), (x, 2)] *) val z = x + y (* [(z, 7), (y, 5), (x, 2)] *) (* #[(x, 49), (z, 7), (y, 5), (x, 2)] произошло затенение *) val x = z * z (* [(x, 49), (z, 7), (y, 5), (x, 2)] в let создается временное динамическое окружение *) val z = let val x = 7 (* [(x, 7), (x, 49), (z, 7), (y, 5), (x, 2)] *) val d = 1 (* [(d, 1), (x, 7), (x, 49), (z, 7), (y, 5), (x, 2)] *) in z + x + d (* [(z, 15), (d, 1), (x, 7), (x, 49), (z, 7), (y, 5), (x, 2)] *) end (* [(z, 15), (x, 49), (z, 7), (y, 5), (x, 2)] *) (* [(e, -10), (z, 15), (x, 49), (z, 7), (y, 5), (x, 2)] *) val e = z - 25 (* [(x, 3), (e, -10), (z, 15), (x, 49), (z, 7), (y, 5), (x, 2)] *) val x = 3 (* [(f, [x], x + 25, [(x, 3), ...]), (x, 3), (e, -10), (z, 15), (x, 49), (z, 7), (y, 5), (x, 2)] *) fun f x = x + 25 ``` Функция в динамическое окружение записывается в виде замыкания: #align(center)[ ```text [форм. параметры], тело, [копия текущего окружения]``` ] Здесь отражён основной принцип формирования динамического окружения. Он не идеален, и существует множество других более эффективных реализаций. #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14597#p28625") = Абстракции #caption[ Что понимается под терминами "Абстракция данных", "Абстракция процессов"? Что значит "построение абстракций"? Что такое "Барьеры абстракций"? За счет чего обеспечивается абстрагирование? ] *Абстрагирование* #sym.dash.em процесс удаления характеристик чего-либо с целью сведения его к набору существенных элементов. *Абстракция данных* #sym.dash.em сведение набора данных к упрощенному представлению целого. *Абстракция процессов* фокусируется на сокрытии деталей реализации процесса или алгоритма и предоставлении упрощенного интерфейса для его запуска (*методы*). Это позволяет инкапсулировать набор операций в единую сущность. Причём пользователь объекта не обязан знать реализацию метода. *Построение абстракций* #sym.dash.em процесс компоновки техник абстракции данных и абстракции процессов для постоения одной абстрактной сущности #sym.dash.em объекта или класса. #que *Барьеры абстракций* #sym.dash.em те высокоуровневые операции, которые предоставлены пользователю создателями класса. Нарушение барьера абстракций #sym.dash.em использование низкоуровневых методов и полей, когда имеются более высокоуровневые, выполняющие ту же задачу. В объектно ориентированных языках программирования абстракция реализована через понятия классов и объектов (абстрагирование данных). Она используется для того, чтобы скрывать низкоуровневые детали компонентов программы, содержащих логику, что позволяет упростить процесс разработки. В ООП приложения строятся вокруг объектов и *сообщений*, с помощью которых объектам можно подавать сигнал на изменение внутреннего состояния или запрашивать информацию о нём (абстрагирование процессов). Пример на языке _Ruby_: ```rb class Point attr_accessor :x, :y def initialize(x, y) @x = x @y = y end def move(dx, dy) @x += dx @y += dy end end # абстракция данных: передаем данные о точке одним объектом def diag_move(p, v) p.move(v, v) end p1 = Point.new(x, y) # абстракция процесса p1.move(4, 7) # нарушение барьера абстракций p1.x += 10 p1.y += 11 ``` = Рекурсивный и итерационный процесс #caption[ Рекурсивный и итерационный процесс. Хвостовая рекурсия. Преимущества хвостовой рекурсии над нехвостовой. Преимущества нехвостовой рекурсии над хвостовой. ] *Рекурсия* #sym.dash.em это функция, которая вызывает саму себя, но с другими значениями параметров. *Рекурсивный процесс* #sym.dash.em это процесс вызова рекурсивной функции, при котором состояние вызывающей функции сохраняется в памяти до момента, пока не будет известен результат вызываемой функции. *Итерационный процесс* #sym.dash.em процесс вызова рекурсивной функции без сохранения в памяти состояния вызывающей функции. Функции, где рекурсивный вызов является последней выполняемой операцией называются *функциями с хвостовой рекурсией*. == Две реализации функции вычисления факториала на языке _SML_ С хвостовой рекурсией: ```sml fun fact (n, acc) = if (n < 1) then acc else fact (n - 1, n * acc) ``` Без хвостовой рекурсии #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14588#p28648"): ```sml fun fact n = if (n < 1) then 1 else n * fact (n - 1) ``` Одним из основных преимуществ хвостовой рекурсии является меньший расход памяти, а нехвостовой #sym.dash.em наглядность выполнения операций и меньшая громоздкость кода. == Хвостовая рекурсия в языках с ленивой моделью вычислений Хвостовая рекурсия может быть неприемлема в языках, где присутствуют ленивые вычисления. Рассмотрим пример на языке _Haskell_: ```hs -- без хвостовой рекурсии fromTo n m = n : xs where xs = if n >= m then [] else fromTo (n + 1) m -- с хвостовой рекурсией fromTo' n m = fromToTmp [] m where fromToTmp acc m' = if m' < n then acc else fromToTmp (m' : acc) (m' - 1) nth l n = if n == 0 then head l else nth (tail l) (n - 1) ``` Вызов ```hs nth (fromTo 5 2000000) 5``` завершится за приемлемое время. Но ```hs nth (fromTo' 5 2000000) 5``` нет. Так происходит потому, что в ``` fromTo ``` результат может быть вычислен до СГНФ, и `nth` сможет выполнить операцию почти моментально. А в `fromTo'` сначала должен создаться полный список, и только потом `nth` сможет извлечь из него значение. = Модели вычислений #caption[ Модели вычислений: аппликативные вычисления, нормальный порядок вычислений. ] *Аппликативные вычисления* #sym.dash.em стратегия вычисления, при которой сначала вычисляются аргументы функции (значения фактических параметров), потом вызывается сама функция. Проблема таких вычислений #sym.dash.em выражения могут быть невычислимы. *Нормальные вычисления* #sym.dash.em стратегия вычисления, при которой сначала вызываются все функции до тех пор, пока выражение не будет упрощено до элементарных операций, потом вычисляется полученное упрощенное выражение (подстановка аргументов в функции, пока не дойдем до элементарных операций). Проблема таких вычислений #sym.dash.em возможны повторные вычисления. Пусть на некотором языке заданы функции: ```sml fun sq x = x * x fun f (x, y) = sq x + sq y ``` Если бы язык имел аппликативную модель вычислений, то вызов ``` f (1 + 2, 2)``` разрешился бы как: ``` f (1 + 2, 2) f (3, 2) sq 3 + sq 2 (op +) (sq 3) (sq 2) (op +) (3 * 3) (sq 2) (op +) 9 (sq 2) (op +) 9 (2 * 2) (op +) 9 4 13 ``` А если бы нормальную модель, то так #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14589#p28694"): ``` f (1 + 2, 2) (op +) (sq (1 + 2)) (sq 2) (op +) ((1 + 2) * (1 + 2)) (sq 2) (op +) ((1 + 2) * (1 + 2)) (2 * 2) (op +) (3 * (1 + 2)) (2 * 2) (op +) (3 * 3) (2 * 2) (op +) 9 (2 * 2) (op +) 9 4 13 ``` = Объекты первого класса <first-class-citizens> #caption[ Понятие "Объект первого класса". Примеры сущностей, являющихся и не являющихся объектами первого класса. ] *Объект первого класса* #sym.dash.em сущность языка программирования, которую можно: + Передавать в качестве аргумента. + Возвращать в качестве результата. + Связывать с именем. + Сохранять как элемент сложной структуры данных. + Проверять на равенство. Сущность может принадлежать, либо не принадлежать объектам первого класса #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14590#p28623"). Например, в _SML_ объектами 1-го класса будут: - функции; ```sml fun add (x, y) = x + y val myFunction = add ``` - значения (включая сложные структуры данных); ```sml val x = 42 val myList = [1, 2, 3] ``` - записи; ```sml type person = { name: string, age: int } val john = { name = "John", age = 30 } ``` - типы данных. ```sml datatype 'a tree = Empty | Node of 'a * 'a tree * 'a tree val myTree = Node(1, Node (2, Empty, Empty), Node (3, Empty, Empty)) (* использование Empty как аргумента конструктора Node *) ``` В _Ruby_, например, следующие сущности будут принадлежать 1-му классу: - объекты; ```rb x = 42 def add(x, y) x + y end my_function = method(:add) ``` - `Proc` и `Proc`-лямбды ```rb x = -> (x) { x + 5 } ``` - идентификаторы; ```rb my_symbol = :example ``` - массивы и хэши; ```rb my_array = [1, 2, 3] my_hash = { key: 'value' } ``` - классы и модули. ```rb class MyClass # ... end my_class = MyClass.new ``` На самом деле в _Ruby_ всё, что является объектом #sym.dash.em объект 1-го класса. А к объектам относится всё вышеперечисленное. К объектам в _Ruby_ не относятся блоки: им нельзя присвоить имя или сохранить в переменную без перевода в объект класса `Proc`. С ними нельзя делать ничего, кроме как передать в функцию. = Функции как объекты первого класса #caption[ Функции как объекты первого класса на примере языка _Standard ML_. ] _SML_ #sym.dash.em функциональный язык программирования, поэтому функция в нём является объектом первого класса. Приведём примеры такого поведения функции. #list(tight: false)[ Возврат функции в качестве результата в зависимости от значения аргумента #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14591#p28629"): ```sml fun realFun a = if a > 0 then Math.cos else Math.sin ``` ][ Передача `f` в качестве аргумента в функцию `apply` и возврат результата применения этой функции к значению: ```sml fun apply f = f 3.0 ``` ][ Переменным можно присваивать функции: ```sml fun f x = 5 + x val g = f val z = g 4 val k = f 4 ``` ][ Сохранение в список: ```sml val l = [ Math.sin, Math.cos ] ``` ][ Проверка на равенство: ```sml val f = Math.sin val g = Math.cos f = g ``` ] = Затенение #caption[ Что такое затенение? В чем заключается его механизм? ] *Затенение* #sym.dash.em объявление идентификатора, который уже существует в окружении. Таким образом, доступ к прежнему значению идентификатора невозможен, поскольку невозможно разрешить неоднозначность между "старым" (возможно, несколькими старыми) и "новым" значениями данного идентификатора #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14592#p28627"). Пример: ```sml val x = 5 val y = 4 val x = 12 (* (x, 5) затенено в данном окружении *) ``` В функциях _SML_ будет использоваться то значение, которое было первым в динамическом окружении при объявлении функции: ```sml val x = 5 val x = "text" fun f s = x ^ s f "more" ``` = Лексика, синтаксис, семантика #caption[ Лексика, синтаксис, семантика. Что есть что. В частности, в отношении языка программирования. ] *Лексика* #sym.dash.em словарный состав языка, совокупность слов ("лексем") конкретного языка. Включает в себя: - *ключевые слова* #sym.dash.em предварительно определенные идентификаторы, имеющие особое синтаксическое значение (`for`, `while`, `if`, `else`, ...); - *литералы* #sym.dash.em безымянные константы, являющиеся фиксированными значениями (`23`, `-8`, `"abc"`, `7e-8`, ...); - *идентификаторы* #sym.dash.em имена, задаваемые в программе для переменных, типов и функций (`a2`, `abc`, `zlp`, ...); - *разделители* #sym.dash.em используются для отделения друг от друга (разделения) лексем языка (#sym.dot.c (пробел), #sym.arrow.r.curve (переход на новую строку), ...); - *ограничители* #sym.dash.em лексемы, использующиеся для группировки выражений. Например, ограничителями являются `{` `}` в _C++_ или `(` `)` в _Lisp_. *Синтаксис* #sym.dash.em правила построения языковых конструкций. Он описывает форму, последовательность символов, которая составляет синтаксически правильную программу. *Семантика* указывает, имеет ли смысл в контексте данного языка программирования синтаксически верная конструкция. Семантика бывает, в частности: - литерала: задаёт какое-то значение; - идентификатора: обращается к динамическому окружению; если найдена связь идентификатора с некоторым значением из динамического окружения, значит под этим идентификатором скрывается значение, которое нашли; иначе #sym.dash.em семантическая ошибка; - выражения: рассмотрим `v1 + v2`; проверяем, для каких типов определен оператор `+`. Если не нашлось оператора, принимающего объекты данных типов #sym.dash.em семантическая ошибка. Иначе подставляем результат операции вместо `v1 + v2` #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14593#p28634"). = Контейнеры #caption[ Что понимается под термином "Контейнер"? Какие стандартные контейнеры вы знаете? Какие средства для описания новых контейнеров существуют? ] *Контейнер* — структура, заключающая в себе другие элементы, относящиеся к тому же или к другому типу. == Частые контейнеры в _SML_ === `option` ```sml datatype 'a option = NONE | SOME of 'a ``` `NONE` является конструктором, олицетворяющим пустое значение (_ничего_), `SOME` #sym.dash.em конструктор, инкапсулирующий в точности одно значение (_один элемент_). ```sml val a = NONE val b = SOME 5 (isSome a, isSome b) (* val it = (false, true) : bool * bool *) valOf b (* val it = 5 : int *) valOf a (* uncaught exception Option *) ``` - `isSome` #sym.dash.em функция, возвращающая `true`, если аргумент является `SOME`; - `valOf` извлекает значение из `option`. Если аргумент является `NONE`, то поднимается исключение `Option`. === Кортеж Кортеж хранит в себе декартово произведение каких-то значений. Это контейнер, хранящий ровно $n$ элементов любых типов. ```sml val p = (5, 2.5) #1 p (* val it = 5 : int *) #2 p (* val it = 2.5 : real *) ``` === Список ```sml datatype 'a list = nil | :: of 'a * 'a list ``` Список #sym.dash.em контейнер, который может в любой момент времени хранить $>= 0$ элементов. В частности, в _SML_ все элементы списка должны быть одного типа. ```sml val l1 = [1, 2, 3] val l2 = l1 @ [3, 4] hd l1 (* val it = 1 : int *) tl l1 (* val it = [2,3] : int list *) ``` === Запись Запись #sym.dash.em набор в точности из $n$ полей, у каждого из которых есть имя и тип #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14594#p28695"). ```sml val z = {name = "Anna", age = 25}; (* val z = {age=25,name="Anna"} : {age:int, name:string} *) #name z (* "Anna" : string *) ``` = Классы в Haskell #caption[ Классы в _Haskell_. Что означает термин? Что может относиться к классу и что гарантирует факт такой принадлежности? ] *Класс в _Haskell_* обозначает, что при отношении типа `A` к классу `Cl`, для типа `A` разрешены операции, описанные в классе `Cl`. К классу могут относиться любые типы, в том числе и созданные пользователем. Более точно классы в _Haskell_ называются *классами типов данных* (они же ваши `trait` в _Rust_, только с неявным преобразованием типов). Классы типов с иерархией наследования напоминают интерфейсы в классических императивных языках программирования. Синтаксис объявления класса: ``` class <Имя класса> <типовая переменная> where <op1> :: <сигнатура1> <op2> :: <сигнатура2> ... ``` Эта концепция позволяет создавать математические абстракции: класс эквивалентности, порядка, предпорядка. У переменных класса существуют, так называемые, *требования* или *ограничения*: ``` instance (SomeType a, ...) => Class (Type (a, b, c, ...)) where op1() = ... -- определение операций, объявленных в классе, для данного типа op2() = ... op3() = ... ... ``` Здесь для того, чтобы `Type (a, b, c, ...)` можно было отнести к классу `Class` нужно, чтобы `a` относился к классу `SomeType`. Это составляет необходимый функционал для обращения с полиморфными сущностями. *Фактом принадлежности типа к классу* является удовлетворение всем операциям класса, т.е. для того, чтобы тип `A` стал относится к классу `Cl`, для типа `A` необходимо определить все операции, описанные в классе `Cl` #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14595#p28715"). = Полиморфные типы #caption[ Что такое "полиморфный тип"? Каким образом можно определить полиморфный тип? Что такое "Переменная типа"? ] *Переменная типа* #sym.dash.em переменная, вместо которой можно записать любой тип. Рассмотрим пример: ```sml map :: (a -> b) -> [a] -> [b] ``` Здесь вместо переменной `a` можно подставить любой тип: `Int`, `Double`, `Bool`, `String`. При этом одинаковые типовые переменные означают, что при передаче аргументов в функцию на этих местах должны быть одинаковые типы. `(a -> b)` #sym.dash.em тип, обозначающий сигнатуру функции. При объявлении типа в _Haskell_ используется следующий синтаксис: ```hs data MyType <переменные типа> = ... -- Конструктор типа #1 | ... -- Конструктор типа #2 | ... -- ... ``` Блок переменных типа необязателен. Но если таковые будут указаны, то новый тип станет *полиморфным*. Полиморфизм типа заключается в том, что его экземпляры могут создаться по-разному в зависимости от того, какие типы были у аргументов конструктора. Пример: ```hs data MyList a = Cons (a, MyList a) | Null ``` В данном случае объявляется тип (список), аргументом которого является типовая переменная `a`. Это значит, что вместо неё может быть абсолютно любой тип #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14596#p28716"). При этом вторым элементом в конструкторе `Cons` обязан быть экземпляр `MyList a`: - либо `Null`; - либо `Cons a`, где `a` #sym.dash.em тип данных элементов списка. = Статическое окружение #caption[ Статическое окружение. Что это такое? Каков порядок его формирования? Время жизни? ] *Статическое окружение* (*лексическое окружение*) #sym.dash.em окружение, в котором метса, где может использоваться переменная, определяются лексической структурой программы. Статическое окружение *формируется на стадии компиляции* программы. В результате в программе пропадает необходимость в именах переменных, так как на каждом этапе выполнения программы точно известно, к какой переменной будет производиться обращение. *Порядок формирования:* статическое окружение формируется в порядке физического расположения кода (наверное, можно сказать, построчно), в отличие от динамического окружения, которое формируется по ходу выполения программы. Отсюда следует, что такое окружение "*живёт*" до тех пор, пока программа не будет скомпилирована. = Формы результата вычислений на Haskell #caption[ В каких формах может быть представлено значение выражения на _Haskell_? Какой смысл каждой из таких форм? ] Выражение на _Haskell_ может быть представлено в четырех формах: + *Нормальная форма* (НФ) #sym.dash.em полностью вычисленное выражение. Например, выражение `8` (обычная константа) полностью вычислено. + *Дно* (#sym.bot) #sym.dash.em выражение невычислимо. Например, бессмысленная бесконечная рекурсия вида `rec x = rec x` является примером дна. + *Невычисленное выражение* (thunk) #sym.dash.em обещание вычислить выражение. Это форма выражения, которое не использовалось в вычислениях и ещё не было вычислено. Изначально (до участия в вычислениях) к этому типу относится любое выражение, не являющееся константой. + *Слабая головная нормальная форма* (СГНФ) #sym.dash.em выражение частично вычислено до вызова каких-то конструкторов, параметрами которых могут быть выражения в НФ, thunk или СГНФ. Это выражения, которые были вычислены до определённого момента, а остальная часть выражения не требовалась, поэтому она может оставаться в форме thunk. Пример #sym.dash.em вычисление первых $n$ членов бесконечной последовательности #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14599#p28639"): ```hs nat = 1 : map (+1) nat take n l = if n = 0 then [] else head l : take (n - 1) (tail l) take 5 nat -- nat окажется в СГНФ, поскольку будут вычислены -- только первые 5 элементов массива nat ``` = Каррированные функции #caption[ Каррированные функции. Что это? О чем это? В чем отличия коррированной функции от некаррированной. ] *Каррированная функция* #sym.dash.em это функция $n >= 1$ аргументов, результатом которой является функция от $n - 1$ оставшихся аргументов. Рассмотрим пример на _SML_. Рассмотрим функцию `f1` с сигнатурой ```_sml_ ('a * 'b * 'c) -> 'd```: ```sml fun f1 (x, y, z) = x + y + z ``` С точки зрения языка это функция одной переменной #sym.dash.em кортежа из трёх элементов. Ту же функцию можно объявить в каррированной форме: ```sml fun f2 x y z = x + y + z ``` Сигнатура тогда будет ```_sml_ 'a -> ('b -> ('c -> 'd))```. *Отличие* каррированной функции будет проявляться при ее вызове. Можно передавать не все аргументы. Тогда значения переданных параметров "сохранятся" до вычисления итогового результата (они запишутся в замыкание, возвращаемое каррированной функцией). Если попытаться передать не все параметры некаррированной функции, получится ошибка несоответствия типов кортежей #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14600#p28624"). = Полиморфные функции #caption[ Что такое полиморфная функция. Способы определения полиморфных функций. В чем отличие полиморфной функции от перегруженной? ] *Полиморфная функция* #sym.dash.em функция, способная между различными своими вызовами принимать и возвращать значения многих типов. В _SML_ есть два способа *определения полиморфной функции*: + Пользуясь переменными типа (`'a`, `'b`, ...). Статическая система типизации, при отсутствии ограничений, по умолчанию всем аргументам и возвращаемым значениям присваивает наиболее широкий полиморфный тип: ```sml fun f1 x = x (* val f1 = fn : 'a -> 'a *) ``` + Используя по отношению к аргументам другие полиморфные функции. В этом случае система неявной типизации может додумать как наиболее широкий тип (`'a`, `'b`, ...), так и наложить возможные ограничения на полиморфный тип (всё равно оставив его полиморфным): ```sml fun f2 xs = length xs + 1 (* val f2 = fn : 'a list -> int *) ``` #grid( columns: (1fr, 1fr), column-gutter: 2em, [ *В полиморфизме* функция обобщена для работы с разными типами данных. Типы определяются динамически в процессе выполнения программы. Типы аргументов и возвращаемого значения могут быть переменными (типовыми переменными), а не конкретными. ], [ *В перегрузке* функции могут иметь одинаковые имена, но различные сигнатуры (типы аргументов и возвращаемого значения). Решение, какую функцию вызывать, принимается на этапе компиляции или во время разрешения ссылок. ], ) = Механизм вывода типов #caption[ Алгоритм Хиндли#(sym.dash.en)Милнера. Как работает механизм вывода типов? В чем его достоинства и недостатки? ] *Алгоритм Хиндли#(sym.dash.en)Милнера* #sym.dash.em это алгоритм для вывода типов значений на основании того, как они используются. Буквально, он формализует интуитивное представление о том, что тип может быть выведен из поддерживаемых им операций. *Вывод типов* #sym.dash.em возможность компилятора самостоятельно вывести тип значения у выражения. Впервые механизм вывода типов был представлен в языке _ML_, где компилятор всегда выводит наиболее общий полиморфный тип для всякого выражения. Компилятор _ML_ сам определяет тип данных из контекста, удовлетворяя поставленным ограничениям. Он восстанавливает пропущенную информацию о типах наименее строгим путем. == Пример 1 ```sml fun f x = let val (y, z) = x in (sqrt y) + z end f : T1 -> T2 (* f должна быть функцией; все функции принимают один аргумент *) x : T1 y : T3 z : T4 T1 : (T3 * T4) (* аргумент х должен соответствовать шаблону (y, z) *) T3 : real (* sqrt имеет тип real -> real *) T4 : real (* потому что мы складываем z с real *) T1 : (real * real) T2 : real ``` В итоге, функция `f` имеет сигнатуру ```_sml_ (real * real) -> real```. По умолчанию операции `>`, `<`, `+`, `-`, `*` приводят к тому, что аргументы определяются как целочисленные, но если эти же аргументы встречаются в выражении с операцией `/`, то тип определяется как вещественный. == Пример 2 При определении функции по шаблонам тип данных, возвращаемый функцией, как и в примерах выше, определяется по наиболее общему полиморфному типу выражения, находящегося в каком-либо шаблоне функции: ```sml fun g (x, y, 0) = x + y | g (x, y, z) = x / y g : T1 * T2 * T3 -> T4 x : T1 y : T2 z : T3 ``` Так как при определении первого шаблона функции на месте третьего аргумента стоит `0`, ```sml T3 : int ``` Выражение `x + y` в этом же шаблоне по умолчанию относятся к типу `int`. Но так как в следующем определении шаблона вычисляется выражение `x / y`, аргументы которого относятся к типу `real` (и результат имеет тип `real`), который является менее общим, то этот тип и будет являться возвращаемым. В итоге: ```sml T1 : real T2 : real T4 : real ``` И функция `g` будет иметь сигнатуру ```_sml_ (real * real * int) -> real```. == Пример 3 ```sml fun h (x, y) = if x = y then 1 else 0 h : T1 * T2 -> T3 x : T1 y : T2 T3 : int (* функция возвращает либо 1, либо 0, что является значением типа int *) ``` В теле функции используется выражение, сравнивающее `x` и `y` на равенство, поэтому `x` и `y` могут быть любого типа данных, допускающего операцию *полиморфного равенства* (обозначается `''a`). Таким образом: ```sml T1 : ''a T2 : ''a ``` И `h` будет иметь сигнатуру ```_sml_ ''a * ''a -> int``` #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14602#p28696"). = Двумерный синтаксис #caption[ Что это такое? В чем отличия двумерного синтаксиса от одномерного? ] *Двумерный синтаксис* #sym.dash.em синтаксис, управляющими конструкциями которого являются отступы. Это значит, что на семантическое значение влияет не только то, в каком порядке слева направо написан код, но также и то, как это расположено относительно друг друга в вертикальной плоскости (на одном отступе или разных) #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14603#p28640"). Отступ в двумерном синтаксисе означает, что конструкция, начатая на предыдущей строке, продолжена на данной. На практике одномерный синтаксис означает, что любую программу можно написать в одну строку. = Модули #caption[ Что такое модуль. В чем преимущество модульного программирования? Как определяются модули на _Standard ML_. ] Когда размер программы достигает нескольких тысяч строк, возникают следующие проблемы: + Рассмотрение программы как единого набора подпрограмм не обеспечивает хорошего уровня организации программы и управления ею. + Для больших программ продолжительность повторной компиляции становится значительной. Решить эти проблемы можно, разделив программу на модули #sym.dash.em синтаксические контейнеры, содержащие группы логически связанных подпрограмм и данных. Свойство *функциональной законченности* каждого модуля позволяет абстрагироваться от деталей реализации и проще понимать программу, а отсутствие необходимости повторной компиляции уже скомпилированного модуля решает оставшуюся проблему. *Модуль* #sym.dash.em это последовательность логически связанных функционально законченных фрагментов, оформленных как отдельная часть программы. *Назначение модульного программирования* #sym.dash.em скрытие реализации и определение области видимости переменных для пользователя. Различают интерфейсную (подпространство пространства имён, доступное пользователю) и инкапсулированную части модуля. *Преимущества модульного программирования*: - упрощение групповой разработки программы; - возможность корректировки модуля без затрагивания остальной системы; - уменьшение времени перекомпиляции при внесении изменений; - уменьшение объема занимаемой памяти программы за счет сокращения количества повторений кода; Определение модулей на _SML_: #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14604#p28698") ```sml signature TM = sig val h : int -> int val f1 : int -> int -> int val f2 : int -> real -> real end (* : не скрывает от пользователя объявления, не входящие в определение сигнатуры *) (* :> скрывает *) structure M : TM = struct fun h x = x * x + 25 fun f1 x y = h x * h (3 * y) fun f2 x y = real (h x) + y end ``` = Ленивые и энергичные вычисления #caption[ В чем заключается механизм ленивых вычислений? Отличия аппарата ленивых и энергичных вычислений. ] *При ленивых вычислениях* (например, в _Haskell_) выражение не вычисляется, пока оно не понадобится. *При энергичных вычислениях* (например, в _Lisp_) происходит вычисление всех выражений до тех пор пока они не будут вычислены полностью. Ленивые вычисления позволяют создавать бесконечные последовательности и работать с ними, например: ```hs nat = 1 : map (1+) nat main = print (take 5 nat) ``` В языках с энергичными вычислениями придётся самостоятельно откладывать вычисления элементов бесконечной последовательности с помощью лямбда-функций. = Мемоизация #caption[ Что такое мемоизация. Для чего она применяется? ] *Мемоизация* #sym.dash.em это техника оптимизации, которая заключается в сохранении результатов выполнения метода для заданных входных данных и возврате сохраненного результата при повторном вызове метода с теми же входными данными. Это позволяет избежать повторных вычислений и улучшить производительность. *Мемоизация применяется* для общего ускорения исполнения программы, оптимизации рекурсивных функций. Пример на _Ruby_ #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14607#p28638"): ```rb class Fibonacci def initialize @memo = {} end def fib(n) return n unless n > 1 return @memo[n] if @memo.key?(n) # проверяем, есть ли результат в кэше result = fib(n - 1) + fib(n - 2) # если результат не найден, вычисляем его рекурсивно @memo[n] = result # сохраняем результат в кэше для последующих вызовов result end end ``` = Способы передачи параметров #caption[ Передача параметров по ссылке и по значению. ] В случае передачи параметров *по значению* значение переменной копируется в параметр функции. Изменения внутри функции не влияют на первоначальное значение. При передаче параметра *по ссылке* функция получает доступ к оригинальному значению переменной, и изменения внутри функции отражаются на этом значении. #que *Пример* = Перегрузка функций. Динамическая диспетчеризация <dynamic-disp> #caption[ Перегрузка функций в привязке к объектно-ориентированному программированию на примере _Ruby_. Динамическая диспетчеризация. ] В _Ruby_ нет *перегрузки функций*. Но есть другой механизм, не уступающий по возможностям перегрузке, и позволяющий писать более "правильный" с точки зрения ООП код. *Динамическая диспетчеризация* означает выбор конкретной реализации метода во время выполнения программы в зависимости от типа объекта, к которому применяется этот метод. Пример динамической диспетчеризации на _Ruby_: ```rb # родительский класс class Animal def speak puts "Animal speaks" end end # дочерний класс class Dog < Animal def speak puts "Woof" end end # дочерний класс class Cat < Animal def speak puts "Meow" end end # динамическая диспетчеризация animals = [Animal.new, Dog.new, Cat.new] animals.each do |animal| animal.speak end ``` Для нас не имеет значения, к какому классу относится каждый из элементов списка, до тех пор, пока у них есть метод `speak`, принимающий $0$ обязательных параметров. _Ruby_ во время исполнения сам определит тип каджого объекта и вызовет соответствующую реализацию метода. = Макросы #caption[ Что это? Как описать макрос? Протечки макросов. ] *Макросы* это инструмент генерации и преобразования исходного текста программы. В _Lisp_, в частности, макросы позволяют генерировать и преобразовывать код во время препроцессинга. Макрос в _Lisp_ определяется с помощью ключевого слова `defmacro`. Оно принимает список аргументов и тело макроса #sym.dash.em неявный список. Пример создания макроса в _Lisp_: ```lisp (defmacro double (x) `(* 2 ,x)) ``` При написании макроса нужно следить за следующими *протечками*: #enum(tight: false)[ Поскольку макрос #sym.dash.em просто текстовые замены, нужно предусмотреть копирование одного и того же выражения в разные места программы. ```lisp (defmacro cube (x) `(* ,x ,x ,x)) # плохо (defmacro cube (x) # плохо, но лучше `(let (a ,x) (* a a a))) ``` ][ Другая проблема макроса: оперирование локальными именами. Что, если они совпадут с именами окружения? ```lisp (defmacro cube (x) # хорошо (let ((a (gensym))) `(let (,a ,x) (* ,a ,a ,a)))) ``` ][ Порядок вычисления выражений, переданных в качестве аргументов макросу. (Только при наличии побочных эффектов.) Чтобы избежать проблем, принято считать (и разработчикам, и пользователям макросов), что все аргументы макроса вычисляются слева направо в порядке появления в списке аругментов. ] = Статическая и динамическая типизация #caption[ Статическая и динамическая типизация. Определение. Примеры языков. Отличия. ] *Статическая типизация* #sym.dash.em вид типизации, при котором переменная, параметр подпрограммы или возвращаемое значение функции связывается с типом в момент объявления, и тип не может быть изменён позже (переменная или параметр будут принимать только значения заданного типа, функция #sym.dash.em возвращать значения только заданного типа). *Язык программирования со статической типизацией* #sym.dash.em это язык, в котором происходит предварительный анализ типов данных сущностей перед выполнением программы. Если при компиляции все проверки на соответствие типов пройдены, и программа выполняется корректно, то статическое окружение больше не нужно, и далее используется динамическое окружение. При *динамической типизации* переменная может изменять тип хранимого значения во время выполнения. Обычно это достигается путём хранения не просто значения, а пары: `[дескриптор типа, значение]`, благодаря чему интерпретатор может отслеживать изменения всех типов во время выполнения. Языки со статической типизацией: _C/C++_, _Java_, _SML_, _Haskell_, #text(fill: rgb("#ee7777"))[_Rust_]. Языки с динамической типизацией: _Lisp_, _Python_, _Ruby_, _JavaScript_ #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14618#p28633"). = Лексическое и динамическое связывание #caption[ Лексическое и динамическое связывание. Что это? В чем отличия? ] При *лексическом связывании* локальная область видимости функции ограничена текстом определения этой функции (имя переменной имеет значение внутри тела функции и считается неопределённым за его пределами). При *динамическом связывании* локальная область видимости ограничена временем исполнения функции (имя доступно, пока функция выполняется, и исчезает, когда функция возвращает управление вызвавшему её коду). Рассмотрим пример на _SML_: ```sml val x = 5 fun f x = let x = 3 in g x end fun g x = print (Int.toString x) ``` Если бы в _SML_ было динамическое связывание, то при вызове функции `f` и передаче управления `g` в ней значение `x` было бы равно `3`, поскольку локальные значения функции `f` распространялись бы на функцию `g`. Однако, так как связывание лексическое, значение `x` для функции `g` берётся из глобальной переменной `x = 5` (поскольку `g` не входит в лексическую область выполнения функции `f`). В этом заключается различие типов связывания #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14619#p28628"). = Наследование #caption[ Наследование на примере _Ruby_. ] *Наследование* #sym.dash.em это инструмент, позволяющий описать новый класс на основе уже существующего с частично или полностью заимствованной функциональностью. Чтобы не повторяться, пример наследования на _Ruby_ есть в @dynamic-disp. = Шаблоны (образцы) #caption[ Что такое шаблон с точки зрения программиста на Standard ML и Haskell? В чем заключается механизм сопоставления с образцом? Какие средства для работы с шаблонами вы знаете? ] В любом месте, где происходит связывание значения с именем, вместо имени можно использовать шаблон #sym.dash.em разложение данных по конструктору и присвоение новым именам. Тогда, если правая часть связывания сконструирована при помощи тех же конструкторов данных, именам будут присвоены значения соответствующих компонент правой части связывания. В качестве шаблона может быть использован символ `_` (джокер) или идентификатор, начинающийся на символ `_`. Тогда соответствующее место в шаблоне будет проигнорировано #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14608#p28697"). == _SML_ ```sml fun myFoldl (l, start, f) = case l of [] => start | x :: xs => myFoldl (xs, f (x, start), f) (* или *) fun myFoldl ([], start, _) = start | myFoldl (x :: xs, start, f) = myFoldl (xs, f (x, start), f) ``` == _Haskell_ ```hs myFoldl ([], start, _) = start myFoldl (x : xs, start, f) = myFoldl (xs, f (x, start), f) ``` = Идентификаторы #sym.dash.em объекты первого класса #caption[ Идентификаторы #sym.dash.em объекты первого класса: что это значит? Продемонстрировать на примерах. ] В некоторых языках (_Lisp_, _Ruby_) идентификаторы являются объектами 1-го класса. Это означает, что для них справедливы утверждения, упомянутые в @first-class-citizens. Идентификаторы в _Ruby_ начинаются с символа `:`. Например, `:apple`. В _Lisp_ идентификаторы получаются в результате вызова функции `quote` или более короткой записи: `'`. Например, `'apple`. = Исключения #caption[ Стандартные исключения. Описание собственных исключений. Поднятие исключения. "Перехват" исключения. ] *Исключение* #sym.dash.em специальный объект, который поднимается (выбрасывается), когда фрагмент программного кода сталкивается с проблемой, которая на данном уровне не может быть разрешена самостоятельно. Исключение сигнализирует вызывающей функции о том, что принимать решение о дальшейшем ходе программы предстоит ей. *Стандартные исключения* во многих языках программирования: целочисленное деление на $0$, выход за границы массива, или просто ошибка времени исполнения. Часто пользователь может определить собственные исключения, инкапсулирующую дополнительную информацию или измененный текст сообщения. Вызываемая подпрограмма имеет возможность "*поднять*" исключение, в то время как подпрограммы ниже по стеку вызовов могут его "*перехватить*" и обработать соответствующе. = Отражения #caption[ Отражения (reflections) на примере _Ruby_. ] *Отражения* #sym.dash.em инструменты языка, позволяющие получать динамическую информацию о среде исполнения и об объектах самого языка. Пример: ```rb a = "abc" a.class # String a.class.superclass # Object a.class.superclass.superclass # BasicObject ``` = Парадигмы программирования #caption[ Императивное и декларативное программирование. Функциональное, логическое, параллельное и объектно-ориентированное программирование. Факультативно: модульное программирование; событийно-ориентированное программирование. ] Там все расписано: #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14615#p28664"). = Инкапсуляция. Модификаторы доступа к элементам объекта #caption[ Инкапсуляция. Модификаторы доступа к элементам объекта. ] *Инкапсуляция* #sym.dash.em это принцип, согласно которому внутреннее представление объекта скрыто от внешнего мира, а взаимодействие с объектом осуществляется только через строго определенный интерфейс. Методы с модификатором `public` доступны из любого места. Все методы в классе по умолчанию являются `public`. ```rb class MyClass # по умолчанию public def public_method puts "This is a public method" end end ``` Методы с модификатором `private` могут быть вызваны только внутри класса ```rb class MyClass private # модификатор доступа private def private_method puts "This is a private method" end end. ``` Методы с модификатором `protected` могут быть вызваны только внутри класса и его подклассов. ```rb class Parent # родительский класс protected # модификатор доступа protected def protected_method puts "This is a protected method" end end class Child < Parent # дочерний класс def call_protected_method protected_method # наследует метод родительского класса end end ``` Для переменных объекта всё аналогично #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14616#p28636"). = Параметры функции/макроса #caption[ Формальные и фактические параметры. Описание параметров функции/макроса на _Lisp_. ] *Формальный параметр* #sym.dash.em идентификатор, указываемый при объявлении или определении функции, который будет содержать передаваемое снаружи при вызове значение. *Фактический параметр* #sym.dash.em значение, передаваемое в функцию при её вызове. == Описание параметров функции/макроса на _Lisp_ В списке формальных параметров можно указывать ключевые слова, которые позволяют в дальнейшем трактовать параметры функции по-разному. Ключевые слова: `&optional`, `&key`, `&rest` (при определении макросов вместо него используется ключевое слово `&body`), `&aux`. Если ключевое слово упоминается в списке формальных параметров, то оно относится ко всем параметрам, расположенным в списке после него до следующего ключевого слова или до конца списка, если такой отсутствует. Параметры, расположенные в списке до первого ключевого слова, являются *обязательными* параметрами функции. `&optional` указывает, что относящиеся к нему параметры являются *необязательными*, и при вызове для них можно не указывать фактические параметры. Тогда параметр связывается со значением по умолчанию, или, если оно отсутствует, со значением `nil`. `&rest` указывает, что количество фактических параметров описываемой функции может превосходить количество формальных параметров. С формальным параметром, расположенным в списке после слова `&rest`, связывается список всех значений фактических параметров, для которых не предусмотрено формального параметра. Поэтому после `&rest` может быть только один идентификатор, и не может быть других ключевых слов. `&key` служит для определения *ключевых параметров*. Ключевой параметр функции в _Lisp_ #sym.dash.em необязательный параметр для передачи значения, которому требуется указание соответствующего символьного ключа (ключевого слова). Символьный ключ для каждого ключевого параметра представляет имя формального параметра, перед которым поставлено двоеточие. Если при вызове функции ключевой параметр не указан, то он связывается со значением по умолчанию или, если оно отсутствует, с `nil`. Нельзя использовать в одном списке ключевые слова `&rest` и `&key`. `&aux` говорит, что перечисленные далее символьные имена не являются на самом деле параметрами функции, а являются её вспомогательными локальными переменными. Этим именам не могут быть сопоставлены фактические параметры. Но для них можно так же, как и для необязательных параметров, указать значения по умолчанию (начальные значения) #cred("https://course.sgu.ru/mod/forum/discuss.php?d=14621#p28632"). = Замыкание #caption[ Что такое замыкание? Из чего оно состоит? Когда и как формируется? Как используется? ] *Замыкание* #sym.dash.em это результат определения функции. *Замыкание состоит из следующих частей:* - её определения; - параметров функции; - копии динамического окружения в момент её определения. В динамическое окружение функция записывается в виде пары `[имя_функции, замыкание]`. Например, результат объявления функции `f` в динамическом окружении: ``` (f, (f x = a * x, [(a, 3)])) ``` *Замыкание формируется* в момент определения функции в программе (про каррированные функции тоже не забываем). *Замыкание используется для* вычисления значения вызова функции. Копия динамического окружения, сохраненного в замыкании, станет основой для временного динамического окружения, которое создастся при вызове функции. Кроме копии динамического окружения во временное окружение дописываются фактические параметры функции.
https://github.com/chubetho/THWS_Bachelor_Template
https://raw.githubusercontent.com/chubetho/THWS_Bachelor_Template/main/templates/abstract.typ
typst
#heading("Abstract", outlined: false) #lorem(150) #heading("Zusammenfassung", outlined: false) #[ #set text(lang: "de") #lorem(150) ] #pagebreak(weak: true)
https://github.com/tzx/NNJR
https://raw.githubusercontent.com/tzx/NNJR/main/yml.typ
typst
MIT License
#import "template.typ": resume, header, resume_heading, edu_item, exp_item, project_item, skill_item #let yml_personal(d) = { header( name: d.name, phone: d.phone, email: d.email, linkedin: d.linkedin, site: d.site ) } #let yml_education(d) = { resume_heading[Education] for edu in d { edu_item( name: edu.name, degree: edu.degree, location: edu.location, date: edu.date, ) } } #let yml_experience(d) = { resume_heading[Experience] for exp in d { exp_item( role: exp.role, name: exp.name, location: exp.location, date: exp.date, .. exp.points ) } } #let yml_projects(d) = { resume_heading[Projects] for proj in d { project_item( name: proj.name, skills: proj.skills, date: proj.date, ..proj.points ) } } #let yml_skills(d) = { resume_heading[Technical Skills] for skill in d { skill_item( category: skill.category, skills: skill.skills ) } } #let yml_resume(data) = { show: resume yml_personal(data.personal) yml_education(data.education) yml_experience(data.experience) yml_projects(data.projects) yml_skills(data.skills) }
https://github.com/topdeoo/NENU-Thesis-Typst
https://raw.githubusercontent.com/topdeoo/NENU-Thesis-Typst/master/pages/ackonwledge.typ
typst
//! 致谢页 #let acknowledgement( two-side: false, //! 本页参数 title: "致谢", outlined: true, body, ) = { pagebreak( weak: true, to: if two-side { "odd" }, ) [ #heading(level: 1, numbering: none, outlined: outlined, title) <no-auto-pagebreak> #body ] }
https://github.com/typst-community/guidelines
https://raw.githubusercontent.com/typst-community/guidelines/main/src/chapters/style/linebreaks.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/src/util.typ": * #import mantys: * = Linebreaks For documents with a lot of collaboration aided by version control such as git, consider using something similar to #text(eastern, link("https://sembr.org/")[Semantic Line Breaks]). Avoid hard-wrapping by the editor, as it makes diffs in #mode.mark harder to read. Typst will maintain the correct linebreaks in both cases. #do-dont[ ```typst Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nunc non blandit massa enim nec. Eu volutpat odio facilisis mauris. Velit euismod in pellentesque massa placerat duis ultricies lacus. ``` ][ ```typst Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nunc non blandit massa enim nec. Eu volutpat odio facilisis mauris. Velit euismod in pellentesque massa placerat duis ultricies lacus. ``` ] #wbox[ Semantic Line Breaking cannot be used for chinese markup at the moment. ]
https://github.com/wjwei-handsome/personal_poster_typst
https://raw.githubusercontent.com/wjwei-handsome/personal_poster_typst/main/poster.temp.typ
typst
// define a template, just edit body in your own way. #let poster( // The poster's title. title: "Paper Title", // A array of authors, a dict as inner like: (name:"<NAME>", staff:"1,2"). authors: (), // A array of departments, a dict as inner line: (id: "1", name: "Insitute Name") departments: (), // University logo. univ_logo: "Logo Path", // Team or Lab logo. team_logo: "Team logo path", // Footer center text. // For instance, Name of Conference, Date, Location. footer_center_text: "Footer Text", // Footer left text. Just DIY footer_left_text: "Footer Left DIY", // Footer right text. Usually emails. footer_right_text: "<EMAIL>", // Fill color of the footer. footer_color: "Hex Color Code", // Number of columns in the poster. num_columns: "2", // body font size. body_font_size: "30", // body_font, default: Scientific and Technical Information Exchange body_font: "STIX Two Text", // paragragh spacing. body_spacing: "1", // Poster title's font size (in pt). title_font_size: "72", // Authors' font size (in pt). authors_font_size: "28", // Footer's URL and email font size (in pt). footer_left_text_font_size: "30", // Footer's text font size (in pt). footer_center_text_font_size: "40", // The poster's content. body ) = { // Set the body font. set text(font: body_font, size: int(body_font_size) * 1pt) title_font_size = int(title_font_size) * 1pt authors_font_size = int(authors_font_size) * 1pt num_columns = int(num_columns) footer_left_text_font_size = int(footer_left_text_font_size) * 1pt footer_center_text_font_size = int(footer_center_text_font_size) * 1pt // Configure the page. // This poster defaults to 36in x 48in. // NOTE: If modified the page size, some issues may occur. // NOTE: In chinese, the poster size is usually 90cm x 120cm set page( width: 36in, height: 48in, margin: (top: 1in, left: 2in, right: 2in, bottom: 2in), footer: [ #set align(center) #set text(32pt) #block( fill: rgb(footer_color), width: 100%, inset: 20pt, radius: 10pt, [ #text(font: "Courier", size: footer_left_text_font_size, footer_left_text) #h(1fr) #text(size: footer_center_text_font_size, smallcaps(footer_center_text)) #h(1fr) #text(font: "Courier", size: footer_left_text_font_size, footer_right_text) ] ) ] ) // Configure equation numbering and spacing. set math.equation(numbering: "(1)") show math.equation: set block(spacing: 0.65em) // Configure lists. set enum(indent: 10pt, body-indent: 9pt) set list(indent: 10pt, body-indent: 9pt) // Configure headings. // set heading(numbering: "I.A.1.") show heading: it => locate(loc => { // Find out the final number of the heading counter. let levels = counter(heading).at(loc) let deepest = if levels != () { levels.last() } else { 1 } set text(40pt, weight: 900) if it.level == 1 [ // First-level headings are centered smallcaps. #set align(center) #set text({ 48pt }) #show: smallcaps #v(50pt, weak: true) #if it.numbering != none { numbering("I.", deepest) h(7pt, weak: true) } #it.body #v(35.75pt, weak: true) #line(length: 100%) ] else if it.level == 2 [ // Second-level headings are run-ins. #set text(style: "italic") #v(32pt, weak: true) #if it.numbering != none { numbering("i.", deepest) h(7pt, weak: true) } #it.body #v(10pt, weak: true) ] else [ // Third level headings are run-ins too, but different. #if it.level == 3 { numbering("1)", deepest) [ ] } _#(it.body):_ ] }) // Arranging the logo, title, authors, and department in the header. set par(leading: 1.5em) // set header line-spaces. align(center, grid( rows: 2, columns: (4in, 24in, 4in), // TODO: should adjust it by logo sizes. column-gutter: 0pt, row-gutter: 50pt, image(univ_logo, width: 100%), text(weight: "extrabold", size: title_font_size, title+"\n") + text(size: authors_font_size, (authors.map(author => [#author.name#super[#author.staff]]).join(", ")) + "\n")+ text(size: authors_font_size, (departments.map(d => [#super[#d.id]#d.name]).join("\n ")) + "\n"), image(team_logo, width: 100%) ) ) // Start three column mode and configure paragraph properties. show: columns.with(num_columns, gutter: 64pt) set par(justify: true, first-line-indent: 0em) show par: set block(spacing: 0.65em) // Display the poster's contents. set par(leading: float(body_spacing) * 1em) body }
https://github.com/jerrita/CQUPTypst
https://raw.githubusercontent.com/jerrita/CQUPTypst/master/template/font.typ
typst
// 中文字号 到 pt 的转换 // https://www.runoob.com/w3cnote/px-pt-em-convert-table.html #let fs_2 = 22pt #let fs_l2 = 18pt #let fs_3 = 16pt #let fs_l3 = 15pt #let fs_4 = 14pt #let fs_l4 = 12pt // 1.5 倍行距约为 18pt #let s_par_gap = 18pt #let content_numbering(..nums) = { if nums.pos().len() == 1 { "第 " + str(nums.pos().last()) + " 章 " } else if nums.pos().len() <= 3 { nums.pos().map(str).join(".") + " " } else if nums.pos().len() == 4 { str(nums.pos().last()) + ") " } else if nums.pos().len() == 5 { "(" + str(nums.pos().last()) + ") " } }
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/compiler/weeks/week14.typ
typst
#import "../../utils.typ": * #section("JIT part 2") #subsection("Native Code") For CSharp, when trying to run native code, you need to copy the code into memory and mark the page as executable. Then you need to wrap the code within the Marshal.GetDelegateForFunctionPointer<>() and call this delegate. The System.Runtime.InteropServices is required to be implemented. #subsection("Code Optimization") Just like a general compiler, certain operations can be shortened or changed in order to provide faster execution. For example, you can use bit operations instead of regular multiplication, division and modulo. #align( center, [#image("../../Screenshots/2023_12_18_08_22_36.png", width: 50%)], ) Or you can replace unnecessary operations with simpler static calls: e.g. 1 + 2 -> both constants, will always be 3. Replace with constant 3. #align( center, [#image("../../Screenshots/2023_12_18_08_24_54.png", width: 70%)], ) #align( center, [#image("../../Screenshots/2023_12_18_08_25_12.png", width: 70%)], ) ```rs // N and M are constant, this can be replaced with a variable while (x < N * M) { // y doesn't change within this loop, // can therefore be changed to a constant within this loop // e.g. put in variable k = y * M; x = x + k; } // new code k = y * M; temp = N * M; while (x < temp) { x = x + k; } ``` #subsection("Dead Code") Code that is never run, can simply be removed. #align( center, [#image("../../Screenshots/2023_12_18_08_28_05.png", width: 100%)], ) #subsection("Redundant variables") Similarly to the repeated writing in the loop example, you can also create code that needlessy allocates variables. In this case, you can simply remove the write and use the temporary value of a result. ```rs t = x + y; // this is useless u = t; writeInt(u); //new code writeInt(x + y); ``` #align( center, [#image("../../Screenshots/2023_12_18_08_30_24.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_12_18_08_30_49.png", width: 100%)], ) #subsection("Constant Propagation/Folding") This is simply the check for a variable that will always result in a particular value, e.g. if your code evaluates that variable x will always be of value 2, then x can be replaced to be a constant 2. (aka x removed, replaced with 2 in code) ```rs a = 1; if (something) { a = a + 1; // b is still 2 here b = a; } else { b = 2; } // c will always be 3 c = b + 1; // new code a = 1; if (something) { a = 2; b = 2; } else { b = 2; } c = 3; ``` #subsection("Partial Redundancy") This is code that is evaluated twice depending on the branch: ```rs if (something) { y = x + 4; } else { // ... } // this was already executed in the if statement if it evaluated to true z = x + 4; // new code if (something) { // note the code still needs to be here // otherwise you might change the code meaning! t = x + 4; y = t; } else { // ... t = x + 4; } z = t; ``` #subsection("Detection Methods") How to detect that you can optimize anything. #subsubsection("Static Single Assignment") An old principle -> most used in the 90s. This ensures that variables are only allocated once, aka the compiler will use a different variable if you reuse a variable in your code for something new. ```rs // old x = 1; x = 2; y = x; // new x1 = 1; x2 = 2; y1 = x2; ``` Dead Code: ```rs // redundant, can be deleted x1 = 1; x2 = 2; y1 = x2 + 1; writeInt(y1); ``` With this method, you will encounter problems however, for example how do you ensure this works with a loop? ```rs if (something) { x = 1; } else { x = 2; } y = x; if (something) { x1 = 1; } else { x2 = 2; } // which version? y1 = x??; ``` #subsubsubsection("Phi") With phi, the correct x will be chosen. #align( center, [#image("../../Screenshots/2023_12_18_08_41_52.png", width: 100%)], ) summary: - complex - powerful changes - needs time - especially PHI - not viable for JIT #subsubsection("Peephole Optimization") Only a subsectiong of code is analyzed, e.g. the next 3 instructions. #align( center, [#image("../../Screenshots/2023_12_18_08_45_49.png", width: 70%)], ) #align( center, [#image("../../Screenshots/2023_12_18_08_46_08.png", width: 100%)], ) #subsection("Overall Summary") #align( center, [#image("../../Screenshots/2023_12_18_08_46_24.png", width: 100%)], )
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas6/4_Stvrtok.typ
typst
#let V = ( "HV": ( ("","Tridnéven voskrésl jesí","Velíkim tájnam Bóžijim služítelije býste, bohoslóvcy i bohovídcy, učenicý: i blahodáť iscilénij prijáste, i vsím čelovíkom boľízni isciľájete."), ("","","Velíkoje pribížišče i pokróv dušám nášym, duchóv ľútych prohnánije, vý jesté bohovídcy apóstoli Hospódni: ťímže vás prísno počitájem."), ("","","Ot vsjákaho obstojánija, i vréda bisóvskaho, i prehrišénij, i zláho pľinénija izbávite, víroju vás voschvaľájuščich, božéstvenniji apóstoli blažénniji."), ("","Tridnéven voskrésl jesí","Nikólaje blažénne, pripádajušča mjá uščédri, moľúsja tí múdre, i óči prosvití duší mojejá, da čísťi víždu svitodávca ščédraho."), ("","","Vrahóv íščuščich mjá ozlóbiti, izbávi mjá svjáte, derznovénije k Bóhu jáko imýj, svjatíteľu Nikólaje blažénne, spasí mja ot vréda, i ot múž krovéj izbávi mjá."), ("","","Pristánišče ťá nebúrnoje, i sťínu neoborímuju svjatíteľu, nýňi sťažáchom vírniji, i stólp kríposti, i dvér pokajánija, i nastávnika dúš nášich, i zabrálo."), ("Bohoródičen","","Zavíďa soprotívnik lukávyj stádu tvojemú prečístaja, vsehdá bóret, choťá sebí sňíď sotvoríti: no tý Bohoródice, izbávi nás ot tohó vréda."), ), "S": ( ("","","Hóspodi, apóstoli spostihóša inohdá úbo síťmí hlubinú morskúju, inohdá že vysotú cárstvija učénij rádi. óvo úbo chudóžestvom nepostižímuju hlubinú ispytáša: óvo že víroju neopísannaho tvojehó ňídra dostihóša, i míru propovídaša bezľítnaho tvojehó Sýna. ťích molítvami, i vsích svjatých pomíluj nás."), ("","","Inohdá učenicý tvojí Christé, v korablí oburevájemi vopijáchu: učíteľu, spasí nás, pohibájem. i nýňi mý vopijém: čelovikoľúbče Spáse náš, izbávi nás ot bíd nášich, mólimsja."), ("Múčeničen","","Krest tvój Hóspodi, múčenikom býsť orúžije nepobidímoje: víďiša bo predležáščuju smérť, i prezdrjášče búduščuju žízň, upovánijem jéže na ťá ukripľáchusja: ťích molítvami pomíluj nás."), ("Bohoródičen","","Óko sérdca mojehó vozpuščáju k tebí Vladýčice: ne prézri málaho mojehó vozdychánija v čás, jehdá súdit Sýn tvój míru, búdi mí pokróv i pomóščnica."), ), ) #let P = ( "1": ( ("","","Pomóščnik i pokrovíteľ býsť mňí vo spasénije, séj mój Bóh, i proslávľu jehó, Bóh otcá mojehó, i voznesú jehó, slávno bo proslávisja."), ("","","Káko pristupľú k tebí čístaja, otčájan okajánnyj áz, vés strásten nečistotámi býv? No uščédrivši spasí okajánnuju mojú dúšu, Bohorodíteľnice prečístaja."), ("","","Vostávši smirénnaja dušé, ot hlubiný bezčéstija, vozopíj tépľi k jedíňij čísťij: pomíluj mjá otrokovíce preneporóčnaja čístaja, i strastéj mjá izbávi."), ("","","Búreju napástej potoplén bých hrichí: prostrí mi nýňi pómošči rúku čístaja, i izbávi bezčéstija strastéj, jáko da prísno slávľu ťá."), ("","","Hrichá ľútyja búri izbávi mjá Bohorodíteľnice, ot nejáže vés skvérnen jésm. Ťímže tí pritekáju, oblehčí mí nýňi ťahotú prehrišénij mojích."), ), "3": ( ("","","Utverdí Hóspodi, na kámeni zápovidej tvojích, podvíhšejesja sérdce mojé, jáko jedín svját jesí i Hospóď."), ("","","Sostarívšasja strasťmí bezčéstnymi hrichá, mláda sotvorí mja preneporóčnaja, soúzy prehrišénij oblehčájušči."), ("","","Ot brénija mjá očísti, i tíny hrichóvnyja: i chrám mjá božéstvennyj sotvorí Bohoródice, čísťi k tebí pribihájuščaho."), ("","","Vozníkni okajánnyja dušé, ot sná unýnija: očíma že vozzrí k jedíňij spásájuščej ťá otrokovíci Bohonevéstňij."), ("","","Prichoždú Vladýčice, otčájan i sokrušén, i k molítvi tvojejá tépľij pribiháju: spasí mja čístaja, rabá tvojehó."), ), "4": ( ("","","Uslýša prorók prišéstvije tvojé Hóspodi, i ubojásja, jáko chóščeši ot Ďívy rodítisja i čelovíkom javítisja, i hlahólaše: uslýšach slúch tvój, i ubojáchsja, sláva síľi tvojéj Hóspodi."), ("","","Hlahól že i veščéj, právo choščú sudítisja Bohorodíteľnice, k tvojemú Sýnu preneporóčnaja, da obrjášču ťá tohdá pribížišče, i zastuplénije deržávňijšeje, múk vsích izbavľájuščeje mjá."), ("","","Žitijé mojé okaľáno, nečíst že nráv hrichámi, vés strásten bých, čístaja: očísti mjá ot skvérny prehrišénij, i ubilí jáko sňíh tvojím chodátajstvom k Bóhu blahosérdomu."), ("","","Plenícami mojích sohrišénij sťáhnut jésm otvsjúdu, k pokajánnym putém ukloňátisja ne mohíj: prostrí mi rúku preneporóčnaja, uprávi že mí stezjú k spasénija putí nastavľájuščuju mjá."), ("","","Ľútych mjá múk, i ťmý kromíšnija, i hejénny tvojími molítvami svobodí Ďívo: ímaši bo vóľu i sílu, Hóspoda róždšaja jedínaho preblaháho."), ), "5": ( ("","","Ot nóšči útreňujušča, čelovikoľúbče, prosvití moľúsja, i nastávi i mené na poveľínija tvojá, i naučí mja Spáse, tvoríti vóľu tvojú."), ("","","V déň sudá javísja Vladýčice, i predstáni mí, múki i ohňá svoboždájušči: da spássja vospojú tvojú neoborímuju blahodáť."), ("","","Ustránšasja Vladýčice, króva tvojehó, vráh víďa mjá vrínu vo hlubinú prehrišénij dúšu mojú, i zrjá mja smijétsja: no pomozí mi."), ("","","Vozníknuti sotvorí čístaja, okajánnuju i strástnuju mojú dúšu, moľú ťa preneporóčnaja, i izmí ťahotý jejá, mnóhich hrichóv."), ("","","Moľbú prinošú ti preneporóčnaja, ot skvérnych i okajánnych i nečístych mojích ustén: uščédri mjá tvojéju molítvoju, moľú ťa."), ), "6": ( ("","","Vozopích vsím sérdcem mojím k ščédromu Bóhu, i uslýša mjá ot áda preispódňaho, i vozvedé ot tlí živót mój."), ("","","Blúdnaho mené i preokajánnaho prijimí Vladýko Christé, i múki izbávi, moľbámi tebé róždšija, i šúija části izbávi mjá."), ("","","Témnyj áda oderžít mjá strách, čístaja, i kózlišč čásť smuščájet mjá: jejáže izbávi mjá prečístaja Bohoródice, moľú ťa."), ("","","Umertvívši plóti mojejá strástnoje, Vladýčice Bohoródice, oživotvorí mojú, čístaja, dúšu preokajánnuju, i na púť právyj nastávi mjá."), ("","","Rábskoje prinošáju tí molénije, nerazúmnyj áz, i k tvojemú pribiháju blahoutróbnomu milosérdiju: ne vozvratí mené čístaja, posrámlena."), ), "S": ( ("","","Ot sérdca stenánije, i ot utróby prinošáju tí, preneporóčnaja, tvojehó prosjá blahoprebýtnaho zastuplénija: pomíluj vsestrástnuju mojú dúšu: umilosérdi mnohomílostivaho Bóha, izbáviti mjá sudá i jézera óhnennaho, jedína blahoslovénnaja."), ), "7": ( ("","","Sohrišíchom, bezzakónnovachom, neprávdovachom pred tobóju: nižé sobľudóchom, nižé sotvoríchom, jákože zapovídal jesí nám: no ne predážď nás do koncá, otcév Bóže."), ("","","Jáko mílostivu, jáko blahoľubívu Ďívu Máter, vsjú ťa jáko čístuju svídyj, pribiháju áz okajánnyj: no ne otvratí mené vseneporóčnaja, posrámlena ot tebé."), ("","","Vozníkni, o strástnaja dušé, i vostáni okajánnaja: bíj iz hlubiný v pérsi, i ispustí sléz istóčniki, da ťá pomílujet okajánnuju milosérdija Máti Christá i Bóha."), ("","","Chrám Bóžij býv, ot kreščénija božéstvennaho drévle, vés oskverníchsja okajánnyj, i nizležú užásno padénijem ľúťi: no tý mja vozstávi preneporóčnaja, otčájannych nadéžda."), ("","","Óblak ťážek pokrý preokajánnoje mojé sérdce: ťmá i mrák nájde na strástnuju mojú dúšu, Bohonevísto: pokajánija lučámi ozarí mja, da slávľu ťá."), ), "8": ( ("","","Jehóže vóinstva nebésnaja slávjat, i trepéščut Cheruvími i Serafími, vsjáko dychánije i tvár, pójte, blahoslovíte , i prevoznosíte vo vsjá víki."), ("","","Reká óhnennaja smuščájet, i mrák nesvitímyj vsehó mja koléblet, čérv mjá užasájet i skréžet zubnýj, Ďívo: da obrjášču ťá tohdá zastúpnicu deržávnu."), ("","","Vozhňiščénije ohňú da ne búdu Hóspodi, ni da uslýšu hlás preščénija tvojehó, imíja moľáščuju ťá, tvojú čístuju Máter: jejáže moľbámi pomíluj mjá, vzyváju tí."), ("","","Božéstvennaho hlása uslýšati sotvorí mja, i stojánija izbránnych pokaží mja Christé, pričástnika: da ne plačévnoje místo mjá priímet, imúšča moľáščuju ťá o sém Bohoródicu."), ("","","Strují sléz nýňi nizposlí mi, i stenánije ot duší sotvorí vo mňí čístaja, vsehdá pripádati tvojemú pokróvu, jáko da obrjášču razrišénije hrichóv mojích tvojéju molítvoju."), ), "9": ( ("","","Bezsímennaho začátija roždestvó neskazánnoje, Mátere bezmúžnyja netľínen plód: Bóžije bo roždénije obnovľájet jestestvá. Ťímže ťá vsí ródi jáko Bohonevístnuju Máter, pravoslávno veličájem."), ("","","Déň sudá strášnyj smuščájet mjá Ďívo, skréžet zubóv tlít sérdce mojé, stojánije kózlišč užasájet mjá: no pómošč v ľútych da obrjášču ťá Bohoródicu, jehdá choščú osudítisja."), ("","","Nýňi trépet soderžít mjá: i strách smuščájet mjá hejénskij. i čtó soďíjati, ne vím okajánnyj i osuždénnyj: ťímže pritekáju k tebí, i téplym umilénijem vopijú ti: ne prézri mené prečístaja."), ("","","Zrjá sudíšče, i pomyšľája súd tvój Christé mój, v némže choščú sudítisja právedno o ďíľich osuždénnyj. No ímam molébnicu tohdá, k ščedrótam tvojím mnóhim, moľáščuju Bohonevístnuju Máter tvojú."), ("","","Mýslenno prikasájasja tvojím stopám vseneporóčnaja, moľú ťá: prijimí rydánije mojé, pínije vnuší, i prehrišénij razrišénije podážď mí, vopijú ti, molítvami tvojími Ďívo, da ľubóviju ťá veličáju."), ), ) #let U = ( "S1": ( ("","","Jáko posreďí učenikóv tvojích, prišél jesí Spáse, mír tvój dajá ím: prijidí i k nám, i spasí nás."), ("","","Učenikóv tvojích lík vselénnuju prosvití: bývše bo inohdá lovcý rýb, nýňi že čelovíkov býša: ťích rádi Bóže, pomíluj nás."), ("Bohoródičen","","Mnóhaja mnóžestva mojích Bohoródice, prehrišénij, k tebí pribihóch čístaja, spasénija trébuja: posití nemoščstvújuščuju mojú dúšu, i molí Sýna tvojehó, i Bóha nášeho, dáti mí ostavlénije, jáže soďíjach ľútych, jedína blahoslovénnaja."), ), "S2": ( ("","","Učenicý tvojí, Spáse, v koncý zemlí posylájemi, jazýki blahočéstno jáko rýby ulovívše, privedóša tvojéj bláhosti. Ťích rádi úbo vopijém tí Christé: ľúdem tvojím podážď véliju mílosť."), ("","","Dvojenadesjática apóstol, Hóspodi, dvojenadesjatolúčnaja jáko sólnce javísja zemlí: ťích bo rádi uvjadíl jesí prélesti izrastíteľa: ťích rádi ozarjáješi dúšy tvojích rabóv: i nás ích rádi spásáj, jáko blahoutróben."), ("Múčeničen","","Hóspodi, svjatých tvojích pámať dnés javísja, jáko ráj, íže vo Jedémi: v néj bo rádujetsja vsjá tvár, i podajéši nám ťích molítvami mír i véliju mílosť."), ("Bohoródičen","","Vsesvjatája Bohoródice, vo vrémja životá mojehó ne ostávi mené: čelovíčeskomu predstáteľstvu ne vvíri mjá: no samá zastupí, i pomíluj mjá."), ), "S3": ( ("","Vsjú otložívše","Vo vsjú zémľu jáko mólnija premúdrych učenikóv tvojích, Vladýko Christé, izýde spasíteľnoje viščánije, i ozarí súščyja vo ťmí i ľútych, sýny dné i svíta nás soďílavšeje. Ťímže ťá vsjá tvár blahočéstno slávit."), ("","","Mréžeju božéstvennyja víry ľúdije prevratívše rýbarije, iz hlubiný sújetstva izvlekóša vsích, i predáša ích Bóhu, blahočéstvujuščich, i tohó prísno veličájuščich."), ("Bohoródičen","","Svjatája Vladýčice, Christá Bóha nášeho Máti, jáko vsích tvorcá neizrečénno róždšaja, molí so apóstoly svjaščénnymi vsehdá bláhosť jehó, strastéj nás izbáviti, i ostavlénije nám dáti hrichóv."), ), "K": ( "P1": ( "1": ( ("","","Jáko po súchu pišešéstvovav Izráiľ, po bézdňi stopámi, honíteľa faraóna víďa potopľájema, Bóhu pobídnuju písň pojím, vopijáše."), ("","","Svít bývše míru Bohohlahóliviji, svítlymi blistáňmi ozaríte nás: i strastéj izbávite nóšči, i mhlý iskušénij, Bohoblsžénniji."), ("","","Svít bývše míru Bohohlahóliviji, svítlymi blistáňmi ozaríte nás: i strastéj izbávite nóšči, i mhlý iskušénij, Bohoblsžénniji."), ("","","Kňázi čestnýja po vséj zemlí Dúch vás čéstno postávi, Hospódni učenicý: ťímže vozdúšnaho kňázja pobidívše, vírnyja izbavľájete."), ("","","Ot ohňá neveščéstvennaho, jáko svitozárnoje razžéhšesja úhlije, veščéstvennyja mojá premúdriji, strásti popalíte, k svítu bezstrástija i životá nastavľájušče mjá."), ("Bohoródičen","","Apóstol molítvami, prorók, i múčenik, i róždšija ťá čístyja, Hóspodi Iisúse, vsích carjú, uščédri ľúdi sohrišívšyja tí."), ), "2": ( ("","","Čúvstvennyj faraón potóplen býsť so vsevójinstvom: Izrájiľ že prošéd posreďí mórja, vopijáše: Hóspodevi Bóhu nášemu poím, jáko proslávisja."), ("","","Na nebesích živýj rádostno ótče premúdre, na zemlí víroju sohlásno tebí pojúščich, vsjákuju skórb sérdca lukávuju razžení chodátajstvom tvojím."), ("","","Na strásti vrédnyja, na vrahí tletvórnyja, na vsjákuju ľstívaho zlóbu, ukripí nýňi ótče Nikólaje, k pokróvu tvojemú svjatómu víroju pritekájuščyja."), ("","","Ujázvlennych nás ot nevídimych striléc, vračevstvóm tvojejá Nikólaje, molítvy pretvorí, jáko da zdrávo chodíti nám po putém Hospódnim."), ("Bohoródičen","","Íže sýj so Otcém soprisnosúščnyj Sýn, naposľídok voschoťív vselísja v ložesná tvojá na náše Bohoródice, vírnych otroždénije: ťímže vospivájem ťá."), ), ), "P3": ( "1": ( ("","","Ňísť svját, jákože tý Hóspodi Bóže mój, voznesýj róh vírnych tvojích bláže, i utverdívyj nás na kámeni ispovídanija tvojehó."), ("","","Božéstvennyj Dúch váša jazýki izvarív našéstvijem strášnym, sokrušénnyja čelovíki k životú obnovľájet vámi, slávniji apóstoli."), ("","","Božéstvennyj Dúch váša jazýki izvarív našéstvijem strášnym, sokrušénnyja čelovíki k životú obnovľájet vámi, slávniji apóstoli."), ("","","V rázumi sohrišájaj, kóje obrjášču pomílovanije Slóve, v déň súdnyj? Sehó rádi vopijú ti: tvojích rádi učeník uščédri mjá samoosuždénnaho."), ("","","Upodóbľšijisja Christóvym spasíteľnym strastém, duší mojejá strásti ľítnyja i ľútyja iscilíte, vráčeve súšče slávniji apóstoli."), ("Bohoródičen","","Sohrišívšaho mjá Christé, Bohoródicy rádi i tvojích apóstol, obratív jáko Bóh pomíluj, i ohňá víčnaho Spáse, svobodí."), ), "2": ( ("","","Na tvérďim víry tvojejá kámeni pomyšlénije utverdív duší mojejá, utverdí Hóspodi: ťá bo ímam bláže, pribížišče i utverždénije."), ("","","Pobídy jávi na dušetľínnyja strásti prijál jesí, Nikólaje vseblažénne: ot níchže zľí vsehdá pobiždájemych nás tvojími molítvami izbávi."), ("","","Údy plotskíja umertvív vozderžánijem, k žízni prešél jesí nestaríjuščejsja, júže i nám vosprijáti molísja, múdre, rádostno voschvaľájuščym ťá."), ("","","Posiščáti nás ot nebésnyja vysotý ne prestáj svjatíteľu, othoňá vsjú žitéjskuju ťisnotú, k Bóhu tvojími molítvami."), ("Bohoródičen","","Razrišénije nám hrichóv dáti čístaja izbáviteľa umolí, pomračénije vsé ot dúš nášich prísno tvojími molítvami razhoňájušči."), ), ), "P4": ( "1": ( ("","","Christós mojá síla, Bóh i Hospóď, čestnája cérkov Bohoľípno pojét vzyvájušči, ot smýsla čísta o Hóspoďi prázdnujušči."), ("","","Pristánišča blahoutíšnaja, pristánišča nebúrnaja, k tíchomu mjá pristánišču dovedíte, prehrišénij ľútych trevolnénijem oburevájema."), ("","","Pristánišča blahoutíšnaja, pristánišča nebúrnaja, k tíchomu mjá pristánišču dovedíte, prehrišénij ľútych trevolnénijem oburevájema."), ("","","Dušé mojá, vozdochní, dušé mojá, proslezísja: smirénnoje sérdce mojé blahómu otňúd priľipísja, jáko da búduščaho ťá plámene i múki izbávit Bóh."), ("","","Spása Hóspoda molíte, spasítelije súšče čelovíkov vseblažénniji apóstoli: da nás spasét ot iskušénij zlých jáko čelovikoľúbec."), ("Bohoródičen","","Ďívo prečístaja, Ďívo neporóčnaja, so apóstoly o nás moľbú sotvorí: jáko da izbávimsja ľútych iskušénij i bíd."), ), "2": ( ("","","Uslýšach slúch tvój, i ubojáchsja, razumích ďilá tvojá, i užasóchsja: sláva síľi tvojéj Hóspodi."), ("","","Uvračúj svjáte, ujázvlenoje ot ľstívaho neisprávlenoje sérdce mojé, umolív blahodávca Bóha nášeho, Nikólaje."), ("","","Sokrušíl jesí kápišča pohíbeli, Christóv uhódniče: ťímže víroju moľú ťa Nikólaje, umá mojehó zlóbnyja kumíry potrebí."), ("","","Mirodochnovénen býl jesí právednymi ďilesý Bohomúdre, i v Mírich ukrasíl jesí prestól, ótče svjatíteľu Nikólaje."), ("Bohoródičen","","Beznevístnaja Vladýčice, blahoslovénnaja Bohorodíteľnice, pojúščyja ťá spásáj ot vsjákaho vréda, jedína čelovíkov pomóščnice."), ), ), "P5": ( "1": ( ("","","Bóžijim svítom tvojím bláže, útreňujuščich tí dúšy ľubóviju ozarí, moľúsja, ťá víďiti Slóve Bóžij, ístinnaho Bóha, ot mráka hrichóvnaho vzyvájušča."), ("","","Púť vvoďáščij v živót, ziló ťisňíjšim šéstvijem iskušénij i skorbéj, učenicý Slóva jávi chodívšiji, stezjú duší mojejá uhládite."), ("","","Púť vvoďáščij v živót, ziló ťisňíjšim šéstvijem iskušénij i skorbéj, učenicý Slóva jávi chodívšiji, stezjú duší mojejá uhládite."), ("","","Svitíľnicy božéstvennaho vostóka, izbávite mjá ot ťmý strastéj, i slastéj pomračénija, i napástej, i obstojánij, i búri, i bíd, Christóvy apóstoli."), ("","","Svítcy Slóva Bohozráčniji, v knízi mjá živótňij napisátisja molíte, apóstoli, hrichóv mojích zlóje rasterzájušče pisánije molítvami vášimi."), ("Bohoródičen","","Spasénije mojé i upovánije, spasí mja upovájuščaho na ťá, vsích upovánije nepostýdnoje, jáže k Sýnu tvojemú moľbámi, i božéstvennych učeník, otrokovíce jedína vsepítaja."), ), "2": ( ("","","Svít vozsijávyj míru Christé, prosvití sérdce mojé ot nóšči tebí zovúšča, i spasí mja."), ("","","Dremánijem ľínosti oderžíma, usérdno mjá ustrój svjaščénnymi chodátajstvy tvojími, Nikólaje."), ("","","Iisúsa Spása umolí, svjatíteľu Nikólaje, víčnaho mjá izbáviti mučénija."), ("","","Mirskích mjá soblázn sobľudí, i ot bisóvskaho ozloblénija, molítvami tvojími, svjatíteľu Nikólaje."), ("Bohoródičen","","Jéže býti nám podavájaj, v tvojú utróbu vselísja Bohoródice: jehóže molí spastí nás."), ), ), "P6": ( "1": ( ("","","Žitéjskoje móre vozdvizájemoje zrjá napástej búreju, k tíchomu pristánišču tvojemú priték, vopijú ti: vozvedí ot tlí živót mój, mnohomílostive."), ("","","Jáko skrižáli <NAME>, jávi čestnája zakonopoložénija slávniji, v dušách imíste nelóžno: ímiže v pisánijich uprazdníste zakón, mír spásše."), ("","","Jáko skrižáli <NAME>, jávi čestnája zakonopoložénija slávniji, v dušách imíste nelóžno: ímiže v pisánijich uprazdníste zakón, mír spásše."), ("","","Dušé sohrišájušči, obýčajem že zlým umovrédno rabótajušči, obraščénijem obratísja, i Hóspodevi ščédromu vozopíj: apóstol rádi Slóve, spasí mja."), ("","","Ovcám desným sočetáj mjá, vo užásnom i strášnom prišéstviji tvojém, izbránnym tvojím, molítvami božéstvennych propovídnik tvojích, zaklávyjsja za vsích áhnče nezlóbivyj."), ("Bohoródičen","","Lík mólit ťá bezplótnych slúh, Sýne Bóžij prebeznačáľne, mólit ťá sobór učenikóv s róždšeju ťá, ľúdem tvojím podážď mílosti tvojá."), ), "2": ( ("","","Kítom požrén hrichóvnym, vopijú tebí Christé: jáko proróka iz istľínija mjá svobodí."), ("","","Svitíľnika ťá razúmnaho imúšči tvár Nikólaje, prosviščájetsja zarjámi neisčétnych čudés tvojích."), ("","","Nedremánnyj molítvenniče, k tebí pritekájuščym Nikólaje, ot sná zláho ľínosti izbávi mjá."), ("","","Izbávil jesí drévle múdre, choťáščyja neprávedno umréti: tákožde i mené izbávi ot bíd i prehrišénij, Nikólaje."), ("Bohoródičen","","Ďívo jedína čístaja obrádovannaja, pomozí mi, prísno oburevájemu žitéjskimi napásťmi."), ), ), "P7": ( "1": ( ("","","Rosodáteľnu úbo péšč soďíla ánhel prepodóbnym otrokóm, chaldéji že opaľájuščeje veľínije Bóžije, mučíteľa uviščá vopíti: blahoslovén jesí Bóže otéc nášich."), ("","","Údiceju slóva apóstoli, izvlékše vsích iz hlubiný prélesti, privedóste k zaklávšemusja Slóvu nás rádi, pojúšče jemú: blahoslovén Bóh otéc nášich."), ("","","Údiceju slóva apóstoli, izvlékše vsích iz hlubiný prélesti, privedóste k zaklávšemusja Slóvu nás rádi, pojúšče jemú: blahoslovén Bóh otéc nášich."), ("","","Jávľšemusja véščiju ťilésnoju apóstoli, nechodátajstvenňi besídovavše, prosvitístesja svitodáteľnymi blistáňmi jehó. Ťímže mjá prosvitíte vopijúšča: blahoslovén Bóh otéc nášich."), ("","","Pástyrja dóbraho umolíte božéstvenniji učenicý, v horách mjá zablúždšaho prestuplénija vzyskáti, i spastí vopijúščaho priľížno: blahoslovén Bóh otéc nášich."), ("Bohoródičen","","So proróki, apóstoly že i múčeniki, Ďívo, jehóže rodilá jesí, molí, zemných mjá izbáviti zól, i pričástnika nebésnych bláh býti mjá spodóbi Vladýčice."), ), "2": ( ("","","Prepodóbnych tvojích otrokóv molítvu uslýšavyj, i péšč horjáščuju orosívyj, blahoslovén jesí Hóspodi Bóže otéc nášich."), ("","","Síloju Bóžijeju preblažénne, jeretíčestvujuščich polkí poprál jesí, i ot ťích prélesti stádo tvojé spásl jesí, Nikólaje."), ("","","Javléjsja plávajuščym, i tvój hrád prepitál jesí stráždušč: dušetľínnaho mjá hláda izbávi, molítvami tvojími, ótče Nikólaje."), ("","","Utverdí ótče, molítvami tvojími tebé prizyvájuščyja na pómošč Nikólaje, utišája bisóvskuju lukávuju búrju."), ("Bohoródičen","","Vladýčice vsích čelovík, svjatája Bohoródice, rabóty mjá strástnyja tvojími molítvami do koncá svobodí."), ), ), "P8": ( "1": ( ("","","Iz plámene prepodóbnym rósu istočíl jesí, i právednaho žértvu vodóju popalíl jesí: vsjá bo tvoríši Christé, tókmo jéže choťíti. Ťá prevoznósim vo vsjá víki."), ("","","Molítv serpóm očístite plévely vsjá mýsli mojejá, božéstvenniji ďílateli Spásovy apóstoli: jáko da spasíteľnaho plodá prinesú klás."), ("","","Molítv serpóm očístite plévely vsjá mýsli mojejá, božéstvenniji ďílateli Spásovy apóstoli: jáko da spasíteľnaho plodá prinesú klás."), ("","","Oľadeňívšaja serdcá obnovíste rálom slóva, i vsíjavše učénije čestnóje, klás storíčestvujušč spásšichsja požáste, bohovídcy."), ("","","Vrážiju zlóbu uspívše, usnúli jesté snóm právednych podóbnym, neusýpniji o nás molítvennicy bývše učenicý Slóva, vo vsjá víki."), ("Bohoródičen","","Ohňá nehasímaho izbávi mjá Hóspodi, prorók, i múčenik, i apóstol tvojích, i vo utróbu vmistívšija ťá neizrečénno, Ďívy neiskusomúžnyja, ščédre, molítvami."), ), "2": ( ("","","Prepodóbniji tvojí ótrocy v peščí Cheruvímy podražáchu, trisvjatúju písň vospivájušče: blahoslovíte , pójte, i prevoznosíte vo vsjá víki."), ("","","Na vysotú žitijá svitľíjšaho vosték javílsja jesí, i znájem vselénňij Bohonósne, čudoďijániji razlíčnymi prosviščája súščich vo ťmí, Nikólaje."), ("","","Oblahodatí božéstvenňi bódrstvujuščyja, ťá čtúščyja Nikólaje: uspí zlóbu vraždújuščich čelovík, na nás nachoďáščich, blažénne."), ("","","Íže vsjá síti vrážija krípostiju sokrušív duchóvnoju, ot ťích izbávi mjá tvojími molítvami, okormľája živót mój Bohomúdre, svjatíteľu Nikólaje."), ("Bohoródičen","","Pojém ťá Ďívo Bohorodíteľnice, jejáže rádi kľátva neplódna býsť i blahoslovénije vsím priíde, víduščym ťá jedínu Máter Bóha nášeho bezmúžnuju."), ), ), "P9": ( "1": ( ("","","Bóha čelovíkom ne vozmóžno víďiti, na nehóže ne smíjut číni ánheľstiji vziráti: tobóju že vsečístaja, javísja čelovíkom Slóvo voploščénno, jehóže veličájušče, s nebésnymi vóji ťá ublažájem."), ("","","Bóha čelovíkom priobščívšasja, i mértvennoje sovokuplénijem bez sravnénija obožívšaho, vo vsém míri propovídavše, vsích bezbóžnyja prélesti svobodíste: ťímže ublažájemi jesté prísno božéstvenniji apóstoli."), ("","","Bóha čelovíkom priobščívšasja, i mértvennoje sovokuplénijem bez sravnénija obožívšaho, vo vsém míri propovídavše, vsích bezbóžnyja prélesti svobodíste: ťímže ublažájemi jesté prísno božéstvenniji apóstoli."), ("","","Christóvu strásť izobrazívše apóstoli, strasťmí ťilesé razlíčnymi, plóti mojejá strásti umertvíte: i iznemóhšuju, i bídstvujuščuju, i umerščvlénuju mojú dúšu oživotvoríte."), ("","","Púť búdi mí nastavľájuščij mjá k nezablúdnomu putí zápovidej tvojích čelovikoľúbče, v própasť hrichóvnuju vpádšemu: i zabluždájušču, i uklónšusja k putém lukávym, i bídstvujušču."), ("Bohoródičen","","Líki ánhel i archánhel že, vlásti i síly, načála, Hospódstvija, Cheruvími i Serafími i prestóli, Christé, sobór apóstol, s róždšeju ťá, móľatsja tebí jedíne carjú, spasí rabý tvojá."), ), "2": ( ("","","Jéže rádujsja ot ánhela priímšaja, i róždšaja sozdáteľa tvojehó, Ďívo, spasí ťa veličájuščyja."), ("","","Svjatítelej udobrénije, čudés istóčniče Nikólaje, umolí Bóha čelovikoľúbca, obristí nám hrichóv ostavlénije."), ("","","Jákože drévle úzniki izbávil jesí ot smérti: táko i nás izbávi iskušénij žitéjskich, Nikólaje."), ("","","Tý v mírich likíjskich pohrebén býl jesí, míro tóčiši vsehdá Nikólaje, zlovónija strastéj othoňája prísno."), ("","","Ziždíteľa prišéstvije pri dvérech, ne ľinísja dušé mojá, no vozopíj: Nikolája molítvami Christé, spasí mja."), ("Bohoródičen","","Svít róždšaja vsepítaja, sérdca mojehó zinicu osľípšuju prosvití: da pojú ťa íže tebé rádi spasájem."), ), ), ), "CH": ( ("","","Búrju utišívše lésti bisóvskija múdri v tišinú apóstoli Christóvy, vés mír nastáviste vo víru pravoslávnuju, i nýňi molítesja o dušách nášich."), ("","","Pámjať premúdrych učeník Christá carjá nášeho, dostójno písňmi počtím vírniji: tíji bo Tróičeskuju víru v míri propovídaša."), ("Múčeničen","","Izbránnyja udiví i svjatýja Bóh náš. Rádujtesja i veselítesja vsí rabí jehó, vám bo uhotóva vincý i cárstvije svojé: no mólim vý, i nás ne zabúdite."), ("Bohoródičen","","Preložénije skorbjáščich, preminénije boľáščich jesí Bohoródice vsepítaja, spasí hrád i ľúdi, borímych umirénije, oburevájemych tišiná, jedína predstáteľnice vírnych."), ), ) #let L = ( "B": ( ("","","Pomjaní mja Bóže Spáse mój, jehdá priídeši vo cárstviji tvojém, i spasí mja, jáko jedín čelovikoľúbec."), ("","","Jáko lučý tájnyja, protékše v míri apóstoli slávniji, čelovíčeskij ród víroju prosvitíli jesté."), ("","","Jáko óblacy okropíli jesté vódu v míri, božéstvennaho rázuma, prosviščénniji Hospódni apóstoli."), ("","","Mučénija ohňú približájuščesja, božéstvennuju rósu prochlaždájuščuju vás, ot Bóha vosprijáste múčenicy."), ("","","Svjaťíj i čestňíj Tróici, vírniji poklaňájuščesja, sohlásno vozopijím: apóstol moľbámi spasí vsích nás."), ("","","Róždšaja Slóvo páče slovesé Bohoródice, Otcú sobeznačáľnaho, tohó molí spastísja dušám nášym."), ), )
https://github.com/Alignof/typst_template
https://raw.githubusercontent.com/Alignof/typst_template/master/example.typ
typst
MIT License
#import "style/report.typ": * #show: style.with( title: "typst template", authors: ( ( name: "n.takana", organization: [University of xxx, yyyyyyyyy], email: "<EMAIL>" ), ), abstract: none, index-terms: ("typst", "template", "report"), bibliography-file: none, ) #let quote_block(body) = { block( width: 100%, fill: silver, inset: 8pt, body ) } = Section 引用は以下. #quote_block()[ #lorem(20) ] ターミナルは以下. #terminal()[ #lorem(20) ] #lorem(50) = Listing 列挙は以下の通り. - xxx - yyy - zzz 数字の列挙は+を使う. + abc + def + ghi = table NAND の真理値表を @nand に示す. #figure( table( stroke: none, columns: 3, table.hline(y: 1, start: 0), table.vline(x: 2, start: 0), [x], [y], [$overline(x dot y)$], [0], [0], [1], [0], [1], [1], [1], [0], [1], [1], [1], [0], ), caption: [NAND の真理値表], )<nand> 複雑なテーブルを以下に示す. #[ #show table.cell.where(y: 0): set text( fill: white, weight: "bold", ) #rotate( -90deg, reflow: true, figure( table( columns: 4, fill: (_, y) => if y == 0 { blue } else if calc.odd(y) { blue.lighten(85%) } else { blue.lighten(96%) }, align: (horizon + left, horizon + left, horizon + left, horizon + left), table.header[][MOSFET][BJT][IGBT], [Drive method \ (Current or Voltage)], [Voltage], [Current], [Voltage], [Input Impedance (Low or High)], [High], [Low], [High], [Drive Power (Low or High)], [Low], [High], [Low], [Switching Speed \ (Slow, Medium, or Fast)], [Fast], [Slow], [Medium], [Operating Frequency \ (ex. 1KHz-100KHz)], [\- 1MHz], [200Hz - 10kHz], [\- 50kHz], [Saturation Voltage (Low or High)], [High], [Low], [Low], [Cost (Low, Medium, or High)], [Medium], [Low], [High], [Examples of USAGE \ (3 examples or more)], [power amplification, low to medium power switching, and in integrated circuits], [DAC Converters, Induction motor drivers, UPS], [inverters, motor drives, and power electronics], ), caption: [MOSFET,BJT,IGBT の特徴], ) ) ] = Math 数式の例を@integral, @case に示す. $ X(f) &= integral^infinity_(-infinity) w(t)e^(-j 2 pi f t) d t \ &= integral^(T/2)_(-T/2) 1 times e^(-j 2 pi f t) d t \ &= [ 1/(-j 2 pi f) e^(-j 2 pi f t)]^(T/2)_(-T/2) \ &= 1/(-j 2 pi f) (e^(-j pi f T) - e^(j pi f T)) \ &= 1/(-j 2 pi f) (e^(-j pi f T) - e^(j pi f T)) \ &= 1/(pi f) sin (pi f T) $<integral> $ w(t) = cases( 1\, |t| <= T/2, 0\, "otherwise" ) $<case> ブール代数の例を@bool に示す. $ f &= overline(overline(overline(x) and x) and overline(overline(x) and y)) \ &= overline(1 and overline(overline(x) and y)) \ &= overline(overline(overline(x) and y)) \ &= overline(x) and y $<bool> = Code ```typst #show raw.line: it => { box( width: 100%, align(horizon, stack( dir: ltr, box( width: 17pt, inset: (x: 7pt), align(right, text(white)[ #it.number ] )), it.body, )) ) } ```
https://github.com/PorterLu/Typst
https://raw.githubusercontent.com/PorterLu/Typst/main/basic/typst_demo.typ
typst
Typst是一个新的文本编辑器,可以从某种程度上替代Latex,从文将记录笔者学习Typst的过程。在 www.typst.app 上,我们可以在左侧编辑文件,等待一段时间后右侧就会自动渲染完成。 = 介绍 == 段落 在行首添加 = 可以使得文件变为标题,两个 = 可以开启二级标题,同时使用 ‘\_’ 可以开启强调 _强调_, _Emphasize_,现在发现中文的强调不是很明显。 添加一个段落需要加入一个空行即可,如果要列出小点,只需要使用在每一行使用'\+'即可,同时在可以使用'\-'列出子弹列表,例如列出宝可梦三原色,同时举例两只火系宝可梦: + 红 - 小火龙 - 帝君 + 绿 + 蓝 == 图片 #figure( image("pikachu.png", width : 50%), caption: [ A pikachu ], ) <pikachu> 我们使用 `#image` 函数可以添加一张图片。如果为图片添加一个标题,那么可以使用 `#figure` 函数,在`image`属性中添加图片,caption属性中添加标题,这时图片会默认居中。如果在 `figure` 最后使用 `<label_name>`, label_name就会成为这个图片的引用名,可以使用`@label_name`进行引用,如@pikachu。 == 引用 我们使用`#bibliography`函数添加一个`bib`文件,使用`#cite`函数进行具体引用,如 #cite("lee2019keystone")。 #bibliography("typst.bib") == 数学公式 和其他工具一致,typst中使用`$$`可以开启行内公式,如$Q = rho A v + C$。为了使用行间公式,我们可以独立一行输入` $$ `,记得公式开头和末尾都加上空格。 $ 7.32 beta + sum_(i = 0)^nabla Q_i / 2 $ 更多的数学公式写法可以参考typst的数学公式页面。
https://github.com/csimide/SEU-Typst-Template
https://raw.githubusercontent.com/csimide/SEU-Typst-Template/master/seu-thesis/utils/thanks.typ
typst
MIT License
#let thanks(title: "致谢", s) = { heading(bookmarked: true, outlined: true, numbering: none, level: 1, title) s }
https://github.com/ellmau/cv-typst
https://raw.githubusercontent.com/ellmau/cv-typst/main/cv_en.typ
typst
#import "cv.typ": * #show: my-cv.with(language:"en")
https://github.com/Hobr/njust_thesis_typst_template
https://raw.githubusercontent.com/Hobr/njust_thesis_typst_template/main/page/header.typ
typst
MIT License
// 字体 #import "../util/font.typ": fonts, fontSize // 标题 #let showTitle(title) = align( center, text( font: (fonts.en, fonts.zh_黑体), size: fontSize.三号, )[#title], ) // 作者 #let showAuthor(author) = { let count = author.len() let ncols = calc.min(count, 3) grid( columns: (1fr,) * ncols, row-gutter: 16pt, ..author.map(author => align( center, text( font: (fonts.en, fonts.zh_宋体), size: fontSize.五号, )[ #author.name (#author.studentid)\ #author.department#author.major ], )), ) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/accent_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test function call. $grave(a), acute(b), hat(f), tilde(§), macron(ä), diaer(a), ä \ breve(\&), dot(!), circle(a), caron(@), arrow(Z), arrow.l(Z)$
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/import-09.typ
typst
Other
// Error: 9-18 cannot import from user-defined functions #import () => {5}: x
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/list_06.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // This doesn't work because of mixed tabs and spaces. - A with 2 spaces - B with 2 tabs
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cmarker/0.1.0/lib.typ
typst
Apache License 2.0
#let _p = plugin("./plugin.wasm") #let render( markdown, smart-punctuation: true, blockquote: none, h1-level: 1, raw-typst: true, scope: (:), show-source: false, ) = { let options = 0; if smart-punctuation { options += 0b00000001; } if blockquote != none { options += 0b00000010; } if raw-typst { options += 0b00000100; } let rendered = str(_p.render(bytes(markdown), bytes((options, h1-level)))) if show-source { raw(rendered, block: true, lang: "typ") } else { eval(rendered, mode: "markup", scope: ( blockquote: blockquote, image: (..args) => image(..args), ..scope, )) } }
https://github.com/pascalguttmann/git-presentation
https://raw.githubusercontent.com/pascalguttmann/git-presentation/master/README.md
markdown
Git-Presentation ================ Presentation about Version Control with Git and GitHub written in Typst.
https://github.com/kokkonisd/typst-cross
https://raw.githubusercontent.com/kokkonisd/typst-cross/main/src/clues.typ
typst
The Unlicense
#import "preprocessing.typ": * // Produce a list of clues. // // This produces a simple enumerated list with all the clues from a clues dictionary (usually // either `data.clues.across` or `data.clues.down`, coming from the crossword's TOML file), with // each element having the appropriate clue number. // // Parameters: // - `clues`: the dictionary of clues as found in the TOML file. // - `data`: the data of the TOML file (that will be processed). #let _clues-list(clues, data) = { enum( ..clues.map(clue => { let number = _process-data(data).cells.find(cell => { cell.row == clue.row and cell.column == clue.column }).number enum.item(number)[ // Evaluate the clue as Typst code. #eval(clue.clue, mode: "markup") ] }) ) } // Produce the enumerated list of the "across" clues. #let clues-across(data) = { _clues-list(data.clues.across, data) } // Produce the enumerated list of the "down" clues. #let clues-down(data) = { _clues-list(data.clues.down, data) } // Produce a two-column display of both "across" and "down" clues, with headers. #let clues(data) = grid( columns: (1fr, 2pt, 1fr), gutter: 10pt, block[ = Across #clues-across(data) ], block(line(start: (0%, 0%), end: (0%, 100%))), block[ = Down #clues-down(data) ], )
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas3/1_Pondelok.typ
typst
#let V = ( "HV": ( ("", "<NAME>", "Veľmí sohrešájušča mjá, i tebé ohorčevájušča blaháho Vladýku, i mílostiva jestestvóm, obraščájuščasja, jáko blúdnaho prijimí mja, i jedínaho ot najémnik tvojích sotvorí mja, nebésnyj Ótče."), ("", "", "Ľínostiju žitijá míru preidóch, i k koncú užé okajánnyj priblížichsja, ne pomyšľáju ždúščaho mjá sudá, i ot Bóha otpadénija: no obratív mjá Spáse sích vsích ischití."), ("", "", "Hejénny, i zubnáho skréžeta izbávi Hóspodi, smirénnuju mojú dúšu, i vsjákaho inóho tomlénija víčnaho preblahíj: jáko da víroju ťá pojú mílostivaho Bóha i čelovikoľúbca jestestvóm."), ("", "", "Líki bezplótnych Hóspodi, sostávil jesí, bohátstvo javľája vsím tvojejá bláhosti: i privél jesí ot nebytijá vo jéže býti, páče umá slávu tvojú nýňi slávjaščich hlásy nemólčnymi."), ("", "", "Vélija ánhel tvojích Christé síla: bezťilésni bo súšče mír protíčut, sochraňájušče cérkvi síloju, jáže ot tebé Vladýko, i tebé móľatsja o vselénňij."), ("", "", "Dobrótu trisólnečnuju tvojú jedínstvennuju, zrjášče síly tebé služáščyja, javľájut vtorýja svítlosti súščym v míri: i óbščno sijájušče, podajút nám božéstvennyja svítlosti."), ("Bohoródičen", "", "Vsími vlaďáščaja tvármi prečístaja, ľúťi obladájema strasťmí umá mojehó, svobodí téplym tvojím predstáteľstvom i máterneju molítvoju i porabóti mjá Sýnu i Bóhu tvojemú."), ("", "", "Večérňuju písň prinósim tí Christé s kadílom i píňmi duchóvnymi, pomíluj i spasí dúšy náša."), ), "S": ( ("", "", "Spasí mja Hóspodi Bóže mój, tý bo vsím jesí spasénije: búrja mjá strastéj smuščájet, i brémja bezzakónij mojích pohružájet mjá. Dážď mí rúku pómošči, i k svítu vozvedí mja umilénija, jáko jedín milosérd i čelovikoľúbec."), ("", "", "Vélija krestá tvojehó Hóspodi síla: vodruzísja bo na mísťi, i ďíjstvujet v míri, i pokazá ot rýbarej apóstoly, i ot jazýk múčeniki, da móľatsja o dušách nášich."), ("Bohoródičen", "", "Vladýčice, predstáteľnice vsích moľáščichsja tebí, tobóju derzájem, i tobóju chválimsja, i k tebí vsé upovánije náše jésť: molí róždšahosja iz tebé, za nepotrébnyja rabý tvojá."), ), ) #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."), ("", "", "Velikoimenítaja jedína, presvjatája Ďívo Maríje Cheruvím slávňijšaja Davídova dščí, i dobróta Jákovľa, Máti Bóha nášeho: vozvelíčisja ziló sláva tvojá, i mý vsí ťa víroju slávim."), ("", "", "Propénšaho slóvom nébo jáko kóžu, tvoíma rukáma jáko čelovíka nosíla jesí: sehó úbo molí neizmínno čístaja strastéj bezslovésija dúšu mojú izbáviti, i ot vsjákija skórbi."), ("", "", "Jáže préžde vsích vík, pronarečénnaja Ďívo, carjá slávy porfíra prečístaja: v ňúže obléklsja v posľídňaja vremená, pokrý kóžnyja rízy Adáma práotca, i mené nýňi pokrýj."), ("", "", "Tľú tvorjáščij drévle hrích ródu čelovíčeskomu, Ďívo Christá róždši, nesterpímyj óhň izsušíla jesí: ťímže strastéj potóki duší mojejá izsuší tvojími molítvami."), ), "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é."), ("", "", "Íže óhnennym vladýčestvom Vladýka i Hospóď tvój Sýn narečésja čístaja: ťímže izbávi mjá Vladýčice, strástnych rabót tvojími molítvami."), ("", "", "Ot búri plotskích strastéj izbávi mjá rabá tvojehó skóro prečístaja, tišinú róždši spasénija, i istóčnik bezstrástija."), ("", "", "Svíta nezachodímaho svitíľnik svitozáren bývši prečístaja, mír prosvitíla jesí: ťímže zarjámi tvojími duší mojejá razorí óblak."), ("", "", "Mértva mjá súšča dušéju, ot mnóžestva zlých strastéj, oživotvorí Vladýčice, jáže róždšaja živodávca Christá neskazánno."), ), "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."), ("", "", "Priíde na mjá plotskáho mudrovánija bráň, i pľiňájet mojú dúšu: no íže vsják úm preimúščij mír róždšaja, tvój mír Vladýčice podážď mí."), ("", "", "Míro úmnoje iz čréva istočíla jesí míru: ťímže ot skvérn strastéj dúšu mojú svobodí, i dážď mí, prečístaja, bezstrástija míro tvojími molítvami."), ("", "", "Stámnu ťá zlatúju, žízni mánnu nosívšuju, Bohomúžnaho Christá, jávi vídyj moľú: nakormí dúšu mojú tájuščuju hládom, i potókom napój Dúcha."), ("", "", "Jéva úbo préžde neuderžánno vvedé smérť: tý že ďívstvom čístym ístinnuju žízň vvelá jesí. Ťímže smérti mjá hrichóvnyja izbávi, tvojími molítvami."), ), "5": ( ("", "", "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."), ("", "", "Izbavlénije nám býv Sýn tvój Ďívo, vsjá ot tlí izbávi: ťímže izbávi mjá plotskáho mudrovánija, i strastéj nastojánija."), ("", "", "Ohném tvojích molítv Bohoródice, strástnych pomyšlénij térnije vsé popalí, jáže kleščá úhľa, čelovíka očístivšaja."), ("", "", "Tý Bóžija jesí júnica, nás rádi požrénaho čelovikoľúbno, božéstvennaho juncá: jehóže božéstvennoju króviju sérdce mojé očísti."), ("", "", "Krásnuju préžde sťažách dobroďítelej odéždu, jejáže sovlekóchsja ľínostiju mojéju: tý že Ďívo, nýňi mjá oblecý v svitľíjšu, tvojími molítvami."), ), "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í."), ("", "", "Pokolebáša chrám duší mojejá zlóby ľútaja kovárstva: no jáko utverdívšaho zémľu na vodách Christá róždšaja, tvojími molítvami utverdí."), ("", "", "Razrišíla jesí dólh zemnoródnych, bísera mnohocínnaho róždši. Ťímže razriší prečístaja skoríje plenícy prehrišénij mojích, i strastéj, i skorbéj."), ("", "", "Dadé vírnym ťá pribížišče, i božéstvennyj pokróv, roždéjsja iz ložésn tvojích Bóh preblahíj. Ťímže prečístaja, i mené pokrýj tvoíma dláňma, i sobľudí."), ("", "", "Volnámi žitijá umovrédno áz okajánnyj částo pohružájem, i rabótami vrážijimi vsehdá oburevájem, nýňi zovú ti: Bohoródice pomozí mi."), ), "S": ( ("", "Podóben", "Božéstvennaja bylá jesí síň Slóva, jedína prečístaja Ďívo Máti, čistotóju ánhely prevozšédšaja: páče vsích bývša mjá oskvernéna plotskími prehrišéniji, očísti molítv tvojích božéstvennymi vodámi, podajúšči čístaja véliju mílosť."), ), "7": ( ("", "", "Jákože drévle blahočestívyja trí ótroki orosíl jesí v plámeni chaldéjsťim, svítlym Božestvá ohném, i nás ozarí, blahoslovén jesí, vzyvájuščyja, Bóže otéc nášich."), ("", "", "Sobóri lukávych bisóv obydóša mjá, i plotstíji sónmi strastéj: no jáko krípkaho vo bránech Christá róždšaja, izbávi mjá částych pečálej i ľútych napádanij."), ("", "", "Jedínyj cheruvímskim suščestvóm nepristúpnyj, i strášnyj ánheľskim činóm, vselísja v ťá čístaja, i nás obnoví: ímže pokaží mja Vladýčice strášna nevídimym vrahóm."), ("", "", "Ráj slovésen Ďívo tý bylá jesí, prozjábšij drévo žízni: jehóže pričáščsja Adám, smértnaho plodá izbávisja. Ťímže i mené nýňi usladí, i strastéj izbávi vkušénija."), ("", "", "Kála mjá strastéj ťilésnaho izbávi, i iskušénij bisóvskich, jáže izbáviteľa róždšaja čelovíkom výšňaho selénije, i chrám osvjaščén, Bóha otéc nášich."), ), "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."), ("", "", "Óblače svíta, svitíla sotvóršaho v míri vélija, dnevnóje že i noščnóe, vsjáko pomračénije razorí, tvojími zarjámi, vsích strastéj i prehrišénij mojích: i pokaží mjá sýna svíta, Bohorodíteľnice."), ("", "", "S nebesé sošédšim doždém vo črévo tvojé Bohoródice, dúšu mojú i sérdce mojé prosvití i orosí: i plámeň uhasí strastéj i skorbéj, da ťá slávľu tépľi vo vsjá víki."), ("", "", "Neizhlahólanno čístaja, premúdrosť Bóžiju, vsjá ot ne súščich nebésnoje i zemnóje jestestvó sovokúpľšuju, tý rodilá jesí, jejáže slóvom dážď mí múdrosť i rázum, jáko da vospojú jávi božéstvennoje tvojé roždestvó."), ("", "", "orosítisja Vladýčice míru tvojími molítvami duší mojéj i ťílu, vopijú i moľúsja: i boľíznej hrichóvnych i strastéj zlóby, izbávitisja vskóri: tý bo jesí vsích čelovíkov iscilénije."), ), "9": ( ("", "", "Na sinájsťij horí víďa ťá v kupiňí Moiséj, neopáľno óhň Božestvá začénšuju vo črévi: Danijíl že ťá víďi hóru nesikómuju: žézl prozjábšij, Isáia vzyváše, ot kórene Davídova."), ("", "", "Postáv Christú Bohotkán javílasja jesí, ot nehóže odéždu plóť Bohonačálňijšu Dúcha prouhotóva: oblecý úbo mené vo odéždu cilomúdrija, čístaja, tvojími molítvami."), ("", "", "Mýslennyj vinohráde, izrastívšij nám hrózd božéstvennyj, ot nehóže napajájemsja vodóju netľínija, istočí mojéj duší umilénije, i vinó očiščénija, tvojími moľbámi."), ("", "", "Čístyj i svjatýj čertóže, ímže jestestvóm Bóh čelovíkom unevísti jestestvó, moľú ťa: sovokupí mja tvojemú Sýnu, i prisvój božéstvennoju žízniju, tvojími moľbámi."), ("", "", "Pážiť tľínija čelovíčeskaho suščestvá, netľínija istóčnika Christá róždši Ďívo, pretvoríla jesí: umertví mi úbo opaľájuščeje, i búrnoje stremlénije strastéj, tvojími moľbámi."), ), ) #let U = ( "S1": ( ("", "", "Živúšči na zemlí, dušé mojá, pokájsja, pérsť bo vo hróbi ne pojét, ni ot prehrišénij izbavľájet. Vozopíj Christú Bóhu: serdcevídče, sohriších tí, préžde dáže ne osúdiši mjá, poščadí mja Bóže, i pomíluj mjá."), ("", "", "Dokóľi dušé mojá prebyváješi v sohrišénijich? Dokóľi prijémleši pokajániju otložénije? Prijimí vo umí súd hrjadúščij, vozopíj Christú Bóhu: serdcevédče, sohriších, bezhríšne Hóspodi, pomíluj mjá."), ("Bohoródičen", "", "Krasoťí ďívstva tvojehó, i presvítloj čistoťí tvojéj, Havriíl udivívsja, vopijáše tí Bohoródice: kúju tí pochvalú prinesú dostójnuju? Čtó že vozymenúju ťá? Nedoumiváju i užasájusja. Ťímže, jákože poveľín jésm, vopijú ti: rádujsja, blahodátnaja."), ), "S2": ( ("", "", "Na strášnom sudíšči bez ohlahóľnikov obličájusja, bez sviďíteľej osuždájusja: kníhi bo sóvistnyja razhibájutsja, i ďilá sokrovénnaja otkryvájutsja: préžde néže vo ónom vsenaródnom pozórišči ímaši ispytáti, jáže mnóju soďíjannaja, Bóže očísti mjá, i spasí mja."), ("", "", "Hlubinú sohrišénij mojích tý vísi Hóspodi: dážď mí rúku pómošči jákože Petrú, i spasí mja."), ("Múčeničen", "", "Bláhodúšnoje terpínija vášeho, pobidí kovárstvo zlonačáľnaho vrahá, strástotérpcy prechváľniji, sehó rádi víčnaho spodóbistesja blažénstva: no molítesja Hóspodevi, Christoľubívych ľudéj spastí stádo, sviďíteľije súšče ístiny."), ("Bohoródičen", "", "Rádujsja Maríje Ďívo Máti, horó svjatája, jedémskij rajú, iz nejáže rodísja <NAME>, bezsímennoje Slóvo, ímže žízň mírovi prozjabé."), ), "S3": ( ("", "<NAME>", "Jehdá sudíšču tvojemú neumýtnomu, i božéstvennomu sudú predstánem, i síly nebésnyja s trépetom tebí predstánut, káko tohdá tebí javľúsja, o sudijé právedňijšij? Ďilá osuždéniju i ohňú imíju dostójna: no ánhel tvojích molítvami poščadí mja tohdá i spasí mja."), ("", "", "Nebésnaja i zemnája slóvom privél jesí, jáko vsesílen: ánheľskija že líki, s trépetom predstojášče, neprestánnuju chvalú tebí prinósjat Vladýko, vsjá ozarjájušče svítom tvojím koncý. S nímiže i mý tebí vopijém: spasí nás blahoutróbijem tvojím."), ("Bohoródičen", "", "Jáko nevozďílannaja Ďívo lozá, krasňíjšij hrózd prozjablá jesí, istočájušč nám vinó spasénija, vsích veseľáščeje dúšy že i telesá. Ťímže jáko vinú ťa dóbrych blažášče prísno, so ánhelom vopijém tí: rádujsja blahodátnaja."), ), "K": ( "P1": ( "1": ( ("", "", "Faraóni kolesnícy hlubinóju pokrýv Hóspodi, móre razvérhl jesí: i spásl jesí písňmi pojúščyja ťá, ľúdi Izráiľteskija."), ("", "", "Prehrišénij ťmý izbávi mjá bezhríšne, jáže bez umá soďíjach, podajá mi slézy umilénija, jákože inohdá bludníci."), ("", "", "Bývša mjá vertép razbójnikom bezmístnymi ďijániji, dobroďítelmi javí čelovikoľúbče chrám tvój, íže vóleju roždéjsja v vertépi."), ("Múčeničen", "", "Okormlénijem Dúcha božéstvennaho pretekóste mučénij búrju, Bohodochnovénniji múčenicy, i k božéstvennomu dostihóste pristánišču."), ("Múčeničen", "", "Prosvitívšesja blahodátiju Dúcha múčenicy, ťmý hlubočájšija idolobísija ubižáste, rádujuščesja prechváľniji."), ("Bohoródičen", "", "Vsesvjatája i prečístaja, hríšnym pomóščnice, pádajuščym ispravlénije, pokajánije mí dážď umilénija mnohosohrišívšemu."), ), "2": ( ("", "", "Písň nóvuju pojím ľúdije, ot Ďívy róždšemusja vo spasénije náše, i jedíno sotvóršemu s nebésnymi zemnája, jáko proslávisja."), ("", "", "Beznačálen svít, i podátelen svitojavlénija sýj vsehó Christé Bóže, mojé pomyšlénije prosvití predstáteľstvom tvojích síl."), ("", "", "Rádujuščesja anheloľípno, vsebohátym pričástijem ánheľstiji lícy, tvojími Spáse krásnymi sijániji tájno oblistájutsja."), ("", "", "Jáko blahíj životvórec blahoďíteľnyj Dúch ischoďáj ot Otcá, nebésnyja síly utverdí neprikosnovénnymi božéstvennymi blahodáťmi."), ("Bohoródičen", "", "Činonačáľniče Bóžij Havrijíle bezplótnych likóv, i nýňi preboháte, hlás rádosten obrádovanňij vozopíj: rádujsja vseneporóčnaja."), ), ), "P3": ( "1": ( ("", "", "Utverdí mené Hóspodi, jedíne mnohomílostive, i prostrí mi rúku jáko Petróvi, i spasí mja."), ("", "", "Jákože Petrá pohružájema spásl jesí čelovikoľúbče: táko i mené iz hlubiný prehrišénij mojích vozvedí."), ("", "", "Umertví mja ľstívyj strasťmí ubív: tý že mjá žiznodáteľu pokajánija óbrazy oživí."), ("Múčeničen", "", "Ohném veščéstvennym múčenicy neprávedno opaľájemi, neveščéstvenňi neveščéstvennaho vospalístesja želánijem."), ("Múčeničen", "", "Múčenicy rasterzájemi, rasterzánija i lovlénija pohubíša ľstívaho, i vincév spodóbišasja."), ("Bohoródičen", "", "Maríje Hospodoimenítaja, mnóhimi obladájema mjá strasťmí dušetľínnymi, svobodí molítvami tvojími."), ), "2": ( ("", "", "Lúk sokrušíl jesí vrážiji, i ščitý stérl jesí krípostiju Vladýko Christé, utverždénije náše, svját jesí Hóspodi."), ("", "", "Strují tekúščyja i ríki bláhosti, javíl jesí blahíj ánheľskija líki, sokrovénnaho tvojehó táinstva zaréju sijájuščich."), ("", "", "Da pokážeši jávi sokróvišča bohátstva tvojehó, i kríposti Vladýko Christé, tvojejá slávy pričástniki úmnyja síly privél jesí."), ("", "", "S trépetom tebí služébňi ánheľskija svítlosti predstojášče, pojút prísno tvojú sílu Christé neisčetnosíľnuju."), ("Bohoródičen", "", "Vsehó priját iz tebé neizmínno čelovíka, íže Vladýka sehó vsehó Bohomáti, i tebé istóčnika blahodáti javíl jésť."), ), ), "P4": ( "1": ( ("", "", "Jedá v rikách prohňívaješisja Hóspodi? Jedá v rikách járosť tvojá, ilí v móri ustremlénije tvojé?"), ("", "", "Razriší soúzy strastéj mojích Hóspodi, pokajánijem mjá svjazáv, i pričástnika javí blahích tvojích."), ("", "", "Vozsijáj mí svitozárnyja pokajánija óbrazy, sólnce sýj Christé, zól mojích othoňája nóšč hlubókuju."), ("Múčeničen", "", "Javístesja múdriji stradáľcy, jákože úhlije véšč bezbóžija popaľájušče, i súščyja vo ťmí prosviščájušče."), ("Múčeničen", "", "Mértvosti Christóvi upodóbistesja múčenicy, boľíznem primisívšesja razlíčnym: ťímže božéstvennuju žízň nasľídovaste."), ("Bohoródičen", "", "Dážď mí čístaja ístinnoje pokajánije, utíši strastéj mojích molvú, sohrišájuščym predstáteľnice."), ), "2": ( ("", "", "Stránna i neizrečénna roždestvá tvojehó tájna: uslýšach slúch tvój, i ubojáchsja, i veseľásja vopijú ti: síľi tvojéj sláva čelovikoľúbče."), ("", "", "Óblacy íže trisólnečnoje svitozarénije prijémľušče, prinesóstesja božéstvennym choťínijem, Tróičeskaja ukrašénija, okormľájemi síloju Dúcha."), ("", "", "V mír posylájutsja k choťáščym vírovati tebí, jákože chranítelije spasénija blahočestívych ánheli, sobľudájušče Spáse rabý tvojá."), ("", "", "Prosviščájutsja tájno ánheli, čístym približénijem, i Bohonačáľnym tvojím osijánijem: síľi tvojéj sláva, zovúšče, čelovikoľúbče."), ("Bohoródičen", "", "Rábski molébnik nýňi prichoždú v króv tvój preneporóčnaja: izbávi mjá Bohorodíteľnice strastéj smuščénija, jáže bezstrástiju vinóvnaho róždšaja."), ), ), "P5": ( "1": ( ("", "", "Svítom tvojím nevečérnim Christé, ozarí Bóže smirénnuju mojú dúšu, i nastávi na strách tvój: zané svít poveľínija tvojá."), ("", "", "Ne postávi mené náha ot ďíl dóbrych, na sudíšči tvojém čelovikoľúbče: no vo odéždu božéstvennych ďijánij oblecý pokajánijem."), ("", "", "Ujazvíchsja orúžijem strastéj, i v róv otčájanija vpadóch: ne prézri Vladýko, no iscilí mja obraščénija býlijem."), ("Múčeničen", "", "I nohťmí strúžemi ľúťi, i mečém stradáľcy ubivájemi, i ránami iznurjájemi, ne pokloníste istukánnym koľína."), ("Múčeničen", "", "Mír stradáňmi vášimi krasújetsja prísno svjatíji múčenicy: premírnoje jáko obritóste prebyvánije so ánhely."), ("Bohoródičen", "", "Jáže jedína slóvom na zemlí, plótiju Slóvo róždši, i Ďíva prebývši, bezslovésnych mjá izbávi ďijánija, jáko da slovesý čestnými vospiváju ťá."), ), "2": ( ("", "", "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."), ("", "", "So Otcém Sýna i Dúcha, trisijánnym svítom prosvíščšesja vírniji, vospojím jedíno Božestvó, so ánheľskimi vójinstvy."), ("", "", "Sviščý soobraščájuščyjasja, nezachodímym sijánijem Božestvá prebožéstvennaho, projavlénňi oboháščšesja, ánheľstiji číny propovídajut."), ("", "", "Jedíno načálo prebeznačáľnoje čestí Serafímy učát, vopijúšče hlás trisvjatýj jávi, Dúchom prosviščájemi ánheli Božestvá."), ("Bohoródičen", "", "Bez símene, otrokovíce, tebí archánhel Havrijíl rodíti životodávca blahovistí, Bohoródice vsečístaja, s nebesé sošéd."), ), ), "P6": ( "1": ( ("", "", "Íž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."), ("", "", "Prevoznéssja mýsliju, jákože drévnij fariséj prehrišénijem nizpadóchsja ľúťi, i zrjá mja ľstívyj, veselítsja, Christé: ímže smirívyj sehó krestóm, smirívšasja nýňi uščédri mjá."), ("", "", "Hrichoľubív v žitijí býv, jákože ín niktóže Vladýko, iždích tvojé dolhoterpínije okajánnyj, i ješčé jésm nečúvstven, no obratí mja tvojím blahoutróbijem."), ("Múčeničen", "", "Járostnym proizvolénijem, zakonoprestúpnicy Bohomúdrennych osuždájušče, ohném i sožžénijem i probodéňmi, zláta svitľíjše jáko voístinnu pokazáša, i Christú snasľídniki."), ("Múčeničen", "", "Sudíšče ispólneno borénij, i pódvihov prevelíkich, i páče jestestvá rány prešédše, pobidíste kňázja ťmý, i ot Bóha prijáste stradáľcy vincý."), ("Bohoródičen", "", "Kovčéh zavíta, svjatúju voístinnu trapézu, očistílišče náše, cérkov Bóžiju oduševlénnuju, vsezlatýj svíščnik, ístinnuju Máter ziždíteľa vospivájem."), ), "2": ( ("", "", "<NAME>, jéže v preispódňim áďi, jestéstvennyj óbraz býv, vopijáše: vozvedí ot tlí živót mój, čelovikoľúbče."), ("", "", "Pérvoje i vseďíteľnoje Bohonačálija sijánije, archánheli i ánheli, síľno pojút zovúšče, s načály i vlasťmí i sílami, hlásy nemólčnymi Hóspoda."), ("", "", "Pérvoje i vseďíteľnoje Bohonačálija sijánije, archánheli i ánheli, síľno pojút zovúšče, s načály i vlasťmí i sílami, hlásy nemólčnymi Hóspoda."), ("", "", "Íže mír úmnyj vseslíčnym čínom po činú ukrašéj nevídimo, semú upodobľátisja blahočíniju, čestnúju cérkov bláhovolí."), ("Bohoródičen", "", "Iscilénij ťá istóčnik prisnotekúšč, jéže v ťá vséľšejesja Slóvo pokazá: mojejá úbo duší jázvy Bohoródice Ďívo iscilí."), ), ), "P7": ( "1": ( ("", "", "Trijé ótrocy v peščí Tróicu proobrazívše, preščénije óhnennoje popráša, i pojúšče vopijáchu: blahoslovén jesí Hóspodi Bóže otéc nášich."), ("", "", "Vréma mojé skončavájetsja o dušé, pri dvérech ischód, pokajánija úbo plodý pokaží, préžde dáže dvéri ne zatvorjátsja, vozopíj Christé: Hóspodi, spasí mja."), ("", "", "Obnovím serdcá rálom ístinnaho poznánija, pokajánija pšenícu síjušče, jáko da póžnem klás právdy, o Chrisťí vozďílateľi dúš nášich."), ("Múčeničen", "", "Svitíla blahočéstija, nečéstija soprotivobórcy, níščich obohatítelije, Hospódni múčenicy, preokajánnuju mojú dúšu lišénnuju, dobroďíteľmi obohatíte."), ("Múčeničen", "", "Íže spasýj mytarjá iz hlubiný vozdochnúvša, i mojé máloje vozdychánije prijimí, i spasí mja strástotérpec rádi, proslávľšich ťá Christé svojími údy."), ("Bohoródičen", "", "Istóčniče, íže vódu ostavlénija istočájušči, tečénija mojích prehrišénij izsuší, podajúšči mí túču sléz, da ťá prísno jáko Bohoródicu pojú."), ), "2": ( ("", "", "Hórdyj mučíteľ, no ďitéj býsť ihrálišče: jákože bo pérsť poprávše sedmeríčnyj plámeň, pojáchu: blahoslovén jesí Hóspodi, Bóže otéc nášich."), ("", "", "Tvérdym umóm i dóblestvennym ókom, zrjášče pervonačáľnyja svítlosti, pričástijem byvájete svíti vtoríji, ánheľstiji lícy, blahoslovén jesí, zovúšče, Bóže otéc nášich."), ("", "", "Tvérdym umóm i dóblestvennym ókom, zrjášče pervonačáľnyja svítlosti, pričástijem byvájete svíti vtoríji, ánheľstiji lícy, blahoslovén jesí, zovúšče, Bóže otéc nášich."), ("", "", "Neuklónnym želánijem, i neizdáteľnoju ľubóviju vodími súšče, dobrótami ziždíteľa, položénijem býste svitíla vtorája, lícy ánheľstiji, blahoslovén jesí zovúšče, Bóže otéc nášich."), ("Bohoródičen", "", "Voploščénnoje rodilá jesí Bohoródice, Slóvo beznačáľnoje, jéže iz Otcá bez Mátere predvíčnoje božéstvennym roždestvóm. Blahoslovén Vladýčice, plód tvojehó čréva."), ), ), "P8": ( "1": ( ("", "", "V plámeň ko otrokóm jevréjskim snizšédšaho Bóžijeju síloju, i jávľšahosja Hóspoda, svjaščénnicy blahoslovíte , i prevoznosíte vo vsjá víki."), ("", "", "Ot posmíšstva chrám otéčeskim izrečénijem ráb býsť: čtó sotvoríši dušé mojá, porabotívšisja strastém i bezčínno smijúščisja, i ne styďáščisja nebésnaho Otcá?"), ("", "", "Vraždováv Káin bezúmno bratoubíjca býsť: semú podóbna javílasja jesí, i ne ináho ubívši, no sebé sámuju dušé mojá, slastoľúbijem i prélesťmi žitijá."), ("Múčeničen", "", "Izbránnyja bísery Hospódni, sosúdy čestnýja, sviťáščyjasja sviščý zaréju božéstvennyja blahodáti, Christóvy strastotérpcy, víroju sošédšesja počtím dostójno."), ("Múčeničen", "", "Íže múdrych strastotérpec króv, páče kadíla prijém Slóve, ťích moľbámi pokajánijem k tebí pripádajuščich spasí, jáko jedín mílostiv."), ("Bohoródičen", "", "Izlíšestvom blúdnaho žitijá, ko ádu nýňi priblížichsja: premnóhoje blahoutróbije otrokovíce imúšči, jáko Bóha blahoutróbnaho róždši neizrečénno, uščédrivši spasí mja."), ), "2": ( ("", "", "Veščéstvennaho ohňá plámeň neveščéstvennym uvjadíša, Bohozrímiji ótrocy, i pojáchu: blahoslovíte vsjá ďilá Hospódňa Hóspoda."), ("", "", "Jáko vsích soďíteľ, ánhely umýslil jesí, i predstáša tí so stráchom, zovúšče: blahoslovíte vsjá ďilá Hospódňa Hóspoda, pójte i prevoznosíte jehó vo víki."), ("", "", "Pričástijem božéstvennaho ohňá, jákože plámeň bývše nebésnyja umý zovút: blahoslovíte vsjá ďilá Hospódňa Hóspoda, pójte i prevoznosíte jehó vo víki."), ("", "", "Neveščéstvennyja i úmnyja ánhely préžde sostávil jesí vídimych vsích, neprestánno tebí zovúščich: blahoslovíte vsjá ďilá Hospódňa Hóspoda, pójte i prevoznosíte jehó vo víki."), ("Bohoródičen", "", "Slóvo Ótčeje, páče slóva voploščénnoje Bohorodíteľnice Ďívo rodilá jesí: jehóže pojút vsjá ďilá jáko Hóspoda, i prevoznósjat vo vsjá víki."), ), ), "P9": ( "1": ( ("", "", "Na sinájsťij horí víďi ťá v kupiňí Moiséj, neopáľno óhň Božestvá začénšuju vo črévi: Danijíl že ťá víďi hóru nesikómuju, žézl prozjábšij, Isáia vzyváše, ot kórene Davídova."), ("", "", "Jákov pérvenstvo priját, rádi vozderžánija inohdá, Isáv že staríjšinstvo otdadé, ne uderžáv črévo. Kóľ zló nevozderžánije, i kóľ velíko vozderžánije! Bíhaj nepodóbija, vozľubí, o dušé, dóbrych pribavlénije."), ("", "", "Jáko mnóhaja preterpív neporóčnyj, vinčásja Jov: iskušénij bo stékšesja potócy, ne pokolebáša jemú serdéčnaho stolpá. Tomú revnúj vsehdá, neprelóžna prebyvájušči, o dušé, lukávaho kozňmí."), ("Múčeničen", "", "Obostrívšesja ohném božéstvennaho Dúcha, mečí javístesja jávi, sikúšče polkí protívnyja, strástonóscy Christóvy, i velíkimi pobídami proslavľájemi, vinčástesja vsesíľnoju rukóju vsích carjá."), ("Múčeničen", "", "Mnóžestvo múčenik neporóčnoje, bezmírnych mojích zól mnóžestvo, očístiti molíte Vladýku i Bóha, váša neizrečénnyja trudý prijémšaho, i so bezplótnych vóinstvy vás sočetávšaho."), ("Bohoródičen", "", "Svítlaja Vladýčňaja paláta, dóm mjá pokaží svíta, neprochodímaja dvére, otvérzi mí pokajánija putí, zemlé svjatája, k zemlí mja krótkich nastávi Vladýčice, vsjákaho mjá vladýčestva strastéj javí svobódna."), ), "2": ( ("", "", "Sládkoju prečístaho tvojehó roždestvá strilóju ujázvleni čístaja, tvojéj dostoželánňij dobróťi divjáščesja, písňmi ánheľskimi dostójno ťá, jáko <NAME>óžiju veličájem."), ("", "", "Íže svítu velíkomu i pérvomu nýňi predstojášče lícy, molítvennicy siľňijšiji býste o vsích nás, vás, jákože móščno, o božéstvenňijšiji ánheli Bóžiji, veličájuščich."), ("", "", "Íže svítu velíkomu i pérvomu nýňi predstojášče lícy, molítvennicy siľňijšiji býste o vsích nás, vás, jákože móščno, o božéstvenňijšiji ánheli Bóžiji, veličájuščich."), ("", "", "Ravnosíľnuju Tróicu sláviti spodóbľšesja jásno, tojá sijánijem pérvije osviščájemi, osvitítisja vtorým sijánijem spodóbite nás, íže vás blahočéstno veličájuščich."), ("Bohoródičen", "", "Ťá nášeho spasénija osnovánije vsí vímy: tvojé bo prečístoje roždestvó spasló jésť, króviju Bohoďíteľnoju, pojúščyja ťá Bohoródice, i vírno slávjaščyja."), ), ), ), "ST": ( ("", "", "Razsíjannyj mój úm soberí Hóspodi, i oľadeňívšeje sérdce mojé očísti, jáko Petrú dajá mi pokajánije, jáko mytarjú vozdychánije, i jákože bludníci slézy, da vélijim hlásom zovú ti: Bóže spasí mja, jáko jedín blahoutróben i čelovikoľúbec."), ("", "", "Mnóžiceju pínije soveršája, obritóchsja hrích skončavája, jazýkom úbo pínije viščája, dušéju že bezmístnaja pomyšľája: no obojé isprávi Christé Bóže pokajánijem, i spasí mja."), ("Múčeničen", "", "Svjatých strástotérpec pámjať, prijidíte ľúdije, vsí počtím, jáko pozór bývše ánhelom i čelovíkom, pobídy vincý ot Christá prijáša, i móľatsja o dušách nášich."), ("Bohoródičen", "", "Svjatopervočístaja pochvaló súšči nebésnych činóv, apóstolov pínije, i prorókov sbytijé, Vladýčice, prijimí molítvy náša."), ) ) #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, v cárstviji tvojém."), ("", "", "Zól mojích mnóžestvo, po mnóžestvu mílosti tvojejá, Christé, prezrív spasí mja: i v déň súdnyj osuždénija izbávi mjá Spáse, i víčnaho mučénija, jáko da pisnoslóvľu tvojú blahostýňu."), ("", "", "Cheruvími i Serafími, prestóli, archánheli, síly, i načála, i Hospóďstvija, ánheli i vlásti vsjá, umolíte soďíteľa, prezríti tohdá mojá sohrišénija, jehdá chóščet sudíti zemlí, jáko čelovikoľúbec."), ("", "", "Ot krovéj svjaščénnych bahrjanícu omočívše Christóvy stradáľcy, carjú síl scárstvovati voístinnu spodóbišasja Bohoľípno: i nám prósjat prehrišénij ostavlénija, dostójno ťích vsehdá počitájuščym."), ("", "", "Triipostásnoje vírniji jedíno Božestvó, pojúšče blahočéstno, Otcá, i Slóva, i svjatáho Uťíšiteľa Dúcha, ánheľski vozopijím hlásy nemólčno: svját, svját, svját jesí Bóže, spasájaj dúšy náša."), ("Bohoródičen", "", "Jáže svít ot svíta róždšaja, óblače svítlyj, omračénnaho mjá strasťmí i slasťmí žitijá, ko svítu nastávľši, isprávi čístaja, i ulučíti slávu molísja, júže polučíša nýňi, íže dóbri požívšiji."), ) )
https://github.com/deadManAlive/ui-thesis-typst-template
https://raw.githubusercontent.com/deadManAlive/ui-thesis-typst-template/master/intro.typ
typst
#lorem(128): #for i in range(5) [ + #lorem(40 - 5 * i) ] #lorem(80) #v(4em) // signature next
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2024/WS-03.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (1 - 32)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [1], [SUN Yingsha], [CHN], [3647], [2], [CHEN Meng], [CHN], [3366], [3], [WANG Manyu], [CHN], [3360], [4], [HAYATA Hina], [JPN], [3286], [5], [CHEN Xingtong], [CHN], [3265], [6], [ZHU Yuling], [MAC], [3222], [7], [WANG Yidi], [CHN], [3169], [8], [CHENG I-Ching], [TPE], [3156], [9], [ITO Mima], [JPN], [3146], [10], [HIRANO Miu], [JPN], [3139], [11], [QIAN Tianyi], [CHN], [3135], [12], [HE Zhuojia], [CHN], [3115], [13], [KIHARA Miyuu], [JPN], [3103], [14], [ZHANG Rui], [CHN], [3098], [15], [JEON Jihee], [KOR], [3092], [16], [HARIMOTO Miwa], [JPN], [3084], [17], [SZOCS Bernadette], [ROU], [3077], [18], [KUAI Man], [CHN], [3054], [19], [HASHIMOTO Honoka], [JPN], [3037], [20], [HAN Ying], [GER], [3031], [21], [FAN Siqi], [CHN], [3028], [22], [ISHIKAWA Kasumi], [JPN], [3014], [23], [<NAME>], [GER], [3012], [24], [<NAME>], [CHN], [2997], [25], [YANG Xiaoxin], [MON], [2992], [26], [SHI Xunyao], [CHN], [2966], [27], [CHEN Yi], [CHN], [2965], [28], [OJIO Haruna], [JPN], [2964], [29], [DI<NAME>], [PUR], [2947], [30], [NAGASAKI Miyu], [JPN], [2935], [31], [SHIBATA Saki], [JPN], [2935], [32], [JOO Cheonhui], [KOR], [2898], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (33 - 64)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [33], [ANDO Minami], [JPN], [2886], [34], [SATO Hitomi], [JPN], [2886], [35], [TAKAHASHI Bruna], [BRA], [2864], [36], [<NAME>], [JPN], [2857], [37], [POLCANOVA Sofia], [AUT], [2855], [38], [SHIN Yubin], [KOR], [2853], [39], [DOO Hoi Kem], [HKG], [2832], [40], [<NAME> Gyong], [PRK], [2830], [41], [LEE Zion], [KOR], [2822], [42], [<NAME>], [IND], [2812], [43], [<NAME>], [USA], [2808], [44], [<NAME>], [FRA], [2795], [45], [<NAME>], [CHN], [2791], [46], [<NAME>], [FRA], [2790], [47], [<NAME>], [CHN], [2789], [48], [<NAME>], [ROU], [2785], [49], [<NAME>], [THA], [2783], [50], [<NAME>], [GER], [2778], [51], [<NAME>], [JPN], [2775], [52], [<NAME>], [ROU], [2772], [53], [<NAME>], [CHN], [2765], [54], [<NAME>], [ROU], [2763], [55], [QIN Yuxuan], [CHN], [2748], [56], [XU Yi], [CHN], [2746], [57], [<NAME>], [SGP], [2743], [58], [WANG Xiaotong], [CHN], [2738], [59], [YANG Yiyun], [CHN], [2737], [60], [BAJOR Natalia], [POL], [2736], [61], [<NAME>], [SWE], [2735], [62], [LEE Eunhye], [KOR], [2731], [63], [<NAME>], [GER], [2723], [64], [<NAME>], [KOR], [2723], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (65 - 96)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [65], [MESHREF Dina], [EGY], [2718], [66], [HAN Feier], [CHN], [2712], [67], [YANG Ha Eun], [KOR], [2710], [68], [XIAO Maria], [ESP], [2706], [69], [QI Fei], [CHN], [2704], [70], [KIM Nayeong], [KOR], [2702], [71], [YU Fu], [POR], [2696], [72], [PESOTSKA Margaryta], [UKR], [2694], [73], [LEE Ho Ching], [HKG], [2693], [74], [WANG Amy], [USA], [2689], [75], [SASAO Asuka], [JPN], [2688], [76], [AKULA Sreeja], [IND], [2688], [77], [KIM Hayeong], [KOR], [2687], [78], [ZHU Chengzhu], [HKG], [2685], [79], [CHOI Hyojoo], [KOR], [2670], [80], [FAN Shuhan], [CHN], [2666], [81], [NI Xia Lian], [LUX], [2663], [82], [LIU Hsing-Yin], [TPE], [2662], [83], [HUANG Yi-Hua], [TPE], [2659], [84], [NG Wing Lam], [HKG], [2656], [85], [SHAO Jieni], [POR], [2656], [86], [LI Yu-Jhun], [TPE], [2655], [87], [SAWETTABUT Jinnipa], [THA], [2647], [88], [RAKOVAC Lea], [CRO], [2645], [89], [WEGRZYN Katarzyna], [POL], [2635], [90], [ZHANG Mo], [CAN], [2633], [91], [ARAPOVIC Hana], [CRO], [2632], [92], [LUTZ Charlotte], [FRA], [2624], [93], [ZHU Sibing], [CHN], [2622], [94], [CHEN Szu-Yu], [TPE], [2618], [95], [KIM Byeolnim], [KOR], [2613], [96], [WINTER Sabine], [GER], [2606], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (97 - 128)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [97], [SAWETTABUT Suthasini], [THA], [2604], [98], [LIU Yangzi], [AUS], [2603], [99], [KAMATH Archana Girish], [IND], [2603], [100], [EERLAND Britt], [NED], [2600], [101], [POTA Georgina], [HUN], [2600], [102], [HUANG Yu-Chiao], [TPE], [2595], [103], [WAN Yuan], [GER], [2592], [104], [ZONG Geman], [CHN], [2584], [105], [<NAME>], [SRB], [2583], [106], [<NAME>], [EGY], [2582], [107], [<NAME>], [SUI], [2580], [108], [CHIEN Tung-Chuan], [TPE], [2578], [109], [CIOBANU Irina], [ROU], [2577], [110], [NOMURA Moe], [JPN], [2574], [111], [LIU Jia], [AUT], [2574], [112], [MUKHERJEE Ayhika], [IND], [2570], [113], [<NAME>], [HUN], [2564], [114], [YANG Huijing], [CHN], [2559], [115], [ZH<NAME>yu], [CHN], [2558], [116], [AKAE Kaho], [JPN], [2550], [117], [CHENG Hsien-Tzu], [TPE], [2546], [118], [TOLIOU Aikaterini], [GRE], [2542], [119], [MUKHERJEE Sutirtha], [IND], [2541], [120], [GHORPADE Yashaswini], [IND], [2541], [121], [<NAME>], [KOR], [2537], [122], [ZHANG Sofia-Xuan], [ESP], [2533], [123], [HO Tin-Tin], [ENG], [2527], [124], [SU Pei-Ling], [TPE], [2523], [125], [MALOBABIC Ivana], [CRO], [2513], [126], [<NAME>], [ROU], [2511], [127], [<NAME>], [SVK], [2510], [128], [<NAME>], [SWE], [2507], ) )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/glossarium/0.1.0/README.md
markdown
Apache License 2.0
# Typst glossary > Glossarium is based in great part of the work of [<NAME>](https://github.com/Dherse) from his master thesis available at: <https://github.com/Dherse/masterproef>. His glossary is available under the MIT licence [here](https://github.com/Dherse/masterproef/blob/main/elems/acronyms.typ). Glossarium is a simple, easily customizable typst glossary inspired by [LaTeX glossaries package](https://www.ctan.org/pkg/glossaries) . You can see an example showing the different features in [`example.typ`](example/example.typ). ![Screenshot](example/example.png) ## Manual ### Import and setup This manual assume you have a good enough understanding of typst markup and scripting. For Typst 0.6.0 or later import the package from the typst preview repository: ```ts #import "@preview/glossarium:0.1.0": make-glossary, print-glossary, gls, glspl ``` For Typst before 0.6.0 or to use **glossarium** as a local module, download the package files into your project folder and import `glossarium.typ`: ```js #import "glossarium.typ": make-glossary, print-glossary, gls, glspl ``` After importing the package and before making any calls to `gls`,` print-glossary` or `glspl`, please ***MAKE SURE*** you add this line ```js #show: make-glossary ``` > *WHY DO WE NEED THAT ?* : In order to be able to create references to the terms in your glossary using typst ref syntax `@key` glossarium needs to setup some [show rules](https://typst.app/docs/tutorial/advanced-styling/) before any references exist. This is due to the way typst works, there is no workaround. > >Therefore I recommend that you always put the `#show: ...` statement on the line just below the `#import` statement. ### Printing the glossary First we have to define the terms. A term is a [dictionary](https://typst.app/docs/reference/types/dictionary/) composed of 2 required and 2 optional elements: - `key` (string) *required*: used to make reference to the term. - `short` (string) *required*: the short form of the term replacing the term citation. - `long` (string or content) *optional*: The long form of the term, displayed in the glossary and on the first citation of the term. - `desc` (string or content) *optional*: The description of the term. Then the terms are passed as a list to `print-glossary` ```ts #print-glossary(( // minimal term (key: "kuleuven", short: "KU Leuven"), // a term with a long form (key: "unamur", short: "UNamur", long: "Université de Namur"), // no long form here (key: "kdecom", short: "KDE Community", desc:"An international team developing and distributing Open Source software."), // a full term with description containing markup ( key: "oidc", short: "OIDC", long: "OpenID Connect", desc: [OpenID is an open standard and decentralized authentication protocol promoted by the non-profit #link("https://en.wikipedia.org/wiki/OpenID#OpenID_Foundation")[OpenID Foundation].]), )) ``` You can call this function from anywhere. ### Referencing terms. Referencing terms is done using the key of the terms using the `gls` function or the reference syntax. ```ts // referencing the OIDC term using gls #gls("oidc") // displaying the long form forcibly #gls("oidc", long: true) // referencing the OIDC term using the reference syntax @oidc ``` #### Handling plurals You can use the `glspl` function and the references supplements to pluralize terms: ```ts #glspl("oidc") // equivalent of `#gls("oidc", suffix: "s")` // or @oidc[s] ``` ## Final tips I recommend setting a show rule for the links to that your reader understand that they can click on the references to go to the term in the glossary. ```ts #show link: set text(fill: blue.darken(60%)) // links are now blue ! ```
https://github.com/usami-k/technote
https://raw.githubusercontent.com/usami-k/technote/main/2024/apple-vision-pro-eyes/apple-vision-pro-eyes.typ
typst
Creative Commons Attribution 4.0 International
#import "@preview/touying:0.4.2": * #let s = themes.metropolis.register( aspect-ratio: "16-9", footer: self => "『" + self.info.title + "』" + states.current-section-title, ) #let s = (s.methods.info)( self: s, title: [Apple Vision Proのフォーカス操作], author: [宇佐見公輔], date: [2024-07-17], institution: [株式会社ゆめみ], ) #let (init, slides, touying-outline, alert, speaker-note) = utils.methods(s) #show: init #set text(font: "IBM Plex Sans JP", size: 26pt) #show link: it => underline(text(blue, it)) #let (slide, empty-slide, title-slide, new-section-slide, focus-slide) = utils.slides(s) #show: slides.with(outline-slide: false) == 自己紹介 #grid( columns: 2, gutter: 1em, [ - 宇佐見公輔 - 株式会社ゆめみ - iOSテックリード - iOSDC Japan 2024 - パンフレット記事執筆 - ポスターセッション ], grid( rows: 2, image("images/c40d5199-526b-4bf9-91d7-2a0bc609b305.png", height: 50%), image("images/a28236ac-e8b0-4015-84e9-a0c9ac6670af.png", height: 50%) ), ) == 今日の内容 #touying-outline() = Apple Vision Proの操作感 == Apple Vision Pro購入 #grid( columns: 2, gutter: 1em, [ - Apple Vision Pro日本発売 - 2024年6月28日 - 発売日に購入 - 翌日にオンラインイベントに登壇してみたりした ], image("images/vision_2024-06-29.jpeg"), ) == 操作感に関する個人的な所感:良いところ - 空間にウィンドウを置けるのが心地よい - パススルーのおかげで実際の空間に置いている感覚 - Mac仮想ディスプレイとvisionOSアプリが共存する空間 - 手のジェスチャ操作は良い感じ - わりとちゃんと認識される - 重さや熱さは気にならない - 細かいフィッティングによる良好な装着感 - バッテリーは外付け == 操作感に関する個人的な所感:気になるところ - フォーカス操作が難しい - 視線によるフォーカス移動 - 注視によるフォーカス固定 装着感は良いのだが、次の理由で長時間の使用がたいへん。 - 操作がうまくいかないストレス - 視線を動かすことによる目の疲労 = 視線と注視による操作 == ユーザガイド #link("https://support.apple.com/ja-jp/guide/apple-vision-pro/welcome/visionos")[Apple Vision Proユーザガイド] #image("images/guide_tap.png") 丁寧なユーザガイドだが、視線や注視についてはあまり詳しくない。直感的に理解できるはず、という意図だろう。 == 理解はできるが実践が難しい 理解はできるが、実際には次のようなことが起こる。 - 視線を移動しても、フォーカスがうまく移動しない - 対象を注視していても、フォーカスが移動してしまう このため、次のような問題が発生する。 - 選択したい項目に、フォーカスを当てられない - 選択するときに、意図と異なる項目をタップしてしまう == 自分だけの問題ではなかった 自分の操作が下手なだけかとも思ったが、ゆめみの同僚も同じような感想を持っていた。 視線の設定(キャリブレーション)をやり直せば改善はしたが、根本的な解決には至らない。 == ポインタ表示 #grid( columns: (1fr, auto), gutter: 1em, [ アクセシビリティ設定でポインタを表示できる。 画像の中央あたりの緑丸がポインタ ], image("images/a11y_pointer.jpeg"), ) == 視線は動き回る ポインタ表示すると、視線の動きがわかる。 - 何もしていないときに、視線はふらふらと動き回る - 視線を移動させたときに、意識と視線は意外と一致しない - 注視したときに、視線は固定せずに動いている 視線はじっとしていないで、常に動き回っているもの。 == 補足:フォーカス項目を分かりやすくする #grid( columns: (1fr, auto), gutter: 1em, [ フォーカスのコントラストを上げる設定がある。 ], image("images/a11y_contrast.jpeg"), ) = 操作しやすいUIは? == 参考セッション・ガイドライン - #link("https://developer.apple.com/jp/videos/play/wwdc2023/10073/")[空間入力のためのデザイン - WWDC23] - #link("https://developer.apple.com/jp/videos/play/wwdc2023/10076/")[空間ユーザーインターフェイスのためのデザイン - WWDC23] - #link("https://developer.apple.com/jp/videos/play/wwdc2024/10086/")[優れたvisionOSアプリのデザイン - WWDC24] - #link("https://developer.apple.com/jp/design/human-interface-guidelines/eyes")[視線 - ヒューマンインターフェースガイドライン] これ以外にも、visionOSのデザインに関するセッションやガイドラインがある。 == 項目の中央に視線を誘導する #grid( columns: 2, gutter: 1em, [ 視線の移動や注視が難しいことを考慮した注意点がある。 - 丸い形で中央に視線を誘導 - 鋭い形は外側に注意が逃げる - 外側に縁取りを入れるのも同様によくない ], grid( rows: 2, image("images/wwdc_circle.jpeg", height: 50%), image("images/wwdc_edge.jpeg", height: 50%) ), ) == ボタンの大きさ・間隔 #grid( columns: 2, gutter: 1em, [ - ボタンのタップ領域は60pt - ボタンの表示領域は44pt - 表示領域の間隔は16pt ポインタが見た目で正確にあっていなくても、タップが可能になっている。 ], image("images/wwdc_buttons.jpeg"), ) == 現在のvisionOSのUIの不満点 #grid( columns: 3, gutter: 1em, [ 選択しづらいUIがいくつかある。 例えば: - メニュー - アラート これらは、現状の不満点。 ], image("images/photo_menu.jpeg"), image("images/photo_alert.jpeg"), ) == 選択しづらい要因は? メニューやアラートを選択しやすくするには、どのようなUIが良いのだろうか? 現状のセッションやガイドラインで言及されている注意点だけでは、不十分なのではないか? visionOSはiOSの知見が活かされた優れたOSだが、空間入力の特性を考慮したUI設計はまだ改善点がありそう。 = 視線以外のフォーカス操作 == 視線以外のポインタコントロール アクセシビリティ設定のポインタコントロールでは、視線以外の操作も選べる。 - 視線 - 頭 - 手首(左手または右手) - 人差し指(左手または右手) 視線以外は比較的ポインタを操作しやすい。ただし、頭や手が疲れやすいので一長一短。 == トラックパッド・マウス Magic TrackpadをApple Vision ProにBluetoothで接続できる(残念ながら手持ちがないので試していない)。 visionOS 2では、マウスもBluetoothで接続できる。 なお、ゲームコントローラも接続できるが、これは特定のアプリ内でのみ有効なようだ。 == Macのトラックパッド Mac仮想ディスプレイの機能を使ってMacのディスプレイをApple Vision Proに表示しているとき、Macのトラックパッドを使って操作できる。 このとき、Macのディスプレイ画面の中だけかと思いきや、実はvisionOS全体をMacのトラックパッドで操作できる。 = まとめ - 視線と注視によるフォーカス操作は意外と難しい - 視線は動き回る - UIの工夫が重要 - 視線以外のフォーカス操作もある
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/CHANGELOG/CHANGELOG-0.3.md
markdown
Apache License 2.0
# v0.3.1 ## Changelog since v0.3.1 **Full Changelog**: https://github.com/Myriad-Dreamin/typst.ts/compare/v0.3.0...v0.3.1 ### Known Issues - exporter::svg: tyring to fix baseline of bitmap glyph, but untested in https://github.com/Myriad-Dreamin/typst.ts/pull/249 ### Security Notes - compiler: safer path_for_id in https://github.com/Myriad-Dreamin/typst.ts/pull/271 Before this commit, a malicious package can access any file in the system. ### Bug fix - compiler: reparse with empty content in https://github.com/Myriad-Dreamin/typst.ts/pull/236 - exporter::svg: memorize image_item rendering in https://github.com/Myriad-Dreamin/typst.ts/pull/247 - exporter::svg: correct group class name in https://github.com/Myriad-Dreamin/typst.ts/pull/251 - exporter::svg: remove unused prev correctly in https://github.com/Myriad-Dreamin/typst.ts/pull/264 - exporter::svg: correct reuse target in https://github.com/Myriad-Dreamin/typst.ts/pull/268 - compiler: ignore inotify events from output in https://github.com/Myriad-Dreamin/typst.ts/pull/261 - cli: correct logger setting in https://github.com/Myriad-Dreamin/typst.ts/pull/262 - pkg::core: link script in https://github.com/Myriad-Dreamin/typst.ts/pull/275 - compiler: only download packages in @preview in https://github.com/Myriad-Dreamin/typst.ts/pull/276 - compiler: datetime offset in https://github.com/Myriad-Dreamin/typst.ts/pull/278 ### Changes - cli: distinguish svg and svg-html export in https://github.com/Myriad-Dreamin/typst.ts/pull/259 ### External Feature - exporter::svg: experimental svg minifier in https://github.com/Myriad-Dreamin/typst.ts/pull/252 - exporter::svg: page-level partial rendering in https://github.com/Myriad-Dreamin/typst.ts/pull/263 - pkg::renderer: add renderer_build_info in https://github.com/Myriad-Dreamin/typst.ts/pull/273 - build(typst): update to v0.7.0 in https://github.com/Myriad-Dreamin/typst.ts/pull/277 ### Internal Feature - core: calculate bbox for vector items in https://github.com/Myriad-Dreamin/typst.ts/pull/239 - compiler: expose shadow files apis in https://github.com/Myriad-Dreamin/typst.ts/pull/253 # v0.3.0 ## Changelog since v0.3.0 **Full Changelog**: https://github.com/Myriad-Dreamin/typst.ts/compare/v0.2.3...v0.3.0 ### Security Notes No new security note. ### Bug fix - exporter::svg: animation only transist on fill changes in https://github.com/Myriad-Dreamin/typst.ts/pull/206 ### Changes - exporter::svg: attach defs tag by class attribute instead of id attribute in https://github.com/Myriad-Dreamin/typst.ts/pull/227 ### External Feature - typst: sync to 0.6.0 in https://github.com/Myriad-Dreamin/typst.ts/pull/198 - target: support riscv64-linux in https://github.com/Myriad-Dreamin/typst.ts/pull/207 and https://github.com/Myriad-Dreamin/typst.ts/pull/223 - cli: list packages in https://github.com/Myriad-Dreamin/typst.ts/pull/202 - cli: link/unlink packages in https://github.com/Myriad-Dreamin/typst.ts/pull/203 - cli: generate documentation site for packages packages in https://github.com/Myriad-Dreamin/typst.ts/pull/204 - hexo-renderer-typst uses Dynamic SVG exporter by Me and @seven-mile in https://github.com/Myriad-Dreamin/typst.ts/pull/197 ### Internal Feature - compiler: add `package::Registry` model in https://github.com/Myriad-Dreamin/typst.ts/pull/199 - compiler: add overlay access model in https://github.com/Myriad-Dreamin/typst.ts/pull/218 - test: init heap profiling in https://github.com/Myriad-Dreamin/typst.ts/pull/221
https://github.com/typst-doc-cn/tutorial
https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/basic/reference-syntax-analysis.typ
typst
Apache License 2.0
== variable identifier // `let`关键字后紧接着跟随一个#term("variable identifier")。标识符是变量的“名称”。「变量声明」后续的位置都可以通过标识符引用该变量。 // + 标识符以Unicode字母、Unicode数字和#mark("_")开头。以下是示例的合法变量名: // ```typ // // 以英文字母开头,是Unicode字母 // #let a; #let z; #let A; #let Z; // // 以汉字开头,是Unicode字母 // #let 这; // // 以下划线开头 // #let _; // ``` // + 标识符后接有限个Unicode字母、Unicode数字、#mark("hyphen")和#mark("_")。以下是示例的合法变量名: // ```typ // // 纯英文变量名,带连字号 // #let alpha-test; #let alpha--test; // // 纯中文变量名 // #let 这个变量; #let 这个_变量; #let 这个-变量; // // 连字号、下划线在多种位置 // #let alpha-; // 连字号不能在变量名开头位置 // #let _alpha; #let alpha_; // ``` // + 特殊规则:标识符仅为#mark("_")时,不允许在后续位置继续使用。 // #code(```typ // #let _ = 1; // // 不能编译:#_ // ```) // 该标识符被称为#term("placeholder")。 // + 特殊规则:标识符不允许为`let`、`set`、`show`等关键字。 // #code(```typ // // 不能编译: // // #let let = 1; // ```) // 建议标识符简短且具有描述性。同时建议标识符中仅含英文与#mark("hyphen")。 == let statement // 「变量声明」可以没有初始值表达式: // #code(```typ // #let x // #repr(x) // ```) // 事实上,它等价于将`x`初始化为`none`。 // #code(```typ // #let x = none // #repr(x) // ```) // 尽管Typst允许你不写初始值表达式,本书还是建议你让所有的「变量声明」都具有初始值表达式。因为初始值表达式还告诉阅读你代码的人这个变量可能具有什么样的类型。 == expression // === 逻辑比较表达式 <grammar-logical-cmp-exp> // 数字之间可以相互(算术逻辑)比较,并产生布尔类型的表达式: // - 小于: // #code(```typ // #(1 < 0), #(1 < 1), #(1 < 2) // ```) // - 小于等于: // #code(```typ // #(1 <= 0), #(1 <= 1), #(1 <= 2) // ```) // - 大于: // #code(```typ // #(1 > 0), #(1 > 1), #(1 > 2) // ```) // - 大于等于: // #code(```typ // #(1 >= 0), #(1 >= 1), #(1 >= 2) // ```) // - 等于: // #code(```typ // #(1 == 0), #(1 == 1), #(1 == 2) // ```) // - 不等于: // #code(```typ // #(1 != 0), #(1 != 1), #(1 != 2) // ```) // 不仅整数与整数之间、浮点数与浮点数之间可以做比较,而且整数与浮点数之间也可以做比较。当整数与浮点数相互比较时,整数会转换为浮点数再参与比较。 // #code(```typ // #(1 != 0.), #(1 != 1.), #(1 != 2.) // ```) // === 算术运算表达式 <grammar-arith-exp> // 数字之间可以做算术运算,并产生数字结果的表达式: // - 取正运算:<grammar-plus-exp> // #code(```typ // #(+1), #(+0), #(++1) // ```) // - 取负运算:<grammar-minus-exp> // #code(```typ // #(-1), #(-0), #(--1), #(-+-1) // ```) // - 加运算: // #code(```typ // #(1 + 2), #(1 + 1), #(1 + -1), #(1 + -2) // ```) // - 减运算: // #code(```typ // #(1 - 2), #(1 - 1), #(1 - -1), #(1 - -2) // ```) // - 乘运算: // #code(```typ // #(1 * 2), #(2 * 2), #(2 * -2) // ```) // - 除运算: // #code(```typ // #(1 / 2), #(2 / 2), #(2 / -2) // ```) // 值得注意的是$-2^63$在Typst中是浮点数,这可能是Typst的bug: // #code(```typ // #type(-9223372036854775808) // ```) // 为了正常使用该整数值你需要强制转换: // #code(```typ // #int(-9223372036854775808), #type(int(-9223372036854775808)) // ```) // 在日常生活中,我们还常用整除,如下方法实现了整除: // #code(```typ // #let fdiv(x, y) = int(x / y) // #fdiv(3, 2), #fdiv(-12, 2), #fdiv(-12, 5) \ // // 或 // #int(3 / 2), #int(-12 / 2), #int(-12 / 5) // ```) // #pro-tip[ // `calc.rem`函数帮你求解整除的余数: // #code(```typ // #let fdiv(x, y) = int(x / y) // $ 3 div & 2 = & #fdiv( 3, 2) & ...... & #calc.rem( 3, 2). \ // -12 div & 2 = & #fdiv(-12, 2) & ...... & #calc.rem(-12, 2). \ // -12 div & 5 = & #fdiv(-12, 5) & ...... & #calc.rem(-12, 5). $ // ```) // ] // === 赋值表达式 <grammar-assign-exp> // 变量可以被赋予一个表达式的值,所有的赋值表达式都产生`none`值而非返回变量的值。 // - 赋值及先加(减、乘或除)后赋值: // #code(```typ // #let a = 1 // #repr(a = 10), #a, #repr(a += 2), #a, #repr(a -= 2), #a, #repr(a *= 2), #a, #repr(a /= 2), #a // ```) // === 字符串相关的表达式 // 字符串相加表示字符串的连接:<grammar-string-concat-exp> // #code(```typ // #("a" + "b") // ```) // 字符串与数字相乘表示将该字符串重复$n$次后再连接:<grammar-string-mul-exp> // #code(```typ // #("a" * 4), #(4 * "ab") // ```) // 字符串之间的比较遵从#link("https://en.wikipedia.org/wiki/Lexicographic_order")[#term("lexicographical order")]。<grammar-string-cmp-exp> // 等于和不等于的比较,比较每个字符是否相等: // #code(```typ // #("a" == "a"), #("a" != "a") \ // #("a" == "b"), #("a" != "b") \ // ```) // 大于和小于的比较,从第一个字符开始依次比较,比较每个字符是否相等。直到第一个不相等的字符时作以下判断,字符的Unicode值较小的字符串则x相应更“小”: // #code(```typ // #("a" < "b"), #("a" > "a"), \ // #("a" < "ba"), #("ac" < "ba"), #("aac" < "aba") // ```) // 若一直比到了其中一个字符串的尽头,则较短的字符串更“小”: // #code(```typ // #("a" < "ab") // ```) // 大于等于和小于等于的比较则将「相等性」纳入考虑: // #code(```typ // #("a" >= "a"), #("a" <= "a") \ // ```)
https://github.com/ohmycloud/computer-science-notes
https://raw.githubusercontent.com/ohmycloud/computer-science-notes/main/Misc/grokking_mk.typ
typst
= Grokking Machine Learning #let chapter(title, subtitle, heading) = [ #grid( columns: (auto, auto, auto), rows: (auto, auto), row-gutter: 10pt, column-gutter: (10pt, 25pt), text(gray, weight: "bold", size: 24pt)[#title], [#line(length: 1.8cm, stroke: 3pt + red, angle: 90deg)], text(red, weight: "bold", size: 72pt)[#heading], align(right)[#text(red, weight: "bold", baseline: -30pt, size: 24pt,)[#subtitle]], ) ] == #chapter("Drawing a line close to our points:", "Linear regression", 3) #text(maroon, weight: "bold")[features] The features of a data point are those properties that we use to make our prediction. \ #text(maroon, weight: "bold")[labels] This is the target that we try to predict from the features. \ #text(maroon, weight: "bold")[model] A machine learning model is a rule, or a formula, which predicts a label from the features. \ #text(maroon, weight: "bold")[prediction] The prediction is the output of the model. \ #text(maroon, weight: "bold")[weights] In the formula corresponding to the model, each feature is multiplied by a corresponding factor. These factors are the weights.\ #text(maroon, weight: "bold")[bias] The formula corresponding to the model has a constant that is not attached to any of the features. This constant is called the bias. How o get the computer to draw this line: The linear regression algorithm Start with a random line, and figure out a way to improve this line a little bit by moving it closer to the points. Repeat this process many times, and voila, we have the desired line. This process is called the linear reression algorithm. Start with a random line. Pick a random point in the dataset, and move the line slightly closer to that one point. Repeat this process many times, always picking a random point in the dataset. Pseudocode for the linear regression algorithm Inputs: A dataset of points \ Outputs: A linear regression model that fits that dataset \ Procedure: - Pick a model with random weights and a random bias. - Repeat many times: - Pick a random data point. - Slightly adjust the weights and bias to improve the prediction for that particular data point. - *Return* the model you've obtained. 这个过程中, 你可能会提出一些问题: - 权重的值要调整到多少? - 这个回归算法我要重复多少次? 换句话说, 我怎么知道我做完了? - 我怎么知道这个算法是否有效呢? 我们使用下面两种方法回答上面的问题。 误差函数:“绝对误差”和“平方误差”,会帮助我们决定在哪里停止线性回归算法。\ 梯度下降:Gradient descent。 斜率告诉我们直线所指的方向, y 轴截距告诉我们直线的位置。注意, 通过指定斜率和 y 轴截距, 直线就完全确定了。
https://github.com/TomPlanche/typst-template
https://raw.githubusercontent.com/TomPlanche/typst-template/main/main.typ
typst
MIT License
#import "conf.typ": * #import "@preview/codly:1.0.0": * #show: codly-init.with() #show: conf.with( title: "Title", author: "<NAME>", class: "Class name", subtitle: "Class subtitle", logo: image("assets/cnam_logo.svg"), start-date: datetime(day: 4, month: 9, year: 2024), main-color: "#C4122E", ) #codly( zebra-fill: none )) = Main title == Subtitle === Subsubtitle #my-block( [ Custom Block ] ) #blockquote([ Custom Blockquote ]) ```SQL CREATE TABLE ELEVE ( IDE INT, NOM VARCHAR(30), PRENOM VARCHAR(30), ANNEENAISS NUMBER(4), ENTREPRISE VARCHAR(30), NOMTUTEUR VARCHAR(50) ); ```
https://github.com/peterw16/da_typst_vorlage
https://raw.githubusercontent.com/peterw16/da_typst_vorlage/main/template/template.typ
typst
#import "customs.typ" #let diplomarbeit( title: "", kurzfassung: [], abstract: [], aufgabenstellungen: (), body ) = { // ------ global definitions ----- set text(font: "Helvetica") set page( paper: "a4", margin: (x: 2cm, top: 4cm), header: [ #set align(horizon) #grid( columns: (3cm, 1fr , 3cm), align(left,image("images/htl_zukunft.jpg",width: 80%)), align(center)[HÖHERE TECHNISCHE BUNDESLEHRANSTALT Wien 16\ Abteilung für Informationstechnologie], align(right,image("images/HTLWienWest.png",width: 70%)) ) ], footer: { set align(center) set text(12pt) line(length:100%) // dont display page number on first page locate(loc => { if loc.page() > 1 { counter(page).display("- i -") } }) }, numbering: "i" ) show heading.where(level: 1): set text(size: 17.2pt) show heading.where(level: 1): it => { pad(bottom: 20pt)[#it] } // add outlines to Inhaltsverzeichnis, except for Inhaltsverzeichnis itself // and make first level entries bold show outline.where(title: [Inhaltsverzeichnis]): it => { show outline.entry.where(level: 1): set text(weight: "bold") set heading(outlined: false) it } show outline: set heading(outlined: true) set outline(fill: repeat([#h(3pt).#h(3pt)])) // modify outline entries show outline.entry: customs.outline_entry // no fills for level 1 entries // add spacing between entries show outline.entry.where(level: 1): it => { v(20pt, weak: true) it } set par(leading: 1em, justify: true) // ------------------------------- // -------- Vordefinierte Seiten ------- { show heading: it => {upper(it)} //Deckblatt import "pages/deckblatt.typ": deckblatt deckblatt(title, aufgabenstellungen) pagebreak() //Eidesstattliche Erklärung import "pages/eidesstattliche.typ": eidesstattliche let persons = aufgabenstellungen.map(e => e.schüler) eidesstattliche(persons: persons) pagebreak() //Kurzfassung [= Kurzfassung] kurzfassung pagebreak() //Abstract [= Abstract] abstract pagebreak() } //Abbildungsverzeichnis outline( title: "Abbildungsverzeichnis", target: figure.where(kind: image), ) pagebreak() //Tabellenverzeichnis outline( title: "Tabellenverzeichnis", target: figure.where(kind: table), ) pagebreak() //Inhaltsverzeichnis outline( title: "Inhaltsverzeichnis", indent:auto, ) // ------------------------------- // Numerierung der Kapitel und Seiten festlegen set heading(numbering: "1.1") set page( footer: [ #set align(center) #set text(12pt) #line(length:100%) #counter(page).display("- 1 -") ], numbering: "1", ) // start of actual DA writing pagebreak() counter(page).update(1) { // add pagebreak before each level 1 heading (except for first heading after outline) show heading.where(level: 1): it => { if counter(heading).at(it.location()).first() != 1 { pagebreak() } it } body } pagebreak() // -------- Vordefinierte Seiten -------- // Literaturverzeichnis set heading(numbering: none) bibliography("../literaturverzeichnis.bib", title: [Literaturverzeichnis] ) pagebreak() counter(heading).update(0) set heading(numbering: "A") // Arbeitsaufteilung import "pages/arbeitsaufteilung.typ": arbeitsaufteilung let aufteilungen = aufgabenstellungen .map(a => (a.schüler, a.arbeitsaufteilung)) arbeitsaufteilung(aufteilungen: aufteilungen) pagebreak() // Diplomarbeitsantrag [= Diplomarbeitsantrag] // ---------------------------------------- }
https://github.com/jemus42/typst-slides-bips
https://raw.githubusercontent.com/jemus42/typst-slides-bips/main/README.md
markdown
MIT License
# typst-slides-bips Attempting to recreate the BIPS presentation style as a learning exercise for typst
https://github.com/mrcinv/nummat-typst
https://raw.githubusercontent.com/mrcinv/nummat-typst/master/nummat_jl.typ
typst
#import "template.typ": conf #set text(lang: "sl") #show: doc => conf( title: [Numerična matematika #linebreak() v programskem jeziku Julia], authors: ("<NAME>",), doc, ) #include "00_uvod.typ" #include "01_julia.typ" #include "02_koren.typ" #include "03_tridiag.typ" #include "04_laplace.typ" #include "05_implicitna_interpolacija.typ" #include "06_fizikalna_graf.typ" #include "07_page_rank.typ" #include "08_spektralno_grucenje.typ" #include "09_konvergencna_obmocja.typ" #include "10_nelinearne_geometrija.typ" #include "11_linearni_model.typ" #include "12_hermitov_zlepek.typ" #include "13_porazdelitvena_funkcija.typ" #include "14_povprecna_razdalja.typ" #include "15_avtomatsko_odvajanje.typ" #include "16_nde.typ" #include "17_nde_aproksimacija.typ" #include "domace.typ" #bibliography("reference.yml")
https://github.com/mattyoung101/uqthesis_eecs_hons
https://raw.githubusercontent.com/mattyoung101/uqthesis_eecs_hons/master/pages/title.typ
typst
ISC License
#let config = yaml("../config.yaml") #align(center, [ #image("../util/assets/uqlogo.png", width: 65%) ]) #v(24pt) #align(center, text(24pt)[ *#config.title* ]) #v(2em) #align(center, text(14pt)[ by ]) #align(center, text(18pt)[ #config.author ]) #align(center, text(16pt)[ #box(width: 75%)[School of #config.faculty, University of Queensland.] ]) #v(128pt) #align(center, text(16pt)[ _ Submitted for the degree of \ #config.degrees_candidate \ in #config.month #config.year _ ])
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/valkyrie/0.1.0/src/types/array.typ
typst
Apache License 2.0
#import "../base-type.typ": base-type, assert-base-type #import "../context.typ": context #import "any.typ": any /// Valkyrie schema generator for array types. Array entries are validated by a single schema. For arrays with positional requirements, see @@tuple. /// /// - name (internal): /// - default (array, none): Default value to set if no value is provided. *MUST* itself pass validation. /// - min (integer, none): If not none, the minimum array length that satisfies the validation. *MUST* be a positive integer. The program is *ILL-FORMED* if `min` is greater than `max`. /// - max (integer, none): If not none, the maximum array length that satisfies the validation. *MUST* be a positive integer. The program is *ILL-FORMED* if `max` is less than `min`. /// - length (integer, auto): If not auto, the exact array length that satisfies validation. *MUST* be a positiive integer. The program *MAY* be *ILL-FORMED* is concurrently set with either `min` or `max`. /// - custom (function, none): If not none, a function that, if itself returns none, will produce the error set by `custom-error`. /// - custom-error (string, none): If set, the error produced upon failure of `custom`. /// - transform (function): a mapping function called after validation. /// - ..args (schema, none): Variadic positional arguments of length `0` or `1`. *SHOULD* not contain named arguments. If no arguments are given, schema defaults to array of @@any /// -> schema #let array( name: "array", default: (), min: none, max: none, length: auto, custom: none, custom-error: auto, transform: it=>it, ..args ) = { // assert default is array assert( type(min) in (int, type(none)), message: "Minimum length must be an integer") if ( min != none){ assert( min >= 0, message: "Minimum length must be a positive integer")} assert( type(max) in (int, type(none)), message: "Maximum length must be an integer") if ( max != none){assert( max >= 0, message: "Maximum length must be a positive integer")} assert( type(length) in (int, type(auto)), message: "Length must be an integer") if ( length != auto){assert( length >= 0, message: "Maximum length must be a positive integer")} assert( type(custom) in (function, type(none)), message: "Custom must be a function") assert( type(custom-error) in (str, type(auto)), message: "Custom-error must be a string") assert( type(transform) == function, message: "Transform must be a function that takes a single string and return a string") let positional-arguments = args.pos() let valkyrie-array-typ if ( positional-arguments.len() < 1 ){ valkyrie-array-typ = any() } else { valkyrie-array-typ = positional-arguments.first() assert-base-type(valkyrie-array-typ, scope: ("arguments",)) } let name = name + "[" + (valkyrie-array-typ.name) +"]" return (:..base-type(), name: name, default: default, min: min, max: max, length: length, valkyrie-array-typ: valkyrie-array-typ, custom: custom, custom-error: custom-error, transform: transform, validate: (self, it, ctx: context(), scope: ()) => { // Default value if (it == none){ it = self.default } // Array must be an array if not (self.assert-type)(self, it, scope: scope, ctx: ctx, types: (type(()),)){ return none } // Minimum length if (self.min != none) and (it.len() < self.min) { return (self.fail-validation)(self, it, ctx: ctx, scope: scope, message: "Array length less than specified minimum of " + str(self.min)) } // Minimum length if (self.max != none) and (it.len() > self.max) { return (self.fail-validation)(self, it, ctx: ctx, scope: scope, message: "Array length greater than specified maximum of " + str(self.max)) } // Exact length if (self.length != auto) and (it.len() != self.length) { return (self.fail-validation)(self, it, ctx: ctx, scope: scope, message: "Array length must exactly equal " + str(self.length)) } // Check elements for (key, value) in it.enumerate(){ it.at(key) = (valkyrie-array-typ.validate)(valkyrie-array-typ, value, ctx: ctx, scope: (..scope, str(key))) } // Custom if ( self.custom != none ) and ( not (self.custom)(it) ){ let message = "Failed on custom check: " + repr(self.custom) if ( self.custom-error != auto ){ message = self.custom-error } return (self.fail-validation)(self, it, ctx: ctx, scope: scope, message: message) } return (self.transform)(it) } ) }
https://github.com/nhuongmh/nhuongmh.cv
https://raw.githubusercontent.com/nhuongmh/nhuongmh.cv/main/template.typ
typst
Do What The F*ck You Want To Public License
// You may need to change this settings #let sansen = "KpSans" #let sanszh = "Source Han Sans SC" #let serifen = "KpRoman" #let serifzh = "Source Han Serif SC" #let emj = "Segoe UI Emoji" // #let info = author => align(center)[ // #author.email \ // #author.phone \ // #author.home · #author.github · #author.linkin // ] // You don't really need to change the content below #let sans = (sansen, sanszh, emj) #let serif = (serifen, serifzh, emj) #let titlefont = (serifen, sanszh, emj) #let icon(name, baseline: 1.5pt) = { box( baseline: baseline, height: 10pt, image(name) ) } #let titleemj(name, baseline: 1.5pt) = { box( baseline: baseline, height: 16pt, image(name) ) } #let chiline() = {v(-3pt); line(length: 100%); v(-5pt)} #let section(term) = { show heading.where( level: 1 ): it => block(width: 100%)[ #set text( font: sans, weight: "regular", ) #smallcaps(it.body) ] [ = #term ] chiline() } #let datedsubsection(term, data) = { grid( columns: (1fr, auto), align(left)[ #term ], align(right)[ #data ], ) } #let leftsection(term) = [ #show heading.where( level: 1 ): it => block(width: 100%)[ #set text( font: sans, weight: "regular" ) #smallcaps(it.body) ] = #term ] #let group(terms) = { v(1.35em) grid( columns: (2fr, 8fr), column-gutter: 2em, row-gutter: 2em, ..terms ) } #let left_right(term, data) = { grid( columns: (1fr, auto), align(left)[ #term ], align(right)[ #data ], ) } #let info = author => [ #left_right( align(left)[ #author.phone \ #author.location \ #author.email ], align(right)[ #author.home \ #author.github \ #author.linkin ] ) ] //main template #let project(title: "", author: ( name: "" ), body) = { // Set the document's basic properties. set document(author: author.name, title: title) set page( // numbering: "1 / 1", number-align: center, margin: ( x: 0.4in, y: 0.2in ) ) set text( font: serif, lang: "en" ) show math.equation: set text(weight: 300) // Title row. align(center)[ #block( text( font: titlefont, weight: 700, 1.75em, smallcaps(title) ) ) ] // Author information. pad( top: 0.5em, bottom: 0.5em, x: 0em, info(author) ) // Main body. set par(justify: true) body }
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/examples/clustered-barchart.typ
typst
#import "@preview/cetz:0.2.0": canvas, chart, draw #set page(width: auto, height: auto, margin: .5cm) #let data2 = ( ([15-24], 18.0, 20.1, 23.0, 17.0), ([25-29], 16.3, 17.6, 19.4, 15.3), ([30-34], 14.0, 15.3, 13.9, 18.7), ([35-44], 35.5, 26.5, 29.4, 25.8), ([45-54], 25.0, 20.6, 22.4, 22.0), ([55+], 19.9, 18.2, 19.2, 16.4), ) #canvas({ draw.set-style(legend: (fill: white)) chart.barchart(mode: "clustered", size: (9, auto), label-key: 0, value-key: (..range(1, 5)), bar-width: .8, x-tick-step: 2.5, data2, labels: ([Low], [Medium], [High], [Very high]), legend: "legend.inner-north-east",) })
https://github.com/typst-tud/tud-slides
https://raw.githubusercontent.com/typst-tud/tud-slides/main/tud-slides.typ
typst
Apache License 2.0
// TUD Theme for Typst Touying // // based on https://touying-typ.github.io/touying/docs/build-your-own-theme #import "@preview/touying:0.4.2": * #import "colors.typ": * /* * Utility Functions */ #let tud-gradient(self, body) = { rect( stroke: self.colors.debug-stroke, fill: gradient.linear( self.colors.tud-blue, self.colors.tud-lightblue, angle: 45deg, ), body ) } /* * Standard Slide */ #let slide( self: none, title: auto, subtitle: none, ..args, ) = { if title != auto { self.tud-title = title } if subtitle != none { self.tud-subtitle = subtitle } (self.methods.touying-slide)(self: self, ..args) } /* * Title Slide */ #let title-slide( self: none, ..args, ) = { self = utils.empty-page(self) // clears self.page-args.header, self.page-args.footer, sets margin and padding to 0em let info = self.info + args.named() let cell(body) = rect( width: 100%, height: 100%, inset: 0mm, outset: 0mm, fill: none, stroke: self.colors.debug-stroke, align(top + left, body) ) let body = { set text(fill: self.colors.tud-white) set block(inset: 0mm, outset: 0mm, spacing: 0em) set align(top + left) grid( columns: 100%, rows: (4em, 1fr), grid( columns: (2em, 1fr, 10em), rows: (100%), cell([]), // empty space cell( align(horizon + left, image("logos/TU_Dresden_Logo_blau_HKS41.svg", width: 49mm, height: auto))), // TUD logo cell([]), // empty, or DDC or secondary logo ), tud-gradient(self, block( stroke: self.colors.debug-stroke, fill: none, width: 100%, height: 100%, inset: (left: 4em, top: 6em), grid( columns: (1fr), rows: (4em, 8em, 1fr), cell([ #set text(fill: self.colors.tud-white.transparentize(25%)) #text(weight: "bold", info.author) #linebreak() #info.institution ]), cell([ #text(size: 2em, weight: "bold", info.title) #linebreak() #text(size: 2em, weight: "regular", info.subtitle) ]), cell([ #set text(fill: self.colors.tud-white.transparentize(25%)) #self.info.location \/\/ #utils.info-date(self) ]), ), ) ) ) } (self.methods.touying-slide)(self: self, repeat: none, body) } /* * Section Slide * * register self.methods.touying-new-section-slide = new-section-slide, * so new-section-slide is called when first-level title is encountered */ #let new-section-slide( self: none, title: auto, subtitle: none, section, ..args, ) = { // reset page margin and padding, so full page is covered by gradient self.page-args += ( margin: (top: 0em, bottom: 3em, x: 0em), ) self.padding = (x: 0em, y: 0em) let cell(body) = rect( width: 100%, height: 100%, inset: 0mm, outset: 0mm, fill: none, stroke: self.colors.debug-stroke, body ) let body = { set align(left + horizon) tud-gradient( self, block( stroke: self.colors.debug-stroke, width: 100%, height: 100%, inset: (left: 4em, top: 12em), grid( columns: (1fr), rows: (8em), cell(text(size: 2em, fill: self.colors.tud-white, weight: "bold", section)) ) ) ) } // call default slide (self.methods.slide)(self: self, section: section, body) } /* * Slides Function * * When title-slide is true, using #show: slides will automatically create a title-slide. */ #let slides(self: none, title-slide: true, slide-level: 1, ..args) = { if title-slide { (self.methods.title-slide)(self: self) } (self.methods.touying-slides)(self: self, slide-level: slide-level, ..args) } /* * Register Function and Init Method */ #let register( self: themes.default.register(), aspect-ratio: "16-9", debug: false, footer : [], // footer-columns: (4.13%, 16.18%, 38.38%, 30.88%, 1fr), // footer-columns: (14mm, 54.8mm, 130mm, 19.6mm, 1fr, 35.3mm), footer-info: self => {[ #self.info.title – #self.info.subtitle \ #self.info.institution \/\/ #self.info.author \ #self.info.location \/\/ #utils.info-date(self) ] }, footer-number: self => { "Slide " + states.slide-counter.display() + " / " + states.last-slide-number }, footer-second-logo: self => { // if self.info.ddc-logo { // image("...", width: 80%, height: 10em) // DDC logo enabled // } else { // [] // DDC logo disabled // } }, ) = { // color theme self = (self.methods.colors)( self: self, tud-blue: cddarkblue, tud-lightblue: cdblue, tud-gray: cdgray, tud-white: cdwhite, debug-stroke: if debug { 1pt + red } else { none }, ) self.tud-title = [] self.tud-subtitle = [] self.tud-footer = footer let header(self) = { let title = utils.call-or-display(self, self.tud-title) let subtitle = utils.call-or-display(self, self.tud-subtitle) // define cell function for grid as rects let cell(body) = rect( width: 100%, height: 100%, inset: 0mm, outset: 0mm, fill: none, stroke: self.colors.debug-stroke, align(bottom + left, text(size: 24pt, fill: self.colors.tud-blue, body)) ) set align(top) block( grid( columns: (4em, 1fr), rows: (18mm, 10.6mm), cell([]), cell(heading(level: 2, text(weight: "bold", title))), cell([]), cell(text(weight: "regular", subtitle)) ), ) } let footer(self) = { // define cell function for grid as rects let cell(body) = rect( width: 100%, height: 100%, inset: 0mm, outset: 0mm, fill: none, stroke: self.colors.debug-stroke, align(horizon + left, text(size: 0.4em, fill: self.colors.tud-gray, body)) ) set align(center + horizon) block( stroke: self.colors.debug-stroke, width: 100%, height: 3em, grid( // columns: (25%, 1fr, 25%), // columns: footer-columns, columns: (14mm, 54.8mm, 130mm, 19.6mm, 1fr, 35.3mm), // 6 columns rows: (2em), // 1 row cell([]), // empty space cell(image("logos/TU_Dresden_Logo_blau_HKS41.svg", width: auto, height: 100%)), // TUD logo cell(utils.call-or-display(self, footer-info)), // title etc. cell(utils.call-or-display(self, footer-number)), // slide number cell([]), // empty space cell(utils.call-or-display(self, footer-second-logo)), // empty, or DDC or secondary logo ) ) } // page settings self.page-args += ( paper: "presentation-" + aspect-ratio, header: header, footer: footer, margin: (top: 41mm, bottom: 3em, x: 4em), ) // register methods self.methods.slide = slide self.methods.title-slide = title-slide self.methods.new-section-slide = new-section-slide self.methods.touying-new-section-slide = new-section-slide self.methods.slides = slides self.methods.alert = (self: none, it) => text(fill: self.colors.tud-blue, it) self.methods.init = (self: none, body) => { set text(font: "Open Sans", size: 16pt) body } self }
https://github.com/jamesrswift/journal-ensemble
https://raw.githubusercontent.com/jamesrswift/journal-ensemble/main/src/part.typ
typst
The Unlicense
#import "elements.typ" #let part-state = state("__journal-ensemble:part", none) #let update(new) = { part-state.update(new) } #let make-new-section( body, display: auto ) = { display = if display == auto {body} else {display} pagebreak(weak:true, to: "even") update(body) v(1fr) move( dx: -2.5cm, block( width: 10cm, height: 10cm, elements.fancy-box({ set text(fill: white, size: 24pt) v(1fr) align(center,block(width: 5cm,display)) v(1fr) }) ) ) v(1fr) pagebreak(weak:true) } #let get() = part-state.get()
https://github.com/jrihon/cv
https://raw.githubusercontent.com/jrihon/cv/main/cv.typ
typst
#import "brilliant-template/template.typ": * #show: layout #cvHeader(hasPhoto: true, align: left) #autoImport("education") #autoImport("projects") #autoImport("competencies") #autoImport("other_skills") #autoImport("publications") #cvFooter()
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/system-implementation/server.typ
typst
=== Ungrammar Language Server <subsec-impl-langserver> The Ungrammar Language Server acts as a crucial intermediary, facilitating communication between the Language Service and various code editors. By implementing the JSON-RPC protocol and adhering to the Language Server Protocol (LSP) specification, the Language Server ensures seamless integration and effective feature exchange. Key Features and Benefits: - *JSON-RPC Protocol*: Enables efficient data exchange between the Language Service and code editors, using a well-defined protocol for communication. - *LSP Adherence*: Conforms to the LSP specification, ensuring compatibility with a wide range of code editors and IDEs. - *Caching Mechanism*: Implements a caching mechanism to store results from the Language Service, reducing processing time and improving performance for common operations like undo and redo. - *Integration Flexibility*: Can be integrated with various code editors and development environments, providing a versatile and adaptable language support solution. The Ungrammar Language Server plays a pivotal role in the ecosystem by: - *Serving as a communication gateway*: Facilitating interaction between the Language Service and code editors. - *Enhancing performance*: Optimizing the language support experience through caching and efficient communication. - *Enabling LSP features*: Providing a foundation for implementing LSP features within code editors. ==== Implementation Detail To optimize performance and improve the user experience, we've extended the Ungrammar Language Service with a caching mechanism. This mechanism efficiently stores and retrieves results from previous language analysis tasks, significantly reducing processing time for common operations like undo and redo. Furthermore, we've meticulously translated all core features of the Language Service into LSP definitions using the JSON-RPC protocol. This ensures seamless integration with various code editors and provides a standardized interface for accessing language-specific functionalities. By incorporating these enhancements, we've created a more responsive and efficient Language Server that delivers a superior user experience and streamlines the development process. #figure( raw(read("/assets/tree-server.txt"), block: true), caption: [Tree of Ungrammar Language Server workspace], ) ==== Deployment to NPM Upon completion of development, we successfully deployed the Ungrammar Language Server to the NPM registry. This strategic move allows other developers to easily discover, integrate, and extend our project for their own language-related endeavors. By making the Language Server readily available on NPM, we've expanded the accessibility and potential impact of our work within the developer community. Here is our deployed Ungrammar Language Server, which has been downloaded by 152 users since its public release and is currently hosted at #link("https://www.npmjs.com/package/ungrammar-languageserver"). #figure( image("/assets/server.jpg", width: 90%), caption: [Deployed Ungrammar Language Server on NPM], )
https://github.com/xdoardo/co-thesis
https://raw.githubusercontent.com/xdoardo/co-thesis/master/thesis/chapters/index.typ
typst
#import "/includes.typ": * #include "./introduction.typ" #include "./recursive/index.typ" #include "./delay/index.typ" #include "./imp/index.typ" #include "./conclusions.typ"
https://github.com/horaoen/java-cheat-sheet
https://raw.githubusercontent.com/horaoen/java-cheat-sheet/main/cheat-sheet.typ
typst
MIT License
#import "./typstempl/cosheet.typ": cosheet #show: doc => cosheet(doc) = java基础 == 去除空格 ```java public String trim(String str) { // "\u0020" 半角空格, office空格, 全角空格 return str.trim().replace("\u00a0", "").replace("\u3000", ""); } ``` = Spring == 获取Servlet相关参数 ```java ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletResponse response = servletRequestAttributes.getResponse(); HttpServletRequest request = servletRequestAttributes.getRequest(); ``` = 类库 == Hutool === ExcelUtil + example ```java ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletResponse response = servletRequestAttributes.getResponse(); ExcelReader reader = ExcelUtil.getReader(FileUtil.file("公务用车车辆管理员信息.xlsx"), 0); List<Map<String, Object>> carManagerMaps = reader.readAll(); // 所有用车管理员userCode List<String> carManagersUserCode = carManagerMaps.stream() .map(map -> map.get("账号").toString()) .collect(Collectors.toList()); final List<LinkedHashMap<String, String>> rows = carManagersUserCode.stream().map(userCode -> { LinkedHashMap<String, String> row = new LinkedHashMap<>(); row.put("账号", userCode); return row; }).collect(Collectors.toList()); ExcelWriter excelWriter = ExcelUtil.getWriter(); excelWriter.renameSheet("所有车辆管理员账号"); excelWriter.write(rows, true); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=test_1.xls"); ServletOutputStream out = response.getOutputStream(); excelWriter.flush(out, true); excelWriter.close(); IoUtil.close(out); ``` + 获取reader ```java ExcelReader reader = ExcelUtil.getReader(FileUtil.file("path"), 0); ``` + 获取writer ``` ExcelWriter excelWriter = ExcelUtil.getWriter(); ```
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/block-sizing_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Layout inside a block with certain dimensions should provide those dimensions. #set page(height: 120pt) #block(width: 60pt, height: 80pt, layout(size => [ This block has a width of #size.width and height of #size.height ]))
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/poc/options_ui_decision.typ
typst
#import "../../../acronyms.typ": ac = UI Framework Decision <option-ui-decision> All technologies to implement UIs in a functional language are unfamiliar to the authors. Because of that, it is crucial to have a good abstraction between #ac("UI") and business logic in place so that the #ac("UI") framework, if necessary, can be exchanged with another option with as little effort as possible. #ac("FRP") is an excellent concept for incorporating #ac("UI") behavior and events into functional programming. Of the frameworks considered, only threepenny-gui includes a library that supports #ac("FRP"). Despite not following the #ac("FRP") concepts, Bolero also supports reactive handling of #ac("UI") contents. Since the project intends to create a tool for visual programming in Haskell, it also makes sense to implement the #ac("UI") of VisualFP in Haskell. For that reason, Threepenny will be used for the #ac("PoC"). As already mentioned in @ghcjs, using GHCJS as a Haskell compiler that targets JavaScript would enable other interesting possibilities but has been deemed too time-consuming for the #ac("PoC").
https://github.com/typst-community/mantodea
https://raw.githubusercontent.com/typst-community/mantodea/main/tests/author/test.typ
typst
MIT License
#import "/src/author.typ" #show heading.where(level: 1): it => pagebreak(weak: true) + it #set page(width: auto, height: auto) = Name #author.name("Knuth", short: 0) #author.name("Donald", "Knuth", short: 0) #author.name("Donald", "Ervin", "Knuth", short: 0) #author.name("Knuth", short: 1) #author.name("Donald", "Knuth", short: 1) #author.name("Donald", "Ervin", "Knuth", short: 1) #author.name("Knuth", short: 2) #author.name("Donald", "Knuth", short: 2) #author.name("Donald", "Ervin", "Knuth", short: 2) = Author Inline #author.author("Tinger", email: "<EMAIL>") #author.author("Tinger", label: <manual>) #author.email(mark: sym.dagger, <manual>, "me AT tinger.dev") #author.author("Tinger", label: <tinger>) #author.author("John", "Doe", label: <univeristy>) #author.email(<tinger>, "<EMAIL>") #author.email(<univeristy>, "<EMAIL>")
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/layout-infinite-lengths_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // #set page(width: auto, height: auto) // // // Error: 17-54 cannot create polygon with infinite size // #layout(size => polygon((0pt,0pt), (0pt, size.width)))
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/stroke_08.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Converting to stroke // #assert.eq(stroke(red).paint, red) // #assert.eq(stroke(red).thickness, auto) // #assert.eq(stroke(2pt).paint, auto) // #assert.eq(stroke((cap: "round", paint: blue)).cap, "round") // #assert.eq(stroke((cap: auto, paint: blue)).cap, auto) // #assert.eq(stroke((cap: auto, paint: blue)).thickness, auto) // // // Error: 9-21 unexpected key "foo", valid keys are "paint", "thickness", "cap", "join", "dash", and "miter-limit" // #stroke((foo: "bar")) // // // Constructing with named arguments // #assert.eq(stroke(paint: blue, thickness: 8pt), 8pt + blue) // #assert.eq(stroke(thickness: 2pt), stroke(2pt)) // #assert.eq(stroke(cap: "round").thickness, auto) // #assert.eq(stroke(cap: "round", thickness: auto).thickness, auto)
https://github.com/steelpancake/cv-typst
https://raw.githubusercontent.com/steelpancake/cv-typst/main/cv.typ
typst
MIT License
//#import "@preview/modern-cv:0.6.0": * #import "@local/modern-cv:0.7.0": * #show: resume.with( author: ( firstname: "Pranshu", lastname: "Tanwar", email: "<EMAIL>", //homepage: "", phone: "+90 534 297 5089", github: "pranshuthegamer", github2: "steelpancake", //scholar: "", birth: [14#super([th]) December, 2006], //linkedin: "Example", address: "Mashattan, Maslak, Ayazaga, Istanbul", positions: ( "aspiring multimedia programmer", ), ), date: datetime.today().display(), language: "en", colored-headers: true, show-footer: false, ) = Education #resume-entry( title: "MEF International Schools of Istanbul", location: "Istanbul, Turkiye", date: "September 2022 - June 2025", description: [IB Diploma, IGCSE], ) #let row_gutter = 0.65em #let indent = 2em #let name_width = 16em #resume-item[ - Completing *IB Diploma* with the following subjects: #grid( columns: (indent, name_width, auto), row-gutter: row_gutter, [], [- Mathematics AA], [HL], [], [- Physics], [HL], [], [- Digital Society], [HL], [], [- Chemistry], [SL], [], [- French Ab Initio], [SL], [], [- English A Language & Literature], [SL], ) - Completed *IGCSE* course with the following subjects: #grid( columns: (indent, name_width, auto), row-gutter: row_gutter, [],[- Co-ord Sciences (Double Award)], [A*A\*], [],[- Cambridge Intl Mathematics], [A(a)], [],[- First Language English], [B(b)], ) ] = Activites #resume-entry2( title: "Robotics Club & FRC Robotics Competition", location: "Istanbul", date: "2022 - 2024", ) #resume-item[ - Vectorized team's and sponsors' logos and other miscellaneous artwork for our team in the FRC competition - Programmed a simple serially controllable LED light system for the robot - Edited recap videos about the competition for school assembly ] #resume-entry2( title: "Cross-country Running", location: "Istanbul", date: "2024 - Present", ) #resume-item[ - Ran 5km every week for 5 weeks before inter-school cross-country running competition - Ran a 5km course in for the competition in Belgrad Forest in 26 minutes ] #resume-entry2( title: "News Club", location: "Istanbul", date: "2024 - Present", ) #resume-item[ - Editor for school's weekly news club videos - Experiments with variations in editing process for each broadcast ] #resume-entry2( title: "Auditorium Sound & Lights", location: "Istanbul", date: "2023 - Present", ) #resume-item[ - Mix audio for school assemblies, talent shows and other events in the auditorium. - Manage lighting during assemblies as a substitute ] = Skills #let skills-helper( row_gutter : 0.8em, indent : 0em, name_width : 10em, tertiary-size: 0.8em, tertiary-leading : 0.5em, body, ) = { set text(hyphenate: false) show grid.cell.where(x: 1): set par(leading: 0.5em) show grid.cell.where(x: 2): set text(style: "italic", size: 0.8em) show grid.cell.where(x: 2): set par(leading: 0.5em) set grid(columns: (indent, name_width, 16em)) body } #resume-skill-item( "Languages", ([ #show: skills-helper.with() #grid( row-gutter: row_gutter, [], [English], [Fluent], [], [Hindi], [Native], [], [French], [Learning], ) ],) ) #v(0.5em) #resume-skill-item( "Programming Languages", ([ #show: skills-helper.with() #grid( row-gutter: row_gutter, [], [Bash], grid.cell(rowspan: 3, [#set text(hyphenate: false); Flexible with programming languages, picks up languages easily.]), [], [Python], [], [Lua], ) ],) ) #v(0.5em) #resume-skill-item( "Computer Related", ([ #show: skills-helper.with() #grid( row-gutter: row_gutter, [], [Video Transcoding \ & Editing], [Makes regular use of tools like `ffmpeg`, `OBS studio`, and `Shotcut` for making videos and sharing them on the web], [], [Linux User], [], [], [], [] ) ],) )
https://github.com/RandomcodeDev/FalseKing-Design
https://raw.githubusercontent.com/RandomcodeDev/FalseKing-Design/main/game/game.typ
typst
#set heading(numbering: "1.") #show link: underline #align(center, text(30pt)[*False King*]) #align(center, text(20pt)[By <NAME>]) #outline() #pagebreak() #include("intro.typ") #pagebreak() #include("concept.typ") #pagebreak() #include("platforms.typ") #pagebreak() #include("tools.typ") #pagebreak() #include("visuals.typ") #pagebreak() #include("audio.typ") #pagebreak() #include("input.typ") #pagebreak() #include("ui.typ") #pagebreak() #include("story.typ") #pagebreak() #include("timeline.typ")
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/037%20-%20Ravnica%20Allegiance/004_The%20Ledger%20of%20Hidden%20Fortunes.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Ledger of Hidden Fortunes", set_name: "Ravnica Allegiance", story_date: datetime(day: 20, month: 02, year: 2019), author: "<NAME>", doc ) #strong[Date: The 15th of Dhazo] #strong[Location: Clover Heights] Summary of Tithe Collection Proceedings: Of the 360 names listed on the tithing register: - 259 citizens paid the requisite 30% of their salaries in full - 87 citizens submitted partial payments with debt promises (See Debt Ledger for details) - 13 citizens optioned for public flogging and indentured servitude - 1 citizen refused outright to pay—as per requisite, their assets will be seized, along with those of their extended family members, to be redistributed pending absolutions Total Weekly Tithings: - 21,890 zinos in minted coinage - 7,503 zinos in debt promises - 4,401 zinos in forfeited property (See estimated valuations in notes below) Property Item 1: Qty 3 – Coin chains, silver. Valued at 69 zinos#linebreak() Property Item 2: Qty 1 – Orzhov charm, lapis lazuli with crystal sunburst. Valued at 155 zinos#linebreak() Property Item 3: Qty 7 – Thrull face masks, gold plated. Valued at 109 zinos#linebreak() ~ It's my third full week as a certified tithe taker, and despite my father's assurances, it hasn't gotten any easier. Today was especially bad, so I'm writing about it here in my ledger. No one ever reads through all these notes anyway, and I can jot down my feelings whenever I want, and nobody will be the wiser. Today was my first refusal. The citizen in question tried to argue with me that the new thirty-percent requisite tithing was too much. It used to be ten percent, he said, as far back as he could remember. I gently explained that it #emph[was] still ten percent—the first ten percent going toward defense and war management, the second ten percent going to social services and infrastructure, and the final ten percent going to Orzhova to compensate the Obzedat and the Oligarchs for their valuable time, but he didn't want to hear that. I presented him with the opportunity to make up the other twenty percent in debt promises if he needed to, but then he started cursing the guild, saying that our guildmasters had better get their greedy hands out of his pockets before he did something about it. I could overlook his agitation and swearing, but I couldn't ignore a blatant threat against the Obzedat. As I moved to subdue him, his eyes twitched like those of a rabid bat. He charged me, his bare hands beating against my gold-plated armor until the metal turned red with his blood. I dealt him a forearm to the temple and then used my staff to sweep his feet from underneath him. He fell back and hit the dirt, his breathing heavy and hard. He locked eyes with me, like the punishment that was about to befall him was all my fault. #emph[He's ] the one who refused to pay. I was just doing my job. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Date: The 24th of Dhazo] #strong[Location: Prosperity Estates] Summary of Tithe Collection Proceedings: Of the 292 names listed on the tithing register: - 120 citizens paid the requisite 30% of their salaries in full - 127 citizens submitted partial payments with debt promises (See Debt Ledger for details) - 37 citizens optioned for public flogging and indentured servitude - 8 citizens refused outright to pay—as per requisite, their assets will be seized, along with those of their extended family members, to be redistributed pending absolutions Total Weekly Tithings: - 6,890 zinos in minted coinage - 37,503 zinos in debt promises - 8,143 zinos in forfeited property (See estimated valuations in notes below) Property Item 1: Qty 3 – Brass knuckles, spiked. Valued at 37 zinos#linebreak() Property Item 2: Qty 12 – Small censers, silver with gold trim. Valued at 155 zinos#linebreak() Property Item 3: Qty 1 – Communications earpiece, Dimir, enchanted. Valued at 109 zinos#linebreak() ~ Today, after dinner, I presented my father with the money I'd skimmed from the tithes. Nearly five hundred zinos. I could practically see the gold reflecting in his wide, glassy eyes. He wiped away a tear before it fell, then he pulled me into a tight embrace. "Two-hundred fifteen zinos more than last week! That's my girl!" he said to me, pinching my ear. I felt proud to contribute to my family's diminishing coffers. It's been rough going lately, even before Orzhova's tithing hike. A few years ago, a string of bad investments had obliterated much of Father's inheritance. He went to our ancestor spirits in hopes of obtaining a loan from the massive fortunes they'd clung to after death. Admitting failure wrecked him, and we would all have to suffer through our ancestors' contemptuous stares whenever they visited us for Absolutions Day or the Eve of Reckoning. But what Father came back home with was worse than being saddled with debt. He'd returned home with the truth: there was no family fortune. Our ancestors' wealth had been heavily tied into the coffers of the Ghost Council, and when the Ghost Council bit the dust, their money went, too. Our ancestor spirits had been keeping up pretenses of their affluence this whole time, when in reality, they #emph[only ] had a few million zinos to their names and couldn't bear to part with any of it. #figure(image("004_The Ledger of Hidden Fortunes/01.jpg", width: 100%), caption: [Ministrant of Obligation | Art by: <NAME>], supplement: none, numbering: none) I was resentful, but Father understood better than I did. Keeping up appearances was both important and expensive for us as well. We didn't dare employ less than three servants, for fear of word getting back to the Oligarchs. As a pontiff, Father only associated with them on occasion, but standing in the shadows of Oligarchs was a privilege many aspired to. We couldn't risk having our social standing downgraded, so everyone in our family chipped in. Tithe taking is my contribution. "I knew you had it in you," Father said, stuffing the money into one of his deep pockets. "Didn't I tell you it'd get easier?" Pinch a zino here, pinch one there. Fudge the ledgers. All the tithe takers do it. Only I couldn't. I know it was the whole reason Father pushed me into the profession. #emph[An honest day's work for an honest day's skimming ] he'd say with a laugh. But taking people's money didn't bring me joy, even if our family needed it, because all those families out there had so much less than we did. So I got a second job assisting a fleshmage. Making thrulls isn't the most glamorous line of work, but it pays well, and I'm good at it. If my parents ever find out, I'll never hear the end of it—how flesh magic is beneath our station, and if the spirits in our family ever found out~gods help us all. Half of what I earn each week, I give to my father. I use the other half to assist citizens who fall short on their tithes. I can't help many, but in my heart, I hope there are more tithe takers out there doing the same. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Date: The 11th of Prahz] #strong[Location: Oligarch's Row, South] Summary of Tithe Collection Proceedings: Of the 402 names listed on the tithing register: - 34 citizens paid the requisite 40% of their salaries in full - 339 citizens submitted partial payments with debt promises (See Debt Ledger for details) - 34 citizens optioned for public flogging and indentured servitude - 29 citizens refused outright to pay—as per requisite, their assets will be seized, along with those of their extended family members, to be redistributed pending absolutions Total Weekly Tithings: - 1,890 zinos in minted coinage - 68,667 zinos in debt promises - 22,852 zinos in forfeited property (See estimated valuations in notes below) Property Item 1: Qty 4 – Cluestones, enchanted. Valued at 67 zinos#linebreak() Property Item 2: Qty 2 – Sigils, tainted. Valued at 55 zinos#linebreak() Property Item 3: Qty 12 – Quart of human blood, pasteurized. Valued at 109 zinos#linebreak() ~ Father came home in a foul mood today, another one of his get-rich-quick schemes gone wrong. Terribly wrong from the look of his leg, now a mangled twist of blue-gray thrull flesh. I tried to get close enough to work my flesh magic on it without him noticing, but he'd fumed and stomped all over the house. The thrull's gold faceplate attached to the bottom of his foot pounded against the stone floor so hard that it toppled the porcelain dolls in Mother's curio. Father cursed the Selesnya Conclave, calling them a bunch of bran eating, leaf wearing, brainwashed zealots, and saying he'll bring the guild down single handedly for what they did to him. All the while, copper zibs kept falling from the holes in his pockets. From his rantings, I gleaned there was an Izzet machine and wurms involved. It sounded interesting, but I didn't pry. It's better to avoid him when he's in one of his moods. Something interesting #emph[did] happen working for Fleshmage Jarek today. I was busy rendering a corpse, when I heard him in the reckoning room. "Quiet," he said. "Your pleas are useless now." A woman begged for her life, which was nothing new. All borrowers did that. But then she said, "I've got information about a vulnerability at Vitu-Ghazi. I just need to check in with my handler, and I'll be compensated justly. Then I can clear all my debts!" Beyond curious, I let the flesh I was working with drop into a heap and nearly knocked over a stack of kneecaps as I rushed to the door. When I peeked inside the reckoning room, I saw a woman dressed in fine Selesnyan robes, the gauzy material barely a whisper against her skin. Her movements were rash and harsh, though, and caught me by surprise. When I was younger, I knew in my heart that I wanted to join Selesnya. I'd wanted to study their ways and embrace the power of "the gift." Father shut that down before the idea had a chance to take root, so I didn't get to learn much about them, but I did know one thing—no Selesnyan would dare get caught up into debt with the Orzhov Syndicate. I could only conclude she was a spy. Dimir, most likely. Jarek had no pity for her, and he called upon the runes lurking in the shadowy corners of the reckoning room. Magic struck out from his fingertips, black tendrils of smoke that were ephemeral at first, but then sharpened into daggers. He flayed the borrower from head to toe, and as soon as Jarek made the final cut, the spirit drifted free toward the ceiling. Before it could escape, he bound it to a tome with another set of spells, and then ordered the spirit to queue along the wall with the others he'd harvested today. A baker's dozen. Busy times. When he called for me, I counted to five, then ran in like I hadn't been snooping at the door. I dragged the corpse out of the reckoning room, undressed it, and then cleansed it with fragrant oils that would halt decomposition. I consulted my diagrams, figuring out the shapes I needed to carve from the flesh. We'd gotten an order for a treasury thrull. Creating a six-ton beast is a tricky puzzle to put together, and usually required no less than forty humanoid bodies, but I'd taught myself to do it in thirty-three. The trick is to #emph[measure twice, cast once] ~not a big secret, but you'd be amazed at how many mages just start invoking magic without any planning. I could make a whole 'nother thrull out of the flesh scraps they leave behind. But as I started to draw my outlines on the body with a charcoal stick, my eyes kept flicking over to the Selesnyan robes folded nicely in the middle of the floor. #figure(image("004_The Ledger of Hidden Fortunes/02.jpg", width: 100%), caption: [Camaraderie | Art by: <NAME>], supplement: none, numbering: none) I prayed to my ancestor spirits for the rogue thought to go away. One of the thrull imps I'd assembled today mewed, its eyes darting from me to the robes and back, like it knew what I was thinking. "I really shouldn't~" I said back to it. It'd be improper to take the robes. They belonged to Orzhova now, just another bit of forfeited property to log into a ledger: Property Item 12,542: Qty 1 – Robes, Selesnyan, silk. Valued at 68 zinos No one would miss them. I shoved the robes into my satchel. Maybe I'm not so bad at skimming after all. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Reading back over that entry, I realize it made my dad sound awful, but he's wonderful in all the ways that count. During our times of plenty, he often contributed to the arts, commissioning the stained-glass portraits of our ancestors that hung in our dining hall windows. He'd invested in several small businesses, including one that manufactured a keyrune generator, which changed the security scene of Ravnica. And Father has the patience of a saint with me. In my younger days, I'd had a bit of a rebellious streak~still trying to figure out who I was and where I belonged. I'd dyed my hair every color of the rainbow (except green, of course~Father would never allow #emph[that ] color in his house), and he didn't bat an eye, just paraded me through our basilica while my mother cowered ten steps behind us, too embarrassed to be seen by the ladies in her social circles. I was small under the bulk of those intimidating basilica arches, but walking next to Father, with that smile he had on his face, I felt like a giant. He's supported me in every way imaginable, which is why I'm willing to deny this one part of myself for him. But through him, I've been able to see the good that fills our guild, and Orzhov is enough for me. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Date: The 26th of Prahz] #strong[Location: Penance Place] Summary of Tithe Collection Proceedings: Tithe taking has been temporarily suspended due to rioting. Reinforcement soldiers from the Tenth District are being sent to help pacify the situation. Well, I had the afternoon off unexpectedly, and I'm not looking forward to going back tomorrow. The citizens aren't happy about another tithing hike so soon, and I'm getting tired of scrubbing blood from all the nooks and crannies in my armor. Father went off to meet with a dock boss about a potential investment, and my mother was at her social club, so I thought I'd have the house all to myself for the day. It wasn't long before my thoughts circled back to the Selesnyan robes hidden under my mattress. I went to try them on, just to see how they felt. They fit so well, and compared to the armor I'd grown used to, it was like wearing clouds. I imagined leaf filigree running down my arms, hair pulled up and bound with a twirling vine, berries and flowers pinned in there just so. I capered into the living room and bowed before Mother's stately curio, pretending it was Vitu-Ghazi. I danced like I was the wind bristling through the world tree's leaves—like I was free from seizing the assets people had worked themselves to the bone for, and free from seizing their #emph[actual ] bones. Then the front door slammed shut. My father was home and judging by the swampy stench he'd brought back with him, I knew it wasn't going to be pretty. I tried to get free of those treacherous robes, but the ties in the back were knotted tightly. Left without options, I pressed into the shadows, watching as he stormed about, ranting over how he'd nearly been squashed by a crate of whisky. He tore off his wet cloak which had all sorts of flotsam clinging to the black wool. "Miri!" he called for me, voice loud, like he thought I was still in my room. "Miri! Come here." Then his eyes finally adjusted to the dim lighting, and he saw me. I'd never seen him so mad. His voice shook the rafters, sending bits of dust raining down upon me. Wearing Selesnyan robes in his house? I'd be disowned. So I scrambled for an excuse, any excuse. "I came across some information, Father, a tip that Vitu-Ghazi has a vulnerability." I swallowed down the lump in my throat. "I'm going undercover to see if I can find it, and if I do, we can exploit it and have all of Selesnya begging us for mercy!" "Where did you get this information?" he grated at me, eyes still slit. "This doesn't sound like an assignment for a tithe taker. I'm going to speak with your commander." I grabbed his shirt, still sopping wet, realizing I'd have to come clean about practicing flesh magic. "The assignment didn't come from my commander. I heard the information from a spy with my own two ears." "But from where?" "The spy was pleading for her life, right before her spirit was taken. I've~been working for a fleshmage in my spare time." His scowl didn't ease. Instead of helping my cause, I'd just defied him twice over. If I was going to win my father's trust back, I really needed to sell it. "Father, do you honestly think I'd wear these confounded rags if I didn't think this tip could bless us with unfathomable wealth? I've seen how you and Mother have struggled, forgoing your own happiness to bolster mine. The moment I heard about Selesnya's vulnerability, all I could think about was how I could use it to bolster Orzhov's prosperity. The tithe takers have trained me in intimidation and combat. You've taught me how to manipulate the system for our family's gain. Please. Let me do this." His eyes eased. His posture went from one tensed muscle to arms spread wide, ready for an embrace. I'd planted the seed of fortune in his mind, and when he looked at me in those robes, he no longer saw a traitor, but an apt successor who would restore our family's wealth. I am not sure which look scares me more. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Date: The 7th of Mokosh] #strong[Location: Initiates' Compound] I'm #emph[here] ! Selesnyan orientation. And I've got a proper journal now, made of twice-blessed palm leaf paper with little yellow flowers pressed into the pulp. The pages are brittle and too thick to turn properly, and in some spots, it seems like it's actively repelling my ink~but it's beautiful, and it's mine, and I no longer have to hide it. In fact, the elders actively encourage the journaling of our feelings whenever the need strikes. #figure(image("004_The Ledger of Hidden Fortunes/03.jpg", width: 100%), caption: [Plains | Art by: <NAME>], supplement: none, numbering: none) Our class is three hundred initiates strong. Danika, Caz, and Vasil are in my assigned developmental pod. Caz and Vasil are unguilded. Danika had worked as an Azorius arrester, but after the carnage of the Udzec riot and the following crackdowns, she had a nervous breakdown and decided she needed a change of scenery. Our developmental pod is connected to four others, forming a support branch, and those branches connect to enrichment trunks, and then there was something about a root system, but I'd tuned the elder out by then, because as if on cue, the odor from all three hundred of our collective armpits started to shout obscenities at my nose. We'd cleansed ourselves in a warm bath of berries and oils before changing back into our freshly washed robes. It smelled heavenly at the time, but those botanicals apparently did nothing to counteract the sweat and stench generated in our moist spots. One of the initiates had the gall to raise his hand to complain. The elder had called the smell a part of our "natural aura" and promised we'd soon get used to it. Danika passed a small vial around our pod, and we each pressed a dab of fragrant oil below our noses, then sat back and listened intently to the prayer instructions. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Date: The 12th of Mokosh] #strong[Location: Conclave Assembly] I almost feel bad for writing this, but I already miss home. Sure, the Orzhov Syndicate has its issues, but our hygiene is impeccable, and our paper doesn't spontaneously crumble into pieces if you look at it too hard. And never in my life have I appreciated money as much as I do now. For example, yesterday, when I found out we were being called to attend our first Collective Blessing, I instantly knew that I had to show up in something more dazzling than my stolen robes. After nearly a week of solid wear, they were starting to look shabby, but there's no clothier within walking distance of the initiates' compound, just a couple of seamstresses who make robes out of their homes. I found the exact robes I wanted, though, beautiful flowing silks embroidered with leaves in threaded gold. My wallet practically jumped out of my pocket when I saw them. Her work was magnificent. Celestial. I couldn't help but think of how profitable her business could be with the help of a good investor. She could buy out the debt contracts of a half-dozen borrowers and have them do all the sewing. She could triple her profits in the first year alone, expand her brand, purchase a vendor spot on Tin Street, woo more investors, then~ ~But that is not the Selesnyan way. To make matters worse, the seamstress would only trade the robes for a copper tea kettle or bandu-filed pruning shears. I figured a tea kettle would be easier, since I had no idea of what bandu-filed pruning shears were. I went to a metalsmith who wanted four pairs of knitted socks for the tea kettle. The only knitter nearby wanted three pounds of white wolf fur. (I didn't dare inquire what it was to be used for.) I found a wolf-rider who was infirmed and wanted his pup walked in trade. I walked the wolf (#emph[sooo] not a pup). Gave the fur to the knitter and the socks to the metalsmith. I was really getting the hang of bartering, though I'd spent nearly my entire morning running errands instead of studying, and let me tell you, my personal aura was #emph[ripe] . So I cleansed myself before I went to back to the seamstress, because I knew I wouldn't have time before the Collective Blessings assembly to do it. Then I knocked on her door, and when she answered, I held the kettle out to her, nice and polished, unable to contain the proud smirk on my face. "I would like to barter this for those robes, please." She smiled the kindest smile and said, "But what use would I have for #emph[two ] tea kettles?" And from inside her home, I heard a kettle whistling, traded to her by some other customer not twenty minutes prior. My head ached. My heart did, too. When I reconvened with my pod, Danika saw my frustration and leant me a shawl that completely changed the look of my robes. We were late to Blessings, so we sat in back where the shaman wouldn't notice us. We grew restless after the third hour of chanting and started passing notes on palm leaf paper. I asked if she'd go to Vitu-Ghazi with me tomorrow. She seemed to be settling into the Conclave faster than I was, and I could use her support. She agreed, and when our note disintegrated into a pile of pulp when she handed it back to me, we could barely contain our laughter. I knew the chances of me finding Vitu-Ghazi's vulnerability were slim. I knew disappointment awaited my father. We may never claim back our fortune, but at least I'll be able to tell him I made an effort. And maybe with his birthday coming up, he'd soon forget all about this silly plan. In the Syndicate, birthdays are celebrated with coin necklaces, and every year, the Oligarchs who Father spends so much of his time trying to impress will douse him in wealth. The necklaces are mere trinkets to the Oligarchs, of course, but their generosity could keep our family afloat for months, maybe even a year. Back when I was a kid, and when birthday money was just fun money, I'd help him cut the coins from the string and stack them into piles. He'd donate half to the church, as is mandated, but the other half he'd spend at the dromad races, his chance to turn that seeming pittance into a fortune. He always took me with him. I'd sit on his lap, though I'd fall off every time he stood in a flurry of emotions—either thanking the spirits for a winning pick or cursing them for a losing one. There was a lot more of the latter. Every year, he would head home with empty pockets and a big grin stretched across his face, saying how he was #emph[that ] #emph[close] to winning it all, and how one day there would be nothing I could ask for that he wouldn't be able to give me, and then he'd pinch my ear and gasp at how he'd found one last coin tucked behind it. Ugh. This Blessings assembly is running into its fourth hour. My butt cheeks have fallen asleep. Gods, I miss home right now. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Date: The 13th of Mokosh] #strong[Location: Initiates' Compound] Today we learned a growth spell. My podmates all seem to have found "the gift" and were able to conjure seeds into healthy plants. Me, I just spent my time praying to the ancestor spirits for something to happen, #emph[anything ] to happen, before the elder came back from his meditations and saw my sad terracotta pot filled with nothing but dirt. "Have you tried the Chant of Vitu-Ghazi?" Vasil asked me, a concerned bend on his brow. I shook my head. I spent all of yesterday morning chasing down that tea kettle, so I didn't get a chance to practice. Vasil walked me through the chant, and when I tried it myself, I could see something wriggling beneath the dirt, but the seeds never sprouted. I dug them up and held them in my palm. The plump white seeds had shriveled and turned brown. "Don't worry," said Caz, pressing new seeds into the pot. "The seed spark invocation is foolproof." He nudged me. "They don't teach it to initiates because it's so simple, they wouldn't bother learning the chants." Then Caz twirled his fingers in a spiral, gathered an orb of green, pulsing magic into his hand, and sprinkled it into his pot. His succulent plant doubled in size. I tried doing the same, and when I sprinkled my dirt, three sprouts emerged. For a brief moment, I was ecstatic, but then they withered, just as the seeds had. When my pod ran out of ideas, some of the people in our support branch tried to help. When those ideas failed, I got advice from one of the initiates in our enrichment trunk who had placed out of enchantment lessons. But nothing worked, and the elder was due back any moment. I wondered if I'd touched too many dead things to ever make something grow. Danika wouldn't give up on me though. She worked with me on my chants, right until the elder was upon us, then at the last possible second, she switched her pot with mine. "Nice work," the elder said to me, pinching the leaves to test their suppleness. "Very nice." Then he moved onto Danika and frowned at her wilted sprouts. "The gift will find you eventually," he said. "But I'd like you to spend the rest of the evening in remedial meditation." Later, I asked her why she would do that for me. She said she knew how much I wanted to visit Vitu-Ghazi today, and if we couldn't go together, at least I'd be able to go alone. I didn't know what to say. I was simply bowled over by her generosity and sacrifice, and the kindness of everyone who'd tried to help me. So I went to the Guildhall all by myself, and when I stood before it, I marveled at the massive world tree. Seeing it in person was bittersweet. It was so perfect, so serene, and the organic architecture swirling around it looked more like it was made from wisps of smoke than stone. But I knew tomorrow I'd be heading home empty-handed and would face my father's disappointment. All those feelings washed away when something buzzed against my thigh. I reached down and found a pocket in my robe. I hadn't noticed it before. Actually, I'm sure it hadn't been there. As I slipped my hand inside, threads of dispelled magic drifted away. The pocket suddenly felt heavy and pulled my robes down on one side. I made sure no one was watching, then pulled the item out. It was an artifact~Selesnyan. It pulsed in my hand, and when I raised it up to Vitu-Ghazi, a shocking truth was revealed. The great tree had been restored after an attack from some Izzet magelord, but it seemed those mendings were superficial. Beneath the bark, I could see how fragile the world tree was, stress fractures running through its branches, hidden support struts barely able to take the weight. One well-targeted attack could bring the whole structure down, this time for good. This artifact would be worth #emph[millions ] to Orzhov. Tens of millions. Maybe more. Our family would be pulled out of despair, and the pride my father would have for me would shine as brightly as the sun. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Date: The 14th of Mokosh] #strong[Location: My Bedroom] Yesterday evening, I rushed home all the way from the Conclave, eager to tell my father what I discovered. I busted through the door, sweating and heaving. Before I could open my mouth, my father took one look at the mess I was and called the servants to draw me a bath with fragrant soaps, to fetch me something decent to wear, and to make me a proper Orzhovian meal. Only then would he hear the news I'd brought him. He sent a page for my mother to fetch her from her social club. When she got home, she fawned all over me, picking the sticks and berry stems from my hair like a momma wolf preening her pup's fur. "I've missed you, Miri," she said, and for the first time, my name was like a song off her lips. Any embarrassment she'd felt toward me was gone. "The house hasn't been the same without you. Your father's been insufferable, bragging to anyone and everyone about how brave his daughter is." The smell of beef tips and gravy wafted up. After a week of eating bran flakes and dried fruit, I was practically salivating all over myself. It drew my attention, but my mother's hand pulled my chin back so I faced her. "I know that your trip to Selesnya was just a ruse. You've had that guild in your heart since you were a child. A mother always knows. Just tell your father you found this." She hands me an artifact—a delicate crown of gold, radiating a soft white light. "Tell him you pilfered it from the halls of Vitu-Ghazi. Make up a wonderful story, and it will sate his fancies of fortune for now." When she said that, I couldn't wait for an even bigger reveal at dinner. The ancestor spirits even joined us, sulking over the delicious spread that they knew we couldn't afford. I told my story, and my father hung on my every word. He laughed when I mentioned the awful paper and my morning spent bartering. My mother smiled, a crinkle of pride at the corner of her eyes. It was then I saw how much wealth my family already had. Not by the coins in our pockets, but the love we had for each other in our hearts. I thought of the friends I'd made at the Conclave, too. Of the deep connections we'd made in so little time. Connections I'm not quite ready to give up on. When I got to the part about Vitu-Ghazi, something unexpected came out. I didn't tell them about the vulnerability, and that our family was destined to share a true fortune. Instead I presented my father with the artifact my mother had given me. "The Crown of Convergence? Miri, this is worth thousands!" my father bellowed, and as he pulled me in for a hug, my mother and I shared a conspiratorial grin. #figure(image("004_The Ledger of Hidden Fortunes/04.jpg", width: 100%), caption: [Crown of Convergence | Art by: Jen Page], supplement: none, numbering: none) "I did it for you, Father. I wanted for you to be proud." "Oh, Miri. I've always been proud," he said. "And there's no fortune in this world that could tip the scales against the love I have for you." This will be the last entry in my Selesnyan journal. I don't want my father to ever stumble upon it, though I doubt the paper will last more than a few months in storage, especially with the way my tears are turning the pages to mush. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Date: The 29th of Mokosh] #strong[Location: Oligarch's Row, North] Summary of Tithe Collection Proceedings: Of the 614 names listed on the tithing register: - 551 citizens paid the requisite 18% of their salaries in full - 65 citizens submitted partial payments with debt promises (See Debt Ledger for details) - 5 citizens optioned for public flogging and indentured servitude - 0 citizens refused outright to pay Total Weekly Tithings: - 68,417 zinos in minted coinage - 3,670 zinos in debt promises - 2,852 zinos in forfeited property (See estimated valuations in notes below) Property Item 1: Qty 3 – Runes, enchanted. Valued at 67 zinos#linebreak() Property Item 2: Qty 1 – Sigil, very tainted. Valued at 75 zinos#linebreak() Property Item 3: Qty 12 – Flagon of bat guano. Valued at 205 zinos#linebreak() ~ I'm back at work, and things are better now. Fortunately, I missed the worst of the revolt, and calm has reclaimed the streets now that the Syndicate has agreed on a very reasonable tithing of eighteen percent. I haven't had to wash blood from my armor in over a month. Father's birthday was last week. As expected, he brought home a small fortune in coin necklaces, but he said the best present was the gift I'd given him. "It's an enchanted money tree," I said as I presented him with the terracotta pot. He looked down at the sapling and frowned. He was about to scream something about not allowing anything green inside our home, but then I reached into the soil and retrieved a gold coin. His eyes brightened. "I skimmed it from forfeited property yesterday," I said. "It produces one coin every night." Ever since then, my father has dutifully tended to that tree—watering it, making sure it gets enough sun, and even talking to it when he thinks no one is listening. And every night, after my father has fallen to sleep, and before I slip off to secretly work flesh magic until the wee hours of the morning, I place a gold coin in the soil for him to find. Having that bit of greenery in our home fills me with serenity and with hope. Right now, it's just a sapling that he's allowed into our lives, but soon it will be ready to spread its roots beyond its pot, and eventually, so will I.
https://github.com/Gavinok/typst-res
https://raw.githubusercontent.com/Gavinok/typst-res/master/projects.typ
typst
#import "layout.typ": project_subheading #let project(url, name, language, body) = { ( url: url, name: name, language: language, body: body ) } #let project_to_text(project) = { project_subheading(project.url, project.name + " (" + project.language + ")", project.body) } #let is_desired_project(desired_languages, project) = { desired_languages.map(upper).contains(upper(project.language)) } #let projects = ( project("https://github.com/Gavinok/scripts", "Automation Scripts", "POSIX Shell")[ A collection of POSIX Shell Scripts for automating my life and improving my productivity. These are probably my most popular side projects. ] ,project("https://github.com/Gavinok/RL_Encoding", "Run-length encoding", "C")[ A C implementation of the Run-length encoding (RLE) lossless data compression technique. ] ,project("https://github.com/Gavinok/StrokeMonitor", "StrokeMonitor", "C++")[ Embedded stroke rate, speed, and distance monitor for canoes and kayaks. ] ,project("https://github.com/Gavinok/Filesystem-Emu", "Filesystem-Emu", "Java")[ An emulation of a FAT-based filesystem in Java. Introduced me to the foundations of Object Oriented Programming. ] ,project("https://github.com/Gavinok/html2csv", "HTML to CSV", "Python")[ A python script that converts HTML5 tables into a CSV. Introduced me to text parsing with regex as well as python programming. ] ,project("https://github.com/Gavinok/YALL", "YALL Scheme Interpreter", "C++")[ YALL is a simple and extensible Scheme (lisp) dialect written in C++ ] )
https://github.com/pabsantos/anpet-typst
https://raw.githubusercontent.com/pabsantos/anpet-typst/main/anpet-typst.typ
typst
#let anpet-typst( // Título title: [Título do trabalho], // Vetor com a lista de autores. Para cada autor é possível incluir o nome, instituição, departamento e e-mail para o primeiro autor authors: (), // Resumo do trabalho resumo: [#lorem(150)], // Abstract do trabalho abstract: [#lorem(150)], // Restante do texto body, // Agradecimentos agradecimentos: [], // Referências bibliográficas bibliography: none ) = { // Configura a página set page( paper: "a4", margin: (top: 3cm, left: 3cm, right: 2cm, bottom: 3cm), header: [ #grid( columns: 1fr, align: center, image("logo/logo-38-ANPET.png", width: 27%) ) ], footer: [ #grid( columns: 1fr, align: left, image("logo/ANPETlogo_novo.png", width: 2.39cm) ) ] ) // Metadados // set document(title: title, author: authors.map(author => author.name)) // Configura a fonte e corpo do texto set text(font: "Times New Roman", size: 12pt, lang: "pt", hyphenate: false) set par(justify: true, leading: 0.65em) show par: set block(spacing: 1.3em) // Configura os títulos de seção set heading(numbering: "1.1.1.") show heading.where(level: 1): set text(weight: "bold", size: 12pt) show heading.where(level: 2): set text(weight: "bold", size: 12pt) show heading.where(level: 3): set text( weight: "regular", size: 12pt, style: "italic" ) show heading: set block(above: 1.3em) // Tabelas e figuras set table( stroke: (_, y) => if y == 0 { (bottom: black + 1pt, top: black + 1pt) } ) show table.cell.where(y: 0): set text(fill: black, weight: "bold") show table.cell: it => {text(it, size: 10pt)} show figure.where(kind: table): set figure.caption(position: top) show figure.caption: it => [ #text( weight: "bold", size: 10pt, [#it.supplement #it.counter.display(it.numbering):] ) #text(size: 10pt, [#it.body]) ] // Equações set math.equation(numbering: "(1)") // Título align( center, text(weight: "bold")[#title] ) v(12pt) // Lista de autores grid( columns: 1fr, align: center, ..authors.map(author => [ #text(weight: "bold", [#author.name]) \ #if "affiliation" in author [ #text(size: 10pt, [#author.affiliation]) \ ] #if "department" in author [ #text(size: 10pt, [#author.department]) \ ] #v(6pt) ]), ) v(6pt) // Resumo text(size: 10pt, weight: "bold", [RESUMO \ ]) text(size: 10pt, [#resumo]) v(6pt) // Abstract text(size: 10pt, weight: "bold", [ABSTRACT \ ]) text(size: 10pt, [#abstract]) v(6pt) // Renderiza o documento body // Agradecimentos if agradecimentos != none [ #text(size: 10pt, weight: "bold", [Agradecimentos \ ]) #text(size: 10pt, [#agradecimentos]) ] // Bibliografia text(10pt, [#bibliography]) v(5pt) // Informações finais dos autores line(length: 100%, stroke: 0.5pt) v(-10pt) grid( columns: 1fr, align: left, ..authors.map(author => [ #text( size: 10pt, [ #text(style: "italic", [#author.name]) (#author.email) \ #if "affiliation" in author [ #author.affiliation, ] #if "department" in author [ #author.department \ ] #if "address" in author [ #author.address #v(6pt) ] ] ) ]), ) }
https://github.com/AlexCid/CryptographieLaSalle
https://raw.githubusercontent.com/AlexCid/CryptographieLaSalle/main/td01.typ
typst
#set page( paper: "a4", numbering: "1" ) #set heading(numbering: (..nums) => nums .pos() .slice(1) .map(str) .join(".") ) #align(center, text(25pt)[Cryptographie]) #align(center, text(17pt)[TD n°1 : Introduction & Histoire de la cryptographie]) = Partie I == Chiffrement Caesar En utilisant la substitution A #sym.arrow E, B #sym.arrow F, ..., chiffrez le texte suivant: `ATTAQUEZ AU CREPUSCULE` == Avé Caesar ! Le texte suivant a été chiffré suivant un chiffrement de substitution de type Caesar. Saurez-vous retrouver le message originel ? `WR AR CRAFR CNF DH VY L NVG QR OBAAR BH QR ZNHINVFR FVGHNGVBA` Remarque: vous pouvez écrire un programme en Python pour vous aider = Partie II On a intercepté le texte suivant: ``` VLETDIBTLRVWISIDIZSFDJAAQHEKXVTWMXWQRMILMFJVEBWRVZJUZDLWWSELWZSSKMIEEAXFNAGYKQVNWJQWU CABSRWVLITSGGZMRMDETWZTMWXDTDBZSKWYFUBWRLNVRMBEARVCMHEQXVTRSMEJPVQNVWURRKWUMJAYIAQWXI AKARWXTEAHVGKFNLWWWYUETAGSYVSZSGASVSYMMSYKAKZIFYLNPGQEJRLILIJWVOCKSFYEEAWXETITAKIKFZE CPUMNCABLEUMVNBSGWVLOVHIFXVEBSGWVLOVEEFLVACPYKFXEAUSERVACPRGZIRQLYJJJACPPGHLTQGRKQFCI DIKFLXQFXGSRTQGRKIVSXSCKFESIMBGIVUZKHMXFLLWWNNCLI<KEY> AQ<KEY>EQ<KEY> ``` Grâce à votre raiseau d'espions, vous savez qu'il s'agit d'un texte clair en français qui a été chiffré avec un système de Vigenère, réputé inviolable ! Cela ne va cependant pas vous arrêter, et vous vous attelez à la lourde tâche de déchiffrer ce message cryptique... == Décryptage automatique du chiffre Caesar Dans la partie précédente, vous avez probablement essayé les 25 chiffrements Caesar différents pour voir "à l'oeil" quel déchiffrement produit un texte français lisible. C'est une solution, mais on peut faire mieux : retrouver directement le chiffrement utilisé grâce à la méthode des fréquences. En français, les fréquences des lettres sont les suivantes : ```python frequences = {'A': 0.0815, 'N': 0.0712, 'B': 0.0097, 'O': 0.0528, 'C': 0.0315, 'P': 0.028, 'D': 0.0373, 'Q': 0.0121, 'E': 0.1739, 'R': 0.0664, 'F': 0.0112, 'S': 0.0814, 'G': 0.0097, 'T': 0.0722, 'H': 0.0085, 'U': 0.0638, 'I': 0.0731, 'V': 0.0164, 'J': 0.0045, 'W': 0.0003, 'K': 0.0002, 'X': 0.0041, 'L': 0.057, 'Y': 0.0028, 'M': 0.0287, 'Z': 0.0015} ``` Afin de retrouver automatiquement le bon texte clair pour un texte chiffré par un chiffrement Caesar, vous pouvez appliquer l'algorithme suivant : - Appliquez un déchiffrement Caesar (B #sym.arrow A puis C #sym.arrow A etc) - Calculez la fréquence des lettres du nouveau texte obtenu - Effectuez un produit scalaire entre le vecteur des fréquences du texte et le vecteur de fréquence des lettres dans la langue française - Le texte qui maximise ce produit scalaire a de fortes chances d'être le bon texte clair Implémentez une telle fonction de déchiffrement automatique. Fonctionne-t-elle sur le texte chiffré de la partie I ? Pourquoi cela pourrait-il ne pas être le cas ? / Question bonus: Pourquoi cela fonctionne-t-il ? == Détermination de la taille de la clé utilisée Armé de cet algorithme, nous allons pouvoir déterminer la taille de la clé utilisée pour le chiffrement Vigenère. En effet, on peut remarquer que pour une clé de taille $L$, le texte obtenu en ne gardant qu'une lettre sur $L$ du chiffré est en fait le chiffrement, par un chiffre de type Caesar, du texte clair dans lequel on n'aurait gardé qu'une lettre sur $L$. Ainsi, si on a correctement déterminé la longueur de la clé, alors l'algorithme de la question précédente devrait trouver un déchiffrement Caesar associé à un produit scalair important (pour le chiffré obtenu en gardant une lettre sur $L$), alors que pour une longueur de clé incorrecte, tous les produits scalaires devraient être relativement faibles. Sachant que la clé est de longueur inférieure à 20, déterminez celle-ci. Vous pouvez sélectionner le sous-texte obtenu un gardant une lettre sur $L$ en Python en utilisant la syntaxe `texte[::L]`. Pour toutes les hypothèses de taille $L$ entre 1 et 20, calculer le produit scalaire le plus important en appliquant tous les déchiffrement Caesar possibles, et affichez ces valeurs. Que remarquez-vous ? == Décryptage complet Une fois la taille de la clé obtenue, il devrait être aisé de décrypter entièrement le texte en effectuant $L$ décryptage Caesar successifs. Quelle était la clé ?
https://github.com/Shuenhoy/modern-zju-thesis
https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/pages/undergraduate-cover.typ
typst
MIT License
#import "../utils/fonts.typ": 字号, 字体 #import "../utils/datetime-display.typ": datetime-display #import "../utils/twoside.typ": * #let undergraduate-cover( info: (:), // 其他参数 stoke-width: 0.5pt, row-gutter: 11.5pt, anonymous-info-keys: ("grade", "student-id", "author", "supervisor"), ) = { info = ( title: ("毕业论文/设计", "题目"), grade: "20XX", student-id: "1234567890", author: "张三", department: "某学院", major: "某专业", supervisor: ("李四", "教授"), submit-date: datetime.today(), ) + info if type(info.submit-date) == datetime { info.submit-date = datetime-display(info.submit-date) } context { twoside-pagebreak counter(page).update(0) set text(weight: "bold", font: 字体.仿宋) align(right)[ 涉密论文 $square$ #h(1em) 公开论文 $square$ #h(8em) ] set align(center) v(22pt) image("../assets/zju-name.svg", width: page.width * 0.5) v(2pt) text(size: 字号.小一, font: 字体.黑体, spacing: 50%)[本 科 生 毕 业 论 文<mzt:no-header-footer>] image("../assets/zju-emblem.svg", width: page.width * 0.17) v(20pt) block( width: 70%, [ #set text(size: 字号.三号) #grid( columns: (0.5fr, 1fr), align: (start, center), rows: 1em, stroke: (x, y) => ( bottom: if x == 1 { stoke-width } else { none }, ), row-gutter: row-gutter, "题目", info.title.first(), ..info.title.slice(1).map(v => (none, v)).flatten(), grid.cell(stroke: none)[], grid.cell(stroke: none)[], "姓名与学号", info.author + " " + info.student-id, "指导教师", info.supervisor, "年级与专业", info.grade + info.major, "所在学院", info.department, grid.cell(stroke: none)[], grid.cell(stroke: none)[], "递交日期", info.submit-date, ) ], ) } twoside-emptypage }
https://github.com/max-niederman/MATH51
https://raw.githubusercontent.com/max-niederman/MATH51/main/hw/6.typ
typst
#import "../lib.typ": * #show: homework.with( title: "Math 51 Homework #6", ) = 18.2 $B$ and $B'$ are inverses of the $n times n$ matrix $A$. $ B A B' &= B A B' \ (B A) B' &= B (A B') \ I_n B' &= B I_n \ B' &= B $ = 18.3 == a Since $A$ is $2 times 2$, we can use the formula for the inverse of a $2 times 2$ matrix. $ A^(-1) &= 1 / (a d - b c) mat( d, -b; -c, a; ) \ &= 1 / (a d) mat( d, 0; 0, a; ) \ $ If $a d = 0 iff a, d = 0$, then $A$ is invertible; but otherwise, we can further simpify: $ A^(-1) &= mat( 1 / a, 0; 0, 1 / d; ) $ So if $a, d != 0$, then $A$ is invertible. and its inverse is the diagonal matrix whose diagonal entries are the reciprocals of the entries of $A$. Geometrically, this corresponds to a transformation which "squeezes" $RR^2$ inwards by a factor of $1 / a$ in the $x$ direction and a factor of $1 / d$ in the $y$ direction. == b If $a = 0$, we have $ A &= mat( 0, 0; 0, d; ) \ A vname(e)_1 &= vname(0) $ And similarly if $d = 0$, we have $ A &= mat( a, 0; 0, 0; ) \ A vname(e)_2 &= vname(0) $ So in either case, $A$ is not invertible. == c If $forall i <= n : d_i != 0$, let the $n times n$ matrix $M$ be defined as $ M &= mat( 1 / d_1, 0, ..., 0; 0, 1 / d_2, ..., 0; dots.v, dots.v, dots.down, dots.v; 0, 0, ..., 1 / d_n; ) $ Both $D$ and $M$ are diagonal, so they commute and we can compute their product by simply multiplying their diagonals entry-wise: $ D M = M D = mat( d_1 / d_1, 0, ..., 0; 0, d_2 / d_2, ..., 0; dots.v, dots.v, dots.down, dots.v; 0, 0, ..., d_n / d_n; ) = I_n $ Therefore $M$ and $D$ are inverses of each other, so $D^(-1)$ is given by the expression $ D^(-1) &= M \ &= mat( 1 / d_1, 0, ..., 0; 0, 1 / d_2, ..., 0; dots.v, dots.v, dots.down, dots.v; 0, 0, ..., 1 / d_n; ) $ If, on the other hand, there is an $i$ such that $d_i = 0$, $D$ can be written in terms of its columns: $ D &= mat( d_1 vname(e)_1, d_2 vname(e)_2, ..., d_i vname(e)_i, ..., d_n vname(e)_n; ) \ &= mat( d_1 vname(e)_1, d_2 vname(e)_2, ..., vname(0), ..., d_n vname(e)_n; ) $ So we can multiply $D$ by $vname(e)_i$ to get $vname(0)$, $ D vname(e)_i &= vname(0) $ And therefore $D$ is not invertible. = 18.7 == a To check that $M_a$ and $M_(-a)$ are inverses of each other, we can compute their product for the general case of $a in RR$: $ M_(-a) M_a &= mat( 1, -a, 0; 0, 1, 0; 0, 0, 1; ) mat( 1, a, 0; 0, 1, 0; 0, 0, 1; ) \ &= mat( 1, a - a, 0; 0, 1, 0; 0, 0, 1; ) \ &= mat( 1, 0, 0; 0, 1, 0; 0, 0, 1; ) \ &= I_3 $ So $M_a$ and $M_(-a)$ are indeed inverses of each other. == b To check that $N_b$ and $N_(-b)$ are inverses of each other, we can compute their product for the general case of $b in RR$: $ N_(-b) N_b &= mat( 1, 0, 0; 0, 1, -b; 0, 0, 1; ) mat( 1, 0, 0; 0, 1, b; 0, 0, 1; ) \ &= mat( 1, 0, 0; 0, 1, b - b; 0, 0, 1; ) \ &= mat( 1, 0, 0; 0, 1, 0; 0, 0, 1; ) \ &= I_3 $ So $N_b$ and $N_(-b)$ are indeed inverses of each other. == c For any $a, b in RR$, we have: $ mat( 1, a, 0; 0, 1, b; 0, 0, 1; ) = N_b M_a $ This is because left-multiplication by $M_a$ is equivalent to adding $a$ times the second row to the first row, and left-multiplication by $N_b$ is equivalent to adding $b$ times the third row to the second row. Therefore, we need $M_a$ to be applied before $N_b$, so that the second row is not modified before it is added to the first row. Knowing this, we can compute the inverse: $ mat( 1, a, 0; 0, 1, b; 0, 0, 1; )^(-1) &= (N_b M_a)^(-1) \ &= M_a^(-1) N_b^(-1) \ &= M_(-a) N_(-b) \ &= mat( 1, -a, 0; 0, 1, 0; 0, 0, 1; ) mat( 1, 0, 0; 0, 1, -b; 0, 0, 1; ) \ &= mat( 1, -a, a b; 0, 1, -b; 0, 0, 1; ) $ = 18.8 == a $ (D f)(x, y) &= mat( (diff f_1) / (diff x), (diff f_1) / (diff y); (diff f_2) / (diff x), (diff f_2) / (diff y); ) \ &= mat( 3 x^2 - 3 y^2, -6 x y; 6 x y, 3 x^2 - 3 y^2; ) $ == b $ vname(a)_1 &= vec(2 / 3, 1 / 3) \ (D f)(vname(a)_1) &= mat( 3 (2 / 3)^2 - 3 (1 / 3)^2, -6 (2 / 3) (1 / 3); 6 (2 / 3) (1 / 3), 3 (2 / 3)^2 - 3 (1 / 3)^2; ) \ &= 1 / 9 mat( 3(2)^2 - 3(1)^2, -6(2)(1); 6(2)(1), 3(2)^2 - 3(1)^2; ) \ &= 1 / 9 mat( 9, -12; 12, 9; ) \ &= 1 / 3 mat( 3, -4; 4, 3; ) \ (D f)(vname(a)_1)^(-1) &= 3 dot 1 / ((3)(3) - (-4)(4)) mat( 3, 4; -4, 3; ) \ &= 3 dot 1 / 25 mat( 3, 4; -4, 3; ) \ &= 3 / 25 mat( 3, 4; -4, 3; ) \ $ $ vname(a)_2 &= vname(a)_1 - (D f)(vname(a)_1)^(-1) f(vname(a)_1) \ &= vec(2 / 3, 1 / 3) - 3 / 25 mat( 3, 4; -4, 3; ) vec( (2 / 3)^3 - 3 (2 / 3) (1 / 3)^2 - 1, 3 (2 / 3)^2 (1 / 3) - (1 / 3)^3 ) \ &= vec(2 / 3, 1 / 3) - 3 / 25 mat( 3, 4; -4, 3; ) (1 / 27 vec( 8 - 6 - 27, 12 - 1 )) \ &= vec(2 / 3, 1 / 3) - 1 / 225 mat( 3, 4; -4, 3; ) vec( -25, 11 ) \ &= vec(2 / 3, 1 / 3) - 1 / 225 vec( - 75 + 44, 100 + 33 ) \ &= 1 / 225 vec(150, 75) - 1 / 225 vec(-31, 133) \ &= 1 / 225 vec(181, -58) \ &approx vec( #repr(calc.round(181 / 225, digits: 3)), #repr(calc.round(-58 / 225, digits: 3)), ) $ == c $ ||vname(a)_2 - vec(1, 0)|| &= ||vec( 181 / 225 - 1, -58 / 225 - 0 )|| \ &= ||vec( 44 / 225, -58 / 225 )|| \ &= 1 / 225 ||vec( 44, -58 )|| \ &= 1 / 225 sqrt(44^2 + (-58^2)) \ &= 1 / 225 sqrt(#repr(44*44 + 58*58)) \ &approx #repr(calc.round(1 / 225 * calc.sqrt(44*44 + 58*58), digits: 2)) $ $ ||vname(a)_1 - vec(1, 0)|| &= ||vec( 2 / 3 - 1, 1 / 3 - 0 )|| \ &= ||vec( -1 / 3, 1 / 3 )|| \ &= 1 / 3 ||vec( -1, 1 )|| \ &= 1 / 3 sqrt(1^2 + 1^2) \ &= sqrt(2) / 3 \ &approx #repr(calc.round(calc.sqrt(2) / 3, digits: 2)) $ $vname(a)_2$ is closer to $vec(1, 0)$ than $vname(a)_1$ is. = 19.5 == a $ vname(v)'_1 &= vname(e)_1 - Proj_vname(v) vname(e)_1 \ &= vname(e)_1 - (vname(e)_1 dot vname(v)) / (vname(v) dot vname(v)) vname(v) \ &= vec(1, 0, 0) - 2 / 30 vec(2, -1, 5) \ &= vec( 13 / 15, 1 / 15, - 1 / 3 ) = 1 / 15 vec( 13, 1, - 5 ) \ $ $ vname(v)'_2 &= vname(e)_2 - Proj_vname(v) vname(e)_2 \ &= vname(e)_2 - (vname(e)_2 dot vname(v)) / (vname(v) dot vname(v)) vname(v) \ &= vec(0, 1, 0) + 1 / 30 vec(2, -1, 5) \ &= vec( 1 / 15, 29 / 30, 1 / 6 ) = 1 / 30 vec( 2, 29, 5 ) $ $ vname(v)'_3 &= vname(e)_3 - Proj_vname(v) vname(e)_3 \ &= vname(e)_3 - (vname(e)_3 dot vname(v)) / (vname(v) dot vname(v)) vname(v) \ &= vec(0, 0, 1) - 5 / 30 vec(2, -1, 5) \ &= vec(0, 0, 1) - 1 / 6 vec(2, -1, 5) \ &= vec( - 1 / 3, 1 / 6, 1 / 6 ) = 1 / 6 vec( - 2, 1, 1 ) $ Safety check that they are orthogonal to $v$: $ vname(v)'_1 dot vname(v) = 1 / 15 (13 dot 2 + 1 dot -1 - 5 dot 5) = 1 / 15 (0) = 0 \ vname(v)'_2 dot vname(v) = 1 / 30 (2 dot 2 + 29 dot -1 + 5 dot 5) = 1 / 30 (0) = 0 \ vname(v)'_3 dot vname(v) = 1 / 6 (- 2 dot 2 + 1 dot -1 + 1 dot 5) = 1 / 6 (0) = 0 \ $ == b === $vname(v)'_1$ and $vname(v)'_2$ $ alpha_1 vec(13, 1, -5) + alpha_2 vec(2, 29, 5) = vname(0) \ alpha_1 = -29 alpha_2 \ -5(-29 alpha_2) + 5 alpha_2 = 0 \ 5 alpha_2 = 5(-29 alpha_2) \ alpha_2 = -29 alpha_2 \ alpha_2 = 0 \ alpha_1 = 0 $ So $vname(v)'_1$ and $vname(v)'_2$ are linearly independent. === $vname(v)'_1$ and $vname(v)'_3$ $ alpha_1 vec(13, 1, -5) + alpha_2 vec(-2, 1, 1) = vname(0) \ alpha_1 = - alpha_2 \ -5(- alpha_2) + alpha_2 = 0 \ 6 alpha_2 = 0 \ alpha_2 = 0 \ alpha_1 = 0 $ So $vname(v)'_1$ and $vname(v)'_3$ are linearly independent. === $vname(v)'_2$ and $vname(v)'_3$ $ alpha_1 vec(2, 29, 5) + alpha_2 vec(-2, 1, 1) = vname(0) \ 5 alpha_1 + alpha_2 = 0 \ alpha_2 = -5 alpha_1 \ 2 alpha_1 -2 (-5 alpha_1) = 0 \ 12 alpha_1 = 0 \ alpha_1 = 0 \ alpha_2 = 0 $ So $vname(v)'_2$ and $vname(v)'_3$ are linearly independent. == c We will call the vectors generated by Gram-Schmidt $vname(w)_3$ and $vname(w)_1$, so the orthogonal basis is ${ vname(w)_3, vname(w)_1 }$. $vname(w)_3$ is just $vname(v)'_3$, so we compute $vname(w)_1$ as follows: First, let us compute $vname(v)'_3 dot vname(v)'_3$ and $vname(v)'_3 dot vname(v)'_1$, which will be useful later: $ vname(v)'_3 dot vname(v)'_3 &= (1 / 6 vec( - 2, 1, 1 )) dot (1 / 6 vec( - 2, 1, 1 )) \ &= 1 / 36 (4 + 1 + 1) \ &= 1 / 36 (6) \ &= 1 / 6 $ $ vname(v)'_3 dot vname(v)'_1 &= (1 / 6 vec( - 2, 1, 1 )) dot (1 / 15 vec( 13, 1, - 5 )) \ &= 1 / 90 (- 26 + 1 - 5) \ &= 1 / 90 (- 30) \ &= - 1 / 3 $ Then we can project $vname(v)'_1$ onto $vname(w)_3$ to get $vname(w)_1$: $ vname(w)_1 &= vname(v)'_1 - Proj_vname(w)_3 vname(v)'_1 \ &= vname(v)'_1 - Proj_(vname(v)'_3) vname(v)'_1 \ &= vname(v)'_1 - (vname(v)'_1 dot vname(v)'_3) / (vname(v)'_3 dot vname(v)'_3) vname(v)'_3 \ &= 1 / 15 vec(13, 1, -5) - (- 1 / 3) slash (1 / 6) (1 / 6 vec(- 2, 1, 1)) \ &= 1 / 15 vec(13, 1, -5) + 1 / 3 vec(- 2, 1, 1) \ &= 1 / 15 vec( 13 + 5(-2), 1 + 5(1), -5 + 5(1) ) = 1 / 15 vec( -3, 6, 0 ) = 1 / 5 vec( -1, 2, 0 ) $ We can verify that $vname(w)_1$ and $vname(w)_3$ are orthogonal: $ vname(w)_3 dot vname(w)_1 &= (1 / 6 vec(-2, 1, 1)) dot (1 / 5 vec(-1, 2, 0)) \ &= 1 / 30 (- 2 dot -1 + 1 dot 2 + 1 dot 0) \ &= 1 / 30 (-2 + 2) \ &= 0 $ So one orthogonal basis for $L^(perp)$ is ${ 1 / 6 vec(-2, 1, 1), 1 / 5 vec(-1, 2, 0) }$. = 19.7 #[ #let rows = ( (1, 5, 9, -7), (-1, 2, 5, -7), (3, 0, -3, 9), (2, 1, 0, 4), ) #let columns = transposeArray(rows) #let vs = columns.map(entries => math.vec(..entries.map(repr))) #let colVec = j => math.vec(..columns.at(j).map(repr)) $ vname(v)_1 &= #colVec(0), vname(v)_2 &= #colVec(1), vname(v)_3 &= #colVec(2), vname(v)_4 &= #colVec(3) $ == a #let proveLinearDependence = (coefficients) => { let terms = format => coefficients .enumerate() .map(((j, c)) => format(c, j)); $ &#terms((c, j) => $(#c) vname(v)_#j$).join($+$) \ = &#terms((c, j) => $(#c) #colVec(j)$).join($+$) \ = &#math.vec( ..rows .map(row => coefficients .zip(row) .map(((c, e)) => $(#c) (#e)$) .join($+$)) ) \ = &#math.vec( ..rows .map(row => coefficients .zip(row) .map(((a, b)) => a * b) .sum()) .map(repr) ) \ = &vname(0) $ } #proveLinearDependence((3, 2, -3, -2)) #v(0.5in) #proveLinearDependence((-5, 6, -2, 1)) #pagebreak() == b $ 3 vname(v)_1 + 2 vname(v)_2 - 3 vname(v)_3 - 2 vname(v)_4 &= vname(0) \ -5 vname(v)_1 + 6 vname(v)_2 - 2 vname(v)_3 + vname(v)_4 &= vname(0) \ -7 vname(v)_1 + 14 vname(v)_2 - 7 vname(v)_3 &= vname(0) \ 7 vname(v)_3 &= -7 vname(v)_1 + 14 vname(v)_2 \ vname(v)_3 &= -vname(v)_1 + 2 vname(v)_2 \ \ 3 vname(v)_1 + 2 vname(v)_2 - 3 vname(v)_3 - 2 vname(v)_4 &= vname(0) \ -5 vname(v)_1 + 6 vname(v)_2 - 2 vname(v)_3 + vname(v)_4 &= vname(0) \ 6 vname(v)_1 + 4 vname(v)_2 - 6 vname(v)_3 - 4 vname(v)_4 &= vname(0) \ 15 vname(v)_1 - 18 vname(v)_2 + 6 vname(v)_3 - 3 vname(v)_4 &= vname(0) \ 21 vname(v)_1 - 14 vname(v)_2 - 7 vname(v)_4 &= vname(0) \ 7 vname(v)_4 &= 21 vname(v)_1 - 14 vname(v)_2 \ vname(v)_4 &= 3 vname(v)_1 - 2 vname(v)_2 \ $ == c $ -vname(v)_1 + 2 vname(v)_2 &= - #colVec(0) + 2 #colVec(1) \ &= vec( 9, 5, -3, 0 ) \ &= vname(v)_3 $ $ 3 vname(v)_1 - 2 vname(v)_2 &= 3 #colVec(0) - 2 #colVec(1) \ &= vec( -7, -7, 9, 4 ) \ &= vname(v)_4 $ ] = 19.8 == a $ &(a_1 - 3 t) vname(v)_1 + (a_2 + 7 t) vname(v)_2 + (a_3 - 5 t) vname(v)_3 + (a_4 + 2 t) vname(v)_4 \ = & a_1 vname(v)_1 + a_2 vname(v)_2 + a_3 vname(v)_3 + a_4 vname(v)_4 - 3 t vname(v)_1 + 7 t vname(v)_2 - 5 t vname(v)_3 + 2 t vname(v)_4 \ = & a_1 vname(v)_1 + a_2 vname(v)_2 + a_3 vname(v)_3 + a_4 vname(v)_4 + t (- 3 vname(v)_1 + 7 vname(v)_2 - 5 vname(v)_3 + 2 vname(v)_4) \ = & a_1 vname(v)_1 + a_2 vname(v)_2 + a_3 vname(v)_3 + a_4 vname(v)_4 + t vname(0) \ = & a_1 vname(v)_1 + a_2 vname(v)_2 + a_3 vname(v)_3 + a_4 vname(v)_4 $ == b Let $(a_1, a_2, a_3, a_4) = (-2, 4, 3, -5)$. Then, we choose a nonzero value for $t$: $ & -2 vname(v)_1 + 4 vname(v)_2 + 3 vname(v)_3 - 5 vname(v)_4 \ = & (-2 - 3 (1)) vname(v)_1 + (4 + 7 (1)) vname(v)_2 + (3 - 5 (1)) vname(v)_3 + (-5 + 2 (1)) vname(v)_4 \ = & -5 vname(v)_1 + 11 vname(v)_2 - 2 vname(v)_3 - 3 vname(v)_4 \ $ So $(b_1, b_2, b_3, b_4) = (-5, 11, -2, -3)$. Then, we choose another nonzero value for $t$: $ & -2 vname(v)_1 + 4 vname(v)_2 + 3 vname(v)_3 - 5 vname(v)_4 \ = & (-2 - 3 (-1)) vname(v)_1 + (4 + 7 (-1)) vname(v)_2 + (3 - 5 (-1)) vname(v)_3 + (-5 + 2 (-1)) vname(v)_4 \ = & 1 vname(v)_1 - 3 vname(v)_2 + 8 vname(v)_3 - 7 vname(v)_4 \ $ So $(b_1, b_2, b_3, b_4) = (1, -3, 8, -7)$. == c Suppose that there were such coefficients $a_i$ and $b_i$. Then, we have that $ a_1 vname(v)_1 + a_2 vname(v)_2 + a_3 vname(v)_3 + a_4 vname(v)_4 &= b_1 vname(v)_1 + b_2 vname(v)_2 + b_3 vname(v)_3 + b_4 vname(v)_4 \ (a_1 - b_1) vname(v)_1 + (a_2 - b_2) vname(v)_2 + (a_3 - b_3) vname(v)_3 + (a_4 - b_4) vname(v)_4 &= vname(0) \ $ But since $(a_1, a_2, a_3, a_4) != (b_1, b_2, b_3, b_4)$, at least one of $a_i - b_i$ is nonzero. Therefore, the vectors $vname(v)_1, vname(v)_2, vname(v)_3, vname(v)_4$ are linearly dependent. This is a contradiction, so the premise that there exist such coefficients $a_i$ and $b_i$ is false. = 20.3 == a $A$ is orthogonal because its columns are mutually orthogonal $ vec(1, -2) dot vec(2, 1) = 1 dot 2 - 2 dot 1 = 0 $ and all unit vectors: $ ||1 / sqrt(5) vec(1, -2)|| &= sqrt(1^2 + (-2)^2) / sqrt(5) = sqrt(5) / sqrt(5) &= 1 \ ||1 / sqrt(5) vec(2, 1)|| &= sqrt(2^2 + 1^2) / sqrt(5) = sqrt(5) / sqrt(5) &= 1 $. Therefore, its inverse is just its transpose: $ A^(-1) = A^T = 1 / sqrt(5) mat( 1, -2; 2, 1; ) $ == b $B$ is not orthogonal because its first column has length $sqrt(1^2 + 1^2 + 1^2 + 1^2) = sqrt(4) = 2 != 1$. == c The columns of $B'$ must be unit vectors, so $B'$ is orthogonal iff its columns are mutually orthogonal. By examining all 6 unordered pairs of columns, we can see that the columns of $B'$ are mutually orthogonal. Therefore, $B'$'s inverse is given by its transpose: $ B'^(-1) = B'^T = 1 / 2 mat( 1, 1, 1, 1; -1, -1, 1, 1; -1, 1, -1, 1; 1, -1, -1, 1; ) $ == d $ B &= 2 B' \ B^(-1) &= (2 B')^(-1) \ &= 1 / 2 B'^(-1) \ &= 1 / 2 (1 / 2 mat( 1, 1, 1, 1; -1, -1, 1, 1; -1, 1, -1, 1; 1, -1, -1, 1; )) \ &= 1 / 4 mat( 1, 1, 1, 1; -1, -1, 1, 1; -1, 1, -1, 1; 1, -1, -1, 1; ) $ = 20.5 == a The $i j$-th entry of $1 / 2 (A + A^T)$ is given by $ (1 / 2 (A + A^T))_(i j) &= 1 / 2 (A_(i j) + (A^T)_(i j)) \ &= 1 / 2 (A_(i j) + A_(j i)) \ &= 1 / 2 (A_(j i) + (A^T)_(j i)) \ &= (1 / 2 (A + A^T))_(j i) $ Which is the definition of matrix symmetry. == b $ q(vname(x)) &= ||B vname(x)||^2 \ &= (B vname(x)) dot (B vname(x)) \ &= (B vname(x))^T (B vname(x)) \ &= vname(x)^T B^T B vname(x) \ &= vname(x)^T (B^T B) vname(x) \ M &= B^T B $ = 20.8 == a $S_+$ meets the $x y$-plane at the circle $x^2 + y^2 = 1$, the $x z$-plane at the hyperbola $x^2 - z^2 = 1$, and the $y z$-plane at the hyperbola $y^2 - z^2 = 1$. #columns(3)[ #figure( image("../images/ex20_8_a_xy.png"), caption: [ The intersection of $S_+$ and the $x y$-plane, with $x$ as the horizontal axis and $y$ as the vertical axis. ] ) #colbreak() #figure( image("../images/ex20_8_a_xz.png"), caption: [ The intersection of $S_+$ and the $x z$-plane, with $x$ as the horizontal axis and $z$ as the vertical axis. ] ) #colbreak() #figure( image("../images/ex20_8_a_yz.png"), caption: [ The intersection of $S_+$ and the $y z$-plane, with $y$ as the vertical axis and $z$ as the horizontal axis. ] ) ] == b For any given $a in RR$, $S_+$ intersects the plane $z = a$ at the circle $x^2 + y^2 = 1 + a^2$. Circles on $z = a$ are carried to themselves by rotation about the $z$-axis, and every "slice" of $S_+$ has this property, so $S_+$, the union of those slices, is also carried to itself by any rotation around the $z$-axis. == c Because $S_+$ has rotational symmetry around the $z$-axis, it is given by the revolution about the $z$-axis of its own intersection with any plane containing the $z$-axis. Furthermore, only one half of the plane is required, since the other half is given by a $180degree$ rotation. One half-plane containing the $z$-axis is $ { (x, y) in RR^2 | y = 0 and x >= 0 } $ This is also the positive-$x$ half of the $x z$-plane pictured in Part a. Its equational form is $ y = 0 and x >= 0 and x^2 - y^2 = 1 $ Which is one half of a hyperbola, so $S_+$ is one half of a hyperbola revolved around the $z$-axis. #figure( image("../images/ex20_8_c.jpeg", width: 40%), caption: [A sketch of $S_+$] ) == d $S_-$ intersects each horizontal plane $z = a$ at the circle $x^2 + y^2 = 1 + a^2$. Exactly as with $S_+$, the fact that intersections of $S_-$ with planes parallel to the $x y$-plane are circles implies that $S_-$ has total rotational symmetry around the $z$-axis. == e As with $S_+$, $S_-$ is given by the revolution about the $z$-axis of its own intersection with the $x z$-plane. That intersection is defined by the curve $ y = 0 and x^2 - z^2 = -1 $ which is a hyperbola. #figure( image("../images/ex20_8_e.jpeg", width: 40%), caption: [A sketch of $S_-$] ) Unlike $S_+$, this set consists of two disconnected components. This is because the curve from which it is generated, $x^2 - z^2 = -1$, has two components on any line parallel to the $z$-axis, one with $x$ positive and one with $x$ negative. Even after revolving around the $z$-axis, these two components must remain disconnected. = 20.12 == a $vname(v) vname(v)^T$ is symmetric because the product of any matrix and its transpose is symmetric. $- 2 / ||vname(v)||^2 vname(v) vname(v)^T$ because the scalar multiple of any symmetric matrix is symmetric. $H_v = I_n - 2 / ||vname(v)||^2 vname(v) vname(v)^T$ is symmetric because the sum of any two symmetric matrices is symmetric. == b $ H_vname(v)^T H_vname(v) &= (I_n - 2 / ||vname(v)||^2 vname(v) vname(v)^T)^T (I_n - 2 / ||vname(v)||^2 vname(v) vname(v)^T) \ &= (I_n - 2 / ||vname(v)||^2 vname(v) vname(v)^T)^2 \ &= I_n I_n + 2 I_n (-2 / ||vname(v)||^2 vname(v) vname(v)^T) + (-2 / ||vname(v)||^2 vname(v) vname(v)^T)^2 \ &= I_n - 4 / ||vname(v)||^2 vname(v) vname(v)^T + 4 / ||vname(v)||^4 vname(v) vname(v)^T vname(v) vname(v)^T \ &= I_n - 4 / ||vname(v)||^2 vname(v) vname(v)^T + 4 / ||vname(v)||^4 vname(v) (vname(v)^T vname(v)) vname(v)^T \ &= I_n - 4 / ||vname(v)||^2 vname(v) vname(v)^T + 4 / ||vname(v)||^2 vname(v) vname(v)^T \ &= I_n $ == c $ H_vname(v) (c vname(v)) &= c H_vname(v) vname(v) \ &= c (I_n - 2 / ||vname(v)||^2 vname(v) vname(v)^T) vname(v) \ &= c (I_n vname(v) - 2 / ||vname(v)||^2 vname(v) vname(v)^T vname(v)) \ &= c (vname(v) - 2 / ||vname(v)||^2 vname(v) ||vname(v)||^2) \ &= c (vname(v) - 2 vname(v)) \ &= c (- vname(v)) \ &= - c vname(v) $ == d If $vname(v) dot vname(u) = 0$: $ H_vname(v) vname(u) &= (I_n - 2 / ||vname(v)||^2 vname(v) vname(v)^T) vname(u) \ &= I_n vname(u) - 2 / ||vname(v)||^2 vname(v) vname(v)^T vname(u) \ &= vname(u) - 2 / ||vname(v)||^2 vname(v) (vname(v) dot vname(u)) \ &= vname(u) - 2 / ||vname(v)||^2 vname(v) (0) \ &= vname(u) $ == e $ H &= H_vec(2, -1, 2) \ &= I_n - 2 / (2^2 + (-1)^2 + 2^2) vec(2, -1, 2) vec(2, -1, 2)^T \ &= I_n - 2 / 9 mat( 4, -2, 4; -2, 1, -2; 4, -2, 4; ) \ &= 1 / 9 mat( 9, 0, 0; 0, 9, 0; 0, 0, 9; ) + 1 / 9 mat( -8, 4, -8; 4, -2, 4; -8, 4, -8; ) \ &= 1 / 9 mat( 1, 4, -8; 4, 7, 4; -8, 4, 1; ) $ = 21.2 == a The value of $d$ is simply the number of columns of the matrix. $ N(A) &subset.eq RR^2 \ N(B) &subset.eq RR^4 \ N(C) &subset.eq RR^2 $ == b $N(A)$ is the solution set of the system: $ x_1 - 2 x_2 &= 0 \ 2 x_1 - 4 x_2 &= 0 $ $N(b)$ is the solution set of the system: $ &x_1 - 3 &x_2 + & &x_4 = &0 \ 2 &x_1 + 5 &x_2 - &x_3 & = &0 \ 3 &x_1 + 2 &x_2 - &x_3 + &x_4 = &0 $ $N(C)$ is the solution set of the system: $ 3 x_1 + 2 x_2 &= 0 \ -4 x_1 - x_2 &= 0 $ == c The second row of $A$ is just twice the first row, so any solution to $x_1 - 2x_2 = 0$ is an element of $N(A)$: $ N(A) = span{vec(2, 1)} $ The third row of $B$ is the sum of the first two rows, so it can be ignored. Then, solving for $x_3$ and $x_4$ in terms of $x_1$ and $x_2$: $ x_3 &= 2 x_1 + 5 x_2 \ x_4 &= - x_1 + 3 x_2 \ N(B) &= span{vec(1, 0, 2, -1), vec(0, 1, 5, 3)} $ We can solve the system for $C$ by adding the second row to the first row: $ -x_1 + 0 x_2 &= 0 \ x_1 &= 0 \ -4 (0) - 1 x_2 &= 0 \ x_2 &= 0 \ N(C) &= {vname(0)} $ = 21.4 == a $C(A')$ is spanned by the set of columns of $A'$, which is the set of columns of $A$, plus $vname(v)$. Therefore, $C(A')$ is spanned by $span{"columns of" A} = C(A)$ and $vname(v)$. Adding the column $vname(v)$ will either increase the dimension of $C(A)$ by 1 if $vname(v) in.not C(A)$, or leave it unchanged if $vname(v) in C(A)$. This is because if $vname(v)$ is not a linear combination of the columns of $A$, a new vector must be added to any basis for $C(A)$ to span all of $C(A')$. However, if $vname(v)$ is already a linear combination of the columns of $A$, it has no effect on the column space. == b If $vname(v) in C(A)$, then there must be some $vname(u) in RR^n$ such that $A vname(u) = vname(v)$. Now, given any $vname(y) in C(A')$, there must be some $vname(x) in RR^(n+1)$ such that $A' vname(x) = vname(y)$. Then $vname(y)$ is also in $C(A)$ because $ vname(y) &= A' vname(x) \ &= A vec(x_1, x_2, ..., x_n) + x_(n+1) vname(v) \ &= A vec(x_1, x_2, ..., x_n) + A (x_(n+1) vname(u)) \ &= A (vec(x_1, x_2, ..., x_n) + x_(n+1) vname(u)) \ \ vname(y) &in C(A) \ C'(A) &= C(A) $ Now if we are given that $C'(A) = C(A)$, then because $vname(v) = A' vname(e)_(n+1) in C'(A)$, we must have that $vname(v) in C(A)$. == c $ vname(v) in C(A) &implies exists vname(u) in RR^n : A vname(u) = vname(v) \ &implies A' vec(vname(u), -1) &= mat(A, vname(v)) vec(vname(u), -1) \ & &= A vname(u) - vname(v) \ & &= vname(v) - vname(v) \ & &= vname(0) $ So $vec(vname(u), -1) in N(A)$ and $N(A) supset.eq span{vec(vname(u), -1)} supset {vname(0)}$, so $N(A) != {vname(0)}$. = 21.7 == a $ vname(a)'_2 &= vname(a)_2 - Proj_(vname(a)_1) vname(a)_2 \ &= vname(a)_2 - (vname(a)_2 dot vname(a)_1) / (vname(a)_1 dot vname(a)_1) vname(a)_1 \ &= vec(2, 13, -3) - 44 / 11 vec(1, 3, -1) \ &= vec( 2 - 4(1), 13 - 4(3), -3 - 4(-1) ) \ &= vec(-2, 1, 1) $ $ C(A) = span{vname(a)_1, vname(a)'_2} = span{vec(1, 3, -1), vec(-2, 1, 1)} $ The given linear combinations imply that $ vec(-3, 2, -1, 0), vec(1, -1, 0, 1) in N(0) $ because their first two entries are the coefficients of $vname(a)_1$ and $vname(a)'_2$ (so they alone are taken to $vname(a)_3$ or $vname(a)_4$ by multiplication with $A$), and their last two entries are $-1$ and $0$, (which are taken to $-vname(a)_3$ or $-vname(a)_4$ by multiplication with $A$). == b === $vname(b)_1$ $ Proj_(C(A)) (vname(b)_1) &= Proj_(vname(a)_1) (vname(b)_1) + Proj_(vname(a)'_2) (vname(b)_1) \ &= (vname(b)_1 dot vname(a)_1) / (vname(a)_1 dot vname(a)_1) vname(a)_1 + (vname(b)_1 dot vname(a)'_2) / (vname(a)'_2 dot vname(a)'_2) vname(a)'_2 \ &= (1 + 18 - 8) / (1 + 9 + 1) vec(1, 3, -1) + (-2 + 6 + 8) / (4 + 1 + 1) vec(-2, 1, 1) \ &= 11 / 11 vec(1, 3, -1) + 12 / 6 vec(-2, 1, 1) \ &= vec(1, 3, -1) + 2 vec(-2, 1, 1) \ &= vec(-3, 5, 1) != b ", so" not exists vname(x) in RR^4 : A vname(x) = vname(b)_1 $ === $vname(b)_2$ $ Proj_(C(A)) (vname(b)_2) &= Proj_(vname(a)_1) (vname(b)_2) + Proj_(vname(a)'_2) (vname(b)_2) \ &= (vname(b)_2 dot vname(a)_1) / (vname(a)_1 dot vname(a)_1) vname(a)_1 + (vname(b)_2 dot vname(a)'_2) / (vname(a)'_2 dot vname(a)'_2) vname(a)'_2 \ &= (- 5 - 3 - 3) / (1 + 9 + 1) vec(1, 3, -1) + (10 - 1 + 3) / (4 + 1 + 1) vec(-2, 1, 1) \ &= - 11 / 11 vec(1, 3, -1) + 12 / 6 vec(-2, 1, 1) \ &= - vec(1, 3, -1) + 2 vec(-2, 1, 1) \ &= vec(-5, -1, 3) = vname(b)_3 ", so" exists vname(x) in RR^4 : A vname(x) = vname(b)_2 \ \ b_2 &= - vname(a)_1 + 2 vname(a)'_2 \ &= - vname(a)_1 + 2 (vname(a)_2 - 4 vname(a)_1) \ &= - vname(a)_1 + 2 vname(a)_2 - 8 vname(a)_1 \ &= - 9 vname(a)_1 + 2 vname(a)_2 \ \ A vec(-9, 2, 0, 0) &= vec( -9(1) + 2(2), -9(3) + 2(13), -9(-1) + 2(-3), ) \ &= vec(-5, -1, 3) \ &= vname(b)_2 $ #pagebreak() === $vname(b)_3$ $ Proj_(C(A)) (vname(b)_3) &= Proj_(vname(a)_1) (vname(b)_3) + Proj_(vname(a)'_2) (vname(b)_3) \ &= (vname(b)_3 dot vname(a)_1) / (vname(a)_1 dot vname(a)_1) vname(a)_1 + (vname(b)_3 dot vname(a)'_2) / (vname(a)'_2 dot vname(a)'_2) vname(a)'_2 \ &= (1 - 12 + 0) / (1 + 9 + 1) vec(1, 3, -1) + (- 2 - 4 + 0) / (4 + 1 + 1) vec(-2, 1, 1) \ &= - 11 / 11 vec(1, 3, -1) - 6 / 6 vec(-2, 1, 1) \ &= - vec(1, 3, -1) - vec(-2, 1, 1) \ &= vec(1, -4, 0) = vname(b)_3 ", so" exists vname(x) in RR^4 : A vname(x) = vname(b)_3 \ \ b_3 &= - vname(a)_1 - vname(a)'_2 \ &= - vname(a)_1 - (vname(a)_2 - 4 vname(a)_1) \ &= - vname(a)_1 - vname(a)_2 + 4 vname(a)_1 \ &= 3 vname(a)_1 - vname(a)_2 \ \ A vec(3, -1, 0, 0) &= vec( 3(1) - 1(2), 3(3) - 1(13), 3(-1) - 1(-3), ) \ &= vec(1, -4, 0) \ &= vname(b)_3 $ == c The parametric form of the solutions to $A vname(x) = vname(y)$ take the form of a particular solution, plus a parameterization of $N(A)$, which is given in Part a. For $A vname(x) = vname(b)_2$: $ vname(x) = vec(-9, 2, 0, 0) + t vec(-3, 2, -1, 0) + t' vec(1, -1, 0, -1) $. And for $A vname(x) = vname(b)_3$: $ vname(x) = vec(3, -1, 0, 0) + t vec(-3, 2, -1, 0) + t' vec(1, -1, 0, -1) $ = 21.9 == a $C(A)$ cannot be a point, because at least one of the columns of $A$, either $A vname(e)_1$ or $A vname(e)_2$, is nonzero. This column is therefore an element of a basis for $C(A)$, so $C(A)$ has dimension at least one and cannot be ${vname(0)}$. Then $C(A)$ must have either dimension one, in which case it is the spanning set of $A$'s nonzero column, which is a line, or dimension two, in which case it is equal to $RR^2$. Similarly, $N(A)$ cannot be all of $RR^2$, because one of $A vname(e)_1$ and $A vname(e)_2$ is nonzero, so it must be of dimension zero, in which case it is ${vname(0)}$, or dimension one, in which case it is a line. == b By definition, $C(A) = span{ A vname(e)_1, A vname(e)_2 }$. If $A vname(e)_1$ and $A vname(e)_2$ are linearly independent, the set containing them is a basis and $dim C(A) = 2$, so $C(A)$ is all of $RR^2$, not a line. However, if they are _not_ linearly independent, then the set containing either one of them (provided it is nonzero), is a basis of $C(A)$, and $C(A)$ is therefore the line spanned by that column. If the columns of $A$ are linearly dependent, then there exist some nonzero $alpha_1, alpha_2 in RR$ such that $ alpha_1 A vname(e)_1 + alpha_2 A vname(e)_2 &= vname(0) \ A vec(alpha_1, alpha_2) &= vname(0) \ vec(alpha_1, alpha_2) &in N(A) $ So $N(A)$ has dimension at least one, but it cannot have dimension two because either $A vname(e)_1 != 0$ or $A vname(e)_2 != 0$. Therefore, $N(A)$ is the line spanned by $vec(alpha_1, alpha_2)$. Buf if the columns of $A$ are linearly independent, then the only $alpha_1, alpha_2 in RR$ such that $alpha_1 A vname(e)_1 + alpha_2 A vname(e)_2 = vname(0)$ are $alpha_1 = alpha_2 = 0$. Since $alpha_1 A vname(e)_1 + alpha_2 A vname(e)_2 = A vec(alpha_1, alpha_2)$, this means the only vector $vname(x)$ such that $A vname(x) = vname(0)$ is the zero vector, $vname(0)$. Therefore, $N(A) = {vname(0)}$, which is not a line. == c From the previous Parts, we have that $C(A) = RR^2$ iff the columns of $A$ are linearly independent, and from Part b that if the columns of $A$ are linearly independent, $N(A) = {vname(0)}$. Therefore, $ C(A) = RR^2 implies N(A) = {vname(0)} $ And we have from Part b that $N(A) = {vname(0)}$ iff the columns of $A$ are linearly independent, and as previously that $C(A) = RR^2$ if the columns of $A$ are linearly independent. So it follows that $ N(A) = {vname(0)} implies C(A) = RR^2 $
https://github.com/BoostCookie/systemd-tshirtd
https://raw.githubusercontent.com/BoostCookie/systemd-tshirtd/main/src/tshirtd.newlogo.transparent.typ
typst
#set page(fill: rgb(0%, 0%, 0%, 0%)) #include "common.newlogo.typ"
https://github.com/lucifer1004/leetcode.typ
https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/solutions/s0009.typ
typst
#import "../helpers.typ": * #let palindrome-number-ref(x) = { if x < 0 { return false } if x == 0 { return true } if calc.rem(x, 10) == 0 { return false } let rev = 0 while x > rev { if rev > 214748364 or (rev == 214748364 and calc.rem(x, 10) > 7) { return false } rev = rev * 10 + calc.rem(x, 10) x = calc.floor(x / 10) } x == rev or x == calc.floor(rev / 10) }
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/软件分析/hw/2100012990-郭子荀-软分第四次作业.typ
typst
#import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark #import "../../template.typ": * #show: note.with( title: "作业4", author: "YHTQ", date: datetime.today().display(), logo: none, withOutlined : false, withTitle : false, withHeadingNumbering: false ) #let Node = $"NodeValue"$ = 分析方向 反向,向控制流图的前驱进行 = 抽象域 - 抽象值集合为程序中表达式集合的全体 - $gamma(S)$ 表示从当前位置开始,繁忙表达式恰为 $S$ 的所有实际(有限)执行序列 - 初始值:表达式全集(exit 节点的初始值为空集) = 转换函数 $ f_v (S) = (S - "exp_with_value_change"_v) union "exp_calculated"_v $ 其中: - $"exp_with_value_change"_v$ 指所有与该语句中值被改变的变量相关的表达式 - $"exp_calculated"_v$ 指所有在该语句中被计算(读取)的表达式 = 合并操作 所有后继节点的值取交,也即 $Node(v) := f_v (sect.big_(v' in "succ"(v)) Node(v'))$(方便起见,暂时认为零个集合的交是空集) = 正确性 #lemmaLinear[][给定从某个节点 $v$ 开始的终止执行,则算法稳定后 $Node(v)$ 中的所有表达式都是该执行的繁忙表达式,即该表达式在其中变量被赋值前一定在执行中被读取。] #proof[ 设 $e in Node(v)$,由于算法的稳定,将有: $ Node(v) = (sect.big_(v' in "succ"(v)) Node(v') - "exp_with_value_change"_v) union "exp_calculated"_v $ 讨论: - 若 $e in "exp_calculated"_v$,则 $e$ 在节点 $v$ 被读取,当然是繁忙表达式。 - 否则,若 $e in sect.big_(v' in "succ"(v)) Node(v') - "exp_with_value_change"_v$,此时 $v$ 一定不是 exit 节点,假设该具体执行中下一个节点为 $v'$,由前式显然有: $ e in Node(v') - "exp_with_value_change"_v $ 递归证明 $e$ 是 $v'$ 节点开始的繁忙表达式,则上式同时表明 $e$ 的值没有在节点 $v$ 被修改,当然有 $e$ 是 $v$ 节点开始的繁忙表达式。 由于该执行序列在有限步终止(执行到 exit 节点),上面的递归证明可以终止。 ]
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/casoslov/styleCasoslov.typ
typst
#import "/style.typ": * #import "../texts.typ": * #import "../textsTmp.typ": * #let si = [ #lettrine("Sláva:") #lettrine("I teraz:") ] #let ektenia(num) = [ ==== Ekténia <X> #lettrine("Pane, zmiluj sa.") #primText[(#(num)x)] #si ] #let zoznam(verse, slava: false) = [ #let c = counter("verse") #c.update(1) #let tbl = { verse.map(k => ( primText[#c.display("i:"); #c.step()] ,[#k] ) ) } #if slava [#tbl.push((primText[S:I:], si))] #table( columns: (15pt, auto), stroke: none, align: (x, y) => (right, left).at(x), ..tbl.flatten() ) ] #let verse(verse, start: 10) = [ #let c = counter("verse") #c.update(start) #let tbl = { verse.map(k => ( primText[#c.display("1:"); #c.update(c => c - 1)] ,[#k] ) ) } #tbl.push((primText[S:I:], si)) #table( columns: (15pt, auto), stroke: none, align: (x, y) => (right, left).at(x), ..tbl.flatten() ) ] #let prokimenyVecierne = [ === Pondelok - Nedeľa večer,\ 8. hlas <X> #lettrine("Hľa, teraz oslavujte Pána, všetci služobníci Pánovi.") #vers[Ktorí ste v dome Pánovom a na nádvoriach domu nášho Boha.] === Utorok - Pondelok večer,\ 4. hlas <X> #lettrine("Pán ma vyslyší, * keď budem volať k nemu.") #vers[Bože, spravodlivosť moja, vypočuj ma, keď volám o pomoc.] === Streda - Utorok večer,\ 1. hlas <X> #lettrine("Tvoja milosť, Pane, bude ma sprevádzať * po všetky dni môjho života.") #vers[Pán je môj pastier, nič mi nechýba. Pasie ma na zelených pasienkach.] === Štvrtok - Streda večer,\ 5. hlas <X> #lettrine("Bože, spas ma svojím menom * a vo svojej moci súď ma.") #vers[Bože, vypočuj moju modlitbu a vypočuj slová mojich úst.] === Piatok - Štvrtok večer,\ 6. hlas <X> #lettrine("Pomoc mi príde od Pána, * ktorý stvoril nebo i zem.") #vers[Svoj zrak upieram na vrchy. Príde mi odtiaľ pomoc?] === Sobota - Piatok večer,\ 7. hlas <X> #lettrine("Bože, ty si môj ochranca, * a tvoja milosť ma sprevádza.") #vers[Vytrhni ma, Bože, z moci mojich nepriateľov, chráň ma pred tými, čo povstávajú proti mne.] ] #let slohy(slohy) = [ #let c = counter("verse") #c.update(1) #let tbl = { slohy.map(k => ( [],primText[\[#c.display("1.") sloha\]], primText[#c.display("i:"); #c.step()] ,[#k] ) ) } #tbl.push(( [],primText[\[#c.display("1.") sloha\]], primText[S:I:], si, [],primText("[Bohorodičník]") )) #table( columns: (15pt, auto), stroke: none, align: (x, y) => (right, left).at(x), ..tbl.flatten() ) ] #let verseSoZvolanim(zvolanie, verse, prve: true, add_note: true, slava: "", iteraz: "", slava_iteraz: "") = { if prve { lettrine(zvolanie) if add_note { note[Opakuje sa po každom verši] } } let c = counter("bjp") c.update(1) let tbl = { verse.map(k => ( primText[#c.display("i:"); #c.step()] ,[#k] ) ) } if not prve { tbl.insert(1, []) tbl.insert(2, pad(left:-20pt)[#zvolanie]) tbl.insert(3, []) tbl.insert(4, pad(left:-20pt)[#note[Opakuje sa po každom verši]]) } if slava_iteraz != "" { tbl.push(secText([$#sym.SS #sym.II$:])) tbl.push(slava_iteraz) } if slava != "" { tbl.push(secText([$#sym.SS$:])) tbl.push(slava) } if iteraz != "" { tbl.push(secText([$sym.II$:])) tbl.push(iteraz) } table( columns: (15pt, auto), stroke: none, align: (x, y) => (right, left).at(x), ..tbl.flatten() ) } #let postne_svitileny = [ ] #let svitileny = [ === Pondelok <X> #lettrine("Archanjeli a anjeli, kniežatstvá a panstvá, * sily a tróny, aj mnohookí cherubíni a serafíni, * prihovárajte sa za nás, * aby sme boli zachránení pred večným zatratením.") #note[alebo] #lettrine("Ako Boh si ozdobil nebo hviezdami PAne, * celý svet si ožiaril svojimi anjelmi. * Stvoriteľ vesmíru, zachráň tých, ktorí ťa oslavujú.") #si #lettrine("Najčistejšia, ty si moja zástankyňa, * istá ochrana, aj záchrana celého sveta.* K tebe prichádzam a volám: * \"Zachráň ma pred nerozumnými skutkami, * aby som nebol odsúdený na večné zatratenie. * Pann, pomôž mi, lebo do teba vkladám svoju nádej.\"") === Utorok <X> #lettrine("Slávny prorok a predchodca milosti, <NAME>, * všetkým si hlásal spasiteľné pokánie. * Poukázal si na Baránka, ktorý sníma hriechy sveta. * Aj teraz sa u neho prihováraj za nás, - aby sa nad nami zmiloval.") #note[alebo] #lettrine("Všetci oslavujeme <NAME>ľa, predchodcu Pánovho, * proroka medz prorokmi, * učiteľa v púšti, * Alžebetinho vytúženého syna.") #si #lettrine("<NAME>, hovorili o tebe všetci proroci. * Dávid ťa nazval svätou horou, * kadidlom aj svietnikom, - mostom i rukou, ktorá nosila večnú Mannu. * Bohorodička, my ťa chceme výdy dôstojne oslavovať.") === Streda <X> #lettrine("Ospevujeme svätý kríž, * nepremožiteľnú zbraň aj záruku viery. * Klaniame sa mu s dôverou, * lebo on je naša istota, chvála všetkých kresťanov, * ochrana pravoverných, sláva mučeníkov. * Vždy ho chceme dôstojne uctievať.") #note[alebo] #lettrine("Svätý kríž je mocnou ochranou celého sveta. * Kríž je ozdobou svätej Cirkvi. * Kríž je silou všetkých nadriadených. * Kríž je oporou veriacich. Svätý kríž je slávou anjelov * a premožiteľom zlého ducha.") #si #lettrine("<NAME>, ty si stála pod krížom * a videla si na ňom svojho Syna pribitého a bez dychu. * Ako jeho Matka si veĺmi trpela * a so slzami v očiach si volala: \"Aký je to veľký zázrak1 * Stvoriteľ sveta zomiera pribitý na drevo kríža.\"") === Štvrtok <X> #lettrine("Veriaci, dôstojne oslavujme Pánových učeníkov * Petra a Pavla, * Andreja, Jakuba, Bartolomeja, Mateja, * Jakuba, Filipa, Tomáša, Šimona, * Lukáša, Jána a Marka.") #note[alebo] #lettrine("Pánovi apoštoli, išli ste do celého sveta. * Všetkým ste hlásali Kristovo sväté narodenie z Panny. * Národy ste ochránili pred klamnými náukami * a všetkých ste naučili uctievať si Najsvätejšiu Trojicu.") #note[alebo] #lettrine("Svätí dvanásti apoštoli, * neprestajne sa prihovárajte za nás u Pána. * Proste spolu s dôstojným otcom Mikulášom, svätiteľom z Myry.") #si #lettrine("Nepoškvrnená Panna, spolu s múdrymi apoštolmi * i s množstvom mučeníkov a so svätým Mikulášom, * prihovárajte sa u Krista, * aby nás ochránil pred každým nedostatkom. * Svoju nádej sme vložili do teba, Bohorodička.") === Piatok <X> #lettrine("Raduj sa, svätý kríž! * Nepremožiteľná opora sveta, * útočisko trpiacich a ochrana všetkých, ktorí sú v úzskostiach. * Záštita pravoverných, víťaz nad klamným učením. * Ozdoba apoštolov a záchrana veriacich.") #note[alebo] #lettrine("Svätý kríž je mocnou ochranou celého sveta. * Kráž je ozdobou svätej Cirkvi. * Kríž je silou všetkých nadriadených. * Kráž je oporou veriacich. * Svätý kríž je slávou anjelov * a premožiteľom zlého ducha.") #si #lettrine("Keď ťa, Pane, Najčistejšia Bohorodička * uzrela pribitého na dreve kríža, * so slzami v očiach zvolala: * \"Akože by nebolo zašlo Slnko, pôvodca svetla? * Nechal si sa pribiť na kríž a svoj bok prebodnúť kopijou?! * Syn môj a Boh môj! * Toto všetko si urobil z lásky k ľuďom, len aby si ich zachránil.\"") === Sobota <X> #lettrine("Slávni proroci, blažení apoštoli, spravodliví patriarchovia * i zástupy vyznávačov a spravodlivých žien, * aj vy svätí mučeníci! * Všetci spolu s Bohorodičkou proste Pána, * aby sa zmiloval nad nami.") #note[alebo] #lettrine("Ako Boh si ozdobil nebo hviezdami, Pane, * a celý svet si ožiaril svojimi svätými. * Stvoriteľ vesmíru, zachráň tých, ktorí ťa oslavujú.") #si #lettrine("Bohorodička, šťastie apoštolov, potešenie zarmútených, * zástankyňa kresťanov, Panna a <NAME>, * zastaň sa nás a zachráň nás pred večným utrpením.") ] #let efrem = [ == Modlitba svätého Efréma Sýrskeho #lettrine("Pane a Vládca môjho života, odním odo mňa ducha znechutenosti, nedbalosti, mocibažnosti a prázdnych rečí.") #secText("(veľká poklona)") #lettrine("Daruj mne, svojmu služobníkovi, ducha miernosti, poníženosti, trpezlivosti a lásky.") #secText("(veľká poklona)") #lettrine("Áno, Pane a Kráľu, daj, aby som videl vlastné prehrešenia a neposudzoval svojho brata, lebo ty si požehnaný na veky vekov. Amen.") #secText("(veľká poklona)") #note("Potom nasleduje dvanásť malých poklôn, pričom pri každej poklone hovoríme:") #lettrine("Bože, buď milostivý mne hriešnemu.") #secText("(malá poklona)") #lettrine("Bože, očisť moje hriechy a zmiluj sa nado mnou.") #secText("(malá poklona)") #lettrine("Mnoho ráz som zhrešil, Pane, odpusť mi.") #secText("(malá poklona)") #note("A znovu celú modlitbu svätého Efréma s jednou veľkou poklonou na jej konci:") #lettrine("Pane a Vládca môjho života, odním odo mňa ducha znechutenosti, nedbalosti, mocibažnosti a prázdnych rečí. Daruj mne, svojmu služobníkovi, ducha miernosti, poníženosti, trpezlivosti a lásky. Áno, Pane a Kráľu, daj, aby som videl vlastné prehrešenia a neposudzoval svojho brata, lebo ty si požehnaný na veky vekov. Amen.") #secText("(veľká poklona)") ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cheq/0.1.0/lib.typ
typst
Apache License 2.0
#let unchecked-sym(fill: white, stroke: rgb("#616161"), radius: .1em) = move( dy: -.08em, box(stroke: .05em + stroke, fill: fill, height: .8em, width: .8em, radius: radius), ) #let checked-sym(fill: white, stroke: rgb("#616161"), radius: .1em) = move( dy: -.08em, box( stroke: .05em + stroke, fill: stroke, height: .8em, width: .8em, radius: radius, { box(move(dy: .48em, dx: 0.1em, rotate(45deg, line(length: 0.3em, stroke: fill + .1em)))) box(move(dy: .38em, dx: -0.05em, rotate(-45deg, line(length: 0.48em, stroke: fill + .1em)))) }, ), ) #let checklist( fill: white, stroke: rgb("#616161"), radius: .1em, default: ([•], [‣], [–]), unchecked: auto, checked: auto, body, ) = { let _typst-sequence = ([A] + [ ] + [B]).func() if unchecked == auto { unchecked = unchecked-sym(fill: fill, stroke: stroke, radius: radius) } if checked == auto { checked = checked-sym(fill: fill, stroke: stroke, radius: radius) } show list.item: it => { if type(it.body) == content and it.body.func() == _typst-sequence { let children = it.body.children if children.len() >= 5 and children.slice(0, 4).sum() == [[ ] ] { set list(marker: unchecked) list.item({ // use default marker for sublist set list(marker: default) children.slice(4).sum() }) } else if children.len() >= 5 and children.slice(0, 4).sum() == [[x] ] { set list(marker: checked) list.item({ // use default marker for sublist set list(marker: default) children.slice(4).sum() }) } else { it } } else { it } } body }
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/README.md
markdown
The Unlicense
<div align="center"> ![alt text](./logo.png) </div> <div align="center"> ![GitHub Repo stars](https://img.shields.io/github/stars/battlech1cken/notebookinator?style=for-the-badge) ![GitHub contributors](https://img.shields.io/github/contributors/battlech1cken/notebookinator?style=for-the-badge) ![GitHub License](https://img.shields.io/github/license/battlech1cken/notebookinator?style=for-the-badge) ![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/battlech1cken/notebookinator/ci.yml?style=for-the-badge&label=CI) ![Discord](https://img.shields.io/discord/1183511612322222183?style=for-the-badge&logo=discord&label=Discord) </div> This is the Notebookinator, a [Typst](https://github.com/typst/typst) template designed for the Vex Robotics Competition. This template aims to make it as easy as possible to get you up and running with a clean and organized notebooking environment, with minimal overhead. It provides multiple themes, and can even be extended with your own. To get started, read the [documentation](https://the-notebookinator.github.io/notebookinator/). If you have questions, or just want to hang out, feel free to join our [Discord server](https://discord.gg/sUpcVPtBDg). ## Gallery ### Radial Theme <table> <tr> <td> <a href="./gallery/radial.typ"> <img src="./gallery/radial-4.png" width="350px"> </a> </td> <td> <a href="./gallery/radial.typ"> <img src="./gallery/radial-5.png" width="350px"> </a> </td> <td> <a href="./gallery/radial.typ"> <img src="./gallery/radial-6.png" width="350px"> </a> </td> </tr> </table> ## Linear Theme <table> <tr> <td> <a href="./gallery/linear.typ"> <img src="./gallery/linear-03.png" width="350px"> </a> </td> <td> <a href="./gallery/linear.typ"> <img src="./gallery/linear-04.png" width="350px"> </a> </td> <td> <a href="./gallery/linear.typ"> <img src="./gallery/linear-05.png" width="350px"> </a> </td> </tr> </table> ## Special Thanks - Maqmoon (logo drawing) - CeTZ (inspiration for a lot of different things)
https://github.com/sabitov-kirill/comp-arch-conspect
https://raw.githubusercontent.com/sabitov-kirill/comp-arch-conspect/master/questions/7_cache.typ
typst
= Кэш-память. _Кэш-память (Как устроена? Почему кэш-промахи не случаются часто?, инклюзивность/эксклюзивность, политики замещения, виды ассоциативности, протоколы когерентности)._ В современном мире скорость доступа к памяти значительно медленее скорости работы процессора. Решением проблемы стал концепт кэш-памяти -- добавляем какое-то количество статической памяти рядом с процессором, в которой хранитья копия каких-то данных из оперативной памяти. Менеджмент этой памяти ложиться на ОС, программист не имеет интерфейса для прямого взаимодействия с ней (проверить закэшированны какие-то данные или нет). Доступ процессора к оперативной памяти происходит через кэш, а не напрямую через шину. В момент доступа происходит проверка на наличее необходимых данных в кэше, если данных нет в кэше то происходит _cache miss_. #import "/commons.typ": imagebox #grid(columns: (auto, 150pt), column-gutter: 30pt, [ кэш делиться на несколько уровней: + Самый маленький, порядка 32KiB, вребя обращения \~4 такта. Чаще всего разделяется на 2 части -- отдельно для данных и для инструкций. + Размер \~500KiB, время обращения \~20 тактов + Размер \~10MiB, время доступа \~40 тактов. Как правило кэш 1 и 2 уровней собственные для каждого вдра процессора, кэш 3 уровня общий для всех ядер. ], [ #imagebox("l3_cache.png", height: 90pt, label: [Иллюстрация организация доступа процессора к оперативной памяти.]) ]) == Чтение из кэш памяти #columns(2)[ === Look-aside При чтении оперативной памяти запрос одновременно отправляеться так же в кэш память, если данные есть в кэше, то быстро отвечаем на запрос, игнорируя данные из оперативной памяти. #imagebox("look_asight.png") *Плюсы:* - Быстрый доступ к незакэшированным данным -- не тратится время на проверку всего кэша (время сравнимо с временем доступа к оперативной памяти. *Минусы:* - Шина доступа к оперативной памяти забивается ненужными данными. - кэш и оперативная память подключены через одну шину (достаточно длинную, из-за чего она не может работать на слишком большой частоте). #colbreak() === Look-throught Сначала ищем данные только в кэше, если не нашли их, то только тогда отправляем запрос к оперативной памяти. #imagebox("look-thrught.png") *Плюсы:* - Шина не забита ненужными данными. - Есть возможность использования разных шин для обмена даннами между процессором и кэшем, кэшем и оперативной памятью (первая короткая, может работать на большей частоте). *Минусы:* - Время ответа на запрос получения данных может быть до двух раз больше. ] #pagebreak() == Запись в кэш память #columns(2)[ === Write-throught Одновременно отправляем два паралельных запроса на запись и в кэш, и в оперативную память. *Плюсы:* - Легко реализовать в железе. *Минусы:* - Постоянное перезаписывание данных при кэшировании, что забивает шину. #colbreak() === Write-back Сначала данные записываются в кэш, потом при необходимости в оперативную. Производительность данного подхода завсист от реализации конкретного контроллера, реализованного хардварно. *Плюсы:* - Нет лишних запросов к опреативной памяти. *Минусы:* - Сложнее реализовать, контроллер занимает какое-то место. ] == Способы размещения данных на уровнях кэша #columns(2)[ === Inclusive cache В кэше более высокого уровня _храниться копия данных_ из кэша более низкого уровня. При доступе данные ищутся в кэше от низкого до более выского уровней, при нахождении на уровне $n$, данные записываются на уровни $\[1, n\)$. При освобождении данные просто выкидываються из самого выского уровня, в более низких остаеться копия этих данных. #colbreak() === Exclusive cache Данные _храняться эксклюзивно_ на каждом уровне. При получении данных из уровня $n$, они переносяться на первый, чтение происходит всегда из кэша первого уровня. При необходимости освободить место на каком-то уровне, они переносяться на более низкий уровнь. ] == Политики замещения данных - *Random replacement* (ARM CPUs). При необъодимости перезаписать данные, перезаписываеться случайный фрагмент кэш-памяти. Очень просто в реализации, не требуеться сложных контроллеров, работает не слишком плохо. - *LRU, Least Recently Used*. Храним возраст для каждой строчки кэша (при взаимодействии со строкой ее возраст становиться самым маленьким), выкидываются самые "старые". - *TLRU, Time Aware LRU*. Помимо возраста храним время хранения, если оно больше какой-то константы, то данные выкидываются. - *LFU, Least Frequently Used*. Данные выкидываются на основе частоты использования. - *FIFO/LIFO*. Выкидываем на основе порядка добавления. - Всевозможные комбинации вышеприведенных полиитик. == Хранение данных кэшей Помимо данных в кэше необходимо хранить адресс их расположения в опреативной памяти. Адрессация по байтам невыгодна (влишком много места), адрессуются блоки по 64 байта с дополнительным смещением внутри одного блока. #imagebox("cache_addressing.png", height: 40pt, label: [Хранение блока данных в кэше, _tag_ - адресс блока в оперативной памяти.]) == Политики кэширования Способы проверить закэшированны какие-то данные. === Полная ассоциативность В любой линии кэш памяти может храниться любая линия оперативной памяти. В таком влучае если в кэш памяти $n$ линий, то проверка наличия линии опреативной памяти с заданным тегом за $O(n)$. === Прямая ассоциативность (прямое отображение) Предполагаеться, что 1 линия оперативной памяти может быть отображена только в одну линию кэш памяти. В таком случае оперативная память разбивается на блоки размера $C$, время проверки -- $O(1)$. _Возникает проблема._ Если активно используються какие-то конкретные линии из одного блока, то они будут часто перезаписывать друг-друга. В следствии этого второй способ может не дать существенного прироста, по сравнению с первым. === Групповая ассоциативность Синтез первых двух подходов. Вся память делиться на банки (группы), внутри которых реализуется полная ассоциативность. #columns(3)[ #imagebox("full_association.png", label: [Полная ассоциативность.]) #colbreak() #imagebox("single_association.png", label: [Прямая ассоциативность.]) #colbreak() #imagebox("group_assosiation.png", label: [Групповая ассоциативность.]) ] == Когерентность кэша При использовании многовдерных/многопроцессорных система может случиться несоглассованность кэша, в момент когда кэш 1-2 уровней одного из ядер изменился, но изменения не были перенесены в оперативную. === Протоколы когеренстности MSI Каждая кэш линия каждого кэша (т.е. свое состояние на каждое ядро) имеет одно из трех состояний: - *M (Modified)* --- линия была изменена, но изменение не было перенесено в оперативную память, во время этого состояния можно читать и писать данные. Гарантируется, что изменения будут перенесены в оперативную память, состояние из *M* измениться на *S*. Для конкретного тега оперативной памяти ровно в одном кэше может быть состояние *M*. - *S (Shared)* --- кэш линия не изменена и присутсвует еще в хотя бы одном кэше, данные можно свободно читать, для изменения требуется смена состояния на *M*. - *I (Invalid)* --- кэш линия не присутсвует в конкретном кэше или не валдина (данные не согласованы с другими кэшами). Для чтения необходимо получить данные из оперативной памяти. === Протокол когерентности MESI Новое состояние - *E (Exclusive)* --- данная данные с таким тегом есть только в одном кэше, можно свободно менять. Состояние активируется, в случае когда данные подгружаются из оперативной памяти (переход из *I*) и они не представлены ни в каком другом кэше. Если при подгрузке данные есть в кэш линии с состоянием *E*, то линии в обоих кэшах становяться *S*. === Протокол когеренстности MOESI Новое состояние - *O (Owned)* --- при изменении данные броадкастятся в другие кэши напрямую (в обход оперативной памяти), что бы линии с таким же тегом в состоянии *S* поменяли данные. === Протокол когерентности MESIF Новое состояние - *F (Forward)* --- линия с таким состоянием может отвечать на запросы о наличии данных с определенным тегом в кэше. Благодаря этому в других кэшах можно перейти из *I* в *S* без доступа к оперативной памяти. Состояние *F* переходит к последнему кэшу, который запрашивал данные с нужным тегом (предыдущий владелец меняет состояние на *S*).
https://github.com/Treeniks/bachelor-thesis-isabelle-vscode
https://raw.githubusercontent.com/Treeniks/bachelor-thesis-isabelle-vscode/master/utils/todo.typ
typst
#let TODO(color: yellow, body) = { rect( width: 100%, fill: color, body ) }
https://github.com/timetraveler314/Note
https://raw.githubusercontent.com/timetraveler314/Note/main/ICS/main.typ
typst
#import "@local/MetaNote:0.0.1" : * #let detm = math.mat.with(delim: "|") #show: doc => MetaNote( title: [ Introduction to Computer Systems ], authors: ( ( name: "timetraveler314", affiliation: "University of Genshin", email: "<EMAIL>", ), ), doc, )
https://github.com/metamuffin/typst
https://raw.githubusercontent.com/metamuffin/typst/main/docs/src/reference/scripting.md
markdown
Apache License 2.0
--- description: Automate your document with Typst's scripting capabilities. --- # Scripting Typst embeds a powerful scripting language. You can automate your documents and create more sophisticated styles with code. Below is an overview over the scripting concepts. ## Expressions { #expressions } In Typst, markup and code are fused into one. All but the most common elements are created with _functions._ To make this as convenient as possible, Typst provides compact syntax to embed a code expression into markup: An expression is introduced with a hashtag (`#`) and normal markup parsing resumes after the expression is finished. If a character would continue the expression but should be interpreted as text, the expression can forcibly be ended with a semicolon (`;`). ```example #emph[Hello] \ #emoji.face \ #"hello".len() ``` The example above shows a few of the available expressions, including [function calls]($type/function), [field accesses]($scripting/#fields), and [method calls]($scripting/#methods). More kinds of expressions are discussed in the remainder of this chapter. A few kinds of expressions are not compatible with the hashtag syntax (e.g. binary operator expressions). To embed these into markup, you can use parentheses, as in `[#(1 + 2)]`. ## Blocks { #blocks } To structure your code and embed markup into it, Typst provides two kinds of _blocks:_ - **Code block:** `{{ let x = 1; x + 2 }}` \ When writing code, you'll probably want to split up your computation into multiple statements, create some intermediate variables and so on. Code blocks let you write multiple expressions where one is expected. The individual expressions in a code block should be separated by line breaks or semicolons. The output values of the individual expressions in a code block are joined to determine the block's value. Expressions without useful output, like `{let}` bindings yield `{none}`, which can be joined with any value without effect. - **Content block:** `{[*Hey* there!]}` \ With content blocks, you can handle markup/content as a programmatic value, store it in variables and pass it to [functions]($type/function). Content blocks are delimited by square brackets and can contain arbitrary markup. A content block results in a value of type [content]($type/content). An arbitrary number of content blocks can be passed as trailing arguments to functions. That is, `{list([A], [B])}` is equivalent to `{list[A][B]}`. Content and code blocks can be nested arbitrarily. In the example below, `{[hello]}` is joined with the output of `{a + [ the ] + b}` yielding `{[hello from the *world*]}`. ```example #{ let a = [from] let b = [*world*] [hello ] a + [ the ] + b } ``` ## Bindings and Destructuring { #bindings } As already demonstrated above, variables can be defined with `{let}` bindings. The variable is assigned the value of the expression that follows the `=` sign. The assignment of a value is optional, if no value is assigned, the variable will be initialized as `{none}`. The `{let}` keyword can also be used to create a [custom named function]($type/function/#definitions). Let bindings can be accessed for the rest of the containing block or document. ```example #let name = "Typst" This is #name's documentation. It explains #name. #let add(x, y) = x + y Sum is #add(2, 3). ``` Let bindings can also be used to destructure [arrays]($type/array) and [dictionaries]($type/dictionary). In this case, the left-hand side of the assignment should mirror an array or dictionary. The `..` operator can be used once in the pattern to collect the remainder of the array's or dictionary's items. ```example #let (x, y) = (1, 2) The coordinates are #x, #y. #let (a, .., b) = (1, 2, 3, 4) The first element is #a. The last element is #b. #let books = ( Shakespeare: "Hamlet", Homer: "The Odyssey", Austen: "Persuasion", ) #let (Austen,) = books Austen wrote #Austen. #let (Homer: h) = books Homer wrote #h. #let (Homer, ..other) = books #for (author, title) in other [ #author wrote #title. ] ``` You can use the underscore to discard elements in a destructuring pattern: ```example #let (_, y, _) = (1, 2, 3) The y coordinate is #y. ``` Destructuring also work in argument lists of functions ... ```example #let left = (2, 4, 5) #let right = (3, 2, 6) #left.zip(right).map( ((a,b)) => a + b ) ``` ... and on the left-hand side of normal assignments. This can be useful to swap variables among other things. ```example #{ let a = 1 let b = 2 (a, b) = (b, a) [a = #a, b = #b] } ``` ## Conditionals { #conditionals } With a conditional, you can display or compute different things depending on whether some condition is fulfilled. Typst supports `{if}`, `{else if}` and `{else}` expression. When the condition evaluates to `{true}`, the conditional yields the value resulting from the if's body, otherwise yields the value resulting from the else's body. ```example #if 1 < 2 [ This is shown ] else [ This is not. ] ``` Each branch can have a code or content block as its body. - `{if condition {..}}` - `{if condition [..]}` - `{if condition [..] else {..}}` - `{if condition [..] else if condition {..} else [..]}` ## Loops { #loops } With loops, you can repeat content or compute something iteratively. Typst supports two types of loops: `{for}` and `{while}` loops. The former iterate over a specified collection whereas the latter iterate as long as a condition stays fulfilled. Just like blocks, loops _join_ the results from each iteration into one value. In the example below, the three sentences created by the for loop join together into a single content value and the length-1 arrays in the while loop join together into one larger array. ```example #for c in "ABC" [ #c is a letter. ] #let n = 2 #while n < 10 { n = (n * 2) - 1 (n,) } ``` For loops can iterate over a variety of collections: - `{for letter in "abc" {..}}` \ Iterates over the characters of the [string]($type/string). (Technically, iterates over the grapheme clusters of the string. Most of the time, a grapheme cluster is just a single character/codepoint. However, some constructs like flag emojis that consist of multiple codepoints are still only one cluster.) - `{for value in array {..}}` \ Iterates over the items in the [array]($type/array). The destructuring syntax described in [Let binding]($scripting/#bindings) can also be used here. - `{for pair in dict {..}}` \ Iterates over the key-value pairs of the [dictionary]($type/dictionary). The pairs can also be destructured by using `{for (key, value) in dict {..}}`. To control the execution of the loop, Typst provides the `{break}` and `{continue}` statements. The former performs an early exit from the loop while the latter skips ahead to the next iteration of the loop. ```example #for letter in "abc nope" { if letter == " " { break } letter } ``` The body of a loop can be a code or content block: - `{for .. in collection {..}}` - `{for .. in collection [..]}` - `{while condition {..}}` - `{while condition [..]}` ## Fields { #fields } You can use _dot notation_ to access fields on a value. The value in question can be either: - a [dictionary]($type/dictionary) that has the specified key, - a [symbol]($type/symbol) that has the specified modifier, - a [module]($type/module) containing the specified definition, - [content]($type/content) consisting of an element that has the specified field. The available fields match the arguments of the [element function]($type/function/#element-functions) that were given when the element was constructed. ```example #let dict = (greet: "Hello") #dict.greet \ #emoji.face #let it = [= Heading] #it.body \ #it.level ``` ## Methods { #methods } A method is a kind of a [function]($type/function) that is tightly coupled with a specific type. It is called on a value of its type using the same dot notation that is also used for fields: `{value.method(..)}`. The [type documentation]($type) lists the available methods for each of the built-in types. You cannot define your own methods. ```example #let array = (1, 2, 3, 4) #array.pop() \ #array.len() \ #("a, b, c" .split(", ") .join[ --- ]) ``` Methods are the only functions in Typst that can modify the value they are called on. ## Modules { #modules } You can split up your Typst projects into multiple files called _modules._ A module can refer to the content and definitions of another module in multiple ways: - **Including:** `{include "bar.typ"}` \ Evaluates the file at the path `bar.typ` and returns the resulting [content]($type/content). - **Import:** `{import "bar.typ"}` \ Evaluates the file at the path `bar.typ` and inserts the resulting [module]($type/module) into the current scope as `bar` (filename without extension). - **Import items:** `{import "bar.typ": a, b}` \ Evaluates the file at the path `bar.typ`, extracts the values of the variables `a` and `b` (that need to be defined in `bar.typ`, e.g. through `{let}` bindings) and defines them in the current file.Replacing `a, b` with `*` loads all variables defined in a module. Instead of a path, you can also use a [module value]($type/module), as shown in the following example: ```example #import emoji: face #face.grin ``` ## Operators { #operators } The following table lists all available unary and binary operators with effect, arity (unary, binary) and precedence level (higher binds stronger). | Operator | Effect | Arity | Precedence | |:----------:|---------------------------------|:------:|:----------:| | `{-}` | Negation | Unary | 7 | | `{+}` | No effect (exists for symmetry) | Unary | 7 | | `{*}` | Multiplication | Binary | 6 | | `{/}` | Division | Binary | 6 | | `{+}` | Addition | Binary | 5 | | `{-}` | Subtraction | Binary | 5 | | `{==}` | Check equality | Binary | 4 | | `{!=}` | Check inequality | Binary | 4 | | `{<}` | Check less-than | Binary | 4 | | `{<=}` | Check less-than or equal | Binary | 4 | | `{>}` | Check greater-than | Binary | 4 | | `{>=}` | Check greater-than or equal | Binary | 4 | | `{in}` | Check if in collection | Binary | 4 | | `{not in}` | Check if not in collection | Binary | 4 | | `{not}` | Logical "not" | Unary | 3 | | `{and}` | Short-circuiting logical "and" | Binary | 3 | | `{or}` | Short-circuiting logical "or | Binary | 2 | | `{=}` | Assignment | Binary | 1 | | `{+=}` | Add-Assignment | Binary | 1 | | `{-=}` | Subtraction-Assignment | Binary | 1 | | `{*=}` | Multiplication-Assignment | Binary | 1 | | `{/=}` | Division-Assignment | Binary | 1 |