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/README.md | markdown | Other | # 全球文种的字体与布局
## 介绍
本书是 <NAME> 编写的《[Fonts and Layout for Global Scripts][origin-book]》的中文翻译版,是一本关于字体设计、Unicode和计算机中复杂文本处理的免费书籍。
因为本书的主题是字体,为了保证显示效果和想表达的内容一致和满足我个人打印出来阅读的需求,没有沿用原书的 Markdown 格式。
本项目使用 [Typst] 作为排版系统,借助 [typst-book] 生成在线阅读版本。
## 阅读
### 在线
访问 [Github Pages] 即可在线阅读,点击左上角的笔刷图标进行主题切换。
请注意,由于技术方案的特性,可能在某些设备/情况下不太稳定。如果在阅读时遇到任何问题,请[提交 Issue][new-issue] 或选择下载PDF。
如果不出意外,在线版本永远是最新的。
### 离线
编译出的PDF文件可从以下两处下载:
1. [GitHub Release]
2. [CI][github-action-ci] 中的 Artifacts
其中 Release 中的不一定是最新版,但永久有效,会在有改动时每周六发布一次。
CI 中会有最新版但文件可能过期,如果过期可开 Issue 告知。
## 反馈与共建
各章节内容在 `chapters` 文件夹中,正文内容(除各类图示外)基本均为类似 Markdown 的纯文本,即使没有使用过 Typst 也非常容易看懂。
所以如果发现明显翻译问题或笔误,鼓励直接提交 PR,并通过 CI 生成的文件检查修复结果。
版式调整与字体更换(涉及`/template`)、术语翻译(涉及`/lib/glossary.typ`)等影响较大的修改等请在 PR 前先开 Issue 讨论。
原文更新导致翻译需要更新时,请同时修改 `/template/consts.typ` 中的 `upstream-version`。
## 本地编译
(本节内容可能需要您有一些技术方面的基础知识,以及对 Typst 和相关生态的了解,如果只是普通读者可以跳过)
整体流程可以参考 [CI workflow 文件][action-build-yaml],或按照以下文字描述操作。
### 网页
安装 [typst-book] 0.1.5。
下载[字体包][extra-font-release],并将其解压到 `fonts/extra` 文件夹(没有就建一下)中。
使用下列命令编译:
```bash
typst-book serve --font-path fonts
```
注意,编译时间比较久。编译成功后会启动 HTTP Server 并输出应该访问的 URL。
如果只想编译,`serve` 换成 `build`。
### PDF
PDF 需要网页版编译成功作为前置,请先确定能够正常在本地编译出网页版。
然后安装 [Typst] 0.11.1。
```bash
typst --font-path fonts --input realpdf=1 --input theme=light pdf.typ
```
和网页版一样支持主题选择,可选 `[ light, rust, coal, navy, ayu ]`。
### 所见即所得
如果想所见即所得的编辑,推荐使用 VSCode 配合 [Tinymist] 和 [Typst Preview][typst-preview] 插件。
`.vscode/setting.json` 中已经包含了所需的配置,直接从 `pdf.typ` 文件启动 `typst-preview` 即可,这时预览的是 PDF 的效果。
如果你想查看网页版的效果,可以将 `.vscode/setting.json` 中的两处 `realpdf=1` 参数删去,然后从各章节文件启动单页预览。
## 参考资料
- 《FontForge 与字体设计》一书中的[术语表][fontforge-glossary]
- 知乎专栏文章《[Unicode®标准英文术语翻译对照表及部分术语汇释][unicode-glossary]》
- [Unicode 术语英中对照表][unicode-terminology]
- [symbl.cc]
- Adobe OpenType 特性语言的语法高亮文件是从 [language-fontforge] 项目转换而来,经过少量修改。
- 黑暗模式的语法高亮方案为 [tokyo night][theme-tokyo-night],tmTheme 颜色配置来自 [typst-book] 的储存库。
## LICENSE
许可证原书一致,为 [CC BY-SA 4.0]。
细节请参考 LICENSE 文件(或原项目 README),其中有原作者对演绎版本的一些要求。
[origin-book]: https://simoncozens.github.io/fonts-and-layout/
[Typst]: https://github.com/typst/typst
[typst-book]: https://github.com/Myriad-Dreamin/typst-book
[Github Pages]: https://7sdream.github.io/fonts-and-layout-zhCN/
[new-issue]: https://github.com/7sDream/fonts-and-layout-zhCN/issues/new
[Github Release]: https://github.com/7sDream/fonts-and-layout-zhCN/releases/latest
[github-action-ci]: https://github.com/7sDream/fonts-and-layout-zhCN/actions/workflows/ci.yaml
[action-build-yaml]: https://github.com/7sDream/fonts-and-layout-zhCN/blob/master/.github/workflows/action-build.yaml
[extra-font-release]: https://github.com/7sDream/fonts-and-layout-zhCN/releases/tag/extra-fonts%2F20240615
[Tinymist]: https://github.com/Myriad-Dreamin/tinymist
[typst-preview]: https://github.com/Enter-tainer/typst-preview
[fontforge-glossary]: http://designwithfontforge.com/zh-CN/Glossary.html
[unicode-glossary]: https://zhuanlan.zhihu.com/p/79246427
[unicode-terminology]: https://www.unicode.org/terminology/term_en_zh_Hans_CN.html
[symbl.cc]: https://symbl.cc/
[language-fontforge]: https://github.com/Alhadis/language-fontforge
[theme-tokyo-night]: https://github.com/enkia/tokyo-night-vscode-theme
[CC BY-SA 4.0]: https://creativecommons.org/licenses/by-sa/4.0/deed.zh-hans
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/import-19.typ | typst | Other | // Error: 23-24 unexpected equals sign
#import "module.typ": =
|
https://github.com/ffasbend/refcards | https://raw.githubusercontent.com/ffasbend/refcards/main/python_refcard/python_refcard_fr.typ | typst | MIT License | #import "@preview/tablex:0.0.6": tablex, colspanx, rowspanx, vlinex, hlinex
/* --- page layout --- */
#set page(margin: (
top: 1.2cm,
bottom: 1cm,
x: 0.8cm,
))
/* --- define symbol, spacing shortcuts --- */
// rigth arrow
//#let ar = sym.arrow
#let ar = {
text(font:"Wingdings", "\u{f0f0}")
}
// left arrow
//#let al = sym.arrow.l
#let al = {
text(font:"Wingdings", "\u{f0ef}")
}
// 1em space
#let quad = sym.space.quad // 1em space
#show "1er": it => box[
1#super[er]
]
#show "1ère": it => box[
1#super[ère]
]
#show "2e": it => box[
2#super[e]
]
#show "1st": it => box[
1#super[st]
]
#show "2nd": it => box[
2#super[nd]
]
/* --- page header --- */
#set page(header: rect(stroke:(top:0pt, bottom:0.6pt), inset:(x:0pt, y:3pt))[
#smallcaps[Python 3 - Refcard] v3.0.7 (1ère et 2e B)
#h(1fr)
Page #counter(page).display(
"1/1",
both: true,
)
])
/* --- page footer --- */
#let today = datetime.today().display("[day]/[month]/[year]") // specify a custom format
#set page(footer: rect(stroke:(top:0.6pt, bottom:0pt), inset:(x:0pt, y:3pt))[
python_refcard_fr.typ #quad [available online: #link("https://github.com/ffasbend/refcards")]
#h(1fr)
version du #today
])
/* --- fonts, colors, line spacing --- */
//#let blue = color.rgb(56, 83, 145)
#let blue = color.rgb(36, 54, 96)
#set text(font: "Calibri", 6.5pt)
//#set text(font: "Barlow", 10pt)
#show par: it => {
set block(above:0.6em, below: 0.5em)
it
}
/* --- headings --- */
#show heading: set text(blue, font:"Calibri")
#show heading.where(
level: 1
): it => {
set text(blue, font: "Calibri", size:9pt, weight:"regular")
set block(fill:rgb(219,226,241), inset:(x:0pt, y:3pt), above: 0.5em, below: 0.3em, width:100%)
rect(stroke:(top:0pt, bottom:0.8pt), inset:(x:0pt, y:0pt))[#it]
}
#show heading.where(
level: 2
): it => {
set text(blue, font:"Calibri", size:8pt, weight:"semibold")
set block(above: 0.6em, below: 0.3em)
it
}
#show heading.where(
level: 3
): it => {
set block(above: 0.6em, below: 0.3em)
it
}
/* --- raw text --- */
//#set raw(theme: "myPython.tmTheme")
#set raw(lang:"py")
#show raw: set text(font: "Iosevka Fixed", size:6.5pt)
/* --- define alert --- */
#let alert(body, fill: red) = {
set text(fill: red)
[#body]
}
/* --- define table --- */
#let syntaxTable(columns: (auto, 1fr), ..data) = {
//repr(data.pos())
tablex(
columns: columns,
rows: auto, // at least 1 row of auto size
align: left + top,
stroke: white,
inset: (x: 0.3em, y: 0.3em),
auto-hlines:false,
// add some arbitrary content to entire rows
map-rows: (row, cells) => cells.map(c =>
if c == none {
c // keeping 'none' is important
} else {
(..c, fill: if calc.even(row) { rgb(208,208,208) } else { rgb(230,230,230) })
}
),
..data,
)
}
/* --- use 2 columns --- */
#show: rest => columns(2, gutter: 3mm, rest)
= #smallcaps[Valeurs et types #h(1fr) list, tuple, dict (voir pages suivantes)]
== Types numériques
#syntaxTable(
[`int a = 5`],
[integer (entier compris entre -∞ … +∞)],
[`float c = 5.6 , c = 4.3e2`],
[floating point number (nombre décimal)],
[`complex d = 5 + 4j`],
[complex numbers (nombres complexes)],
)
== Strings (Types d'objets itérables, mais non modifiables)
#syntaxTable(
[`str e = "hello"`],
[Character string, chaîne de caractères],
)
== Conversion de type
#syntaxTable(
[`int(s)`],
[convertir chaîne `s` en nombre entier],
[`float(s)`],
[convertir chaîne `s` en nombre décimal],
[`str(number)`],
[convertir nombre entier/décimal en string],
[`list(x)`],
[convert tuple, range or similar to list],
)
== Noms des variables #ar case sensitive #text(size: 6.5pt)[(différence entre caractères majuscules et minuscules)]
Certains mots réservés ne sont pas autorisés :
#pad(left:0.2cm)[
*False, None, True, and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while*
(*print*, *sum* #ar not recommended, else internal functions will be overridden)
]
#syntaxTable(
[lettres (a…z , A…Z) \
chiffres (0…9) \
\_ (underscore, blanc souligné)],
[caractères autorisés, doit commencer par une lettre],
[`i, x`],
[boucles et indices #ar lettres seules en minuscule],
[`get_index()`],
[modules, variables, fonctions et méthodes \
#ar minuscules + blanc souligné],
[`MAX_SIZE`],
[(pseudo) constantes #ar majuscules et blanc souligné],
[CamelCase],
[nom des classes #ar CamelCase],
)
= #smallcaps()[Chaînes de caractères (=séquences non-modifiables, immutable)]
*Les caractères d'une chaîne ne peuvent pas être modifiés.* Python ne connaît pas de caractères. Un caractère isolé = chaîne de longueur 1. Dans les exemples suivants : `s` = chaîne de caractères
- `ord('A')` #ar return integer Unicode code point for char (e.g. 65)
- `chr(65)` #ar return string representing char at that point (e.g. 'A')
== String literals
#syntaxTable(
[`"texte"` ou `'texte'`],
[délimiteurs doivent être identiques],
[```
""" chaîne sur
plusieurs lignes """```],
[chaîne sur plusieurs lignes, délimitée par `"""` ou `'''`],
[`"abc\"def"` ou `'abc\'def'`],
[inclure le délimiteur dans la chaîne],
[`\n`],
[passage à la ligne suivante],
[`\\`],
[pour afficher un \\],
)
== Caractères et sous-chaînes (Voir les exemples sous #ar Listes-Affichage)
== Opérateurs
#syntaxTable(
[`"abc" + "def"` ou `"abc" "def"`],
[#ar `"abcdef"` (concaténation)],
[`"abc" * 3` ou `3 * "abc"`],
[#ar `"abcabcabc"` (multiplication)],
)
== Affichage #ar f-string (formatted strings), chaîne de char. préfixée par `f` ou `F`
#syntaxTable(
[`f"{var1} x {var2} = {var1 * var2}"` \
`"{} x {} = {}".format(v1, v2, v1*v2)`],
[{…} = remplacé par variables ou expression \
ou bien : `str.format()`],
[`"{0}{1}{0}".format('abra', 'cad')`],
[#ar `"abracadabra"` (on peut aussi les numéroter)],
)
Placeholder options
#syntaxTable(
[```
{:format-spec}
format-spec is : [fill]align
fill = espace (par défaut)
{x:3d} ➭ display as integer, padding = 3
```],
[`{:4}` ou `{:>4}` #ar padding of 4, right aligned \
`{:.5}` #ar truncate to 5 chars \
`{:10.5}` #ar padding of 10, truncate to 5 \
`{:.2f}` #ar display as float with 2 decimals \
`{:6.2f}` #ar float with 2 decimals, padding = 6
],
)
#tablex(
// columns: (auto, 1fr, 1fr), // 4 columns
columns: (auto, 2em, 1fr, 2em, 1fr),
rows: auto, // at least 1 row of auto size
align: left + top,
stroke: black + 0.5pt,
auto-lines:false,
(), vlinex(), vlinex(), vlinex(), vlinex(), vlinex(),
hlinex(start: 1, end: 5),
inset: (x: 0.3em, y: 0.3em),
auto-hlines:false,
// add some arbitrary content to entire rows
[align:], [` < `], [left-aligned], [` = `], [padding after sign, but before numbers],
[], [` > `], [right-aligned (default for numbers)], [` ^ `], [centered],
hlinex(start: 1, end: 5),
)
Utiliser une variable `var1` dans `format-spec` : `"…{:{var1}}…".format(…, var1 = value, …)`
== Méthodes
#syntaxTable(
[`s.capitalize()`],
[renvoie une copie avec le premier caractère en majuscule],
[`s.lower() | s.upper()`],
[renvoie une copie en lettres minuscules | majuscules],
[`s.strip()`],
[renvoie une copie et enlève les caractères invisibles (whitespace) au début et à la fin de `s`],
[`s.strip(chars)`],
[renvoie une copie et enlève les caractères chars au début et à la fin de `s`],
[`s.split()`],
[renvoie une liste des mots (délimités par whitespace), pas de mots vides],
[`s.split(sep)`],
[renvoie une liste des mots (délimités par sep), sous-chaînes vides si plusieurs `sep` consécutifs],
[`s.find(sub[, start[, end]])`],
[renvoie l'indice de la 1ère occurrence de `sub` dans la sous-chaîne `[start:end]` de `s`, renvoie `-1` si pas trouvé],
[`s.index(sub[, start[, end]])`],
[idem, mais exception `ValueError` si pas trouvé],
[`s.replace(old, new[, n])`],
[renvoie une copie avec les `n` (default = toutes) premières occurrences de `old` remplacés par `new`],
[`s.isalpha()`],
[`True` si au moins un caractère et que des lettres],
[`s.isdigit()`],
[`True` si au moins un chiffre et que des chiffres],
[`s.isalnum()`],
[`True` si au moins un caractère et que des lettres ou chiffres],
[`s.islower()`],
[`True` si au moins une lettre et que des minuscules],
[`s.isupper()`],
[`True` si au moins une lettre et que des majuscules],
[`s.isspace()`],
[`True` si au moins un whitespace et que des whitespace],
[`for char in s :`],
[parcourir les lettres de la chaîne de caractères],
[`s.join(iterable)`\
`"xx".join("123")` #ar `"1xx2xx3"`],
[returns a string created by joining the elements of an iterable by string separator],
[`s.join([str(elem) for elem in lst])`],
[convertir liste en chaîne avec séparateur `s`],
)
= #smallcaps[Listes (=séquences modifiables)] #ar [] #h(1fr) type: list
Dans une même liste #ar variables de différents types = possible.
== Création #h(1fr) `*` = unpack operator
#syntaxTable(
[`lst = []`],
[créer une liste vide],
[`lst = [item1, item2, … ] , lst = [23, 45]`],
[créer une liste avec des éléments],
[`new_lst = lst1 + lst2 ( = [*lst1, *lst2] )`],
[#alert[Attention] : *crée une nouvelle liste*],
[`list(x), ex : lst = list(range(5))`],
[Convertir uplet, range ou semblable en liste],
)
Remarque
#syntaxTable(
[`A = B = []` #quad #ar #quad `A = [] et B = A`],
[les 2 noms (`A` et `B`) pointent vers la même liste],
)
list comprehensions (computed lists)
#syntaxTable(
[`lst = [expr for var in sequence]`\
`lst = [expr for var in sequence if …]`],
[`expr` is evaluated once for every item in `sequence`, (`if` is optional)],
)
Exemple : création d'une matrice 3x3
#syntaxTable(
[`p = [x[:] for x in [[0]*3]*3]` ou \
`p = [[0,0,0], [0,0,0], [0,0,0]]`],
[+ construire 3 vecteurs, chacun avec 3 composants nuls
+ une copie est placée dans `p`, pour obtenir 3 vecteurs-lignes indépendants, ne pointant pas sur le même objet],
)
== Affichage et sous-listes #h(1fr) premier élément d'une liste #ar index 0
#syntaxTable(
[`lst[index]`],
[retourne l'élément à la position `index`\
(un `index < 0` #ar accède aux éléments à partir de la fin)],
[`lst[start :end]`\
`lst[start :end :step]`],
[retourne une sous-liste de l'indice `start` à `end` (non compris) \
(seuls les éléments avec `index` = multiple de `step` inclus)],
)
#tablex(
columns: (auto, 1fr), // 4 columns
rows: auto, // at least 1 row of auto size
align: left + top,
stroke: black + 0.5pt,
inset: (x: 0.3em, y: 0.3em),
auto-hlines:false,
hlinex(start: 0, end: 2),
[`lst[-1]`],
[retourne le dernier élément de `lst`],
[`lst[2:-1]`],
[sous-liste à partir de l'indice 2 jusqu'à l'avant dernier],
[`lst[:4]`],
[sous-liste à partir du début jusqu'à l'indice 3],
[`lst[4:]`],
[sous-liste à partir de l'indice 4 jusqu'à la fin],
[`lst[:]`],
[retourne la liste entière, pour copier une liste dans une autre variable],
[`lst[::2]`],
[retourne sous-liste des éléments à index pair],
[`lst[::-1]`],
[retourne sous-liste des éléments dans l'ordre inverse],
hlinex(start: 0, end: 2),
)
Pour copier une liste
#syntaxTable(
[`lst = [2, 3, 4, 5]` \
`copie = lst[:]` ou `copie = lst.copy()`],
[1st level copy (`copie = lst` ne fonctionne pas, car variables pointent alors sur la même liste)],
[`copie = [x[:] for x in lst]`],
[copier une liste de listes (2nd level copy, shallow copy)],
[`copie = copy.deepcopy(lst)`],
[`import copy` (any level copy, deep copy)],
)
== Modification
#syntaxTable(
[`lst[index] = item`],
[modifie l'élément à la position `index`],
[`lst[start :end] = […]`],
[remplace la sous-liste à partir de `start` jusqu'à `end` (exclu), même de taille différente],
[`lst.append(item)`],
[add `item` as single element to end of *existing* list],
[`lst.extend(iterable)`\
`lst += [item1, …, item_n]`],
[add each element of `iterable` (all items) to the existing list by iterating over the argument],
[`lst = lst + [item1, …, item_n]`],
[#alert[Attention:] create new list and add all items from both],
[`del lst[index] , del(lst[index])`],
[supprime l'élément à la position `index`],
[`lst.remove(item)`],
[supprime le premier élément avec la valeur `item`],
[`lst.pop()`\
`lst.pop(index)`],
[enlève et retourne le dernier élément de la liste (à la position indiquée par `index`)],
[`lst.reverse()`],
[inverse les items d'une liste (modifie la liste)],
[`new_lst = reversed(lst)`],
[retourne une liste inversée (`lst` = unchanged)],
[`lst.sort()`],
[trier la liste (modifie la liste)],
[`new_lst =sorted(lst)`],
[retourne une liste triée (`lst` = unchanged)],
[`lst.insert(index, item)`],
[insère l'`item` à la position donnée par `index`],
)
Attention :
#tablex(
columns: (auto, 1fr), // 4 columns
rows: auto, // at least 1 row of auto size
align: left + top,
inset: (x: 0.3em, y: 0.3em),
stroke: black + 0.5pt,
auto-lines:false,
(), vlinex(), (),
// add some arbitrary content to entire rows
[`lst = [1, 2, 3, 4]` \
`lst[2] = [7,8,9]` #ar `[1, 2, [7, 8, 9], 4]` \
(liste imbriquée)],
[`lst = [1, 2, 3, 4]`\
`lst[2:2] = [7,8,9]` #ar `[1, 2, 7, 8, 9 , 4]` \
(élément remplacé par plusieurs éléments)],
)
== Divers
#syntaxTable(
[`print(lst)`],
[affiche le contenu de la liste],
[`len(lst)`],
[nombre d'items dans `lst`],
[`lst.count(item)`],
[nombre d'occurrences de la valeur `item`],
[`lst.index(item)`],
[retourne l'index de la 1ère occurrence de item, sinon #ar exception `ValueError`],
[`item in lst (item not in lst)`],
[indique si l'`item` se trouve dans `lst` (n'est pas dans)],
[`min(lst) / max(lst)`],
[retourne l'élément avec la valeur min. / max.],
[`sum(lst[,start])`],
[retourne la somme à partir de `start` (= 0 par défaut)],
[`for item in lst:`],
[parcourir les éléments],
[`for index in range(len(lst)):`],
[parcourir les indices],
[`for index, item in enumerate(lst):`],
[parcourir l'indice et les éléments],
[`for item in reversed(lst):`],
[parcourir dans l'ordre inverse],
[#alert[`for item in lst[:]:`]],
[#alert[effacer éléments d'une liste #ar utiliser copie de `lst`]],
[#alert[``` for i in range(len(lst)-1, -1, -1):
… code pour effacer des items
```]],
[#alert[effacer certains éléments d'une liste #ar il faut parcourir la liste de la fin au début, si on a besoin de l'index]],
[#alert[```
while i < len(lst):
if … code pour effacer items
else:
i = i + 1
```]],
[#alert[effacer certains éléments d'une liste]],
[`if lst: ou if len(lst) > 0:`],
[test si la liste `lst` n'est pas vide],
[`map(fonction, lst)`],
[applique la fonction sur chaque élément de la liste],
)
= #smallcaps[Range (=séquences non modifiables)]
Retourne une séquence non modifiable d'entiers
#syntaxTable(
[`range([start], stop[, step])`\
(start, stop, step = integers)
],
[retourne une séquence d'entiers sans la valeur `stop`\
`range(n)`#ar [0,1,2, …, n-1], #quad ex.: `range(3)` #ar [0, 1, 2] \
`range(2, 5)` #ar [2, 3, 4] \
`range(0, -10, -2)` #ar [0, -2, 4, -6, -8]
],
)
= #smallcaps[Les uplets (Tuples) -> ()] #h(1fr) type: tuple
Uplet = collection d'éléments séparés par des virgules. Comme les chaînes *pas modifiables*
== Création
#syntaxTable(
[`tuple = (a, b, b, …)` #quad#quad `t = ("a", 2.4, 45)` \
`tuple = a, b, c, …` #h(1fr) `t = (1,) ou t = 1,`],
[créer un uplet \
(on peut omettre les parenthèses, si clair)],
[`tuple1 = tuple2`],
[copier un uplet],
)
== Extraction
#syntaxTable(
[`(x, y, z) = tuple` #quad ou #quad `x, y, z = tuple`],
[extraire les éléments d'un uplet],
)
== Affichage #ar voir listes
Premier élément d'un uplet #ar index 0
#syntaxTable(
[`tuple[index]`],
[retourne l'élément à la position index \
(un index < 0 #ar accède aux éléments à partir de la fin)],
[`tuple[start:end]`],
[retourne un sous-uplet de l'indice \[start ; end\[ ],
)
= #smallcaps[Les dictionnaires -> \{\} ] #h(1fr) type: dict
Les dictionnaires sont modifiables, mais pas des séquences. L'ordre des éléments est aléatoire. Pour accéder aux objets contenus dans le dictionnaire on utilise des clés (keys). Classe : `dict`
== Création
#syntaxTable(
[`dic = {}` ou `dic = dic()`],
[créer un dictionnaire vide],
[`dic = {key1: val1, key2: val2, …}`],
[créer un dictionnaire déjà rempli : \
`d = {"nom":"John", "age":24}`],
[`dic[key] = value`],
[ajouter une `clé:valeur` au dictionnaire si la clé n'existe pas encore, sinon elle est remplacée],
)
`key` peut être alphabétique, numérique ou type composé (ex. uplet)
== Affichage
#syntaxTable(
[`dic[key]`],
[retourne la valeur de la clé `keys`. Si la clé n'existe pas une exception `KeyError` est levée],
[`dic.get(key, default = None)`],
[retourne la valeur de la clé, sinon `None` (ou la valeur spécifiée comme 2e paramètre de `get`)],
[`dic.keys()` \
`list(dic.keys())` #quad ou #h(1fr)`list(dic)` \
`tuple(dic.keys())` \
`sorted(dic.keys())` #h(1fr) `sorted(dic)`],
[retourne les clés du dictionnaire \
… comme liste \
… comme uplet \
renvoie une liste des clés dans l'ordre lexicographique],
[`dic.values()`#quad #quad #h(1fr) `list(dic.values())`],
[renvoie les valeurs du dictionnaire / comme liste],
[`dic.items()` #h(1fr) `list(dic.items())`],
[renvoie les éléments du dictionnaire sous forme d'une séquence de couples / d'une liste de couples],
)
== Modification
#syntaxTable(
[`dic[key] = value`],
[ajouter une `clé:valeur` au dictionnaire, si la clé n'existe pas encore (sinon elle est remplacée)],
[`del dic[key]` #quad ou #quad `del(dic[key])`],
[supprime la clé `key` du dictionnaire],
[`dic.pop(key)`],
[supprime la clé `key` du dictionnaire et renvoie la valeur supprimée],
)
== Divers
#syntaxTable(
[`len(dic)`],
[renvoie le nombre d'éléments dans le dictionnaire],
[`if key in dic: , if key not in dic`],
[tester si le dictionnaire contient une certaine clé],
[`for c in dic.keys():`#quad ou \
`for c in dic:`],
[parcourir les clés d'un dictionnaire],
[`for c, v in dic.items():`],
[parcourir les éléments du dictionnaire ],
[`copie = dic.copy()`],
[crée une copie (shallow copy) du dictionnaire (une affectation crée seulement un nouveau pointeur sur le même dictionnaire) - 1st level copy],
[`copie = copy.deepcopy(dic)`],
[`import copy` (any level copy)],
[`max(dic, key=len)`],
[retourne la clé la plus longue],
[`dic1.update(dic2)`],
[combine 2 dictionnaires en un seul (`dic1`), les clés de `dic2` sont prioritaires],
)
= Expressions et opérateurs
Opérateurs entourés d'espaces. Utiliser parenthèses pour grouper des opérations (modifier la priorité)
== Opérateurs mathématiques
La 1ère colonne indique la priorité des opérateurs
#syntaxTable(columns: (auto, 3em, 1fr),
[1.],
[`**`],
[exponentiation #h(1fr) `6 ** 4` #ar `1296`],
[2.],
[`-, +`],
[signe #h(1fr) `-5`],
[3.],
[`*`],
[multiplication #h(1fr) `x *= 3` #ar `x = x * 3`],
[],
[`/`],
[division (entière ou réelle) #h(1fr) `x /= 3` #ar `x = x / 3`],
[],
[`//`],
[quotient de la division entière #h(1fr) `6 // 4` #ar `1`\
(arrondit vers le négatif infini) #h(1fr) `-6.5 // 4.1` #ar `-2.0`],
[],
[`%`],
[modulo, reste (positif) de la division entière #h(1fr) `6 % 4` #ar `2`, ` -6.5 % 4. 1` #ar `1.7` \
obtient le signe du diviseur #h(1fr) `6 % -4` #ar `-2`],
[4.],
[`+`],
[addition #h(1fr) `x += 3` #ar `x = x + 3`],
[],
[`-`],
[soustraction #h(1fr) `x -= 3` #ar `x = x - 3`],
)
== Opérateurs relationnels
retournent `True` ou `1` si l'expression est vérifiée, sinon `False` ou `0`
#syntaxTable(columns: (auto, 3em, 1fr),
[5.],
[`==`],
[égal à],
[],
[`!=`],
[différent de],
[],
[`>`],
[strictement supérieur à],
[],
[`<`],
[strictement inférieur à],
[],
[`>=`],
[supérieur ou égal à #h(1fr) (exemple : #quad `x >= a` #quad ou #quad `b >= x >= a ` pour ` a <= b`)],
[],
[`<=`],
[inférieur ou égal à #h(1fr) (exemple : #quad `x <= b` #quad ou #quad `a <= x <= b`)],
)
chaînes de caractères #ar ordre lexicographique, majuscules précèdent les minuscules
//#colbreak()
== Opérateurs logiques
#syntaxTable(columns: (auto, auto, 1fr),
[6.],
[`not x`],
[*non* (retourne `True`, si `x` est faux, sinon `False`)],
[7.],
[`x and y`],
[*et* (retourne `x`, si `x` est faux, sinon `y`) \
`and` ne vérifie le 2e argument que si le 1er argument est vrai],
[8.],
[`x or y`],
[*ou* (retourne `y`, si `x` est faux, sinon `x`) \
`or` ne vérifie le 2e argument que si le 1er argument est faux],
)
== Affectation
L'affectation attribue un type bien déterminé à une variable.
#syntaxTable(
[`variable = expression`],
[Affectation simple, attribuer une valeur à une variable],
[`a = b = c = 1`],
[affectation multiple],
[`x, y = 12, 14`],
[affectation parallèle],
[`x, y = y, x `],
[échanger les valeurs des 2 variables (swap)],
)
= Entrée / Sortie
== Entrée
#syntaxTable(
[`var = input()`],
[renvoie une chaîne de caractères],
[`var = input(message)`],
[renvoie une chaîne de caractères et affiche le message],
[`int = int(input(…))`],
[renvoie un entier],
[`float = float(input(…))`],
[renvoie un nombre décimal],
)
== Sortie
#syntaxTable(
[`print(text, end="final")`],
[affiche `text` et termine avec `final` (par défaut `end="\n"`)],
[`print("abc", "def")`],
[#ar `abc def` (arguments séparés par espace, nouvelle ligne)],
[`print("abc", end="+")`],
[#ar abc+ (pas de passage à la ligne)],
[`print(var)`],
[`var` est converti en chaîne et affichée],
[`print("value=", var)`],
[affiche le texte suivi d'une espace, puis de la valeur de `var`],
[`print()`],
[simple passage à la ligne],
[`print(str * n) | print(n * str)`],
[afficher `n` fois le texte `str`],
)
= Les commentaires
#syntaxTable(
[`# commentaire`],
[sur une seule ligne],
[`'''comments'''` ou `"""comments"""`],
[sur plusieures lignes ( = string literal)],
)
= Structure alternative et répétitive
== Structure alternative
#syntaxTable(
[```
if condition1:
instruction(s)
elif condition2:
instructions(s)
…
else:
instruction(s)```],
[- exécute seulement les instructions, où la condition est vérifiée \
- si aucune condition n'est vérifiée, les instructions de `else` sont exécutées \
- `else` et `elif` sont optionnels],
[`<on true> if <expr> else <on false>`],
[- ternary operator (opérateur ternaire)],
)
== Structure répétitive (boucle for)
#syntaxTable(
[```
for itérateur in liste de valeurs:
instruction(s)
for i in range (10): # values 0, 1, … 9
for _ in range (10): # values 0, 1, … 9```],
[- répète les instructions pour chaque élément de la liste \
- nombre de répétitions = connu au départ \
- `_` si valeur de l'itérateur n'est pas utilisée],
)
== Structure répétitive (boucle while)
#syntaxTable(
[```
while condition(s):
instruction(s)```],
[- répète les instructions tant que la condition est vraie \
- *pour pouvoir sortir de la boucle, la variable utilisée dans la condition doit changer de valeur* \
- nombre de répétitions != connu au départ],
)
A l'intérieur d'une boucle *for* ou *while*
#syntaxTable(
[`break`],
[quitte la boucle immédiatement],
[`continue`],
[continue avec la prochaine itération],
)
= Les fonctions
Le code de la fonction doit être placé plus haut dans le code source (avant l'appel de la fonction).
- arguments simples (nombres, chaînes, uplets) #ar passage par valeur (valeurs copiés)
- arguments complexes (listes, dictionnaires) #ar passage par référence (vers les originaux)
== Définition et appels
#syntaxTable(
[```
def my_function(par1, …, par_n):
instruction(s)
…
return var
```],
[définit une fonction `my_function` \
- `par1 … par_n` sont les paramètres \
- une ou plusieurs instructions `return…` \
- peut renvoyer plusieurs réponses (uplet, liste) \
Si la fonction ne contient pas d'instruction `return`, la valeur `None` est renvoyée],
[```
my_function(arg1, … arg_n)
var = my_function(arg1, … arg_n)
```],
[appel de la fonction, arguments affectés aux paramètres dans le même ordre d'apparition],
[`my_function(*lst)`],
[`*` to unpack list elements],
[`my_function(**dct)`],
[`*` to unpack dictionary elements],
[```
def func(par1, …, par_n = val):
ex : def add(elem, to = None):
if to is None:
to = []
```],
[paramètre par défaut \
#alert[ATTENTION:] \
` def add(elem, to = []):` \
#alert[ne marche pas, car les arguments par défaut ne sont évalués qu'une seule fois et réutilisés pour tous les appels de la fonction.]],
[`def func(par1, …, *par_n):`],
[`*par_n` = nombre variable de paramètres (liste)],
)
`*` = unpack operator to unpack list elements #h(1fr) #link("https://docs.python-guide.org/writing/gotchas/")
== Variables globales
Les paramètres et variables locales cachent les variables globales/extérieures.
#syntaxTable(
[```
def func(…):
global var```],
[`var` est déclaré comme variable global, la variable `var` à l'extérieur de la boucle est donc modifiée/utilisée],
)
#colbreak()
= #smallcaps[Utilisation de modules (bibliothèques)]
#syntaxTable(
[`import module`],
[importe tout le module, il faut préfixer par le nom du module . Ex : `import math` #ar `math.sqrt()`],
[`import module as name`],
[],
[`from module import *` \
#alert[`*** à éviter ***`]],
[intègre toutes les méthodes de module, pas besoin de préfixer le nom du module.
Ex : `from math import *` #ar `sqrt()`],
[`from module import m1, m2, …`\
`from math import sqrt, cos`],
[intègre seulement les méthodes mentionnées \
#ar `sqrt(…), cos(…)`],
)
= #smallcaps[Module: math] #h(1fr) import math
Built-in functions (no import required)
#syntaxTable(
[`abs(x)`],
[valeur absolue (aussi nombres complexes)],
[`round(x)`],
[`x` est arrondie vers l'entier pair le plus proche (rounds to nearest EVEN integer)\
- `round(3.5)` #ar 4 #quad `round(4.5)` #ar 4],
)
import math
#syntaxTable(
[`math.pi`],
[le nombre pi],
[`math.cos(x) / .sin(x) / .tan(x)`],
[cosinus/sinus/tangente d'un angle en radian],
[`math.sqrt(x)`],
[racine carrée],
[`math.fabs(x)`],
[valeur absolue #ar retourne un float],
[`math.ceil(x) / math.floor(x)`],
[`x` est arrondie vers le haut / vers le bas],
[`math.trunc(x)`],
[retourne l'entier sans partie décimale],
[`math.pow(x, y)`],
[x exposant y],
[`math.gcd(x, y)`],
[retourne le PGCD des 2 nombres],
)
= #smallcaps[Module: random] #h(1fr) import random
#syntaxTable(
[`random.randint(a, b)`],
[retourne un entier au hasard dans l'intervalle [a ; b]],
[`random.random()`],
[retourne un réel au hasard dans l'intervalle \[0 ; 1\[],
[`random.uniform(a, b)`],
[retourne un réel au hasard dans l'intervalle \[ a ; b\]],
[`random.choice(seq)`],
[retourne un élément au hasard de la séquence `seq` \
(si `seq` est vide #ar exception `IndexError`)],
[`random.sample(seq, k)`],
[retourne une liste de `k` éléments uniques (choisis au hasard) de la séquence `seq`],
[`random.randrange(stop)` \
`random.randrange(start, stop)`\
`radnom.randrange(start, stop, step)`],
[retourne un entier au hasard de `[start ; stop[`. Seuls les multiples de `step` sont possibles. \
(`start` = 0, `step` = 1 par défaut)],
[`random.shuffle(seq)`],
[mélange aléatoirement les éléments de `seq`],
)
retourner le nombre aléatoire -1 ou 1
#syntaxTable(
columns: (1fr, 1fr, 1fr),
[`randrange(-1, 2, 2)`],
[`2 * randint(0, 1) - 1`],
[`h = [-1, 1] , choice(h)`],
)
= #smallcaps[Module: timit] #h(1fr) import timit
#syntaxTable(
[```
t1_start = timeit.default_timer()
…
t2_stop = timeit.default_timer()
print(t2_stop - t1_start)
```],
[Return process time of current process as float in seconds],
)
= #smallcaps[Les fichiers]
== Entrées/sorites console et redirection
#syntaxTable(
[`STDIN`],
[entrée standard #ar le clavier (pour entrer des données)],
[`STDOUT`],
[sortie standard #ar l'écran (pour afficher les résultats)],
[`STDERR`],
[l'écran (pour envoyer les messages d'erreur)],
[`command > filename`],
[rediriger la sortie standard vers un fichier (créé/remplacé)],
[`command >> filename`],
[rediriger la sortie standard vers un fichier (ajouté)],
[`command > NUL`],
[annuler sortie vers STDOUT],
[`command < filename`],
[rediriger entrée depuis un fichier],
)
== Tubes et filtres
#syntaxTable(
[`command1 | command2`],
[rediriger la sortie de `command1` comme entrée à `command2`],
)
== Manipulation de fichiers
#syntaxTable(
[`file = open(filename, mode='r')` \
`file = open(filename, mode='r',` \ #h(1fr) `encoding='utf-8')`],
[retourne un objet fichier \
- `mode='r'` (lecture), `'w'` (écriture), `'a'` (ajout à la fin) \
(`'w'` crée un nouveau fichier ou vide le fichier existant)
- (optionnel) `encoding='utf-8'`, `'ascii'` ou `'latin-1'`],
[`line = file.readline()`],
[lit et retourne la prochaine ligne complète avec caractère fin de ligne (retourne chaîne vide `""` si fin du fichier est atteinte)],
[`for line in file:` \
` …`],
[lit tout le fichier ligne après ligne (voir ci-dessous)],
[```
line = file.readline()
while line != "":
…
line = file.readline()
```],
[lit tout le fichier ligne après ligne #ar utiliser `line.strip()` pour enlever les caractères invisibles (espaces, newline) au début et à la fin d'une ligne],
[`lines_list = file.readlines()`],
[lit tout le fichier et retourne une liste de chaînes],
[`file.read()`],
[lit tout le fichier et retourne une chaîne],
[`file.write(str)`],
[écrit dans `file` la chaîne `str`],
[`file.close()`],
[fermer `file` (si traitement du fichier est terminé)],
)
== Vérifier si un fichier existe
#syntaxTable(
[```
import os
filename = os.path.normpath(f"{path}/{filename}")
if os.path.isfile(filename):
…
```],
[ \
convertir les séparatuers de chemin \
vérifie si le fichier du nom `filename` existe]
)
== Lire de STDIN en Python (manière de filtres)
#syntaxTable(
[```
import sys
line = sys.stdin.readline()
while line != "":
…
line = sys.stdin.readline()
```],
[lire les données de STDIN, ou \
```
import sys
for line in sys.stdin:
…
```],
)
To terminate readline(), when STDIN is read from keyboard, press CTRL-D (CTRL-Z on Windows) #colbreak()
= #smallcaps[Module: string] #h(1fr) import string
#syntaxTable(
[`string.ascii_uppercase`],
[chaîne de caractères pré-initialisée avec `'ABCDEF … XYZ'`],
[`string.ascii_lowercase`],
[chaîne de caractères pré-initialisée avec `'abcdef … xyz'`],
)
= #smallcaps[Module: sys] #h(1fr) import sys
#syntaxTable(
[`sys.stdin.readline()`],
[lit la prochaine ligne de STDIN (`''` si EOF)],
[`sys.maxsize`],
[valeur max. d'un entier en Python (32-bit #ar $2^31$, 64-bit #ar $2^63$)],
[`sys.setrecursionlimit(limit)`],
[définir la profondeur maximale de la pile lors d'appels récursifs],
)
= #smallcaps[Module: copy] #h(1fr) import copy
#syntaxTable(
[`copie = copy.deepcopy(x)`],
[renvoie une copie récursive (ou profonde) de `x` (= copie de l'objet et copies des objet trouvés dans l'objet original) ],
)
= #smallcaps[MODULES ET LIBRAIRIES (PACKAGES)]
== Modules
#ar fichiers dans lesquels on regroupe différentes fonctions
#syntaxTable(columns:(1fr, 1fr),
[+ créer un fichier (module) contenant des fonctions \
+ dans un 2e fichier utiliser : import module],
[#ar utiliser les fonctions du module\
*Attention* : lors de modifications dans le module, il faut d'abord supprimer le fichier avec l'extension `.pyc` dans le dossier : `__pycache__`],
)
== Librairies (packages)
#ar dossier complet pour gérer les modules, peuvent contenir d'autres dossiers \
#ar dossier principal doit contenir le fichier vide nommé `__init__.py`
#syntaxTable(
[+ créer un dossier \
+ ajouter des modules \
+ créer le fichier vide `__init__.py` dans le dossier],
[#ar créer une librairie],
)
== Installer des librairies (packages) externes
=== PyCharm
#ar `File` -> `Settings` -> `Project:` votre projet actuel \
#ar Sélectionner l'interprétateur Python (p.ex. 3.6.1), puis cliquer sur le symbole + à droite \
#ar Choisir libraire à installer dans la liste (cocher "Install to user's site packages directory" si pas administrateur)
=== Thonny
#ar `Tools` -> `Manage Packages…` \
#ar Entrez le nom de la librairie pour la rechercher et cliquer sur Install
= #smallcaps[Package : pillow] #h(1fr) from PIL import image
Module : Image (#link("https://pillow.readthedocs.io/en/5.1.x/"))
#syntaxTable(
[`PIL.Image.open(fp, mode="r")`],
[ouvre l'image fp et retourne un objet Image],
[`PIL.Image.new(mode, size, color=0)`],
[crée un nouveau objet image et le retourne
- mode : `'RGB'` #ar 3x8 bit pixels, true color
- `size` = uplet (largeur, hauteur)],
[`Image.crop(box=None)`],
[retourne une région rectangulaire
- box = uplet (left, upper, right, lower)],
[`Image.paste(im, box=None, mask=None)`],
[copie l'image `im` sur cet image
- box = uplet (left, upper) ou (left, upper, right, lower)],
[`Image.save(fp, format=None, **params)`],
[enregistre l'image sous le nom `fp`],
)
= #smallcaps[Programmation orienté objet (POO)]
OOP = object oriented programming, Python = langage orienté objet hybride
== Objet
Objet = structure de données valuées et cachées qui répond à un ensemble de messages
- *attributs* = données/champs qui décrivent la structure interne
- *interface de l'objet* = ensemble des messages
- *méthodes* = réponse à la réception d'un message par un objet
*Principe d'encapsulation* #ar certains attributs/méthodes sont cachés
- *Partie publique* #ar visible et accessible par tous
- *Partie privée* #ar seulement accessible et utilisable par les fonctions membres de l'objet (invisible et inaccessible en dehors de l'objet)
*Principe de masquage d'information* #ar cacher comment l'objet est implémenté, seul son interface publique est accessible.
== Classe (= définition d'un objet)
Instanciation #ar création d'un objet à partir d'une classe existante (chaque objet occupe une place dans la mémoire de l'ordinateur)
#syntaxTable(
[```
class ClassName:
def __init__(self, par1, … par_n):
self.var1 = …
self.var2 = …
def __str__(self):
…
return chaîne_de_texte
def method1(self, …):
…
return result
```],
[définit la classe `ClassName` (CamelCase) \
les fonctions sont appelées *méthodes*
- `__init__()` #ar constructeur, appelé lors de l'instanciation
- `__str__(self)` #ar string representation of object, e.g. `print(object)`
- `self` doit être le 1er paramètre et référencie la classe elle-même
- `self.var…` #ar attributs, accessibles de l'extérieur
- `method…()` #ar méthodes, accessible de l'extérieur
*Convention* : utiliser le préfix (`_`) si des attributs ou méthodes ne doivent pas être accédés de l'extérieur (même s'ils sont toujours accessibles)
],
[`obj = ClassName(…)`],
[instancie un nouvel objet de la classe dans la mémoire],
[`obj.method(…)`],
[appel de la méthode de l'objet (self = `obj` est toujours passé comme 1er paramètre)],
)
= Récursivité
- Algorithme récursif #ar algorithme qui fait appel(s) à lui-même
- Attention : il faut prévoir une condition d'arrêt (= cas de base)
- Pour changer la limite max. de récursions #ar voir module *sys*
#colbreak()
= #smallcaps[Pygame] #h(1fr) #smallcaps[bibliothèque pour créer des jeux]
== Structure d'un programme Pygame
#syntaxTable(
[```
import pygame, sys
from pygame.locals import *
pygame.init()
```],
[`# Initialisation` \
importer les librairies et initialiser les modules de pygame
],
[```
WIDTH = …
HEIGHT = …
size = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(size)
```],
[`# Création de la surface de dessin` \
définir la largeur (0…WIDTH-1) et la hauteur (0…HEIGHT-1) de la fenêtre
et retourner un objet de type `surface`
],
[`pygame.display.set_caption(str)`],
[`# Titre de la fenêtre` \
définir le titre de la fenêtre
],
[`screen.fill(color)`],
[`# Effacer surface de dessin` \
remplir arrière-plan avec couleur
],
[```
FPS = frequence # en Hz
clock = pygame.time.Clock()
```],
[`# Fréquence d'image` \
créer l'objet `clock` avant la boucle
],
[```
done = False
while not done:
```],
[`# Boucle principale` \
boucle principale (infinie)
],
[```
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == <type d'événement>:
<instruction(s)>
…
```],
[`# Gestion des événements` \
*Event loop*
- Gestion de tous les événements dans une seule boucle `for` à l'intérieur de la boucle principale.
- Toutes les instructions `if` doivent être regroupées dans une seule boucle `for`
],
[```
… dessins …
# mise à jour de l'écran
pygame.display.update()
```],
[],
[```
# Fréquence d'image
clock.tick(FPS)
```],
[insère des pauses pour respecter FPS (appel à la fin de la boucle principale)
],
[```
pygame.quit()
sys.exit()
```],
[`# Fermer la fenêtre et quitter le programme`],
)
== Types d'événements #h(1fr) #link("https://www.pygame.org/docs/ref/event.html")
Événement de terminaison
#syntaxTable(
[```
QUIT
if event.type == QUIT:
…
```],
[L'utilisateur a cliqué sur la croix de fermeture de la fenêtre. \
Pour terminer correctement, utiliser : \
` pygame.quit()` #quad et #quad `sys.exit()`
],
)
Événements - clavier #h(1fr) #link("https://www.pygame.org/docs/ref/key.html")
#syntaxTable(
[```
KEYDOWN / KEYUP
if event.type == KEYUP:
```],
[une touche du clavier est enfoncée / relâchée \
#ar `event.key`, `event.mod`
],
[```
if event.key == K_a:
…
```],
[indique quelle touche a été enfoncée \
`K_a`, `K_b`, … #h(1fr) touche a, b,… (pareil pour le reste de l'alphabet) \
`K_0`, `K_1`, … #h(1fr) touche 0, 1, … en haut (pareil pour les autres chiffres) \
`K_KP0`, `K_KP1`, … #h(1fr) touche 0, 1, … sur pavé numérique (pareil …) \
`K_LALT`, `K_RALT` #h(1fr) touche ALT (à gauche | à droite) \
`K_LSHIFT`, `K_RSHIFT` #h(1fr) touche SHIFT (à gauche | à droite) \
`K_LCTRL`, `K_RCTRL` #h(1fr) touche CONTROL (à gauche | à droite) \
`K_SPACE` #h(1fr) touche espace \
`K_RETURN` #h(1fr) touche ENTER \
`K_ESCAPE` #h(1fr) touche d'échappement \
`K_UP`, `K_DOWN`, `K_LEFT`, `K_RIGHT` #h(1fr) touches flèches \
`KMOD_NONE` #h(1fr) no modifier keys pressed \
#h(1fr) (can be used to reset pressed keys on KEYUP)
],
)
#syntaxTable(
[```
keys = pygame.key.get_pressed()
if keys[K_LEFT] and not keys[K_RIGHT]:
…
```],
[renvoie dictionnaire de toutes les touches pressées
(rafraichir avec #ar `pygame.event.get()`) \
p. ex. faire une action aussi longtemps que la touche flèche #al est enfoncée],
)
Événements – souris #h(1fr) #link("https://www.pygame.org/docs/ref/mouse.html")
#syntaxTable(
[```
MOUSEBUTTONDOWN
MOUSEBUTTONUP
```],
[un bouton de la souris a été enfoncé / relâché \
#ar `event.pos`, `event.button`],
[```
MOUSEMOTION
if event.type == MOUSE…
```],
[la souris a été déplacée \
#ar `event.pos`, `event.rel`, `event.buttons`],
)
Boutons de la souris
#syntaxTable(
[`if event.button == 1:`],
[indique quel bouton a déclenché l'événement \
1 = left, 2 = middle, 3 = right, 4 = scroll-up, 5 = scroll-down],
[`pygame.mouse.get_pressed()`],
[retourne séquence de 3 valeurs pour l'état des 3 boutons de la souris (de gauche à droite), `True` si enfoncé. Ex. : \
`if pygame.mouse.get_pressed() == (True, False, False):`],
[```
event.buttons
if event.buttons[0]: # left b.?
```],
[#ar tuple for (left, middle, right) mouse buttons \
Ex. : (1,0,0) #ar value 1 if pressed, else 0],
)
Position de la souris
#syntaxTable(
[`(x, y) = event.pos`],
[position du pointeur de souris à l'instant de l'événement],
[`(x, y) = pygame.mouse.get_pos()`],
[position actuelle du pointeur de souris (uplet)],
)
#grid(
columns: (auto, 1fr), // 2 means 2 auto-sized columns
gutter: 2mm, // space between columns
[== La surface de dessin
Origine (0,0) = point supérieur gauche
- largeur de `0` … `WIDTH-1`
- hauteur de `0` … `HEIGHT-1`
],
align(right)[#image("inc/pygame_screen.svg", width: 2.8cm)],
)
Dimensions de la surface de dessin
#syntaxTable(
[`screen = pygame.display.get_surface()`],
[retourne la surface de dessin],
[`screen.get_width()`],
[retourne la largeur de la surface de dessin],
[`screen.get_height()`],
[retourne la hauteur de la surface de dessin],
[`w, h = screen.get_size()`],
[retourne les dimensions de la surface de dessin sous forme d'uplet],
)
Couleurs
#syntaxTable(
[```
color = Color(name)
color = name
```],
[renvoie la couleur du nom `name` (String), ex.: \
`"white"`, `"black"`, `"green"`, `"red"`, `"blue"`],
[`color = Color(red, green, blue)`],
[`red`, `green`, `blue` = nombres de 0 … 255],
)
Obtenir la couleur d'un point (pixel)
#syntaxTable(
[`color = screen.get_at((x, y))`],
[retourne la couleur du point (pixel) à la position indiquée],
)
Effacer/Remplir surface de dessin
#syntaxTable(
[`screen.fill("black")` #quad `screen.fill(Color("black"))`],
[remplir arrière-plan en noir],
[`screen.fill("white")` #quad `screen.fill(Color("white"))`],
[remplir arrière-plan en blanc],
)
Dessiner une ligne/un point sur la surface (`screen`)
#syntaxTable(
columns: (1fr, 1fr),
colspanx(2)[`pygame.draw.line(screen, color, start_point, end_point[, width])`], (),
colspanx(2)[- dessiner un point si `start_point` = `end_point`
- `start_point` et `end_point` sont inclus
- `width` = 1 par défaut], (),
[`screen.set_at((x, y), color )`],
[dessiner un point (pixel) à la position `(x, y)`],
)
Dessiner un rectangle sur la surface (`screen`)
#syntaxTable(
columns:(1fr),
[`pygame.draw.rect(screen, color, rect_tuple[, width])`],
[- `rect_tuple = (x, y, width, height)` avec `x`, `y` = coin supérieur gauche
- ou `rect_tuple = pygame.Rect(x, y, width, height)`
- `width = 0` par défaut (= rectangle plein)],
)
Dessiner une ellipse inscrite dans le rectangle bounding_rect sur la surface (`screen`)
#syntaxTable(columns:(1fr),
[`pygame.draw.ellipse(screen, color, bounding_rect[, width])`],
[- `bounding_rect = (x, y, width, height)` avec `x`, `y` = coin supérieur gauche
- ou `rect_tuple = pygame.Rect(x, y, width, height)`
- `width = 0` par défaut (= ellipse pleine)],
)
Dessiner un cercle sur la surface (`screen`)
#syntaxTable(columns:(1fr),
[`pygame.draw.circle(screen, color, center_point, radius[, width])`],
[- `center_point` = centre du cercle
- `radius` = rayon
- `width = 0` par défaut (= cercle plein)],
)
#grid(
columns: (auto, 1fr), // 2 means 2 auto-sized columns
gutter: 2mm, // space between columns
// inset: (x:0pt, y:0pt),
[Remarque : `rect_tuple` et `bounding_rect`
- coordonnées du point supérieur gauche : (`x`, `y`)
- coordonnées du point inférieur droit : (`x+width-1`, `y+height-1`)
],
align(right)[#image("inc/pygame_rect.svg", width: 3cm)],
)
== Mise à jour de la surface de dessin
#syntaxTable(
[```
pygame.display.update()
pygame.display.flip()
```],
[rafraîchir la surface de dessin pour afficher les dessins],
[`pygame.display.update(rect)`],
[rafraîchir que la partie `rect` = pygame.Rect(x, y, width, height)],
)
== Gestion du temps (fréquence de rafraîchissement)
avant la boucle principale
#syntaxTable(
[`FPS = frequence`],
[définir fréquence de rafraîchissement en Hz],
[`clock = pygame.time.Clock()`],
[créer un objet de type Clock],
)
à la fin de la boucle principale (après la mise à jour de la surface de dessin)
#syntaxTable(
[`clock.tick(FPS)`],
[insérer des pauses pour respecter la fréquence voulue],
)
== pygame.Rect
#syntaxTable(
[```
rect = Rect(left, top, width, height)
rect = Rect((left, top), (width, height))
```],
[créer un nouveau objet `Rect`, \
avec `left`, `top` = coin supérieur gauche],
[`rect.normalize()`],
[corrige les dimensions négatives, le rectangle reste en place avec les coordonnées modifiées],
[`rect.move_ip(x, y)`],
[déplace `rect` de x, y pixels (retourne `None`)],
[`rect.move(x, y)`],
[retourne un nouveau `rect` déplacé de x, y pixels],
[`rect.contains(rect2)`],
[retourne `True` si `rect2` est complètement à l'intérieur de `rect`],
[```
rect.collidepoint(x, y)
rect.collidepoint((x, y))
```],
[retourne `True` si le point donné se trouve à l'intérieur de `rect`],
[`rect.colliderect(rect2)`],
[retourne `True` si les 2 rectangles se touchent],
)
== Affichage de textes
#syntaxTable(
[`pygame.font.SysFont(name, `\
` size[, bold, italic])`],
[crée un objet de type Font à partir des polices système (`bold` et `italic` = `False` par défaut)],
[`surface = font.render(text, `\
` antialias, color[, background])`],
[dessine le texte `text` sur une nouvelle surface de dessin et retourne la surface (`background` = `None` par défaut)],
[`screen.blit(source, dest[, area,`\
` special_flags])`],
[copie la surface `source` sur la surface `screen` à la position `dest` (coin sup. gauche)],
[`pygame.display.update()`],
[met à jour la surface de dessin],
)
Exemple:
#syntaxTable(
[```
font = pygame.font.SysFont("comicsansms", 20)
surf_text = font.render("Hello", True, "green")
screen.blit(surf_text, (100, 50))
pygame.display.update()
```],
[crée un objet font \
crée nouvelle surface avec texte \
copie la surface `surf_text` sur `screen` à la position indiquée et mise à jour \
(`dest` indique le coin sup. gauche)
],
)
(`surf_text.get_height()`, `surf_text.get_width()` #ar retourne la largeur/hauteur du texte)
== Divers
#syntaxTable(
[`pygame.time.delay(delay)`],
[interrompre le programme pour un nombre de ms donnés (`delay`) et renvoie le nombre effectif de ms utilisés],
[`pygame.time.ticks()`],
[renvoie le temps en ms depuis l'appel de `pygame.init()`],
)
#colbreak()
= #smallcaps[ASCII codes] #h(1fr) #link("https://theasciicode.com.ar/")
#grid(
columns: 2, // 2 means 2 auto-sized columns
gutter: 2mm, // space between columns
[*ASCII Control characters*], [*ASCII printable characters*],
image("inc/ascii_control_characters.png", height:9cm),
image("inc/ascii_printable_characters.png", height:9cm),
)
*Extended ASCII characters*
#image("inc/ascii_extended_characters.png", height:8cm)
// #syntaxTable(columns: (auto, auto, auto),
// [*00*], [NULL], [(Null character)],
// [*01*], [SOH], [(Start of Header)],
// [*02*], [STX], [(Start of Text)],
// [*03*], [ETX], [(End of Text)],
// [*04*], [EOT], [(End of Transmission)],
// [*05*], [ENQ], [(Enquiry)],
// [*06*], [ACK], [(Acknowledgement)],
// [*07*], [BEL], [(Bell)],
// [*08*], [BS], [(Backspace)],
// [*09*], [HT], [(Horizontal Tab)],
// [*10*], [LF], [(Line feed)],
// [*11*], [VT], [(Vertical Tab)],
// [*12*], [FF], [(Form feed)],
// [*13*], [CR], [(Carriage return)],
// [*14*], [SO], [(Shift Out)],
// [*15*], [SI], [(Shift In)],
// [*16*], [DLE], [(Data link escape)],
// [*17*], [DC1], [(Device control 1)],
// [*18*], [DC2], [(Device control 2)],
// [*19*], [DC3], [(Device control 3)],
// [*20*], [DC4], [(Device control 4)],
// [*21*], [NAK], [(Negative acknowledgement)],
// [*22*], [SYN], [(Synchronous idle)],
// [*23*], [ETB], [(End of transmission block)],
// [*24*], [CAN], [(Cancel)],
// [*25*], [EM], [(End of medium)],
// [*26*], [SUB], [(Substitute)],
// [*27*], [ESC], [(Escape)],
// [*28*], [FS], [(File separator)],
// [*29*], [GS], [(Group separator)],
// [*30*], [RS], [(Record separator)],
// [*31*], [US], [(unit separator)],
// [*127*], [DEL], [(Delete)],
// )
// #syntaxTable(columns:(auto, auto, auto, auto, auto, auto),
// [*32*], [`(space)`], [*64*], [`@`], [*96*], [\`],
// [*33*], [`!`], [*65*], [`A`], [*97*], [`a`],
// [*34*], [`"`], [*66*], [`B`], [*98*], [`b`],
// [*35*], [`#`], [*67*], [`C`], [*99*], [`c`],
// [*36*], [`$`], [*68*], [`D`], [*100*], [`d`],
// [*37*], [`%`], [*69*], [`E`], [*101*], [`e`],
// [*38*], [`&`], [*70*], [`F`], [*102*], [`f`],
// [*39*], [`'`], [*71*], [`G`], [*103*], [`g`],
// [*40*], [`(`], [*72*], [`H`], [*104*], [`h`],
// [*41*], [`)`], [*73*], [`I`], [*105*], [`i`],
// [*42*], [`*`], [*74*], [`J`], [*106*], [`j`],
// [*43*], [`+`], [*75*], [`K`], [*107*], [`k`],
// [*44*], [`,`], [*76*], [`L`], [*108*], [`l`],
// [*45*], [`-`], [*77*], [`M`], [*109*], [`m`],
// [*46*], [`.`], [*78*], [`N`], [*110*], [`n`],
// [*47*], [`/`], [*79*], [`O`], [*111*], [`o`],
// [*48*], [`0`], [*80*], [`P`], [*112*], [`p`],
// [*49*], [`1`], [*81*], [`Q`], [*113*], [`q`],
// [*50*], [`2`], [*82*], [`R`], [*114*], [`r`],
// [*51*], [`3`], [*83*], [`S`], [*115*], [`s`],
// [*52*], [`4`], [*84*], [`T`], [*116*], [`t`],
// [*53*], [`5`], [*85*], [`U`], [*117*], [`u`],
// [*54*], [`6`], [*86*], [`V`], [*118*], [`v`],
// [*55*], [`7`], [*87*], [`W`], [*119*], [`w`],
// [*56*], [`8`], [*88*], [`X`], [*120*], [`x`],
// [*57*], [`9`], [*89*], [`Y`], [*121*], [`y`],
// [*58*], [`:`], [*90*], [`Z`], [*122*], [`z`],
// [*59*], [`;`], [*91*], [`[`], [*123*], [`{`],
// [*60*], [`<`], [*92*], [`\`], [*124*], [`|`],
// [*61*], [`=`], [*93*], [`]`], [*125*], [`}`],
// [*62*], [`>`], [*94*], [`^`], [*126*], [`~`],
// [*63*], [`?`], [*95*], [`_`], [], [``],
// )
- `ord('A')` #ar return integer Unicode code point for char (e.g. 65)
- `chr(65)` #ar return string representing char at that point (e.g. 'A')
= #smallcaps[String constants (module : string)] #h(1fr) import string
#h(1fr)#link("https://docs.python.org/3/library/string.html")
#syntaxTable(
[`string.ascii_lowercase`],
[all lowercase letters : `'abcdefghijklmnopqrstuvwxyz'`],
[`string.ascii_uppercase`],
[all uppercase letters : `'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`],
[`string.ascii_letters`],
[concatenation of the `ascii_lowercase` and `ascii_uppercase` constants],
[`string.digits`],
[the string `'0123456789'`],
[`string.hexdigits`],
[the string `'0123456789abcdefABCDEF'`],
[`string.octdigits`],
[the string `'01234567'`],
[`string.punctuation`],
[string of ASCII punctuation chars : \
``` !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~. ```],
[`string.whitespace`],
[string containing all ASCII whitespace (space, tab, linefeed, return, formfeed, and vertical tab)],
[`string.printable`],
[string of printable ASCII characters (combination of `digits`, `ascii_letters`, `punctuation`, and `whitespace`)],
)
= #smallcaps[Python sets #ar { }]
Set items are unordered, unchangeable and do not allow duplicate values. Items can be added or deleted.
#syntaxTable(
[`s = set()`],
[create empty set],
[`s = {"ap", "ban", "ch"}`],
[create set with items],
)
#colbreak()
= #smallcaps[Pygame colors] #h(1fr)
#h(1fr)#link("https://github.com/pygame/pygame/blob/main/src_py/colordict.py")
//#include("python_refcard_colours_columns.typ")
#import "inc/pygame_colors.typ": colors_gray, colors_all1, colors_all2, colors_all3, colors_grouped, colors_single
== grey0 … grey100 | gray0 … gray100
// grey/gray table
#{
set rect(width: 1.5em, height: 1.5em, stroke:0.5pt+gray)
tablex(
columns: 21, // 2 means 2 auto-sized columns
gutter: 0.8mm, // space between columns
align: center+horizon,
auto-lines: false,
inset: (x: 0em, y: 0em),
..colors_gray.flatten()
)
}
== color, color1, color2, color3, color4 // color table
// color table
#box(height:69em,
columns(3, gutter:1em)[
#set rect(width: 0.8em, height: 1.2em, stroke:0.5pt+gray)
#set text(size:6pt)
#tablex(
columns: 6, // 2 means 2 auto-sized columns
gutter: 0.5mm, // space between columns
align: horizon,
auto-lines: false,
inset: (x: 0em, y: 0em),
..colors_all1.flatten(),
..colors_all2.flatten(),
..colors_all3.flatten(),
)
]
)
// the following code compiles with the warning message:
// layout did not converge within 5 attempts
// #{
// set rect(width: 0.8em, height: 1.2em, stroke:0.5pt+gray)
// let cell = rect.with(width:100%, inset:0pt, stroke:none, height:auto)
// grid(columns: (33%,37%,30%),
// cell[
// #tablex(
// columns: 6,
// gutter: 0.5mm, // space between columns
// align: horizon,
// auto-lines: false,
// inset: (x: 0em, y: 0em),
// ..colors_all1.flatten(),
// )],
// cell[
// #tablex(
// columns: 6,
// gutter: 0.5mm, // space between columns
// align: horizon,
// auto-lines: false,
// inset: (x: 0em, y: 0em),
// ..colors_all2.flatten(),
// )],
// cell[
// #tablex(
// columns: 6,
// gutter: 0.5mm, // space between columns
// align: horizon,
// auto-lines: false,
// inset: (x: 0em, y: 0em),
// ..colors_all3.flatten(),
// )],
// )}
// the following code produces 2 tables, one for grouped colors
// and one for single colors
// #box(height:38em,
// columns(3, gutter:1em)[
// #set rect(width: 0.8em, height: 1.2em, stroke:0.5pt+gray)
// #tablex(
// columns: 6, // 2 means 2 auto-sized columns
// gutter: 0.5mm, // space between columns
// align: horizon,
// auto-lines: false,
// inset: (x: 0em, y: 0em),
// ..colors_grouped.flatten(),
// )
// ]
// )
// #box(height:36.7em,
// columns(3, gutter:1em)[
// //#set rect(width: 0.8em, height: 1.2em, stroke:0.5pt+gray)
// #set rect(width: 1.4em, height: 1.2em, stroke:0.5pt+gray)
// #tablex(
// columns: 2, // 2 means 2 auto-sized columns
// gutter: 0.5mm, // space between columns
// align: horizon,
// auto-lines: false,
// inset: (x: 0em, y: 0em),
// ..colors_single.flatten(),
// )
// ]
// )
= #smallcaps[Écrire une commande python sur plusieurs lignes]
- Utiliser la continuité implicite des lignes au sein des parenthèses/crochets/accolades
- Utiliser en dernier recours le backslash `"\"` (= line break)
#syntaxTable(
[*continuité implicite*],
[*backslash*],
[```
def __init__(self, a, b, c,
d, e, f, g):
```],
[],
[```
output = (a + b + c
+ d + e + f)
```],
[```
output = a + b + c \
+ d + e + f
```],
[```
lst = [a, b, c,
d, e, f]
```],
[],
[```
if (a > 5
and a < 10):
```],
[```
if a > 5 \
and a < 10:
```],
)
= #smallcaps[Divers]
- Distance entre 2 points $P_1(x_1, y_1)$ et $P_2(x_2, y_2)$ :
$d=sqrt((x_1-x_2)+(y_1-y_2))$ |
https://github.com/donghoony/typst_editorial | https://raw.githubusercontent.com/donghoony/typst_editorial/main/problem_title.typ | typst | MIT License | #let tag(_tag) = {
align(bottom)[
#align(right)[
#text(
font: "Consolas",
size: 15pt,
weight: "bold",
fill: rgb("bfbfbf")
)[#_tag]
]
]
}
#let problem_text(number, title, _tag) = {
let title = [
#text(
size: 30pt,
weight: "bold",
fill: rgb("bfbfbf")
)[#number ]
#text(
size: 30pt,
weight: "bold",
fill: black
)[#title]
]
grid(
columns: (70%, 30%),
title,
tag(_tag)
)
} |
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/7e1810-algo_hw/hw4.typ | typst | #import "utils.typ": *
== HW4 (Week 5)
Due: 2024.04.07
=== Question 14.4-2
Give pseudocode to reconstruct an LCS from te completed c table (See Theorem 14.1 Optimal substructure of an LCS) and the original sequences $X = angle.l x_1, x_2, dots.c, x_m angle.r$ and $Y = angle.l y_1, y_2, dots.c y_n angle.r$ in $O(m+n)$ time, without using the b table.
#rev1_note[
Review: 最长公共子序列
考虑状态转移方程:
$
c[i,j] = cases(
c[i-1, j-1] + 1\, & "if" x_i = y_j,
max(c[i-1, j], c[i, j-1])\, & "otherwise"
)
$
通过这个方程, 可以得到最长公共子序列的长度, 但是无法直接得到最长公共子序列的内容. 通过构造一个二维数组 $b$, 可以在 $O(m+n)$ 的时间内得到最长公共子序列的内容:
- 如果 $x_i = y_j$, 那么 $b[i,j] = "TOP_LEFT"$
- 如果 $c[i-1, j] >= c[i, j-1]$, 那么 $b[i,j] = "TOP"$
- 否则, $b[i,j] = "LEFT"$
回溯时, 只需要根据 $b$ 数组的内容, 从 $c[m,n]$ 开始, 依次回溯到 $c[0,0]$, 当 $b$ 为 "TOP_LEFT" 时, 输出 $x_i$, 否则, 根据 $b$ 的内容选择回溯方向.
接下来我们考虑如何不使用 $b$ 数组, 直接输出最长公共子序列的内容.
通过观察, 我们可以发现, 当 $x_i = y_j$ 时, $c[i,j] = c[i-1, j-1] + 1$, 否则, $c[i,j] = max(c[i-1, j], c[i, j-1])$. 这意味着, 当 $x_i = y_j$ 时, $x_i$ 一定在最长公共子序列中, 否则, $x_i$ 一定不在最长公共子序列中.
]
#ans[
Consider the following pseudocode:
```txt
PRINT-LCS(X, Y, i, j, c)
if c[i,j] == 0
return
if X[i] == Y[j]
PRINT-LCS(X, Y, i-1, j-1, c)
print X[i]
else if c[i-1, j] > c[i, j-1]
PRINT-LCS(X, Y, i-1, j)
else
PRINT-LCS(X,Y, i, j-1, c)
```
]
=== Question 14.4-5
Give an $O(n^2)$-time algorithm to find the longest monotonically increasing subsequence of a sequence of $n$ numbers.
#rev1_note[
思路: 给定一个序列 $L$, 复制一份并排序, 记为 $L^'$, $O(n lg n)$ 时间排序 $L$
计算 $L$ 和 $L^'$ 的最长公共子序列, 由于最长公共子序列一定是单调递增的(是 $L^'$ 的子序列), 且最长, 所以最长公共子序列即为 $L$ 的最长单调递增子序列.
特别的, 考虑此问题的一个变种, 如果要求严格递增子序列, 可以对排序结果去重, 然后再计算最长公共子序列.
另一种思路也是 DP, 构建这样一组 $c[n]$, 其中 $c[i]$ 是 $A[1:i]$ 子问题中上升子列的长度, 转移方程:
$
c[i] = max_(j<i) {c[j] + 1 | A[j] < A[i]}
$
]
#ans[
Given a sequence of numbers $L$, make a copy and sort it, let the $L^'$ be the sorted array:
$O(n lg n)$ time to sort $L$
Then consider the following pseudocode:
```txt
PRINT-LCS(X, Y, c)
n = c[X.length, Y.length]
s = new array[n]
i = X.length
j = Y.length
while i > 0 and j > 0
if x[i] == y[j]
s[n] = x[i]
n--
i--
j--
else if c[i - 1, j] >= c[i, j - 1]
i--
else
j--
print s
MEMO-LCS(X, Y, c, b)
m = X.length
n = Y.length
if c[m, n] != 0 or m == 0 or n == 0
return
if x[m] == y[n]
b[m, n] = TOP_LEFT
c[m, n] = MEMO-LCS(X[1..m - 1], Y[1..n - 1], c, b) + 1
else if MEMO-LCS(X[1..m - 1], Y, c, b) >=
MEMO-LCS(X, Y[1..n - 1], c, b)
b[m, n] = TOP
c[m, n] = MEMO-LCS(X[1..m - 1], Y, c, b)
else
b[m, n] = LEFT
c[m, n] = MEMO-LCS(X, Y[1..n - 1], c, b)
c = new array[X.length][Y.length]
b = new array[X.length][Y.length]
MEMO-LCS(X,Y,c,b)
```
Then the porblem could be turned into running LCS on these two lists ($L$ and $L^'$), since the longest common subsequence must be monotone increasing (being subsequence of $L^'$), and longest (the restriction is only on monotone increasing).
The final runtime would be $o(n^2) + O(L."length" * L^'."length") = O(n^2)$.
] |
|
https://github.com/jamesrswift/graceful-genetics | https://raw.githubusercontent.com/jamesrswift/graceful-genetics/main/src/lib.typ | typst | The Unlicense | #import "impl.typ": template |
https://github.com/daskol/typst-templates | https://raw.githubusercontent.com/daskol/typst-templates/main/cvpr/cvpr.typ | typst | MIT License | /**
* cvpr.typ
*
* Templates for Computer Vision and Pattern Recognition Conference (CVPR)
* series.
*/
#import "/cvpr2022.typ": cvpr2022, conf-name, eg, etal, indent
#import "/cvpr2025.typ": cvpr2025, conf-year
/**
* cvpr - Template for Computer Vision and Pattern Recognition Conference
* (CVPR) series.
*
* Args:
* title: Paper title.
* authors: Tuple of author objects and affilation dictionary.
* keywords: Publication keywords (used in PDF metadata).
* date: Creation date (used in PDF metadata).
* abstract: Paper abstract.
* bibliography: Bibliography content. If it is not specified then there is
* not reference section.
* appendix: Content to append after bibliography section.
* accepted: Valid values are `none`, `false`, and `true`. Missing value
* (`none`) is designed to prepare arxiv publication. Default is `false`.
* id: Submission identifier.
* aux: An optional dictionary to adjust conference specific features.
*/
#let cvpr(
title: [],
authors: (),
keywords: (),
date: auto,
abstract: [],
bibliography: none,
appendix: none,
accepted: false,
id: none,
aux: (:),
body,
) = {
show: cvpr2022.with(
title: title,
authors: authors,
keywords: keywords,
date: date,
abstract: abstract,
bibliography: bibliography,
appendix: appendix,
accepted: accepted,
id: id,
aux: aux,
)
body
}
|
https://github.com/msakuta/typst-test | https://raw.githubusercontent.com/msakuta/typst-test/master/neural-network.typ | typst | #import "template.typ": *
#set math.equation(numbering: "(1)")
#set heading(numbering: "1.")
// 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: "Neural Networks",
authors: (
"<NAME>",
),
)
#outline()
= A little bit of history
The history of neural networks is like a series of emerging waves.
It oscillates between periods of hyped and lost interest from the society like @fig:timeline.
#figure(
image("neuralnetwork-timeline.png"),
caption: [A brief timeline of neural networks]
) <fig:timeline>
Its origins can be traced back to the 1940s.
It is based on the formal neuron model proposed by <NAME> and <NAME>, but the most important in history is the perceptron published in 1958 by <NAME>.
However, the perceptron was difficult to scale up with the hardware of the time, and efficient learning methods had not been established, so the learning speed did not reach a practical level.
After that, neural networks entered a dark age for a while, but a brief revival occurred in the 1980s when backpropagation using the sigmoid function was invented.
However, it still entered another dark age again because it did not produce a practical level of performance.
The tide has changed at the 2009 NIPS Workshop, where the Deep Belief Net implemented by <NAME> produced a better score than any other state-of-the-art algorithms at that time.
Around that time, convolutional neural networks were getting popular.
They are good at image recognition in particular.
Since then, artificial intelligence is dominated by deep learning to the point that just the word AI implies deep learning.
#figure(
image("tahc_rosenblatt-sepia.jpg", width: 50%),
caption: [Probably the most famous historical photo of AI history, a portrait of <NAME>]
)
= The model of the Perceptron
The activation function of the first model of perceptron proposed by Rosenblatt was a step function like @eq_step
$ S(x) = cases(1 & 0 < x , 0 & "otherwise") $ <eq_step>
This was because the model of a neuron was thought to have active and inactive states like @step.
#figure(
image("step.png", width: 60%),
caption: [A step function]
) <step>
However, sigmoid function became popular for an activation function since it became clear that derivative is necessary for backpropagation.
This function is advantageous for activation function since it has derivatives over the whole range of input variable, but it doesn't have a basis on real neurons.
A sigmoid function is defined like @eq_sigmoiod and it looks like @sigmoid.
$ sigma(x) = 1 / (1 + e^(-x)) $ <eq_sigmoiod>
#figure(
image("sigmoid.png", width: 60%),
caption: [A sigmoid function]
) <sigmoid>
The sigmoid function is good and smooth, but the output range is fixed between 0 and 1, so it cannot represent an arbitrary function and has an issue called vanishing gradient.
Therefore, the sigmoid function is not without its shortcomings.
As a result, ReLU (Regularized Linear Unit) which is defined as @eq_relu is often used these days.
It looks like @relu.
This function does not require a relatively expensive exponential function, since it is simple combination of identity and constant functions.
Another advantage of it is that it has a value range from $0$ to $infinity$, and the derivative can be defined over the entire range of the variable.
At this point, the analogy of biological neuron is like thrown out of the window.
$ R(x) = cases(x & 0 < x, 0 & "otherwise") $ <eq_relu>
#figure(
image("relu.png", width: 60%),
caption: [A ReLU function]
) <relu>
Note that you could think of the simplest activation function as the identity transformation $f( x ) = x$.
If you use it, however, no matter how deep the neural network architecture you are using, it can be collapsed into a single linear transformation, so it would be incapable of representing nonlinearity.
Also, since the entire network can be collapsed into one linear transformation, there would be no point having intermediate layers.
There are a lot of variants of ReLU, in attempt to overcome the limitation of flat derivative part.
One of them is SiLU (Sigmoid Linear Unit), a sigmoid multiplied by a proportional function.
It looks like ReLU as a whole, but the derivative is not zero over the whole value range.
$ sigma(x) = x / (1 + e^(-x)) $ <eq:silu>
#figure(
image("silu.svg", width: 60%),
caption: [A SiLU function]
) <silu>
= Feed Forward Neural Network
Feedforward simply means transmitting a signal in the forward direction.
For example, consider a simple neural network like @feedforward.
#figure(
image("feedforward.png", width: 50%),
caption: [Feedforward neural network]
) <feedforward>
The input is represented as $s_i ( i = 1 , 2 , ... ,n( 1 ))$, the weights of the first layer as $w^((1))_(i j) ( j = 1 , 2 , ... ,n( 2 ))$, then the signal from the input layer to the hidden layer $s^((1))_j$ is transmitted as @eq_feedforward1.
$ s^((1))_j = f( sum_(i = 1)^n w^((1))_(i j) s_i) $ <eq_feedforward1>
here $f(dot)$ is the activation function described in the previous section.
Furthermore, the weights of the second layer are $w^((2))_(j k)$, the signal in the output layer $s^((2))_k$ becomes
$ s^((2))_k = f( sum_(j = 1)^n w^((2))_(j k) s^((1))_j). $ <eq_feedforward2>
From the discussion so far, it is obvious that the number of hidden layers can be increased arbitrarily.
You could also use matrix multiplication to represent @eq_feedforward1 or @eq_feedforward2.
$ bold(s)^((1)) &= f( W^((1)) bold(s) ) \
bold(s)^((2)) &= f( W^((2)) bold(s)^((1)) ) $
Here, $W$ is a matrix and $bold(s)$ is a column vector.
Parallel computing utilizing GPU is really good at this kind of computation.
There are many math libraries that can do this, such as MATLAB, SciPy, NumPy, and Pandas.
= Bias term
In practice, we often put a constant input in each layer, unaffected by previous layers. These inputs are called biases.
#figure(
image("bias.png", width: 50%),
caption: [A neural network with a bias term]
) <bias>
The usefulness of this is to have constant degrees of freedom in the arguments of the activation function.
For example, Let the last signal in the input layer $s_n$ be a constant value $1$.
Then we can transform @eq_feedforward1 into
$ s^((1))_j = f(w_(0 j) + sum_(i = 1)^n w^((1))_(i j) s_i) $
This is effectively the same as shifting the origin of the activation function by $-w_(0 j)$.
In this way, the offset of the origin can be included in the weight matrix and the offset need not be considered as a separate optimization target.
In Rosenblatt's perceptron, the activation threshold is a separate parameter from the weight, which increases the complexity of multi-layering.
We can also add a bias term to the intermediate layer.
$ s^((2))_k = f(w^((2))_(0 k) + sum_(j = 1)^n w^((2))_(j k) s^((1))_j) $
A more concise way to put it is to include a constant term in the input signal.
So $bold(s)$ will be $(s_1, s_2, ... s_n, 1)$ an we can simply write
$ bold(s)^((1))_j &= f(W^((1)) bold(s)) \
bold(s)^((2))_j &= f(W^((2)) bold(s^((1)))) = f(W^((2)) f(W^((1)) s)) $
= Backpropagation
When training a neural network, a technique called backpropagation is used.
First, let's define the cost function $L$, which is a indication of the magnitude of the deviation from ground truth answer.
This is defined in terms of the ground truth $A_k$ and the predicted answer $s^((2))_k$ as @eq_l.
Here, the reason why the deviation from the ground truth is squared isn't entirely clear, but it will become clear in a later section.
$ L = 1 / 2 sum_k(A_k - s^((2))_k)^2 $ <eq_l>
== Gradient of the Weights on the First Layer
First, let's think about how we can modify the output layer weights $w^((2))_(j k)$ so that the prediction get closer to the correct answer.
It means finding the direction of motion in $bold(w)$ space that decreases $L$, so we can take gradient of $L$ with respect to each element of $bold(w)$.
In other words, compute $(diff L)/(diff w^((2))_(j k))$.
We can use this gradient and the learning rate parameter $delta$ to define the update rule for the $bold(w)$ as @eq_w.
The weight of the next step can be obtained by subtracting the gradient multiplied by $delta$.
$ lr( w^((2))_(j k) |)_(t+1) = lr(w^((2))_(j k)|)_t - delta lr((diff L)/(diff w^((2))_(j k))|)_t $ <eq_w>
This corresponds to the gradient descent method in the optimization problem, and we will discuss later in dropout whether it falls into a local solution in a multifaceted solution space.
Calculating the second term on the right-hand side of @eq_w, from the chain rule of composite functions,
$ - delta (diff L)/(diff w^((2))_(j k)) &= - delta (diff L)/(diff s^((2))_k ) (diff s^((2))_k)/(diff w^((2))_(j k)) \
&= delta (A_k - s^((2))_k) (diff s^((2))_k)/(diff w^((2))_(j k)) $
and can be easily calculated from only the difference between the teacher signal answer and the predicted answer.
Let's focus on the second half $(diff s^((2))_k)/(diff w^((2))_(j k))$.
Since the variables are related with the activation function $f$ through @eq_feedforward2 like below.
we can simplify the calculation by placing an intermediate variable $p^((2))_k$, which is the argument given to $f$.
$ p^((2))_k equiv sum_(j=1)^n w^((2))_(j k) s^((1))_j $ <eq:p>
Here we can use the chain rule again to yield
$ (diff s^((2))_k) / (diff w^((2))_(j k)) = (diff s^((2))_k) / (diff p^((2))_k) (diff p^((2))_k)/(diff w^((2))_(j k)). $
$(diff s^((2))_k)/(diff p^((2))_k)$ is the derivative of the activation function $f'$.
Also we can use
$ (diff p^((2))_k) / (diff w^((2))_(j k)) &= diff / (diff w^((2))_(j k)) sum_(j=1)^n w^((2))_(j k ) s^((1))_j \
&=s^((1))_j $
to represent
$ (diff s^((2))_k) / (diff w^((2))_(j k)) = s^((1))_j f'(p^((2))_k) $
Once again we write the entire @eq_w as
$ lr(w^((2))_(j k)|)_(t+1) = lr(w^((2))_(j k)|)_t + delta (A_k - s^((2))_k) s^((1))_j f'(p^((2))_k) $
From here, it is obvious that backpropagation requires that the activation function can be derived.
Here we can use a little trick when the activation function is a sigmoid function.
$
(diff sigma) / (diff x) &= diff / (diff x) 1 / (1 + e^(-x)) \
&= e^(-x) 1 / (1 + e^(-x))^2 \
&= (1 + e^(-x) - 1) / (1 + e^(-x)) 1/(1 + e^(-x)) \
&= (1 - 1 / (1 + e^(-x))) 1 / (1 + e^(-x)) \
&= (1 - sigma) sigma
$
Using this, @eq_w can be further rewritten as follows:
$ lr(w^((2))_(j k)|)_(t + 1) = lr(w^((2))_(j k)|)_t + delta (A_k - s^((2))_k) s^((1))_j (1 - s^((2))_k) s^((2))_k $
== Backpropagating to the first layer
Now, let's focus on the hidden layer weights $w^((1))_(i j)$.
We can replace the weight of $w^((1))_(i j)$ in @eq_w like below.
$ lr( w^((1))_(i j) |)_(t+1) = lr(w^((1))_(i j)|)_t - delta lr((diff L)/(diff w^((1))_(i j))|)_t $ <eq_w1>
However, the method of applying the chain rule will change.
Since there is an index variable $k$ which is neither the final indices $i, j$,
the whole derivative becomes total derivative, not the partial derivative.
$ (diff L) / (diff w^((1))_(i j)) &= sum_k (diff L) / (diff s^((2))_k) (diff s^((2))_k) / (diff w^((1))_(i j)) \
&= sum_k (diff L) / (diff s^((2))_k) (diff s^((2))_k) / (diff s^((1))_j) (diff s^((1))_j) / (diff w^((1))_(i j)) \
&= sum_k underbracket((diff L) / (diff s^((2))_k), (1))
underbracket((diff s^((2))_k) / (diff p^((2))_k), (2))
underbracket((diff p^((2))_k) / (diff s^((1))_j), (3))
underbracket((diff s^((1))_j) / (diff w^((1))_(i j)), (4)) $
Wow, there are a lot of factors!
Let's disect them into pieces.
(1) we already calculated $(diff L) / (diff s^((2))_k) = A_k - s^((2))_k$.
(2) we already calculated $(diff s^((2))_k) / (diff p^((2))_k) = f'(p^((2))_k)$.
(3) can be calculated using @eq:p.
$ (diff p^((2))_k) / (diff s^((1))_j) &= diff / (diff s^((1))_j) sum_(j = 1)^n w^((2))_(j k) s^((1))_j \
&= w^((2))_(j k) $
In summary, this whole summation can be reused to reduce the computation in the next layer.
Let's call it $L^((1))_j$ for it being the "loss function" for the next layer.
#footnote[Technically, it is a _derivative_ of the loss function, but we don't want to put any more fancy notations.]
Note that it is a vector of $j$ elements.
$ L^((1))_j &equiv sum_(k = 1)^(n_k) (diff L) / (diff s^((2))_k) (diff s^((2))_k) / (diff p^((2))_k) (diff p^((2))_k) / (diff s^((1))_j) \
&= sum_(k = 1)^(n_k) (A_k - s^((2))_k) f'(p^((2))_k) w^((2))_(j k) $
This is the crucial part of the backpropagation.
We are considering a neural network with 2 layers, but you can imagine extending this logic to many layers indefinitely.
Now, we want to calculate (4), but to make them simplier, let's define an intermediate variable like before:
$ p^((1))_j = sum_(i = 1)^n w^((1))_(i j) s_i $
Using this, we can write (4) as
$ (diff s^((1))_j) / (diff w^((1))_(i j)) &= (diff s^((1))_j) / (diff p^((1))_j) (diff p^((1))_j) / (w^((1))_(i j)) \
&= f'(p^((1))_j) diff / (diff w^((1))_(i j)) sum_(i = 1)^n w^((1))_(i j) s_i \
&= s_i f'(p^((1))_j) $
The whole expression becomes
$ (diff L) / (diff w^((1))_(i j)) = L^((1))_j s_i f'(p^((1))_j) $
With a neural network of only few layers, we cannot really feel the benefits of reusing the previous layer's computation.
However, the number of repeated computations grow exponentially as the layers get deeper, so this technique is essential to the large scale deep learning.
The idea of this algorithm is a bit like FFT butterfly operation.
Calculation is performed in order from the output side to the input side, so it is called backpropagation.
= Batch training
Loss function given in @eq_l was the result for only one sample.
If we calculate all $N$ samples together, we get the following (we are running out of space for subscripts,
but the superscript $[l]$ indicates the $l$th sample):
$ L = 1/2 sum_(l = 1)^N ∑_k (A_k^[ l ] - s_k^((2) [ l ]))^2 $
Since the partial derivatives are independent for each sample, the second term of the right side of @eq_w is as follows.
$ -delta (diff L) / (diff w^((2))_(j k)) &= -delta sum_(l = 1)^N (diff L) / (diff s^((2) [l])_k) (diff s^((2) [l])_k) / (diff w^((2))_(j k)) \
&= -delta sum_(l = 1)^N (A_k - s^((2) [l])_k) (diff s^((2) [l])_k) / (diff w^((2))_(j k)) \
&= -delta sum_(l = 1)^N (A_k - s^((2) [l])_k) s^((1) [l])_j f'(sum_(j = 1)^N w^((2))_(j k) s^((1) [l])_j) $
It is obvious that the gradient of the hidden layer can be calculated in the same way.
Batch training is a method of determining the gradient direction from the loss functions of multiple samples at once.
On the other hand, as we saw in the previous section, calculating the gradient direction from each sample one by one is called online training or stochastic gradient descent.
There is also a method called mini-batch, where you train repeatedly with a sample size in bite-sized chunks.
Each has advantages and disadvantages as described below.
- Batch training has high stability and fast convergence because it descends a gradient that smoothes the data with variability.
- Online training is swayed by noise in individual data, so convergence is poor, but it can be applied to very large training data that cannot be stored in memory.
= Appendix
== All You Need to Know about Derivatives
You should know a little calculus to understand how neural networks work (or any machine learning algorithms in that regard).
Your high school should have taught you about it, but the world is a diverse place now and I don't know if you had that opportunity.
#footnote[Surprisingly many people don't have a clear idea of basic calculus, even in the field of AI research.
I hope the reader is not one of them, or quit being an imposter like them.]
I have tried to teach how the machine learning works to several people, and found out that some people have really hard time understanding it.
Right now my theory why is that these people didn't understand basic math including calculus.
=== Ordinary derivatives
The definition of derivative is as follows:
$ (d f) / (d x) = lim_(epsilon -> 0) (f(x + epsilon) - f(x)) / epsilon $ <eq:derive>
The notion like $(d f)/(d x)$ was invented by Leibniz, who is also credited as one of the inventors of the calculus.
The other person in credit that invented calculus at the same time (how that could happen was an interesting story for another time) is Newton.
He also invented his version of notation, like $dot(f)$.
It is sometimes written as $f'$ too, although I don't know who invented it.
The Leibniz notation has an advantage that it indicates a variable that derive $f$ with respect to.
It is especially handy with partial derivatives.
The Newton notation implies that the function is derived with respect to time variable, so it has limits when you want to apply it to other variables.
Let's do some exercies with basic functions.
Consider a function @eq:square.
$ f(x) = x^2 $ <eq:square>
Let's put it into @eq:derive.
$ (d f) / (d x) = lim_(epsilon -> 0) ((x + epsilon)^2 - x^2) / epsilon $
You can calculate the denominator inside the limit as follows:
$ (x + epsilon)^2 - x^2 &= x^2 + 2 epsilon x + epsilon^2 - x^2 \
&= epsilon (2 x + epsilon)
$
Now, we can reduce the $epsilon$ to 0, since nothing is in the factor of $epsilon$.
$ (d f) / (d x) = lim_(epsilon -> 0) (2 x + epsilon) = 2 x $
You won't calculate the derivatives like this every time, but you can find tables of derivatives of common functions on the web.
Basic ones like polynomials are worth memorizing since they are not too complex.
$ (d x^n) / (d x) = n x^(n-1) $
Another important technique to calculate derivatives is the chain rule.
Suppose we had a function $f(x)$ which is in turn a variable of another function $g(f(x))$.
Then we can calculate the derivative of $g$ with respect to $x$ using this "chain of derivatives".
$ (d g) / (d x) = (d g) / (d f) (d f) / (d x) $
It is not very clear with this abstract notation, so let's use an example functions like below.
$ g(f) &= f^2 \
f(x) &= x + a $
Here, $a$ is a constant.
We can calculate the derivative of each function like below.
$ (d g) / (d f) &= 2f \
(d f) / (d x) &= x $
So the result of the whole derivative is:
$ (d g) / (d x) = 2x (x + a) $
Remember that you can define the intermediate function however you like.
So if your function is given like this:
$ g(x) = (x + a)^2 $
you can see that you can define an intermediate function $f(x) = x + a$.
This is one of the most basic technique to derive a complicated function.
There are few other techniques like derivative of products, but I won't go into details.
=== Partial derivatives
Partial derivatives are derivatives on a function with multiple independent variables.
For example, suppose we have a function with 2 variables, $f(x, y)$.
The notion of each partial derivative with respect to each variable is like below.
$ (diff f) / (diff x), (diff f) / (diff y) $
When you compute a partial derivative, you fix the other variables as if they were constants.
For example, let's take a function like below.
$ f(x, y) = x^2 + y^2 $
Partial derivatives are calculated like below.
$ (diff f) / (diff x) = 2 x, (diff f) / (diff y) = 2 y $
=== Total derivatives
A less known variant of derivatives is called total derivatives.
It is a derivative of a function with multiple variables, like partial derivatives, but it incorporates both variables.
$ d f = (diff f) / (diff x) d x + (diff f) / (diff y) d y $
The notable thing about total derivatives is that it doesn't specify a derived variable.
In a sense, it is a template of derivatives that can adapt to any variable.
It is useful when the variables $x, y$ are not independent.
For example, if they are both dependent on the third variable, $z$, we can write like $x(z), y(z)$.
Then, we can calculate like below:
$ (d f) / (d z) = (diff f) / (diff x) (d x) / (d z) + (diff f) / (diff y) (d y) / (d z) $
Another way to put it is that it is kind of a version of chain rule with multiple variables.
=== Conclusion
As you can see, the value of derivative is that it reduces the idea of taking limits (which drives minds crazy) into mere manipulation of symbols.
It is one of the most successful mathematical tools and still a valuable tool in the age of computers to analyze complicated models in the world, as you are witnessing with deep learning.
|
|
https://github.com/david-davies/typst-prooftree | https://raw.githubusercontent.com/david-davies/typst-prooftree/main/src/utils.typ | typst | MIT License | /*************************************************************************************************/
// Type utils
#let is_none(x) = type(x) == "none"
#let is_not_none(x) = not is_none(x)
#let is_bool(x) = type(x) == "bool"
#let is_func(f) = type(f) == "function"
#let default_if_none(x, default) = if is_none(x) {default} else {x}
#let apply_if_func(f, x) = if is_func(f) {f(x)} else {f}
#let guard(x, ..tests, default: none) = {
for (t, then) in tests.pos() {
if (
(is_func(t) and t(x))
or (not is_bool(x) and is_bool(t) and t)
or x == t
) {
then
}
}
default
}
#let when_not_none(val, f) = if is_not_none(val) {f}
#let with_maybe(default: none, val, f) = {
if is_none(val) {
f(default)
} else {
f(val)
}
}
#let from_none(val, default) = {
if is_none(val) {default}
else {val}
}
/*************************************************************************************************/
// Measurement utils
#let content_size(body, then_do) = style(styles => {
let size = measure(body, styles)
then_do(size)
})
#let maybe_content_size(m_body, then_do) = {
if is_none(m_body) {
then_do(0pt)
} else {
content_size(m_body, then_do)
}
}
// Gets the sizes of contents
#let contents_size(..contents, then_do) = style(styles => {
let sizes = contents.pos().map(c => measure(c, styles))
then_do(sizes)
})
/// Typst doesn't let us use keyword arguments on function calls if the corresponding parameter
/// doesn't have a default value.
/// Some functions have many arguments with no defaults, so they are annoted with `__kw_arg`,
/// implementing a builder-like pattern.
#let __kw_arg = none
#let __check_kw_args(..args) = args.pos().map(is_not_none)
|
https://github.com/jneug/schule-typst | https://raw.githubusercontent.com/jneug/schule-typst/main/src/subjects/cs-erd.typ | typst | MIT License | #import "@preview/fletcher:0.5.0"
#let connect(from, to, c: none) = {
(
(
type: "edge",
from: from,
to: to,
id: repr(from) + "-" + repr(to),
c: c,
func: fletcher.edge,
),
)
}
#let entity(pos, id, content) = {
(
(
type: "entity",
pos: pos,
id: id,
content: content,
func: fletcher.node,
),
)
}
#let attribute(pos, id, content, to: none) = {
let r = (
(
type: "attribute",
pos: pos,
id: id,
content: content,
func: fletcher.node.with(shape: fletcher.shapes.pill),
),
)
if to != none {
r.push(connect(id, to).first())
}
return r
}
#let relation(pos, id, e1: none, c1: none, e2: none, c2: none, content) = {
let r = (
(
type: "relation",
pos: pos,
id: id,
content: content,
from: e1,
to: e1,
c1: c1,
c2: c2,
func: fletcher.node.with(shape: fletcher.shapes.diamond),
),
)
if e1 != none and e2 != none {
r.push(connect(e1, id, c: c1).first())
r.push(connect(e2, id, c: c2).first())
}
return r
}
#let erd(
width: auto, //100%,
height: auto,
padding: 5pt,
inset: 6mm,
fill: white,
stroke: 1.2pt + black,
unit: 1cm,
..fletcher-args,
elements
) = {
let nodes = (:)
for elem in elements {
nodes.insert(elem.id, elem)
}
let resolve(pos) = {
while type(pos) == str {
pos = nodes.at(pos).pos
}
return pos
}
let f-elements = ()
for (id, node) in nodes {
if node.type == "edge" {
node.from = resolve(node.from)
node.to = resolve(node.to)
f-elements.push((node.func)(node.from, node.to, label: node.c, label-pos: .33, label-side: left))
} else {
node.pos = resolve(node.pos)
f-elements.push((node.func)(node.pos, node.content))
}
}
fletcher.diagram(
node-stroke: stroke,
edge-stroke: stroke,
node-inset: inset,
spacing: (unit, unit),
crossing-fill: none,
..fletcher-args.named(),
..f-elements,
)
}
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/chronos/0.1.0/src/lib.typ | typst | Apache License 2.0 | #import "diagram.typ": diagram, from-plantuml, _gap, _evt
#import "sequence.typ": _seq
#import "group.typ": _grp
#import "participant.typ": _par
#import "separator.typ": _sep
#import "note.typ": _note
#import "sync.typ": _sync |
https://github.com/piepert/philodidaktik-hro-phf-ifp | https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/spue/anforderungen/main.typ | typst | Other | #import "/src/template.typ": *
= Allgemeine Hinweise für den Unterricht
#author[<NAME>]
Das Ziel der SPÜ ist das erfolgreiche Vorbereiten, Durchführen und Nachbereiten einer philosophischen Bildungsstituation. Dafür ist vor dem Unterricht ein Kurzentwurf, ein Langentwurf und nach dem Unterricht eine Reflexion abzugeben. Dazu kommt das Durchführen der Unterrichtsstunde an sich. Hier folgen einige allgemeine Hinweise zu Anforderungen an den Unterricht. Die Hinweise ergeben sich aus dem Ziel der SPÜ, nach deren eine _erfolgreiche_ und _philosophische_ Bildungssituation vorbereitet, durchgeführt und nachbereitet werden soll. Hier soll sich besonders auf den Aspekt konzentriert werden, was _philosophischer_ und was _erfolgreicher_ Unterricht ist. Der Aspekt der Vor- und Nachbereitung soll später besprochen werden. *Nehmen Sie die Handouts zur Kenntnis, die Ihnen in der Vorbereitungssitzung zur Verfügung gestellt werden, sie sind hilfreich!*
#include "erfolgreicher_unterricht.typ"
#include "philosophischer_unterricht.typ"
#include "checkliste_unterricht.typ" |
https://github.com/typst-jp/typst-jp.github.io | https://raw.githubusercontent.com/typst-jp/typst-jp.github.io/main/.devcontainer/README.md | markdown | Apache License 2.0 | # ローカル環境を構築するDockerfile
[Docker](https://docs.docker.com/)を用いてWebページの仕上がりを確認できます。
以下の操作はDockerがインストール済み、かつDockerデーモンを起動していることが前提となります。
## VS Codeを使用している場合
[Dev Container](https://code.visualstudio.com/docs/devcontainers/containers)を使用します。
Visual Studio Codeでtypst-jp.github.ioディレクトリを開き、以下の操作を実施してください。
1. Ctrl+Shift+Pから`> Dev Containers: Reopen in Container`を実行
2. Webサーバーが起動したらブラウザで http://localhost:3000 に接続
3. ページを更新した際には、Ctrl+Shift+Pから`> Tasks: Run task`を実行し`gen: typst-jp documentation`を選択。ビルドが完了したらブラウザを更新。
## 別のエディターを使用している場合
ターミナルからDockerfileをビルドして、コマンド実行します。
typst-jp.github.io ディレクトリ上で以下のコマンドを実行してください。
1. Docker imageをビルドしてコンテナを作成
```
docker build . -f .devcontainer/Dockerfile -t typst-jp-doc
docker run --name typst-jp-doc -p 3000:3000 -it -v "$(pwd):/workspace" -w /workspace --rm typst-jp-doc /bin/bash
```
2. Dockerコンテナ内でページを生成
```
cargo test --package typst-docs --lib -- tests::test_docs --exact --nocapture && python3 ./gen.py && npx serve -n ./dist
```
3. Webサーバーが起動したらブラウザで http://localhost:3000 に接続
4. ファイルを更新した際には、2 のコマンドを一旦 Ctrl+C で終了して再度実行、その後ブラウザを更新。
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/mecanique_quantique.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Mécanique Quantique",
authors: (
"Lucas",
),
date: "26 Mars, 2023",
)
// We generated the example code below so you can see how
// your document will look. Go ahead and replace it with
// your own content!
#set heading(numbering: "1.1.")
= Introduction<Introduction>
La mécanique quantique est une théorie fondamentale de la physique qui décrit les propriétés physiques de la nature à l'échelle des atomes et des particules subatomiques. Elle est le fondement de toute la physique quantique, y compris la chimie quantique, la théorie quantique des champs, la technologie quantique et la science de l'information quantique.
La mécanique quantique diffère de la physique classique à bien des égards, notamment :
- La quantification : en mécanique quantique, l'énergie, la quantité de mouvement, le moment angulaire et d'autres quantités sont souvent limités à des valeurs discrètes.
- La dualité onde-particule : les objets ont des caractéristiques à la fois de particules et d'ondes.
- Le principe d'incertitude : étant donné un ensemble complet de conditions initiales, il existe des limites à la précision avec laquelle la valeur d'une quantité physique peut être prédite avant sa mesure.
- L'intrication quantique : des objets peuvent être liés entre eux de telle sorte qu'ils partagent le même destin, même s'ils sont séparés par une grande distance.
La mécanique quantique a joué un rôle important dans le développement de nombreuses technologies modernes, notamment les lasers, les transistors et les armes nucléaires. Elle est également essentielle pour comprendre de nombreux processus fondamentaux dans la nature, tels que le comportement des atomes et des molécules, la structure des matériaux et la nature de la lumière.
Ce cours propose une introduction aux concepts de base de la mécanique quantique. Nous discuterons de la fonction d'onde, de l'équation de Schrödinger et du principe d'incertitude. Nous aborderons aussi certaines applications de la mécanique quantique, telles que les lasers et les transistors.
= Cours associés <A>
- #link("lagrange.pdf", "Mécanique de Lagrange")
- #link("champs_quantiques.pdf", "La théorie des champs quantiques")
= Histoire
== Quanta
Un quanta est la plus petite unité d'énergie pouvant être absorbée ou émise. C'est la particule fondamentale de la lumière, et c'est aussi l'énergie transportée par d'autres particules, telles que les électrons et les protons.
L'histoire de la découverte des quanta est longue et sinueuse. Le premier soupçon d'existence d'un quanta est apparu au début des années 1900, lorsque les physiciens étudiaient le comportement de la lumière. Ils ont découvert que la lumière pouvait être émise en unités discrètes et que ces unités étaient proportionnelles à la fréquence de la lumière. Cette découverte a conduit au développement de la théorie quantique, qui est la branche de la physique qui traite du comportement de la matière et de l'énergie au niveau atomique et subatomique.
La théorie quantique a révolutionné notre compréhension de l'univers et a conduit au développement de nombreuses nouvelles technologies, telles que les lasers et l'énergie nucléaire. Il s'agit toujours d'un domaine de recherche actif, et les scientifiques apprennent constamment de nouvelles choses sur le fonctionnement des quanta.
Le terme "quanta" a été utilisé pour la première fois en 1905 par <NAME>, un physicien allemand. Planck essayait d'expliquer le spectre de rayonnement du corps noir, c'est-à-dire la distribution de l'énergie émise par un corps noir à différentes longueurs d'onde. Il a découvert qu'il ne pouvait expliquer le spectre que s'il supposait que la lumière était émise en unités discrètes, qu'il a appelées quanta.
== Dualité onde-corpuscule
La dualité onde-particule est le concept de la mécanique quantique selon lequel toute particule ou entité quantique peut être décrite soit comme une onde, soit comme une particule. Elle exprime l'incapacité des concepts classiques de "particule" ou d'"onde" à décrire pleinement le comportement des objets à l'échelle quantique. Comme l'a écrit <NAME> : "Il semble que nous devions utiliser tantôt l'une, tantôt l'autre théorie, et tantôt l'une ou l'autre. Nous sommes confrontés à un nouveau type de difficulté. Nous avons deux images contradictoires de la réalité ; séparément, aucune d'entre elles n'explique totalement les phénomènes lumineux, mais ensemble, elles le font.
La dualité onde-particule a été découverte pour la première fois par le physicien français Louis de Broglie en 1924. <NAME> a proposé que toutes les particules aient une longueur d'onde, et que cette longueur d'onde soit inversement proportionnelle à l'élan de la particule. En d'autres termes, plus la longueur d'onde est courte, plus l'élan de la particule est important.
L'hypothèse de <NAME> a été confirmée par l'expérience de Davisson-Germer en 1927. Dans cette expérience, un faisceau d'électrons a été diffusé à partir d'un cristal. On a constaté que les électrons interféraient les uns avec les autres, comme le feraient des ondes. Cette expérience a confirmé que les électrons peuvent se comporter comme des ondes.
La dualité onde-particule est l'un des concepts les plus importants de la mécanique quantique. Elle est à la base de nombreux effets étranges observés dans le monde quantique, tels que l'effet tunnel quantique et l'intrication quantique.
#figure(
image("twosource.gif", width: 80%),
caption: [
Image d'une onde dans l'expérience de la double fente
],
)
Cette image montre comment une onde peut interférer avec elle-même. Les ondes sont représentées par les lignes bleues. Les zones bleu clair représentent les zones où les ondes sont en phase, et les zones bleu foncé représentent les zones dans lesquelles les ondes sont déphasées. Comme vous pouvez le voir, les ondes peuvent interférer les unes avec les autres pour créer des motifs clairs et sombres.
C'est un bon exemple de la façon dont les ondes peuvent se comporter comme des particules. Les ondes de cette image sont en fait des électrons qui interfèrent les uns avec les autres pour créer un motif. Ce n'est qu'un exemple de la manière dont la dualité onde-particule se manifeste dans le monde quantique.
== Le problème de la mesure
Le problème de la mesure est un problème fondamental de la mécanique quantique. Il s'agit de réconcilier la fonction d'onde d'un système quantique avec les résultats des mesures classiques. La fonction d'onde d'un système quantique est une fonction mathématique qui décrit l'état du système. Les résultats des mesures sont les valeurs que nous observons lorsque nous mesurons le système.
L'effondrement de la fonction d'onde est le processus par lequel la fonction d'onde d'un système quantique change lorsqu'elle est mesurée. La fonction d'onde s'effondre en un seul état, et on dit que le système est dans un état propre. L'état propre est l'état qui correspond au résultat de la mesure.
Le problème de la mesure a été proposé pour la première fois par <NAME> en 1928. Bohr a soutenu que l'effondrement de la fonction d'onde est une conséquence nécessaire de l'interaction du système quantique avec l'appareil de mesure. L'appareil de mesure est un système classique, et il ne peut pas interagir avec le système quantique sans le perturber.
Il existe de nombreuses interprétations différentes de la mécanique quantique et chaque interprétation a sa propre façon d'expliquer le problème de la mesure. L'interprétation la plus populaire de la mécanique quantique est l'interprétation de Copenhague. Selon cette interprétation, l'effondrement de la fonction d'onde est un événement réel, qui se produit lorsque le système quantique interagit avec l'appareil de mesure.
== Intrication quantique
L'intrication est un phénomène dans lequel deux ou plusieurs particules quantiques sont liées de telle sorte qu'elles partagent le même destin, même lorsqu'elles sont séparées par une grande distance. Par exemple, si deux électrons sont intriqués, ils auront toujours le même spin, même s'ils sont séparés par un continent.
L'intrication a été découverte pour la première fois par <NAME>, <NAME> et <NAME> en 1935. Ils ont proposé une expérience consistant à séparer une paire de particules intriquées et à mesurer leurs propriétés. Ils ont constaté que les propriétés des particules étaient toujours corrélées, même si elles étaient séparées par une grande distance. Cette expérience a montré que l'intrication est un phénomène réel, qui a depuis été confirmé par de nombreuses autres expériences.
Cependant, il est important de noter que l'intrication ne peut pas être utilisée pour communiquer des informations à une vitesse supérieure à celle de la lumière. En effet, l'information partagée entre les particules intriquées n'est pas réellement transmise entre elles. Au lieu de cela, les particules se trouvent simplement dans un état dans lequel elles partagent le même destin.
= Fondements mathématiques de la mécanique quantique <B>
== Fonction d'onde <BA>
La fonction d'onde est une fonction mathématique qui décrit l'état d'un système quantique. Il s'agit d'une fonction à valeurs complexes, dont le carré donne la probabilité de trouver la particule en un point particulier de l'espace. La fonction d'onde peut être utilisée pour calculer l'énergie de la particule, sa quantité de mouvement et d'autres propriétés.
Un exemple de fonction d'onde est la fonction d'onde d'une particule dans une boîte. Cette fonction d'onde est une onde sinusoïdale dont la longueur d'onde et l'amplitude varient en fonction de l'énergie de la particule. Le carré de la fonction d'onde d'une particule dans une boîte donne la probabilité de trouver la particule en un point particulier de la boîte.
Un autre exemple de fonction d'onde est la fonction d'onde d'un électron libre. Cette fonction d'onde est une onde sphérique dont la longueur d'onde et l'amplitude varient en fonction de l'énergie de l'électron. Le carré de la fonction d'onde d'un électron libre donne la probabilité de trouver l'électron en un point particulier de l'espace.
La fonction d'onde est un concept très important en mécanique quantique, et elle a de nombreuses applications dans la théorie des ondes et des particules. En comprenant la fonction d'onde, nous pouvons mieux comprendre le comportement des systèmes quantiques.
Voici un exemple de fonction d'onde pour une particule dans une boîte :
#align(center,$psi (x) = sqrt(frac(2,L)) sin (frac(pi n x,L))$)
où $n$ est un entier et $L$ la longueur de la boîte. La longueur d'onde de cette fonction d'onde est $lambda = 2L/n$, et l'amplitude est $A = sqrt(2/L)$. Le carré de cette fonction d'onde donne la probabilité de trouver la particule en un point particulier de la boîte.
#figure(
image("280px-QuantumHarmonicOscillatorAnimation.gif", width: 60%),
caption: [
Representation de fonction d'onde
],
)
== Espaces de Hilbert et vecteurs d'état <BB>
La mécanique quantique est une théorie mathématique qui utilise des _espaces de Hilbert_ pour représenter les *états quantiques d'un système*. Un _espace de Hilbert_ est un *espace vectoriel complexe* avec une structure interne qui permet de définir une notion de distance et de convergence, nommé produit interne. Les _vecteurs d'état_ quantique sont des éléments de cet espace de Hilbert et représentent l'état quantique d'un système. Les vecteurs d'état sont généralement notés *|ψ⟩* et peuvent être exprimés comme une *combinaison linéaire de vecteurs de base appelés états propres*.
=== Produit Scalaire (Produit interne) <BBA>
Le produit scalaire correspond pour deux vecteurs de taille n $accent(u,arrow) vec(x_1,x_2,..,x_n) x_i in CC$ et $accent(v,arrow) vec(y_1, x_2, .., y_n) y_i in CC space space.thin$
à #align(center,$angle.l u bar.v v angle.r = sum_(i=1)^n x_i^* y_i in CC $) avec \* le conjugué
==== Linéarité et anti-linéarité <BBAA>
Le produit scalaire est linéaire à droite et anti-linéaire à gauche \
- $angle.l u bar.v v_1 +v_2 angle.r = angle.l u bar.v v_1 angle.r +angle.l u bar.v v_2 angle.r $
- $angle.l u_1+u_2 bar.v v angle.r = angle.l u_1 bar.v v angle.r+ angle.l u_2 bar.v v angle.r$
- $angle.l u bar.v lambda v angle.r= lambda angle.l u bar.v v angle.r$
- $angle.l u bar.v lambda v angle.r= lambda angle.l u bar.v v angle.r lambda in CC$
- $angle.l lambda u bar.v v angle.r= lambda^* angle.l u bar.v v angle.r lambda in CC$
Ex.
- $angle.l u bar.v (2+3i) v angle.r= (2+3i) angle.l u bar.v v angle.r$
- $angle.l (2+3i) u bar.v v angle.r= (2-3i) angle.l u bar.v v angle.r$
==== Norme <BBAB>
$accent(u,arrow) vec(x_1,x_2,..,x_n) bar.v.double accent(u,arrow) bar.v.double = sqrt(sum_(i=1)^n bar.v x_i^2 bar.v) in RR_+$ avec |x| le module de x soit pour un nombre complexe $z = a+i b$ le module de z est $ |z| = sqrt(a^2+b^2)$ par conséquent $ bar.v.double accent(u,arrow) bar.v.double ^2 = bar.v x_1 bar.v^2 + bar.v x_2 bar.v^2 + .. + bar.v x_n bar.v^2 $ puisque $bar.v z space.thin bar.v^2 = a^2+b^2 = z^*dot.op z arrow. $
$ bar.v.double u bar.v.double = sqrt(angle.l u bar.v u angle.r)$
==== Orthogonalité <BBAC>
Deux vecteurs sont orthogonaux si $angle.l u bar.v v angle.r = 0$
==== Symétrie <BBAD>
$ angle.l u bar.v v angle.r = (angle.l v bar.v u angle.r)^* $
== Opérateurs et observables <BC>
Les _opérateurs quantiques_ sont des *transformations linéaires* qui agissent sur les vecteurs d'état quantique pour produire de nouveaux vecteurs d'état. Les _observables_ sont des grandeurs physiques qui peuvent être mesurées expérimentalement, telles que la *position*, la *quantité de mouvement* et l'*énergie*. Les observables sont représentées par des _opérateurs hermitiens_. Les valeurs propres de ces opérateurs sont les valeurs possibles pour les mesures de l'observable correspondante.
=== Opérateurs linéaires <BCA>
Un opérateur linéaire est une fonction $L$ qui fait correspondre des vecteurs d'un espace vectoriel $V$ à des vecteurs d'un autre espace vectoriel $W$, de telle sorte que pour tout vecteur $x$ et $y$ dans $V$ et tout scalaire $c$,
$accent(L, hat)(|x angle.r + |y angle.r) = accent(L, hat)(|x angle.r) + accent(L, hat)(|y
angle.r)$
$accent(L, hat)(c |x angle.r) = c accent(L, hat)(|x angle.r)$
La notation d'un opérateur linéaire est généralement un chapeau, $accent(L, hat)$. Par exemple, l'opérateur linéaire qui prend un vecteur $x$ à sa transposée est désigné par $accent(T, hat)$.
En mécanique quantique, les opérateurs linéaires sont utilisés pour représenter les observables. Par exemple, l'opérateur linéaire qui représente la position d'une particule est désigné par $accent(x, hat)$. La formule de la valeur espérée d'une observable $O$ est donnée par
#align(center,$angle.l O angle.r = integral psi^* O psi d x$)
où $psi$ est la fonction d'onde de la particule.
=== États propres et valeurs propres <BCB>
Un observable est une quantité qui peut être mesurée dans un système quantique. Les observables ont des valeurs propres, qui sont les valeurs possibles que l'observable peut prendre. Les états propres sont les états d'un système quantique qui correspondent aux valeurs propres d'un observable.
Les trois règles concernant les états propres et les valeurs propres des observables sont les suivantes :
1. Les observables ont des valeurs propres réelles.
2. Les états propres des observables doivent couvrir tout l'espace vectoriel.
3. Les états propres doivent être mutuellement orthogonaux.
*Exemple*:
Énergie potentielle
L'énergie potentielle d'un système quantique est l'énergie que le système possède en raison de sa position. L'opérateur d'énergie potentielle est désigné par $accent(V, hat)$.
La formule de l'énergie potentielle est donnée par
#align(center,$accent(V, hat) = -frac(planck.reduce^2,2 m) nabla^2$)
où $nabla^2$ est l'opérateur Laplacien.
L'opérateur d'énergie potentielle peut être utilisé pour trouver les valeurs propres et les états propres de l'atome d'hydrogène. Les valeurs propres de l'atome d'hydrogène sont données par
#align(center,$E_n = -frac(13.6 " eV",n^2)$)
où $n$ est un nombre entier. Les états propres de l'atome d'hydrogène sont donnés par les fonctions d'onde
#align(center,$psi_n(r, theta, phi) = frac(1,sqrt(4pi a_0^3)) ( frac(n^2,r) )^(3/2) e^(-n^2r/2a_0) e^(i m theta) e^(i n phi)$)
où $a_0$ est le rayon de Bohr.
Les états propres de l'atome d'hydrogène sont mutuellement orthogonaux et couvrent tout l'espace vectoriel.
== Le formalisme de Dirac <BD>
Le formalisme de Dirac est une notation mathématique pour la mécanique quantique qui utilise des notations spéciales pour les vecteurs d'état et les opérateurs. Dans cette notation, les vecteurs d'état sont représentés sous forme de ket *$bar.v psi angle.r$* et les vecteurs duale, qui sont les vecteurs adjoints, sont représentés sous forme de bra *$angle.l psi bar.v $*. Lorsque l'on prend le produit scalaire d'un ket avec un bra, on obtient une expression appelée le bra-ket, notée *$angle.l psi bar.v phi angle.r$*, qui représente la probabilité de transition entre les deux états quantiques. Le formalisme de Dirac permet également de représenter les opérateurs quantiques sous forme de notations spéciales, telles que l'opérateur identité, l'opérateur de projection et l'opérateur de translation. Cette notation simplifie considérablement les calculs en mécanique quantique et permet une compréhension plus intuitive de la théorie.
=== Bra-Ket notation <BDA>
La notation de Bra-ket est une notation pour l'algèbre linéaire et les opérateurs linéaires sur des espaces vectoriels complexes ainsi que leur espace dual, à la fois en dimension finie et en dimension infinie. Elle est spécifiquement conçue pour faciliter les types de calculs qui se présentent fréquemment en mécanique quantique. Son utilisation en mécanique quantique est très répandue. De nombreux phénomènes expliqués à l'aide de la mécanique quantique sont expliqués à l'aide de la notation bra-ket.
Dans la notation bra-ket, un bra est désigné par $angle.l psi bar.v$ et un ket est désigné par $bar.v phi angle.r$. Un bra est une fonction linéaire, ce qui signifie qu'il prend un vecteur en entrée et renvoie un nombre complexe. Un ket est un vecteur, ce qui signifie qu'il prend un nombre complexe en entrée et renvoie un vecteur.
La représentation matricielle d'un bra est un vecteur ligne et la représentation matricielle d'un ket est un vecteur colonne. Le produit intérieur d'un bra et d'un ket est un nombre complexe.
La notation bra-ket est liée au produit intérieur de la manière suivante :
#align(center,$angle.l psi bar.v phi angle.r = integral_(-infinity)^(infinity) psi^*(x) phi (x) d x$)
où $psi^*(x)$ est le conjugué complexe de $psi(x)$. Le produit intérieur est une mesure du chevauchement entre deux fonctions.
La notation bra-ket est un outil très utile en mécanique quantique, et elle a de nombreuses applications dans la théorie des ondes et des particules. En comprenant la notation bra-ket, nous pouvons mieux comprendre le comportement des systèmes quantiques.
== Distribution de Dirac <BE>
La fonction delta de Dirac est une fonction définie comme nulle partout sauf au point x=0, où elle est infinie. Elle est souvent désignée par la lettre grecque delta, $delta (x)$. La fonction delta de Dirac a de nombreuses applications en mécanique quantique, où elle est utilisée pour représenter des particules ponctuelles et d'autres objets ayant une très petite étendue spatiale.
Un exemple d'utilisation de la fonction delta de Dirac en mécanique quantique est l'intégrale de la fonction d'onde. L'intégrale de la fonction d'onde est un moyen de calculer la probabilité qu'une particule se trouve à un endroit donné. L'intégrale de la fonction d'onde est définie comme suit :
#align(center,$integral_(-infinity)^(infinity) psi (x) delta (x-x_0) d x$)
où $psi (x)$ est la fonction d'onde de la particule et $x_0$ est l'endroit où la particule est trouvée. La fonction delta de Dirac dans cette intégrale nous indique que nous sommes uniquement intéressés à trouver la particule à l'endroit $x_0$, et que la probabilité de trouver la particule n'importe où ailleurs est nulle.
La fonction delta de Dirac est également utilisée dans la définition de l'opérateur de quantité de mouvement. L'opérateur de quantité de mouvement est un opérateur mathématique qui représente la quantité de mouvement d'une particule. L'opérateur de quantité de mouvement est défini comme suit
#align(center,$accent(p, hat) = -i planck.reduce frac(d,d x)$)
où $i$ est l'unité imaginaire et $planck.reduce$ est la constante de Planck réduite. La fonction delta de Dirac dans cette définition nous indique que nous ne nous intéressons qu'à la dérivée de la fonction d'onde à l'endroit $x=0$, et que la valeur de la dérivée partout ailleurs est nulle.
La fonction delta de Dirac est un outil très utile en mécanique quantique, et elle a de nombreuses applications dans la théorie des ondes et des particules.
#figure(
image("Dirac_distribution_PDF.svg", width: 80%),
caption: [
Representation de la fonction delta de Dirac
],
)
== Probalités : La loi de Born <BF>
La probabilité de trouver le système dans l'état propre $|E_i angle.r$ est donnée par :
#align(center,$P(E = E_i) = abs( angle.l E_i | psi angle.r )^2$)
où $|E_i angle.r$ est l'état propre de l'observable $E$ avec la valeur propre $E_i$ et $psi$ est la fonction d'onde du système.
La fonction d'onde $psi$ peut être écrite comme une somme des états propres de l'observable $E$, comme suit :
#align(center,$psi = sum_i c_i |E_i angle.r$)
où $c_i$ sont les coefficients des états propres.
En substituant ceci à la formule de la probabilité, nous obtenons :
#align(center,$P(E = E_i) = abs(angle.l E_i | sum_i c_i |E_i angle.r )^2 = sum_i |c_i|^2$)
Ceci montre que la probabilité de trouver le système dans l'état propre $|E_i angle.r$ est égale à la somme des carrés des coefficients des états propres.
=== Matrice densité et Espérance mathématique
Une matrice densité est une matrice qui décrit l'état quantique d'un système physique. Elle permet de calculer les probabilités des résultats de toute mesure effectuée sur ce système, en utilisant la règle de Born. Il s'agit d'une généralisation des vecteurs d'état ou des fonctions d'onde plus habituels : alors que ceux-ci ne peuvent représenter que des états purs, les matrices de densité peuvent également représenter des états mixtes.
L'espérance mathématique d'un opérateur $accent(A, hat)$ dans un système quantique décrit par une matrice densité $rho$ est donnée par la formule suivante :
#align(center,$angle.l accent(A, hat) angle.r = "Tr"(rho accent(A, hat))$)
où $"Tr"$ est la fonction trace. La fonction trace d'une matrice est la somme de ses éléments diagonaux.
La fonction trace possède les propriétés suivantes :
- C'est une fonction linéaire.
- Elle est invariante sous les transformations unitaires.
- Elle est définie positive.
La fonction trace peut être utilisée pour calculer la valeur d'espérance de tout opérateur dans un système quantique.
La matrice densité peut être utilisée pour calculer les probabilités des résultats de toute mesure effectuée sur un système quantique. La règle de Born stipule que la probabilité d'obtenir un résultat $a$ lors de la mesure d'une observable $accent(A, hat)$ est donnée par la formule suivante :
#align(center,$P(a) = frac(angle.l a | rho | a angle.r,sum_i angle.l i | rho | i angle.r)$)
où $|a angle.r$ est l'état propre de $accent(A, hat)$ correspondant au résultat $a$.
La matrice densité est un outil très important en mécanique quantique. Elle peut être utilisée pour calculer les valeurs d'espérance des opérateurs, les probabilités des résultats des mesures et la fonction d'onde d'un système quantique.
== Opérateurs Hermitien <BG>
=== L'adjoint Hermitien <BGA>
L'adjoint hermitien d'un ket est un bra. Il est noté $A^dagger$. L'adjoint hermitien d'un ket est défini comme suit :
$angle.l A^dagger psi | phi angle.r = angle.l psi | A phi angle.r$
pour tous les vecteurs $psi$ et $phi$ dans l'espace vectoriel.
L'adjoint hermitien possède plusieurs propriétés. L'une d'entre elles est qu'il est linéaire. Cela signifie que si $A$ et $B$ sont deux opérateurs, alors
$(A B)^dagger = B^dagger A^dagger$
Une autre propriété est qu'elle est anti-linéaire. Cela signifie que si $A$ est un opérateur et $c$ un nombre complexe, alors
$(c A)^dagger = overline(c) A^dagger$
Enfin, l'adjoint hermitien satisfait la relation suivante :
$(A^dagger)^dagger = A$
L'adjoint hermitien est un outil très important en mécanique quantique. Il est utilisé pour définir le produit intérieur, qui est une mesure du chevauchement entre deux vecteurs. Le produit intérieur est utilisé pour calculer la valeur d'espérance d'une observable, qui est la valeur moyenne de l'observable sur tous les états possibles du système.
==== L'adjoint d'un Ket et d'un Bra <BGAA>
L'adjoint d'un Ket et d'un bra correspond à
$angle.l phi | psi angle.r ^dagger = angle.l phi | psi angle.r^star.op = angle.l psi | phi angle.r$
ou
$(angle.l phi | psi angle.r)^dagger = bar.v psi angle.r^dagger angle.l phi bar.v^dagger $
D'où $bar.v psi angle.r^dagger = angle.l psi bar.v$ et $angle.l phi bar.v^dagger = bar.v phi angle.r$
=== Opérateur Hermitien <BGB>
Un opérateur hermitien est un opérateur qui satisfait cette condition $accent(E,hat)^dagger = accent(E, hat)$
C'est le cas des observables par conséquent $angle.l psi | accent(E, hat)phi angle.r = angle.l accent(E, hat)psi | phi angle.r$
== Opérateur Unitaire <BH>
Un opérateur unitaire est un opérateur linéaire $U$ sur un espace de Hilbert $H$ qui satisfait les conditions suivantes :
1. $U$ est inversible.
2. $U^(-1) = U^dagger$, où $U^dagger$ est l'adjoint de $U$.
3. $U$ préserve le produit intérieur de $H$, c'est-à-dire que pour tous les vecteurs $x$ et $y$ dans $H$, on a $angle.l U x, U y angle.r = angle.l x comma y angle.r$.
Les opérateurs unitaires sont importants en mécanique quantique, car ils représentent des transformations physiques qui préservent le produit intérieur et la probabilité. Par exemple, l'opérateur d'évolution temporelle $U(t)$ pour un système quantique est unitaire et représente l'évolution du système dans le temps.
Les propriétés des opérateurs unitaires peuvent être déduites de leur définition. Par exemple, les valeurs propres d'un opérateur unitaire sont toujours des nombres complexes de module unitaire, et les vecteurs propres d'un opérateur unitaire forment une base orthonormée pour $H$.
Les opérateurs unitaires conservent les probabilités parce qu'ils préservent le produit intérieur. Le produit intérieur est une mesure du chevauchement entre deux vecteurs, et il est égal à la probabilité que deux vecteurs se retrouvent dans le même état après une mesure. Si un opérateur unitaire préserve le produit intérieur, il préserve également la probabilité.
Voici quelques exemples d'opérateurs unitaires :
- L'opérateur de rotation $R(theta)$, qui fait pivoter un vecteur d'un angle $theta$ autour de l'origine.
- L'opérateur de réflexion $S$, qui réfléchit un vecteur à travers l'origine.
- La transformée d'Hadamard $H$, qui transforme un vecteur en une superposition égale de tous les états de base possibles.
- Les matrices de Pauli $sigma_x$, $sigma_y$, et $sigma_z$, qui sont utilisées pour décrire le spin en mécanique quantique.
== Principe d'incertitude et Commutation <BI>
En mécanique quantique, le commutateur de deux opérateurs est une mesure de la manière dont les deux opérateurs peuvent être mesurés simultanément. Le commutateur de deux opérateurs est défini comme $bracket.l accent(A, hat) comma accent(B, hat) bracket.r = accent(A, hat) accent(B, hat) - accent(B, hat) accent(A, hat)$, où $accent(A, hat)$ et $accent(B, hat)$ sont les deux opérateurs. Si le commutateur de deux opérateurs est nul, on dit que les opérateurs sont commutatifs. Les opérateurs commutatifs peuvent être mesurés simultanément, ce qui signifie que les résultats de la mesure d'un opérateur n'affecteront pas les résultats de la mesure de l'autre opérateur.
Si deux observables commutent, ils ont alors une base propre simultanée. Une base propre est un ensemble de vecteurs qui sont des vecteurs propres d'un opérateur donné. Un vecteur propre est un vecteur qui, lorsqu'il est influencé par un opérateur, a une valeur fixe. La base propre simultanée de deux observables commutatives est un ensemble de vecteurs qui sont des vecteurs propres des deux observables.
Le principe d'incertitude stipule qu'il est impossible de connaître à la fois la position et la quantité de mouvement d'une particule avec une précision parfaite. Le principe d'incertitude peut être dérivé du commutateur des opérateurs de position et de quantité de mouvement. Le commutateur des opérateurs de position et de quantité de mouvement est $[x,p] = i planck.reduce$, où $planck.reduce$ est la constante de Planck réduite. Cela signifie qu'il est impossible de mesurer simultanément la position et la quantité de mouvement d'une particule avec une précision parfaite.
Le principe d'incertitude peut être exprimé mathématiquement comme suit pour la position et la quantité de mouvement:
#align(center,$sigma_x sigma_p gt.eq frac(planck.reduce,2)$)
où $sigma_x$ est l'incertitude sur la position et $sigma_p$ est l'incertitude sur la quantité de mouvement.
Il existe une forme généralisée du principe d'incertitude nommé relations d'incertitude Robertson-Schrödinger:
#align(center,$sigma_A sigma_B gt.eq abs(1/(2i) angle.l bracket.l accent(A, hat) comma accent(B, hat) bracket.r angle.r)$)
Le principe d'incertitude est un principe fondamental de la mécanique quantique. Il a des implications importantes pour l'interprétation de la mécanique quantique et pour la compréhension du monde physique.
= Postulats de la mécanique quantique <C>
1. L’état d’un système quantique est entièrement défini par un vecteur d’état dans un espace de Hilbert. Un vecteur d’état est généralement noté $bar.v psi angle.r$ et appartient à un espace de Hilbert H. Les états quantiques sont des vecteurs unitaires dans H, c’est-à-dire que $angle.l psi bar.v psi angle.r = 1$.
2. Les observables quantiques sont représentées par des opérateurs hermitiens. Un opérateur hermitien A est un opérateur qui est égal à sa propre adjointe $A^(dagger)$ (c’est-à-dire que $A = A^dagger "avec "dagger "le conjugué soit "star.op$). Les valeurs propres de l’opérateur hermitien A correspondent aux résultats possibles de la mesure de l’observable associée à A.
3. Les résultats de la mesure d’une observable quantique sont des valeurs propres de l’opérateur associé à cette observable. Si l’on mesure une observable quantique représentée par l’opérateur hermitien A sur un état quantique $bar.v psi angle.r$, la probabilité d’obtenir une valeur propre a est donnée par la formule $P(a) = bar.v angle.l a bar.v psi angle.r bar.v^2 " où "bar.v a angle.r$ est le vecteur propre correspondant à la valeur propre a.
4. La probabilité de mesurer une valeur propre donnée est donnée par le carré du module de l’amplitude de probabilité correspondante. L’amplitude de probabilité pour obtenir une valeur propre a lorsqu’on mesure une observable quantique représentée par l’opérateur hermitien A sur un état quantique $bar.v psi angle.r$ est donnée par $angle.l a bar.v psi angle.r$. La probabilité P(a) d’obtenir la valeur propre a est alors donnée par #align(center,$P(a) = bar.v angle.l a bar.v psi angle.r bar.v^2$).
5. L’évolution temporelle d’un système quantique est décrite par l’équation de Schrödinger. L’évolution temporelle d’un état quantique $bar.v psi(t) angle.r$ est décrite par l’équation de Schrödinger #align(center,$i planck.reduce frac(diff, diff t)bar.v psi(t) angle.r = accent(H,hat) bar.v psi(t) angle.r $) où $accent(H,hat)$ est l’hamiltonien du système donc l'énergie totale du système et $planck.reduce " est " = frac(planck, 2pi) $.
6. Les états quantiques peuvent être intriqués, ce qui signifie que les propriétés de chaque particule ne peuvent pas être décrites indépendamment des autres particules avec lesquelles elle est intriquée. Par exemple, si deux particules sont intriquées, alors la mesure de l’une des particules affectera instantanément l’état de l’autre particule, peu importe la distance qui les sépare.
== Equation de Schrödinger
L'équation de Schrödinger dépendante du temps peut être obtenue à partir de l'équation de Schrödinger indépendante en suivant les étapes suivantes :
1. Supposons que la fonction d'onde $Psi (t comma r)$ puisse être écrite comme un produit d'un facteur dépendant du temps et d'un facteur dépendant de l'espace :
#align(center,$Psi (t comma r) = psi (t) phi (r)$)
2. Substituer ceci dans l'équation de Schrödinger indépendante et multiplier les deux côtés par $psi (t)^*$ :
#align(center,$-frac(i planck.reduce,2m) psi'(t) = ( -frac(planck.reduce^2,2m)) Delta phi (r) + V(r) phi (r)) psi (t)^*$)
3. Simplifier le côté gauche en combinant les termes :
#align(center,$-frac(i planck.reduce,2m) psi'(t) = -frac(planck.reduce^2,2m) Delta psi (t) + V(r) psi (t)^*$)
4. Intégrer les deux côtés par rapport au temps :
#align(center,$psi (t) = psi (0) + frac(i planck.reduce,2m) integral_0^t Delta psi (s) d s - frac(i planck.reduce,2m) integral_0^t V(r) psi (s)^* d s$)
5. Le premier terme du côté droit est la fonction d'onde initiale, que l'on suppose connue. Le second terme du côté droit est une fonction de l'espace et du temps, et il peut être trouvé en résolvant l'équation de Schrödinger indépendante du temps :
#align(center,$Delta psi (s) + V(r) psi (s) = 0$)
L'équation de Schrödinger dépendante du temps peut alors être écrite comme suit :
#align(center,$i planck.reduce frac(diff psi (t),diff t) = H psi (t)$)
où $H$ est l'opérateur hamiltonien.
L'équation de Schrödinger dépendante du temps est une équation linéaire qui peut être résolue en utilisant le principe de superposition. Le principe de superposition stipule que toute solution à l'équation de Schrödinger indépendante du temps peut être additionnée pour former une autre solution à l'équation de Schrödinger dépendante du temps.
La densité de probabilité est définie comme $|psi|^2$, et c'est une mesure de la probabilité de trouver la particule en un point donné de l'espace. La probabilité totale doit toujours être égale à 1, ce qui signifie que la fonction d'onde doit être normalisée.
La constante de Planck donne les unités de l'opérateur hamiltonien. L'opérateur hamiltonien est le générateur de translations temporelles, et l'énergie est la quantité conservée sous l'effet des translations temporelles.
=== Exemple d'un puits de potentiel fini
L'équation de Schrödinger pour une particule dans un puits de potentiel fini est la suivante :
#align(center, $-frac(planck.reduce^2,2m)nabla^2 psi (x) + V(x)psi (x) = E psi (x)$)
où $V(x)$ est l'énergie potentielle de la particule, $E$ est l'énergie de la particule, $psi (x)$ est la fonction d'onde de la particule, et $planck.reduce$ est la constante de Planck réduite.
Pour résoudre l'équation de Schrödinger, on peut utiliser la méthode de séparation des variables. Cette méthode consiste à supposer que la fonction d'onde peut être séparée en deux parties :
#align(center,$psi (x) = X(x)Y(y)Z(z)$)
où $X(x)$ est une fonction de $x$, $Y(y)$ est une fonction de $y$, et $Z(z)$ est une fonction de $z$. En substituant ceci à l'équation de Schrödinger, nous obtenons :
#align(center,$-frac(planck.reduce^2,2m)nabla^2X(x) + V(x)X(x) = E X(x)$)
#align(center,$-frac(planck.reduce^2,2m)nabla^2Y(y) + E Y(y)$)
#align(center,$-frac(planck.reduce^2,2m)nabla^2Z(z) + E Z(z)$)
La première équation peut être résolue pour $X(x)$, la deuxième pour $Y(y)$ et la troisième pour $Z(z)$. Les solutions de ces équations sont appelées fonctions propres, et les valeurs propres correspondantes sont les niveaux d'énergie de la particule.
Dans le cas d'une particule dans un puits de potentiel fini, l'énergie potentielle est nulle à l'intérieur du puits et infinie à l'extérieur. Cela signifie que les fonctions propres doivent être nulles à l'extérieur du puits. Les solutions de l'équation de Schrödinger dans ce cas sont appelées ondes stationnaires et sont données par :
#align(center,$psi_n(x) = sqrt(frac(2,a) sin ( frac(n pi x,a)))$)
où $a$ est la largeur du puits et $n$ est un entier. Les niveaux d'énergie de la particule sont donnés par :
#align(center,$E_n = frac(n^2pi^2planck.reduce^2,2m a^2)$)
Les ondes stationnaires représentent les états possibles de la particule dans le puits. La particule ne peut exister que dans ces états, et elle ne peut avoir d'autre énergie que les niveaux d'énergie donnés par l'équation de Schrödinger.
=== Exemple sur un oscillateur harmonique
L'équation de Schrödinger pour l'oscillateur harmonique est la suivante :
#align(center,$-frac(planck.reduce^2,2m)nabla^2 psi (x) + frac(1,2)m omega^2x^2psi (x) = E psi (x)$)
où $m$ est la masse de l'oscillateur, $omega$ est la fréquence angulaire, et $E$ est l'énergie de l'oscillateur.
Pour résoudre cette équation, on peut utiliser la méthode de séparation des variables. Cette méthode consiste à supposer que la fonction d'onde peut être séparée en deux parties :
#align(center,$psi (x) = X(x)Y(y)Z(z)$)
où $X(x)$ est une fonction de $x$, $Y(y)$ est une fonction de $y$, et $Z(z)$ est une fonction de $z$. En substituant ceci à l'équation de Schrödinger, nous obtenons :
#align(center,$-frac(planck.reduce^2,2m)frac(d^2X(x),d x^2) + frac(1,2)m omega^2x^2X(x) = E X(x)$)
#align(center,$-frac(planck.reduce^2,2m)frac(d^2Y(y),d y^2)$)
#align(center,$-frac(planck.reduce^2,2m)frac(d^2Z(z),d z^2) + 0 = E Z(z)$)
La première équation peut être résolue pour $X(x)$, la deuxième pour $Y(y)$ et la troisième pour $Z(z)$. Les solutions de ces équations sont appelées fonctions propres, et les valeurs propres correspondantes sont les niveaux d'énergie de l'oscillateur.
Les fonctions propres de l'oscillateur harmonique sont appelées polynômes d'Hermite et sont données par :
#align(center,$psi_n(x) = frac(1,sqrt(n!)) sqrt(frac(2omega,\pi)) H_n ( sqrt(frac(omega,2)) x)$)
où $H_n$ est le $n$ème polynôme d'Hermite. Les niveaux d'énergie de l'oscillateur sont donnés par :
#align(center,$E_n = planck.reduce omega (n + frac(1,2))$)
Les polynômes d'Hermite représentent les états possibles de l'oscillateur. L'oscillateur ne peut exister que dans ces états, et il ne peut avoir d'autre énergie que les niveaux d'énergie donnés par l'équation de Schrödinger.
== Moment quantique
L'opérateur de quantité de mouvement est noté $accent(P,hat)$, et la fonction d'onde d'une particule est notée $psi$. L'opérateur de quantité de mouvement agit sur la fonction d'onde comme suit :
#align(center,$accent(P,hat) psi (x) = -i planck.reduce frac(d psi (x),d x)$)
où $planck.reduce$ est la constante de Planck réduite.
L'opérateur de quantité de mouvement peut être utilisé pour calculer la quantité de mouvement d'une particule. La quantité de mouvement d'une particule est donnée par la formule suivante :
#align(center,$p = angle.l psi | accent(P,hat) psi angle.r$)
où $angle.l psi | accent(P,hat) psi angle.r$ est la valeur d'espérance de l'opérateur de quantité de mouvement.
= Effet Tunnel
L'effet tunnel quantique est un phénomène dans lequel un objet tel qu'un électron ou un atome traverse une barrière d'énergie potentielle que, selon la mécanique classique, l'objet n'a pas suffisamment d'énergie pour franchir.
L'effet tunnel est une conséquence de la nature ondulatoire de la matière, où la fonction d'onde quantique décrit l'état d'une particule ou d'un autre système physique, et où les équations d'onde telles que l'équation de Schrödinger décrivent leur comportement.
L'équation de Schrödinger peut être résolue pour trouver la fonction d'onde d'une particule dans une barrière d'énergie potentielle. La fonction d'onde pourra avoir une valeur non nulle de l'autre côté de la barrière, même si la particule n'a pas assez d'énergie pour atteindre ce côté selon la mécanique classique.
La probabilité d'un effet tunnel est proportionnelle au carré de la fonction d'onde. Cela signifie que les particules ayant une fonction d'onde plus grande auront plus de chances de traverser une barrière que les particules ayant une fonction d'onde plus petite.
#link("tunnel.html", "Tunnel Effect Video")
= Spin
Le spin est une forme intrinsèque de moment angulaire porté par les particules élémentaires. Il s'agit d'une propriété quantifiée exprimée par un nombre quantique de spin, noté "s". Par exemple, les électrons ont un spin 1/2, ce qui signifie qu'ils ont deux états de spin possibles. Le spin d'une particule détermine un grand nombre de ses propriétés, comme son moment magnétique et son comportement statistique. Le spin est une propriété fondamentale des particules, comme la masse et la charge, et il ne peut pas être expliqué par d'autres propriétés.
Une conséquence importante du spin des particules est le couplage spin-orbite, qui résulte de l'interaction entre le spin d'une particule et son mouvement dans un champ magnétique. Le couplage spin-orbite peut provoquer la division des niveaux d'énergie dans les atomes, ce qui affecte les propriétés des électrons et peut conduire à des phénomènes tels que la structure fine des lignes spectrales.
Le spin d'une particule la fait agir comme un petit aimant. Cela signifie que les particules peuvent interagir par l'intermédiaire de la force magnétique et que l'interaction du moment magnétique de spin entraîne également l'alignement des particules dans les champs magnétiques. Les propriétés magnétiques d'une particule sont déterminées par son spin, qui détermine l'intensité et la direction de son moment magnétique. Le moment magnétique μ d'une particule est proportionnel à son moment angulaire de spin :
#align(center,$μ = g * (e / 2m) * S$)
où g est le facteur g, e est la charge élémentaire et m est la masse de la particule.
La direction du spin d'une particule peut être décrite par son vecteur spin, qui est une quantité vectorielle pointant dans la direction du moment angulaire de spin de la particule. L'ampleur du moment angulaire de spin peut être calculée à l'aide de la formule suivante :
#align(center,$|S| = sqrt(s(s + 1)) * ħ$)
où ħ (h-bar) est la constante de Planck réduite.
Le moment angulaire du spin a des composantes quantifiées le long d'un axe donné (généralement l'axe z). La composante le long de l'axe z, notée Sz, peut prendre des valeurs discrètes données par :
#align(center,$S z = m_s * ħ$)
où $m_s$ est le nombre quantique magnétique, qui varie de -s à s par pas entiers. Par exemple, un électron, qui est un fermion de spin 1/2, peut avoir deux valeurs possibles pour $S z$ : $+ħ/2$ et $-ħ/2$, correspondant respectivement à $m_s = +1/2$ et $m_s = -1/2$.
La rotation du vecteur spin sous l'effet des rotations de la particule est décrite par l'opérateur de moment angulaire de spin, noté S. L'algèbre de spin régit les relations de commutation entre les composantes du vecteur spin :
#align(center,$[S x, S y] = i ħ S z, [S y, S z] = i ħ S x, [S z, S x] = i ħ S y$)
Les valeurs propres de $S z$ sont $m_s = s, s-1, ...,-s$, ce qui signifie que la projection du spin est quantifiée le long de l'axe z. Cette quantification a des implications pour le comportement des particules dans les champs magnétiques, ainsi que pour la distribution des particules dans les systèmes. Cette quantification a des implications sur le comportement des particules dans les champs magnétiques, ainsi que sur la distribution des particules dans les systèmes.
La force du couplage spin-orbite est proportionnelle au numéro atomique du noyau et au spin électronique, et joue un rôle important dans des phénomènes tels que la division de la structure fine dans les spectres atomiques et l'effet Hall de spin dans les systèmes à l'état solide.
La direction du moment angulaire du spin est déterminée par la direction du moment magnétique. Le moment magnétique d'une particule est une quantité vectorielle qui pointe dans la direction du moment angulaire de spin. L'orientation du moment magnétique est affectée par les champs magnétiques externes et peut entraîner la précession du moment angulaire du spin autour de la direction du champ magnétique, un phénomène connu sous le nom de précession de Larmor.
Le comportement du spin sous l'effet des rotations est régi par les transformations de Lorentz, qui relient les coordonnées d'un événement mesurées par des observateurs situés dans des cadres de référence inertiels différents. Sous l'effet d'une transformation de Lorentz, les composantes du spin le long de différentes directions se mélangent, ce qui conduit au phénomène de couplage spin-orbite.
Le principe d'exclusion de Pauli stipule que deux fermions ne peuvent pas occuper simultanément le même état quantique, ce qui inclut l'état de spin.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/foundations-17.typ | typst | Other | // Error: 7-17 cannot continue outside of loop
#eval("continue")
|
https://github.com/0x1B05/nju_os | https://raw.githubusercontent.com/0x1B05/nju_os/main/book_notes/content/02_virtualization_01_CPU_00_basic.typ | typst | #import "../template.typ": *
#pagebreak()
= CPU virtualization
== Process
=== Introduction
The *process* is a *running program*.
=== time sharing and space sharing
- Q: How can the OS provide the illusion of a nearly-endless supply of said CPUs?
- A: Virtualizing the CPU. By running one process, then stopping it and running another, and so forth, the OS can promote the illusion that many virtual CPUs exist when in fact there is only one physical CPU (or a few). (*time sharing of the CPU*)
- Time sharing is a basic technique used by an OS to share a resource.
- By allowing the resource to be used for a little while by one entity, and then a little while by another, and so forth, the resource in question (e.g., the CPU, or a network link) can be shared by many.
- Space sharing, where a resource is divided (in space) among those who wish to use it.
- For example, disk space is naturally a space-shared resource; once a block is assigned to a file, it is normally not assigned to another file until the user deletes the original file.
=== To implement virtualization of the CPU:
- some low-level machinery (*mechanisms*)
- time-sharing mechanism
- some high-level intelligence(*policies*)
- scheduling policy
=== The Abstraction: The Process
==== Machine State
the component of machine state the comprises a process:
- memory(called ites address sapce)
- registers
- some particularly special registers:
- program counter(PC)
- stack pointer
- frame pointer
#tip("Tip")[
They are used to manage the stack for function parameters, local variables, and return addresses
]
=== Interlude: Process API
Process API forms:
- Create(create a process)
- Destroy(destroy a process)
- Wait(wait for a process to stop running)
- Miscellaneous Control(suspend, resume...)
- Status(get some info about a process)
=== Process Creation: A Little More Detail
==== load the process
#image("images/2023-12-04-19-59-55.png", width: 60%)
The first thing that the OS must do to run a program is to load its code and any static data (e.g., initialized variables) into memory, into the address space of the process.
In early (or simple) operating systems, the loading process is done *eagerly*; modern OSes perform the process *lazily*(paging and swapping)
==== before running the process
- Some memory must be allocated for the program’s *run-time stack* (or just *stack*).
#tip("Tip")[
The OS will also likely initialize the stack with arguments; specifically, it will fill in the parameters to the `main()` function, i.e., `argc` and the `argv` array.
]
- The OS may also allocate some memory for the program’s *heap*.
#tip("Tip")[
The heap will be small at first; as the program runs, and requests more memory via the `malloc()` library API, the OS may get involved and allocate more memory to the process to help satisfy such calls.
]
- The OS will also do some other initialization tasks, particularly as related to input/output (I/O).
#tip("Tip")[
Each process by default has three open file descriptors, for standard input, output, and error.
]
- Finally set the stage for program execution, one last task: to start the program running at the entry point, namely `main()`.By jumping to the `main()` routine, the OS transfers control of the CPU to the newly-created process, and thus the program begins its execution.
=== Process States
States:
- Running
- Ready
- Blocked.
#image("images/2023-12-04-19-59-31.png", width:60%)
#image("images/2023-12-04-20-00-23.png", width:60%)
#image("images/2023-12-04-20-00-32.png", width:60%)
=== Data Structures
To track the state of each process, the OS likely will keep some kind of *process list* for all processes that are ready and some additional information to track which process is currently running.
==== an OS needs to track about each process in the xv6 kernel
```c
// Saved registers for kernel context switches.
struct context {
uint64 ra;
uint64 sp;
// callee-saved
uint64 s0;
uint64 s1;
uint64 s2;
uint64 s3;
uint64 s4;
uint64 s5;
uint64 s6;
uint64 s7;
uint64 s8;
uint64 s9;
uint64 s10;
uint64 s11;
};
enum procstate { UNUSED, USED, SLEEPING, RUNNABLE, RUNNING, ZOMBIE };
// Per-process state
struct proc {
struct spinlock lock;
// p->lock must be held when using these:
enum procstate state; // Process state
void *chan; // If non-zero, sleeping on chan
int killed; // If non-zero, have been killed
int xstate; // Exit status to be returned to parent's wait
int pid; // Process ID
// wait_lock must be held when using this:
struct proc *parent; // Parent process
// these are private to the process, so p->lock need not be held.
uint64 kstack; // Virtual address of kernel stack
uint64 sz; // Size of process memory (bytes)
pagetable_t pagetable; // User page table
struct trapframe *trapframe; // data page for trampoline.S
struct context context; // swtch() here to run process
struct file *ofile[NOFILE]; // Open files
struct inode *cwd; // Current directory
char name[16]; // Process name (debugging)
};
```
*context switch*:
- The register context will hold, for a stopped process, the contents of its registers.
- When a process is stopped, its registers will be saved to this memory location; by restoring these registers (i.e., placing their values back into the actual physical registers), the OS can resume running the process.
Sometimes a system will have an *initial state* that the process is in when it is being created. Also, a process could be placed in a *final state* where it has exited but has not yet been cleaned up (in UNIX-based systems, this is called the *zombie state*).
#tip("Tip")[
*Final state* can be useful as it allows other processes (usually the parent that created the process) to examine the return code of the process and see if the just-finished process executed successfully (usually, programs return zero in UNIX-based systems when they have accomplished a task successfully, and non-zero otherwise).
]
When finished, the parent will make one final call (e.g., `wait()`) to wait for the completion of the child, and to also indicate to the OS that it can clean up any relevant data structures that referred to the now-extinct process.
==== DATA STRUCTURE — THE PROCESS LIST
Operating systems are replete with various important data structures. The *process list* (also called the *task list*) is the first such structure.
Sometimes people refer to the individual structure that stores information about a process as a *Process Control Block (PCB)*, a fancy way of talking about a C structure that contains information about each process (also sometimes called a *process descriptor*).
== Interlude: Process API
=== The `fork()` System Call
=== The `wait()` System Call
=== The `exec()` System Call
=== Why? Motivating The API
The separation of `fork()` and `exec()` is essential in building a UNIX shell, because it lets the shell run code after the call to `fork()` but before the call to `exec()`; this code can alter the environment of the about-to-be-run program, and thus enables a variety of interesting features to be readily built.
```sh
prompt> wc p3.c > newfile.txt
```
In the example above, the output of the program `wc` is redirected into the output file `newfile.txt`, when the child is created, before calling `exec()`, the shell closes standard output and opens the file `newfile.txt`. By doing so, any output from the soon-to-be-running program `wc` are sent to the file instead of the screen.
=== Process Control And Users
There are a lot of other interfaces for interacting with processes in UNIX systems.
`kill()` system call is used to send signals to a process, including directives to pause, die, and other useful imperatives.
- control-c sends a `SIGINT` (interrupt) to the process (normally terminating it)
- control-z sends a `SIGTSTP` (stop) signal thus pausing the process in mid-execution
> you can resume it later with a command, e.g., the `fg` built-in command found in many shells.
To use this form of communication, a process should use the `signal()` system call to “catch” various signals.
Doing so ensures that when a particular signal is delivered to a process, it will suspend its normal execution and run a particular piece of code in response to the signal.
==== Who can send a signal to a process, and who cannot?
Modern systems include a strong conception of the notion of a user.
The user, after entering a password to establish credentials, logs in to gain access to system resources.
The user may then launch one or many processes, and exercise full control over them (pause them, kill them, etc.). Users generally can only control their own processes; it is the job of the operating system to parcel out resources (such as CPU,memory, and disk) to each user (and their processes) to meet overall system goals.
THE SUPERUSER (ROOT):A system generally needs a user who can administer the system, and is not limited in the way most users are.
=== Useful Tools
- `ps` command allows you to see which processes are running;
- `top` is also quite helpful, as it displays the processes of the system and how much CPU and other resources they are eating up.
#tip("Tip")[
Humorously, many times when you run it, top claims it is the top resource hog; perhaps it is a bit of an egomaniac.
]
- The command `kill` can be used to send arbitrary signals to processes, as can the slightly more user friendly `killall`.
- `MenuMeters`: CPU meters you can use to get a quick glance understanding of the load on your system, we can see how much CPU is being utilized at any moment in time.
*In general, the more information about what is going on, the better.*
== Mechanism: Limited Direct Execution
There are a few challenges, however, in building such virtualization machinery.
- *performance*: how can we implement virtualization without adding excessive overhead to the system?
- *control*: how can we run processes efficiently while retaining control over the CPU?
#tip("Tip")[
Control is particularly important to the OS, as it is in charge of resources; without control, a process could simply run forever and take over the machine, or access information that it should not be allowed to access.
]
=== Basic Technique: Limited Direct Execution
==== "direct execution" part
"direct execution" part idea: just run the program directly on CPU.
#image("images/2023-12-12-19-59-56.png",width: 80%)
problems:
- *protection*
- *time sharing*
Without limits on running programs, the OS wouldn’t be in control of anything and thus would be *just a library*
=== Problem #1: Restricted Operations
- Running on the CPU introduces a problem: What if the process wishes to perform some kind of restricted operation, such as:
- issuing an I/O request to a disk
- gaining access to more system resources such as CPU or memory?
#tip("Tip")[
Without giving the process complete control over the system. How can the OS and hardware work together to do so?
]
One simple approach: let any process do whatever it wants.
Absolutely a bad way, no protection at all!!
==== user/kernel mode
The approach we take is to introduce a new processor mode. known as *user mode*
- *user mode* code that runs in user mode is restricted in what it can do.
- For example, when running in user mode, a process can’t issue I/O requests; doing so would result in the processor raising an exception; the OS would then likely kill the process.
- *Kernel mode*, which the operating system (or kernel) runs in. Code that runs can do what it likes.
==== System call
What should a user process do when it wishes to perform some kind of privileged operation?
*System call*, allow the kernel to carefully expose certain key pieces of functionality to user programs.(accessing the file system, creating and destroying processes, communicating with other processes, and allocating more memory...)
==== Trap
To execute a system call, a program must execute a special trap instruction.
- This instruction simultaneously jumps into the kernel and raises the privilege level to kernel mode
- Once in the kernel, the system can thus do the required work for the calling process.
When finished, the OS calls a special *return-from-trap* instruction,
- returns into the calling user program
- while simultaneously reducing the privilege level back to user mode.
When executing a trap, the hardware must save enough of the caller’s registers in order to be able to return correctly when the OS issues the return-from-trap instruction. On x86, for example,
- the processor will push the program counter, flags, and a few other registers onto a per-process *kernel stack*;
- the return-from-trap will pop these values off the stack and resume execution of the user-mode program.
How does the trap know which code to run inside the OS?
The calling process can’t specify an address to jump to. Doing so would allow programs to jump anywhere into the kernel which clearly is a Very Bad Idea
When the machine boots up, it does so in privileged (kernel) mode, and thus is free to configure machine hardware as need be.
The kernel does so by setting up *a trap table* at boot time. The OS thus does is to tell the hardware what code to run when certain exceptional events occur:
- what code should run when a hard-disk interrupt takes place
- when a keyboard interrupt occurs
- when a program makes a system call.....
The OS informs the hardware of the locations of these trap handlers, usually with some kind of special instructions, and thus the hardware knows what to do (i.e., what code to jump to)when system calls and other exceptional events take place.
==== system call number
To specify the exact system call, *a system-call number* is usually assigned to each system call.
- The user code is thus responsible for placing the desired system-call number in a register or at a specified location on the stack;
- The OS, when handling the system call inside the trap handler, examines this number, ensures it is valid, and, if it is, executes the corresponding code.
This level of indirection serves as a form of *protection*; user code cannot specify an exact address to jump to, but rather must request a particular service via number.
==== WHY SYSTEM CALLS LOOK LIKE PROCEDURE CALLS
You may wonder why a call to a system call, such as `open()` or `read()`, looks exactly like a typical procedure call in C; that is, if it looks just like a procedure call, how does the system know it’s a system call, and do all the right stuff?
The simple reason: it is a procedure call, but hidden inside that procedure call is the famous trap instruction.
More specifically: the library uses an agreed-upon calling convention
- the kernel to put the arguments to open in well-known locations (e.g., on the stack, or in specific registers)
- puts the system-call number into a well-known location as well (onto the stack or a register)
- then executes the aforementioned trap instruction, puts the syscall return val into a well-known location too
- the code in the library after the trap unpacks return values and returns control to the program that issued the system call
Thus, the parts of the C library that make system calls are hand-coded in assembly, somebody has already written that assembly for you.
==== BE WARY OF USER INPUTS IN SECURE SYSTEMS
- There are still many other aspects to implementing a secure operating system that we must consider:
- One of these is the handling of arguments at the system call boundary; the OS must check what the user passes in and ensure that arguments are properly specified, or otherwise reject the call.
#example("Example")[
For example, with a `write()` system call, the user specifies an address of a buffer as a source of the write call. If the user passes in a “bad” address, the OS must detect this and reject the call.
]
In general, a secure system must treat user inputs with great suspicion.
==== Timeline
We assume each process has a kernel stack where registers (including general purpose registers and the program counter) are saved to and restored from (by the hardware)when transitioning into and out of the kernel.
#image("images/2023-12-12-20-37-13.png", width: 90%)
#tip("Tip")[
All privileged inst are highlighted in bold.
]
There are two phases in the *limited direct execution (LDE)* protocol.
=== Problem #2: Switching Between Processes
The next problem with direct execution is achieving a switch between processes.
Specifically, if a process is running on the CPU, this by definition means the OS is not running. If the OS is not running, how can it do anything at all? (hint: it can’t)
So how can the operating system regain control of the CPU so that it can switch between processes?
==== A Cooperative Approach: Wait For System Calls
One approach that some systems have taken in the past is known as the cooperative approach:
The OS trusts the processes of the system to behave reasonably.
Processes that run for too long are assumed to periodically give up the CPU so that the OS can decide to run some other task.
How does a friendly process give up the CPU in this utopian world?
Most processes, as it turns out, transfer control of the CPU to the OS quite frequently by making system calls.
Systems like this often include an explicit `yield` system call, which does nothing except to transfer control to the OS so it can run other processes.
Applications also transfer control to the OS when they do something illegal.
For example, if an application divides by zero, or tries to access memory that it shouldn’t be able to access, it will generate a trap to the OS.
The OS will then have control of the CPU again (and likely terminate the offending process).
Thus, in a cooperative scheduling system, the OS regains control of the CPU by waiting for a system call or an illegal operation of some kind to take place.
==== A Non-Cooperative Approach: The OS Takes Control
What if a process ends up in an infinite loop? In the cooperative approach, your only recourse when a process gets stuck in an infinite loop is to resort to the age-old solution to all problems in computer systems: *reboot the machine*.
How can the OS gain control of the CPU even if processes are not being cooperative? What can the OS do to ensure a rogue process does not take over the machine? *a timer interrupt*
- A timer device can be programmed to raise an interrupt every so many milliseconds.
- When the interrupt is raised, the currently running process is halted, and a pre-configured *interrupt handler* in the OS runs.
- At this point, the OS has regained control of the CPU, and thus can do what it pleases: stop the current process, and start a different one.
So:
- the OS must inform the hardware of which code to run when the timer interrupt occurs
- during the boot sequence, the OS must start the timer(privileged inst)
This hardware feature is essential in helping the OS maintain *control* of the machine.
===== REBOOT IS USEFUL
- Reboot is useful because it moves software back to a known and likely more tested state.
- Reboots also reclaim stale or leaked resources (e.g., memory) which may otherwise be hard to handle.
- Finally, reboots are easy to automate.
==== Saving and Restoring Context
Now that the OS has regained control(whether cooperatively via a system call, or more forcefully via a timer interrupt), a decision has to be made: whether to continue running the currently-running process, or switch to a different one.
#tip("Tip")[
This decision is made by a part of the operating system known as the *scheduler*
]
If the decision is made to *switch*, the OS then executes a low-level piece of code which we refer to as *a context switch*.
- All the OS has to do is save a few register values for the currently-executing process (onto its kernel stack, for example)
- And restore a few for the soon-to-be-executing process (from its kernel stack).
The OS will execute some low-level assembly code to
- save the general purpose registers, PC, and the kernel stack pointer of the currently-running process,
- and then restore said registers, PC, and switch to the kernel stack for the soon-to-be-executing process.
==== timeline
#image("images/2023-12-18-18-45-50.png", width: 80%)
In this example, Process A is running and then is interrupted by the timer interrupt.
- The hardware saves its registers (onto its kernel stack) and enters the kernel (switching to kernel-mode).
- In the timer interrupt handler, the OS decides to switch from running Process A to Process B.
- At that point, it calls the `switch()` routine, which carefully saves current register values (into the process structure of A), restores the registers of Process B (from its process structure entry), and then switches contexts, specifically by changing the stack pointer to use B’s kernel stack (and not A’s).
- Finally, the OS return-from-trap, which restores B’s registers and starts running it.
There are two types of register saves/restores that happen during this protocol
- The first is when the timer interrupt occurs; in this case, the user registers of the running process are implicitly saved by the hardware, using *the kernel stack of that process*.
- The second is when the OS decides to switch from A to B; in this case, the kernel registers are explicitly *saved by the software* (i.e., the OS), but this time into memory *in the process structure of the process*.
context switch code for xv6:
```asm
# void swtch(struct context *old, struct context *new);
#
# Save current register context in old
# and then load register context from new.
.globl swtch
swtch:
# Save old registers
movl 4(%esp), %eax # put old ptr into eax
popl 0(%eax) # save the old IP
movl %esp, 4(%eax) # and stack
movl %ebx, 8(%eax) # and other registers
movl %ecx, 12(%eax)
movl %edx, 16(%eax)
movl %esi, 20(%eax)
movl %edi, 24(%eax)
movl %ebp, 28(%eax)
# Load new registers
movl 4(%esp), %eax # put new ptr into eax
movl 28(%eax), %ebp # restore other registers
movl 24(%eax), %edi
movl 20(%eax), %esi
movl 16(%eax), %edx
movl 12(%eax), %ecx
movl 8(%eax), %ebx
movl 4(%eax), %esp # stack is switched here
pushl 0(%eax) # return addr put in place
ret # finally return into new ctxt
```
=== Worried About Concurrency
- What happens when, during a system call, a timer interrupt occurs?
- What happens when you’re handling one interrupt and another one happens?
The OS does indeed need to be concerned as to what happens if, during interrupt or trap handling, another interrupt occurs.*concurrency*
One simple thing an OS might do is disable interrupts during interrupt processing; doing so ensures that when one interrupt is being handled, no other one will be delivered to the CPU.
#tip("Tip")[
The OS has to be careful in doing so; disabling interrupts for too long could lead to lost interrupts, which is (in technical terms) bad.
]
Operating systems also have developed a number of sophisticated *locking schemes* to protect concurrent access to internal data structures.
This enables multiple activities to be on-going within the kernel at the same time, particularly useful on multiprocessors.
==== HOW LONG CONTEXT SWITCHES TAKE
There is a tool called `lmbench` that measures exactly those things, as well as a few other performance measures that might be relevant.
It should be noted that not all operating-system actions track CPU performance.
As Ousterhout observed, many OS operations are *memory intensive*, and memory bandwidth has not improved as dramatically as processor speed over time.
Thus, depending on your workload, buying the latest and greatest processor may not speed up your OS as much as you might hope.
=== Summary
The basic idea of LDE is straightforward: just run the program you want to run on the CPU, but first make sure to set up the hardware so as to limit what the process can do without OS assistance.
In an analogous manner, the OS “baby proofs” the CPU, by first (during boot time) setting up the trap handlers and starting an interrupt timer, and then by only running processes in a restricted mode.
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-aspect_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test that square doesn't overflow due to its aspect ratio.
#set page(width: 40pt, height: 25pt, margin: 5pt)
#square(width: 100%)
#square(width: 100%)[Hello there]
|
https://github.com/morrisfeist/cvgen | https://raw.githubusercontent.com/morrisfeist/cvgen/master/template/body.typ | typst | MIT License | #import "data.typ": data
#import "theme.typ": theme
#let header = block(
fill: theme.crust,
width: 100%,
outset: (left: 16pt),
inset: (left: 0pt, rest: 16pt),
)[
#align(horizon + start)[
#stack(
spacing: 16pt,
text(size: 18pt, fill: theme.primary, strong(data.name)),
line(stroke: 2pt + theme.primary, length: 40%),
text(size: 14pt, data.job_title),
)
]
]
#let profile = block(
breakable: false,
)[
#block[= #data.labels.profile]
#stack(spacing: 16pt, ..data.profile.map(paragraph => block[#paragraph]))
]
#let cv_item(name, institution, year, location, highlights) = {
let line_overhang = 4pt
block(breakable: false, inset: (x: -line_overhang))[
#grid(
columns: (1fr, auto),
align: (start, end),
row-gutter: 4pt,
inset: (x: line_overhang),
strong[#name],
text(fill: theme.subtext0)[#year],
text(fill: theme.subtext0)[#institution],
text(fill: theme.subtext0)[#location],
grid.hline(stroke: 0.5pt + theme.overlay0),
grid.cell(colspan: 2, inset: (x: line_overhang + 10pt, top: 8pt))[
#list(..highlights)
],
)
]
}
#let experiences = [
#block[= #data.labels.experiences]
#stack(spacing: 24pt, ..data.experiences.map(e => [
#cv_item(
e.at("position", default: ""),
e.at("company", default: ""),
e.at("year", default: ""),
e.at("location", default: ""),
e.at("highlights", default: ()),
)
]))
]
#let education = [
#block[= #data.labels.education]
#stack(spacing: 24pt, ..data.education.map(e => [
#cv_item(
e.at("degree", default: ""),
e.at("school", default: ""),
e.at("year", default: ""),
e.at("location", default: ""),
e.at("highlights", default: ()),
)
]))
]
#block(inset: 16pt)[
#let content = ()
#content.push(header)
#if data.profile.len() > 0 { content.push(profile) }
#if data.experiences.len() > 0 { content.push(experiences) }
#if data.education.len() > 0 { content.push(education) }
#stack(spacing: 24pt, ..content)
]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-2FF0.typ | typst | Apache License 2.0 | #let data = (
("IDEOGRAPHIC DESCRIPTION CHARACTER LEFT TO RIGHT", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER ABOVE TO BELOW", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER LEFT TO MIDDLE AND RIGHT", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER ABOVE TO MIDDLE AND BELOW", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER FULL SURROUND", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM ABOVE", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM BELOW", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM LEFT", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM UPPER LEFT", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM UPPER RIGHT", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM LOWER LEFT", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER OVERLAID", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM RIGHT", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM LOWER RIGHT", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER HORIZONTAL REFLECTION", "So", 0),
("IDEOGRAPHIC DESCRIPTION CHARACTER ROTATION", "So", 0),
)
|
https://github.com/appare45/Typst-template | https://raw.githubusercontent.com/appare45/Typst-template/main/file.typ | typst | #import "default.typ": template
#import "util.typ": Title
#let title = [タイトル]
#let author = sys.inputs.CREDIT
#show: doc => template(doc, title, author)
#Title(title, author)
= こんにちは
こんにちは
#pagebreak()
#include "class1/file.typ"
|
|
https://github.com/ljgago/typst-chords | https://raw.githubusercontent.com/ljgago/typst-chords/main/src/piano.typ | typst | MIT License | #import "./utils.typ": size-to-scale, parse-input-string, top-border-sharp, top-border-round, total-bounds, set-default-arguments
// A dictionary with the key names for the white-keys and their indices
#let white-keys-dict = (
"C1": 0,
"D1": 1,
"E1": 2,
"F1": 3,
"G1": 4,
"A1": 5,
"B1": 6, "C2b": 6,
"C2": 7, "B1#": 7,
"D2": 8,
"E2": 9, "F2b": 9,
"F2": 10, "E2#": 10,
"G2": 11,
"A2": 12,
"B2": 13, "C3b": 13,
"C3": 14, "B2#": 14,
"D3": 15,
"E3": 16, "F3b": 16,
)
// A dictionary with the key names for the black-keys and their indices
#let black-keys-dict = (
"C1#": 1, "D1b": 1,
"D1#": 2, "E1b": 2,
"F1#": 4, "G1b": 4,
"G1#": 5, "A1b": 5,
"A1#": 6, "B1b": 6,
"C2#": 8, "D2b": 8,
"D2#": 9, "E2b": 9,
"F2#": 11, "G2b": 11,
"G2#": 12, "A2b": 12,
"A2#": 13, "B2b": 13,
"C3#": 15, "D3b": 15,
"D3#": 16, "E3b": 16,
)
// Returns the indices of a key array of white-keys-dict or black-keys-dict
#let keys-to-array-index(dict, key-array) = {
key-array
.map(k => dict.at(k, default: none))
.filter(k => k != none)
}
// Remove the number of the key name (C1# -> C#)
#let normalize-key-name(key) = {
return key.replace(regex("\d+"), "").replace(regex("b$"), "\u{266D}")
}
// Gets the indices min and max of the layout
#let piano-limits-from-layout(layout) = {
return if layout == "C" {
(min: 0, max: 9)
} else if (layout == "2C") {
(min: 0, max: 13)
} else if layout == "F" {
(min: 3, max: 13)
} else { // "2F"
(min: 3, max: 16)
}
}
// Returns the white-keys amount in the layout
#let white-keys-amount-from-layout(layout) = {
return if layout == "C" {
10
} else if layout == "F" {
11
} else {
14
}
}
// Returns the black-keys amount in the layout
#let black-keys-index-from-layout(layout) = {
return if layout in ("C", "2C") {
( left: (1, 4, 8, 11), mid: (5, 12), right: (2, 6, 9, 13) )
} else {
( left: (4, 8, 11, 15), mid: (5, 12), right: (6, 9, 13, 16) )
}
}
// Draws the piano
#let draw-piano(self) = {
// draws the white-keys
let elements = {
for i in range(self.white-keys.amount) {
let key-pressed = i + self.limit.min
let fill-color = if key-pressed in self.tabs.white-keys-index { self.fill-key } else { white }
let dx = i * self.white-keys.width
let radius-design = if self.design == "sharp" {
0pt
} else {
if i == 0 {
(bottom: self.round, top-left: self.round)
} else if i == self.white-keys.amount - 1 {
(bottom: self.round, top-right: self.round)
} else {
(bottom: self.round)
}
}
place(
dx: dx,
rect(
width: self.white-keys.width,
height: self.white-keys.height,
radius: radius-design,
stroke: self.stroke,
fill: fill-color
)
)
}
// draw the black-keys
for i in range(self.white-keys.amount) {
let key-pressed = i + self.limit.min
let fill-color = if key-pressed in self.tabs.black-keys-index {self.fill-key} else {black}
let base = i * self.white-keys.width - self.black-keys.width / 2
let dx = 0pt
if key-pressed in self.black-keys.left {
dx = base - self.black-keys.shift
} else if key-pressed in self.black-keys.mid {
dx = base
} else if key-pressed in self.black-keys.right {
dx = base + self.black-keys.shift
} else {
continue
}
place(
dx: dx,
rect(
width: self.black-keys.width,
height: self.black-keys.height,
radius: if self.design == "sharp" {0pt} else {(bottom: self.round)},
stroke: self.stroke,
fill: fill-color
)
)
}
}
return (
bounds: (
dx: 0pt,
dy: 0pt,
width: self.piano.width,
height: self.piano.height
),
elements: elements
)
}
// Draws border top
#let draw-top-border(self) = {
let size = (
width: self.piano.width,
height: 1.2pt * self.scale
)
let elements = {
if self.design == "sharp" {
top-border-sharp(size, self.stroke, self.scale)
} else {
top-border-round(size, self.stroke, self.scale)
}
}
return (
bounds: (
dx: 0pt,
dy: -size.height,
width: size.width,
height: size.height
),
elements: elements
)
}
// Draws tabs or dots over the piano
#let draw-tabs(self) = {
// draws tabs on white-keys chord
let elements = {
for i in self.tabs.white-keys-index {
if i < self.limit.min or i > self.limit.max {
continue
}
let radius = 1.7pt * self.scale
let dx = (i - self.limit.min + 0.5) * self.white-keys.width - radius
let dy = self.piano.height - 4pt * self.scale - radius
place(dx: dx, dy: dy, circle(radius: radius, stroke: none, fill: black))
}
// draws tabs on black-keys chord
for i in self.tabs.black-keys-index {
if i < self.limit.min or i > self.limit.max {
continue
}
let radius = 1.7pt * self.scale
let dx = 0pt
let dy = self.black-keys.height - 3.5pt * self.scale - radius
let base = (i - self.limit.min) * self.white-keys.width - radius
if i in self.black-keys.left {
dx = base - self.black-keys.shift
} else if i in self.black-keys.mid {
dx = base
} else if i in self.black-keys.right {
dx = base + self.black-keys.shift
} else {
continue
}
place(dx: dx, dy: dy, circle(radius: radius, stroke: none, fill: black))
}
}
return (
bounds: (
dx: 0pt,
dy: 0pt,
width: self.piano.width,
height: self.piano.height
),
elements: elements
)
}
// Draws pressed note names
#let draw-key-notes(self) = {
let note-offset = 1.8pt * self.scale
let elements = {
// white-keys
let white-keys = self.keys
.map(key => (white-keys-dict.at(key, default: none), normalize-key-name(key)) )
.filter(arr => arr.at(0) != none)
for (i, key-name) in white-keys {
if i < self.limit.min or i > self.limit.max {
continue
}
let dx = (i - self.limit.min + 0.5) * self.white-keys.width
let dy = self.piano.height + note-offset
place(dx: dx, dy: dy, place(center + top, text(6pt * self.scale)[#key-name]),
)
}
// black-keys
let black-keys = self.keys
.map(key => (black-keys-dict.at(key, default: none), normalize-key-name(key)) )
.filter(arr => arr.at(0) != none)
for (i, key-name) in black-keys {
if i < self.limit.min or i > self.limit.max {
continue
}
let dx = 0pt
let dy = -(self.top-border-height + note-offset)
let base = (i - self.limit.min) * self.white-keys.width
if i in self.black-keys.left {
dx = base - self.black-keys.shift
} else if i in self.black-keys.mid {
dx = base
} else if i in self.black-keys.right {
dx = base + self.black-keys.shift
} else {
continue
}
place(dx: dx, dy: dy, place(center + bottom, text(6pt * self.scale)[#key-name]))
}
}
let border = 1.2pt * self.scale
let size = (:)
size.key = measure(text(6pt * self.scale)[~])
size.total = (
width: self.piano.width,
height: self.piano.height + (note-offset + size.key.height) * 2 + border
)
return (
bounds: (
dx: 0pt,
dy: -(note-offset + size.key.height + border),
width: size.total.width,
height: size.total.height
),
elements: elements
)
}
// Draws the chord name below the piano
#let draw-name(self) = {
let size = (:)
size.name = measure(text(12pt * self.scale)[#self.name])
let vertical-offset = 10pt * self.scale
let dx = self.piano.width / 2
let dy = self.piano.height + vertical-offset
let anchor = top
if self.position == "bottom" {
let border = 1.2pt * self.scale
dx = self.piano.width / 2
dy = -(vertical-offset + border)
anchor = bottom
}
let elements = {
place(
center + anchor,
dx: dx,
dy: dy,
box(
fill: self.background,
outset: 2pt * self.scale,
radius: 2pt * self.scale,
text(size: 12pt * self.scale, ..self.text-params)[#self.name]
)
)
}
if self.position == "bottom" {
dy -= size.name.height
}
dx = (self.piano.width - size.name.width) / 2
return (
bounds: (
dx: dx,
dy: dy,
width: size.name.width,
height: size.name.height
),
elements: elements
)
}
// Render the piano
#let render(self) = context {
let objects = (
draw-piano(self),
draw-top-border(self),
draw-tabs(self),
draw-key-notes(self),
draw-name(self),
)
let init = (
bounds: (dx: 0pt, dy: 0pt, width: 0pt, height: 0pt),
elements: []
)
let (bounds, elements) = objects.fold(
init,
(acc, (bounds, elements)) => {
return (
bounds: total-bounds(acc.bounds, bounds),
elements: acc.elements + elements
)
}
)
box(
width: bounds.width,
height: bounds.height,
place(
left + top,
dx: -bounds.dx,
dy: -bounds.dy, {
elements
}
)
)
}
/// Generates a piano chord.
///
/// - ..text-params (auto): Embeds the native *text* parameters from the standard library of *typst*. *Optional*.
///
/// - keys (str): Keys chord notes from *C1* to *E3* (Depends on your layout). *Optional*.
/// #parbreak() Example: ```js "C1, E1b, G1"``` (Cm chord)
///
/// - layout (str): Sets the layout and size of the piano, ```js "C"```, ```js "2C"```, ```js "F"```, ```js "2F"```. *Optional*.
/// - ```js "C"```: the piano layout starts from key *C1* to *E2* (17 keys).
/// - ```js "2C"```: the piano layout starts from key *C1* to *B2* (24 keys, two octaves).
/// - ```js "F"```: the piano layout starts from key *F1* to *B2* (19 keys).
/// - ```js "2F"```: the piano layout stars from key *F1* to *E3* (24 keys, two octaves).
///
/// - fill-key (color): Sets the fill color of the pressed key. *Optional*.
///
/// - design (str): Sets the piano design. *Optional*.
/// - ```js "sharp```: piano with sharp corners.
/// - ```js "round```: piano with round corners.
///
/// - position (str): Sets the chord chart position. *Optional*.
/// - ```js "top"```: chord chart in top position.
/// - ```js "bottom"```: chord chart in bottom position.
///
/// - background (color): Sets the background color of the chord name. *Optional*.
///
/// - name (str, content): Shows the chord name. *Required*.
///
/// -> content
#let piano-chord(
..text-params,
keys: "",
layout: "C",
fill-key: gray,
design: "sharp",
position: "top",
background: rgb(0, 0, 0, 0),
name
) = {
assert.eq(type(keys), str)
assert.eq(type(fill-key), color)
assert.eq(type(background), color)
assert(upper(layout) in ("C", "2C", "F", "2F"), message: "`layout` must to be \"C\", \"2C\", \"F\" or \"2F\"")
assert(design in ("sharp", "round"), message: "`design` must to be \"sharp\" or \"round\"")
assert(position in ("bottom", "top"), message: "'position' must to be '\"bottom\"' or '\"top\"'")
assert(type(name) in (str, content), message: "type of `name` must to be `str` or `content`")
let (size, font, ..text-params) = set-default-arguments(text-params.named())
set text(font: font)
let scale = size-to-scale(size, 12pt)
let step = 7.5pt
let layout = upper(layout)
let white-keys-amount = white-keys-amount-from-layout(layout)
let black-keys-index = black-keys-index-from-layout(layout)
let piano-limits = piano-limits-from-layout(layout)
let keys = parse-input-string(keys)
let self = (
white-keys: (
width: step * scale,
height: 25pt * scale,
amount: white-keys-amount,
),
black-keys: (
width: (step / 3) * scale * 2,
height: 17pt * scale,
shift: 1pt * scale, // small shifting of the black-keys
left: black-keys-index.left, // black-keys index with left shift
mid: black-keys-index.mid, // black-keys index without shift
right: black-keys-index.right, // black-keys index with right shift
),
piano: (
width: white-keys-amount * step * scale,
height: 25pt * scale
),
tabs: (
white-keys-index: keys-to-array-index(white-keys-dict, keys),
black-keys-index: keys-to-array-index(black-keys-dict, keys)
),
text-params: text-params,
round: 1pt * scale,
stroke: black + 0.5pt * scale,
top-border-height: 1.1pt * scale,
keys: keys,
limit: piano-limits,
fill-key: fill-key,
scale: scale,
design: design,
position: position,
background: background,
name: name,
)
render(self)
}
|
https://github.com/ukihot/igonna | https://raw.githubusercontent.com/ukihot/igonna/main/articles/rust/exercise.typ | typst | == 例題
=== じゃんけん
BobとCarolは、以下のルールに従って$N$回じゃんけんを行った。
- グー>チョキ、パー>グー、チョキ>パー
- 勝者に$1$点
- 勝者が連続したとき、$+1$点多く付与
$ "input" <- mat(
N;
B_i, C_i;
dots.v, dots.v;
B_N, C_N;
) $
BobとCarolの得点をそれぞれ計算せよ。
ただし、以下の条件を制約とする。
- $1 <= N <= 300$
- $B_i, C_i in {1, 2, 3}$
=== ナンバー2
$N$個の整数列が与えられるとき、その中で2番目に大きな数と小さな数をそれぞれ出力せよ。
ただし、この整数列は重複する数を含む場合がある。
$ "input" <- mat(
N;
x_0, dots.h, x_N;
) $
=== 門番
$N$行$M$列のマス目がある。
$N$行$1$列目のマス目がスタート地点、$1$行$M$列目がゴール地点とする。
スタート地点とゴール地点以外のマス目にはそれぞれ一人ずつ門番が入っている。
$i$行$j$列目から$i$行$j+1$列目のマスに移動するには、門番へ$p_"i{j+1}"$円支払う必要がある。
ゴール地点までへ到達するまでにかかるコストの最小値を求めよ。
ただし、以下の条件を制約とする。
$ "input" <- mat(
N, M;
p_00, p_01, dots.h, p_"0M";
p_10, p_11, dots.h, p_"1M";
dots.v, dots.v, dots.down, dots.v;
p_"N0", p_"N0", dots.h, p_"NM";
) $
$ p_"N0", p_"0M" = 0 $
- 斜め移動不可
=== 文字列
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/019%20-%20Magic%20Origins/001_Chandra’s Origin: Fire Logic.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Chandra’s Origin: Fire Logic",
set_name: "Magic Origins",
story_date: datetime(day: 10, month: 06, year: 2015),
author: "<NAME>",
doc
)
#figure(image("001_Chandra’s Origin: Fire Logic/01.jpg", width: 100%), caption: [Art by Chase Stone], supplement: none, numbering: none)
= City of Ghirapur, Plane of Kaladesh
Eleven-year-old <NAME> climbed through a shower of sparks. One or both of her parents were welding somewhere up the mine shaft from her and she grinned as the little flecks of fire bounced off her red hair. She climbed hand-over-hand up the web of scaffolding that clung to the walls of the tunnel. Today was finally the day. Her parents were inventors, her grandparents had been inventors, ancestors throughout Chandra’s family had been inventors. Today was the day she would finally embrace what had always been her chosen destiny: to become a deliverer of canisters.
Inventing had never been her strong point.
It wasn’t that she didn’t appreciate devices. Her world was full of wondrous inventions and marvels of clicking, gear-driven artificial life. It was just that somehow her patience seemed to end sometime before her projects did. And somehow, sometime during the construction phase, her fist almost invariably wound up colliding with the face of someone who deserved it.
It was a personal failing. She accepted it.
She had tried other callings. She set her mind to becoming a master artist, and had a roomful of snapped paintbrushes and ripped canvases to prove it. She had tried applying herself to schoolwork, until she was sent home with bruised knuckles and a headmaster’s note. She had never quite found her place in a world governed by clockwork and consuls. But today her true calling would begin.
Maybe Chandra would never be a metalsmith like her father or an ingenious artisan like her mother, but in a world that ran on elegant machines, she could supply the power source—the mystical Æther—to those who needed it. The supply of Æther was tightly controlled by the consuls, but her parents knew ways of procuring it, and they always helped those who needed fuel for their inventive passions.
Chandra clambered over the railing onto the platform where her father was at work on one of his own metallic creations. He pushed his thick-lensed goggles up on his head, leaving a raccoon mask of clean skin around his eyes. "Chandra! Haven't I told you to keep inside the safety railing? Why did I even build that thing?"
"It makes a much better ladder," Chandra said. She hugged his waist. "So. Father dearest. I’m ready to go. Did you know that I’m ready to go? I’m informing you now. Ready."
Her father rolled his eyes. "I’m not going to try to instill the virtue of patience in you. But I’m not the one to talk to. Your mother has it."
Her mother clanked down a tight coil of stairs, wearing heavy gloves and an embroidered shawl around her hips. She carried a metal canister with all the ceremony of a birthday cake. "Her inaugural solo delivery! Oh, just look at her, Kiran! She’s going to burst. Here, daughter, come and help me seal this before the shipment explodes—or you do."
Chandra’s mother set down the canister. The lid shimmered and hissed with a thin jet of effervescent vapor. In the same time it took for her father to gasp a word—"Careful!"—Chandra had given the canister a swift kick with her boot. The lid dented in, but it stopped hissing. Chandra grinned.
"I can tell already you’re going to be the best courier this city has ever seen," said her mother with a wink.
#figure(image("001_Chandra’s Origin: Fire Logic/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Chandra tipped her chin up like mock royalty. "Please prepare all my medals and trophies for when I return. I’ll try to remember you all when I am the world’s most important outlaw."
"We prefer ‘vehicles of grassroots change,’" her father said. "But this is a serious responsibility, Chandra. The consuls have been stepping up patrols. People need what we can provide, but if we bring them trouble they will turn against our cause. Your mother and I are reaching out to find people we can trust."
Chandra took the canister into her satchel and slung it on her back. "And today we’re trusting the old lady who lives by the Foundry."
"<NAME>, yes," said her father.
"She was always fond of you," said her mother. "Remember, she’ll know the signal. Those who know the signal know us for who we truly are."
"I already know who I am. Chandra, the World’s Finest Courier."
Her mother gave her an awkward hug, patting the canister on her back. "Your father and I believe in you. You know the route. You know the city. You’ll do great."
"Just be sure no one follows you back here," added her father, but Chandra was already climbing.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The sun dazzled her eyes. The city of Ghirapur moved like a living thing, the architecture adapting to the needs of the gearcrafters, thopter-builders, clockforgers, and other inventors and artisans who swarmed through it. Chandra struggled her way through the crowd, pulling on a school tunic with her teeth, the canister clanking against her back.
#figure(image("001_Chandra’s Origin: Fire Logic/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The thoroughfare was jammed with too many people. She made a decision and took a perpendicular turn toward the canal. Two halves of a bridge glided to meet each other with a series of metallic clicks, merging to become a span over the canal, and Chandra hopped over the gap before it had completely come together. She diagonaled through the gates of the Akhara, a huge, round plaza ringed with tiered seats, skipping across the gears that rotated in the pavement and the raised dais in the center, dodging a clique of jabbering Ætherologists.
She took two more out-of-the-way turns and stopped at a baked-clay wall inlaid with vibrant mosaic tile portraits of great inventors. The surface was sheer and smooth, but she put her boot into a notch above one inventor’s nose and clambered over, dropping down onto a pathway painted with slashing stripes.
When she hit the ground, a group of soldiers, straight-backed and clean-cut, stood in her path: consuls’ forces. They wore standard-issue snapblades strapped to their forearms, and one had an Æther-charged dart-thrower.
"Where are you off to, young one?" one of them asked. "This is a restricted corridor." He noted Chandra’s uniform, a replica of the ones some kids wore to the Builder’s Institute. "Shouldn’t you be in school?"
"I’m in a hurry," said Chandra. "And my examiner will eat me alive if I’m late again, so if you’ll excuse me…"
"As I’m sure you’re aware, miss, this is a restricted corridor," said a second soldier. The snapblade clicked out from his forearm mount, its edge glittering. "The thoroughfare for pedestrians is back on the other side of the courtyard."
"And the school bell already rang," said the first soldier. "You sure you’re a student?"
"You wouldn’t be transporting illegal goods, would you?"
"Hand over the bag, please."
Prickly heat crossed Chandra's brow. She couldn’t dodge past them, and she couldn’t exactly make a run for it.
"If I get another demerit, I’m done," she said, glancing from the soldier’s gleaming blade up into his eyes. "Can’t you just let me go?"
One of them nodded to the other one. "Get out the Æther detector."
Chandra shifted her weight away from the one who’d seized her, then jabbed sideways, elbowing another of the soldiers in the gut. She rebounded and slammed her fist into the collarbone of the first. #emph[That was probably a bad idea] , she thought an instant after having done it. Such was fist logic.
The soldiers collapsed on her like a trap. Their hands took hers behind her back, so that she could only look down at the street. She kicked one in the shins and tried to head-butt one in the chest, but she couldn’t get free. A flood of heat and fury washed through her, and she clenched her teeth.
The soldiers halted. Another set of feet approached.
"<NAME>," one of the soldiers said.
Chandra wrestled to her feet and looked up at him. <NAME> was a monolith of a man, stout and statuesque, with a face that seemed to taunt those around it for being of lesser handsomeness. The other soldiers stood silently.
"What’s the problem here?" he asked, looking at Chandra but not addressing her, his voice a gravelly whisper.
"Uncooperative, sir. A possible truant."
"We told her this wasn’t the thoroughfare for pedestrians."
Captain Baral smirked down at her. "You have to use small words with these street children," he whispered. "Simple commands. ‘Sit.’ ‘Stay.’"
Chandra’s hands squeezed into fists. Rage spread through her fast, like a lit box of matches, igniting all the nerves in her body. Heat spread down her arms, into her hands, still held behind her back.
"I know you’re not a student," said Baral. "Slide the bag off your shoulders and hand it to me."
"No."
"I don’t think you understand, child. You’re already in violation of the law in a half-dozen ways. Comply, or I will make you comply." He put his hand on Chandra’s shoulder—gently, but with no tenderness in it. It was a clinical touch, somehow revolting in its cold detachment.
Chandra’s muscles tensed and she jerked away, making a sound through her teeth. She wanted to lash out, to yell, to throw her fury out at him.
And then something happened that had never happened to her before. Her hands glowed from within, illuminating the bones and blood vessels and the lines in her palms. Growing in intensity, the heat erupted through her skin until her hands were engulfed with fire like two torches. Chandra yelped in shock and stood there, dazzled, looking back and forth between her hands as they burned.
#figure(image("001_Chandra’s Origin: Fire Logic/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The soldiers backed away in a semicircle. Captain Baral stood still, surprise turning to genuine interest.
Chandra shook her hands. They didn’t go out. She thought about patting them against herself, but thought better of it. She looked to the men, too upset for words, gesturing with her burning hands. Strangely, her skin was not burning. The flames enveloped her hands, but there was no pain.
Baral put his hand out to her again. "Let me help you with that, child."
"Get back!" Chandra instinctively waved away the aggressor, creating a blazing arc of fire in the air. The men backed away. The fire evaporated, and for a moment, everyone just blinked.
Chandra burst into a run. She slipped between two of the soldiers, both of whom made an inadequate half-motion to stop her, and she was gone. Behind her, she heard Baral’s gravel-throated whisper become a growl. "I want whirlers after her. Now."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Chandra took a series of turns through the streets, leaving the consuls’ soldiers and a tangle of bewildering emotions behind her. She kept glancing down at her hands, but they appeared to be nothing but hands now. There was no sign of the self-immolating craziness from moments before. It wasn’t that she hadn’t seen magic before; inventors regularly built creations that defied explanation, made even more wondrous by the power of Æther. But conjuring fire without the use of a device—that was new to her.
#figure(image("001_Chandra’s Origin: Fire Logic/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
She ran onto a bridge back in the direction of home, but froze midway across. Rising almost silently into view were three ornate flying roterothopters, beating the air with their spinning rotors, each one with a large lens staring right at her.
She still had the canister. She wasn’t sure whether she was still eligible for the World’s Finest Courier Award at this point—she wondered if there was an award for Worst—and most of all she wanted badly to run home. But that would lead the whirlers there, directly to her family. The flying spies would report on all of her parents’ activities, and she was sure <NAME> would come for them. She wasn’t sure what the punishment was for trafficking in Æther supplies. But she had heard stories of harsh and painful sentences carried out in the Akhara, in front of crowds of people.
The whirlers dipped and swung through the air toward her, staying just behind her as she fled back across the bridge. It was hard to escape on foot something that flew; the whirlers rose easily over obstacles she had to run around and she had to keep checking what was directly in front of her. She ducked into narrow alleys and dashed through shops, but the whirlers nimbly curved around to meet her when she came out the other side.
#figure(image("001_Chandra’s Origin: Fire Logic/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
She approached a familiar spire: the Consuls’ Foundry, the Æther-powered factory that mass-produced automatons for the consuls. She was about to circle around it and head deeper into the city when she heard her name.
"Chandra?" It was Mrs. Pashiri, Chandra's contact and a friend of the Nalaar family. She was emerging from the main doors of the Foundry, a set of keys in her hand.
"Mrs. Pashiri!" cried Chandra, out of breath.
"What’s wrong, dear? We weren’t supposed to meet here."
"They’re after me," Chandra said, pointing over her shoulder at the oncoming whirlers. Then she hesitated, remembering her parents’ warnings of whom to trust, and eyeing the ring of keys to the Consuls’ Foundry. On reflex, her fists tightened.
But <NAME> made a loop with her forefinger and thumb, and held them near her forehead, as if she were pushing up a pair of goggles. It matched the signal Chandra’s parents had shown her. When Mrs. Pashiri made the gesture, she made it with reverence, almost a salute. "The Nalaars and I go way back, child," she said.
Chandra vacillated. She could hear the whirlers’ approach. She wanted to trust her contact, this family friend who knew the right gesture, but the set of keys meant some kind of connection to the consuls. Options spun around her.
Mrs. Pashiri’s eyes narrowed as she looked past Chandra and saw the whirlers. She turned and unlocked the Foundry door again. "Get in here. Go out the back. I’ll distract them."
It was the last place Chandra would have chosen to enter. As she debated, <NAME> produced a delicate copper bird from her tunic. The bird came to life, fluttering its feather-etched wings, and launched toward the whirlers. The copper bird collided with one of the whirlers and exploded, sending a shower of pieces down to the street.
"Get inside," said Mrs. Pashiri with a sharp nod, producing a little bat of silver filigree. "The machinists aren’t in yet. Go, dear. Get to safety."
Chandra ran inside as Mrs. Pashiri began yelling insults at the whirlers.
#figure(image("001_Chandra’s Origin: Fire Logic/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The interior of the Foundry was a still life of silent machinery. Half-assembled automata hung motionless, suspended by their torsos at machinists’ stations. Legs and grippers stood in racks, waiting for their turn to be riveted together and become another mass-produced servitor. The main overhead lamps were dark, and the only light was from a round glass skylight in the domed ceiling. A huge pylon, planted in the center of the space, soared up to the top of the dome. Automatic arms and gear-driven manipulators were folded against the pylon like a duck’s wings.
Chandra crept between assembly stations and filigreed gears, looking for the other exit. She heard another small explosion outside, and Mrs. Pashiri’s invectives faded into the distance. Chandra heaved a full-chested sigh of gratitude for the distraction.
She heard a ticking sound high above. Up on the ceiling, a series of elegant gears turned, and the skylight swiveled open. An unmistakable whisper of rotors heralded the last whirler, which descended through the skylight and found her with its eye.
A series of orange lamps flickered on across the foundry ceiling, cascading to life in a spiral pattern. The arms of the pylon stirred, splaying out its surprisingly long limbs and clawlike grippers. All around the foundry floor, artifact creatures unhitched themselves from their mountings and pivoted their heads toward her under the lurid light of the lamps.
A surge of heat flooded through her body. Her hands tingled and began to glow.
"No, thank you," she said to her hands. "Not again. No, no, no."
She pushed past one small artifact creature and elbowed another out of the way. She spied the exit, but a huge, six-legged machine stepped in the way of it. She turned back to the entrance, but that way looked even worse. Automata came out of nowhere, striding or shuffling for her.
A gear-driven humanoid construct reached out to her. Instead of hands it had metal shackles, and it reached for her wrists with its fetter-claws. She punched it, because that was fist logic. But instead of connecting, her fist threw a blast of fire, knocking back the construct and smashing it into scorched pieces on the ground. Another artifact creature crept at her and she fire-punched it too, flame erupting out of her at the point of impact. Her hands bloomed with fire again. These were beautiful machines, and she was in no way in control of her fire skill, but there was no time to stop and think. She raged forward with a progression of shouts and blows, scorching her intricate assailants one by one as they surrounded her.
#figure(image("001_Chandra’s Origin: Fire Logic/08.jpg", width: 100%), caption: [Art by Daarken], supplement: none, numbering: none)
She tried to cut her way to the rear exit but the horde of Foundry servitors came at her too fast, and the big, six-legged monstrosity still stood guard at the door. The whirler even had the audacity to swing low, sprout a bladed claw, and nip at her back.
She whipped around and yelled at it. Its rotor blades somehow caught fire and it tilted, collided with the pylon, and fell to the ground in a flaming heap.
Chandra remembered that she hadn’t actually made the delivery to Mrs. Pashiri. The canister of Æther was still on her back. As she turned back to the door guardian, a very bad idea occurred to her.
"Let’s see what you can do, hands," she said. With her fingers still aflame, she grabbed the satchel off her back and flung the canister at the rear doors. The canister cracked against the multilegged door guardian and hit the foundry floor, knocking the lid loose. A spurt of Æther hissed from the container.
Chandra willed all of her fire and fury at the canister; she didn’t have time to worry about whether it was the right thing to do.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The dark of the underground shanty was cold comfort. When Chandra ran down the stairs, her mother doused a welding wand and her father raised his goggles. They could see the look on her face and the charred edges of her tunic.
"I…I have to tell you something," said Chandra.
They embraced her. "Are you hurt? Are you burned? What happened?"
"I’m all right," she said, trembling in their arms. "I made…I made fire."
"You set a fire? On the delivery?"
"No. I #emph[made] it," said Chandra, breaking her parents’ embrace. "With my hands. I ran into some consuls’ soldiers and I got mad, and my hands caught fire."
Her mother’s eyes went wide. She grabbed Chandra’s hands in hers, and turned them over and back, scanning them. "Were you hurt? Was anybody hurt?"
"Wait," said her father. "You encountered consuls’ forces?"
"Nobody got hurt." Chandra felt a heaviness, a sodden blanket of guilt, at the prospect that someone might have been hurt because of her. Her shoulders fell. A lump welled up in her throat. "I mean, there was—I caused—damage. At the Foundry."
"The Consuls’ Foundry?"
"<NAME> helped me get in. But I had to get through the door, and I may have destroyed it."
"Destroyed the door?"
"Destroyed the Foundry."
Her parents looked at each other. Their mouths opened and closed as if they were trying to say something, but no words came. Finally her father turned to her.
"Your hands caught fire, without a device? Spontaneously?"
Chandra’s eyes threatened tears, but she smeared them away with her wrist. "Yes."
"And your skin did not burn?"
"My shirt did, some, here."
"Can you…show me?"
"I don’t know if I can do it on command. It came out when I didn’t want it to. What’s wrong with me?"
"Chandra! Oh, Chandra." Her mother wrapped her arms around her, squeezing her so that her face pressed against her mother’s neck.
"I know," Chandra mumbled. She wanted to reach around her mother, but she kept her hands at her sides. She squeezed a tear into her mother’s embroidered shawl. "I’m…I’m a freak."
"Honey, you’re not a freak," her mother said. She broke the embrace and kept her hands on Chandra’s shoulders, looking at her face, her lips pressed together. "You’re a pyromancer."
"If that’s what you call someone with matches for hands, then that’s me."
"Listen to me," her mother said. Her eyes were intense. "This is a gift. You have something special, something that’s not been seen in many years."
Chandra heard this, but the words didn’t latch onto anything in her mind. She searched her mother’s face for some clue.
"I don’t understand."
"Your fire," her mother said. "It’s a form of magic. A special kind. But it’s something that intimidates them. If it’s something you can do without machines, without the need for Æther…you do it your own way, you see? And they hate that."
"They need the people to need them," said her father. "And if you don’t need them, you become a threat."
Chandra balled her fists. How could two little hands cause so much trouble?
"Now Chandra, I have to ask you. Did anyone follow you here?"
"I think I blew up everything that could have followed me."
"And the soldiers you met. Did they identify you?"
"They might have. I don’t know. But I lost them back by the arena. Father?"
"Yes?"
"I’m not ever going to be the World’s Finest Courier, am I?"
Her mother pressed her hand against her lips, holding back tears.
Her father took Chandra’s little hands in his large ones. "You #emph[are] the World’s Finest, my Chandra. The finest any mother or father could ask for. No matter what happens."
Chandra nodded, and her father hugged her, and her mother touched her hand. Somehow just being herself, just being their daughter, meant so much for them. She wondered what they saw, what being World’s Finest Chandra meant.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The darkness spoke her name.
#emph[Chandra.]
It came at her as if it were muttered through molasses, unreal at first. Her consciousness seized on it and it dragged her up.
#emph[Chandra.]
Her mother’s voice was soft, but the hand on her shoulder was firm. "Chandra. Let’s go, honey. It’s time to get up."
Her room was dark, lit only by her parents’ handlights. Strangely the darkness woke her much sooner than morning’s light would have. Darkness didn’t fit the routine. Darkness meant something was wrong, even more wrong than yesterday.
Knapsacks. Tool belts. Armfuls of possessions.
"Wh—? Where are we going?"
"Grab a bag and follow your father."
"What’s going on?"
Her mother pressed a knapsack into Chandra’s arms. They climbed the stairs to the heavy segmented door that formed the entrance to their home. Her father rolled the door closed and her mother welded it shut with a wand. They headed out into the night, their home in their hands, stealing from shadow to shadow. They didn’t speak, and Chandra didn’t ask questions as they climbed into the back of a waiting wagon and put a blanket over themselves.
#figure(image("001_Chandra’s Origin: Fire Logic/09.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The villages had no names. Dirt roads replaced the mobile mosaic courtyards of Ghirapur. Thatched roofs replaced rotating towers. Bent-over field laborers replaced stirring portraits of inventor-heroes. A simple shift dress and sandals replaced Chandra’s tunic and boots. Even her identity was replaced, as her parents told her to introduce herself and them with counterfeit names. They gave her a navy-blue scarf to wear over her red hair, a scarf she promptly lost.
They learned not to unpack. Chandra and her parents stayed only for a few days at a time, sometimes moving on to the next village after only a few hours’ sleep.
"How long will we be here?" Chandra asked as they arrived by cart in a new village.
"Not long," said her father. "Our home is the road for the time being. I’d advise you to get used to it."
"Are we having fun?" Chandra asked, half-jokingly.
"It’s an adventure, yes," her father said in a flat voice.
Whenever her family drove over a rise, Chandra looked back at the city, comparing the distance to the last time she could see the skyline. Every time she looked, the vivid structures paled, the sharp spires and bright copper domes of the city swallowed up by the broad shapes of the mountain range around it. She would scan her father’s face at these times, searching for some kind of confirmation that this wasn’t hard on him, that it hadn’t crushed his spirit to be away from his little forge and his projects. She was adapting to this time on the road, even enjoying it, but she believed in her heart that this journey was all because of her, because of the trouble she had caused.
She spent her days roaming the villages and their surrounding woods, chasing peckingbirds from their coops and exploring the elevated paths of intertwined tree branches. The villagers had smiles worn into their faces, and they nodded to her and let her be. Her mother said that rules were only words used by people who wanted something, and these people wanted nothing from her, so she wallowed in freedom. She collected seeds and heavy fruit and other gifts from the woods, and left them at village doorsteps. She thought about her fire sometimes, but she did not seek it out, and it didn’t show itself. She thought of her power like one of her discarded devices back in Ghirapur—unfinished, unmastered, and abandoned.
On a bright day when she had thought nothing of fire and almost nothing of soldiers, she found a treasure in the trees. A huge, corrugated horn jutted from between two heavy branches. It curved in a sinuous shape, with striations that would hold paint nicely—a fine gift for someone in the village. She climbed up to the prize and wrested it free, letting the horn fall to the earth.
When she hopped down to the ground, a herd of furred beasts surprised her. Their horns matched the one she had found—she was clearly in their territory. Their snouty lips pulled back to reveal tusks meant for tearing flesh. They bellowed in her face.
She bellowed in theirs.
Her fire came readily, without thinking, as natural as the impulse to run. She carved handfuls of fire as she ran, cupping her hands as if she were grabbing clay out of the air, grazing the beasts’ faces with it and cutting off their paths. She threw flame without hesitation, without burning her sleeves, without trying. There was no negotiation with the fire this time. She needed it and it came to her.
#figure(image("001_Chandra’s Origin: Fire Logic/10.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The beasts dispersed with only singed fur or superficial burns, leaving Chandra alone with her heaving breaths and the glow in her cheeks. She found a trail and walked back to the village, clasping her hands together with a secret smile on her face. She didn’t tell her parents she had almost been gored to death by a herd of woodland creatures, but they pointed out that she had barely eaten anything at dinner. She couldn’t, not with the excitement making little explosions in her stomach.
That night she tossed and turned on her cot, unable to sleep. She traced a finger down the lines of one palm, feeling the contours of the bones in her hand, then switched hands and traced lines on the other. There was something in her that no one else shared, something that left her breathless, like painting still lifes or delivering canisters never could. She lay awake for hours, imagining a moth fluttering around inside her chest—a moth made of fire, burning but not consumed.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
A candle in a filigree enclosure cast elaborate shadows around the walls of Captain Baral’s office. A messenger in uniform entered, touching her fist to her chest in salute. Capt<NAME> looked up from his desk.
"Report, soldier," said the captain in his low rasp.
"We have word from one of our scouts, sir," said the messenger.
"They’ve seen her?"
"All the three of them. The Nalaars have fled the city."
"You have a location?"
"Only an approximate one. They’re hiding out in the outskirts, moving from village to village. Whirlers have caught sight of them once or twice."
Captain Baral’s mouth twisted. "Return to me when you have specifics. You’re released."
"But…sir? There’s something else."
Capt<NAME> just raised his eyebrows at her.
She placed a missive marked with an official stamp on the desk. "Sir, the consuls recommend that we cease the search. Their missive claims we’re expending large amounts of Æther to track the Nalaars. Sir, we’ll be sure to apprehend them if they attempt to return to Ghirapur. The consuls just don’t consider them worth the resources to pursue them."
"This is not about a couple of fugitives, soldier," said the captain, not raising his voice above an even whisper. "It’s about the future. We need to show the people of this city that we’re prepared to move beyond the barbaric age of the past, to embrace progress. The girl is a remnant of a chaotic time. An obstacle. If we’re going to move forward, we’ll need our path to be clear. The consuls will understand that."
"Yes, sir," said the messenger. "We’ll find them."
"Good. I want a skyship and a detachment of soldiers at the ready."
The messenger hesitated. "Sir? Are we prepared for a fight, should we encounter them? The girl’s fire magic—it’s powerful."
"We have nothing to fear from her, for we are members of an enlightened society of builders and creators." Baral reached for the filigree cage on his desk that contained a small taper, and opened a little door in the cage. The shadow of his hand loomed across the walls. Baral didn’t touch the flame, but only held his hand near it. The flame dimmed and went out, leaving a sinuous line of smoke. "We know that fire never creates—it only destroys. Ultimately it will bring nothing but ruin to its wielder."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"You wanted to see me?" Chandra asked, entering the modest dwelling in their latest host village.
"Come in," said her father, patting a wooden bench. "Sit down."
Chandra brushed dust off of her tunic instead of sitting. "Wait. Is this your ‘We have to have a serious talk about your behavior, young lady’ voice? Or is it ‘I want you to know I’ll always be there for you, darling daughter’ voice? I can’t tell."
"Always the latter. Today, a bit of the former as well. Sit."
Chandra sat. "Is this ‘We found out you set some stuff on fire, and that’s bad?’"
"Using your gift is never bad," her father said. "It’s what’s special about you, and that will always be a good thing. It’s just that…not everyone sees it that way."
"Is this about the beasts? Who told?"
"It’s just that some of the people in this village—they rely on the animals of the forest to survive. They’re helping us hide out, because they don’t get along with the consuls."
"The consuls’ forces. They’re who’re after us."
"That’s right. The people here are volunteering to keep us safe. So when we’re out here, we’re their guests. We have to play by their rules."
"Mother says there are no rules out here."
"I’m not sure you’re quite capturing her position. We owe our hosts a lot for their generosity. We must use our gifts in ways that don’t interfere with their lives."
"It’s #emph[fire] . What’s the point of saying it’s good if it’s against everybody’s rules?"
"You just have to be more careful. I have something for you, something that should help." Her father handed her a small mechanism. It was a finely-etched metal box with vents on one side. It had a shoulder strap and a flexible cable that led into it.
Chandra turned it over in her hands. "What is it?"
"It’s called a vent pack. It’s based on an old invention from long ago. Your mother and I made this for you."
"Should I be greeting this with skepticism? Because I am."
"Try it on."
Chandra stood and looped the strap over her shoulder. The vent pack settled in the small of her back. Her father touched the loose end of the cable to a spot of bare skin near her shoulder blade, and it adhered to her skin.
"What does it do? It’s heavy." She twisted around to look at it. The metal of it felt cold through her shirt. And at the place where the cable met her skin, she felt a slight electrical charge.
Her father put his hand to his chin and regarded her. "Now some bad news. I’m afraid you can’t go back into the woods again. Ever."
Chandra whirled on him. "#emph[What?] Why?"
The pack hissed, venting a quantity of steam.
"Test successful," her father said.
Chandra narrowed her eyes. "Skepticism turning to outright distrust, dear father."
"I’m sorry. The vent pack converts excess energy into steam. The design is usually used for safely offloading surplus power in Æther collectors. In your case, your temper is an energy source. It feeds your gift. And this will help you control it."
Chandra frowned. "So when I wear this, I won't be able to produce fire?"
"It should dampen your gift so that it will only manifest in a safer form. It won’t go off when you don’t want it to. And you’ll wear it all the time now."
The vent pack hissed. She thought of the image of the fluttering fire moth, but now imagined it enclosed inside the vent pack, choking and dissipating into smoke. Maybe fire magic was something no one was supposed to enjoy. She felt suddenly childish.
Her father squeezed her arm. "This is for your own good, and for the safety of our village hosts."
Chandra sighed and collapsed back down. "Father. Us being out here. Is it because of me? Because of what I did at the Foundry?"
"Chandra, listen to me." Her father put his arms around her. "Your mother and I are very proud of the person you’re becoming. You’re the most important thing in the world to us. We want you to know that everything we do, we do to keep you safe, and to make the world a better place for our family. Nothing else matters."
Her father broke the hug. She looked up at him, and his smile was warm and real. The metal corner of the vent pack poked into her back uncomfortably, but she held back and didn’t remark.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The day the soldiers surrounded the village, Chandra was exploring in the woods, her vent pack tapping against her back as she walked. She didn’t notice them approaching the homes, didn’t even hear the skyship descending. It was only when she heard the shouting that she ran back to the village and saw them.
They wore the same uniforms as those who had stopped her in the restricted corridor back in Ghirapur. Weapons were affixed to their forearms, and many of them carried lit lanterns, despite it being the middle of the day. One of them was tall and confident, and spoke to the others in a hoarse whisper. <NAME>. Somehow he had found them.
#figure(image("001_Chandra’s Origin: Fire Logic/11.jpg", width: 100%), caption: [Art by Daarken], supplement: none, numbering: none)
The soldiers created a human fence around the village, crossing their arms and displaying their snapblades. One woman from the village shouted at them, and at Captain Baral’s order, the soldiers shoved her back.
Chandra’s vent pack gave a puff of steam. She stamped out of the woods at them. "Hey!" she shouted. "You looking for me? If you want me, here I am!"
The soldiers looked at each other. "It’s the Nalaar girl."
"My name," she said, standing up to chest-height, "is Chandra. Leave these people alone. They’ve done nothing wrong. Take me."
"We will take you," said <NAME>. She had forgotten the way his low voice sounded like stones being ground to dust. "Because you and yours are a danger to yourselves and to the public." He turned to the woman and the other villagers. "You may go."
The villagers moved away, the adults ushering the children into their homes. Chandra scanned for her parents, but couldn't see them among the crowd.
"I'm not a danger," she said. "Not anymore." She swung her vent pack around for Baral to see. A constant trail of steam curled out of its vents.
"Your very existence is a danger," Baral whispered. "Do you know how we found you, child? These people finally gave you up."
"That’s a lie. My parents said they were keeping us safe."
"Your parents’ crimes are many, but your crimes are far worse, pyromancer. You’re an instrument of chaos and death. How many people have you killed?"
"No one. I just broke some of your mass-produced toys."
Baral’s mouth curled up at one edge, revealing his teeth. "That’s not what I heard. I heard you were responsible for dozens of deaths, in this very village." He nodded to the other soldiers. "Do it."
The soldiers used their lanterns to light the thatched roofs of the village buildings. They caught fire immediately, spewing thick, ugly smoke.
"No!" Impulsively, Chandra extended her arms to blast them with fire, but nothing emerged. Steam sizzled from her vent pack. Baral smiled, and something glimmered in his eyes.
"Chandra!" Her father came running from around the building. "Chandra, run! This way!" He hurled a small copper orb onto the ground at the soldiers’ feet. It exploded in a blast of light, spraying their faces with glimmering motes. They moaned and clapped their hands over their eyes.
Chandra ran into the village, her father close behind. She raced between the dwellings of the village, now consumed with fire and screams. Smoke rolled through the dirt pathways, cloaking the way back to the building where her family had been staying. She barreled ahead, trying to keep an eye on where her father was.
When she emerged from the smoke, she was on the opposite side of the village. Fire blazed tall, consuming entire buildings. People staggered out of the village, shrieking, rolling in the dirt to put themselves out. Baral’s soldiers stood by, doing nothing to help the victims. This would be blamed on her, she realized. She was the one who scared the woodland beasts with her fire, and so some villager must have contacted <NAME>. And now all this fiery death would be on her hands, because she was the pyromancer. She had been tricked so easily, and Baral had all but stated it right to her face.
The soldiers caught sight of her. She turned to run the other way, but she slipped on something and fell. Her foot had caught on a slippery piece of fabric, trampled in the dirt. She took it in her hands. It was her mother's shawl, the one she always wore around her, with its characteristic embroidery. It was smoking and singed from fire. She realized she was in front of the dwelling where they were staying, and it was consumed in fire.
"Mother!" she yelled, suddenly unable to get up and run again. "No!"
The soldiers deployed the razor-sharp blades at their forearms. They parted to let Captain Baral approach her. He had a simple dagger in his hand, and towered over her. She couldn’t force herself to move.
"The arena will have an excellent show," whispered Baral. "The consuls enjoy making an example of dissidents. And the crowds enjoy shows of force, when it doesn’t involve them."
Her father appeared out of the village smoke. He shoved himself between them, wedging himself between Chandra and the soldiers. "Enough," he said, coughing. "Take me. I’m the one you want. I yield."
Baral approached her father, put one hand on his shoulder, and stabbed him through the gut with a dagger. Her father gasped and crumpled, falling to his knees, holding his stomach in his hands. He glanced at Chandra for a moment, and she saw his last emotion in his eyes—not fear, but disappointment that he couldn’t do better for her. He bent over, shuddering, and fell to the ground.
#figure(image("001_Chandra’s Origin: Fire Logic/12.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Chandra didn’t hear the sound she made at that moment. The world became enveloped in steam and smoke, and the uniforms of soldiers. She didn’t feel the clink of cuffs around her wrists, the dainty loops of copper filigree that held like heavy iron. She didn’t feel the vent pack blasting steam. She didn’t feel herself being walked to the skyship, stepping over the threshold and put in her seat, gripping her mother’s shawl. And she didn't see the plumes of smoke trailing away from the village as the skyship rose and turned its nose around toward Ghirapur. She only saw her father crumpling down into the mud, over and over again, and heard the disheartened sigh of his final breath leaking out of him.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The executioner was tall and broad; his face was hidden by a hood with a filigree mask. More relevant to Chandra's situation was that his forearm ended in a massive cutting blade. It may have been fitted over a hand, but to Chandra it looked grafted on, fused into the entire deadly costume of the executioner’s role. He walked in a circle around Chandra, tracing the perimeter of the central dais of the arena. It was the Akhara, the same courtyard Chandra had cut across when making her failed delivery only a few weeks ago. Now the stands were filled with people gathered to watch the grim spectacle.
She looked down at the delicate cuffs that held her wrists firmly in place. Her hands didn’t look like the weapons of a pyromancer, but like an ordinary child’s hands.
A squat announcer in a silk robe read her sentence in a booming voice. "For crimes against the public good, destruction of the honored Foundry of Ghirapur, and for the deaths of three people in the fire in the village of Bunarat, this citizen has been sentenced to meet the blade of justice."
As he read, Chandra tried to muster her fire. But it didn’t come to her. She could feel something pressing down on her, dulling any fire she could muster. She still wore the vent pack on her back, now resting just above her mother’s shawl. The pack wasn’t hissing. Her rage was gone, along with her father. Chandra scanned the crowd for any sign of her mother—if she were alive, she would doubtless be here, trying to stop this, trying to save her daughter. But nothing stopped the announcer’s speech, which made it clear to Chandra. Her mother must be dead as well.
She had nothing left. Maybe it was only right that the executioner take her life.
"Today we all learn a difficult lesson about the limits of compassion and the importance of vigilance," the announcer continued. "Today we learn that, for some, no amount of direction, no amount of moral guidance, can be enough. Some are born with destruction built into them, and for the good of us all, these must be eliminated."
Maybe she wasn’t meant to go on. Maybe she was never meant to be the best at anything. Maybe she was just a freak after all, a monster with a "gift" that could only cause those around her pain. Maybe no one could trust her, could love her for who she was. Maybe she should just lower her head and accept her fate.
Something in the crowd caught her eye. It was <NAME>, her contact from the foundry. Mrs. Pashiri nodded to her from the crowd, her mouth a thin, taut line, her eyes glazed with defiant tears. Slowly, Mrs. Pashiri raised her hand. Her fingers closed into a circle by her forehead—the Nalaar signal, like a pantomime of her father’s welding goggles, performed like a salute.
Chandra’s fists squeezed. The vent pack hissed, then whistled like a tea kettle. She kept her eyes held on <NAME>, that gesture, that respect for who she was. She was a Nalaar. She was <NAME>.
"This citizen’s continued existence endangers us all," said the announcer. "So for the sake of us all, she meets the demands of justice. Bladebearer, please step forward."
As the executioner took three ritualized steps toward Chandra, the blade slid out from his arm, doubling its deadly length. Chandra’s whole body tensed. The vent pack’s whistling turned to a sputter as something boiled within her.
#figure(image("001_Chandra’s Origin: Fire Logic/13.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The executioner leaned his masked face close to Chandra’s. "I know you’re trying, pyromancer," he said in a gravelly whisper.
Chandra tore her eyes away from Mrs. Pashiri and looked directly into his mask, her teeth gritted. She knew the voice instantly. "Baral."
She could see Baral’s eyes through the filigree of the mask, and his glare was utterly cold. She could feel the weight of his presence on her, the pressure of his antimagic.
"You and I aren’t the only mages this world has seen," he whispered. "But I’ll be the last you’ll ever know." He tilted back from her slowly, letting the blade swing out and up for all the crowd to see.
Chandra focused on <NAME> in the crowd. The old lady never lowered her hand. Chandra’s wrists strained at the restraints, but she couldn’t move. This was her final moment.
Baral raised the blade high. Chandra heard the announcer give the order: "Swing."
Every one of her muscles tensed. She reached inside, grasping for something, anything—and she found the fiery moth, its bright wings fluttering. It was a tiny but rebellious source of light, undeterred, undoused. It was her, she realized—a manifestation of her gift, but also a manifestation of herself. She was her fire, and her fire was her. She felt a tiny part of what it meant to be a pyromancer, what it meant to be alive, what it meant to be Chandra.
In a slow instant, the blade arced down through the air toward her neck. Chandra felt the prickling sensation wash over her like a wave of coals. Her vision flickered at the edges, blurring out Baral and the announcer and everything around her. The arena and the crowd warped in a molten haze. She felt the sputtering steam from her vent pack turn to white-hot liquid, barely aware that the pack had melted into slag, and was dripping down her leg and burning through the stone dais.
#figure(image("001_Chandra’s Origin: Fire Logic/14.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Her hands caught fire, flash-melting the restraints. Her arms caught fire. Her shoulders and torso caught fire. She turned her face away, but the flame spread up her face. Her hair became a blaze of incandescence. Her eyes roasted, becoming red-hot orbs in their sockets.
She uttered a scream of fury, and the scream became an explosion. A cascade of fire blasted out from her, enveloping the dais, enveloping her captors, enveloping the entire world. Everything she could perceive was bathed in fire.
She held her flaming arms over her flaming head, and squeezed her flaming eyes shut tight. Her ears rang, deafened and roaring at once. A moment or an eternity passed. One moment she thought she heard the screams of Baral, and the next she had the sensation of being blown out like a candle, or of rushing through a tornado and coming out the other side.
When she opened her eyes, the smoke from her blast still cloaked the world around her. Her clothes fumed, and her vent pack was gone. When she heard voices of people approaching her, she readied more fire, preparing to throw it at her captors once again. The fire came to her readily, like a trusted ally.
The smoke cleared enough for her to see the people who approached her. They didn’t look like consuls’ enforcers, or like anyone she had ever known: tall and noble, robed like monks, with ash streaked on their faces like ornate masks. Behind them rose a hilltop of roughly sculpted rock, with stairs leading up to a monumental archway leading into the mountain. Craggy stone architecture bloomed from the mountain, lit by brazierless trails of fire, and the air smelled of hot gases and baking earth.
The arena was nowhere to be found. The entire city, her entire world had abandoned her—or she had abandoned it.
Chandra sputtered in terror. The monks reached out their hands to her in a calming gesture, and one of them said something in a soothing tone.
So she summoned up her will and blasted all of them with fire. Fire logic.
Somehow, though, the raging funnel of flame did not harm them. One of the monks raised his hand and her fire subsided, attenuating and becoming a warm glowing ring that encircled her and them together. The monk nodded to her.
"Greetings, pyromancer," said the monk. "You are welcome here."
#figure(image("001_Chandra’s Origin: Fire Logic/15.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
|
|
https://github.com/enseignantePC/2023-24 | https://raw.githubusercontent.com/enseignantePC/2023-24/master/TODO.typ | typst | #let ok = sym.checkmark
+ 1ère activité prête
+ cours buffer, annexes, énigme
+ le premier chapitre
+ activité
+ $ok$
+ exercices
+ cours $ok$
Corps purs et mélange
- Précision de la verrerie
- Masse volumique?
- Identification corps pur vs mélange
- CCM
Ondes sonores
- Mesure célérité du son
- Production d'un son microctrl
Solutions
Masse volumique?
- préparation par dilution et dissolution
|
|
https://github.com/chendaohan/rust_tutorials | https://raw.githubusercontent.com/chendaohan/rust_tutorials/main/books/7.函数(function).typ | typst | #set heading(numbering: "1.")
#set text(size: 15pt)
= 函数的要点(演示在`main()`中)
- 函数名和变量名使用蛇形命名法(snake case),例如 fn add_two() -> {}
- 函数的位置可以随便放,Rust 不关心我们在哪里定义了函数,只要有定义即可
- 每个函数参数都需要标注类型
|
|
https://github.com/alberto-lazari/computer-science | https://raw.githubusercontent.com/alberto-lazari/computer-science/main/advanced-topics-pl/presentation/script.md | markdown | # Markup
## Procedural markup
- Troff?
- TeX
## Descriptive
- LaTeX: TeX but structure
- Markdown
# Typst
## Syntax modes
- Markup
- Math
- Code
# Markup mode
But wasn't the presentation about programming languages?
Actually, everything's a function and modes are just a syntactic sugar for (pure) function calls
- Content type
- Joining
# Code
- Type system
- Value types (no reference types): reference counting in the implementation, to avoid unnecessary copies
## Functions
- Closures
- Pure
- First class values
- Recursion
### Parameters
- Named vs LaTeX
- Partial application
# Compiler
## Evaluation
- Markup
- Bindings
## Modules
- Immutable
- Caching (introspection)
# New vs old
Comparisons between the Typst way and LaTeX, highlighting the rigidity of macros and simplicity of a complete syntax
- Syntax: consistency and syntactic sugars
- Diagnostic
- Automatability and computational foundations
|
|
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Diagrams/rendered/ER_Translation.typ | typst | #image("ER_Translation.svg") |
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/scripting/arguments.md | markdown | MIT License | # Advanced arguments
## Spreading arguments from list
Spreading operator allows you to "unpack" the list of values into arguments of function:
```typ
#let func(a, b, c, d, e) = [#a #b #c #d #e]
#func(..(([hi],) * 5))
```
This may be super useful in tables:
```typ
#let a = ("hi", "b", "c")
#table(columns: 3,
[test], [x], [hello],
..a
)
```
## Key arguments
The same idea works with key arguments:
```typ
#let text-params = (fill: blue, size: 0.8em)
Some #text(..text-params)[text].
```
# Managing arbitrary arguments
Typst allows taking as many arbitrary positional and key arguments as you want.
In that case function is given special `arguments` object that stores in it
positional and named arguments.
> Link to [reference](https://typst.app/docs/reference/foundations/arguments/)
```typ
#let f(..args) = [
#args.pos()\
#args.named()
]
#f(1, "a", width: 50%, block: false)
```
You can combine them with other arguments. Spreading operator will "eat" all remaining arguments:
```typ
#let format(title, ..authors) = {
let by = authors
.pos()
.join(", ", last: " and ")
[*#title* \ _Written by #by;_]
}
#format("ArtosFlow", "Jane", "Joe")
```
## Optional argument
_Currently the only way in Typst to create optional positional arguments is using `arguments` object:_
TODO
|
https://github.com/comforttiger/lipu-sona-pi-toki-pona | https://raw.githubusercontent.com/comforttiger/lipu-sona-pi-toki-pona/main/README.md | markdown | Creative Commons Attribution Share Alike 4.0 International | # lipu sona mi pi toki pona
## contributing translations
to contribute a new translation, fork this repo, and make a new folder for your translation in the `content/` directory. name it the language code of the language you're translating to. copy the contents of `en/` as a starting point, and then just start translating! when you're done, make a pull request and i'll take a look at it :)
### building
if you want to look at your translation on the site before making the pull request:
1. install dependencies
```bash
npm install
```
2. start the development server
```bash
npm run dev
```
3. take a look!
visit `http://localhost:3000/<language-code>`!
## translating the pdf
if you wanna go the extra mile, you can translate the pdf too. the pdf is written with typst, you can find the english pdf's typst file in `/public/en/pdf/`.
or you can just translate the `.optional.md` file in `/content/en`, and then i'll add your translation to the pdf for you. |
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/复习/光电子材料与器件复习/temple/pkuthss-typst-main/README.md | markdown | # PKUTHSS-Typst
Typst template for dissertations in Peking University (PKU).
![PKUTHSS-Typst](./images/cover.png)
The full PDF file is available [here](./build/thesis.pdf).
## Usage
- Install the latest version of [Typst](https://github.com/typst/typst)
- Download and extract the entire folder
- Modify `thesis.typ`
- Run `typst compile thesis.typ --font-path fonts` to compile the thesis
|
|
https://github.com/Scriptorgames/JIF-JUFO-Paper | https://raw.githubusercontent.com/Scriptorgames/JIF-JUFO-Paper/main/jif.typ | typst | #import "template.typ": *
#show: ams-article.with(title: [JIF - Roboter & Controller GUI], authors: (
(name: "<NAME>"),
(name: "<NAME>"),
(name: "<NAME>"),
), abstract: {}, bibliography-file: "refs.bib")
= Einleitung
Roboter, Software; Technik, Informatik: Zwei spannende Themen, die, nebenbei
bemerkt, extrem gut zusammenpassen. Genau das ist, was wir uns gedacht haben,
oder zumindest so ähnlich, als wir beschlossen haben, uns bei dem diesjährigen
Jugend Forscht Wettbewerb anzumelden. Wir, das sind <NAME>, <NAME> und <NAME>, arbeiten schon seit einigen Jahren immer wieder in
Wahlkursen und jetzt auch im P-Seminar an Robotern, hatten 2023 sogar einen
kleinen Auftritt auf der Consumenta-Messe, in Zusammenarbeit mit Schülern
anderer Schulen, die auch an dem Projekt teilgenommen haben. Da dieses Projekt
vorbei ist, haben wir uns überlegt, im Alleingang ein Robotik-Projekt in Angriff
zu nehmen.\
\
Das Projekt ist in drei Teile aufgeteilt: Die Hardware, also den Roboter selbst
hat Jonas gebaut, die Software, die den Roboter erst zum Leben erweckt hat Ilian
entwickelt und die Benutzeroberfläche zum Steuern des Roboters stammt aus der
Feder von Felix. Natürlich ist das keine Einteilung mit festen Grenzen, sodass
sich auch hin und wieder gegenseitig geholfen werden konnte, wenn man mal wieder
spontan vergessen hat wie ROS funktioniert oder ähnliche Probleme...\
\
Die Arbeit ist folgendermaßen gegliedert: Zunächst wird die Hardware, dann die
Software vom Roboter und zuletzt das GUI behandelt. Zuletzt folgt noch ein
Fazit.
#pagebreak()
= Roboter
== Fahrgestell und Karosserie
Das Fahrgestell ist nicht von uns designt worden, eben so wenig wie der
Kettenantrieb. Dies war auch nicht notwendig, da Dejan von HowToMechatronics
eine wunderbare Basis für unser Vorhaben bereits geschaffen hatte.
@howtomechatronics2024 Auf dieser Basis wurde eine Karosserie für unsere Zwecke
in Fusion360 erstellt mit zwei aufklappbaren Deckeln, die die Wartung an dem
Roboter erleichtern. Um die elektronischen Komponenten auf dem Fahrgestell zu
befestigen, wurden Adapterstücke konstruiert, da die Löcher des Fahrgestells für
andere Komponenten designt wurden. Ebenso wurden stärkere Federn in den Dämpfern
eingebaut die 10 Newton in etwa maximal Belastung haben. Der Schlitz auf der
Oberseite des Hinterendeckels ist für die Kabelführung der Webcam.
#image("pictures/JifFusion.png")
#pagebreak()
== Hardware
Der Roboter wird von zwei 37mm 12V DC-Motoren mit 66rpm betrieben, welche
angesteuert werden über zwei L298N H-Brücken, wobei jeder Motor mit einem der
Motoren verkabelt ist. Die Steuerung der H-Brücken hat ein ESP32 development
board, welches seriell mit einem Raspberry Pi 3B+ verbunden ist, inne. Die
Stromversorgung übernimmt ein 12V 5000mAh LiPo-Akku, der die Motortreiber direkt
versorgt, parallel dazu geschaltet ist ein Abwärtswandler, welcher die 12V auf
5V konvertiert und so den Raspberry Pi mit Strom versorgt. Man stellt sich
sicherlich die Frage warum zwei H-Brücken verbaut wurden, wenn man an einem 2
Motoren anschließen kann, aber eine H-Brücke kann maximal 2 Ampere abgeben, was
sich dann auch auf beide Motoren aufteilen würde was zu einem Leistungsverlust
führt, da jedem Motor nur 1 Ampere zugewiesen werden kann. Um diese Problematik
zu lösen wurden zwei H-Brücken verbaut und so können jedem Motor 2 Ampere
zugewiesen werden. Leider ist aber immer noch ein Spannungsabfall zu bemerken.
So wird ein zukünftiger Schritt sein ein Motortreiber zu verbauen, welcher eine
noch höhere Stromstärke stemmen kann.
#image("pictures/SchaltplanUpdate.png")
== micro-ROS
Um den ESP32 vom ROS2-Netzwerk aus anzusteuern, wurde micro-ROS verwendet. Dazu
wurde zuerst ein neues Workspace erstellt, welches für das Flashen und dem
micro-ROS-Agent zuständig sein wird. Anschließend noch ein src Ordner in dem
micro-ROS Workspace erstellen, wo dann das micro_ros_setup Package hinein
geklont wurde. @microros2024 Nachdem ersten Build ist nun ein firmware Ordner zu
sehen, in dem Verzeichnis ,".../microros_ws/firmware/freertos_apps/apps", wurde
dann die ros_esp32cam_diffdrive App geklont. @reinbert2024 Nach dem
Konfigurieren und dem Builden konnte der ESP32 auch schon geflasht werden. Nun
fehlte nur noch der micro-ROS-Agent. Nach dessen Builden und Starten konnte man
unter den Topics auch unser /cmd_vel finden. Somit war der erste Teil der Basis
geschaffen.
#pagebreak()
= Containerisierung des ROS2 environments für Entwicklung auf einem nicht-Ubuntu Gerät
Zum Aufsetzen eines simplen Containers für ROS2 mussten wir uns zuerst mehrere
essenzielle Fragen stellen: Welche Ordner sollten dauerhaft bestehen bleiben?
Wollen wir grafische Oberflächen unterstützen? Welche Software wollen wir
nutzen? Wie speichern wir unseren Containerstand zwischen?
== Podman
Podman ist unser Container Manager. Jetzt fragt man sich, warum nicht Docker?
Hier eine kurze Übersicht, warum ich mich für Podman entschieden habe.
- Kein Daemon, daher keine verpflichtenden Admin-Rechte
- Daher keine Nutzerrollen nötig, um einen Container ohne sudo rechte zu starten
- Sogenannte 'Pods', die es ermöglichen mehrere Container zu gruppieren und zu
Verwalten
- Daher ist es auch möglich, in diesem Fall eine Robotersimulation und einen
Client-Container in ein privates Netzwerk zu packen und eine ungehinderte
Simulation bzw. Testphase ablaufen zu lassen.
- Mir kommt das Containerstand speichern sehr simpel vor. Dies ist für später
häufiger notwendig.
\
Außerdem habe ich mehrere Probleme mit Docker gehabt und mich deshalb dazu
entschieden, mal etwas anderes zu probieren.
== Graphische Oberflächen
Ich dachte mir zu Beginn, dass ein reiner Development-Container keine GUIs
braucht, da es ja genug Terminal Text-Editioren gibt. Nach jedoch etwas
Überlegung sollte klar sein, dass ein GUI zur Kontrolle des Roboters fast
unverzichtbar ist (beispielsweise für die Kamera).
#sc[```bash
podman run -it \
# ...
--env DISPLAY=${DISPLAY} \ #Für Übergabe der Display env-var
--env PULSE_SERVER=unix:${XDG_RUNTIME_DIR}/pulse/native \ #Für die audio Übergabe der GUIs
--env PULSE_COOKIE=/run/pulse/cookie \ #Audio
--env QT_AUTO_SCREEN_SCALE_FACTOR=1 \ #Set QT screen scale to 1 so you dont get weird scaling issues
--env XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR} \ #Ordner mit Sockets und Pipes
#Viele verschiedene Geräte oder virtuelle Geräte für die Video Übertragung
--device /dev/dri \
--device /dev/input \
--device /dev/nvidia0 \
--device /dev/nvidiactl \
--device /dev/nvidia-modeset \
--device /dev/nvidia-uvm \
--device /dev/nvidia-uvm-tools \
#Mounten(Anschließen) von Ordnern, die für Videobearbeitung verantwortlich sind
--mount type=bind,source=${XDG_RUNTIME_DIR}/pipewire-0,target=${XDG_RUNTIME_DIR}/pipewire-0 \
--mount type=bind,source=$XAUTHORITY,target=/tmp/.host_Xauthority,readonly \
--mount type=bind,source=/etc/localtime,target=/etc/localtime,readonly \
--mount type=bind,source=/tmp/.X11-unix,target=/tmp/.X11-unix \
--mount type=bind,source=${XDG_RUNTIME_DIR}/pulse/native,target=${XDG_RUNTIME_DIR}/pulse/native \
--mount type=bind,source=${HOME}/.config/pulse/cookie,target=/run/pulse/cookie \
--mount type=bind,source=${HOME}/.local/share/fonts,target=/usr/share/fonts,readonly \
--mount type=bind,source=/usr/share/fonts,target=/root/.local/share/fonts \
# Das ist n bissel komisch eingerückt ...
```]
== Synchronisierte Ordner
Das Folgende ist nötig, da sonst die Konfigurationen und Änderungen verloren
gehen würden. Im Grunde mounten wir nur Konfig Dateien und den Workspace, um
keinen Datenverlust zu haben und damit unsere Daten nicht davon abhängig sind,
ob der Container noch existiert oder nicht.
#sc[```bash
# ...
--mount type=bind,source=${HOME}/Dokumente/Docker/ros2-humble/workspace,target=/root/workspace\
--mount type=bind,source=${HOME}/Dokumente/Docker/ros2-humble/shared,target=/root/shared\
--mount type=bind,source=${HOME}/Dokumente/Docker/ros2-humble/.bashrc,target=/root/.bashrc \
--mount type=bind,source=${HOME}/Dokumente/Docker/ros2-humble/.config,target=/root/.config \
# ...
```]
== Containerstände Zwischenspeichern
#term(
ps1: [`$`],
input: [podman export {ContainerName} -o {Dateiname}.tar],
output: [Dieser Befehl speichert den momentanen Containerzustand in einer tar Datei],
)
Der Containerzustand ist jetzt in einer Datei gespeichert, jedoch ist es so
nicht so simpel einen neuen Container mit `podman run` zu starten. Daher müssen
wir nun den Containerzustand als eigene Vorlage für einen neuen Container
speichern.
#term(
ps1: [`$`],
input: [podman import {DateiName(Unsere tar)} {template-name}],
output: [Dieser Befehl sorgt dafür, dass der Container der Datei als template genommen
werden kann und daher Dinge wie `podman run {template-name}` möglich sind],
)
#pagebreak()
== Gesamtergebnis
#sc[```bash
#!/bin/bash
# sudo damit network-host funktioniert. Dies ist für ROS fast zwangsweise notwendig.
sudo podman run -it \
--name ros2-humble-io \
--userns=keep-id \
--network=host \
--env DISPLAY=${DISPLAY} \
--env PULSE_SERVER=unix:${XDG_RUNTIME_DIR}/pulse/native \
--env PULSE_COOKIE=/run/pulse/cookie \
--env QT_AUTO_SCREEN_SCALE_FACTOR=1 \
--env XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR} \
--device /dev/dri \
--device /dev/input \
--device /dev/nvidia0 \
--device /dev/nvidiactl \
--device /dev/nvidia-modeset \
--device /dev/nvidia-uvm \
--device /dev/nvidia-uvm-tools \
--device /dev/bus/usb \
--device-cgroup-rule='c 81:* rmw' \
-v /dev/video0:/dev/video0 \
--mount type=bind,source=/sys,target=/sys \
--mount type=bind,source=${HOME}/Dokumente/Docker/ros2-humble/workspace,target=/root/workspace\
--mount type=bind,source=${HOME}/Dokumente/Docker/ros2-humble/shared,target=/root/shared\
--mount type=bind,source=${HOME}/Dokumente/Docker/ros2-humble/.bashrc,target=/root/.bashrc \
--mount type=bind,source=${HOME}/Dokumente/Docker/ros2-humble/.config,target=/root/.config \
--mount type=bind,source=${XDG_RUNTIME_DIR}/pipewire-0,target=${XDG_RUNTIME_DIR}/pipewire-0 \
--mount type=bind,source=$XAUTHORITY,target=/tmp/.host_Xauthority,readonly \
--mount type=bind,source=/etc/localtime,target=/etc/localtime,readonly \
--mount type=bind,source=/tmp/.X11-unix,target=/tmp/.X11-unix \
--mount type=bind,source=${XDG_RUNTIME_DIR}/pulse/native,target=${XDG_RUNTIME_DIR}/pulse/native \
--mount type=bind,source=${HOME}/.config/pulse/cookie,target=/run/pulse/cookie \
--mount type=bind,source=${HOME}/.local/share/fonts,target=/usr/share/fonts,readonly \
--mount type=bind,source=/usr/share/fonts,target=/root/.local/share/fonts \
--rm \
--workdir /root/workspace \
ros2-humble-io \
/bin/bash
```]
Das -it am Anfang steht für Interactive Terminal. Dadurch kriegen wir eine
SSH-artige Shell, die /bin/bash (Das man Ende Steht), also ganz normales Bash,
öffnet. --workdir bestimmt, in welchem Ornder unser Terminal gestartet wird.
Dies ist aus Praxisgründen unser Workspace. --rm sorgt dafür, dass der Container
gelöscht wird, wenn er beendet wird. Dies ist kein Problem da wir alle wichtigen
Daten an unser reelles System gemountet haben.
#pagebreak()
= Kamera publisher
Damit der Fahrer des Roboters auch etwas sieht, muss das Kamerabild irgendwie
übertragen werden. Dies machen wir über den ROS2 image transport. Das Kamerabild
fangen wir mit OpenCV ab.
#sc[```cpp
// Ein Haufen imports
using namespace std::chrono_literals;
class MinimalImagePublisher : public rclcpp::Node {
public:
// Der Konstruktor
private:
//mehrere Funktionen
};
int main(int argc, char *argv[]) {
rclcpp::init(argc, argv);
// erstelle ROS Node
auto node = std::make_shared<MinimalImagePublisher>();
// ausführen der Ros calls bis zum Absturz oder Ctrl-C
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}
```]
Die Main Funktion initialisiert zuerst ROS2 und erstellt dann eine ROS2 Node mit
dem MinimalImagePublisher. Dann wird der ROS Cyclus gestartet. Es wird die
Timer_Callback-Funktion in einem Loop ausgeführt, bis Ctrl-C gedrückt wird. Der
Delay zwischen den Loops ist in timer\_ definiert.
#v(12pt)
\
*Der Konstruktor:*
#sc[```cpp
MinimalImagePublisher() : Node("opencv_image_publisher"), count_(0) {
publisher_ =
this->create_publisher<sensor_msgs::msg::Image>("campub", 10);
timer_ = this->create_wall_timer(
500ms, std::bind(&MinimalImagePublisher::timer_callback, this));
}
```]
Im Konstruktor wird die publisher node definiert. Diese sendet eine
Imagesensor-Message. Der timer bestimmt den delay zwischen den loops.
#pagebreak()
*Die Funktion*
#sc[```cpp
void timer_callback() {
cv::Mat image;
cv::VideoCapture cap(0);
if (!cap.isOpened()){
std::cout << "cannot open camera";
return;
}
cap >> image;
msg_ = cv_bridge::CvImage(std_msgs::msg::Header(), "bgr8", image)
.toImageMsg();
publisher_->publish(*msg_.get());
RCLCPP_INFO(this->get_logger(), "Frame %ld published", count_);
count_++;
}
rclcpp::TimerBase::SharedPtr timer_;
sensor_msgs::msg::Image::SharedPtr msg_;
rclcpp::Publisher<sensor_msgs::msg::Image>::SharedPtr publisher_;
size_t count_;
```]
Zu Beginn wird eine Matrix erstellt, die Image heißt. Diese ist einfach nur eine
Rohdarstellung der Bilddaten. Dann wird ein VideoCapture namens cap erstellt.
Die `0` bei `cap(0)` bestimmt die ausgewählte Kamera. Tendenziell könnte man da
eine andere Nummer eingeben und es würde eine andere Kamera ausgewählt werden,
falls es eine auf dieser Position gibt. Die erfolgreiche Erstellung des Video
captures wird daraufhin in Z. 4ff. Überprüft.
In Z. 8 setzen wir Image auf das Bild, das cap momentan besitzt, also das, das
die Kamera momentan aufnimmt. Daraufhin wird eine Image-Message erstellt, die
versendet werden kann. Dazu müssen wir von dem OpenCV Matrix Format erst einmal
in das ROS kompatible Imageformat konvertieren. Dann publishen wir das Image und
senden es in das Netzwerk. Dann geben wir noch aus, wie viele Frames bereits
geschickt wurden und erhöhen den Counter für die bereits geschickten Frames.
Die letzten vier Zeilen deklarieren den Typ der öffentlich verfügbaren
Variablen, die oben im Konstruktor gesetzt werden.
#pagebreak()
= Das GUI
Der letzte größere Teil des Projekts ist das GUI, um den Roboter steuern zu
können. Um das ganze auch für spätere Projekte nutzbar machen zu können ist ein
sehr universelles Design notwendig, das für verschiedenste Anwendungszwecke
geeignet ist. Das Design und die Grundidee sind simpel und gleichzeitig
erstaunlich effizient: Warum ein unveränderbares UI festlegen, was für wenige
Aufgaben ausgelegt ist? Warum sich als Entwickler die Mühe machen, etwas zu
designen, was viele Nutzer vielleicht nur begrenzt oder teilweise verwenden
können? Warum nicht einfach... den Anwender seine Benutzeroberfläche selbst
gestalten lassen? Genau das war die Idee hinter dem Projekt: ein universelles,
komplett veränderbares ROS2 UI, was für so ziemlich alle noch kommenden
Roboter-Projekte, an denen wir oder andere arbeiten, eine Möglichkeit bietet,
schnell zu testen oder einfach drauf los zu fahren! Doch wie soll die Software
nun aussehen? Wie schon gesagt, sehr einfach: ein Fenster, oben eine
Menü-Leiste, ansonsten: leer.
#image("pictures/gui1.png")
== Implementations-Überblick
Die Software selbst ist in C++ für Linux programmiert; als Entwicklungsumgebung
dient hierbei Microsoft Visual Studio Code mit WSL 2 unter Windows. Das GUI
basiert auf vier grundlegenden "Säulen": OpenGL @opengl bzw. GLEW @glew, GLFW
@glfw, ImGui @imgui und ROS2 @ros2 (RCLCpp), Version "Humble". Hierbei ist GLFW
für die Fensterverwaltung und Context-Bereitstellung zuständig, OpenGL übernimmt
das Graphic-Backend, ImGui generiert das GUI, und ROS2 ist, einfach gesagt,
ROS2. Um das Arbeiten mit den unterschiedlichen Libraries einfacher zu gestalten
habe ich einige Wrapper-Klassen und Funktionen geschrieben, die die
Funktionalität der Libraries etwas abstrahieren. Dazu zählt zum Beispiel die
Window-Klasse, die die Funktionen von GLFW (ursprünglich für C gemacht) nimmt
und in eine Klasse verpackt, mit deren Hilfe man relativ einfach (dafür umsomehr
eingeschränkt) ein Fenster erstellen und verwalten kann.\
\
Ein zusätzliches Tool, dass ich selbst geschrieben habe ist eine Art
Resourcen-Management, das die verschiedenen Resourcen der App, befindlich im "res"
Ordner, installiert im Hauptverzeichnis der App, verwaltet, einliest und so
weiter. Alle Resourcen-Dateien sind im JSON Format verfasst. Dieses System ist
dazu gemacht, die Weiterentwicklung des Programms zu vereinfachen: so sind zum
Beispiel die Menü-Leiste und das Standart Layout nicht fest einprogrammiert,
sondern können schnell, ohne das das Projekt lange neu gebuildet werden muss
angepasst werden:
#sc[```JSON
{
"type": "viewlayout",
"id": "default",
"name": "Default Layout",
"views": [
{
"type": "view",
"id": "0",
"name": "Demo",
"viewtype": "demo"
},
{
"type": "view",
"id": "1",
"name": "Help",
"viewtype": "help"
}
]
}
```] _layout-default.json_
Der oben gezeigte Codeblock enthält die _layout-default.json_. Diese Datei
definiert das Standart Layout, dass beim Start der App geladen wird. Zunächst
definieren wir hier den Typ der Datei ("viewlayout"), dann eine ID ("default")
und einen Anzeigenamen ("Default Layout"). Dannach wird ein Array mit Views
festgelegt: Ein Demo-View mit der ID "0" und dem Namen "Demo", und ein
Help-View, ID "1" und Name "Help". Die in "viewtype" eingetragenen Werte sind
die IDs der jeweiligen Typen von Views, diese werden in anderen Resourcen
definiert. Wenn man das Programm startet dann sieht das Ergebnis ungefähr so
aus:
#image("pictures/gui2.png")
Warum nur ungefähr? Nun ja, die JSON-Datei gibt ja nicht an, wo sich die Views
befinden und wie groß sie sind. Dafür ist die so genannte _imgui.ini_ zuständig:
#sc[```INI
[Window][DockSpaceViewport_11111111]
Pos=0,19
Size=800,581
Collapsed=0
[Window][Debug##Default]
Pos=60,60
Size=400,400
Collapsed=0
[Window][Demo##view@0]
Pos=60,60
Size=100,71
Collapsed=0
[Window][Help##view@1]
Pos=276,131
Size=268,133
Collapsed=0
[Docking][Data]
DockSpace ID=0x8B93E3BD Window=0xA787BDB4 Pos=0,19 Size=800,581 CentralNode=1
```]
Diese Datei wird von ImGui generiert und gespeichert. Das heißt: wenn man die
Views verschiebt/ihre Größe verändert, dann werden die Änderungen in der _imgui.ini_ gespiegelt.\
\
Das Resourcen-Management erlaubt außerdem auch das definieren eigener
View-Types, also was für Views der Nutzer erstellen kann, neuen Menüs in der
Menü-Leiste, verschiedene Standartlayouts die geladen werden könenn und so
weiter. Später kommen auch noch Resourcen-JSONs für Bilder, Schriftarten,
Textdateien und noch einiges mehr dazu, um die Entwicklung noch weiter zu
beschleunigen und zu vereinfachen.\
\
Um die Arbeit an dieser Stelle nicht noch weiter unnötig in die Länge ziehen zu
müssen wird hier kein Source-Code eingefügt, da der Code an sich zu komplex,
viel zu groß und noch mehr viel zu durcheinander ist, um ihn hier sinnvoll und
verständlich darstellen zu können. Das gesamte Software-Projekt ist jedoch auf #link("https://github.com/Scriptor25/jif")[*_GitHub_*] zu
finden. Das Projekt ist folgendermaßen strukturiert (nur die wichtigsten Ordner
und Dateien):
#sc[```
├─include // Header Dateien
│ ├─imgui // ImGui
│ ├─jif // JIF
│ ├─kubazip // Zip-Library
│ ├─nlohmann // JSON-Library
│ └─stb // stb_image Library
├─res // Resourcen
│ ├─drawable
│ ├─font
│ ├─layout
│ └─viewtype
├─src // Source Code
│ ├─imgui
│ ├─jif
│ └─kubazip
├─.gitignore
├─CMakeLists.txt
├─LICENSE.txt
└─package.xml
```]
und läuft unter der "BEERWARE" Lizenz:
#sc[```
"THE BEERWARE LICENSE" (Revision 42):
<NAME> wrote this code. As long as you retain this
notice, you can do whatever you want with this stuff. If we
meet someday, and you think this stuff is worth it, you can
buy me a beer in return.
```]
== Funktionsweise
Doch was kann man mit der Software bis jetzt als Nutzer alles machen? Die
Palette an Funktionen wächst zwar ständig weiter, aber zum Zeitpunkt dieser
Arbeit sind ein paar grundlegende Dinge möglich:
- Das Laden/Speichern von Layouts und
- Das Hinzufügen/Entfernen/Verwalten von Views
So kann man zum Beispiel schon eine kleine App zusammenbasteln:
#image("pictures/gui3.png")
Um ein View zum Layout hinzuzufügen geht man auf "View => Add". Dann öffnet sich
ein Fenster, dass einen durch den Prozess begleitet: Zunächst gibt man dem neuen
View einen Namen, zum Beispiel "Test". Dann wählt man im nächsten Dialog aus
einem Dropdown-Menü den View-Type aus, in diesem Beispiel "image". Unter dem
Dropdown tauchen dann weitere Felder auf, die man je nach Typ ausfüllt, bei "image"
zum Beispiel den ROS-Topic, aus dem das Bild gezogen werden soll.\
\
Um ein View zu entfernen/wieder sichtbar zu machen (man kann Views minimieren,
wenn man auf das X klickt), geht man auf "View => Manager". Darauf öffnet sich
ein View-Manager Fenster, in dem man die einzelnen Views (de-)aktivieren oder
löschen kann.
#image("pictures/gui4.png")
Beim Speichern eines Layouts wird die _imgui.ini_ und _layout.json_ in eine _.jif_ Datei
gepackt, die eigentlich nur eine ganz normale _.zip_ Datei ist, aber der Name
klingt cooler... Jedenfalls kann diese mit anderen ausgetauscht, geteilt,
verschoben, etc. werden, wenn man sie über "Layout => Load" wieder lädt, wird
das Layout und die ImGui Konfiguration wiederhergestellt.
#pagebreak()
= Fazit
Alles in allem war das Projekt mehr oder minder erfolgreich: wir haben einen
funktionierenden, fahrenden Roboter und Software, die für noch folgende Projekte
weiter verwendet werden kann. Hard- und Software hat noch Ausbaubedarf, vor
allem die Software, was nicht wenig daran liegt, dass der Fokus mehr auf die "universalität"
lag als auf einem vollständigen Paket. Außerdem hat Programmieren die
unangenehme Eigenschaft, dass man nach einem Projekt meistens mehr Probleme hat
als davor: warum funktioniert der Code urplötzlich nicht mehr, obwohl der
Rechner nur über Nacht aus war; warum macht der Compiler einfach seinen Job
nicht richtig; warum haben mich meine Freunde und Familie verlassen, ich war
doch nur zwei Monate ununterbrochen im Keller... Naja, jedenfalls gibt es noch
viel zu tun. Aber: wir haben viel gelernt auf unserem Weg, und damit sind wir
besser auf das nächste große Vorhaben oder auf nächstes Jahr Jugend Forscht
vorbereitet als bei diesem Projekt.\
\
Den Source-Code der schriftliche Arbeit finden Sie #link("https://github.com/Scriptorgames/JIF-JUFO-Paper")[*_hier_*] in
unserer GitHub-Organization. Bei Fragen können Sie sich an #link("mailto:f.<EMAIL>")[*_diese Mail-Addresse_*] wenden.
|
|
https://github.com/cadojo/correspondence | https://raw.githubusercontent.com/cadojo/correspondence/main/src/rolo/src/authors.typ | typst | MIT License | #import "names.typ": *
#import "attributes.typ": *
#import "affiliations.typ": *
#import "../../options/options.typ": some
#let author(
number: none,
name: name(),
url: none,
email: none,
phone: none,
fax: none,
orcid: none,
note: none,
acknowledgements: none,
attributes: attributes(),
roles: none,
metadata: none,
affiliations: (affiliation(),),
) = {
let affil = if type(affiliations) == "array" {affiliations} else {(affiliations,)}
(
number: number,
name: name,
url: url,
email: email,
phone: phone,
fax: fax,
orcid: orcid,
note: note,
acknowledgements: acknowledgements,
attributes: attributes,
roles: roles,
metadata: metadata,
affiliations: affil,
)
}
#let address(author) = {
if some(author) {
let affil = author.affiliations.at(0)
if some(affil) {
let state = (affil.region, affil.postal-code).filter(some).join(" ")
let location = (affil.city, state).filter(some).join(", ")
(affil.address, location, affil.country).filter(some)
} else {
none
}
} else {
none
}
}
#let shortaddress(author) = {
if some(author) {
let affil = author.affiliations.at(0)
if some(affil) {
(affil.city, affil.region).filter(some).join(", ")
}
} else {
none
}
}
#let contact(author) = {
if some(author) {
(
author.phone,
author.email,
author.fax,
author.url,
author.orcid,
).filter(some)
} else {
none
}
}
#let authorblock(author) = {
let affil = author.affiliations.at(0)
if some(author) {
stack(
dir: ttb,
spacing: 0.65em,
..(
text(weight: "semibold", fullname(author.name)),
author.email,
author.orcid,
affil.department,
affil.name,
).filter(some)
)
} else {
none
}
}
|
https://github.com/IdoWinter/UnitedDumplingsLegislatureArchive | https://raw.githubusercontent.com/IdoWinter/UnitedDumplingsLegislatureArchive/main/elections/april_24/parties.typ | typst | MIT License | #import "../ballot.typ": *
#set page(paper: "a4", margin: 0pt)
#repeat_ballot(ballot([יש], [יש כופתה \ בראשות עידו וינטר]))
#repeat_ballot(ballot([כפת], [כופתאי \ בראשות איתי וינטר]))
#repeat_ballot(ballot([שמנ], [המחנה הכופתאי \ בראשות דור וינטר]))
#repeat_ballot(ballot([גו], [גופתאית \ בראשות גילה וינטר])) |
https://github.com/takotori/PhAI-Spick | https://raw.githubusercontent.com/takotori/PhAI-Spick/main/sections/kinematik.typ | typst | = Kinematik
#grid(
columns: (auto, auto),
gutter: 5pt,
[*Mittlere Geschwindigkeit:*], [*$macron(v) = (Delta v)/(Delta s)$*],
[*Mittlere Beschleunigung:*], [*$macron(a) = (Delta v)/(Delta t)$*],
[*Gleichförmige Bewegung:*], [*$s = s_0 + v dot t a => s/v = t $*],
[*Geradlinige Bewegung:*], [$Delta s= macron(v) Delta t$]
)
*Gleichmässig beschleunigte Bewegung:*
$
s &= s_0+v_0 dot t+1/2 a t^2 \
v &= v_0+a t \
v^2&=v_0^2+2a(s-s_0) => "wenn" v_0=0 => s=v^2/(2a) \
macron(v) &= (v_1 + v_2)/2 \
t&= v/a=(v_0-v)/a
$
== Gleichförmige Kreisbewegung ($omega$ = konst.)
#grid(
columns: (auto, auto, auto),
gutter: 5pt,
[*Umlaufzeit:*], [$T$],[$[T]=s$],
[*Frequenz:*], [$f= 1/T$],[$[f]= s^(-1) = "Hz"$],
[*Winkelkoordinate:*], [$phi= b/r$],[$[phi]="rad"=m/m$],
[*Winkel-geschwindigkeit:*],[$omega&= frac(Delta phi, Delta t) \ &=2pi/T=2pi f$],[$[omega]="rad"/s$]
)
#grid(
columns: (60%, auto),
gutter: 5pt,
[*Bahngeschwindigkeit:*], [$v=r omega$],
[*Zentripetalbeschleunigung:*], [$a_z= v^2/r=r omega^2$],
[*Tangentialgeschwindigkeit:*], [$v_T= (2pi r)/T$],
[*Radialbeschleunigung/ \ Zentripetalbeschleunigung:*], [$a_r=(4pi^2 r)/T^2$],
[*Tangentialbeschleunigung:*], [$a_T=(v_1-v_0)/t$],
[*Kreisbewegung Funktion:*], [$r(t)=r vec(cos(w t+phi_0),sin(w t+phi_0))$],
[*Radialgeschwindigkeit:*], [$v="Umfang"/T$]
)
#image("../figures/gleichkreisbewegung.png")
== <NAME>
*Bewegungsgleichung:* $arrow(r) (t)= arrow(r_0) + arrow(v_0 ) t+1/2 arrow(g) t^2$ \
$ vec(x(t), y(t)) = vec(0,y_0) + v_0 vec(cos(alpha), sin(alpha)) dot t + 1/2 vec(0,-g) t^2 $
#image("../figures/schieferwurf.png")
#grid(
columns: (auto, 38%),
gutter: 5pt,
$
y =& x dot tan(alpha_0) - g / (2 v_0^2 cos^2(alpha_0)) dot x^2 \
y_(max) &= (v_0^2 sin^2(alpha_0))/(2g) \
x_w &=(v_0^2 sin(2 alpha_0))/g
$,
image("../figures/schieferWurf2.png")
) |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/space_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test font change after space.
Left #text(font: "IBM Plex Serif")[Right].
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/font_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 23-27 unexpected argument
// #set text(size: 10pt, 12pt) |
https://github.com/eliapasquali/typst-thesis-template | https://raw.githubusercontent.com/eliapasquali/typst-thesis-template/main/preface/dedication.typ | typst | Other | #set page(numbering: none)
#v(3cm)
#align(center, [
Dice l'uomo ragno...
#v(6pt)
#sym.dash#sym.dash#sym.dash <NAME>
])
#v(2cm)
#align(center, [
Dedicato a ...
]) |
https://github.com/Menahra/CVTemplate | https://raw.githubusercontent.com/Menahra/CVTemplate/main/content/utils.typ | typst | #let accentColor = rgb("#E9EDFA");
#let accentTextColor = rgb("#B1BFED");
#let baseUnit = 8pt;
#let spacing(
amount: int
) = baseUnit * amount; |
|
https://github.com/julyfun/db-lab1 | https://raw.githubusercontent.com/julyfun/db-lab1/main/HW1.typ | typst | #set page(paper: "us-letter")
#set heading(numbering: "1.1.")
#set figure(numbering: "1")
// 这是注释
#figure(image("sjtu.png", width: 50%), numbering: none) \ \ \
#align(center, text(17pt)[
*Database System Concepts - Assignment (I)* \ \
#table(
columns: 2,
stroke: none,
rows: (2.5em),
// align: (x, y) =>
// if x == 0 { right } else { left },
align: (right, left),
[Name:], [<NAME>],
[Student ID:], [521260910018],
[Date:], [2024/3/4],
[Score:], [],
)
])
#pagebreak()
#set page(header: align(right)[
DB Lab1 Report - <NAME>
], numbering: "1")
#show outline.entry.where(
level: 1
): it => {
v(12pt, weak: true)
strong(it)
}
_Source Code_: #link("https://github.com/julyfun/db-lab1")
#outline(indent: 1.5em)
= Problem 1
==
The relational algebra expression is:
$
Pi_("ID", "name")("instructor") - Pi_("instructor.ID", "instructor.name")
("instructor" attach(inline(join), br: "instructor.salary < d.salary") rho_("d")("instructor"))
$
The relational algebra expression tree is like:
#import "@preview/syntree:0.2.0": tree
#figure(
tree($-$,
tree($Pi_("ID, name")$, "instructor"),
tree($Pi_("instructor.ID", "instructor.name")$,
tree(
$attach(join, br: "instructor.salary < d.salary")$,
"instructor",
tree($rho_("d")$, "instructor")
)
)
)
)
==
The relational algebra expression is:
$
Pi_("ID", "name")("student") - Pi_("student.ID", "student.name")
(sigma_("year"=2018)("takes") attach(inline(join), br: "student.ID = takes.ID") "student")
$
The relational algebra expression tree is like:
#figure(
tree($-$,
tree($Pi_("ID, name")$, "student"),
tree($Pi_("student.ID", "student.name")$,
tree(
$attach(join, br: "student.ID = takes.ID")$,
tree(
$sigma_("year"=2018)$, "takes"
),
"student"
)
)
)
)
==
The relational algebra expression is:
$
Pi_("i.ID", "i.name")(rho_(a_1)("advisor") attach(inline(join), br: a_1."i_id" = a_2."i_id" and a_1."s_id" != a_2."s_id") rho_(a_2)("advisor") attach(inline(join), br: i."ID" = a_1."i_id"), rho_(i)("instructor"))$
The relational algebra expression tree is like:
#figure(
tree($Pi_("i.ID", "i.name")$,
tree(
$attach(inline(join), br: i."ID" = a_1."i_id")$,
tree(
$attach(inline(join), br: a_1."i_id" = a_2."i_id" and a_1."s_id" != a_2."s_id")$,
tree($rho_(a_1)$, $"advisor"$),
tree($rho_(a_2)$, $"advisor"$)
),
tree($rho_(i)$, $"instructor"$),
)
)
)
= Problem 2
The relational algebra expression is:
$
Pi_(A_1, ..., A_n)(R) - Pi_(A_1, ..., A_n)((Pi_(A_1, ..., A_n)(R) times S) - R)
$
The relational algebra expression tree is like:
#figure(
tree($-$,
tree($Pi_(A_1, ..., A_n)$, $R$),
tree($Pi_(A_1, ..., A_n)$,
tree($-$,
tree(
$times$,
tree($Pi_(A_1, ..., A_n)$, $R$),
$S$),
$R$
)
)
)
)
|
|
https://github.com/maucejo/book_template | https://raw.githubusercontent.com/maucejo/book_template/main/template/front_matter/remerciements.typ | typst | MIT License | #import "../../src/book.typ": *
#show: chapter.with(title: "Remerciements", toc: false)
#lorem(50)
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Divergence.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Divergence",
authors: (
"<NAME>",
),
date: "30 Octobre, 2023",
)
#set heading(numbering: "1.1.")
= Divergence
<divergence>
Divergence is a measure of how much a vector field "flows" outward from
a given point. It is calculated by taking the dot product of the
gradient of the vector field with the unit normal vector at a point.
$ upright("div") lr((arrow(F))) eq nabla dot.op arrow(F) $
A vector field has positive divergence at a point if the flow is outward
from that point, negative divergence if the flow is inward, and zero
divergence if the flow is balanced.
In three dimensions, the divergence of a vector field
$arrow(F) eq lr((P comma Q comma R))$ is calculated using the following
formula:
$ upright("div") lr((arrow(F))) eq frac(diff P, diff x) plus frac(diff Q, diff y) plus frac(diff R, diff z) $
Divergence is an important concept in calculus 3, as it allows us to
understand the behavior of vector fields in relation to surface and
volume integrals. For example, the divergence theorem states that the
flux of a vector field across a closed surface is equal to the volume
integral of the divergence of that field within the surface.
$ integral.double_S arrow(F) dot.op d arrow(S) eq integral.triple_V upright("div") lr((arrow(F))) comma d V $
|
|
https://github.com/VanillaViking/EPM-Project-Research-Narrative | https://raw.githubusercontent.com/VanillaViking/EPM-Project-Research-Narrative/master/assignment2.typ | typst | #import "@preview/wordometer:0.1.1": word-count, total-words
#align(center, text(20pt)[
*Task 2 - Project Research Narrative*
])
#align(center, text(17pt)[
Engineering Project Management
])
#align(center, text(14pt)[
<NAME> - 14259321
])
#set heading(numbering: "1.a")
#show link: underline
#show link: set text(blue)
#show cite: set text(maroon)
#show: word-count
#outline()
#pagebreak()
= Project A: Raspberry Pi
The Raspberry Pi is a single board computer developed by the Raspberry Pi Foundation in the UK.
The original Model B board was released in February 2012, after which it rapidly gained popularity becoming the best-selling british computer by 2015 @lifeofpi.
It is a credit-card sized circuit board that includes an ARM-compatible CPU as well as a GPU, making it capable of running a full-fledged desktop operating system.
The Pi was originally intended to give students access to programmable hardware, which would increase the number and calibre of students that apply for computer science at Cambridge @lifeofpi.
However the model was far more popular than anticipated, and has seen use in areas outside it's target market due to it's low cost and modularity.
The project is extremely relavant to the discipline of software engineering.
The purpose of the Raspberry Pi is to give young people the tools equip themselves with important programming knowledge that can shape their career.
It is a fundamental building block to gain domain knowledge in areas such as embedded software development and has also seen uses in robotics, web development and automation, making it an instrumental tool for software engineers.
#figure(
image("raspi.jpg", width: 30%),
caption: [A Raspberry Pi board],
) <raspi>
== Why the Pi was successful
Initially, the Raspberry Pi Foundation set out to build a curcuit board that meets the criteria of being small size, low cost, and low power consumption @successpi.
This was a well-defined scope which was not subject to change over the course of the project, which gave it stability inspite of the challenging criteria.
Furthermore, the project was under a strict timeline, as it was already advertised that the Pi would be available to purchase in 2012 @storyofpi.
Although a deadline that is too harsh can often be detrimental to a project's success, in the case of the Pi, it provided a sense of urgency to the team, allowing them to overcome technical difficulties at an accelarated pace and deliver the product on time.
== Learnings
Researching into the Raspberry Pi project reveals elements that make a project successful. For example, it is very important to have a clearly established project scope. This will guide the team's decision-makeing and focus throughout the project life cycle.
Furthermore, It was clear that the Pi targeted a niche market of affordable computing devices for education and hobbyist projects. Identifying and catering to an underserved market can create opportunities for success by addressing unmet needs. The Pi's educational value attracted support from students and institutions, leading to widespread adoption, while the openness of the board encouraged collaboration by hobbyists leading to diverse ecosystems around the project. This solidified the Raspberry Pi platform as a core part of embedded systems education, and depicts the importance of finding a market with untapped potential.
= Project B: Google Glass
Google glass is a family of smart glasses produced by Google. It's main features were a heads up display, a built-in camera and Internet connectivity through natural language voice commands. It was developed by Google X, a facility within google that was focused on improving commodities by a factor of 10, through efforts called "moonshots". The product was launched in 2014, however pulled from the market by 2015 @investopedia.
The purpose of Google Glass was to take a leap forward in the way humans interact with technology, and provide a more seamless and hands-free way to interact with the internet, by integrating it directly into smart glasses. However, the product ultimately failed due to underwhelming sales and negative customer reception @screenrantgoogleglass.
The google glass project is relevant to the discipline of software engineering as it is a project that marks the importance of requirements elicitation and implementation for software-embedded systems. Often times, the software can make the difference between a project successfully meeting requirements and a project failing to satisfy stakeholders. In the case of Google glass, lack-luster software contributed to the poor execution of the Google Glass project.
#figure(
image("google-glass.png", width: 30%),
caption: [Google glass],
) <raspi>
== Why Google Glass Failed
Google glass, as a product of the Google X facility was a "moonshot" product, which caused the expectations out of the product to be unrealistically high. This negatively impacted the retail of the product in many ways. The google glass launched with a luxurious price of \$1,500 despite costing less than \$200 to manufacture @computerworld. It was marketed by Google as a luxury item for a specific niche of fashion, which indicated poor requirements gathering of what customers truly want out of smart glasses.
The product was also greatly over-marketed before it's release. The glass was advertised to augment experiences, with the demo in 2012 featuring skydiving, biking and many other activities, which in reality it was not capable of doing @investopedia. It is important to a project's success that it is appropriately marketed, so that it reaches the intended audience. In reality, the google glass suffered from technical limitations such as limited battery life, small display and performance issues. Customers also expressed privacy concerns of having a camera built into the glass that users might wear for most of the day, further indicating poor requirements analysis of the end user.
== Learnings
The google glass project was a failure due to sub-optimal prioritisation of requirements. Important details such as user privacy, retail price and technical limitations were neglected in favor of marketing the product as a fashion accessory for a niche customer base. Google was trying to pioneer a new market of smart glasses, however failed to accurately predict features that might entice a potential customer. As a result, not many wanted to take a risk on an unfamiliar product. Google Glass' lack of appealing features failed to establish enough demand for more customers to justify a \$1,500 price tag, ultimately leading to underwhelming sales for the product. This emphasizes the importance of delivering clear value propositions.
= Project C: Falcon 1
Falcon 1 was a small-lift rocket operated from 2006 to 2009. It was designed and manufactured by American aerospace company SpaceX. The Falcon 1 was designed to minimize price per launch for low-Earth orbit satellites, by creating reusable pieces for the launch system as much as possible, greatly lowering the cost of space access @smithsonian12.
SpaceX's Falcon 1 project is deeply connected to the discipline of software engineering. Rocket boosters require extremely fast and accurate real-time computing to maintain balance and ensure that they are on the correct trajectory. It is of critical importance that the software embedded on the rocket is robust and efficient, as even a minor miscalculation could put the entire rocket in jeopardy. Moreover, Telemetry services and communication to ground control is only possible through software networking protocols.
#figure(
image("falcon1.jpg", width: 30%),
caption: [Falcon 1 Rocket],
) <falcon>
== Why Falcon 1 Was Successful
The demand for reliable and cheap space travel was very high in the US after the retirement of NASA's Space Shuttle. As a result, SpaceX received government funding from agencies such as Department of Defense (DoD), NASA and the U.S Air force @smithsonian12. This initial demand and capital proved to be crucial while iterating through designs of the falcon 1, ultimately leading to it's success.
SpaceX took a radically different approach to development in comparison to other space exploration companies. They adopted an iterative development process, where they would rapidly build and test prototypes, improving on the design with each cycle @arstech20. This is very similar to the Agile methodology used in software engineering. Despite the greater chance of mistakes and setbacks using this approach, it proved to be successful for the falcon 1 project, which took 3 iterations to finally succeed in reaching low earth orbit.
Furthermore, despite initial setbacks, SpaceX managed to instill confidence in their customers, securing contracts including government agencies and commercial satellite operators, demonstrating the demand and viability of their services @qz16. The iterative development approach helped demonstrate tangible progress to customers with each launch attempt. Even though some launches failed, SpaceX showcaed their ability to learn from failures and iterate on their designs. In combination with competitive pricing and strong marketing and communication, SpaceX was able to retain many customers inspite of setbacks that could have proved fatal for the company.
== Learnings
SpaceX's falcon 1 project demonstrates the importance of selecting a development methodology that suits the project as well as the team. Due to their decision to use a more agile approach, they were able to develop falcon 1 at an accelarated pace which was instrumental to success.
The project also shows the importance of having or establishing high demand for the product. SpaceX received strong support from companies that were reliant on space travel, due to the extremely high demand for a economical space flight option.
SpaceX prioritized customer needs and worked closely with customers to understand their requirements and deliver solutions that met those needs. They also effectively communicated progress, achievements, and vision to stakeholders and the public. Building strong relationships with customers and delivering value are essential for long-term success for a project.
= Project D: Dyson Electric Car
Dyson is a Singaporean based technology company that designs and manufactures household appliances such as vacuum cleaners, air purifiers, hand dryers and more. In 2017, Dyson announced that it had been working an electric car that placed emphasis on innovative technology and systainability @electrifying22. However, despite significant a resource investment into the project, Dyson cancelled the the project due to not being commercially viable @vergedyson.
This project is relevant to the discipline of software development, as embedded software plays a crucial role in the automobile industry. Software is used in cars in areas such as vehicle control systems, battery management and powertrain optimization, which are all critically important areas of the car. Modern features such as traction control, cruise control and emergency braking all rely on software systems to ensure safety of the passengers. Embedded software is essential in vehicles for managing critical functions of the car, as well as managing intelligent safety features to protect passengers.
#figure(
image("dyson.jpg", width: 30%),
caption: [Dyson EV],
) <falcon>
== Why the Dyson Electric Car Failed
The Dyson EV project was faced with significant costs in research development and manufacturing. Developing a new electric vehicle from scratch involves substantial R\&D costs. Furthermore, they were also developing a proprietary solid-state battery technology to be used in the car, which further added to the financial challenge of the project @drive20. Vehicle manufacturing can often benefit from economies of scale, where unit costs decrease as production volumes increase @investopediascale. As Dyson was a newcomer to the automotive industry, achieving economies of scale would have requried a significant initial investment and volume commitment. Furthermore, meeting automotive safety and regulatory standards adds additional costs to vehicle development and manufacturing. The aggregation of such factors contributed to the decision to discontinue the electric car project.
Dyson also underestimated the complexity of manufacturing and scaling an electric vehicle. Transitioning from producing small-scale consumer electronics to manufacturing automobiles at a larger scale posed significant challenges, which would require substantial investment and expertise to solve. Automotive manufacturing involves a complex supply chain with numerous components sourced from various suppliers globally. Ensuring a reliable and cost-effective supply chain is a momentous challenge for a new automotive manufacturer. Such problems require specialized knowlege and expertise across various disciplines, including engineering, manufacturing and supply chain management. Dyson may have faced challenges in recruiting and retaining talent with the necessary skills.
== Learnings
The failure of Dyson's electric car project uncovers several valuable elements that influence success. For instance, businesses should conduct thorough risk assessments and scenario planning before embarking on ambition projects. Dyson's electric car project likely faced risks related to technology development, manufacturing scalability and regulatory compliance, which should have been carefully managed. Risk management is an ongoing process that requires continuous monitoring and adaptation. Dyson should have continuously evaluated the projcet's progress, and adjust its strategies accordingly.
Effective communication with stakeholders, employees and the public is another crucial factor in the face of setbacks. Dyson's decision to cancel the electric car project was met with surprise, highlighting the underwhelming communication regarding the project status. Overall, Dyson's electric car project portrays the importance of proactive risk management, scenario planning, continuous monitoring and frequent communication.
#bibliography("ref.bib", style: "apa")
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/04-opentype/exploring/cff.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/components.typ": note
#import "/lib/glossary.typ": tr
#show: web-page-template
// ### The `CFF` table
=== `CFF` 表
// Finally, let's look at the table which is of least interest to typography and layout software, although font designers seem to rather obsess over it: the actual glyph outlines themselves. First, we'll look at the `CFF` table which, as mentioned above, represents OpenType fonts with PostScript outlines.
最后我们来看看排版软件最不关心,但字体设计师痴迷其中的东西:#tr[glyph]#tr[outline]。我们先以用PostScript方式表达#tr[outline]时使用的`CFF`表为例。
// What's interesting about the `CFF` table is that its representation is "alien" to OpenType. CFF is a data format borrowed wholesale from elsewhere - Adobe invented the Compact Font Format in 1996 as a "compact" (binary) way to represent its PostScript Type 1 fonts, as opposed to the longform way of representing font data in the PostScript language. It was used since PDF version 1.2 to represent font subsets within PDF documents, and later introduced into OpenType as the representation for PS outlines.
`CFF`表的一个特点是,对于OpenType来说它就像一种外来生物。确实,CFF 是一种从其他技术中借鉴而来的数据格式。1996 年,为了优化长期以来低效地用PostScript语言直接表示PostScript Type 1字体的方法,Adobe发明了紧凑字体格式(Compat Font Format)。它也用于在PDF 1.2之前的文档中储存字体子集。后来OpenType标准将其定为储存PostScript#tr[outline]的格式。
// In other words, CFF is an *independent* font format. You actually have another whole font file inside your font file. This CFF font file begins with its own "public" header before it launches into the outline definitions, giving some general information about the font:
换句话说,CFF本身就是一个*独立的*字体格式。在这个字体文件中其实包含了另一个完整的字体文件。CFF 字体文件在#tr[outline]之前有它自己的公共头部信息,用于提供关于字体的基础信息:
```xml
<CFF>
<CFFFont name="TTXTest-Regular">
<version value="001.000"/>
<Notice value="copyright missing"/>
<FullName value="TTX Test Regular"/>
<Weight value="Regular"/>
<isFixedPitch value="0"/>
<ItalicAngle value="0"/>
<UnderlineThickness value="50"/>
<PaintType value="0"/>
<CharstringType value="2"/>
<FontMatrix value="0.001 0 0 0.001 0 0"/>
<FontBBox value="3 -200 578 800"/>
<StrokeWidth value="0"/>
<!-- 字符集被单独储存在 GlyphOrder 元素中 -->
<Encoding name="StandardEncoding"/>
```
// From an OpenType perspective, much of this is information we already know, but which has to be filled in to make this table conform to the CFF format. Font production software will generally copy this information from other parts of the font: the copyright notice and font name find their native OpenType home in the `name` table, the weight value can be found in the `OS/2` table, the bounding box information comes from the `head` table, and so on.
从OpenType标准的视角来说,这个头部中的大多数信息都在别处已经提供。但为了满足CFF格式标准,必须在这里也填写一遍。字体制作软件通常会从其他表中自动复制所需的信息进行填入。比如版权信息和字体名会从`name`表中获取,字重值则来自`OS/2`表,#tr[bounding box]相关信息可以从`head`表中得知。
// It's not clear if any software cares too much about the values in this header. As an experiment, I tried modifying the paint type and stroke width to attempt to create an outline font (recompiling the XML representation back into OpenType, again using `ttx`), and embedding this in a PDF document, but nothing changed.
我不确定是否有软件真的会使用这个公共头部里的信息。我尝试过修改其中的`PaintType`和`StrokeWidth`字段,然后将XML表示重新转换回字体文件并嵌入PDF文件里,但结果什么都没变。
// After the public header comes a private header, which is very much used:
公共头部之后是私有头部,这部分就很有用了:
```xml
<Private>
<BlueScale value="0.037"/>
<BlueShift value="7"/>
<BlueFuzz value="0"/>
<ForceBold value="0"/>
<LanguageGroup value="0"/>
<ExpansionFactor value="0.06"/>
<initialRandomSeed value="0"/>
<defaultWidthX value="0"/>
<nominalWidthX value="0"/>
</Private>
```
// These mainly have to do with hinting, which we will deal with in the appropriate chapter.
这些字段大多和#tr[hinting]有关,我们会在专门的章节中再进行详细介绍。
// Finally we get to the good stuff:
再往后就是我们现在感兴趣的部分了:
```xml
<CharStrings>
<!-- ... -->
<CharString name="A">
580 213 72 342 73 hstem
3 574 vstem
240 700 rmoveto
-237 -700 rlineto
91 hlineto
67 213 rlineto
255 hlineto
66 -213 rlineto
95 hlineto
-237 700 rlineto
-157 -415 rmoveto
33 107 24 79 24 75 22 81 rlinecurve
4 hlineto
22 -81 23 -76 25 -78 34 -107 rcurveline
endchar
```
// The definition of the characters themselves, in the PostScript language, begins with some hinting information: the total width is 580, and there's a horizontal stem that starts at 213 and goes for 72 units to 285; (the crossbar of the A) then another which goes from 285+342=627 to 627+73=700 to represent the apex of the A. The vertical stem goes from the left side bearing (3 units) all the way across the glyph.
这些就是用PostScript语言写成的#tr[glyph]定义了。定义中最开始的部分也是#tr[hinting]。其含义为:整个#tr[glyph]宽度为580;有两个水平的#tr[stem],第一个#tr[stem](A字中间的横梁)从坐标213处开始,高72个单位,持续到`213+72=285`;第二个#tr[stem](A的顶部尖端部分)则从坐标`285+342=627`处开始,持续到`627+73=700`。竖向的#tr[stem]则从左#tr[sidebearing](横坐标为3)处开始,一直横跨整个字符(这里描述的是竖向#tr[stem]的横轴长度,正如之前横向#tr[stem]是描述其纵轴高度)。
// Then there are a series of moving and drawing operations: we `rmoveto` the left side of the apex, and draw the left outmost stroke of the A, a diagonal `rlineto` the position (3,0). (PostScript uses relative coordinates: we move left 237 units and down 700 units, so we end up at (3,0).) Now we're at the bottom left corner of the A, about to draw the horizontal line at the bottom of the left leg. PostScript has a special drawing instruction, `hlineto`, for horizontal lines, which omits the vertical coordinate, which means that `91 hlineto` takes us from (3,0) to (94,0).
后续则是一些移动和绘制指令。首先 `rmoveto` 将画笔移动到顶部尖端的左侧,然后 `rlineto` 命令绘制出A字的最左边的一笔。这里 PostScript 语言使用的是相对坐标,因为最开始将画笔移动到了 `(240, 700)`,所以往左 237,往下 700 单位后就到了最左下角的 `(3, 0)`。现在要接着画左脚的底部横线,PostScript 对于水平线段有一个专用的指令 `hlineto`,使用它就无需填写纵坐标参数。所以这里代码 `91 hlineto` 就画出了从 `(3, 0)` 到 `(94, 0)` 的一条横线。
// We go around the outline until `-237 700` takes us back to the top *right* of the apex. (I've added a blank line here for clarity, although it would not be in the actual TTX outline.) This is almost the end of the outer outline. We haven't actually drawn the line between the top right of the apex and the top left where we started, but it turns out we don't need to. When we pick up the pen and move it somewhere else, which will be our next instruction, the outline gets closed for us.
在经过了一系列绘制后,通过 `-237 700` 的一次移动,最终我们回到了顶部尖端的右侧(为了能看的更清楚,我在这条语句之后加了一个空行,要注意代码中实际上是没有的),这基本就是整个最外侧#tr[outline]的样子了。我们不需要手动写出从尖端右侧到作为绘制起点的尖端左侧的横向线条,因为下一条语句是 `rmoveto`,将画笔拿起并移动到其他位置的命令会自动将当前的#tr[outline]封闭。
// We've just been dealing with straight lines so far, but moving us left 157 units and down 415 units places us in the middle of the counter of the A, where we start to see some curves - there are subtle flexes within the diagonals of the aperture. (You font designers are *clever* people.) `rlinecurve` specifies the relative positions of the start, first control point, second control point and end point of our cubic Bézier curve. We move across to the right a bit, have a curve that comes down, and that concludes our letter A.
至今为止我们都是在画直线,不过在将画笔移动到A的#tr[counter]部分之后,因为开口的内部角落处会有细微的弯曲,所以我们得开始画曲线了。`rlinecurve` 通过起始点、第一控制点、第二控制点、终结点之间的相对位置来绘制一条贝塞尔曲线。然后向右画一条小横线,再画一条向下的曲线,这样我们的字母A就完成了。
|
https://github.com/linhduongtuan/DTU-typst-presentation | https://raw.githubusercontent.com/linhduongtuan/DTU-typst-presentation/main/slide_footnotes.typ | typst | #import "slides.typ": *
#let slide_footnotes = state("slide_footnotes")
#let slide-footnote(e) = {
slide_footnotes.update(k => {
if (k == none) {
return (e,)
}
k.push(e)
return k
})
locate(loc => {
let f = slide_footnotes.at(loc)
if f != none {
super([#{f.len()}])
}
})
}
#let gen-footnotes() = {
locate(loc => {
let f = slide_footnotes.at(loc)
if f != none {
let i = 1
for e in f {
[#super(str(i))#e #h(0.5em)]
i += 1
}
}
})
state("slide_footnotes").update(())
} |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/dashy-todo/0.0.1/lib/side-margin.typ | typst | Apache License 2.0 | #let rel-to-abs = (rel, size) => rel.length + rel.ratio*size
#let calc-side-margin(side) = {
// https://typst.app/docs/reference/layout/page/#parameters-margin
let auto-margin = calc.min(page.width, page.height)*2.5/21
if page.margin == auto {
auto-margin
} else if type(page.margin) == relative {
rel-to-abs(page.margin, page.width)
} else {
if side == left and page.margin.left == auto or side == right and page.margin.right == auto {
auto-margin
} else {
if side == left {
rel-to-abs(page.margin.left, page.width)
} else {
rel-to-abs(page.margin.right, page.width)
}
}
}
} |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/040%20-%20Zendikar%20Rising/002_Red%20Route.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Red Route",
set_name: "Zendikar Rising",
story_date: datetime(day: 04, month: 09, year: 2020),
author: "<NAME>",
doc
)
#emph[Note: This is Part 1 of a two-part story to be continued. . .]
In Tazeem's deep Umara River Gorge, a lone pair flew by hook and line. The two, a battle-worn kor and a tall, lithe merfolk, were only ever still in the moments between swings. For those weightless heartbeats, it appeared as if the whole world moved around them; on Zendikar, this was possible.
The two had traveled for the better part of as many days up from their last rest, the Magosi Portage, itself some days up from the far banks of the Halimar, across which their home, Sea Gate, stood against the raging ocean. They chased rumors of a fallen hedron—an artifact of the world long gone.
This flight, the swing-and-leap in defiance of natural rules, fed one worry and hid the other: when a moment of inattention could send you tumbling to raging water below, esoterica was pushed to the side.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("002_Red Route/01.jpg", width: 100%), caption: [Clearwater Pathway | Art by: Daarken], supplement: none, numbering: none)
Akiri's lead hook bit the well-worn anchor, the line tensed through her swing, and she fell with the confidence of someone who knew they would never land. At the nadir of her swing, the whole world was a rush of sound and color: the roaring river white and emerald below her, the stratified crimson-and-umber walls of the gorge blurring to either side, the hum of her kor line as it sliced the air. Flying, for Akiri, was simply a matter of holding on.
Akiri and her companion Zareth traveled up the Umara River Gorge, a long, stable, well-textured valley carved over millennia by the Umara River. With sheer walls plunging hundreds of feet from rim to river, the gorge bristled with natural and artificial anchor points, the best of them painted in bright colors for line-slingers eager to make good time. A stiff wind raced down from the gorge's heights, perfect for downstream navigation if one wanted to take the fast route to Halimar Bay. It was a canyon of flight, one of the few stable places in all of Zendikar. To a master like Akiri, traveling the gorge was easy as walking.
Akiri pulled through her swing, using her momentum to propel herself forward and up. A flick of the wrist, and she was free, soaring. A weightless moment between flight and fall critical for rest, to catch one's breath. Akiri did both, sighted her next anchor, and threw her following hook as she started to fall.
A small thing. A moment unwelcome: fear, the old friend, always there. Should the hook miss (impossible) or the earth break (quite possible, but unlikely given the rock that composed the gorge), then Akiri would not #emph[fly] , she would #emph[fall] , and that would be the end of her. Another kor swallowed by the Umara. Another kor who forgot what Zendikar thought of them now; even those born to walk tripped once in a while.
Akiri's following hook caught, bit, and held. She felt the impact resonate through her line, through her arm, and into her heart, and she swung up from the earth without fear. On this swing, she would not falter—she would fly.
Shouting behind her reminded Akiri that not everyone was so meditative in their practice.
Zareth, her old friend and companion, whooped and hollered each time he flew an apex, cheered when his lead or follow hook caught an anchor, and egged her on.
"Akiri!" Zareth shouted behind. "Go Red! Red Route!"
Red Route was a difficult, quick hookroute up the Umara River Gorge. Akiri knew it well—she'd set the route herself during the Battle, scouting and building the Red for her company of skilled line-slingers. Back then, it was to outpace hungering beasts and the Eldrazi broodlings that stalked the high places of the gorge; now, line-slingers ran the Red to settle bets and show off. A change for the better.
A few momentum-building swings, and she was ready. At the apex of her next swing, she held her throw, twisting in the air to look back at Zareth, her white hair whipping around her face.
Flying behind her, Zareth still looked like the lanky merfolk filch that tried to steal her hooks all those years ago, only now with a bit more age to his scale and his own set of hooks. Youth, though it quit most, never really left him.
"Follow!" Akiri shouted to her old friend. She fell, twisting, and flung both hooks out before her—Red Route had anchors on both sides, and she would need the strength in both of her arms to make the next set. She trusted Zareth to match her movements, if not her pace.
The fear was there yes, always. But the #emph[freedom] !
Akiri and Zareth's happy shouts echoed up the Umara River Gorge. Ahead, there was danger—that was a given across Zendikar, and especially so considering they had been dispatched by Sea Gate to follow up on rumors of a fallen hedron—but for now, that seemed very far off.
Together, Akiri and Zareth flew.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("002_Red Route/02.jpg", width: 100%), caption: [Akiri, Fearless Voyager | Art by: <NAME>], supplement: none, numbering: none)
Later that evening, Akiri and Zareth made camp atop the high rim of the gorge. The hazy, burnt-orange sun spread like a cooked yolk across the horizon, and the sound of the Umara far below was a gentle, constant roar. The plains atop the gorge stretched to the horizon, split only by jagged, spear-blade mountains rising in the distant north, where the planes gave way to low foothills and, eventually, the bruised darkness of the Bulwark. Mountain roots hovered across the horizon, as if one had taken a double handful of rocks and sand, threw them into the air, and froze the silicate rain in fall.
#emph[That] , Akiri thought,#emph[ is likely not far from the truth.]
Akiri sat against the trunk of a small, windswept tree and spread slinger's paste over her tired arms. Zareth stood a way off, watching the sun set. Before the sinking orb, he was a dark silhouette, his shadow long and sharply defined.
To be on mission once more with Zareth had shaken her in ways she had not expected. His recent return to Sea Gate was welcome but carried with it heavy reminders. Reminders of what had been done not only to Tazeem, but to all of Zendikar. Reminders of those who had committed the act; people who could dance between worlds, dip their brilliant light into them for a moment, then move on with ruin in their wake.
The sun sank, and the day cooled. Akiri recalled the chill in Sea Gate under Ulamog, in the shadow of the beast free of its ancient chains.
Akiri shivered. How long had that thing been jailed under the earth, and what had its jailing done to the world made into a prison? And who made her world the world-eaters' prison?
An overwhelming burst of anger barely contained: #emph[This is why] , she thought. #emph[Sea Gate, and the climb to Murasa. This is why you're doing this—remember!]
A life of reminders was as exhausting as the Umara Red Route. Akiri exhaled the tension. Better to breathe. To note that it was a nice evening, if humid. The sky was clear but for a hedron shards of Emeria, one low enough that its trailing waterfall veil was visible, a sparkling lace springing endless, spilling into the open air. A patch of green growth huddled beneath, an oasis in the grass. Birds drifted around its bulk, alighting with piercing cries only just audible under the churning Umara. Zendikar the prison, Zendikar the ruin. Zendikar the wounded world still could be beautiful.
"Akiri," Zareth called back to her, "the thing we're chasing after."
"The hedron?"
"Why do you think it fell?"
"If I had to guess"—Akiri looked up toward the sky, toward Emeria—"it simply fell."
Zareth grunted. He followed Akiri's gaze. "Nothing that ordered would fall without a reason."
"That's true," Akiri said.
The scholars back at Sea Gate quibbled over the nature of the hedrons and the mechanisms by which they remained suspended in the air. They sat with telescopes and mapped their minor oscillations and movements, hired expeditions—some that Akiri had even led—to charted courses by which one might ascend into Emeria, and argued over the naming of layers and skymarks; but did they #emph[know] why they remained in place or why they fell? No, no more than they knew what their function was, or who had made them.
Akiri was not afflicted with those scholarly fears. The libraries and study halls of Sea Gate were useful to her only in that they had food and drink freely available for the rangers, line-slingers, and adventurers of the Expeditionary House. Did she wonder? Yes, of course she did. Did she fear? No more than one would fear a sudden death; yes, and no.
"That hypothesis would put you in vaunted company, Zareth," Akiri said. She stood and tossed Zareth her pouch of slinger's paste. He caught it. "When you come back to the Gate, I can introduce you to some scholars who study the hedrons," Akiri said. "They'll surely have some good books on the subject. Good resale value." Akiri spoke with mirth, and gently.
Zareth laughed. "Hey now," he said, "#emph[allegedly] ."
Akiri believed him. That Zareth fled years ago; the one who returned to Sea Gate and its Expeditionary House now was a different person, in a different time.
Well, she hoped.
Over a traveling dinner—a thick stew of harvested wild onions, chopped tubers, smoked meat, and sprigs of herbs found nearby—Akiri and Zareth recovered from the day.
"You were good up the Red Route," Akiri said to Zareth as he stirred the low-boiling stew, "but you need to work on your follow-hook disengagement—we'll take the Green Route tomorrow, so you can practice."
Zareth nodded. He tasted the stew, then sprinkled some more salt into the broth. "It's my shoulder. Broke it in a fall learning to sling." He rolled his shoulder, a movement that Akiri could tell was genuinely limited, if exaggerated to prove a point. "Otherwise I'd take the title for fastest up the Red," Zareth said with a smile.
Akiri thought not, but didn't say. Instead, she pointed to the hooks attached to his harness. "Those don't look like normal hooks. Where did you pick those up?"
"They're Skyclave. From the kor that run the Trenches in Ondu," Zareth said. He reached over to his harness and unclipped one from its line. "Brave line-slingers find them in the ruins," he said, tossing the hook to Akiri. "That's the only place you can find them. You have to be brave, or dear to someone who is."
Akiri examined the hook, turning it over. It was covered in a fine and regular etching, a geometric pattern that looked to Akiri like a winding, spiraling labyrinth. Angles and corners, diamonds and perfect squares. Not natural, but not of any make that she recognized—save for what it could not be.
"Did you find this one?" Akiri asked.
"No," Zareth said, "it was dear to someone brave." A sad smile crossed his face. "Anyways. They'll never let you down," Zareth said.
"And yet," Akiri said, raising an eyebrow.
"My shoulder, I know. Don't believe everything anyone says, right?"
Zareth's clever smile. Akiri knew it well; Mirth lurked around every corner. Likely how he fell.
"It's beautiful," she said, passing the hook back to Zareth. "The pattern carved into it?"
"Just like those on a hedron's face." Zareth nodded. "I saw many of them in Ondu—landbound at one, even." He turned the hook over, and a small smile crossed his face. "Here," he said, offering Akiri the hook, "you take it, I have others."
"Thank you, Zareth," Akiri said, taking the hook. She reached over to her pack, pulled her main line, and secured the Skyclave hook to it. She did not need to ask Zareth where his supply came from—#emph[In fact] , she thought, #emph[I might be better off not knowing] . She stowed the hook in her pack and returned to her seat with a waxed canvas case from which she pulled a map. Akiri rolled the map out on the dry ground and pinned its corners with some nearby stones.
Zareth ladled out their dinner and sat opposite the map. "Tomorrow or the day after?" he asked.
"Tomorrow," Akiri said. "It is only six miles to this waterfall," she said, pointing to a marked but unnamed fall on the map. "The hedron should be at its source."
"Do we need to worry about them?" Zareth asked.
For a moment, Akiri was confused, but then—
#emph[The skinless titan, eclipsing the sun. Waterfalls of ocean water spill from its looming form. It spreads its arms as wide as the horizon, and Sea Gate shakes and shimmers with heat.]
—she knew.
"No," Akiri said, "they're gone from this world. We won." Her throat was dry as dust, even now, at the thought of them.
Zareth ate, regarding the map—but not really looking at it, Akiri noticed. Looking #emph[through ] it. She knew that look, the faraway way that caught those who had seen things no one should—
#emph[Nighttime stained orange with fire, the stink of quick-rotting dead and the screams of the living. Her sword heavy and slick with steaming blood. The Eldrazi killed with a touch—some with their mere presence. Comrades crumbled to white ash, choking the air she struggled to breathe. The first rush of the brood beasts nearly overwhelmed them, but somehow, they held, and the air sizzled with energy and the next wave crashed into them.]
—she remembered how inexperienced Zareth had been during the Battle. He had been pressed into the liberation of Sea Gate because he could hold a spear, assigned to her unit because so many had been killed. He was tall for his age then, and the other conscripts thought him older, more experienced.
She'd only been a handful of years older than Zareth when the Eldrazi burst upon the world, a kor who thought herself invincible because she had learned to fly as her ancestors did, with hook and line and Zendikar itself as her wide-open playground. She was quick with a sword, an adept warrior in a band of champions. Even then, her skill and grace had won her acclaim across Zendikar and had given to her a sense of being beyond herself. With her kin and loves by her side, she did not fear when she first heard the news of the titans bursting from the earth. What were they but another chance to cover herself in glory? She and her band would join the forces of the Living, fly triumphant in the face of these things others called "gods," and save the world.
She had thought.
"Akiri," Zareth said, breaking her reverie, "I am sorry to have left the way I did." He spoke softly, a whisper Akiri did not know him able to voice. "I couldn't take the quiet. I thought that I would be free of it all if I went far away. Away from Sea Gate, and Kaza, and Orah. Away from all of it"—the small muscles of his jaw pulsed as he spoke through old pain—"away from you."
#emph[The sound of the ocean never still. The rough, gutter fights of human, kor, and merfolk against dust-making Eldrazi drones and lesser spawn. Above, the crack and flash of the walkers' magic blasting apart more terrifying beasts.]
She could be mad at him. Akiri could have raged at him for how he left and for the things he stole. For how much Kaza had wept for him. Orah certainly cursed Zareth for his flight and threatened to kill the boy if he returned, but that was Orah being Orah, and Akiri knew he was only dramatic in his anger—it hid his love, and his fear. She could be mad at him; in her own young life, Akiri learned hard the cost of leaving without saying goodbye, but she also had come to recognize what a gift it was to be able to forgive. On Zendikar, their wounded little world, healing was not done passively: it was a practice. Whether remaking the world or mending the self, healing was work. Same with forgiveness.
"Zareth," she said, "I'm happy to have you back."
Zareth looked up from his work. For the first time since he swaggered back into Sea Gate days ago, she saw the Zareth she knew.
"I've never had a place to come back to," Zareth said. "It's nice. Feels like things might be getting better. Being back at Sea Gate showed me that we did something more than survive."
"We do more than survive," Akiri said. "We saved the world. Now, we bring power to its people, and then we live."
Zareth smiled, small. Some time passed in quiet before the two of them returned to their meal. Together they sat under their tree atop the Umara River Gorge, and the waning light of the sun slipped below the distant horizon, and they talked about nothing important at all.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The next day they reached the site of the fallen hedron. The waterfall—reported to have dried up—spilled at a steady course.
"Well," Zareth said between breaths, bent double over his knees, "there's nothing here." He stood and looked around the small summit of the spire they had ascended. Bowl-shaped, the amphitheater summit cradled a pond sprung from no visible source, which fed a shallow stream that spilled out above the gorge below. The summit was shrouded in mist, and the day's light was overpowering in the high air. Little vegetation grew save for patchy, twisted grass. It was less an oasis than an excerpt, a slice of land that appeared utterly out of place for the place that it was.
"Hey Akiri!" he shouted. "Where's the big rock?"
Akiri stood a little way off, toward the edge of the pool that fed the waterfall they had spent the better part of a day ascending. Save for the white chalk on her hands and forearms, one could not tell she had just led and set the day's climb. A frown furrowed her face. Hands on her hips, she looked around, just to be sure. Some spell, perhaps? Or a lingering effect of the Roil that hid the hedron from their sight?
The pool that fed the waterfall was a chromatic beauty, and it was the only feature of note atop this bare summit. Mineraled in brilliant reds, blues, greens, and yellows, the crystal-clear water was still as a held breath. It didn't take any deep investigation to see that Zareth was right.
"It's not a rock, it's an artifact," Akiri called back. Three days of hard travel, line-slinging, and this final climb to find nothing. Not even a big rock.
"That's a pretty pond, at least," Zareth said.
Akiri grunted. It was a pretty pond. "Don't drink from it," she said.
"Poisoned?"
"That's possible." Akiri scuffed a small stone from the bank into the pond. It skipped into the water, then vanished. "More likely to be magic," she said.
"Maybe that's what happened to the hedron?"
"Absolutely possible."
They stood and let the wind fill the silence. It whistled, lonely.
"What now?" Zareth asked.
Akiri looked back to Zareth, and then past him. The whole of Tazeem spread out, hazy through the golden mist of the wind-whipped fall. Hidden beyond vision was her answer.
"We go back to Sea Gate," Akiri said.
No beacon could be seen this far out, but one could imagine it and the city beneath. Shining, distant, but full of promise. A glittering city at the mouth of Halimar Bay.
"We still have work to do," Akiri said. "Back there. Up there."
Zareth peered with her, looking for the easterly horizon. "In the meantime, it's a nice view," he said. "Not all bad, even if the work is not done."
Akiri gave him a soft smile. "Come on then Zareth," she said. "Let's go home."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("002_Red Route/03.jpg", width: 100%), caption: [Umara Skyfalls | Art by: <NAME>], supplement: none, numbering: none)
Though distant from Sea Gate and no more grand than a single long hall and some outbuildings, the Magosi Portage was a beacon of civilization this far into the interior. Atop the mighty Magosi waterfall, the portage was the major rest stop for travelers and traders taking the safe route up or down the Umara, and a common base camp and waystation for explorers.
Constant about the portage was the low rumble of the Magosi itself. The tallest waterfall along the gorge, the Magosi Falls formed where the Umara River took a single, sheer step three hundred feet down. Some ancient geologic trauma rent the world here, lifting one section of it up and tearing another down. Impassible for centuries, surveyors out of Sea Gate had carved a series of switchbacks into the wall after the city's liberation; vertiginous, it nonetheless allowed travelers to make a relatively safe ascent from the lower gorge to the upper. The Magosi Falls echoed the story of Zendikar: something old had done something terrible to the world, some people died, most lived, nothing changed, and Zendikar continued its shuddering and shaking, riddled with planar fever. Then, the world and its people adapted.
Akiri and Zareth, for the first time in days, spent an evening seated about a table on sturdy chairs, eating food that had been served to them, that they had paid for with coin and credit from trade goods they'd brought back from their expedition. They even had cold drinks and listened to music played by a valiant group of merfolk trying to overcome the low and constant roar of the Magosi waterfall. Dozens of kor, merfolk, and humans milled about the portage's main hall, eating and conversing, haggling over small goods and swapping news and rumors they'd accrued on their travels. Outside the stamp and call of docile pack beasts—hirable for the trek to the next portage climb many miles away—carried in on the wind with their heady fragrance.
"Civilization," Zareth sighed, finishing his cup. He crunched on some ice and rubbed the back of his neck with his hands. "I think I'll take another one of these," he said, rattling his cup, "and then go for another wash—I forgot how nice hot water is on the scales." Zareth grabbed up their shared purse and tugged at the drawstring to open it.
Akiri, finishing her food, nodded toward the pouch. "You'll have to use your coin-hunting to find anything in there," she said. "We spent the last of that on this meal and the supplies we need to get back." Akiri cocked an eyebrow and looked to Zareth's pack, which rested on the large table next to her own gear. "The last of what I know that held, in any case."
"Hey, you won't let me lighten any pockets here," Zareth said.
"We're representatives of Sea Gate, Zareth. We're not hungry conscripts anymore."
"Right. We are thirsty members of Sea Gate, Akiri," Zareth said. "The scholars get their maintenance taxes; I don't see a difference in us getting our share."
"The scholars earn those taxes through their work," Akiri said, as she busied herself with clearing her kit from the table. "Same as we earn ours. Now, to that point." Akiri reached into her main pack and fished out a small purse which she tossed on the table before Zareth. It landed with a heavy thud and the sound of gold.
"You didn't," Zareth laughed. He grabbed the purse, opened it, pawed through, and pulled out a coin.
"I found us work. Pays half now and half at the end," Akiri said. "A caravan bound for Coralhelm, set to depart tomorrow."
"At least that is on the way," Zareth said. He plucked a few more coins from the purse, tied it, and stood. "Early morning departure?"
"Would it be any other way?"
Zareth laughed. "Fine then, I'm off to find another drink." He stood.
"Zareth," Akiri said, stopping him. She upended the coin purse, and pebbles spilled from it. Zareth laughed, held his hands up.
"Caught me," he said. "Let me get your round, then?"
"And some of those dumplings," Akiri said. "The ones with the sauce in them."
Zareth left and returned with drinks and food. He sat, passed her share across the table, and the two of them set to eating.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Later that evening, as night had truly fallen and the crowd had grown larger, Akiri and Zareth sat out on the Portage's cliffside deck, finishing one last round of salted, fried food and cool drinks. They had spent some good time catching up—actually catching up—and maybe it was the cool drinks, or the casual atmosphere after so long on the road, but in the course of otherwise light conversation, Zareth asked Akiri a question that would mark this moment as the night's coda.
"When we return to Sea Gate," Zareth said, "you plan to volunteer us for some secret mission. An expedition into one of the Skyclaves." Zareth leaned back in his chair. "That's why we were out here following up on that hedron, right?"
Akiri did not deny it. "Murasa," she said. "Sea Gate thought we might find something useful from a freshly fallen hedron, but that assumed there was a hedron there to find."
"What is there to find in Murasa?" Zareth asked. "Those Skyclaves are all old and dead."
"I don't know," Akiri said. "Our patron is willing to spend good coin on a bet that something waits up there. Something powerful."
"Who is this Akiri?" Zareth asked. "Willing to stake her dream for a better world on a hunch."
Akiri nodded. "The money is good," she said. "No one spends that amount of coin on a hunch. It's a bet—a bet that what we find in Murasa could help us fix our world."
"I know it's my pattern but," Zareth leaned in, lowering his voice, "we could leave in the night, and head for some other land. You and I together, with your skill and my charm? We wouldn't want for anything.
Akiri shook her head. "This is our world, all of its agonies and sickness. Fixing what has been done to her is our struggle, our charge, our #emph[place] ," Akiri said. "We can't leave."
"We might not return," Zareth countered.
"Yes," Akiri said. "We have the same fight as any~bloom after a long winter: a hundred of us might wither in the late cold, or be cut by a jealous gardener, but there are too many for spring not to come. We have to try, no matter the cost."
"And if we find nothing?"
Akiri sipped her drink.
"Hope, at least, I suppose you can bring that back," Zareth suggested. "Give people something to dream about."
"Hope? No," Akiri said, not unkind, but firm. "People cannot make a fervent blade from hope, or shape that feeling into a tender knife." Akiri shook her head. "I don't want to give people hope, I want to create power for our people. Find a way to give our people—all of Zendikar's people—the means by which they might shape a weapon from their pain and use it to heal this world for good," she said.
Zareth leaned back from his conspiratorial hunch. Akiri was rigid, serious.
"Look, I think I've had enough," Akiri said, breaking the rigidity that had gripped her. She indicated the empty mugs and plates. "I'm going to bed. I'll see you tomorrow?"
"I'll be there, Akiri," Zareth said, quiet.
"Will you?"
"You asked me to be there," Zareth said, "so I'll be there."
Akiri regarded Zareth for a moment, a long moment. Zareth did not see Akiri the Fearless Voyager, decorated veteran and storied line-slinger, but Akiri unnamed, the young kor officer who pulled him through the darkness at Sea Gate. Her gray skin caked in the flat ash of their dead friends and the decayed landscape. Her eyes, lit by firelight, blank with terror—but still pulling him forward. Akiri who pressed a dead man's spear into his hand and told him that he needed to #emph[fight ] the things that killed the world with a touch, otherwise no one would be left alive when the Battle was done.
"I'll be there, Aki," Zareth said again.
"Good," Akiri said. "Good," she repeated, quietly, as she left.
The night dragged on long, and Zareth spent none of it asleep.
|
|
https://github.com/mitex-rs/mitex | https://raw.githubusercontent.com/mitex-rs/mitex/main/docs/logo.typ | typst | Apache License 2.0 |
#let wh = 2.5em
#set page(width: wh, height: wh, margin: .08em)
// Default font of Typst
#set text(font: "Linux Libertine")
#let TeX = {
// Default font of LaTeX
set text(font: "New Computer Modern", weight: "regular")
box(width: 1.7em, {
[T]
place(top, dx: 0.56em, dy: 0.22em)[E]
place(top, dx: 1.1em)[X]
})
}
#let func = text.with(fill: rgb("4b69c6"))
#let punc = text.with(fill: rgb("d73a49"))
#align(left + horizon, {
v(-0.1em)
box(scale(61.8%, func("mi") + punc("\u{005B}")))
linebreak() + v(-1.1em)
h(0.35em) + TeX
linebreak() + v(-1.2em)
box(scale(61.8%, [~]+punc("\u{005D}")))
})
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/TA/Fall%202023/Math%20314/Tutorial%209/Tutorial%209%20Solutions.typ | typst | #import "../../../../Templates/generic.typ": generic
#import "../../../../Templates/question.typ": question_heading
#import "@preview/cetz:0.1.2"
#show: doc => generic(title: "Tutorial 8 Solutions", name: "<NAME>", doc)
#show: doc => question_heading(doc)
#let ve = $epsilon$
#let curl = math.op("curl")
#let vect(symbol) = $upright(bold(symbol))$
#let anglevec(body) = { $lr(angle.l body angle.r)$ }
= Question 1
== Statement
Determine whether or not $F$ is a conservative vector field, if it is find its potential function.
+ $F(x,y) = (x y + y^2) vect(i) + (x^2 + 2 x y) vect(j)$
+ $F(x,y) = y e^x vect(i) + (e^x + e^y)vect(j)$
+ $F(x,y) = (y e^x + sin y) vect(i) + (e^x + x cos y)vect(j)$
== Solution
Finding whether $F$ is conservative is quite straight forward as long as the vector field is defined on all of $RR^2$/$RR^3$, we simply check that its curl is zero. (Note that this means we cannot have any division by zero or other undefined operations anywhere else in the definition of the vector field as that means the vector field won't be defined there).
The curl for a 2 dimensional vector field is quite simple, we think of it as alternating the derivatives and the terms. Visually what I like to do is place the elements of the vector field and the partial derivatives in a column, and then alternate.
That is
$
#cetz.canvas({
import cetz.draw: *
content((0,0), anchor: "right", [$ diff / (diff x) quad $])
content((0,-1.5), anchor: "right", [$ diff / (diff y) quad $])
content((2,0), anchor: "left", [$ quad F_1(x,y) $])
content((2,-1.5), anchor: "left", [$ quad F_2(x,y) $])
line((0,0), (2,-1.5))
line((2,0), (0,-1.5))
})
=
(diff F_2(x,y))/(diff x)
-
(diff F_1(x,y))/(diff y)
$
where $F_1,F_2$ denote the first and second components of the vector field respectively.
////
////
+ Using the formula for a curl we have
$
(diff (x^2 + 2 x y))/(diff x)
-
(diff (x y + y^2))/(diff y)
=
2x + 2y
-
(x + 2y)
=
x
$
and so the curl is non-zero, and so this is not a conservative vector field.
////
////
+ Using the formula for a curl we have
$
(diff (e^x + e^y))/(diff x)
-
(diff (y e^x))/(diff y)
=
e^x
-
e^x
=
0
$
and so the curl is zero, and so this is a conservative vector field.
To find the potential let us assume that
$
nabla f = F = (y e^x, e^x + e^y)
$
then we must have
$
(diff f)/(diff x) = y e^x
$
and so we must have
$
f = y e^x + g(y)
$
since the antiderivative of $y e^x$ in $x$ is $y e^x + C$ and the constant $C$ can depend on $y$. Next to find $g(y)$ we check the other component, one one hand we have
$
(diff f)/(diff y) = e^x + g'(y)
$
and on the other hand we have
$
(diff f)/(diff y) = F_2(x,y) = e^x + e^y
$
and so we must have $e^y = g'(y)$ and thus $g(y) = e^y + C$.
Thus our potential function is $f = y e^x + e^y + C$ where $C$ is any constant.
////
////
+ Again, first we check that it is conservative,
$
(diff (e^x + x cos y))/(diff x)
-
(diff (y e^x + sin y))/(diff y)
=
e^x cos y
-
e^x cos y
=
0
$
and so the curl is zero and so it is conservative.
To find the potential let us assume that
$
nabla f = F = (y e^x + sin y, e^x + x cos y)
$
then we must have
$
(diff f)/(diff x) = y e^x + sin y
$
and so we must have
$
f = y e^x + x sin y + g(y).
$
Next to find $g(y)$ we check the other component, one one hand we have
$
(diff f)/(diff y) = e^x + x cos y + g'(y)
$
and on the other hand we have
$
(diff f)/(diff y) = e^x + x cos y
$
and so we must have $0 = g'(y)$ and thus $g(y) = C$.
Thus our potential function is $f = y e^x + x sin y + C$ where $C$ is any constant.
= Question 2
== Statement
Find a function $f$ such that $F = nabla f$ and use it to evaluate the integral $integral_C F dot dif r$ along the given curve $C$.
+ $F(x,y) = #anglevec()[$2x, 4y$]$ and $C$ is the arc of the parabola $x = y^2$ from $(4,-2)$ to $(1,1)$.
+ $F(x,y) = (1 + x y)e^(x y) vect(i) + x^2 e^(x y) vect(j)$ and $C : r(t) = cos(t) vect(i) + 2 sin(t) vect(j) quad 0 <= t <= pi/2$.
+ $F(x,y,z) = (y^2 z + 2x z^2) vect(i) + 2x y z vect(j) + (x y^2 + 2x^2 z) vect(k)$ and $C : x = sqrt(t)$, $y = t + 1$,#linebreak() $z = t^2$ where $0 <= t <= 1$.
== Solution
For this question we repeat the same procedure that we for the previous question except we don't need to check that the vector field is conservative now since the question already gives us that. Then once we have the potential function we simply evaluate it at the two end points.
+ By the same method as above we get that
$
f(x,y) = x^2 + g(y)
$
and then that $g(y) = 2y^2 + C$ and so
$
f(x,y) = x^2 + 2y^2 + C.
$
Since $C$ can be anything, and because we want our life to be easier, we will chose it to be $0$.
The two end points are given in the question so we just evaluate
$
integral F dot dif r = f(1,1) - f(4,-2) = 1 + 2 - (16 + 8) = #(1 + 2 - (16 + 8)).
$
////
////
+ Again using the same method we get
$
f(x,y) = x e^(x y) + g(y)
"and then"
g(y) = C
$
and again we choose $C = 0$ leaving us with just $f(x,y) = x e^(x y)$. The endpoints are not given this time, we must instead calculate them, but this is fairly easy,
$
a = r(0) = 1 vect(i) "and"
b = r(π/2) = 2 vect(j)
$
which gives us
$
integral_C F dot dif r = f(b) - f(a)
= 0 - 1 e^(0) = - 1
$
////
////
+ Finally for 3 dimensions we do the exact same procedure except that finding the potential function is a little bit more complicated.
First from integrating the second component we find that
$
f(x,y,z) = x y^2 z + x^2 z^2 + g(y,z)
$
then from the second one we find that
$
g(y,z) = h(z)
$
and from the last one we find that $h(z) = C$ for some constant $C$. Again we choose $C = 0$. Now the two points are calculated as
$
a = (sqrt(0), 0 + 1, 0^2) = (0,1,0) "and"
b = (sqrt(1), 1 + 1, 1^2) = (1,2,1)
$
and so we have
$
f(b) - f(a) = (0 + 0) - (4 + 1) = -5
$
= Question 3
== Statement
Use green's theorem to evaluate the line integral along the given positively oriented curve.
+ $integral_C y e^x dif x + 2 e^x dif y$, $C$ is the rectangle with vertices $(0, 0)$, $(3, 0)$, $(3, 4)$ and $(0, 4)$.
+ $integral_C x^2 y^2 dif x + y tan^(-1) y dif y$, $C$ is the triangle with vertices $(0, 0)$, $(1, 0)$ and $(1, 3)$.
+ $integral_C (x^2 + y^2) dif x + (x^2 - y^2) dif y$, $C$ is the triangle with vertices $(0, 0)$, $(2, 1)$ and $(0, 1)$.
== Solution
Green's theorem is quite simple in concept, it allows us to convert from line integrals to region integrals. It looks like this
$
integral_(diff D) F dot dif r =
integral.double_D curl F dif A
$
The first thing we do when we have a Green's theorem question like this is to identify the region of integration. Once that is done the rest is easy.
+ Here identifying the region is easy since it is just the rectangle itself. We now need to calculate the curl
$
curl thin (y e^x, 2 e^x)
=
(diff (2 e^x)) / (diff x)
-
(diff (y e^x)) / (diff y)
=
2 e^x
-
e^x
=
e^x
$
and using this we get that
$
integral_C y e^x dif x + 2 e^x dif y
=
integral.double_R e^x dif A
=
integral_0^3 integral_0^4 e^x dif y dif x
=
integral_0^3 4 e^x dif x
=
4 (e^3 - 1)
$
+ For a triangle the region is a bit trickier, but one can check that it can be written as the set
$
{
(x, y) |
0 <= x <= 1,
0 <= y <= 3x
}.
$
The curl is calculated as usual
$
curl thin (x^2 y^2, y tan^(-1) y)
=
(diff (y tan^(-1) y))/(diff x)
-
(diff (x^2 y^2))/(diff y)
=
0
-
2 x^2 y
=
-2x^2 y
$
which gives us
$
integral_C x^2 y^2 dif x + y tan^(-1) y dif y
&=
integral.double_R -2x^2 y dif A
=
-2 integral_0^1 integral_0^(3x) x^2 y dif y dif x
\ &=
- integral_0^1 x^2 [y^2]^(3x)_0 dif x
=
- 9 integral_0^1 x^4 dif x
\ &=
- 9 [1/5 x^5]^1_0
= -9/5
$
+ Again after some working out the region of integration can be written as
$
{
(x, y) |
0 <= x <= 2,
0 <= y <= 1/2x
}.
$
and the curl can be found to be
$
curl thin (x^2 - y^2, x^2 + y^2)
=
(diff (x^2 + y^2))/(diff x)
-
(diff (x^2 - y^2))/(diff y)
=
2x
-
(-2y)
=
2x + 2y
$
and so we can compute
$
integral_C (x^2 - y^2) dif x + (x^2 + y^2) dif y
&=
integral.double_R 2x + 2y dif A
=
2 integral_0^2 integral_0^(1/2 x) 2x + 2y dif y dif x
\ &=
2 integral_0^1 [2x y + y^2]^(1/2 x)_0 dif x
=
2 integral_0^1 5/4 x^2 dif x
\ &=
5/2 [1/3 x^3]^1_0
= 5/6
$ |
|
https://github.com/RY997/Thesis | https://raw.githubusercontent.com/RY997/Thesis/main/thesis_typ/abstract_de.typ | typst | MIT License | #let abstract_de() = {
set page(
margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm),
numbering: none,
number-align: center,
)
let body-font = "New Computer Modern"
let sans-font = "New Computer Modern Sans"
set text(
font: body-font,
size: 12pt,
lang: "en"
)
set par(
leading: 1em,
justify: true
)
// --- Abstract (EN) ---
v(1fr)
align(center, text(font: body-font, 1em, weight: "semibold", "Zusammenfassung"))
text[
Als Reaktion auf die Herausforderungen, die sich aus größeren Klassen in der Informatikbildung ergeben, übernimmt Artemis, eine Open-Source-Lernplattform, interaktive Lernprinzipien, um die Skalierbarkeit und Anpassungsfähigkeit zu verbessern. Die Plattform sieht sich jedoch mit Mängeln konfrontiert, wenn es darum geht, auf die unterschiedlichen Fähigkeitsniveaus und Lernbedürfnisse der Studierenden einzugehen. Dies motiviert die Erforschung der Erzeugung adaptiver Programmieraufgaben, die darauf abzielt, maßgeschneiderte Herausforderungen für einzelne Lernende anzubieten. Adaptive Aufgaben haben das Potenzial, sowohl fortgeschrittene Studierende herauszufordern als auch Anfänger effektiv zu unterstützen, um intellektuelles Wachstum und Selbstvertrauen zu fördern. Durch die Nutzung von Fortschritten in der künstlichen Intelligenz (KI), insbesondere von großen Sprachmodellen (LLMs), stellt diese Arbeit einen neuartigen Ansatz zur Erstellung adaptiver Programmieraufgaben vor. Die Ziele umfassen die Entwicklung eines Chatbots namens Iris für die intelligente Planung von Übungen, die Ermöglichung von LLMs für die dynamische Ausführung von Übungsänderungsplänen und die nahtlose Integration von Übungsänderungen in die Artemis-Plattform. Diese innovative Methodik verspricht, die Informatikbildung durch die Bereitstellung personalisierter Lernerfahrungen zu revolutionieren und ein kontinuierliches Wachstum bei den Studierenden zu fördern.
]
v(1fr)
} |
https://github.com/Gekkio/gb-ctr | https://raw.githubusercontent.com/Gekkio/gb-ctr/main/chapter/peripherals/serial.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "../../common.typ": *
== Serial communication
#reg-figure(
caption: [#hex("FF01") - SB - Serial data register]
)[
#reg-table(
[R/W-0], [R/W-0], [R/W-0], [R/W-0], [R/W-0], [R/W-0], [R/W-0], [R/W-0],
table.cell(colspan: 8)[SB\<7:0\>],
[bit 7], [6], [5], [4], [3], [2], [1], [bit 0]
)
#set align(left)
#grid(
columns: (auto, 1fr),
gutter: 1em,
[*bit 7-0*], [*SB\<7:0\>*: Serial data],
)
]
#reg-figure(
caption: [#hex("FF02") - SC - Serial control register]
)[
#reg-table(
[R/W-0], [U], [U], [U], [U], [U], [U], [R/W-0],
[SIO_EN], unimpl-bit(), unimpl-bit(), unimpl-bit(), unimpl-bit(), unimpl-bit(), unimpl-bit(), [SIO_CLK],
[bit 7], [6], [5], [4], [3], [2], [1], [bit 0]
)
#set align(left)
#grid(
columns: (auto, 1fr),
gutter: 1em,
[*bit 7*], [*SIO_EN*],
[*bit 6-1*], [*Unimplemented*: Ignored during writes, reads are undefined],
[*bit 0*], [*SIO_CLK*]
)
]
|
https://github.com/Isaac-Fate/booxtyp | https://raw.githubusercontent.com/Isaac-Fate/booxtyp/master/src/main.typ | typst | Apache License 2.0 | #import "lib.typ": *
#show figure.where(kind: "Theorem"): it => it.body
#show figure.where(kind: "Proposition"): it => it.body
#show figure.where(kind: "Definition"): it => it.body
#show: book
= Introduction
@thm:5 is a very important theorem.
@def:1 is the definition of the exponential function.
@def:2 is the definition of the exponential function.
@pro:1 is a very important proposition.
== First Section
#definition[
The exponential function, denoted by $exp(x)$, is defined as
$ exp(x) := sum_(n = 0)^oo x^n / n! $
]<def:1>
@eq:1 is a very important equation.
#theorem(title: "Important theorem")[
This is a theorem.
$ e^x = lim_(n -> oo) a $
]
#proof[
#lorem(1000)
]
#note[
Hmmm... I wonder if this is true.
]
#exercise[
This is an exercise.]
#exercise[
This is an exercise.
]
#exercise[
This is an exercise.
]
#solution[
This is the solution.
]
#proposition(title: "Important theorem ")[
This is a theorem.
$ e^x = lim_(n -> oo) a $
]<pro:1>
#definition[
The exponential function, denoted by $exp(x)$, is defined as
$ exp(x) := sum_(n = 0)^oo x^n / n! $
]<def:2>
#theorem(title: "Important theorem ")[
This is a theorem.
$ e^x = lim_(n -> oo) a $
]<thm:5>
@eq:1 is a very important equation.
== Second Section
$ T: V -> W $
$ T: V -> W $<eq:1>
#definition[
The exponential function, denoted by $exp(x)$, is defined as
$ exp(x) := sum_(n = 0)^oo x^n / n! $
]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/titleize/0.1.1/lib.typ | typst | Apache License 2.0 | #let _plugin = plugin("titleize.wasm")
#let string-to-titlecase(s) = {
str(_plugin.titlecase(bytes(s)))
}
#let titlecase(body, limit: 4) = {
show regex(".{" + str(limit) + ",}"): it => string-to-titlecase(it.text)
body
} |
https://github.com/PhilChodrow/cv | https://raw.githubusercontent.com/PhilChodrow/cv/main/src/cv.typ | typst | #import "template.typ": *
#show: layout
#cvHeader(align: left, hasPhoto: true)
#autoImport("experience")
#autoImport("education")
#autoImport("grants")
#autoImport("papers")
#pagebreak()
#autoImport("talks")
#autoImport("awards")
// #pagebreak()
#autoImport("teaching")
#autoImport("pd")
#autoImport("service")
#autoImport("college-service")
// #grid(
// columns: (60%, 40%),
// gutter: 16pt,
// stack(
// spacing: 20pt,
// autoImport("experience"),
// autoImport("education"),
// ),
// stack(
// spacing: 20pt,
// autoImport("skills"),
// autoImport("interests"),
// ),
// ) |
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/PianoDiProgetto/sections/PianificazioneSprint/DecimoSprint.typ | typst | MIT License | #import "../../functions.typ": glossary
=== Decimo #glossary[sprint]
*Inizio*: Venerdì 23/02/2024
*Fine*: Giovedì 29/02/2024
*Obiettivi dello #glossary[sprint]*:
- Proseguire la stesura del _Piano di Progetto_:
- Aggiornare pianificazione e preventivo pertinenti allo #glossary[sprint] 10 e inserire il consuntivo pertinente allo #glossary[sprint] 9;
- Aggiornare ed aggiungere pianificazione e preventivo per gli #glossary[sprint] 11 e 12;
- Continuare a progettare la struttura architetturale del prodotto, traducendo le architetture individuate in una bozza di diagrammi (seguendo le prassi specificate a tal riguardo nelle _Norme di Progetto v2.0_);
- Proseguire la stesura della _Specifica Tecnica_, con il miglioramento delle sezioni *Introduzione* e *Tecnologie* e lo sviluppo dei contenuti fondamentali della sezione *Architettura* in modo da avere una progettazione definita, che permetterà successivamente l'inizio della sua implementazione nel prodotto. |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/044%20-%20Innistrad%3A%20Crimson%20Vow/006_Survivors.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Survivors",
set_name: "Innistrad: Crimson Vow",
story_date: datetime(day: 12, month: 11, year: 2021),
author: "<NAME>",
doc
)
"Good people of~" Torens began but stopped short when he drew a blank at the village's name. Over the past two years, earning money had involved cycling through Innistrad's isolated hamlets, eating from the same roast chicken for a week, and avoiding stretches of road where ghastly things prowled for easy prey. Keeping track of where he was had become even harder when all the days blended into a single endless night. "Good people," he began again. "These are challenging times. And challenging times require challenging~things."
#emph[Dammit.] The extra half day of travel along the Kessig-Stensia border—thanks to a rather zealous cathar named Ingrid who unceremoniously chased him out of Silbern, his preferred stay—had caused words to feel slippery and serpentine. Regrouping himself, he motioned toward the contents of his wagon, all prepped for display. The canvas top had been pulled up over the wagon hoops with the words "Torens's Curious Goods" painted on the inside of the cover. In the wagon bed rested wicker bins filled with various small sundries, all reasonably priced and labeled accurately.
#emph[Reasonably] accurately.
#figure(image("006_Survivors/01.jpg", width: 100%), caption: [Torens, Fist of the Angels | Art by: Justine Cruz], supplement: none, numbering: none)
"Have a werewolf problem?" Torens asked the crowd, reaching into one of the baskets to pull out a small brown bottle. "I have a werewolf #emph[solution] ." He'd never heard any complaints about his anti-lycanthrope serum—mostly because he never stuck around long enough to hear them.
"What about witches' curses?" he continued, dipping into another basket and producing a necklace strung with hollowed bat bones. "Wear this, and you'll be hex-free, guaranteed. Plus, it's one hell of a fashion statement."
"Vampires?" Some faces in the crowd lit up with recognition. Torens pulled out a small silver mirror, dirty and smudged, along with a flat canister from his back pocket. He slathered the viscous contents of the canister all over the mirror, and after a short once-over with his shirt cuff, he turned the spotless glass back onto the crowd. "Vampires can look like anyone, fade into mist, turn into bats! But you'll always be able to spot them with this—Torens's Clairvoyic Varnish! Now don't all come rushing at me at once."
They didn't. Instead came jeers and bouts of laughter.
"People, people!" a voice called out, cutting short the laughter. The man who had spoken stepped forward, parting the crowd like a returning king. "We get so few visitors to our humble village. If you're not going to show our guest respect, then you should go home." The crowd responded with murmurs but no protestations as they dispersed. The man introduced himself. "I am Vytas. Allow me to apologize on behalf of the people of Traublassen. They are simple folk."
"Whatever. The message was loud and clear. I'll be on my way."
"Sir, I don't want you to leave. I have a task suited to a man of your talents. One that pays."
Hmm. A paying gig would do a lot of good to wash out the sour taste of that day. But frankly, he couldn't stand being in the same vicinity as Vytas let alone work for him. The man's wardrobe screamed a pretense of haute couture: a tunic of linen with underlayers of silk and velvet, all with fine gold trimming. Worse was his high-and-mighty tone, like a lord palliating a hog with choice morsels just before nodding a go-ahead to the butcher.
"Pass," said Torens.
"The offer is most generous," Vytas said. "I doubt those looking for you would make nearly as equitable a deal. It would be a shame if someone aided them in their search." He patted Torens's wagon. "Quite remarkable how fast determined cathars on horseback can travel compared to someone pulling a load like this."
Torens grumbled. "What do you want?"
"For you to listen," Vytas said. "Come. We'll talk in my study."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Torens and Vytas rode through the village to Vytas's manor house. Alabaster columns dominated the front facade, and the dozen windows implied at least that many rooms. As they approached, Torens spied a young man standing by the front door. Vytas let out an annoyed groan as he climbed down from the wagon.
"Aleksandar," said Vytas. "It is late."
Though he was a clear head taller than Vytas, Aleksandar was a jumble of knees and elbows under a messy blonde mop. In a few years, Torens surmised, he'd fill out his frame. But until then he'd have the presence of a noodle in day-old soup.
"It's about rent, sir," Aleksandar said, managing to stay in front when Vytas's man tried to sidestep him. "Give us one more week. My father has some contracts coming in, and—"
"This is neither the time nor the place."
"Why not?" said Torens, joining them on the doorstep. "Give the kid a break."
Vytas leaned in close to Torens. "These are separate matters from ours."
"I'm hearing you out. Why don't you do the same for him?"
Vytas harrumphed but maintained his composure.
"Aleksandar, you and I can discuss things after my dealings with this gentleman are concluded. In the meantime, take his wagon to the stables." Vytas straightened his shirt, pulled his cloak tight, and beamed a wide smile back at Torens. "Shall we?"
Vytas's manor was as ostentatious as the finest mansion back in Thraben. Before The Travails, Torens had served as a Mausoleum Guard; his least favorite jobs were house calls to the homes of jumpy aristocrats who swore their dead relatives had risen from the grave to steal back their inheritances. It usually turned out to be the cat (except for that one time). Greeting Torens just inside Vytas's foyer was a bronze sculpture of a wolfpack dashing across a prairie. Farther up, on either side of a grand archway, hung two paintings: one of Vytas himself, with a generous tuft of hair on the top of his head, and another of a bearded man clad in a black tunic and coif, a pair of thick-lensed spectacles balanced on the tip of his nose.
"My great-grandfather, Taivas," Vytas proclaimed. "He founded Traublassen with nothing more than a vision and his knack for hunting."
Torens followed Vytas through hallways bedecked with various art pieces until they arrived at a room dominated by a dark wooden desk topped with papers, quills, and a decanter of wine. Vytas poured out two glasses.
"What's the job?" said Torens, ignoring the wine Vytas nudged toward him.
"Not one for niceties, eh?"
"Threats don't exactly make a great first impression."
"Threats?" Vytas lowered himself into his leather-backed desk chair. "It's my business to know who is coming in and out of my town. I have extensive church contacts. Word can travel fast, given means and motivation. A weapon imbued with a runechanter's ward is quite the motivation for your fellow cathars, as is the apprehension of the brother-turned-thief that absconded with it."
Torens stewed in silence. #emph[Exactly how much does Vytas know?]
"Relax. I have no interest in your internecine squabbles," Vytas continued. "In fact, I sense a good soul in you, despite what I've been told. You carry yourself with a certain nobility that I believe surpasses whatever issues have plagued your past."
"Get to the point."
"Indeed. You've no doubt taken note of the people of this town. They're stalwart stock. My great-grandfather ensured that from the outset. He formed alliances, used his wealth to encourage more settlers and provide for their security."
"His #emph[tenants'] security."
"He shouldered the risk, as I do now. I provide seed, medicine for livestock, arms for the village's security. Some measure of compensation is a reasonable expectation." Vytas straightened some papers on his desk into a neat pile. "Still, no one is perfect. Recently, some reports have come to me in private about strange sounds emanating from the keep overlooking the village."
"A keep?" Torens didn't remember seeing such a structure on his way into town.
"With the encroaching darkness, it can be hard to discern against the horizon," said Vytas. "According to reports, the noise is a faint screeching. It could merely be some wounded animal, but it's my job to be sure."
"No one seemed very distressed back in the village square."
"With all due respect, you're an outsider. They don't trust you like they trust me."
"Trust. Sure. That's what I saw back in the square."
Vytas smirked at Torens's barb. "You will investigate the keep. If you find something out of the ordinary, you will take care of it. Discreetly, of course."
"Of course," Torens sneered. "Got me over a barrel."
"Hardly. The fee will absolutely be worth your time." Vytas pulled open one of the lower drawers of the desk, pulled out a small box, and lifted the lid to reveal that it was filled with pristine gold coins, each stamped with the laureled symbol of Avacyn. Vytas counted out twenty-five, one by one, and slid them across his desk into a pile. "That's half with the other half due upon completion."
Torens picked up a coin to study it. He pressed it between his fingers, flipped it over close to Vytas's lantern light, even sniffed it. It was the real thing. And fifty total for the whole job? That was enough to keep him well stocked for well over a year. Still, this whole deal felt off, even accounting for Vytas's coercion and Torens's own revulsion at working for someone so slimy.
"So," said Vytas, wrenching Torens from his thoughts. "Do we have a deal?"
"I don't have much choice, do I?"
"There's always a choice," said Vytas. "It's simply that some options are better than others."
"Fine, except for one thing," said Torens, sliding the coins into his hand. "How much is the boy's rent?"
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[Vendors in Hanweir's famed marketplace split their time packing up their booths and hurriedly addressing customers' last-second purchases to avoid an impending cloudburst. The hubbub was a perfect distraction for Torens to slip his hands into unguarded pockets and come away with spare coin. At twelve years old, his fingers were small and precise—perfect for pilfering bits here and there to surreptitiously add to the family coffers—as long as he had a bit of cover.]
#emph[Wandering by the livestock pens, he spotted the perfect mark: a well-dressed man flanked by two servants holding their cloaks over his head, deep in negotiations with a farmer selling chickens. One of the servants shook a single gold coin at the farmer's face while the well-dressed man held the hard line: "One gold for the whole lot! Take it or leave it!"]
#emph[Gold! Torens had never seen it in real life. His mother, a washer woman, made her wages in copper. His woodworker father, on the other hand, must have been paid some measure in gold, but only a scant few silvers survived his ale-fueled bets on the turtle races down at Lost Lake tavern. Even two or three coins alone could feed the whole family for several weeks.]
#emph[It had started to drizzle. Standing back up, Torens stepped into the flow of the people making their way out of the market. He worked his way up to where the well-dressed man and his cohorts stood, and, timing his window just right, he jabbed his arm out and dipped two fingers into the servant's open pocket, pinching out two of the precious coins. He drew his arm back with his bounty held tight and took a moment to gaze upon the prize.]
#emph[It was a moment too long. The servant lunged after Torens, and while the boy managed to evade his grasp, the men gave pursuit. Unfortunately, the crowd that had provided him shelter now impeded his escape, and it wasn't long before he felt a set of hands grabbing his arms, another set holding his neck. He was dragged back to the merchant's booth. Waiting for him there was the well-dressed man, a scowl on his beet-red face.]
#emph["Insufferable brat!" said the man. "You know what happens to dregs like you? You disappear. Because you're of no use, not worth anyone's care."]
#emph[Suddenly, Torens felt one of the servants let go of him. He turned in time to see the man thrown across the path into a crate of fish. The other servant hopped up to his feet, only to receive a well-placed gut punch. A towering shadow overtook the well-dressed man, who, finding himself alone, fell backward onto the muddy ground.]
#emph["Wh-what is the meaning of this?" he stammered.]
#emph[Torens stood up, smiled, and approached his savior: his older brother Elamon, who stood one and a half heads over everyone else in the market. Before Torens could celebrate, Elamon snatched the coins and tossed them back at the wealthy man.]
#emph["Never touch my brother again," Elamon said to the men on the ground. "Now leave."]
#emph[Scurrying up to their feet, the man and his servants scrounged up their money and fled.]
#emph[Taking Torens by the collar, Elamon dragged him underneath an outcropping to escape the now-downpour.]
#emph["I'm not always going to be around to save your hide," he said.]
#emph["Like you're some hero!" yelled Torens. "I didn't need saving!"]
#emph["How many times have I pulled you from the fire? I've lost count."]
#emph[Torens had no rebuttal. Instead, he focused on his lost quarry. "We needed that money!"]
#emph["Not this way." said Elamon.]
#emph["But—"]
#emph["Enough!" Elamon jammed a finger into Torens's chest, pinning him to the wall. "We're going home."]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
In the dead of night, going alone into the unknown was a choice made by the foolhardy and the desperate; thus, Torens didn't protest when Vytas offered his son, Boris—burly and taciturn, with a jaw like an anvil and the charm of another, slightly heavier anvil—as guide.
"You stink of the city," Boris said upon introductions. Torens sniffed the inside of his collar. He wouldn't have been mistaken for a bouquet of flowers, but at least he didn't smell like a particularly busy day at the slaughterhouse. Traublassen's major cash product was in the pelt and fur trade, and chief among Vytas's trapper corps was Boris.
The keep's days as a protective structure were long past. After crossing a bridge over a dry moat and passing through a crumbling barbican, Boris and Torens arrived at a small courtyard. Perhaps once this had been a verdant garden, but all that remained now were empty stone planters on top of brittle, broken dirt. They crossed the dead ground and approached a set of tall black iron doors, a sculpture of a hellkite embedded into it.
"My great-great-grandfather Taivas built this door," Boris said, patting it like a pet. "He was a visionary, a genius." Placing the lantern on the ground, he pulled a brass sphere the size of his fist from his belt pouch and placed it into a recess in one of the dragon's eyes. The low grinding sounds of tumblers turning against stone followed, and the door slipped ajar.
Suddenly, his prideful smile vanished, and, unsheathing a long knife, Boris sprinted back toward the barbican. Torens gazed past the edge of the lantern light. He saw nothing but heard sounds of a struggle, prompting him to reach into his satchel and grip the iron-shod handle of his weapon. He let go when Boris returned with Aleksandar, the young man from earlier. He'd changed out of his work clothes into a well-worn suit of archer's armor, the hard leather at the elbows cracked and flaking. On his belt hung a sword in its sheath.
"Why are you following us?" asked Torens.
"I wish to offer my protection while you are exploring the keep," answered the boy. "It's a matter of honor. You paid my family's rent."
"Honor and a tin of rotten fish won't get you much more than a stomachache," said Torens. "If you're lucky."
"Listen to sense, boy," Boris mocked. "Go back home and make sure next month's rent is on time. Or would you rather do this dance again?" Judging from Aleksandar's despondent expression, the answer was no. The kid may have had guts, but he didn't have the muscle needed to back that mettle up. At least he knew it. Satisfied with himself, Boris turned his attention back to Torens. "I'll lock the door behind you—for the safety of the town." He pointed up to a small window on the second floor. "When you're done, shine a light, and I'll let you out."
Torens nodded and stepped inside. Then he turned to Aleksandar.
"You coming or what?"
Aleksandar broke out into a smile and raced to Torens's side.
"Your grave," Boris grumbled as Aleksandar hustled past. He shut and locked the door behind them.
Torens, with Aleksandar following, stepped into the quiet hallway. Shards of stone tiles and bits of fallen masonry crunched underfoot. The sounds of tiny claws skittering on the floor came from just outside the edge of the light. At the end of the corridor was a doorway that opened into a wider space on the other side.
"Sir?" said Aleksander. "Why did you change your mind back there?"
Torens didn't answer right away. He scanned the edge of the light for larger signs of movement among the shadows and then proceeded to the doorway. Extending his lantern inside the room beyond, he guessed that this was the keep's great hall, judging by its size. At the far end of the hall was a staircase winding upward to a mezzanine overlooking the ground floor. This place may once have been party to feasts or meetings of import between significant dignitaries. None of that opulence remained.
"I hate bullies," said Torens, waving Aleksandar forward. "And I really hated that one." He knelt, placing his satchel onto the ground. Then he reached inside and once again grasped the handle of his weapon. Electric pinpricks climbed up his arm. "It was still a mistake to follow us."
"I told you why I did. You paid—"
"That's nothing."
"It's not nothing," said Aleksandar. "My family runs a smithy. Without the sun, crops don't grow, and no crops means no need for new farming tools or fixing old ones. We're lucky that I tend Vytas's stables for a bit more money, but there's only so much belt-tightening we can do. You saved us."
"I didn't save anyone," said Torens. He stared at the ground, searching for a change of subject, before catching sight of the scabbard on Aleksandar's belt. "Let's see that sword of yours, kid." The boy unsheathed a sturdy-looking blade and handed it to Torens, who balanced it across his palms to test the weight. "It's good work," he noted as he handed the sword back. The boy was beaming. It didn't matter that the make was simple and the hilt crude. "You know how to use it?"
"I've had a few lessons from my mother," said Aleksandar. "She grew up in Estwald, where her father was captain of the guard. She's shown me a few tricks."
"Sounds like your family's pretty close. Mine wasn't exactly hugs and kisses."
"It's always been just the three of us. We take care of each other."
A scream pierced the silence, a human cry.
"It's coming from up there!" Aleksandar exclaimed as another scream rang out. "C'mon!" Sword in hand, he bolted up the stairs. Torens pulled the mace from his satchel, flooding the room with bright white light. Rushing up, he reached the landing in time to see Aleksandar throw open the locking pin and charge in.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[The night was full of laughter, the slosh of indisputably diluted ale poured into cups followed by the slap of pale amber splashing onto the tabletops. Jorelda's Pub was the latest venue to be graced by Marguerite, one of Gavony's most celebrated bards. It turned out that would-be nobles and gutter ruffians alike enjoyed bawdy songs, even if the tipsy mandolinist accompanying her played every third chord sharp or flat.]
#emph[Torens raised a stein to his mouth with an unsteady hand. His contact was late. It had taken the better part of a month to organize the shipment of bezoars, talismans, rare herbs, and other items declared contraband by the town council. The ban hardly affected demand. Rumors out of otherwise peaceful hamlets pegged the missing travelers not on desperate highwaymen, as the authorities proposed, but on creatures more terrible. Whatever the story—a wolfpack ten thousand strong, winged monstrosities assembling on the Ashmouth, or some other concocted nightmare—it stoked fear in the population that made for fertile, untapped markets.]
#emph[All Torens needed was this one deal to pull through. No more fending away debt collectors, who'd learned to wait until Elamon was away to accost his mother. The take would be enough to outright purchase a home and ensure food was always on the table. All that was left was to meet up with a man named Rogel and finalize the deal. Regrettably, Torens had neglected to obtain a description of Rogel, leaving him to sit at the bar and huddle over his drink.]
#emph[From out of nowhere, a pair of bear paws gripped his shoulders and shook.]
#emph["Little brother!" Elamon, smelling of oiled armor and sweat, sat next to Torens and ordered an ale. Many in the bar momentarily tore their attentions away from Marguerite to gawk at Elamon out of admiration, desire, or fear. He'd become somewhat of a local celebrity, thanks in part to him rooting out a werewolf among the ranks of his fellow garrison members. Goodly people raised their fists in his honor. Outlaws on the lam slinked off seats and made hasty exits. "I didn't expect to see you here!"]
#emph["Same," said Torens, scanning for lines of egress. "You're not the carousing type."]
#emph["A contact tipped us off that some kind of deal was going down here tonight. Last week, we intercepted an entire crate of severed fingers, hundreds of them, each labeled as the holy digit of Saint Traft himself. Can you believe that?"]
#emph[Torens could. He wasn't involved with the deal but knew the people who were. They'd gone into hiding now that the loan sharks who lent them money were coming for their cut in either coin or blood, whichever was most expedient.]
#emph["I thought you were a town watch, not a trade federation."]
#emph["I tried to tell Captain Lysandra. She responded by sending me on this wild goose chase."]
#emph["Have fun with that. I'm going to go."]
#emph["Not so fast," said Elamon, laying a hand on Torens's shoulder, lowering him back into his seat. "How long has it been since we relaxed and talked?"]
#emph[Damn. Why couldn't it be easy? "Let's see. I'm twenty-one, so. . .twenty-one years."]
#emph[Elamon took a long drink and nodded. "I don't expect you to understand." He was different than what Torens remembered—more sullen, content to gaze into the froth topping his drink. "You're still staying with your friends by the docks?"]
#emph["Yeah." Friends? More like accomplices. After their father died two years before, leaving Elamon the default man of the house, the rule of law came swiftly. A curfew. No carousing at local dives. An ever-expanding list of "hoodlums" Torens was forbidden from associating with. Their nightly arguments rarely did more than agitate their mother, herself sickly and bedridden. Two months of this, and Torens had had enough. He moved out and into a hovel ironically populated by the kinds of people Elamon thought he was placing on his list. Still, Torens felt like they were his people, those who understood that you either claw out of the pit or get swallowed. No middle ground, no room for principle when survival was at stake.]
#emph["Ma asks about you. She always sets a place at dinner."]
#emph["Don't," said Torens. "You know how it would be if I was back at home."]
#emph["You could at least stop by to see her once in a while. Just last night. . ." Elamon's voice trailed off as his gaze drifted from Torens to a point across the room. Turning his head, Torens spotted exactly what his brother was looking at—just inside the doorway was a gaunt man who more resembled a lost rabbit than a typical bar patron. He'd only have stuck out more if he were on fire. Elamon got up and left a few coppers on the bar. "Buy us another round. I'll be back."]
#emph[Torens didn't know if that was Rogel who'd just entered, but he couldn't take the chance.]
#emph["Elamon!" he called out.]
#emph["What is it?"]
#emph["For what it's worth, I do understand. Thanks for always looking out for me." Torens curled his fingers around the handle of his stein. "I'm sorry." With that, he picked up the stein and whipped its contents into Elamon's face, using the moment to barrel past his brother, through the crowd, and out the door. He had to get somewhere safe, and quickly. Torens slunk down a gangway between two shops and emerged on a small, twisty lane with the intention of blending in with the rest of the nighttime carousers. A good plan, but it wasn't meant to be.]
#emph["Stop." Elamon was approaching from the far intersection, his crossbow loaded. "Why, Torens?"]
#emph["You know why," he answered.]
#emph["Every day, I work to help our family! To gain respect! This is how you succeed!"]
#emph["Respect? From whom? The captain who bullies you? And the council? They're too busy sipping fine wine while caravans are being slaughtered on the roads. We're nothing to them. We don't matter unless we make our own opportunities."]
#emph["No," said Elamon, only a few steps away. He threw down his crossbow. "There is a right way to do things."]
#emph["Does that include arresting me?"]
#emph[Elamon lunged for his brother, but Torens nimbly ducked and darted away from every attempt. Elamon move forward with another attempt at a bear hug, but Torens dodged again. His brother was pulling his punches—Torens could tell. Even with his armor weighing him down, Elamon was faster than this. If the circumstances only involved convincing Elamon to stand down, perhaps there were options for Torens other than running away. But his brother's lenience, wrought by either love or heartbreak, wouldn't help him fend off the rest of the guard who would soon swarm the area around Jorelda's.]
#emph[Torens waited for Elamon to reach for him once more. This time, he feinted a punch, throwing his brother slightly off balance. That was the opening he needed to break away and get lost in Hanweir's twisty alleyways before skipping town.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Too late to stop Aleksander, Torens launched himself across the threshold and into the doorway. The darkness on the other side was thick, choking—smoke as dense as shadow. The light from his mace, which had been a boon, lit up the smoke, surrounding him in a blanket of featureless gray.
"Aleksandar?" he called out.
Answering him were a series of snarls and hisses that seemed to come from everywhere, and then, arising mere inches from him, a taloned hand attempted to rake him across his face. He managed to dodge backward and swat the claw away with his mace, causing whatever creature it was to squeal in pain. Torens stepped back into a defensive position only to walk right into two more claws slashing him across the leg. He fell to his knee, spying a flurry of three-toed feet clacking on the floor underneath the smoke cloud.
"Aleksandar! Where are you?" He came back to his feet and stood his ground, waiting for something meaty—a head, a body—to swing at. None came. Instead, the smoke dissipated, allowing the light from Torens's mace to gradually permeate the room. The first thing he spotted was Aleksandar's sword on the ground next to the shattered remains of Boris's lantern. He bent to pick up the sword, uttering every curse he'd ever learned.
"<NAME> Hanweir," said a woman's voice from behind him. He swung around with mace and sword ready to strike, only to be faced with something—someone—completely unexpected. Pushed into the corner of the room was a decrepit bed and, on it, a woman in her bedclothes, the covers bunched up around her as she huddled against the stone wall. Had she been there the whole time?
#figure(image("006_Survivors/02.jpg", width: 100%), caption: [Eruth, Tormented Prophet | Art by: <NAME>], supplement: none, numbering: none)
"How do you know my name? What the hell is going on?"
"The devils took the boy to their master."
Devils. Great. And their demon master. Double great. Torens had experience with zombies and ghouls as a Mausoleum Guard, but demons were reserved for Moor Chaplains who specialized in exorcisms or Spearsages adept at incinerating fiends with angelic flame. Best thing he could do was insult the things and then die.
"My name is Eruth." She pulled the bed covers away to reveal shackles on both her ankles chaining her to the wall. The skin under the metal was blistered and raw. "I'm a prisoner of the hunters, as you are."
"Hunters?" he asked.
"Those men who stink like fresh meat left to dry."
And there was the catch. Vytas and Boris and maybe the whole damn town were a bunch of cultists, and Torens and Eruth were the main course for their demon lord. Torens promised that, should he ever encounter Boris again, he'd see how appreciative that offal-smelling brute would be when his great-great-grandfather's visionary genius was dropped on his face.
"Let me get these things off," said Torens. He studied the chains attached to Eruth's ankles. They were thick and strong, but at least there didn't seem to be any magic involved. A bit of elbow grease and the right angling, and he could bend the shackles enough to slide her feet out. "Your legs. I gotta touch them. That okay?"
"Do what you must."
He knelt down and got to work, first testing the tensile strength of the chains with his hands and then wedging a flange on the head of his mace into one of the clasps to pry it open. "What is this place?" he asked. "Some kind of evil temple?"
Eruth shook her head. "I only know what the Dark Lady tells me."
He looked up. "Who?"
"The Dark Lady. She's standing right behind you."
Torens held his breath as he turned to see no one, noting that his mace had not flared up as it normally did in the presence of spirits or fiends.
"She's my companion. I learned your name from her. And she's the one who has helped me evade~people like you. Cathars." The way she said it—more spat out than stated. It wasn't like it was his choice to join the ranks of Avacyn's soldiers. After running away from Hanweir, Torens had made his way toward the high city of Thraben. Soon after, he found himself besieged by zombies and skaabs along with the city's population. When he was caught scavenging corpses on the battlefield, he had the sheer dumb luck to be brought before the commander of the Gavony Riders. Someone less understanding than Odric would have jailed him and left him to rot. Instead, he offered to put in a word with Thalia, Thraben's new guardian. #emph[You're a survivor] , Odric had said. #emph[The church needs men like you, especially now.]
"I'm retired," said Torens.
"Is that not one of their holy weapons?"
"It was. Now it's not."
Eruth went on. "Cathars came to Lambholt demanding information from me."
"From you? Why?"
"I have dreams. Visions of the future, mostly about the impending deaths of others. When they could not act on what I told them, they called me a heretic and erected their execution blade in the center of the village."
Torens had heard stories of so-called "mad prophets," people who purported to divine the fates through communion with lost gods, nature spirits, or demons. Usually, these unfortunate souls were left to wander byways spewing proclamations into the air. More recently, they'd been corralled and sent to facilities like Geier Reach Sanitarium. But execution? That was the purview of one particular group within the church.
"Inquisitors," he growled.
"Sadists in vestments playing at holiness. I fled to the mountains, and there, the Dark Lady came to me. I've only been able to keep one step ahead of them because of her."
"She didn't warn you about the hunters. Isn't that a bit suspicious?"
"She's proven herself to me. Unlike you."
"That's fair," he said, sliding Eruth's feet out of her fetters. "You're free. Can you walk?"
Eruth placed her feet onto the floor, leaned forward, and stood, only to double over immediately after. Torens caught her and walked her around the room until she had her legs under her once more.
Sitting her on the bed, Torens questioned her: "The devils' master. Tell me where."
"The Dark Lady says that he's down. Deep down below."
"Not much to go on, but I'll figure it out. Stay here until I come back."
"I am coming with you, Torens of Hanweir. My destiny is down there, as is yours."
"It's just Torens, okay? And no, you're not coming because it's not safe." He tried to stare Eruth down, but she only gazed back at him with the glassy-eyed stare of someone whose experience lay one step away from the abyss. "Fine," he said, pressing Aleksandar's sword into her hands. "If you're with me, you'll need this."
"I'm no fighter."
"And I'm no hero. But sometimes, it's gotta be you."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[Torens spurred his horse faster.] Almost there#emph[, he thought.]
#emph[The roads linking Thraben to the rest of Gavony had seen much traffic lately, and those connected to his hometown were no exception. A week earlier, refugees from various parts of the province had begun to stream into the high city. Their reasoning was sound. If any place was a haven from the madness that had beset the land, the seat of the church would have been it. But to Torens, Thraben felt more like bait for a giant rat trap about to get sprung, and he'd rather not have had his neck in prime snapping position.]
#emph[Leaving was bittersweet. In the three years he'd been part of the cathars, Torens had grown fond of the motley crew the church had assembled out of desperation: ex-convicts, men and women estranged from their families, lost souls searching for purpose. But once Odric was ousted from his place on the Lunarch Council, Torens forfeited his trust in the banner. That didn't change the respect he had for those he served with, so it bothered him to abandon his post. But once he'd heard the confusing, nonsensical testimonies of those who'd fled Hanweir, he knew he had to leave right away.]
#emph[His departure came at the perfect time. Some refugees described a great earthquake that swallowed Hanweir. Others talked about their friends and neighbors becoming monsters before their eyes. And the wildest, from a pair of boys so exhausted from non-stop traveling that they were barely able to speak:]
#emph["It's gone. The whole town just walked away."]
#emph[Torens slowed his horse as he approached the shore of the River Kirch, the waterway that facilitated Hanweir's rise as Gavony's agricultural center. Sticking out of the water were the masts of several sunken boats, along with the crushed remnants of the piers that had once made up the wharf. He realized that he was standing where the docks used to be.]
This is not possible#emph[, he thought as he led his horse along the river. With each step came the soft squish of soggy earth, yielding not water but a wretched slime that coated his boots. All that remained of the town's formidable walls were small pieces of masonry also coated in the same dark, sticky muck. Beyond the field of broken stonework lay an empty pit, as if the entire town, all at once, had been gouged out of the earth.]
#emph[Nausea hit him, roiling his insides like the churn of the thunderhead above, an apocalypse in repose. The next moments were a blur of shadow and wind as he wound through phantom streets imprinted onto his memory, all the way to the spot where the hovel where he and his family lived used to be.]
#emph[The place he once called home.]
#emph[Torens stood up and fetched the leather scroll case a courier had brought to him eight months before. He didn't have to open it to know who'd sent it, and he had not been inclined to read what the sender wanted to say. Until now.]
Torens,
Do you know how difficult it was to find you? I expect you do. But I did thanks to a friend whose sister is a Parish-Blade in Thraben. I never would have thought you a man of faith, but you've always managed to surprise me.
Mother is not doing well. She sunk into a melancholy after you left, but lately it has been far worse. She refuses to leave her bed, and it has been days since she has eaten. It would do her good to see you again. It would do me good, too. It is strange how you have found your belief, while recent times have robbed me of mine. Perhaps we could talk about that when we're together.
Send me word when you're on your way.
Your brother,
Elamon
#emph[The letter slipped from his fingers and dropped to the ground. The parchment turned a foul green upon contact with the muck, disintegrating within seconds.]
#emph["I'm here," Torens said to nobody.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
By the light of his mace, Torens and Eruth followed the incline of the floor to the lowest elevation in the keep, all the way to a second enclosed courtyard at the rear of the structure. No, not a courtyard—a graveyard, with ancient headstones overtaken by brambles and a gnarled tree at the center rising like a claw springing from the earth.
At the tree's foot were a pair of doors built into the crest of the hill. Heaving the doors open, Torens extended his mace in, revealing the macabre décor that lay beyond: human bones stacked like bricks, shoulder blades arranged into spiraling rosettes, skulls embedded into the wall as hollow-eyed sentinels—an ossuary, much like the ones in Thraben maintained by Devisers who infused the walls of tombs and chapels with protective magic.
Torens led the way. Soon, the bone-lined hallway narrowed into an undulating passage lined with glass vials, each held aloft by a careful arrangement of human finger bones. A tongue of azure fire burned within each vial, the flames containing fleeting images—faces, locations, events—like a ghostly phantasmagoria.
"What are these?" he asked Eruth.
"Memories," she said, peering closer. "Fear, horror, pain."
"How do you know?"
Eruth provided no answer. Torens's gut told him that he'd find out soon enough.
They pressed onward, the passage narrowing to single file before opening into a cavernous chamber dimly lit by rows of vials from floor to ceiling. The devils knelt before a taller figure standing on a dais at the far end of the room. They gurgled, as if in a trance. This had to be the leader, the master at the heart of everything that had gone on this night. A devil holding one of the vials pushed forward to the foot of the dais, where it threw the container onto the floor. A spout of blue flame spiraled upward, illuminating the master's face.
No. It couldn't be.
"Aleksandar?"
"That's not him," said Eruth. "It is only his body; there's something else in there with him."
Smoke rose from the shards curling around Aleksandar's shuddering body. With his eyes closed, Aleksandar twitched and spasmed, his fingers curling and his jaw clenching. A tear escaped his eye as he looked out and smiled once he met Torens's gaze.
"She is correct," said the gravelly, impossibly low voice escaping Aleksandar's lips. Torens had heard of entities that could possess bodies and minds—demons for sure, but certain spirits of the long dead as well. "You may call me Umbris." It took a step backward and motioned to the floor where a small, raised ring of metal etched with runes encircled its feet. Torens was no wizard, but he could hazard a guess as to what kind of magic was at play: a binding circle of cold iron preventing escape.
#figure(image("006_Survivors/03.jpg", width: 100%), caption: [Parasitic Grasp | Art by: <NAME>ai], supplement: none, numbering: none)
"Let him go," Torens commanded.
"No," said Umbris. "He is mine by right."
"What right?"
"By the terms of my binding set by the sorcerer Taivas more than a century ago. While the people of Traublassen slumber, I take their fears and sorrows so, come morning, they wake up refreshed and comfortable."
None of this made any sense to Torens. "For what purpose?"
"One is not ready for a hard day's work if preoccupied with sorrow or loss. It is easy for me to free them from the pain of their memories, to purge their pasts. Stability breeds docility, after all. In exchange, Taivas's lineage furnishes me with what I need."
"Victims," said Eruth.
"They are my tributes," Umbris fired back. "The full spectrum of pain can only be experienced through a living body, flesh and blood, which I do not possess myself. Take young Aleksandar. The anguish he felt at discovering the corpse of his young sister is~delectable. The heart races, the lungs constrict, the knees weaken, and the eyes burn. It is glorious. I've wanted to feel it since I first took her memory away from him. He's got many years of productivity in his future, the good lad."
#emph[Just the three of us] ~Aleksandar hadn't remembered his own sister or her death. Torens tightened the grip on his mace. "You had no right! I don't care about any damn agreement. You will let him go now!"
"Your fine weapon can most certainly injure this body, but it will do little to me or change our circumstances. What issue is my own enjoyment? I end suffering! Is that not a noble cause?"
"Don't believe anything it says," said Eruth.
"You are one to talk!" Umbris exclaimed. "Have you not wondered why I did not take you as tribute? Another has already claimed you, and I do not share. What honeyed promises did your Dark Lady make to take hold of your soul?"
"She saved me!" said Eruth. "When the whole Plane went mad, I would have, too, if she hadn't appeared. You are the liar!"
"One of us is lying." Umbris twisted Aleksandar's head at an unnatural angle to gawk back at Torens. "Has she told you of her dreams? The ones about you?"
Confused, Torens stepped away from Eruth. She had said that her dreams contained visions of the future. Had she seen his future? "Why didn't you say anything?" he asked her.
"It~was not the time."
"Then when?"
"She will not give you answers," said Umbris. "Her own fears remain elusive to my spying thanks to her unfortunate stowaway. But through her, I have seen all I need about #emph[you] . Such a tragedy—the fate of your town. And your dear brother, Elamon—"
"Don't you ever say his name again!" screamed Torens.
"What if I told you I can help you?"
"I'd say you can stuff it," Torens spat. "I don't care how powerful you are."
Umbris laughed. "Powerful? Power is a trap. You see Vytas as a prosperous man, a powerful man. Yet, since he was a child, his dreams have been consumed with being anyone but himself—Any other fate besides the legacy that Taivas had meted out for him. Trapped by Taivas, just as Taivas trapped me here. Vytas and I~we were brothers in suffering, and in time, we understood what a wonderful system Taivas had created. So elegant! We had something more precious than power or freedom—we had purpose! What is your purpose, Torens of Hanweir?"
Torens felt the strength in his arms waver, the resolve in his heart blink out of existence for a second before returning a bit weaker than before.
"Your pain," said Umbris. "You suppress it, yet it remains all-encompassing. You could have opened your brother's missive and returned home right away. But because of your ego, your vanity, you didn't. The faithless son~if only you could have seen as I do, with the eyes of belief, of conviction and clarity. #emph[I] would have seen the danger stalking Hanweir. #emph[I] would have made my family leave—no negotiation. #emph[I] would have saved them all instead of merely surviving."
"Don't listen," said Eruth, but her voice sounded distant and hollow. Because Umbris was right. Torens was a survivor—one who lived while others around him met grim ends.
"It is not too late for you, Torens," Umbris continued. "Allow me to take your pain away and give you purpose. Riches? Fame? Acclaim as the hero who vanquishes evil in the name of justice? All of that is there for the taking. Meanwhile, I will keep your secret safe and hidden, where no one will ever find it. Especially you."
"What's the catch?"
"Nothing. I have my tribute already. All you need to do is walk away." Umbris crouched down and whispered to one of the devils who disappeared in a wisp of smoke. "The door will be unlocked. Then you're free to go."
"Torens," said Eruth. "We are not gods. We are not demon lords or angels. We cannot shape the ends of divinity."
"I should have been there," he said. "Elamon~I just didn't want him to say he was right. I didn't want to hear a lecture on all the things I'd ever done wrong. Was that a good enough reason to turn my back on him? On all of them?"
"Destinies cannot be changed, only delayed or hastened," she said. "I know because I've tried—hundreds of times. I warn someone of danger, and another danger befalls them. I orchestrate events to prevent a situation, and the new arrangement proves even deadlier. No matter what I did, fate always won."
"So, what is my fate—the one that you dreamed about?"
"That's for you to decide," Eruth said.
"What the hell kind of answer is that?"
"One that changes nothing," said Umbris.
Torens muddled over his next course of action. To have Hanweir melt into inky oblivion—it wasn't anything he could have ever considered possible. What if Umbris was telling the truth? If it could rewrite the past in Torens's mind, would that open new paths for him? Or like Vytas's promised riches, was it a trap? He so wanted Elamon to be there to tell him the right thing to do. But his brother was gone. All Torens had was his instinct to survive, to find unorthodox ways to skirt out of impossible situations.
So that's what he went with.
"Tell me what you wish to do," said Umbris.
"I wish~you would shut the hell up." In a single motion, he strode forward, arcing the mace above his head and swinging down with the entire force of his body. He thought he saw an expression on Aleksandar's face of surprise, confusion, and most notably fear. Was it Aleksandar fighting past Umbris's thrall? Or was it Umbris's turn to fear for himself instead of basking in the fear of others?
Either way, Torens had made his choice. When the head of the mace met the binding circle, the impact sent a thunderclap pealing throughout the catacomb and bathed the room in intense blue light. When the light faded, Umbris stepped past the confines of the iron circle, the runes inscribed to keep it trapped no longer visible. One foot, then the other.
"This is unexpected," Umbris said.
Torens picked up his mace and settled into a battle stance, eyeing the devils who gathered around their newly freed master.
"Good. Because I have a proposal for you to consider."
"I'm~listening."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The shouts from the village square carried far up the hill. Shopkeepers, forgemasters, and farmhands brandished the tools of their trade as weapons against those whom they once swore fealty to. Vytas, in a robe of vibrant red and green, along with Boris and a handful of his hunters, were surrounded.
Torens turned away from the scene below. "I don't know about this."
"You did what you were destined to do," Eruth said. That was no reassurance. The position of judge and jury was never one that sat well with Torens, even if it could be argued that Vytas and those who came before him had signed their own family's death warrant.
"I'm leaving," he said. "There's unfinished business I have back in Gavony, some things to answer for. I can stop by Lambholt if you like."
Eruth shook her head. "I'm staying. These people will need guidance. The Dark Lady says that this is my chance for a new beginning."
"You're staying here? I'm sure a home-cooked meal would hit the spot."
"Lambholt is not my home anymore."
"But your family—"
"A few weeks back, before the hunters took me, I had a dream about my mother."
"And?"
"She was happy."
Climbing the hill toward them was Umbris in Aleksandar's body, a wide smile on his face.
"It is sweeter than I could have imagined," it said. "Visions of fear and pain do no justice compared to bearing physical witness." Umbris exuded a dark aura not perceptible in his underground prison. But out in the wild night, the effects of his presence were evident, from grass underfoot turning brown to the pervasive chill felt in its vicinity.
"Remember your end of our bargain," Torens said. He knew it wasn't wise to trust Umbris at his word. Nevertheless, it had fulfilled at least part of what it had promised. Down below in the ossuary, the devils were hard at work shattering the receptacles holding the townsfolk's memories collected over the years. Umbris himself would make sure all the people knew that Vytas and his ilk were responsible. #emph[For my own edification] , Umbris had said.
"It is time," said Umbris. "There is so much of this land I yearn to see."
#figure(image("006_Survivors/04.jpg", width: 100%), caption: [Umbris, Fear Manifest | Art by: Daarken], supplement: none, numbering: none)
"The next time we meet, I'm bringing you down," said Torens. "I promise you."
"We will have many tales to exchange on that day," it said. With one final grin, Umbris relinquished control of Aleksandar, who collapsed into Torens's arms.
"Sir?" he said weakly.
"I'm here," said Torens, embracing Aleksandar tightly as the boy's faculties returned. Aleksandar began to tremble and break down as Umbris's influence waned, his confusion giving way to the realization of his sister's existence and then her death. Torens steadfastly held on.
"I'm here," he repeated. He gazed downward at the mob in the village square. Calls for retribution and justice had boiled over into a desire for blood. One man picked up a stone and hurled it at Vytas. The old man managed to duck the rock, but he didn't dodge the next two. Torens closed his eyes and imagined another day, another time, another dream, to the chorus of stone hitting flesh, stone breaking bone.
"I'm here."
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/frackable/0.1.0/README.md | markdown | Apache License 2.0 | # The `frackable` Package
<div align="center">Version 0.1.0</div>
Provides a function, `frackable(numerator, denominator)`, to typeset vulgar fractions
```typ
#import "@preview/frackable:0.1.0": *
#frackable(1, 2)
#frackable(1, 3)
#frackable(9, 16)
#frackable(31, 32)
#frackable(0,"000")
```
![plot](./example.png)
|
https://github.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024 | https://raw.githubusercontent.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024/master/chap10/tree.typ | typst | #let tree(label, ..children) = style(styles => block(align(center, {
let label = rect(align(center + horizon)[#label])
let label_dim = measure(label, styles)
let children_widths = children.pos().map(x => measure(x, styles).width)
let all_children = stack(dir: ltr, spacing: 1em, ..children.pos())
let all_children_dim = measure(all_children, styles)
// If there are no children, stacking will result in excess space
if children.pos().len() == 0 {
label
} else {
stack(spacing: 1em, label, all_children)
}
// Draw lines
let label_bottom = (all_children_dim.width / 2, label_dim.height)
let x = 0em
let y = label_dim.height + 1em
for (i, child) in children.pos().enumerate() {
let child_dim = measure(child, styles)
let child_top = (x + child_dim.width / 2, y)
place(top + left, line(start: label_bottom, end: child_top))
x += child_dim.width + 1em
}
})))
|
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/themes/gallery/metropolis.md | markdown | # Metropolis theme
![metropolis](metropolis.png)
This theme is inspired by the
[Metropolis beamer theme](https://github.com/matze/mtheme),
created by <NAME>.
Use it via
```typ
#import "@preview/polylux:0.2.0": *
#import themes.metropolis: *
#show: metropolis-theme.with(...)
```
`metropolis` uses polylux' section handling, the regular `#outline()` will not work
properly, use `#metropolis-outline` instead.
## Options for initialisation
`metropolis-theme` accepts the following optional keyword arguments:
- `aspect-ratio`: the aspect ratio of the slides, either `"16-9"` or `"4-3"`,
default is `"16-9"`
- `footer`: text to display in the footer of every slide, default is `[]`
## Slide functions
`metropolis` provides the following custom slide functions:
```typ
#title-slide(...)
```
Creates a title slide where title and subtitle are separated by additional
information by a bright line.
Accepts the following keyword arguments:
- `title`: title of the presentation, default: `[]`
- `subtitle`: subtitle of the presentation, default: `none`
- `author`: author of presentation, can be arbitrary contet, default: `none`
- `date`: date of the presentation, default: `none`
- `extra`: some extra information, can be used for affiliation, instiution,
logos, etc., default: `none`
Does not accept additional content.
---
```typ
#slide(...)[
...
]
```
Decorates the provided content with a header containing the slide title and a
footer containing some custom text and the slide number.
Pass the slide title as a keyword argument `title` (default: `none`).
---
```typ
#focus-slide[
...
]
```
Draw attention with this variant where the content is displayed centered and text
is enlarged and bright.
Uses the background colour of the title on regular slides as the background
colour for the whole slide.
Not suitable for content that exceeds one page.
---
```typ
#new-section-slide(name)
```
Start a new section with the given `name` (string or content, positional argument).
Creates a slide with this name in the center, a progress bar indicating the
current progress of the presentation below, and nothing else.
Use `#metropolis-outline` to display all sections, similarly to how you would use
`#outline()` otherwise.
## Additional features
`metropolis` provides a further way to highlight text besids `#emph` and `#strong`,
namely `#alert` (as known from LaTex's beamer).
```typ
#alert[very important]
```
prints its content in a bright colour.
There is also `#metropolis-outline` which customises `#polylux-outline` and
displays a table of contents with all sections.
## Example code
The image at the top is created by the following code:
```typ
#import "@preview/polylux:0.2.0": *
{{#include metropolis.typ:3:}}
```
|
|
https://github.com/MrHedmad/kerblam-paper | https://raw.githubusercontent.com/MrHedmad/kerblam-paper/main/src/resources/acronyms.typ | typst | #let my_acronyms = (
// "SA": ("Some Acronym", "Some Acronym in plural form"),
// Leave the plural form empty to accept the default, e.g. ("Some Acronym")
// The default is to add an "s" to the singular form.
)
|
|
https://github.com/marcantoinem/CV | https://raw.githubusercontent.com/marcantoinem/CV/main/fr/awards.typ | typst | #import "../src/style.typ": experience
#let csgame2024 = {
experience(
"CS Games 2024",
"Montréal, Canada",
"Mars 2024",
"Première place globale",
[
- Participer à une compétition rassemblant plus de 300 étudiants de 20 universités à travers le Canada pour concourir dans divers défis en informatique.
- Choisir la délégation de Polytechnique Montréal à travers un examen de sélection couvrant plusieurs sujets de l'informatique tel que l'intelligence artificielle, l'algorithmique, la cybersécurité et l'intégration continue.
],
)
}
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1BC0.typ | typst | Apache License 2.0 | #let data = (
("BATAK LETTER A", "Lo", 0),
("BATAK LETTER SIMALUNGUN A", "Lo", 0),
("BATAK LETTER HA", "Lo", 0),
("BATAK LETTER SIMALUNGUN HA", "Lo", 0),
("BATAK LETTER MANDAILING HA", "Lo", 0),
("BATAK LETTER BA", "Lo", 0),
("BATAK LETTER KARO BA", "Lo", 0),
("BATAK LETTER PA", "Lo", 0),
("BATAK LETTER SIMALUNGUN PA", "Lo", 0),
("BATAK LETTER NA", "Lo", 0),
("BATAK LETTER MANDAILING NA", "Lo", 0),
("BATAK LETTER WA", "Lo", 0),
("BATAK LETTER SIMALUNGUN WA", "Lo", 0),
("BATAK LETTER PAKPAK WA", "Lo", 0),
("BATAK LETTER GA", "Lo", 0),
("BATAK LETTER SIMALUNGUN GA", "Lo", 0),
("BATAK LETTER JA", "Lo", 0),
("BATAK LETTER DA", "Lo", 0),
("BATAK LETTER RA", "Lo", 0),
("BATAK LETTER SIMALUNGUN RA", "Lo", 0),
("BATAK LETTER MA", "Lo", 0),
("BATAK LETTER SIMALUNGUN MA", "Lo", 0),
("BATAK LETTER SOUTHERN TA", "Lo", 0),
("BATAK LETTER NORTHERN TA", "Lo", 0),
("BATAK LETTER SA", "Lo", 0),
("BATAK LETTER SIMALUNGUN SA", "Lo", 0),
("BATAK LETTER MANDAILING SA", "Lo", 0),
("BATAK LETTER YA", "Lo", 0),
("BATAK LETTER SIMALUNGUN YA", "Lo", 0),
("BATAK LETTER NGA", "Lo", 0),
("BATAK LETTER LA", "Lo", 0),
("BATAK LETTER SIMALUNGUN LA", "Lo", 0),
("BATAK LETTER NYA", "Lo", 0),
("BATAK LETTER CA", "Lo", 0),
("BATAK LETTER NDA", "Lo", 0),
("BATAK LETTER MBA", "Lo", 0),
("BATAK LETTER I", "Lo", 0),
("BATAK LETTER U", "Lo", 0),
("BATAK SIGN TOMPI", "Mn", 7),
("BATAK VOWEL SIGN E", "Mc", 0),
("BATAK VOWEL SIGN PAKPAK E", "Mn", 0),
("BATAK VOWEL SIGN EE", "Mn", 0),
("BATAK VOWEL SIGN I", "Mc", 0),
("BATAK VOWEL SIGN KARO I", "Mc", 0),
("BATAK VOWEL SIGN O", "Mc", 0),
("BATAK VOWEL SIGN KARO O", "Mn", 0),
("BATAK VOWEL SIGN U", "Mc", 0),
("BATAK VOWEL SIGN U FOR SIMALUNGUN SA", "Mn", 0),
("BATAK CONSONANT SIGN NG", "Mn", 0),
("BATAK CONSONANT SIGN H", "Mn", 0),
("BATAK PANGOLAT", "Mc", 9),
("BATAK PANONGONAN", "Mc", 9),
(),
(),
(),
(),
(),
(),
(),
(),
("BATAK SYMBOL BINDU NA METEK", "Po", 0),
("BATAK SYMBOL BINDU PINARBORAS", "Po", 0),
("BATAK SYMBOL BINDU JUDUL", "Po", 0),
("BATAK SYMBOL BINDU PANGOLAT", "Po", 0),
)
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/044%20-%20Innistrad%3A%20Crimson%20Vow/004_The%20Blessing%20of%20Blood.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Blessing of Blood",
set_name: "Innistrad: Crimson Vow",
story_date: datetime(day: 05, month: 11, year: 2021),
author: "<NAME>",
doc
)
#emph[Dear Odric,]
#emph[The war is not over. Far from it. We thought the nightmares had been defeated, but something else has come, something far more powerful and evil. It's hard to explain. So much has happened. I will try to make sense of it for you as best I can.]
#emph[The vampires fought side by side with us. They wanted to save this Plane like we did. But I couldn't help thinking, "To what end?" To make slaves of us all? Food? But there was no time to think of the future, only the present. Only the present enemy that must be destroyed. We'll have to deal with them when this is all over.]
#emph[Among the fallen are the archangels, Bruna and Gisela, who were slain by their own sister and our last archangel—Sigarda. I cannot describe to you what this madness had truly done to them. They are gone now. And you are probably wondering why I have not mentioned Avacyn. She is dead, too.]
#emph[With the aid of Saint Traft, I was able to wield her divine spear and help defeat the first of the nightmares. But whatever it is that has followed. . .] #emph[it was strong enough to force the Saint out of me and leave me prey to the madness. I barely escaped with my life.]
#emph[Odric, you are the best of us, and we need you to lead us. We need your help to stop this. Before it is too late. I am on my way to you. And I will bring those cathars still loyal to the light with me.]
#emph[Please, do not forget who you are and have always been. We were all deceived at one time. I pray to see you soon.]
#emph[Your dearest friend,]
#emph[Thalia]
#figure(image("004_The Blessing of Blood/01.jpg", width: 100%), caption: [Thalia, Guardian of Thraben | Art by: <NAME>], supplement: none, numbering: none)
The priest shuddered as he finished reading Thalia's letter aloud to Odric. His voice was somber and echoed softly from the walls of the small Nearheath chapel Thalia and Grete had left Odric in.
Over the past several weeks, Odric had rarely wondered if they would ever return, if they would ever want to see him again. He instead spent the whole of his time on his knees before the altar of Avacyn, praying without ceasing for answers, tracing Avacyn's collar across his chest—shoulder to heart, shoulder to heart.
Regret gripped him like a vice. Thalia had warned him of the Lunarch Council's corruption, but he was too blind and too arrogant to believe her, despite always knowing demons were afoot. He traced his tear-drenched chest harder.
There were two attending monks who would often drape him in furs on the cold nights and kept the chapel fires burning. They brought him food and drink, most of which he did not take. But what he did consume without fail was holy water prayed over by the priest. It was promised to edify his blood and cleanse it, to make it unsavory for those who might want to steal it and bring ultimate protection against the darkness outside—demons and vampires alike. Unfortunately, the kindness gave him little comfort.
#emph["The angels are supposed to ] protect #emph[us!" ] The words Thalia spat at him before her exile struck like daggers to his heart. And try as he had to resist complete collapse, his will finally failed him. The dam of emotions broke. He wept and wailed uncontrollably, mourning the cathars he had killed in Thraben—those noble warriors he had reared himself and made worthy to defend the light. He anguished for the "sin-plagued" children he had allowed to be burned at the stake. He damned the souls of traitorous Bishops who so zealously consorted with demons. For weeks, he did this.
Then~
"It is true," came the grizzled voice of the priest the day Thalia's letter arrived. "The wards, Sir Odric~they have fallen, and I can no longer cast them as strongly." The groans he made were grave, as if the words were tearing at his throat as they escaped. Yet the air beneath them was thick with a sudden, ill resolution. "Avacyn~is dead. Madness has swept the land. All is lost. There is no more need for worship. No more need~for hope."
The revelation from him turned Odric's despair into unmitigated rage. He drew his sword, still glowing with angelic moonlight, and glared at the symbol of the angel emblazoned at the hilt. #emph["You—have—betrayed—us!"] A moment later, he found himself hacking the altar to pieces, destroying every holy plant, relic, and artifact in sight.
When he had concluded the assault, Odric lifted his head and looked back over his shoulder, just in time to see the kind priest exiting solemnly into the coming night. The man had removed his holy robes and dropped his blessed staff to the ground, leaving himself completely unprotected. Such incredible dangers lay just beyond these holy walls. Every priest and patron were keenly aware. And for a man of faith to enter the gaping maw of the damned naked and hopeless, all was truly lost indeed.
"Priest," Odric called out, "this house of Avacyn may have fallen, but we are still protected inside its walls." He waited for a response, but none came. "Priest! Come back inside! The sun is going down."
A small gasp came from a corner of the chapel. Odric turned to the noise to discover a middle-aged man, fearfully cradling his adolescent daughter, both seated in the last pew. Bewilderment and despair were awash on their emaciated faces after hearing the news and witnessing Odric's outburst. As was custom, the townsfolk would often come by to offer worship to the now dead angel or get a small meal. The poorest of them would even stay overnight, huddled in a corner near the fires. He had seen the two of them before.
"Do not worry," Odric spoke softly, staring into the child's fearful eyes. "You are still safe here. I will protect you~"
Suddenly, there came a scream. It echoed through the open chapel doors and snuffed out every candle in the sanctuary. It was followed by the sound of a wet gurgle from choking lungs, a cracking of bones, and the unsettling din of tearing flesh—then maniacal, unholy laughter.
#emph["Hide!"] he ordered urgently to the man and child. They immediately rose from the pew and ran into a closet near the back of the building.
The noises from outside rode in on the back of a heavy gray mist that, like a thick puddle, rolled in through the entrance and crept down the aisle toward the altar where Odric stood battle-ready, his eyes burning through the hanging, sweat-drenched tussle of white hair with its shock of raven black at his forehead. The mist halted its advance ahead of him but never dissipated. It simply lingered, undulating with strange intentions.
At that moment, the two monks rushed in from either side of Odric and beheld the destruction he had wreaked on the altar. "Sir Odric, we heard a scream—!" the first exclaimed, before falling to his knees at the sight. His voice quivered with fright and confusion. The second frantically began to gather what she could of Avacyn's broken symbols. "What have you done?!"
Odric did not look to them. He kept his focus on the churning mist. "Get back to your quarters," he said sternly, "and arm yourselves."
"Where is our priest?!" the second monk clamored. "He is our protection~!"
"He's gone!" Odric growled, raising his sword to the mist. Sounds of murder and destruction were growing outside. "Get back to your quarters and arm yourselves now!"
Suddenly, two ethereal, fog-made tentacles slithered out of the mist and enwrapped the ankles of the monks. They wrapped and unraveled along their arms, legs, and torsos, sweeping like elegant scarves over their flesh, and all at once, the monks became docile and entranced. Together, they pointed their fingers to the altar, and with emotionless tones, they spoke as one, answering a question the mist had silently asked them:
"The tears of Avacyn rest above the altar where they can drink the light of the moon, <NAME>."
#figure(image("004_The Blessing of Blood/02.jpg", width: 100%), caption: [Henrika, Infernal Seer | Art by: Billy Christian], supplement: none, numbering: none)
#emph[Henrika. ] Odric had heard this name once before. The name had been whispered in talks of how to quash the Skirsdag and other demon sympathizers—a futile endeavor he had come to understand, given the whole of Lunarch leadership would gladly lay prostrate before such fiendish demonlords. He remembered how Jerren, chief among the traitorous lot, became uneasy at her mention, gritted his teeth and tensed his shoulders. A wave of jealousy and reproach had washed over Jerren, knowing she was closer to them than he could ever hope to be.
#emph[Vampires consorting with demons. ] A truly diabolical combination.
A silver beam of moonlight appeared through a small window in the roof. It cut through the rising darkness like a spear and struck a shattered ceremonial mirror perched upon the altar, sending several beams of light refracting against the walls and Odric's blade. Odric raised his sword behind him to capture the true form of the enemy now standing with him in its reflection. There he saw her hooded, feminine silhouette, her arms outstretched to the monks, playing them like puppets on invisible strings.
Avacyn's tears were a precious commodity in the church, if not all of Innistrad. While followers of the faith were usually anointed on their foreheads with holy water, on special occasions, some were anointed with her divine drops. Infused with the power of the soft light, Avacyn's tears enhanced their spells, healed their wounds after battle, and bolstered their reach into the spirit realms. Odric snarled. If such a villain as Henrika wanted them—the demon she served, moreover—she must intend to debase them somehow.
At once, Odric turned his sword at a sharp angle, bending the moonlight in Henrika's direction, shining the new beam upon the floor. Her mist swirled and parted immediately to avoid it, retreating beneath the wooden pews like snakes into their hollows.
The enchantment that held the monks fell away at that moment, and they came back to themselves. Dazed and frightened, they looked to one another, then to Odric.
"You've been glamered!" Odric shouted. "Now do as I say! Get to safety!"
Without rebuttal or hesitation, the monks rushed into the darkness of the entrances from which they came. The moment they disappeared, however, the heavy thuds of two bodies hitting the floor boomed from the doorways.
Odric grimaced at the sounds. He had been taught to be prepared for the unexpected, and what was coming was definitely that. Footsteps on the roof, skulking about the perimeter of the chapel, even the strident whistle of blades cutting the air should have alerted him that other cathars were present. In fact, it was he who taught them to move in silence; trained them to go unnoticed by the enemy when the situation called for it. But he was so distracted by his grief and the sudden arrival of this Henrika that his guard was momentarily lowered.
He whipped around, bending the light with him and sending it into the darkened door. The beam landed upon two soldiers, both wiping the monks' blood from their shimmering blades. Odric beheld them with surprise, as they stepped forward. Their faces were like stone with eyes flashing, without remorse for those they had just slain. #emph[Cathars murdering the innocent. . .and clergymen no less? ] Avacyn's madness had spread a greater distance than he thought.
What further caught his eye was that each one was missing a hand—or rather, their left hands had been replaced by the decaying bones of dead ones.
"Brother? Sister?" Odric asked through grinding teeth. "What have you done to yourselves?"
"They've been marked by the divine," came a gloating female voice—Henrika's clever voice—undulating with the rolling of the mist. "Hearing that their precious angel was dead, they practically lost their will to live. How pitiful they felt knowing they had wasted their best years on the good lie."
The mist receded into a swirling ball, then rose into the air, coming to form in the shape of a very tall, very thin woman in a cascading gown. Henrika's lips parted as she smiled, revealing the sharpened fangs behind them. The cathars raised their swords in Odric's direction, as she went on. "Cathars, such mindless sheep—always in need of purpose, some master to prove their worth to. Well, they have found a new one and been reborn through self-sacrifice. Ormendahl is their angel now."
Her last words released the dogs from their cages, and the two cathars rushed Odric, one attacking high and the other low. This was a typical method of these oath-traitors—two against one, a rather dishonorable tactic in Odric's opinion—but one he had grown to expect from their lot. He deftly cartwheeled in place, as their blades passed over and under him, then returned their advances with his own aggressive flurry that, between his near impossible dodges and blocks, lacerated limbs, scored faces, and shattered bone. Blood ran in rivers over Avacyn's shattered mementos.
Henrika's vile laughter echoed from the walls. She applauded the display, encouraging newcomers to join her revelry. For in the ten or so windows of the chapel, the dark silhouettes of more cathars, each one clad in their holy armor with their unholy afflictions on display, loomed over the scene, looking down upon their defamed leader. Odric beheld them with shame and disbelief. So many of them had fallen victim to Henrika's influence and her demon's will. He eyed her with murderous intent.
"Fascinating," smiled Henrika, "a natural-born killer with an unnatural sense of honor. To humans, too. What they've said about you, Sir Odric—the legends. They prove absolutely true."
"Then you know already that you will never leave with those tears," Odric growled, aiming his blood-drenched sword in her direction.
"#emph[Leave?] " Henrika chuckled. She spun around gleefully, allowing her golden gown to dance in wild circles. "No. They are going to stay right here in this fine house of worship where they belong. Though I'd hardly call it #emph[fine ] myself. I have a mansion with thirty rooms, drenched in silken cloths, hewn out of marble, and an army of familiars to do my bidding." She shrugged playfully. "But demons, like angels, are gluttons for ceremony."
"Ceremony?" Odric whispered, slowly piecing the clues together of her end goal. "An anointing?"
Henrika smiled, rolling her eyes coyly, before she answered, "Perhaps."
#figure(image("004_The Blessing of Blood/03.jpg", width: 100%), caption: [Vampire's Vengeance | Art by: <NAME>], supplement: none, numbering: none)
He observed with keen eyes this nonchalance she exuded. He had been trained to read the enemy. Henrika was one who could care less about the mission she had been tasked with, like a whimsical child who took joy in distractions from her nightly chores. Moreover, the way she spoke of her master's aims proved she held the demon in no real esteem. The attack on the chapel was only~
"A means to an end," said Odric. "That is why you and your horde of dogs have come here."
"#emph[Domnathi ] is what we prefer to be called~"
"Never heard of you," Odric spat at her. "Yours must be one of those inferior bloodlines." The ever-present smile left Henrika's face for a moment. His tactic had worked as he knew it would. #emph[That is what she wants. ] He surmised immediately. #emph[What all minor vampire houses want—Supremacy.]
"#emph[Inferior] is a word that denotes weakness and stupidity, cathar." She allowed her tongue to linger on her lips after her last rebuttal. "We kill the weak and stupid~"
"But spare the strong and willing." Odric stepped forward, another tactic in mind—#emph[make her feel small and the whole truth will expose itself.] "So that they can be soldiers in #emph[his] army." There was a stirring among the cathars in the windows as he approached her. "But you're not their leader as you seem to boast. These damned men and women are not marked for you. They are not familiars you can control. You are simply an errand girl~"
"I am a dealmaker," she hissed back at him, glaring at the remark. Her claws gave a shrill ting as they flexed.
"Dealmaker? What kind of deal would a demon and a vampire make?"
"One of blood," came another voice from the entrance—a sad, familiar voice.
At the chapel doors stood the kind priest once again. The moonlight showed his face beaten and bruised, his bare limbs torn and bleeding. He hobbled forward, his right leg broken in several places, but he did not even wince from the pain. His skin was pale from a massive loss of blood—not just from injury but from the kiss of a vampire—a neck riddled with fang marks.
"For our loyalty," the priest continued, "the liege of darkness will offer up his divine blood~"
"Hush now," Henrika whispered to him, smiling at Odric. The priest fell silent. His eyes were empty and fixed upon the pool of tears above the altar. The mist swirled gently around him. "Grief-stricken men are always such loquacious creatures, aren't they?" she continued. "Strong helpers, though."
It is then that Odric noticed the grinning, giggling devil cradled in the priest's frail arms. Like a rabid dog, it was gnawing at the bones of a dead human hand—a hand now fixed to the priest's bleeding wrist. Each bite caused his fingers to flex and wriggle.
"Though your angel is dead, there is still power in the tears," Henrika spoke. "That power needs direction and vessels to wield it. Demons need priests, too—priests that must be anointed into their unholy order. He will be our first."
"Stop, priest!" Odric threatened, cutting the air with his sword. The priest continued his procession.
"You would kill an innocent?" asked Henrika coolly. "The smallest flick of a finger would probably kill him, you know. Would you want another stain on your conscience, Sir Odric? After all those poor children you let burn?"
The sound of blades erupting from their sheaths rang out from behind him in the darkened doorways. The turncoat cathars were readying their attack. Odric counted twenty spread about the perimeter of the chapel—at the windows, at the entrance, at the doorways—not to mention the glamered priest and his devil.
"No," Henrika started again. "You have a higher calling—a new master to serve."
Odric again caught the reflection of the moon in his sword and was suddenly stirred by something Thalia had told him. "I serve the soft light of the moon," he started, "the moon that holds back the terrors of the night. I serve the holiness humanity aspires to~!"
"Long-winded cathars," Henricka sneered. "This is a war the terrors will win!"
Then she dissolved into the gray mist and spread to the corners of the sanctuary, pushing the pews to the walls as she moved, as if preparing an arena for them to duel. At the same time others appeared—an audience of Domnathi vampires, peering with glowing eyes from the doorway, window, and hole in the roof. The sounds of their amusement filled the air.
At her last words, the footsteps began to pound and rush. Two of them, their arms raised, moved to pounce upon him, when a dark shadow broke the beam of moonlight. The muffled sounds of a violent skirmish rumbled through the roof, and not an instant later did it give way, sending glass, wood, and a pummeled cathar plummeting directly on top of one of Odric's assailants. Thalia came down along with her and landed hard, both boots flat on the dead cathar's chest. The sounds of bones crushing terminated the clash.
Thalia stood tall as she extracted her blood-drenched sword from the dead bodies. She turned to Odric, her head of long golden hair waving in the night wind. Odric turned to her as well, pulling his sword from the third cathar's belly.
"Hello, old friend," she smiled, and Odric smiled back, feeling an anxious quickening in his heart. Emotion rose in his throat and charged through his limbs. He wanted to reach and hug her tight in that moment, to know that she was truly real. He was grateful she was still alive; grateful she had not succumbed to the wiles of demons; but more than anything, he was grateful at the chance to finally redeem himself for all the horrors he had allowed to pass in his time at Thraben.
Their salutation lasted only a moment, as the shattering glass of the chapel windows heralded a new onslaught of cathars. Thalia rolled out of the way, avoiding more falling shards and the slash of the enemy's sword, while Odric caught the blow with his own blade. He then suffered the brute with a blow to the nose that ended him. Several others had entered after the first but did not fight right away. They ransacked the chapel, snatching every piece of silver from the walls and throwing them outside through the windows and door.
With mighty swings of her sword and the deftest aerobatics, Thalia slashed open cathars' arms and legs, letting her momentum take her spinning over her shoulder to finish off several more. Odric shattered the skull of three with his fists, crushed the ribcages of several who had fallen at his feet. His killing sword sent reams of blood flying against the walls and floor and suffused the chapel with a kaleidoscope of moonlight from its polished silver. Back to back, the two comrades battled without mercy until the last cathars had fallen. Through it all, the priest continued his slow march.
"Protect our dear priest," Henrika's voice sang over the collapsing of bodies and clanging of swords. "Clergies are kept by dead men."
As if it were a rallying call, her words triggered an onslaught of at least twenty Domnathi vampires, who swooped into the chapel from all sides. Like a swarm of hungry rats, they overran the two weary fighters, sinking their fangs into flesh and drinking their fill. Odric and Thalia struggled to fend them off—Odric able to tear out the throats of two, Thalia able to gouge out an eye and stomp one's head in—but there were too many. Soon they were disarmed, overwhelmed, and held at the mercy of Henrika's minions.
Henrika came to full form again. Her eyelids and cheeks were stained in red, painted in the blood of one of her hapless victims. In her presence, the vampires halted their feed, though they kept their nails and fangs sunk deep in their prey's flesh.
"How valiant," she jeered, giving a soft clap. "A fine effort by the both of you. You managed to kill some forty of your weaker kinsmen in one fell swoop and at the same time provide me two of the strongest cathars there ever were~"
She looked at the priest, who was now standing at the altar, holding the devil out over the pool. A wink of her eye prompted one of her subjects to proffer the priest a dagger.
From there, the priest sank the blade into the devil's belly and, pulling upward, tore the creature in two. Black blood, thick as oil, gushed out of the forlorn creature and into the pool, where the liquid sizzled and smoked. As it did, the priest began to mumble a prayer in a tongue Odric had never heard. His voice became deep and gnarled like the growl of a dying bear. And suddenly, the swirling mixture of damned blood and divine tears became cloudy, then turned a shade of deep crimson. As it did, the darkened visage of a horned beast beneath the liquid came into view—an essence of the demon.
"Ah, the blood of demons," Henrika smiled, approaching Odric. "It is immeasurable in its power, when wielded in the right veins. It takes away fear, empathy, doubt. With his blood anointing, you could do a great many wicked, wicked things."
Out of the mist suddenly appeared the father from the pew and his daughter. Both walked as the priest did before—their steps slow and mechanical, their eyes glazed and listless. Both glamered. Henrika's manicured nails—black and sharp, the claws of an aged feline—extended with a strident hiss. The orders already fixed in his mind, the father approached his captor and lifted his chin to her.
"Will you serve?" Henrika asked, directing her question to Thalia.
"<NAME>!" shouted Thalia. "Lady of Lurenbraum, progenitor of the Voldaren line, made a pact on behalf of all vampires on Innistrad. She agreed—she #emph[promised] —no vampire bite or blade would draw human blood until the war was over. She and the other vampires are still fighting out there. All other bloodlines are fighting so that this Plane can survive. You #emph[must] honor that!"
"Unless that demon blood took all sense of honor, too," Odric added fiercely.
Henrika's eyes narrowed on Odric so sharply that she could have torn away his flesh with her stare. "I don't believe, Sir Odric, we #emph[inferior] bloodlines were included in their lot~"
Without the slightest hesitation, Henrika slit the throat of the father. His body crumpled like a fumbled sack of wheat, his blood spilling out beneath him. Three eager Domnathi vampires, who stood patiently observing nearby, reverted to wild beasts and began to devour him.
Unmoved by the display, the young girl approached. She lifted her chin just as her father had done.
"Damn you!" Odric shouted. "Leave the child alone! She means nothing to you!"
"But she means something to you, does she not, #emph[human] ?" She extended her finger and brought it to the girl's throat.
"Take me!" ordered Odric through clinched teeth. "Let Thalia and the girl go. You can have me."
"Oh, I will have you, commander~" smiled Henrika, her eyes flashing, "I will have you for my very own. But Ormendahl needs his cathar army replenished now that you've slaughtered them. Therefore, I ask again~
With great force one of the Domnathi vampires thrust Thalia's arm out to Henrika. Her fist clenched and trembled as she tried to resist them.
"Will you serve?"
Thalia turned to Odric, tears in her eyes from the pain of this moment and the pain surging through her weakening body. "I serve~" she began. "I serve~" In that moment her face turned defiant. "I serve the soft light of the moon that holds back the terrors of the night. They will be avenged, I swear it. I will bring them to the Blessed Rest, and I will watch you burn!"
At the exact moment Henrika's finger began to bend, the voice of the priest, deep and delighted, snaked in. "Bring the girl to the altar."
Odric's eyes widened with horror as he turned to behold the priest, who now stood tall, his wounds mended and spirit lifted. His eyes were like polished black stone, and new lines were drawn in the devil's blood upon his forehead.
"Our lord yearns to baptize his first disciple," he announced with cheerful vigor.
Henrika straightened. Her claws retracted.
"Hmm. To the altar, dear," she sighed, almost disappointed.
The girl obeyed, passing through Odric and Thalia, traipsing through the puddles of her father's blood, and went to stand at the priest's side. Thalia watched in horror after her, but Odric kept his eyes fixed on Henrika, knowing that she was not satisfied; she would have the answer she wanted. And he was right: in the moments it took the child to move, Henrika had picked up Thalia's sword and raised it, prepared to strike a devastating blow to her wrist.
In a final attempt to prolong what now seemed inevitable, Odric gave a scream and erupted from the fanged shackles of the vampire horde. He leaped in front of the sword moments before it was to take Thalia's hand and accepted the full force of the attack across his chest. Blood spurted and spilled out of him like a fountain.
#figure(image("004_The Blessing of Blood/04.jpg", width: 100%), caption: [Hero's Downfall | Art by: <NAME>], supplement: none, numbering: none)
"Honorable to the very last!" Henrika guffawed, surprised at Odric's final attempt.
The other vampires joined her revelry; all except for one who stumbled away from the group, clutching at his collar. He was the smallest of them—a thin, handsome creature with long, wavy hair. He turned to Henrika, looking paler than he had before.
"<NAME>," he whispered, choking, barely able to speak. "I don't feel so~" But she was distracted, all her attention on her victim.
Odric, coughing and spitting, stared into Thalia's eyes, as the last bit of life within him drained away.
"Odric, no," Thalia cried, watching him quickly succumb to the blow. "Don't die! Don't you die on me! We have a Plane to save!"
"No, no, no," Henrika sneered, lifting Odric's chin. "A quick death would be a mercy. I've got one better."
At once, three of the surrounding vampires moved into action: one restraining Odric's arms, another grasping a fist full of his hair and forcing his head back, and a third who crushed his cheeks together and pulled his head to the side to expose the beating vein that ran the side of his neck. The loss of so much blood made Odric weak, and he could not resist them.
"You shall serve a master," Henrika hummed. "And that master will be me."
With her nail, she made a deep cut in her tongue. Blood flowed thick and red over her lips, and with a quickness, she descended upon him, biting into his neck, allowing the cursed blood within her to putrefy his own. Immediately, he felt the cruel poison take hold—the beat of his heart slowing and the thirst for blood rising. He beheld the light of the full moon, glowing upon him through the hole in the roof. Again, Thalia's words rang in his head as he struggled to keep any part of him that was human, any part that was moral and good, alive. Then the moon became awash in blood red as the rest of the Plane did~but not only from his cruel transformation, but from something else~
"<NAME>!" came a cry for across the room, and all eyes turned in its direction. The pale Domnathi who had left the group was now standing in the middle of the room. Black veins were snaking up his neck like vines and had marred his face. His skin was smoking, charring in places, as if he were burning from the inside. #emph["Something is. . .something is wro—!"]
Before the last word could escape, his body burst open, his insides erupting out of him in a thick plume of boiling blood.
A chain reaction of chaos followed, as the bodies of the other Domnathi began to boil and explode around him. The vampires that had held him and Thalia were each ripped apart from the inside out, sending waves of blood and dead flesh crashing against the walls and floor. Henrika herself was drenched in their remains. And like them, her skin too began to boil and burn.
#emph["Blessed water—?!" ] she screamed in disbelief. #emph["There is blessed water in your blood—?!"] The revelation was cut short, as the point of a thin sword speared her through the side.
Looking over her shoulder in horror, Henrika beheld Thalia, staring up at her, eyes fierce and determined. Her gaze was then torn away by a warrior's cry and met the eyes of the one who would end her. Odric was now charging through the air, eyes glowing the color of two crimson suns, fangs flashing, and the sword of Avacyn glowing brighter than ever before.
#figure(image("004_The Blessing of Blood/05.jpg", width: 100%), caption: [Odric, Blood-Cursed | Art by: <NAME>], supplement: none, numbering: none)
"This—is not—over," Henrika screeched as she turned to swirling mist and escaped through the chapel doors.
The sword of Avacyn passed through the haze and hit its mark. Odric, in his new vampiric form, landed hard on the floor and shook the chapel to its foundation. The momentum of his swing did not halt. He launched his sword straight at the altar, where the priest was readying to submerge the girl beneath the unholy waters.
The blade severed the priest's head and lodged in the bowl of the pool. Fissures sprouted along the stone basin like spiderwebs, and through them, the cursed tears of Avacyn, Ormendahl's vile ablution, spilled onto the floor. Before it could touch the child, Thalia scooped her up in her arms and made their retreat to the chapel doors. Odric moved after them.
The pool burst open. A deafening roar like thunder chased after them, erupting from the great wave of devil's blood. Ormendahl's horns, his fiendish skeletal visage, and his dragon-like claws, all of them laced with dripping crimson, rose out of the flood to catch them. But the demon's terrible form could not be sustained. Just before reaching the toes of the cathar's boots, the flow ceased, and the agonized demon, still reeling from his defeat, sank back into oblivion.
Thalia and Odric stood in silence for a long moment, surveying the devastating scene. Then, Thalia turned to Odric, whose eyes were already on her and the child. She clutched the girl tightly to her, even turned her shoulder away from him to shield her from Odric's gaze. Odric breathed deeply, struggling to accept what he had now become; hoping that his friend would somehow accept him, too.
"Can you—see the moon?" Thalia asked softly.
Odric understood her meaning. Vampires could not cross running water that reflects the light of the moon, and looking into it would be a testament to how much Henrika's poison had penetrated his heart. He stared up through the hole in the roof. But where he had expected pain and trepidation, he felt~peace. Utter peace.
Slowly he made his way across the blood-laden sanctuary and pried his sword from the bowl of the pool. It flashed angelically in the moonlight as if still blessed by some higher power. The blade, turned flat in front of him, held his reflection. In it he saw his blackened vampiric eyes but found no monster staring back at him; no woeful abomination. He simply saw himself as a younger man—a cathar full of great ideals and morals, a champion of man, a righteous protector of the soft light.
He looked back to Thalia.
"Yes, I can see it."
She nodded back.
They stood together in solidarity, both cathars and something other, perhaps something more; each one of them knowing that this would be the beginning of a new chapter in the war to save Innistrad. A terrifying adventure lay ahead.
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/025%20-%20Eternal%20Masters/001_The%20Prodigal%20Sorcerers.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Prodigal Sorcerers",
set_name: "Eternal Masters",
story_date: datetime(day: 25, month: 05, year: 2016),
author: "<NAME>",
doc
)
#figure(image("001_The Prodigal Sorcerers/01.png", height: 40%), caption: [], supplement: none, numbering: none)
The cannonball missed him by inches.
Guttural screams wailed over the ringing in his ears as the projectile splintered the foremast with a deafening roar. Still, past the panic of the desperate crew, past the pounding in his head and racing of his heart, Boldt held his ground. This was his chance.
Through the chaos and directly ahead of him, two corsairs were bearing down fast on his smaller passage ship. The only weapons in reach were clutched in his shaking hands: notes, from countless hours of study. And the bronze figurine of a sextant, his reward from an instructor, in hopes of great things to come. All for now.
He held the sextant outward as a focus, its curves and angles framing the corsairs like sights on a crossbow.
#figure(image("001_The Prodigal Sorcerers/02.jpg", width: 100%), caption: [Prodigal Sorcerer | Art by Eric Deschamps], supplement: none, numbering: none)
#emph[Deep breath. In control. Say the words. Clear the—]
"Hullbreachers!" the captain shouted, her hair matted in blood. "Hard to port! Make ready the—"
Cut off abruptly, she and several others vanished into a thick cloud of shrapnel as the world collapsed around him.
#emph[Don't look there, look up. See it.]
He raised his voice above the din and spoke from his notes a statement of power—the words practiced, rehearsed a thousand times.
#emph["Ashkara nix pulu..." ] The focus began to glow softly in his hand, his adrenaline rising with each perfected syllable.#emph[ "Sarko mar benosk..." ] Next an orchestrated gesture, like a grand symphonic conductor. #emph["Kahuga Duru..."] Now, resolution.#emph[ "Tanare!"]
Instantly, a wave of distortion burst from the young man and crested over the water, an immense crack across glass, jaggedly tracking towards the enemy vessel. His eyes widened with expectation, acuteness through anxiety, waiting for impact.
But as quickly as the spell sprang to life, it fizzled, uselessly impotent against the hull of the corsair. A failure.
From the pirates, a double boom sounded—a heartbeat of iron and thunder. In an instant, he saw them: two cannonballs linked by a chain of crackling energy, spinning around each other like a bolo, so fast he could barely make them out. What make of magic was #emph[this] ?
With blinding speed, they whirled overhead to cleave the mainmast like a seared twig. Mast, rigging, and crew came crashing down into the sterncastle and through the deck, bringing several screams to a sickening halt. Nothing but haze and silence followed.
And <NAME>, master apprentice and aspirant elite, first son and heir to the Duchy of Kelsh, schooled in the art by Archmage Ghavos, now crumbled to his knees in utter defeat.
All was quiet, muffled like his family's courtyard after a heavy snow.
"You should have finished me, dogs!" spat an unseen, gravelly voice.
From below deck and through the smoke, an old man emerged, a silver beard partially hiding the scar along his jaw. Boldt had seen him before. He'd noticed his gold and black tunic, once regal, since grown threadbare and muted—and now torn from battle.
#figure(image("001_The Prodigal Sorcerers/03.jpg", width: 100%), caption: [Prodigal Sorcerer | Art by <NAME>], supplement: none, numbering: none)
What was his name...Enthril? Yes, the ship mage. A deckhand for custodial spellcraft, mending fabric and superficial wounds. But there was nothing superficial about the man's bloodied face and injured bearing.
Enthril muttered a curse under his breath, squinted against the charred fog, and held up an empty, outstretched hand. As the wind kicked up behind it, he swept his arm across the waves.
The sea sprang to respond, following the motion and rippling with energy similar to Boldt's, but more powerful, confident. A coursing swell, formidable enough to catch the first ship upright, forcefully spun it across the waves and into its brother with a clash of creaking timber.
The two corsairs, lanced and entangled, ceased fire. Boldt could hear the pirates bellowing at each other, trying to make sense of it.
Enthril, for his part, spent the moment catching his breath.
"That'll hold 'em for now," he decided, then turned to notice the young man. "You there! Snap to!"
Boldt looked off into the distance, the words faded to mist. The old man limped across the deck to approach him.
"'#emph[Snap to] ' means get off your ass and help me before we sink."
"But the crew—"
"We're the crew now. All that's left."
Boldt looked up, jarred from his trance. Were they really the only ones left alive?
"We need to sound the ship, right what we can. Anything that keeps us breathing air instead of ocean."
"Wait. How did you do that?"
Enthril wiped some blood from the bridge of his nose.
"With the power of my good looks. Let's get to work."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Below deck, the pungent smell of hemp fiber and pine tar filled Boldt's nostrils. A wooden caulking mallet sat unused at his feet as he employed a binding spell, a complex one of his own design, against seams in the hull.
He was thankful for the sharp smell of the caulk, as the funk of burnt flesh that hung in the air threatened to break his composure. Salt water had nearly filled the forehold, carrying the submerged bodies of the drowned. With each sway, they smacked relentlessly against the bulkhead.
"To task," Boldt reminded himself. "To task..." He resumed his spell.
Enthril soon joined him, carrying an armful of splintered wood.
"So I found out why the tiller isn't working," said the old man.
"Why not?"
"It's gone."
Boldt's face fell.
Casting aside the wood, the elder mage winced as he favored his right side, just above the hip. Boldt could see blood soaked through the old fabric of his tunic.
"Do you need—?"
Enthril shook his head. "I'm fine. Smart bastards. Waited until the last second to show their colors, #emph[Talas] colors, and surprise. And with that, my curiosity with regards to their fancy new weaponry is permanently satisfied."
The old man stepped forward to look closer at the apprentice's handiwork.
"So we shore up the midhold here..." Enthril indicated a marred patch of the chamber wall. "...and we can isolate the flooding. That'll buy us time. But we have a bad problem and a worse problem. The bad one we're dealing with. The worse..."
"The worse being the pirates? That you drove off with a wave of your hand? I thought you were just—"
"Just a humble ship mage? Your pristine pre-academy training tell you that?"
Boldt narrowed his eyes. "How did you know?"
"You booked passage for the Spice Isles, and vastly overpaid. Doubtless the pride of a noble family, with no reason to tread these waters unless you're bound for Tolaria West, to the institute there. Very prestigious. Congratulations."
#figure(image("001_The Prodigal Sorcerers/04.jpg", width: 100%), caption: [Academy at Tolaria West | Art by James Paick], supplement: none, numbering: none)
The younger man bristled slightly at this. "So you've heard of it."
The old mage nodded toward a gold signet ring on his right hand, bearing the symbol of the all-seeing eye.
"Graduated top honors."
"And you ended up here?"
Enthril grabbed an iron trowel, coated the end with the caulk at Boldt's feet, and spread it across the spot his spell had missed.
"Lad, just use the damned mallet. You make things too complicated."
Boldt picked up the tool and ran fresh tar across it.
"You think I'm afraid of a little work?" He ran oakum along the boards, echoing Enthril's movement. "You don't know what I've given up. I've spent years training to study with the great minds of our age. I have plans, and they don't include ending up a skeleton at the bottom of the sea."
"Plans..." Enthril paused a moment to consider, then pressed forward. "I've been watching you these past few weeks, with your books and notes...."
"That's right," affirmed Boldt, with no small amount of pride. "Books and notes. The road to greatness, as true as brick and mortar. That's why the academy sent for me."
"And what would you learn there?"
"All of it: morphology, control, illusion...."
"Control #emph[is] the illusion."
The young man turned away from the bulkhead and looked Enthril square in the eye.
"What do you mean?"
"Boldt..." the old man began, with the slight edge that reminded the young apprentice that he'd never actually introduced himself to the ship mage—or any of the crew, for that matter. "That's all I wanted to do. Control the results, control the outcome. I left as an academy graduate, confident I'd be a great master and find my fortune—#emph[take] my fortune. But all this ambition, all this mastery, in the face of true wisdom? It's like trying to tie waves against the beach."
If there was any regret in Enthril's eyes, he didn't let it show. He continued working the seams of the hull.
"Out here, I've learned to let subside my thirst for power and glory. To see myself as a conduit, a steward for something greater than myself. A #emph[custodian] ." He held up his trowel, covered in black tar, to punctuate the thought. "And I've learned you can know the heart of something without having to possess it."
Suddenly, a distant explosion echoed throughout the cabin, bringing the lesson to an abrupt end. Enthril dropped the trowel to the floor.
"Topside. Now."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The two mages emerged from the hold, squinting against the bright sun at their bearings. The pirates had broken free from constraint, and now closed within range of their guns—and they were joined by others.
"Four sails on the water," Enthril noted. He turned to the downed mast, its jumble of torn sails and rigging billowing from a strong wind. "And the sheets, what's left of 'em, are catching. That's what I was afraid of. We're winding east."
"But that's away from the pirates, right?"
Another blast of cannon fire detonated to starboard. Closer this time, reverberating across the deck. The old mage drew a broken scimitar from the rubble and gave it to Boldt, who eyed it warily.
"I'll keep 'em busy," said Enthril. "You take this."
"I'm fighting them with #emph[this] ?"
"You're freeing us with that. Cut the lines to the mainsail, those ones there. No spells, save your energy. Go!"
As Enthril drew himself up to face the pirates, Boldt approached the shred of mainsail, surveying the ropes and fabric as he trod across a stump of broken mast. Looking over his shoulder, he could see Enthril spreading his arms, palms down as if gliding with the wind, eyes locked dead on the advancing ships.
Beneath them, the deck moved up and back with the ocean. Enthril's stance rolled with the sway, a loose echo of it, in anticipation. Boldt inched closer to the tangled, chaotic helix of hitches and knots, raising the jagged chunk of blade in the air.
A blast roared from the corsair. Mastcutters incoming, spinning toward them like lightning hewn from stone. Moving with the deck, Enthril quickly brought his arms up, as if hailing the sky.
With a thunderous clang, the heavy irons struck an unseen force at a shallow breadth before the bow. The point of impact rippled in shimmering light as they ricocheted against it, splashing down harmlessly a hundred feet away.
From his perch, Boldt could see Enthril stagger and fall to his knees, the energy dissipating around him.
"Enthril?" he called out.
"Get on with it!" the old man sputtered.
Boldt cut through weathered ropes and rigging, bringing the blade down again and again until the tattered sail pulled itself free. Both mages lurched forward as their ship tilted back against the wind, slowing and forcing them prone against the rush of ships.
The young mage dropped the broken blade and scrambled from his perch toward Enthril. The old man, nearly depleted, could do no more than nod at him and point forward, turning Boldt's attention to the corsairs as the youngster took his place in front.
Boldt peered at the closing ships. What could he possibly do?
Still recovering his strength, Enthril looked up at his new apprentice. "Welcome...to the real academy, lad."
Inspiration struck Boldt like a charge of adrenaline. He dove into his satchel, rummaging through it as the deck pitched and rose beneath his feet.
Wellspring magic. The underlying material of things. Properly managed, he could command the very waves, bring forth a squall from his hand, attack or defend any number of ways. He'd analyzed it for years. But could he manifest it now?
Boldt searched through a leather-bound book, checked a verse, and stowed it back into the satchel. Scraps of loose notes fell away as he retrieved the bronze focus.
Another blast erupted off the port bow, mere feet away. Too close. Boldt clung to the bulwark, righting himself against the rocking ship.
What were the words again? #emph[Avenkari ] was the root. He knew it, what was it?
Sweat forming on his brow, Boldt raised the focus to frame the nearest ship. Sights on a crossbow. A faint glow appeared on the sextant as he began to speak, wavering and uncertain.
"#emph[Avenkari katala nahota...] "
A hand blocked his sight as Enthril, now standing, gently lowered Boldt's arm. The glow left the focus.
"No trinkets." he admonished.
"What the hell are you #emph[doing] ?" Boldt exhaled, barely concealing his panic. "We're about to get blown to kindling, and—"
"Don't speak. Don't command. #emph[Ask] ."
"But—"
"Boldt, the essence of it is there, waiting to help you. Find what's ready. When you see it, you'll know what to do."
"But I #emph[don't] see it, that's what I'm trying to—"
"You'll know."
"#emph[Damn it, I don't see it!] "
#emph[Boom.]
Another blast, direct hit along the hull. Reflexively, Boldt stutter-stepped back, echoing its direction. And then, without thinking, he lunged forward—emotion and alarm given physical form.
And the energy sprang forth from the core of him, unbidden and true. A voltaic surge of force lashed across fathoms of ocean to catch the vanguard upright, knocking it violently broadside to port.
The cannon fire stopped. Everything stopped, as the young mage stood still, absolutely shocked at what he had done.
"That...that..."
"You got out of the spell's way," said Enthril.
"That was unreal!" Boldt beamed. "I can't believe it!"
A drumbeat sounded from the pirate ships. With nimble precision, each of the vessels veered sharply, turning about with growing urgency.
"Gods, old man, we did it!" Boldt exclaimed with exultant joy. "We got 'em to turn tail!"
Turning abaft and eastward, Enthril shook his head and walked away.
"No. That's not it."
Boldt followed quickly. "What? What do you see?"
"There." Enthril pointed past the railing at a series of buoys approaching from the east. "We're too late. The Perimeter."
The markers were spread out by hundreds of feet, a dotted line that stretched to the horizon.
Past it, the character of the sea changed dramatically. Much darker, with cresting whitecaps. And though the sails had been dislodged, the current would not abate, and the ship drifted ever closer.
"What's beyond it?" asked Boldt.
No answer. Enthril regarded the approaching barrier silently, the color rapidly draining from his face.
#figure(image("001_The Prodigal Sorcerers/05.jpg", width: 100%), caption: [Island | Art by Adam Paquette], supplement: none, numbering: none)
"Enthril?"
Finally he uttered, "The Dire Waves. This is what #emph[worse] looks like."
"Ever been there?"
"Am I standing here speaking to you?"
"Yes."
"Then no."
Enthril moved toward center deck, his mind racing.
"Here, lad, right here. Hull's stronger."
"Wait, wait." Boldt protested. "Isn't there some way we can..."
"Too late. Current's got us."
"Or use some sort of spell to..."
"We'll pass the perimeter in seconds. Ready yourself."
"For what?"
Enthril looked Boldt in the eye, gravely.
"Everything."
The sky grew dim beyond the markers as they drifted to the nearest buoy. Approaching it to starboard, they could make out a disquieting detail.
Chained to the marker were a tangle of skeletons, frozen into awkward positions and blanched white from the sun. The first to greet them.
As hollow eye sockets followed them ominously, Boldt and Enthril crossed the threshold of the perimeter.
"All right," said Boldt, "#emph[Now ] what do we—"
Instantly, the buoy lit up in brilliant, unholy light. One after another, each buoy followed suit, the hellish glow of their beacons extending to the horizon. Boldt inhaled sharply as the skeletons came to life, extending bony arms to point directly at the two men, their toothless mouths yawning open in unison to emit a piercing, accusatory shriek.
Then something burst from the sea off the port bow. The pair looked to its source to be brought short by a staggering sight. An enormous tentacle, pockmarked with jagged horns, speared upward of 50 feet in the air.
The appendage crashed through the middle of the ship, splitting it across the keel to send the mages airborne with the deck spinning beneath them, careening like a stone skipped across a pond.
Desperately clutching at anything within reach, the men fought to stay above water as the deck broke apart, whittling their lifeline to the size of a raft. Pieces of the ship rippled end over end, slowing and then caving in, scuttled and sinking among the endless waves.
"Tell me you have something left!" Boldt entreated, frantically grappling for something to stay afloat as the sea grew chest-deep.
But before Enthril could answer, the remnants of the deck creaked and ground to a halt against something solid below.
Boldt caught his breath as Enthril stared through the floating debris.
"We've run aground..."
The young man quickly looked around him.
"Could it be a reef or a—"
Then something rose to meet their feet. Something large. And they too began to rise, surging past the waterline as they ascended from the sea in a rumbling churn of spray and foam.
This was no reef. Beneath them, the barnacled surface of an immense shell, the back of a creature whose scale seemed to have no end, materialized around them as a deluge of brine and sludge downrushed against it like a torrential cauldron.
#figure(image("001_The Prodigal Sorcerers/06.jpg", width: 100%), caption: [Scourge of Fleets | Art by <NAME>in], supplement: none, numbering: none)
As they rose, the shard of deck began shaking to pieces under their feet; soon it would all be over. Boldt looked to Enthril pleadingly. Enthril nodded to him.
"You'll know."
The old man closed his eyes in concentration, blocking out the chaos. Wood and iron dissolved around them like feeble straw, yet Enthril remained still.
Boldt regarded the man in silent concentration, not knowing what to do except...augmentation? Yes, absolutely. The two of them working in concert, sea and sky.
He went for his satchel. But to the surprise of his muscle memory, his hand found nothing but a ripped strap. The books, the notes, the bronze figurine in the shape of a sextant, all gone now.
The mass beneath their feet lurched forward, up and across, leaving Boldt to claw at the splintered muck for leverage. Before him, Enthril barely moved, lost except to the energies he called upon.
With no other option, Boldt anchored himself between what used to be a yardarm and the scaly hide beneath. Then he closed his eyes too.
#emph[Find it. See it. See what? Never mind, just—]
And then the voice in his head, the voice of control, suddenly, inexplicably stopped. Or more accurately, shifted. Because he could finally #emph[see] it.
He could see himself, moments before. With the ships, reacting without calculation, true presence in the moment, the first glint of understanding. All his study and work before, just a part. A channel for the magic to flow through, to find its own shape and meet him at its heart.
He began to utter words aloud, words still learning their form. Raw materials catching the energy like a tide. And the old man, now bathed in blue light, was guiding them through.
But Enthril seemed labored, like a bridge about to collapse under the weight of an army. Exhausted, he floated in and out of consciousness, and whispered as if to someone else.
"There's always...always more to know..."
Boldt opened his eyes and crawled to him, and their two figures huddled against each other amid the maelstrom of wreckage. They were fixed precariously on its back now, this behemoth, and it rose ever upward as the very last of the ship crumbled away.
"I see it now. I see it." Boldt said to Enthril. "It's amazing."
Enthril seemed to smile slightly at this, as he resumed his wordless chant. Boldt began again and joined him.
The creature sounded off, exhaling like a whale. A monstrous, ear-splitting roar of vapor. Undeterred, they chanted silently as one. Until something new started to happen.
A single, defiant plank of broken deck rose up to meet them, hovering at eye level not ten feet away, waiting. And one by one, it was joined by others, until a piecemeal mishmash of wood, fabric, and metal floated and swirled about them.
From the center of the forming tornado, Enthril opened his eyes, suddenly aglow with blazing, vibrant light. As the light grew in intensity, Boldt looked up in alarm.
"Enthril, what—"
The light exploded forth—engulfing the mages, the floating scraps of ship, the creature, the sea, the world. All in an instant, and then all was nothing.
#figure(image("001_The Prodigal Sorcerers/07.jpg", width: 100%), caption: [Eternal Dominion | Art by Shishizaru], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Boldt awoke, his cheek against a wooden deck. The sensation of the flat, smooth surface, like new, caused him to sit upright with a start.
New surroundings greeted him. The deck of a strange-looking vessel. He called out for Enthril. No response. He staggered to a standing position and quickly looked in all directions. The old man was gone. In his place: this new ship, cradled by gleaming sails jutting out in odd directions. A butterfly of white cloth. But he couldn't see the water line beyond.
Then, he heard the sound of the creature in exhalation. But it sounded distant, as if far below. He approached the rail. All around him, sky.
He was on a skyship of some kind, the make of which he could only have imagined. Floating far above his last position, hundreds of feet over the Dire Waves.
Looking down, he could make out the full shape of the bestial leviathan, easily the size of a whole fleet of ships, possibly larger. Now, its tendrils stretched up feebly to grasp at him, but their reach was far too low to even scratch at the hull.
The wind kicked up to fill the sails, and the new vessel smoothly glided past the perimeter far below, faster than the wind should take him. The shade of the sea changed to bright blue, pure as a painting.
In the distance he could see the pirate ships tacking to the south, as if they were toys. And further still, to the west, the rolling, green stretch of the Spice Isles. Within it, the Tolarian Academy, his destination, approaching.
Astern, he noted the tiller, artfully carved and elegant—and directionless, yawning back and forth with the wind.
Something just beneath it reflected the morning light and caught his eye. It was Enthril's signet ring. He picked up the ring and looked at it for a long time.
The Spice Isles drew closer. But soon, the tiller moved to starboard as the sails caught a blast of warm air from the south. And the ship veered away from the archipelago, heading north.
Boldt looked at the tiller at his command. Then, finally, he turned his back to it and strode to the bow of the ship, letting the course of the winds carry him forward. He put on Enthril's ring, as a reminder. It fit perfectly.
Far below and away, the Tolarian Academy and the Spice Isles receded into the background, growing less significant, until they were gone.
And <NAME>, former apprentice and aspirant seeker, once son and heir to the Duchy of Kelsh, humbled in the art by wind and wave, now flew uncontested through the skies. To face new purpose, to find new adventure, and to know the heart of the world.
#figure(image("001_The Prodigal Sorcerers/08.jpg", width: 100%), caption: [Island | Art by <NAME>], supplement: none, numbering: none)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-11AC0.typ | typst | Apache License 2.0 | #let data = (
("PAU CIN HAU LETTER PA", "Lo", 0),
("PAU CIN HAU LETTER KA", "Lo", 0),
("PAU CIN HAU LETTER LA", "Lo", 0),
("PAU CIN HAU LETTER MA", "Lo", 0),
("PAU CIN HAU LETTER DA", "Lo", 0),
("PAU CIN HAU LETTER ZA", "Lo", 0),
("PAU CIN HAU LETTER VA", "Lo", 0),
("PAU CIN HAU LETTER NGA", "Lo", 0),
("PAU CIN HAU LETTER HA", "Lo", 0),
("PAU CIN HAU LETTER GA", "Lo", 0),
("PAU CIN HAU LETTER KHA", "Lo", 0),
("PAU CIN HAU LETTER SA", "Lo", 0),
("PAU CIN HAU LETTER BA", "Lo", 0),
("PAU CIN HAU LETTER CA", "Lo", 0),
("PAU CIN HAU LETTER TA", "Lo", 0),
("PAU CIN HAU LETTER THA", "Lo", 0),
("PAU CIN HAU LETTER NA", "Lo", 0),
("PAU CIN HAU LETTER PHA", "Lo", 0),
("PAU CIN HAU LETTER RA", "Lo", 0),
("PAU CIN HAU LETTER FA", "Lo", 0),
("PAU CIN HAU LETTER CHA", "Lo", 0),
("PAU CIN HAU LETTER A", "Lo", 0),
("PAU CIN HAU LETTER E", "Lo", 0),
("PAU CIN HAU LETTER I", "Lo", 0),
("PAU CIN HAU LETTER O", "Lo", 0),
("PAU CIN HAU LETTER U", "Lo", 0),
("PAU CIN HAU LETTER UA", "Lo", 0),
("PAU CIN HAU LETTER IA", "Lo", 0),
("PAU CIN HAU LETTER FINAL P", "Lo", 0),
("PAU CIN HAU LETTER FINAL K", "Lo", 0),
("PAU CIN HAU LETTER FINAL T", "Lo", 0),
("PAU CIN HAU LETTER FINAL M", "Lo", 0),
("PAU CIN HAU LETTER FINAL N", "Lo", 0),
("PAU CIN HAU LETTER FINAL L", "Lo", 0),
("PAU CIN HAU LETTER FINAL W", "Lo", 0),
("PAU CIN HAU LETTER FINAL NG", "Lo", 0),
("PAU CIN HAU LETTER FINAL Y", "Lo", 0),
("PAU CIN HAU RISING TONE LONG", "Lo", 0),
("PAU CIN HAU RISING TONE", "Lo", 0),
("PAU CIN HAU SANDHI GLOTTAL STOP", "Lo", 0),
("PAU CIN HAU RISING TONE LONG FINAL", "Lo", 0),
("PAU CIN HAU RISING TONE FINAL", "Lo", 0),
("PAU CIN HAU SANDHI GLOTTAL STOP FINAL", "Lo", 0),
("PAU CIN HAU SANDHI TONE LONG", "Lo", 0),
("PAU CIN HAU SANDHI TONE", "Lo", 0),
("PAU CIN HAU SANDHI TONE LONG FINAL", "Lo", 0),
("PAU CIN HAU SANDHI TONE FINAL", "Lo", 0),
("PAU CIN HAU MID-LEVEL TONE", "Lo", 0),
("PAU CIN HAU GLOTTAL STOP VARIANT", "Lo", 0),
("PAU CIN HAU MID-LEVEL TONE LONG FINAL", "Lo", 0),
("PAU CIN HAU MID-LEVEL TONE FINAL", "Lo", 0),
("PAU CIN HAU LOW-FALLING TONE LONG", "Lo", 0),
("PAU CIN HAU LOW-FALLING TONE", "Lo", 0),
("PAU CIN HAU GLOTTAL STOP", "Lo", 0),
("PAU CIN HAU LOW-FALLING TONE LONG FINAL", "Lo", 0),
("PAU CIN HAU LOW-FALLING TONE FINAL", "Lo", 0),
("PAU CIN HAU GLOTTAL STOP FINAL", "Lo", 0),
)
|
https://github.com/alerque/polytype | https://raw.githubusercontent.com/alerque/polytype/master/data/hieroglyphs/typst.typ | typst | #set page(
paper: "a6",
)
#set par(
first-line-indent: 0pt,
justify: false,
)
#set text(
font: "Libertinus Serif",
size: 16pt,
)
#let egyp-sample(phonetics, translation, str)= {([
_#(phonetics)_ ‘#translation’
#v(-0.5em)
#line(length: 100%)
#v(-0.5em)
[#set text(font: "Egyptian Text", size: 1.5em, fallback:false);#str]
])}
#egyp-sample("mdw.t-km.t", "Egyptian language", "𓌃𓂧𓏏𓏯𓀁𓏪𓆎𓅓𓊖")
#egyp-sample("nfr", "fine, beautiful", "𓄤𓆑𓂋")
#egyp-sample("ḫprj", "Khepri", "𓆣𓂋𓇋𓁛")
|
|
https://github.com/xingjian-zhang/typst2img | https://raw.githubusercontent.com/xingjian-zhang/typst2img/main/output/euler_identity.typ | typst | #let display(body) = context {
set page(width: auto, height: auto, margin: (x: 20pt, y: 20pt))
align([#body], center + horizon)
}
#display[$ e^(i pi) + 1 = 0 $] |
|
https://github.com/EpicEricEE/typst-plugins | https://raw.githubusercontent.com/EpicEricEE/typst-plugins/master/united/examples/quantities.typ | typst | #import "../src/lib.typ": qty
#set raw(lang: "typ")
#set text(size: 14pt)
#set table(
inset: 0.7em,
fill: (x, y) => if y == 0 { luma(230) }
)
#set page(
width: auto,
height: auto,
margin: 1em,
background: pad(0.5pt, box(
width: 100%,
height: 100%,
radius: 4pt,
fill: white,
stroke: white.darken(10%),
)),
)
#table(
columns: 2,
[*Input*], [*Output*],
[`#qty(42, "µm")`], [#qty(42, "µm")],
[`#qty[3.5(5)][meter cubed]`], [#qty[3.5(5)][meter cubed]],
[`#qty[1.602e-19][eV]`], [#qty[1.602e-19][eV]],
[`$qty(12+3-1 e-9, s)$`], [$qty(12+3-1 e-9, s)$],
)
|
|
https://github.com/crdevio/typst-themes | https://raw.githubusercontent.com/crdevio/typst-themes/main/typing-course%20template/example.typ | typst | #import "theme.typ": *
#document(title: "Example Page")[
= #lorem(5)
== #lorem(2)
#def(title: "title")[
#lorem(20)
]
#margin-note[#lorem(5)]
#lorem(30)
#th(title: "title of the th")[
#lorem(100)
]
#dem[
#lorem(150)
]
]
|
|
https://github.com/DieracDelta/presentations | https://raw.githubusercontent.com/DieracDelta/presentations/master/polylux/book/src/utils/side-by-side-kwargs.typ | typst | #import "../../../polylux.typ": *
#set page(paper: "presentation-16-9")
#set text(size: 40pt)
#polylux-slide[
#side-by-side(gutter: 3mm, columns: (1fr, 2fr, 1fr))[
#rect(width: 100%, stroke: none, fill: aqua)
][
#rect(width: 100%, stroke: none, fill: teal)
][
#rect(width: 100%, stroke: none, fill: eastern)
]
]
|
|
https://github.com/donRumata03/aim-report | https://raw.githubusercontent.com/donRumata03/aim-report/master/lib/my-theorems.typ | typst | #import "@preview/lemmify:0.1.5": *
#import "split-box.typ" : *
#set heading(numbering: "1.1")
#let cyrsmallcaps(body) = [
#show regex("[а-яё]") : it => text(size:.7em, upper(it))
#body
]
#let map-values(f, m) = {
let res = (_nothing: none)
res.remove("_nothing")
for k in m.keys() {
res.insert(k, f(m.at(k)))
}
res
}
#translations.insert("ru", map-values(cyrsmallcaps, (
"theorem": "Теорема",
"lemma": "Лемма",
"corollary": "Следствие",
"remark": "Замечание",
"proposition": "Предположение",
"example": "Пример",
"definition": "Определение",
"memorizer": "Напоминалочка",
"property": "Свойство",
"statement": "Условие",
"proof": "Доказательство",
"breakable-proof": "Доказательство",
)))
#let right-default-theorems(
group,
lang: "en",
thm-styling: thm-style-simple,
proof-styling: thm-style-proof,
thm-numbering: thm-numbering-linear,
ref-styling: thm-ref-style-simple,
max-reset-level: 1
) = {
let (proof, ..subgroup-map) = translations.at(lang)
let (rules: rules-theorems, ..theorems) = new-theorems(
group,
subgroup-map,
thm-styling: thm-styling,
thm-numbering: thm-numbering
)
let (rules: rules-proof, proof) = new-theorems(
group,
(proof: translations.at(lang).at("proof")),
thm-styling: proof-styling,
thm-numbering: thm-numbering-proof,
ref-numbering: thm-numbering
)
return (
..theorems,
proof:
// use-proof-numbering(proof)
proof
,
// breakable-proof: translations.at(lang).at("breakable-proof"),
rules: concat-fold((
thm-reset-counter-heading.with(group, max-reset-level),
rules-theorems,
rules-proof
))
)
}
#let (
definition, theorem, lemma, corollary, remark, proposition, example, memorizer, property, statement, proof, rules: thm-rules
) = right-default-theorems("thm-group", lang: "ru", max-reset-level: 1)
#let (
proof: breakable-proof, rules: bthm-rules
) = right-default-theorems("bthm-group", lang: "ru", max-reset-level: 1)
// #let (
// definition, theorem, lemma, corollary, remark, proposition, example, proof, rules: thm-rules
// ) = default-theorems("thm-group", lang: "ru", max-reset-level: 1)
// #let (property, memorizer, rules: custom-rules) = new-theorems("thm-group", (
// property: text(red)[Note],
// memorizer: [Напоминалочка],
// ))
// #show: custom-rules
#import "@preview/rose-pine:0.1.0": apply, rose-pine-dawn, rose-pine-moon, rose-pine, apply-theme
#show: apply(variant: "rose-pine-moon")
#let rose-pine-theorem-colors(theme) = {
(
definition: theme.gold,
theorem: theme.love,
lemma: theme.love,
corollary: theme.pine,
remark: theme.foam,
proof: theme.iris
)
}
#let add-paint-if-some(res, source, key) = {
if key in source {
res.insert("paint", source.at(key))
}
res
}
#let my-theorem-styles = (thm-styles: (_nothing: none)) => body => {
show: thm-rules
show: bthm-rules
let proof-border = (
// The starting and ending lines
above: none,
below: none,
// Lines to put between the box over multiple pages
btwn-above: line(length: 100%, stroke: (dash:"dotted")),
btwn-below: line(length: 100%, stroke: (dash:"dotted")),
// Left/right lines
// These *must* use `grid.vline()`, otherwise you will get an error.
// To remove the lines, set them to: `grid.vline(stroke: none)`.
// You could probably configure this better with a rowspan, but I'm lazy.
left: grid.vline(stroke: add-paint-if-some((thickness: 1pt, dash: "dotted"), thm-styles, "proof")),
right: grid.vline(stroke: none),
)
// show: it => thm-reset-counter-heading-at("thm-group", 1, it)
show thm-selector("thm-group", subgroup: "definition"): it => box(
it,
stroke: (left: add-paint-if-some((thickness: 2pt), thm-styles, "definition")),
inset: 1em,
)
show thm-selector("thm-group", subgroup: "theorem"): it => box(
it,
stroke: add-paint-if-some((thickness: 1pt), thm-styles, "theorem"),
inset: 1em
)
show thm-selector("thm-group", subgroup: "lemma"): it => box(
it,
stroke: add-paint-if-some((thickness: 1pt, dash: "dotted"), thm-styles, "lemma"),
inset: 1em
)
show thm-selector("thm-group", subgroup: "corollary"): it => box(
it,
stroke: add-paint-if-some((thickness: 1pt), thm-styles, "corollary"),
inset: 1em
)
show thm-selector("thm-group", subgroup: "example"): it => box(
it,
inset: (left: 1em, right: 1em, top: 1em, bottom: 1em),
)
show thm-selector("thm-group", subgroup: "remark"): it => box(
it,
inset: (left: 1em, right: 1em, top: 1em, bottom: 1em),
)
let proof-with(element, it) = {
element(
it,
stroke: (left:
add-paint-if-some((thickness: 1pt, dash: "dotted"), thm-styles, "proof")
),
inset: (left: 1em, right: 1em, top: 0.5em, bottom: 0.5em),
)
}
show thm-selector("bthm-group", subgroup: "proof"): it => if (false) {
split-box(it, border: proof-border)
} else { proof-with(block.with(breakable: true), it) }
show thm-selector("thm-group", subgroup: "proof"): it => proof-with(box, it)
body
}
= Тест
#show thm-selector("thm-group"): my-theorem-styles(
thm-styles: rose-pine-theorem-colors(rose-pine-moon)
)
#show thm-selector("bthm-group"): my-theorem-styles(
thm-styles: rose-pine-theorem-colors(rose-pine-moon)
)
#theorem(name: "Some theorem")[
Theorem content goes here.
]<thm-label-example>
#proof[
That's quite obvious
#remark[
See YouTube lectures for deeper understanding
]
#lemma[
sdfa
]
#proof[
Lemma's proof
]
]<proof-label-example>
@proof-label-example and @thm-label-example[theorem]
#breakable-proof[
#lorem(1000)
]
|
|
https://github.com/Lypsilonx/Game-of-Intrigue | https://raw.githubusercontent.com/Lypsilonx/Game-of-Intrigue/main/box.typ | typst | #import "data.typ": *
#import "@preview/boxr:0.1.0": *
#let a_size(exponent) = {
let a0_size = (841mm, 1189mm)
for i in range(exponent) {
let last_a_size = a0_size
a0_size = (last_a_size.at(1) / 2, last_a_size.at(0))
}
return a0_size
}
#let calculate_smallest_a_size(width, height) = {
let current_a_size = 0
let current_size = a_size(current_a_size)
while (width < current_size.at(1) and height < current_size.at(0)) {
current_a_size = current_a_size + 1
current_size = a_size(current_a_size)
}
return current_a_size - 1
}
#let card_amount = card_count
#let card_thickness = 1mm
#let structure_args = (
width: card_thickness * card_amount,
height: card_height + 5mm,
depth: card_width + 5mm,
lid-size: card_height * 0.4,
tab-size: 25pt,
)
#let size = get-structure-size(
json("box_lid.json"),
..structure_args
)
#let total_width = size.at(0)
#let total_height = size.at(1)
#let next_biggest_a_size = str(calculate_smallest_a_size(total_width, total_height))
#set page(
fill: gray,
"a" + next_biggest_a_size,
flipped: true,
margin: 0%,
)
#set text(font: "Inter Tight", fill: white, size: 4em)
#place(top + center, dx: 5mm, dy: 5mm)[
#set text(size: 0.5em, fill: black)
Print on A#next_biggest_a_size paper for correct scaling
]
#set align(center + horizon)
#render-structure(
json("box_lid.json"),
..structure_args,
color: black,
cut-stroke: (thickness: 1pt, paint: white, dash: "dashed"),
fold-stroke: 0.3pt + gray,
[
//front
#rotate(180deg)[
#v(card_height * 0.4)
#set text(size: 0.15em)
#logo(banner: true)
]
],
[
//top
#rotate(180deg)[
#set text(size: 0.15em)
#logo()
]
],
[
//left
#set text(size: 0.1em)
#place(
center + horizon,
dy: -8em,
)[
#logo()
]
#place(
center + bottom,
dy: -23mm,
)[
#box(width: 100%, height: 6.3em, fill: gradient.linear(white, black))
]
],
[
//right
#set text(size: 0.1em)
#place(
center + horizon,
dy: -8em,
)[
#logo()
]
#place(
center + bottom,
dy: -23mm,
)[
#box(width: 100%, height: 6.3em, fill: gradient.linear(black, white))
]
],
[
//back
#set text(
size: 0.18em,
fill: white
)
#set align(left + top)
#box(
height: 45%,
inset: (
top: 3em,
left: 3em,
right: 3em
)
)[
#set par(justify: true)
#columns(2, gutter: 3em)[
#text(size: 1.2em)[
#outline_text
]
]
]
#v(1fr)
#box(
inset: (
left: 3em,
right: 3em
)
)[
3-#player_count players#h(1fr)Ages: 12+#h(1fr)Playtime: 30-60 min.#h(1fr)Contains: #card_amount cards
]
#v(1fr)
#set text(size: 0.8em)
#set align(center)
#icon_banner
#v(23mm)
#place(
center + bottom,
dy: -10mm,
[
Game of Intrigue - Version #version\
Lyx Rothböck 2024\
]
)
]
) |
|
https://github.com/Han-duoduo/mathPater-typest-template | https://raw.githubusercontent.com/Han-duoduo/mathPater-typest-template/main/README.md | markdown | Apache License 2.0 | # 一个简易可复用的数模论文模板
<img src="./figures/exampl.png"/>
本模板,主要包括,定制化了:图片、表格、代码块、附录代码、公式、符号说明等数模中经常使用的模块(详细见 ***[template.typ](./template/template.typ)*** 文件)。
这里不再赘述`typst`的基础语法以及`typst`的安装过程。
---
# 文件结构
- `chapter目录` //用于存放各章节的`.typ`文件
- `chap1.typ`
- `chap2.typ`
- `chap3.typ`
- `appendix.typ`
- `...`
- `figures目录`//用于存放各种图片文件
- `fig1.png`
- `fig2.jpeg`
- `icon.svg`
- `...`
- `reference目录`//存放参考文献
- `lib.bib`
- `...`
- `template目录`//存放模板文件
- `template.typ`//主要模板文件
- `utils.typ`//存放一些辅助函数
- `.gitignore文件`//git忽略文件
- `main_text.typ文件`//正文主入口文件
- `README.md文件`//介绍文件
该模板采用**多文件存储**,作者认为利用代码来写文字工作的最显著的优势:
- 格式与内容分离(latex思想)
- 能够利用git等工具进行版本控制。(当修改了若干版之后,老板最终决定要第1版的内容时,bushi)
- 能够制作可复用的模板,包括:图、表、公式等。能够做到上下联动进行修改。不用再像word中一处一处的手动修改(虽然也可以利用样式编辑器对部分模块达到联动修改的效果)
- ⭐⭐⭐***最最最主要的我觉得就是能够多文件分离存储***。(曾经,我看到过有同学用word写论文时,大概写了二百多页的时候,每次操作都可以看到word肉眼可见的卡,然后时不时的,Word:未响应。就怕它突然闪退,然后发现自己一下午的劳动成果没了,真的是算是噩梦了。)
---
# 如何使用
## 1. 首先需要在 ***[main_text.typ](./main_text.typ)*** 正文入口文件中头部添加
```typ
#import "template/template.typ":*
#show: template.with(
abstract: [摘要内容],
title: "基于MR数据的PCI规划问题",
keywords: ("key word1", "key word2", "key word3", "..."),
)
```
## 2. 正文书写
> 在导入模板,并应用模板后就可以开始愉快的正文编写了。
这里同样推荐大家分多文件进行正文书写。示例如下:
1. 在`main_text.typ`中书写如下内容
2. 将各章节的`.typ`文件存放于`chapter`目录下
```typ
#import "template/template.typ":*
#import "template/template.typ":template as T-MathorCup
#show: T-MathorCup.with(
abstract: [摘要内容],
title: "基于MR数据的PCI规划问题",
keywords: ("PCI规划", "整数规划", "蒙特卡洛模拟", "分层序列法"),
)
/*正文区*/
//导入各章节
#include "chapter/chap1.typ"
#include "chapter/chap2.typ"
#include "chapter/chap3.typ"
#include "chapter/chap4.typ"
#include "chapter/chap5.typ"
#include "chapter/chap6.typ"
//参考文献
= 参考文献
#bibliography("reference/lib.bib",title:none,)
//附录
#include "chapter/appendix.typ"
```
## 3. 正文中常用模块
+ ## 图片
1. 在正文,如果需要插入图片,首先将图片资源存放在`figures`目录下。
2. 利用 ***[template.typ](./template/template.typ)*** 中所提供的`img()`函数。
3. 使用示例如下
```typ
#img(
image("../figures/fig1.png", width:85%),
caption: "问题一的数据处理示意图"
)<fig1>
```
首先传入*typst*中的`image()`对象,再指定图注`caption`参数,最后利用`<fig-name>`引用该图片。
+ ## 表格
1. 利用 ***[template.typ](./template/template.typ)*** 中所提供的`tbl()`函数。
2. 使用示例如下:
```typ
#tbl(
table(
columns:3,
align: center+horizon,
stroke:none,
table.hline(stroke:1.5pt),
table.header()[*标题行1*][*标题行2*][*标题行3*],
table.hline(stroke:1.0pt),
[测试数据11],[测试数据12],[测试数据13],
[测试数据21],[测试数据22],[测试数据23],
table.cell(colspan:3)[...],
table.hline(stroke:1.5)
),
caption: [测试数据]
)<tab1>
```
> 这里并没有直接将`table()`美化成三线表,主要是考虑更大程度上的自定义。利用原生`table()`能够按照自己的想法进行美化表格以适用于不同的场景。
+ ## 公式
1. 利用 ***[template.typ](./template/template.typ)*** 中所提供的`equation()`函数。
2. 示例如下:
```typ
#equation(
$ 1-(N / M)^(lambda)>= theta $
)<eq1>
```
> 与图、表一样,公式后同样也可以紧跟引用`<eq1>`用于在正文其他地方进行引用。
+ ## 代码块
1. 利用 ***[template.typ](./template/template.typ)*** 中所提供的`code()`函数。
2. 示例如下:
```
#code(
```cpp
#include<iostream>
using namespace std;
cout << "hello World!" << endl;
```,
caption: [C++代码],
desc: [打印Hello World]
)
```
> - 其中第一个参数:代码内容
> - caption参数:代码的题注
> - desc参数:代码的介绍
> 渲染结果如下:
<img src="./figures/codeExample.png">
+ ## 附录代码
1. 利用 ***[template.typ](./template/template.typ)*** 中所提供的`codeAppendix()`函数。
2. 示例如下:
```typ
#let code = ```cpp
#include<iostream>
using namespace std;
cout << "hello World!" << endl;```
#codeAppendix(
code,
caption:[问题1的示例代码]
)
```
> 渲染结果如下:
<img src="./figures/appendixCode.png">
---
# 定制化修改
针对上述模板,如果有任何觉得不太好的地方,想自定义的进行修改。都可以直接对 [template.typ](./template/template.typ)***(建议还是备份一版)*** 中的内容进行修改以达到自己想要的效果。
模板中的绝大多数地方都已加了备注说明,通过查阅[typst官方文档](https://typst.app/docs/) 进行修改即可。
# 后记
最后,介绍一些学习typst的资源
- typst中文翻译文档: https://typst-doc-cn.github.io/docs/
- 小蓝书: https://typst-doc-cn.github.io/tutorial/
- Awesome Typst 中文版: https://github.com/qjcg/awesome-typst/blob/main/README_ZH.md
- 一个typst交流qq群:793548390(里面有很多***大佬***,而且大家也都很热情。活跃度高!)
> 致谢:
>> 最后再次感谢上述qq群中解答过问题的各位大佬。没有你们的答疑解惑,该模板也难以顺利诞生。
|
https://github.com/bullno1/cross_gear_translation | https://raw.githubusercontent.com/bullno1/cross_gear_translation/master/rulebook/rulebook.typ | typst | The Unlicense | #import "@preview/wrap-it:0.1.0": wrap-content
#set document(title: [CROSS GEAR rule])
#show link: underline
#show heading.where(level: 1): set align(center)
= Play area
#image("zones.png")
= How to read cards
#image("card.png")
= Card states
#let state = image("states.png", height: 15pt * 8)
#wrap-content(state, [
GEAR and art cards and exist in one of the following two states:
- Ready (vertical)
- Exhausted (horizontal)
], align: right)
= Paying for action <pay-for-action>
Exhaust one ready GEAR card.
It does not matter whether the GEAR card is face up or face down.
#image("cost.png")
= About GEARLINK
GEARLINK is an effect that can be activated by paying the GEARLINK cost: Turn that many GEAR cards from the ready face up state into the exhausted face down state.
GEARLINK X means the cost can be chosen by the player activating the effect.
#image("gearlink.png")
= Effect timing and activation order
The effect of arts must be activated at the timing written on the card.
If multiple effects are activated at the same time, the player whose cards have the effects decide the order of activation.
If the effects of both players' arts are activated at the same time, the active player resolves their effects first, then the opposing player resolves theirs.
= Conflict between rule and card effects
If there is a confict between the rule and a card effect, the card effect takes precedence.
= Concepts
#table(
columns: 2,
[\[DRIVE\]], [Activate this effect when you perform a DRIVE],
[\[ACTIVE\]], [You can attack without #link(<pay-for-action>, [paying for action])],
[\[DRAIN\]], [When this art deals damage, you recover life equal to that amount],
[\[ENTER\]], [When this art comes into play],
[\[EXIT\]], [When an art accumulates damage equal to or greater than its power, or due to a destruction effect, the art is moved from the field to the discard pile],
[\[ATTACK\]], [When this art attacks],
[\[RETREAT\]], [When this art is moved from the field to the discard pile],
[\[SPIKE\]], [When this art attacks and get blocked, it deals excess damage to the opponent],
[Destroy], [The card is moved from the field to the discard pile by the effect of an art],
)
== Example of \[SPIKE\]
#let spike = image("spike.png", height: 15pt * 15)
#wrap-content(spike, [
You perform GEARLINK ① with your "State of Transcendence" (2 power) bringing its attack power to 5.
The opponent blocks with "Looping Dark Barrier" (3 power).
The opponent will receive 2 damage.
When the blocker has already received damage due to blocking or other effects, the excess damage will be increased.
For example, if "Looping Dark Barrier" has received 2 damage before this attack, it will block 1 damage from the attack and 4 damage will be dealt to the opponent.
])
= Victory conditions
You win if you meet any of the following conditions:
- If the opponent's life is reduced to 0.
- When the opponent draws from a deck with no cards.
All effects happening at that point will be cancelled.
= Setup
- Each player starts with 20 life (managed with calculators, notes, etc...).
There is no upper limit.
When life is gained, it is possible to go over the initial 20.
- Each player place 10 GEAR cards face down in their GEAR area.
- For first time players, we recommend excluding the advanced characters, Sharon and Lucia, from character selection.
== Playing with one common set
+ A random player (chosen by "rock, paper, scissor" or other means), chooses between getting to pick character first or getting to decide turn order.
Perform "Character selection" then "Turn order selection".
"Character selection": If you get to choose character first, pick one character from your CROSS GEAR set and put it in your character area.
You will also receive all art cards for that character (3 types x 5 copies).
Character selection proceeds in this order: You → Opponent → You → Opponent.
"Turn order selection": If you are the player who get to pick turn order, you choose to go first or second.
+ Each player shuffles their two art card sets (15 + 15 cards) into one deck and put it in their deck area.
+ Each player draws their initial hand of 4 cards.
== Playing with your own set
+ Each players secretly select their two characters without showing it to their opponent.
+ Each player shuffles their two characters' corresponding art card sets (15 + 15 cards) into one deck and put it in their deck area.
+ Reveal the character cards at the same time.
+ The winner of "rock, paper, scissor" or other methods chooses to go first or second.
+ Each player draws their initial hand of 4 cards.
#pagebreak()
= Turn structure
#[
#set align(center)
Ready & Draw Phase → Main Phase → End Phase
]
== Ready & Draw Phase
The active player does the following in order:
- Ready all your art and GEAR cards.
- Gain 2 GEAR cards (if there is only 1 left, gain 1 instead).
\* "Gain a GEAR card" means "Place a GEAR card from your GEAR area face up into your GEAR gauge".
\* On the very first turn, the first player only gain 1 GEAR card instead of 2.
- Draw 1 card.
\* On the very first turn, the first player does not draw.
== Main Phase
The active player can perform any of the following action after #link(<pay-for-action>, [paying for the action]).
You can perform as many actions as you like in any order.
=== Play an art card
Put an art card from your hand into the field in the ready state.
\* Up to 3 art cards can be in the field.
\* Even when put into play by an effect, the art will enter play ready.
=== Retreat
Put one of you arts on the field into the discard pile.
\* Put the DRIVE cards of that art into the discard pile too.
\* Its \[EXIT\] effect will not be activated.
=== Accelerate
Draw 1 card.
=== DRIVE
If you have an art card in your hand that is the same as an art on your field, you can stack the hand card under the field card.
This is called performing a DRIVE.
This also includes DRIVE-ing cards from the discard pile due to card effects.
The hand card being stacked under is called a DRIVE card.
Then, perform the following steps:
+ That art gets +1 power.
\* If the DRIVE card is removed later, the power will decrease.
+ If there is a \[DRIVE\] effect in the art card, it will be activated.
+ Draw 1 card.
+ OVERDRIVE: When the 4th DRIVE card is attached to an art, it gains OVERDRIVE:
- The art gains \[ACTIVE\] for this turn.
- Ready the art.
Notes:
- During step 1-4, do not resolve other effects.
- If an art card leaves play, put all its DRIVE card in the discard pile.
- Since DRIVE cards are considered to be in the DRIVE area, effects such as \[ENTER\] and \[EXIT\] will not be activated.
=== Attack
+ Attack declaration step
Exhaust one ready art on your field and target your opponent.
If there is an \[ATTACK\] effect, it will be resolved after target declaration.
+ Block declaration step
The player being attacked may choose one of their ready arts and make it the target of the attack instead.
This is called a block.
+ Damage step
- If block was declared.
Each art will deal damage to the other equal to their power.
Arts that receive damage greater or equal to their power will be destroyed.
An art will accumulate damage during the turn but its power will not decrease as a result of damage.
- If block was not declared.
Deal damage to the attacked player's life equal to the power of the attacking art.
== End phase
Do the following in order then pass turn to your opponent:
+ If there is any effect that activates during the End Phase, resolve it.
+ If the active player has 6 or more cards in their hand, discard until they have 5 cards.
+ Heal all damage from all arts.
+ If there is a continuous effect with "until the end phase" or "this turn", the effect ends.
== Additional notes
Every phase has a "Start of" and "End of" trigger.
"Start of" means the effect happens before all steps in the phase.
"End of" means the effect happens after all steps in the phase.
#pagebreak()
= FAQ
Q: When there are 2 or fewer cards in the deck, can the effects that reveal 3 cards such as "Ultimate Price" or "Moment of Silence" be activated? \
A: No.
Q: If "Sword of Might and Wisdom" leaves the field at the same time as the opponent's art, can the effect of "Sword of Might and Wisdom" deal 1 damage to the opponent? \
A: Yes.
Q: When I attack with "Terrifying Bullet" and deal 3 damage to all of my opponent's arts using the GEARLINK ④ effect, which comes first: the effect damage or the block? \
A: The effect damage.
Q: When resolving the effect of "Raging Flame" (discard the top 4 cards from the deck), what do you do if there are only 2 cards in the deck? \
A: Discard 2 cards.
Q: When I have "White Wolf's Charge" and "Animal Cooperation" on the field, will the effect of my opponent's "Terrifying Bullet" (deal 3 damage to all arts) destroy "White Wolf's Charge" since "Animal Cooperation" is no longer in play? \
A: No, when "Animal Cooperation" is placed into the discard pile, "White Wolf's Charge" power will be increased so it will no longer be destroyed by 3 damage.
Q: When resolving the effect of "Bewitching Reward", what to do when there are 2 arts with the same power? \
A: The controller of "Bewitching Reward" chooses the target to destroy.
Q: If I receive 3 DRIVE cards at once due to the effect of "Bewitching Reward", would I draw 3 cards? \
A: Yes.
Q: What happens if there is only one face down GEAR card when resolving "Synthesis of Void and Wisdom"? \
A: The effect cannot be activated.
Q: My "State of Transcendence" attacks with 5 power.
The opponent blocks with "Looping Dark Barrier" and activates its effect.
How to resolve the \[SPIKE\] effect? \
A: Because "Looping Dark Barrier" will not receive damage from "State of Transcendence", the effect of \[SPIKE\] will not be resolved.
Q: If I activate the effect of "Looping Dark Barrier" when it takes damage from my opponent's art during a block, will the damage dealt to my opponent's art decrease? \
A: The damage value is determined when each art deals damage equal to their power.
Then, "Looping Dark Barrier"'s power is reduced to pay for its effect.
This will not affect the damage it deals to your opponent's art.
Q: When my "Unwavering Will" attacks with GEARLINK ① and it is blocked by "Theory of Decay and Destruction" or "Ultimate Price" then get destroyed by their \[EXIT\] effect, do I still recover life due to the effect of "Unwavering Will"? \
A: Yes.
Q: The effect of "Bewitching Reward" says: "You may discard 1 DRIVE card from this art. If you do, destroy 1 of your opponent's arts...".
Can this effect still be activated if the opponent has no arts in play? \
A: Yes.
Q: \[DRAIN\] says "When this art deals damage, you recover life equal to that amount".
Do I still recover life when I deal damage to my opponent's art by blocking? \
A: Yes.
Q: My opponent's field has "Animal Cooperation" and "Purple Mist's Guidance" and there are 19 cards in their discard pile.
I attack with "Terrifying Bullet" and activate its GEARLINK ④ effect, will "Purple Mist's Guidance" remain on the field? \
A: Yes, because when "Animal Cooperation" is placed in the discard pile, the number of cards become 20 and "Purple Mist's Guidance" gets +6 power.
Q: If I DRIVE "White Wolf's Charge" when my opponent has no art on the field, will the effect be activated? \
A: No. Only the +1 power and the card draw from the DRIVE will be resolved.
Q: If an attacking art is blocked and accumulates damage, will its power decrease for the rest of the turn? \
A: No, power is not decreased due to damage.
Q: When "Bewitching Reward" gains OVERDRIVE then the number of DRIVE card is reduced by its DRIVE effect, if a 4th DRIVE card is attached, will it gain OVERDRIVE again? \
A: Yes.
Q: When attacking with the effect of "Unwavering Will", can I also target ready arts? \
A: Yes.
Q: Is it possible to recover more life than the initial value? \
A: Yes.
Q: Does the victory condition "opponent draws from a deck with no cards" also cover drawing due to reasons such as DRIVE? \
A: Yes.
Q: If there is only 1 card in my deck, can I choose the "draw 2 cards" effect of "Blood-stained Crimson Wings"? \
A: Yes and you will lose the game.
Q: Can the \[ATTACK\] effect of "Animal Cooperation" be chosen if there is no such card in the deck?
And if so, can I just shuffle the deck? \
A: Yes, it can be chosen and you will shuffle the deck.
Q: If there is one or more "Animal Cooperation" in the deck, can I just shuffle the deck without putting it into play? \
A: No.
Q: The \[RETREAT\] effect of "Theory of Decay and Destruction" states: "If it \[EXIT\], banish it instead", would the \[EXIT\] and \[RETREAT\] effect of the affected art be skipped? \
A: Yes, banishing means not placing in the discard pile so neither \[EXIT\] nor \[RETREAT\] would be activated.
Q: Due to the \[ATTACK\] effect of my opponent's art, my "Theory of Decay and Destruction" leaves play.
I target the attacking art with the GEARLINK ① effect of "Theory of Decay and Destruction" and banish the attacking art.
Do I still take damage from the attacking art? \
A: No.
Q: When there are no cards in my GEAR area, can the GEARLINK ② effect, "Gain 1 GEAR card" of "Superior Talent" be chosen? \
A: No.
|
https://github.com/ludwig-austermann/typst-funarray | https://raw.githubusercontent.com/ludwig-austermann/typst-funarray/main/funarray-unsafe.typ | typst | MIT License | /// splits the array into chunks of given size.
#let chunks(arr, size) = {
let l = arr.len()
let remfreelength = l - calc.rem(l, size)
let rest = arr.slice(remfreelength)
if rest.len() > 0 {
range(remfreelength, step: size).map(i => arr.slice(i, i + size)) + (rest,)
} else {
range(remfreelength, step: size).map(i => arr.slice(i, i + size))
}
}
/// inverse of zip method. array(pair) -> pair(array)
#let unzip(arr) = if arr.len() > 0 {
let n = arr.at(0).len()
let res = range(n).map(_ => ())
for x in arr {
for i in range(n) {
res.at(i).push(x.at(i))
}
}
res
} else {
()
}
/// inverse of zip method. array(pair) -> pair(array)
#let unzipN(arr, n: 2) = {
let res = range(n).map(_ => ())
for x in arr {
for i in range(n) {
res.at(i).push(x.at(i))
}
}
res
}
/// cycles through arr until length is met
#let cycle(arr, length) = {
let l = calc.quo(length, arr.len())
let add = calc.rem(length, arr.len())
arr * l + arr.slice(0, add)
}
/// provides a running window of given size
#let windows(arr, size) = range(arr.len() - size + 1).map(x => arr.slice(x, x + size))
/// same as windows, but continues wrapping at the border
#let circular-windows(arr, size) = windows(arr + arr.slice(size - 1), size)
/// creates two arrays, 1. where f returns true, 2. where f returns false
#let partition(arr, f) = (arr.filter(f), arr.filter(x => not f(x)))
/// after partition, maps each partition according to g
#let partition-map(arr, f, g) = {
let parts = partition(arr, f)
(parts.at(0).map(g), parts.at(1).map(g))
}
/// groups the array into maximally sized chunks, where each elements yields same predicate value
#let group-by(arr, f) = if arr == () { (()) } else {
let state = f(arr.at(0))
let result = ((arr.at(0),),)
for v in arr.slice(1, arr.len()) {
if f(v) != state {
result.push((v,))
state = f(v)
} else {
result.last().push(v)
}
}
result
}
/// inserts a value inbetween each element
#let intersperse(arr, sep) = if arr.len() < 2 { arr } else {
(arr.zip((sep, ) * (arr.len() - 1)) + ((arr.last(),),)).sum() // flattening happens here with sum, as the flatten method acts recursively
//range(2 * arr.len() - 2).map(i => if calc.rem(i, 2) == 0 { arr.at(calc.quo(i, 2)) } else { sep }) + (arr.last(),)
}
/// returns all elements until the predicate returns false
#let take-while(arr, f) = if arr == () { () } else {
let max-index = arr.len()
for (i, v) in arr.enumerate() {
if not f(v) {
max-index = i
break
}
}
arr.slice(0, max-index)
}
/// returns all elements starting when the predicate returns false
#let skip-while(arr, f) = if arr == () { () } else {
let min-index = arr.len()
for (i, v) in arr.enumerate() {
if not f(v) {
min-index = i
break
}
}
arr.slice(min-index)
}
/// maps over elements together with a state, also refered to as accumulate
#let accumulate(arr, init, f) = {
let res = arr
for (k, v) in arr.enumerate() {
init = f(init, v)
res.at(k) = init
}
res
}
/// similar to accumulate, but f : (state, value) -> (state, value), simulating mutable state
#let scan(arr, init, f) = {
let res = arr
for (k, v) in arr.enumerate() {
(init, v) = f(init, v)
res.at(k) = v
}
res
}
/// f : state -> (state, value)
#let unfold(init, f, take) = {
let res = ()
for _ in range(take) {
let (state, v) = f(init)
init = state
res.push(v)
}
res
}
/// iteratively applies f to last value
#let iterated(init, f, take) = {
let res = ()
for _ in range(take) {
init = f(init)
res.push(init)
}
res
} |
https://github.com/leesum1/brilliant-cv | https://raw.githubusercontent.com/leesum1/brilliant-cv/master/modules_zh/skills.typ | typst | // Import
#import "@preview/brilliant-cv:2.0.2": cvSection, cvSkill, hBar
#let metadata = toml("../metadata.toml")
#let cvSection = cvSection.with(metadata: metadata)
#cvSection("技能")
#cvSkill(type: [团队合作], info: [拥有*开源社区经验*,熟悉 Git 工作流,能够高效地与团队成员协作,完成项目开发与维护])
#cvSkill(type: [编程语言], info: [熟练掌握 *C/C++、Rust、Verilog/SystemVerilog、Scala/Chisel* 以及 Python、Shell 等脚本语言])
#cvSkill(type: [芯片设计], info: [熟练掌握处理器设计、SOC 构建、FPGA 开发等设计技术,具备从 *RTL 设计、仿真到验证*的全流程经验])
#cvSkill(type: [嵌入式开发], info: [深入了解嵌入式系统开发流程,拥有 BSP 开发经验,熟悉 *SPI/I2C/UART 等接口协议*,具备从*底层硬件到系统软件*的开发能力])
// #cvSkill(type: [操作系统], info: [熟悉 Linux 系统,日常使用并进行系统开发、调试和优化;熟悉 RTOS(如 RT-Thread)的移植与应用])
// #cvSkill(type: [兴趣方向], info: [热衷于处理器设计、硬件加速技术及嵌入式系统应用开发,积极探索系统软件与芯片设计的前沿技术])
|
|
https://github.com/coljac/toki-pona-poster | https://raw.githubusercontent.com/coljac/toki-pona-poster/main/poster.typ | typst | The Unlicense | #set page(paper: "a2",
margin: 1cm)
#let glyph(symbol, toki, eng)={
align(center)[
#text(size: 50pt, font: "sitelen-pona")[#symbol]\
#text(weight: "bold" , size: 20pt, toki) \
#text(size: 13pt, style: "italic", eng)
]
}
// #set page(header: [
#block[
#set text(font: "Comic Neue", size: 80pt)
#grid(columns: (45%, 10%, 45%), stroke: 0pt + black,
align: (right+horizon, center+horizon, left+horizon),
[toki],
image("images/Toki_pona.svg", width: 80%),
[pona]
)]
#align(center, par(text(size: 18pt)[summary chart]))
#align(center)[
#set text(size: 10pt)
#table(columns: (10%, 10%, 10%, 10%, 10%, 10%, 10%, 10%, 10%),
stroke: 0pt + red,
[#glyph("", "a", "ah; emphasis, emotion, confirmation")], [#glyph("", "akesi", "non-cute animal; reptile, amphibian")], [#glyph("", "ala", "no, not, zero")], [#glyph("", "alasa", "to hunt, forage")], [#glyph("", "ale", "all; abundant, every, universe")], [#glyph("", "anpa", "down, lowly, humble")], [#glyph("", "ante", "different, altered, other")], [#glyph("", "anu", "or")], [#glyph("", "awen", "enduring, kept, safe, waiting")],
[#glyph("", "e", "(introduces direct object)")], [#glyph("", "en", "(between multiple subjects)")], [#glyph("", "esun", "market, shop, business transaction")], [#glyph("", "ijo", "thing, object, matter")], [#glyph("", "ike", "bad, negative; non-essential")], [#glyph("", "ilo", "tool, machine, device")], [#glyph("", "insa", "inside, between; internal organ")], [#glyph("", "jaki", "disgusting, sickly, unclean")], [#glyph("", "jan", "human being, person, somebody")], [#glyph("", "jelo", "yellow, yellowish")],
[#glyph("", "jo", "to have, contain, hold")], [#glyph("", "kala", "fish, sea creature")], [#glyph("", "kalama", "to produce a sound; utter aloud")], [#glyph("", "kama", "arriving, coming, future")], [#glyph("", "kasi", "plant, vegetation; leaf")], [#glyph("", "ken", "can, may; possible")], [#glyph("", "kepeken", "to use, with, by means of")], [#glyph("", "kili", "fruit, vegetable, mushroom")], [#glyph("", "kiwen", "hard object, metal, stone")], [#glyph("", "ko", "clay, dough, paste, powder")],
[#glyph("", "kon", "air, spirit; unseen agent")], [#glyph("", "kule", "colour, colourful")], [#glyph("", "kulupu", "community, group, society")], [#glyph("", "kute", "ear; hear, listen; obey")], [#glyph("", "la", "(context separator)")], [#glyph("", "lape", "sleeping, resting")], [#glyph("", "laso", "blue, green")], [#glyph("", "lawa", "head, mind; control, lead")], [#glyph("", "len", "cloth, clothing, fabric")], [#glyph("", "lete", "cold, cool; uncooked, raw")],
[#glyph("", "li", "(separates subject from verb)")], [#glyph("", "lili", "little, small, young")], [#glyph("", "linja", "long flexible thing; rope, hair")], [#glyph("", "lipu", "flat object; book, paper, website")], [#glyph("", "loje", "red, reddish")], [#glyph("", "lon", "located at, present; real")], [#glyph("", "luka", "arm, hand")], [#glyph("", "lukin", "to look at, see; seek")], [#glyph("", "lupa", "door, hole, window")], [#glyph("", "ma", "earth, land; country, soil")],
[#glyph("", "mama", "parent, ancestor; creator")], [#glyph("", "mani", "money, wealth; domesticated animal")], [#glyph("", "meli", "woman, female; wife")], [#glyph("", "mi", "I, me, we, us")], [#glyph("", "mije", "man, male; husband")], [#glyph("", "moku", "to eat, drink, consume")], [#glyph("", "moli", "dead, dying")], [#glyph("", "monsi", "back, behind, rear")], [#glyph("", "mu", "(animal noise or communication)")], [#glyph("", "mun", "moon, night sky object")],
[#glyph("", "musi", "artistic, entertaining, playful")], [#glyph("", "mute", "many, a lot, several; very")], [#glyph("", "nanpa", "numbers; -th (ordinal)")], [#glyph("", "nasa", "unusual, strange; foolish, drunk")], [#glyph("", "nasin", "way, custom, path, road")], [#glyph("", "nena", "bump, hill, mountain, nose")], [#glyph("", "ni", "that, this")], [#glyph("", "nimi", "name, word")], [#glyph("", "noka", "foot, leg; bottom, lower part")], [#glyph("", "o", "hey! O! (vocative or imperative)")],
[#glyph("", "olin", "to love, respect, show affection")], [#glyph("", "ona", "he, she, it, they")], [#glyph("", "open", "to begin, start; open")], [#glyph("", "pakala", "broken, damaged, harmed")], [#glyph("", "pali", "to do, work on; make")], [#glyph("", "palisa", "long hard thing; stick, rod")], [#glyph("", "pan", "cereal, grain; bread, pasta")], [#glyph("", "pana", "to give, send, provide")], [#glyph("", "pi", "of")], [#glyph("", "pilin", "heart; feeling, emotion")],
[#glyph("", "pimeja", "black, dark, unlit")], [#glyph("", "pini", "completed, finished, past, end")], [#glyph("", "pipi", "bug, insect, spider")], [#glyph("", "poka", "hip, side; nearby, vicinity")], [#glyph("", "poki", "container, bag, box, cup")], [#glyph("", "pona", "good, positive; simple")], [#glyph("", "pu", "interacting with the Toki Pona book")], [#glyph("", "sama", "same, similar; sibling, peer")], [#glyph("", "seli", "fire; heat source")], [#glyph("", "selo", "outer form; skin, boundary")],
[#glyph("", "seme", "what? which?")], [#glyph("", "sewi", "area above; divine, sacred")], [#glyph("", "sijelo", "body; physical state, torso")], [#glyph("", "sike", "round thing; ball, cycle")], [#glyph("", "sin", "new, fresh; additional, extra")], [#glyph("", "sina", "you")], [#glyph("", "sinpin", "face, front, wall")], [#glyph("", "sitelen", "image, picture, writing")], [#glyph("", "sona", "to know, be skilled")], [#glyph("", "soweli", "animal, beast, land mammal")],
[#glyph("", "suli", "big, large, tall; important")], [#glyph("", "suno", "sun; light, brightness")], [#glyph("", "supa", "horizontal surface; furniture")], [#glyph("", "suwi", "sweet, fragrant; cute, adorable")], [#glyph("", "tan", "by, from, because of")], [#glyph("", "taso", "but, however; only")], [#glyph("", "tawa", "to, toward; for; moving")], [#glyph("", "telo", "water, liquid; beverage")], [#glyph("", "tenpo", "time, duration, period")], [#glyph("", "toki", "to communicate, speak, talk")],
[#glyph("", "tomo", "indoor space; building, room")], [#glyph("", "tu", "two")], [#glyph("", "unpa", "to have sexual relations")], [#glyph("", "uta", "mouth, lips, jaw")], [#glyph("", "utala", "to battle, challenge, struggle")], [#glyph("", "walo", "white, light-coloured")], [#glyph("", "wan", "unique, united; one")], [#glyph("", "waso", "bird, flying creature")],
[], [], [],
[#glyph("", "wawa", "strong, powerful; energetic")], [#glyph("", "weka", "absent, away, ignored")],
[#glyph("", "wile", "must, need, require; want")]
)
#align(right)[poster by <NAME>, <EMAIL>, public domain]]
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20interna/Verbali/23-12-06/23-12-06.typ | typst | #import "/template.typ": *
#show: project.with(
date: "06/12/23",
subTitle: "Discussione a seguito del meeting con il Proponente",
docType: "verbale",
authors: (
"<NAME>",
),
reviewers: (
"<NAME>",
),
timeStart: "16:40",
timeEnd: "17:00",
);
= Ordine del giorno
- Discussione relativa al meeting con il Proponente;
- Suddivisione compiti da svolgere.
== Discussione relativa al meeting con il Proponente
Si è svolta una discussione a seguito del meeting con il Proponente allo scopo di definire con precisione ciò che l'azienda ha apprezzato e ciò che va rivisto. Il gruppo si ritiene soddisfatto dell'esito dell'incontro ed è stata creata una lista Keep doing/To Do per i prossimi giorni di lavoro:
- Keep doing:
- lettura file SVG: implementazione coerente con la richiesta del Proponente;
- griglia per snapping degli scaffali: particolarmente apprezzata dal referente aziendale;
- lettura dati dal database: implementata in maniera convincente.
- To do:
- definire con precisione dei parametri per il controllo dello "scaling" dell'applicazione;
- fissare parametri precisi per l'ambiente di default dell'applicazione;
- implementare bin e feature associate.
== Suddivisione compiti da svolgere
La suddivisione dei compiti decisa durante il meeting è:
- il Progettista, a seguito del completamento del lavoro con il Piano di Progetto, passerà allo sviluppo del PoC e si occuperà dell'integrazione dei bin con gli scaffali. |
|
https://github.com/HenkKalkwater/aoc-2023 | https://raw.githubusercontent.com/HenkKalkwater/aoc-2023/master/parts/day-2-1.typ | typst | #let solve = (input) => {
let game_r = regex("Game (\d+):")
let cubes_r = regex("(\d+) (\w+)")
let games = input
.split("\n")
.filter(line => line.len() > 0)
.map(line => {
let game = int(line.match(game_r).captures.at(0))
let game_draws = line.split(";")
let draws = ()
for draw in game_draws {
let game_matches = draw.matches(cubes_r)
let game_vals = (:)
for match in game_matches {
game_vals.insert(match.captures.at(1), int(match.captures.at(0)))
}
draws.push(game_vals)
}
(game, draws)
})
.filter(game => {
let draws= game.at(1)
draws.all(cubes => cubes.at("red", default: 0) <= 12 and cubes.at("green", default: 0) <= 13 and cubes.at("blue", default: 0) <= 14)
})
.map(game => game.at(0))
.sum()
games
}
|
|
https://github.com/WindowDump/typst-ttrpg | https://raw.githubusercontent.com/WindowDump/typst-ttrpg/main/README.md | markdown | The Unlicense | # typst-ttrpg
TTRPG documents, character sheets, and other table artifacts, created with [Typst](https://github.com/typst/).
Fonts included are licensed under the OFL.
If you have the Typst CLI available, you can compile .typ files to the format of your choice like so:
```sh
typst compile --font-path ./fonts -f png fist-handbook.typ fist-handbook-{n}.png
```
See `typst help compile` for a full command reference.
# [FIST Operative Handbook](fist-handbook.typ)
Zine-style booklet for [FIST](https://claymorerpgs.itch.io/fist), a paranormal mercenary TTRPG. Contains a character sheet, rules reference, and character creation instructions. A minimal sheet with a few cute touches.
Also includes a version with two copies of the character sheet, so you can print out two copies at once.
# [Remix Half-Letter Character Sheet](wodu-remix-sheet-halfletter.typ)
Character sheet for [Remix](https://katamoiran.itch.io/remix) (WoDu Remix) that fits on half of a US letter paper. Designed to be customized and hacked - spaces to write are white boxes laid on top of a pattern. A few example versions are provided - start hacking and see what you can make!
|
https://github.com/simon-epfl/notes-ba2-simon | https://raw.githubusercontent.com/simon-epfl/notes-ba2-simon/main/shs/cours.typ | typst | #import "template.typ": *
#let title = "Com B - Essor de l'I.A."
#let author = ""
#let professor = "<NAME>, <NAME>"
#let creater = "<NAME>, <NAME>"
#let time = "Spring 2024"
#let abstract = "Cours de SHS - Enjeux mondiaux de la communication en lien avec l’essor de l’intelligence."
#set quote(block: true)
#show: note_page.with(title, author, professor, creater, time, abstract)
= La loi de Moore
== Les promesses technoscientifiques
- du 16e siècle au 18e siècle #sym.arrow fonction de sensibilisation
- 19e siècle #sym.arrow fonction idéologique
=== Ces promesses sont toujours...
- non dystopiques
- imposent des solutions technologiques
- performatives#footnote[\#olympedegouge], le fait de formuler la promesse contribue à la faire réaliser (orientent les moyens alloués à la recherche & innovation)
=== ...et ont pour contraintes...
- la nécessité de nouveauté radicale (la promesse est la solution unique à un problème urgent)
- crédibilité (soutient des spécialistes, quitte à inventer ces soutiens)
=== Loi de Moore en microélectronique
est un modèle pour la fabrication de promesses technoscientifiques \
#sym.arrow.r.curve définit ce qui est pensable pour l'évolution des micro-processeurs
#box(
stroke: 1pt + rgb(34, 102, 153),
width: 100%,
fill: rgb(34, 102, 153, 30),
inset: 7pt,
text(fill : black, [
#text(fill : rgb(34, 102, 153),
[*📖 Contexte* : apparitions des premiers circuits intégrés]
)
#pad(top: 1pt)[- Fin 1950 $arrow$ Fairchild Seminconductor fabrique des transistors ($"#"$FDS)
- Pour inciter d'autres acteurs à faire le pari de l'ouverture de la société civile, <NAME>, directeur R&D chez Fairchild, publie un manifeste économique
- promesse en faveur de l'intégration :
#quote(attribution: [Moore, 1965])[
The future of integrated electronics is the future of electronics itself...
]]
]))
Seconde formulation de la loi :
#quote(attribution: [Moore, 1975], text([#strike(text("The density has increased at a rate of roughly a factor of two per year")), #text("\nThe density has increased at a rate of roughly a factor of two per two years")]))
Pour les CPU, en 2024, il est probable qu'on se détache de cette loi :
- l'énergie est chère
- coûts des lieux de fabrication
- la consommation change (+ d'économie d'énergie over + de performance)
== depuis 2010 : la course aux GPU
#table(
columns: (auto, auto),
inset: 10pt,
align: horizon,
table.header(
[*CPU*], [*GPU*],
),
"Quelques coeurs: entre 2 et 64", "Plusieurs coeurs: entre 2’000 et 50’000",
"Faible latence", "Haut débit de données",
"Bon pour le traitement en série", "Bon pour le traitement en parallèle",
"Peut effectuer une poignée d’opérations à la fois", "Peut effectuer des milliers d’opérations à la fois"
)
Les G.P.U. (graphical processing units) sont très efficaces pour la multiplication de matrices (donc très utiles pour l'I.A.).
== Loi de Huang
#quote(attribution: [<NAME> (CEO Nvidia, leader des cartes GPU)], "Les performances des GPUs seront plus que doublées chaque 2 ans", )
== Optimisation
*Représentation des nombres :* réduction de la précision pour accélerer les calculs. (2019, Google, grâce au brain floating point).
*Nouvelles cartes :*
- le T.P.U. (Tensor Processing Unit) par Google (2015), conçu pour les réseaux de neurones (fonctionne avec Tensorflow)
- le L.P.U. (Language Processing Unit) par Groq
- Apple Série M (système sur une unique puce SoC : CPU, GPU, mémoire unifié)
et beaucoup d'autres entreprises (AWS...)
== Etat du marché
Nvidia domine, tensions géopolitiques liées aux semi-conducteurs.
= Les modèles de langue
LLM : Large Language Model
== Recette d'un bon LLM
- bcp de paramètres (x10 chaque année, nouvelle loi de Moore#footnote[OMG la dinguerie !??!] ?)
- de la puissance de calcul
- bcp (bcp) de données (seront épuisées en 2026 !)
= Des booms et des hivers de l'IA
Historiquement, les technologies IA ont traversé des phases de booms et de crises.
== Genèse et 1er boom de l'IA (1940–1965)
Seconde Guerre mondiale #sym.arrow augmentation de la demande en calcul \
- Angleterre #sym.arrow décryptage ("Bomb", "Coloss") \
- U.S.A. #sym.arrow calcul balistique (ENIAC)
1942 : Moore School of Electrical Engineering, pour accélérer la production de tables de tir.
1943 : \$400k alloués à la constructeur de l'ENIAC (le dispositif prend le nom de "computer") \
#sym.arrow.r.curve très innovant mais problème d'architecture
1944 : nouveau projet dérivé de l'ENIAC, le *EDVAC* (notament grâce à <NAME>).
Formalisation de l'*architecture Von-Neumann* (encore très utilisée aujourd'hui) :
#image("neumann.png")
Juin 1945 : Neumann publie un rapport sur EDVAC (utilise des analogies avec le cerveau pour la première fois)
1949 : 1er ordinateur BINAC (sert de référence à UNIVAC, 1951), les ordinateurs/calculateurs sortent progressivement de la recherche militaire #sym.arrow *industrie et administration*.
1956 : 1ère appartition du terme I.A. (<NAME>)
1960 : premier boom de l'IA dite "symbolique" \
#sym.arrow.r.curve recherche logicielle visant à décrire les règles de pensée et les exprimer sous forme de code informatique (par ex. chatbot ELIZA).
Un groupe fermé de chercheurs s'arroge le monopole de la définition des enjeux de l'IA. \
#sym.arrow.r.curve capture l'essentiel des financements (75% de US Air Force) \
#sym.arrow.r.curve conserve l'accès aux grands systèmes informatiques
... cela conduit au premier hiver.
== Premier hiver de l'IA (1965-1975)
#sym.arrow promesses des promoteurs de l'IA symbolique n'ont pas été tenues \
#sym.arrow à partir de 1970, baisse des financements (notamment militaires) \
#sym.arrow accusés de se concentrer sur des "mondes jouets"
== Systèmes experts experts et 2ème boom (1975-1985)
Renouveau de l'IA symbolique (ordi + puissant et décomposition des processus de raisonnement en briques élémentairs)
*Système expert :*
#image("expert.png")
1970 : système MYCIN \
#sym.arrow série de questions au médecin \
#sym.arrow env. 600 règles \
#sym.arrow produit une liste de bactéries candidates
1980 : XCON pour aider à configurer les ordinateurs
1984 : DELTA pour identifier les pannes sur les locomotives
*Limites des systèmes expert :*
#quote(attribution: [<NAME>, 1983])[
Dans les décennies à venir, nous devrons disposer de moyens plus automatiques pour remplacer ce qui est actuellement une procédure très fastidieuse, longue et coûteuse.
]
== Deuxième hiver et travail de l'ombre
Des promesses non tenues (encore...) \
#sym.arrow problème de hardware \
#sym.arrow problème de maintenance des logiciels \
#sym.arrow la plupart des startups ont fait faillite
1990 : IA symbolique est si affaiblie que le terme disparaît quasiment du vocabulaire de recherche.
=== Parallel Distributed Processing
1986 : à l'écart de l'IA symbolique, un groupe de chercheurs travaille sur les *réseaux de neurones* (notamment reconnaissance des codes postaux)
notion de rétropropagation du gradient (ajuster les paramètres du modèle en fonction des erreurs qu'il commet, en fait le gradient c'est la dérivée, on l'utilise pour savoir dans quelle direction aller pour minimiser l'erreur).
LeNet-1, reconnaissance de chiffres - 1989 \
LeNet-5, reconnaissance de caractères (reconnaissances de ZIP codes par ex.) - 1998
== Réseau de neurones profonds et 3ème boom (2005-2024)
=== Avènement du Deep Learning :
- puissance de calcul augmente (performances des cpu #sym.arrow.tr + GPU)
- réseaux de neurones + profonds
=== Numérisation et essort d'Internet
- quantité de données #sym.arrow.tr
- mise en place de plateformes de crowdsourcing (pour labelliser des données)
Exemple : ImageNet (1k catégories d'objets, 1.2M d'images)
2012 : AlexNet, reconnaissance d'objets, meilleurs performances sur ImageNet (25% #sym.arrow 16%) grâce aux *filtres de convolution*.
2015 : ResNet
#sym.arrow application d’une même transformation linéaire sur différentes zones de l’image \
#sym.arrow on part de petites matrices (3x3) en demandant au modèle de générer de grandes matrices (5x5) *, chaque groupe est une couche de convolution* (pour éviter de se concentrer sur les détails).
Il y a plusieurs *cartes d'activation* (filtre = feature, appris à l'entraînement) à la sortie de chaque couche.
Réduction des cartes d’activation par *opération de pooling*.
Chaque convolution est suivie d'une *fonction d'activation* non linéaire.
La dernière couche est la couche *de classification*, qui détermine la sortie avec poids (appris pendant l'entraînement).
= Des booms et des hivers de l'IA (II)
== Genèse: memorandum de Weaver et démos. publiques (1950-1965)
1949 : Weaver suggère une meilleure approche (statistique et probabiliste) que celle de la traduction linéaire
1954 : première démonstration publique à New York, traduction de russe à anglais en public.
== Crise: le rapport ALPAC et ses conséquences (1965-1990)
1966 : le rapport ALPAC (Automatic Language Processing Advisory Committee)
#quote(attribution: [National Research Council, 1966])[Il n’y a aucune urgence dans le domaine de la traduction automatique. Le
problème n’est pas de satisfaire un besoin inexistant à travers des
systèmes de traduction automatiques inexistants]
peu de bénéfices à court-terme #sym.arrow *chute drastique des financements.*
== Renouveau et tradition statistique (1990-2015)
1990 : apparition de corpus parallèles#footnote[Merci au parlement canadien d'avoir traduit gratuitement des textes anglais-français. Sinon, on utilise aussi la Bible, vu que c'est un texte traduit dans quasiment 100% des langues] (utiles pour la traduction)
1992 : rapport JTEC (Japan Technology Evaluation Center) et incitations politiques (convaincre les gouvernements d'utiliser les nouvelles technologies)
mais aussi puissance de calcul et stockage #sym.arrow.tr \
et nouvelle culture statistique, probabiliste
=== Focus sur modèles de traduction basés sur les groupes de mots
1993 : IBM introduit plusieurs modèles statistiques pour la traduction (corpus parallèles issus du parlement canadien)
2006 : Google Translate, basée sur cette méthode
==== Comment ça marche ?
- segmentation des phrases en groupe de mots (tokens)
- recherche de correspondances les + probables
- assemblage des correspondances
==== Limitations de l’approche statistique
- traduction fausse si syntaxe non courante
- utilisation de l'anglais comme "langue pivot" (FR #sym.arrow EN #sym.arrow IT)#footnote[le truc drôle en plus, c'est si vous le mettez en PLS il sortira une phrase de la Bible]
== Traduction automatique par réseau de neurones (2014-2024)
=== Boom des ConvNets
Entre 2012 et 2015 : boom des ConvNets pour traitement des images
==== Comment ça marche ?
Comment apprendre le langage naturel avec des réseaux de neurones?
- les machines comprennent le langage binaire
- les réseaux de neurones doivent recevoir en entrée des données continues
- le texte est représenté par des symboles discrets (lettres, chiffres, caractères spéciaux, etc.)
*Problème :* avec ASCII, l'encodage binaire, un mot n'est pas défini par ses lettres, impossibilité d'apprendre le sens d'un mot avec binaire. (ex chouette #sym.eq.not brouette).
*Solution :* encodage one-hot : grâce au word embeddings un graph basé sur le sens tous les mots va se former.
Pour cela : on prend la probabilité de coocurrence P(c/w), puis on réduit les dimensions trouvées pour être + ou - précis dans la compréhension (grâce à la SVD).
#sym.arrow une méthode efficace mais peu efficiente (ça a pris 4 mois pour s'entraîner sur Wikipedia).
==== word2vec (2013)
- modèle linéaire
- tricks pour améliorer l'apprentissage des mots rares
- code open source en C
- apprentissages de word embeddings en quelques minutes
Exemple : déterminer si un avis est positif ou négatif.
=== Réseaux récurrents
- adapté au langage, qui est séquentiel
2014 : premiers réseaux de neurones récurrents pour la traduction
automatique
=== Long-Short Term Memory (LSTM) Network (traduction)
Problème de l'époque : apprentissage des réseaux récurrents difficile pour les longues
séquences.
Une idée des années 90 refait surface: LSTM networks.
2016: Google Translate opte pour un modèle de traduction neuronal basé sur les LSTM
==== Limites des LSTM-RNN
- problème d'optimisation
- modèles séquentiels difficilement parallélisables
- architecture peu efficace sur GPU
- temps d'apprentissage + long
=== Transformer: Attention Is All You Need
- 2017: nouvelle architecture basée uniquement sur le mécanisme d’attention
- efficace sur GPU (entraînement + rapide)
- les RRN n'ont pas dit leur dernier mot (transformer + rapide en entraînement mais gourmands en mémoire)
- Mars 2024: Google DeepMind présente deux nouveaux modèles de langue basés sur des RNNs
*Mécanisme d'attention :* fait attention à n'importance des mots en fonction du contexte des mots en l'entourant.
= Supervision et apprentissage automatique
== Apprentissage supervisé
Une fois qu'un jeu de données est disponible, les chercheurs la divise en 2 sous-ensembles :
- jeu d'entraînement
- jeu d'évaluation
=== Des avancées et des limites
- biais de sélection des données
- biais des annotations des données
- coût de l'annotation des données (contraîntes de temps : ex. annotation de contrats juridiques 1/4 de temps juste pour les annoter).
== Apprentissage auto-supervisé
<NAME> “Cake Analogy” : la grosse partie du gâteau est faite avec un apprentissage non supervisé, et le glaçage, la cerise, est faite avec un peu d'apprentissage supervisé.
=== Apprentissage des données d'entrée
- apprendre à prédire le mot d’après, ou les mots cachés
- GPT (Generative Pre-Trained Transformer) #sym.arrow prédire le mot suivant
- apprendre des images avec des tâches "prétextes" prédéfinies (rotation, mettre en couleur)
=== Apprentissage discriminatif
utilise un signal discriminant entre les images, permet de classifier les images
=== Apprentissage contrastif
Apprendre à déterminer si une paire d'image est positive ou pas (donc si les deux images sont de la même catégorie) \
On donne des paires d'images positives, c'est-à-dire d'un même set, et des paires d'images négatives. Ensuite pour continuer à l'entraîner on lui donne des paires avec une image A et cette image A retournée, et on vérifie si le résultat est bien "positif" (c'est les tâches prétextes).
Exemple : *modèle CLIP*, auto-supervision avec 400M de paires (image, description) collectées sur le web. Performances équivalentes à ImageNet. Meilleures généralisation des données inconnues.
== Apprentissage par instruction (objectif: alignement)
Les modèles basés sur l'apprentissage auto sont limités, ils ne savent que prédire le mot suivant.
*Solution : s'aligner sur les attentes des utilisateurs* :
#box(
stroke: 1pt + rgb(34, 102, 153),
width: 100%,
fill: rgb(34, 102, 153, 30),
inset: 7pt,
text(fill : black, [
#pad(top: 1pt)[
Instruction: Traduit la phrase suivante en Français. \
Observation: The cat sat on the mat. \
Label: [...prédit par le modèle...]]
]))
Cependant, les données annotées restent coûteuses et limitées. Ainsi, on peut utiliser d'autres modèles pré-entraînés pour générer des instructions.
Exemple : *Alpaca dataset,* 52 000 instructions générées avec GPT-3.5 à partir de 175 instructions.
*Solution améliorée : s'aligner sur les domaines spécialisés *
Exemple : Google Med-PaLM (modèle sous license propriétaire) adapté depuis PaLM.
*A intégrer à la solution : s'aligner sur les valeurs humaines*
- le web contient des données toxiques ou mensongères
- human in the loop : humains qui vérifient les données
=== Les limites de l'alignement
- Gemini image était woke
- il est actuellement dans les faits impossible de sortir de la supervision
- les modèles d'IA qu'on utilise ont été supervisés avec des biais arbitraires
- la seule piste qu'on a est de rendre explicite les valeurs qui sous-tendent le process d'annotation et d'alignement#footnote[basiquement on va juste dire "oui j'assume que notre modèle est biaisé et pense que la terre est plate, désolé on y peut rien nos données venaient des platistes"]
= IA Generative & sphère informelle
== Quelques exemples
- <NAME> en doudoune, généré par un employé du BTB à Chicago, relayée sur twitter
- <NAME> arrêté par la police de NY, dans un contexte tendu
- <NAME> au milieu de la réforme des retraites
#sym.arrow À Davos, tous les regards sont sur les deepfakes.
== Generateur d'images par IA
=== IA generative VS IA discriminative
- Discriminatif : focus sur les caractéristiques qui distinguent les différentes catégories (objectif : reconnaître une image)
- Génératif : modélisation de la distribution des données
=== Type de modèles pour la distribution d'images.
*Auto-Encodeur : *\
Apprendre une distribution approximée d'un ensemble de points ayant une distribution inconnue.
Cool : compresser des images dans un espace réduit, apprentissage auto-supervisé.\
Pas cool : Qualité mauvaise, manque de contrôle sur la génération (on ne peut pas dire où sont les yeux d'une image par ex).
*Auto-Encodeur variationnel * \
Apprentissage d'une représentation probabiliste et continue de l'entrée \
Le décodeur génère une image à partir d'une variable latente
Cool : Représentation plus structurée, images + diversifiées, bcp plus de contrôle \
Pas cool : On génère l'image en une étape (VAE)
* Modèle de diffusion * \
On génère l'image en plusieurs étapes. \
#sym.arrow.curve On apprend à prédire le bruit d'une image avec un encodeur, qui "bruite" l'image au fur et à mesure (à la fin on a un espace réduit ducoup), après, on apprend à reconstruire l'image avec un décodeur. \
forward diffusion : obtenir le bruit à partir de l'image \
reverse diffusion : l'inverse.
On a une chaîne de markov, avec des étapes petit à petit.
=== Entrainement pour modèle de diffusion
1. Prend une image
2. Générer du niveau de bruit
3. On choisit un niveau de bruit
4. Ajouter le bruit à l'image
5. On lui demande de prédire le bruit qui a été ajouté à l'image. \
#sym.arrow.curve Une fois entraîné, on peut prédire l'image suivante en retirant le bruit que le modèle pense qui a été ajouté.
=== Conditionner la génération d'image
On va ajouter du texte à notre jeu d'entrainement.\
#sym.arrow.curve On utilise des modèles qui ont déjà labelisé les images (modèle CLIP) #sym.arrow Chaque mot est représenté par du text embedding. \
#sym.arrow.curve Le prédicteur de bruit avec mécanisme d'intention va générer une image aléatoire conditionnée avec le texte entré \
#sym.arrow.curve On peut aussi conditionner en disant "eh à cet endroit tu me met un train"#footnote[Si vous voulez voir à quoi ça ressemble concrètement, vous pouvez aller voir Nvidia Canvas]
=== Principaux modèles de diffusion text-to-image
1. Midjourney (v1 #sym.arrow v6)
2. Dalle-E (2 #sym.arrow 3)
3. Imagen ( #sym.arrow 2)
4. Stable diffusion (v1 #sym.arrow v3)
=== Controverse de génération d'image
Des scientifiques ont publié un papier avec des images générées par Midjourney, ils se sont fait taper dessus
== Fausses images et sphère informationnelle
Jusqu'à présent, il n'y a pas eu de répercussions géopolitiques majeures#footnote[où on ne le sait pas encore MDR], mais ces images génères des inquiétudes. \
#sym.arrow.curve Elles mettent à mal la recherche d'image inversée et l'analyse des retouches (les 2 check des sécurités)
Ces fausses images continuent de mettre de l'huile sur le feu dans un monde avec déjà beaucoup de guerres.
Point de départ de la guerre informationnelle : *Guerre du Golfe*, quand le gouvernement du Koweit engage de nombreuses ressources pour mobiliser l'opinion publique contre <NAME> (ex. témoignage vidéo de Nahira, vu par 60,000,000 d'américains *qui était un faux !*). \
#sym.arrow.r.curve aide bcp le Koweit
Tous les pays commencent à prendre au sérieux cette domination informationnelle.
*Début années 1990 :* Iran, mise en place de l'IRIB. un peu comme CNN, 1Md de budget, 15k employés, mais l'information est orientée pour aller dans le sens de l'islam
*1996* : fondation d'Al Jazeera par le Qatar, sur le modèle aussi de CNN, constitue un canal pour les déclarations du Hamas, du Hezbollah (sud Liban), et d'Al-Qaïda.
*1998* : opération bouclier doré (contrôle de l'accès des internautes chinois aux contenus étrangers). En 2022 : 73% du trafic internet chinois provient de l'intérieur de ses frontières !
*1994* : système SORM (Système pour Activité d'Enquête Opératoire) permet d'intercepter l'ensemble des communications sur l'ensemble des territoires russophones.
*2005* : lancement du média Russia Today (propagande)
*2016* : grande campagne de déstabilisation informationnelle, lors de la campagne électoral entre Trump et <NAME> (piratage des boîtes mails d'<NAME>)
Situation préoccupante de chaos informationnelle.
2024 : Annonce faite par le Hamas (bombardement de l'hopital Al-Ahli) #sym.arrow relayée par la presse internationale... alors que c'était faux. Cela a conduit à une très forte augmentation des manifestations pro-palestine.
== Mais il reste de l'espoir !
Le propriétaire du journal The Guardian est dirigé par une fondation, à but non lucratif. Il assure une indépendance d'écriture, car les journalistes n'ont pas besoin de "rechercher le scoop".
De même Le Temps est sorti d'une entreprise pour se faire racheter par une fondation, Aventinus, créée par des personnes riches pour soutenir la presse romande. *le comité de rédaction est séparé du conseil de fondation !* pas de conflit d'intérêt.
|
|
https://github.com/SkiFire13/typst-touying-unipd | https://raw.githubusercontent.com/SkiFire13/typst-touying-unipd/master/example.typ | typst | MIT License | #import "@preview/touying:0.5.2"
#import "unipd.typ": *
#show: unipd-theme
#title-slide(
authors: "Me and myself",
title: "Some kinda short title",
subtitle: lorem(12),
date: "February 2024",
)
== Bar
=== Baz
#slide[
Altro
]
== Qux
#slide[
- Foo
- Bar
- Baz
- Cafrax
- Qux
- Brux?
]
#new-section-slide("Introduction")
#slide[
== Static text
Here's some code:
```sh
#!/bin/bash
sleep 2
echo "Hello World"
exit 0
```
]
#slide[
== Static text
#lorem(20)
#uncover("2-")[This appears after one slide]
]
#new-section-slide("Conclusions")
#slide[
== Qux
_baz_\
*Fizz*\
`Fuzz`
]
#slide[
#normal-block[Normal block][body]
#alert-block[Alert block][body]
#example-block[Example block][
body
but a bit longer
]
]
#filled-slide[
Thank you for your attention
]
|
https://github.com/flavio20002/typst-presentation-minimal-template | https://raw.githubusercontent.com/flavio20002/typst-presentation-minimal-template/main/README.md | markdown | MIT No Attribution | # minimal presentation
A modern minimalistic presentation template ready to use.
## Usage
You can use this template in the Typst web app by clicking "Start from template"
on the dashboard and searching for `minimal-presentation`.
Alternatively, you can use the CLI to kick this project off using the command
```
typst init @preview/minimal-presentation
```
Typst will create a new directory with all the files needed to get you started.
## Configuration
This template exports the `project` function with the following named arguments:
- `title`: The book's title as content.
- `sub-title`: The book's subtitle as content.
- `author`: Content or an array of content to specify the author.
- `aspect-ratio`: Defaults to `16-9`. Can be also `4-3`.
The function also accepts a single, positional argument for the body of the
book.
The template will initialize your package with a sample call to the `project`
function in a show rule. If you, however, want to change an existing project to
use this template, you can add a show rule like this at the top of your file:
```typ
#import "@preview/minimal-presentation:0.1.0": *
#set text(font: "Lato")
#show math.equation: set text(font: "Lato Math")
#show raw: set text(font: "Fira Code")
#show: project.with(
title: "Minimalist presentation template",
sub-title: "This is where your presentation begins",
author: "<NAME>",
date: "10/08/2023",
index-title: "Contents",
logo: image("./logo.svg"),
logo-light: image("./logo_light.svg"),
cover: image("./image_3.jpg")
)
= This is a section
== This is a slide title
#lorem(10)
- #lorem(10)
- #lorem(10)
- #lorem(10)
- #lorem(10)
== One column image
#figure(
image("image_1.jpg", height: 10.5cm),
caption: [An image],
) <image_label>
== Two columns image
#columns-content()[
#figure(
image("image_1.jpg", width: 100%),
caption: [An image],
) <image_label_1>
][
#figure(
image("image_1.jpg", width: 100%),
caption: [An image],
) <image_label_2>
]
== Two columns
#columns-content()[
- #lorem(10)
- #lorem(10)
- #lorem(10)
][
#figure(
image("image_3.jpg", width: 100%),
caption: [An image],
) <image_label_3>
]
= This is a section
== This is a slide title
#lorem(10)
= This is a section
== This is a slide title
#lorem(10)
= This is a section
== This is a slide title
#lorem(10)
= This is a very v v v v v v v v v v v v v v v v v v v v long section
== This is a very v v v v v v v v v v v v v v v v v v v v long slide title
= sub-title test
== Slide title
#lorem(50)
=== Slide sub-title 1
#lorem(50)
=== Slide sub-title 2
#lorem(50)
```
## Fonts
You can use the font selected by the author of this plugin, by download theme at the following link:
https://github.com/flavio20002/typst-presentation-minimal-template/tree/main/fonts
You can then import thme in your system, import them in the typst web app or just put them in a folder and launch the compilation with the following argoument:
```
typst watch main.typ --root . --font-path fonts
``` |
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Analyse_1_Serie_3.typ | typst | #import "@preview/bubble:0.1.0": *
#import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge
#import "@preview/cetz:0.2.2": canvas, draw, tree
#import "@preview/cheq:0.1.0": checklist
#import "@preview/typpuccino:0.1.0": macchiato
#import "@preview/wordometer:0.1.1": *
#import "@preview/tablem:0.1.0": tablem
#show: bubble.with(
title: "Analyse 1 Série 3",
subtitle: "16/10/2024",
author: "<NAME>",
affiliation: "EPFL",
year: "2024/2025",
class: "Génie Mécanique",
logo: image("JOJO_magazine_Spring_2022_cover-min-modified.png"),
)
#set page(footer: context [
#set text(8pt)
#set align(center)
#text("page "+ counter(page).display())
]
)
#set heading(numbering: "1.1")
#show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em)
= Exercice 1
==
+ $A={n "impair", n <= 19}$
+ $V={n "pair", n in NN}union{n, n >= 41}$
+ $C=({n "pair"}sect{n <= 10})union({n "impair"}sect{n <= 53})$
+ $N=61$
==
+ $A'={1,2,8}$
+ $B'={5,8,12,14,16,17,20,21}$
+
+ $C'={6,9,13,15,19}union{n >= 22}$
+ $N=25$
= Exercice 2
$ x_(n+1) - x_n = (a n+a+b)/(c n+c+d) - (a n+b)/(c n+d) $
$ = (a c n^2+a c n+a n d +a d+b c n+b d-a c n^2 - a c n- a n d -b c n- b c-b d)/((c n+d)(c n+c+d)) $
$ =(a d - b c)/((c n+d)(c(n+1)+d)) $
Ansi $x_(n+1)-x_n >= 0 arrow.l.r.double.long a d-b c>=0$
= Exercice 3
==
On sait que $a_(n+1) - a_n >= 0$ car $a d - b c = 1 - 0 = 1$
$ abs(n/n+1 -1) = 1/(n+1) $
$ 1/(n+1) <= epsilon $
$ 1/(n+1) <= 1/10 $
$ 9 <= n $
Si on pose $N = 9 space forall n >= N space abs(a_n-l) <= epsilon$
==
$ abs(n/n+1 - 1) <= epsilon $
$ 1/(n+1) <= 1/100 $
$ 99 <= n $
Si on pose $N = 99 space forall n >= N space abs(a_n-l) <= epsilon$
==
$ abs((-1)^n/n - 0) <= epsilon $
$ 1/n <= epsilon $
$ 1/n <= 1/100 $
$ 100 <= n $
Si on pose $N = 100 space forall n >= N space abs(a_n-l) <= epsilon$
==
$ abs(n/(n^2 +1) - 0) <= epsilon $
$ n/(n^2+1) <= 1/4 $
$ 4n <= n^2+1 $
$ 0 <= n^2+1 - 4n $
Dans $RR$
$ Delta = 16 - 4 = 12 = (2sqrt(3))^2 $
$ x_1 = (4 + 2sqrt(3))/2 = 2+sqrt(3) approx 3.73$
$ x_2 = 4-2sqrt(3)/2 = 2-sqrt(3) $
Soit $N = 4 space forall n >= N space abs(a_n-l)<=epsilon$
==
$ abs(2n/(n+1)-1) <= epsilon $
Pour $n >= 1$
$ (n - 1)/(n+1) <= epsilon $
$ n-1 <= n+1(3/4) $
$ 0 <= 3/4(n) + 3/4 + 1 - n $
$ 0 <= -1/4(n) + 7/4 $
$ -7/4 <= -1/4(n) $
$ 7 >= n $
$ {n in NN, n <= 7} $
= Exercice 4
$lim(a_2k) = L arrow.l.r.double.long exists N_1, forall epsilon>0 abs(a_2k-L) <= epsilon $
$lim(a_(2k+1)) = L arrow.l.r.double.long exists N_2, forall epsilon>0 abs(a_(2k+1)-L) <= epsilon $
Soit $N = max(N_1, N_2)$
Ainsi $forall n >= N$
Si $n "pair"$ on a $n = 2k, k in NN$ et $abs(a_n - L)=abs(a_(2k)-L) <= epsilon$
Si $n "impair"$ on a $n=2k +1, k in NN$ et $abs(a_n - L)=abs(a_(2k+1)-L) <= epsilon$
Ainsi $ abs(a_n -L )<= epsilon, forall n >= N$
= Exercice 5
$ abs(x_n - l) = abs(x_n - 1) = 10^(-n) $
On pose $ epsilon >= 10^(-n) $
$ n >= -log(epsilon)$
Alors Si $N = round(-log(epsilon)) + 1$
$ forall n >= N, abs(x_n - 1) <= epsilon $
= Exercice 6
==
$ abs((2n-3)/(3n+7) - 2/3) = abs(-23/3(3n+7)) = 23/3(3n+7) $
$ 23/3(3n+7) <= epsilon $
$ 23/(3 epsilon) <=3n+7 $
$ (23-21epsilon)/(9 epsilon) <= n $
Soit $N = round((23-21epsilon)/(9 epsilon)) +1$
$forall n>= N, abs(x_n -2/3) <= epsilon$
==
$ abs((a n+b)/(c n+d) - (a/c)) = abs((a c n + b c - a c n -d a)/c(c n+d)) = abs( b c - d a)/c(c n+d)) = abs(d a-b c)/(c(c n+d) $
$ abs(a d - b c)/c(c n+d) <= epsilon $
$ 1/c(abs(a d - b c)/(c epsilon) - d) <= n$
Soit $N = round(1/c(abs(a d - b c)/(c epsilon) - d))$
$ forall n >= N, abs(x_n - a/c) <= epsilon $
= Exercice 7
==
Equivalent
==
Equivalent
==
Equivalent
==
Equivalent
==
Equivalent
= Exercice 8
==
Faux
==
Faux
==
Faux
==
Vrai
==
Vrai
==
Faux
==
Vrai
==
Faux
==
Faux
==
Faux
= Exercice 9
==
$ 0 <= abs(cos(sqrt(n))/n) <= 1/n $
$ abs(1/n) <= epsilon $
$ 1/epsilon <= n $
Soit $N = round(1/epsilon) $
$ forall n >= N, abs(1/n - 0) <= epsilon $
Ainsi $limits("lim")_(n arrow +infinity) 0 = 0$ et $limits("lim")_(n arrow +infinity) 1/n = 0$
donc $limits("lim")_(n arrow +infinity) abs(cos(sqrt(n))/n) = 0 = limits("lim")_(n arrow +infinity) cos(sqrt(n))/n$
==
$ 0 <= n!/n^n $
$ 1(2)(3)(4)(5)(...)(n)/(n)(n)(n)(n)(...) = (1/n)(2/n)(3/n)(...) <= 1/n $
Ainsi $limits("lim")_(n arrow +infinity) 0 = 0$ et $limits("lim")_(n arrow +infinity) 1/n = 0$
$ limits("lim")_(n arrow +infinity) n!/n^n = 0 $
==
$ root(n, 1+2^n) >= root(n, 2^n) = 2 $
$ root(n, 1+2^n) <= root(n, 2^n+1) = 2^((n+1)/n) $
On sait que $limits("lim")_(n arrow +infinity) (n+1)/n = 1$
Ainsi $limits("lim")_(n arrow +infinity) 2^((n+1)/n) = 2$
D'après le théorème des gendarmes $ limits("lim")_(n arrow +infinity) root(n, 1+2^n) = 2 $
= Exercice 10
==
$ x >= 0 $
$ 1+x >= 1 $
$ sqrt(1+x) >= 1 $
$ sqrt(1+x) = sqrt(1+2x/2) <= sqrt(1+2x/2 + (x/2)^2) = sqrt((1+x/2)^2) = 1+x/2 $
==
$ sqrt(n^2+2)/2n = sqrt(n^2(1+2/n^2))/2n = sqrt(1+2/n^2)/2$
Soit $x = 2/n^2$
$limits("lim")_(n arrow +infinity) sqrt(1+2/n^2) = 1$
$limits("lim")_(n arrow +infinity) sqrt(n^2+2)/2n = 1/2$
= Exercice 11
$ limits("lim")_(n arrow +infinity) a_n = 3/1 = 3 $
==
$ limits("lim")_(n arrow +infinity) 1/a_n = 1/3 $
==
$ limits("lim")_(n arrow +infinity) (a_n/3+3/a_n) = 1+1=2 $
==
$ limits("lim")_(n arrow +infinity) (9n^2)/(n^2+4n+4) = limits("lim")_(n arrow +infinity) (a_n)(a_n) = 3^2 = 9 $
= Exercice 12
On sait que $forall x in A x <= s, forall epsilon > 0 exists x in A, s-epsilon < x <= s $
Soit $epsilon_n = 1/n, N = 1/epsilon_n$
$ forall n>= N, s-1/n < x_n <= s $
$ -1/n< x_n-s<= 0 $
On sait que $ limits("lim")_(n arrow +infinity) -1/n = 0$
Donc d'après le théorème des gendarmes $ limits("lim")_(n arrow +infinity) x_n-s = 0 arrow.l.r.double.long forall epsilon > 0 space exists N,forall n>= N, abs(x_n-s) <= epsilon $
Ainsi $ limits("lim")_(n arrow +infinity) x_n = s $
|
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/docs/dynamic/cover.md | markdown | ---
sidebar_position: 4
---
# Cover Function
As you already know, both `uncover` and `#pause` use the `cover` function to conceal content that is not visible. So, what exactly is the `cover` function here?
## Default Cover Function: `hide`
The `cover` function is a method stored in `s.methods.cover`, which is later used by `uncover` and `#pause`.
The default `cover` function is the [hide](https://typst.app/docs/reference/layout/hide/) function. This function makes the internal content invisible without affecting the layout.
## Updating the Cover Function
In some cases, you might want to use your own `cover` function. In that case, you can set your own `cover` function using:
```typst
let s = (s.methods.update-cover)(self: s, is-method: true, cover-fn)
```
Here, if you set `is-method: false`, Touying will wrap `cover-fn` into a method for you.
## Semi-Transparent Cover Function
Touying supports a semi-transparent cover function, which can be enabled by adding:
```typst
#let s = (s.methods.enable-transparent-cover)(self: s)
```
You can adjust the transparency through the `alpha: ..` parameter.
:::warning[Warning]
Note that the `transparent-cover` here does not preserve text layout like `hide` does because it adds an extra layer of `box`, which may disrupt the original structure of the page.
:::
:::tip[Internals]
The `enable-transparent-cover` method is defined as:
```typst
#let s.methods.enable-transparent-cover = (
self: none,
constructor: rgb,
alpha: 85%,
) => {
self.methods.cover = (self: none, body) => {
utils.cover-with-rect(
fill: utils.update-alpha(
constructor: constructor,
self.page-args.fill,
alpha,
),
body
)
}
self
}
```
It creates a semi-transparent rectangular mask with the same color as the background to simulate the effect of transparent content. Here, `constructor: rgb` and `alpha: 85%` indicate the background color's construction function and transparency level, respectively.
::: |
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/algo/lectures/2024-10-08.typ | typst | = Численное интегрирование
Дана функция $y = f(x)$. Хотим посчитать $integral_a^b f(x)$.
== Метод Монте-Карло
Работает, но сходится медленно
Возьмем $sin(x), x in [0, pi]$.
Будем генерировать точки в прямоугольнике $x in [0, pi]; y in [0, pi]$ и
смотреть, сколько попало под график.
== Детерминированный метод
Разбиваем отрезок на равные кусочки:
$ a = x_0 < x_1 < ... < x_n = b $
$ x_(i + 1) - x_i = h = (b - a) / n $
Один кусок ($x in [x_i, x_(i + 1)]$) --- криволинейная трапеция. Её можно
приближать разными фигурами:
- Прямоугольником:
- $S = h dot f(x_i)$ --- метод левых прямоугольников
- $S = h dot f(x_(i + 1))$ --- метод правых прямоугольников
- $S = h dot f((x_i + x_(i + 1)) / 2)$ --- метод средних прямоугольников
- Трапецией:
- $S = h/2 (f(x_i) + f(x_(i + 1)))$
- Криволинейной трапецией (с параболой сверху):
- $S= h/6 (f(x_i) + 4f((x_i + x_(i + 1)) / 2) + f(x_(i + 1))$ --- формула
Симпсона
У формулы Симпсона сходимость на два порядка выше
=== Пример
Ищем площадь круга:
$ (x - 1)^2 + (y - 5)^2 = 9 $
Разбиваем на две полуокружности: верхнюю ($f_1 (x)$) и нижнюю ($f_2 (x)$)
$ S = integral_(-2)^4 f_1 - f_2 (x) d x $
== Сетки переменной плотности
Интегрируем верхнюю половину окружности. Будем использовать метод левых
прямоугольников. Если разрезать на четыре части, то два центральные кусочка
дают хорошее приближение, а два крайних --- очень плохое.
Вывод: сетка с постоянным шагом --- часто плохой вариант.
Алгоритм:
- Делим на несколько частей
- Проверяем, на каких кусках получили хорошее приближение, а на каких плохое.
Для этого всё же измельчаем сетку в этом месте и проверяем, сильно ли
изменилось приближение. Если слабо, то приближение хорошее:
$ abs(S_1 - S_2) < epsilon $
- Там, где получили плохое приближение, запускается от него рекурсивно.
Метод хорошо сходится, но мы плохо можем оценивать приближение.
== Задача (похожая на 2-ую и 3-ю из контеста)
Есть набор фигур на экране. Найти площадь объединения
Методы решения (по увеличению эффективности):
+ *Монте-Карло*: плохо сходится
+ *Сетка*:
Разрежем на сеточку (по вертикали и горизонтали).
Смотрим на центр: считаем, что если входит центр, то входит весь
прямоугольник
+ *Квадродерево*:
- Режем на сетку. Смотрим на каждый квадратик.
- Если квадратик заполнен полностью или полностью пустой, то сразу добавляем
его в ответ
- Иначе (если заполнен частично), то продолжаем рекурсивно.
- Останавливаемся, если получили квадратик площади меньше $epsilon$
+ *Вертикальные полосы переменной плотности + Сканлайн*
- Режем на полоски, которые дают элементарные элементарные
огибающие. Можно порезать и сильнее.
- Каждая фигура идет от начала до конца полосы (то есть по горизонтали начинается и
заканчивается либо на границе полосы, либо вне её).
- Внутри каждой полосы, заменяем каждую фигуру на прямоугольник, дальше
сканлайном ищем площадь пересечения.
- Потом делим вертикальную линию пополам, проверяем хорошее ли получилось
приближение, если плохое, запускаемся дальше
|
|
https://github.com/linhduongtuan/BKHN-Thesis_template_typst | https://raw.githubusercontent.com/linhduongtuan/BKHN-Thesis_template_typst/main/template/abstract.typ | typst | Apache License 2.0 | #import "font.typ": *
#import "../contents/info.typ": *
#import "../contents/abstract.typ": *
#show heading : it => {
set align(center)
set text(font: arial, size: font_size.large)
it
par(leading: 1.5em)[#text(size:0.0em)[#h(0.0em)]]
}
// format footer
#set page(footer: [
#set align(center)
#set text(size: 10pt, baseline: -3pt)
#counter(page).display(
"I",
)
] )
#pagebreak()
// Abstract written by Vietnamese
#heading(level: 1, outlined: false)[TÓM TĂT]
#v(2em)
#v(2em)
#par(
justify: true,
leading: 1.5em,
first-line-indent: 2em)[#text(font: arial, size: font_size.footnotesize)[#abstract_vn]]
#v(2em)
#par(first-line-indent: 0em)[
#text(weight: "bold", font: arial, size: font_size.footnotesize)[
TỪ KHOÁ: ]
#text(font: arial, size: font_size.footnotesize)[#keywords_vn.join(";") ]
]
#pagebreak()
// Abstract written by English
#heading(level: 1, outlined: false)[ABSTRACT]
#v(2em)
#v(2em)
#par(justify: true,
leading: 1.5em,
first-line-indent: 2em)[#text(font: arial, size: font_size.footnotesize)[#abstract_en]]
#v(2em)
#par(first-line-indent: 0em)[
#text(font: "Times New Roman", size: font_size.footnotesize, weight: "bold")[
KEYWORDS: ]
#text(font: "Times New Roman", size: font_size.footnotesize)[#keywords_en.join("; ") ]
]
//#pagebreak()
|
https://github.com/dainbow/MatGos | https://raw.githubusercontent.com/dainbow/MatGos/master/themes/32.typ | typst | #import "../conf.typ": *
= Математическое ожидание и дисперсия случайной величины, их свойства. Вычисление для нормального распределения.
== Математическое ожидание и дисперсия случайной величины, их свойства.
#definition[
Система $cal(F)$ подмножеств $Omega$ называется *алгеброй*, если
+ $Omega in cal(F)$
+ $A in cal(F) => overline(A) := (Omega without A) in cal(F)$
+ $A, B in cal(F) => A sect B in cal(F)$
]
#definition[
Система $cal(F)$ подмножеств $Omega$ называется *$sigma$-алгеброй*, если
+ $cal(F)$ -- алгебра
+ $forall seq(A) subset cal(F) => union.big_(n = 1)^oo A_n in cal(F)$
]
#definition[
$P$ называется *вероятностной мерой* на $(Omega, cal(F))$, если $P : cal(F) -> [0, 1]$,
удовлетворяющая свойствам:
+ $P(Omega) = 1$
+ $forall seq(A) : space P(union.sq_(n = 1)^oo A_n) = sum_(n = 1)^oo P(A_n)$
]
#definition[
*Вероятностное пространство* -- это тройка $(Omega, cal(F), P)$, где
- $Omega$ -- множество *элементарных исходов*
- $cal(F)$ -- $sigma$-алгебра подмножеств $Omega$, элементы $cal(F)$ называются
*событиями*
- $P$ -- вероятностная мера на измеримом пространстве $(Omega, cal(F))$
]
Далее будем предполагать, что $(E, cal(E))$ -- произвольное измеримое
пространство.
#definition[
*Борелевской сигма-алгеброй* называется наименьшая $sigma$-алгебра над $RR$,
содержащая все интервалы (или отрезки).
Обозначение -- $cal(B) (RR)$
]
#definition[
Отображение $X : Omega -> E$ называется *случайным элементом*, если оно
измеримо, то есть
#eq[
$forall B in cal(E) : space X^(-1) (B) = {omega | X(omega) in B} in cal(F)$
]
]
#definition[
Если $(E, cal(E)) = (RR, cal(B) (RR))$, то случайный элемент называется
*случайной величиной*.
]
#definition[
Если $(E, cal(E)) = (RR^n, cal(B) (RR^n))$, то случайный элемент называется
*случайным вектором*.
]
#definition[
*Распределением* случайной величины (вектора) $xi$ называется вероятностная мера $P_xi$ на $(RR, cal(B)(RR))$ ($(RR^n, cal(B) (RR^n))$),
определённая по правилу:
#eq[
$forall B in cal(B)(RR) : space P_xi (B) := P(xi in B) = P({omega in Omega | xi(omega) in B})$
]
]
#definition[
*Простой случайной величиной* называется случайная величина $xi$:
#eq[
$xi(omega) = sum_(k = 1)^n x_k II_(A_k) (omega)$
]
где $x_1, ..., x_n$ -- все различные значения $xi$, а события $A_1, ..., A_n$ образуют
разбиение $Omega$.
]
#definition[
*Математическим ожиданием* простой случайной величины $xi$ называется величина $EE xi = sum_(k = 1)^n x_k P_xi (A_k)$
]
#lemma(
"Свойства матожидания",
)[
Пусть $xi$ и $eta$ -- простые случайные величины. Тогда
+ Линейность. Если $a, b in RR$, то $EE(a xi + b eta) = a EE xi + b EE eta$
+ Если $xi >= 0$, то $EE xi >= 0$
+ Если $xi >= eta$, то $EE xi >= EE eta$
]
#definition[
Пусть $xi >= 0$ -- неотрицательная случайная величина. Рассмотрим
последовательность простых неотрицательных случайных величин $seq(xi)$, которой
монотонно к ней сходится.
*Математическим ожиданием* неотрицательной случайной величины $xi$ называется
величина $EE xi = lim_(n -> oo) EE xi_n$
]
#definition[
Пусть $xi$ -- произвольная случайная величина. Рассмотрим $xi^= = max(xi, 0); xi^- = max(-xi, 0)$.
Это неотрицательные случайные величины, при этом $xi = xi^+ - xi^-$.
+ Если $EE xi^+ < +oo, EE xi^- < +oo$, то математическим ожиданием величины $xi$ назовём $EE xi = EE xi^+ - EE xi^-$
+ Если $EE xi^+ = +oo, EE xi^- = +oo$, то математическое ожидание случайной
величины $xi$ не определено
+ Иначе $EE xi^plus.minus = +oo$. Тогда математическим ожиданием случайной
величины $xi$ будем считать $plus.minus oo$
]
#note[
Математическое ожидание -- это интеграл Лебега по вероятностной мере $P$.
]
#lemma(
"Дополнительные свойства матожидания",
)[
+ $abs(EE xi) <= EE abs(xi)$
+ Если $xi = 0$ почти наверное, то $EE xi = 0$
+ Если $xi = eta$ почти наверное и $EE xi$ конечно, то $EE eta$ конечно и $EE xi = EE eta$
+ Если $xi >= 0$ и $EE xi = 0$, то $xi = 0$ почти наверное
+ Пусть $EE eta$ и $EE eta$ конечны. Тогда
#eq[
$forall A in cal(F) : EE (xi II_A) <= EE(eta II_A) => xi <= eta$
]
]
#proof[
Все свойства очевидным образом следует из соответствующих свойств интеграла
Лебега.
]
#definition[
Если $EE xi$ конечно, то *дисперсией* случайной величины $xi$ называется
#eq[
$VV xi = EE (xi - EE xi)^2$
]
]
#lemma(
"Свойства дисперсии",
)[
+ $forall c in RR : space VV(c xi) = c^2 VV(xi); quad VV(xi + c) = VV(xi)$
+ $VV xi = EE xi^2 - (EE xi)^2$
]
#proof[
Очевидно следуют из свойств матожидания.
]
== Вычисление для нормального распределения
#definition[
*Функцией распределения* вероятностной меры $P$ на $RR$ называется
#eq[
$F(x) = P((-oo, x])$
]
]
#definition[
Пусть $P$ -- вероятностная мера на $(RR, cal(B)(RR))$, а $F$ -- её функция
распределения.
Она называется *абсолютно непрерывной*, если
#eq[
$exists p(t) >= 0 : forall x in RR : integral_RR p(t) dif t = 1 and F(x) = integral_(-oo)^x p(t) dif t$
]
В этом случае $p(t)$ называтся *плотностью* функции распределения $F$ и меры $P$.
]
#definition[
Распределение называется *нормальным* c параметрами $a in RR, sigma in RR^(++)$,
если его плотность имеет вид
#eq[
$p(x) = 1 / sqrt(2 pi sigma^2) exp(- (x - a)^2 / (2 sigma^2))$
]
Обозначение -- $cal(N)(a, sigma^2)$
]
#proposition[
Если $xi$ имеет нормальное распределение $cal(N)(a, sigma)$, то
#eq[
$EE xi = a$
]
]
#proof[
#eq[
$EE xi = 1 / sqrt(2 pi sigma^2) integral_RR x exp(- (x - a)^2 / (2 sigma^2)) dif mu(x) = attach(=, t: t = (x - a) / sigma) 1 / sqrt(2 pi) integral_RR (sigma t + a) e^(-t^2 / 2) dif mu(t) = \
1 / sqrt(2 pi) (integral_RR underbrace(sigma t e^(-t^2 / 2), "нечётная") dif mu(t) + integral_RR a e^(-t^2 / 2) dif mu(t)) = a / sqrt(2 pi) integral_RR e^(-t^2) dif mu(t) $
]
Получили интеграл Эйлера-Пуассона. Напомним, как его вычислять:
#eq[
$\
(integral_RR e^(-x^2) dif x)^2 = (integral_RR e^(-x^2) dif x)(integral_RR e^(-y^2) dif y) = integral.double_(RR^2) e^(-x^2 - y^2) dif x dif y attach(=, t: cases(x = rho cos phi, y = rho sin phi)) 1 / 2 integral_0^(2pi)integral_0^oo e^(-rho^2) dif rho^2 dif phi = \
1 / 2 integral_0^(2pi) dif phi integral_0^oo e^(-t) dif t = pi $
]
Мы вычисляли квадрат интеграла, а значит сам интеграл равен $sqrt(pi)$.
Таким образом матожидание равно $a$.
]
|
|
https://github.com/maucejo/book_template | https://raw.githubusercontent.com/maucejo/book_template/main/README.md | markdown | MIT License | # Modèle Typst pour les mémoires Cnam
[![Generic badge](https://img.shields.io/badge/Version-0.2.1-cornflowerblue.svg)]()
[![MIT License](https://img.shields.io/badge/License-MIT-forestgreen)](https://github.com/maucejo/Cnam_thesis_template/blob/main/LICENSE)
[![User Manual](https://img.shields.io/badge/doc-.pdf-mediumpurple)](https://github.com/maucejo/Cnam_thesis_template/blob/main/docs/manual.pdf)
Ce dépôt contient un modèle en langage Typst pour la rédaction de mémoire de type thèse et HDR pour le Cnam.
## Usage
Pour utiliser le modèle, il faut l'importer dans votre fichier principal `typ` en utilisant la commande suivante :
```typ
#import "./template/thesistemplate.typ": *
```
Pour plus d'informations, veuillez consulter le [manuel](https://github.com/maucejo/Phd_template/blob/main/docs/manual.pdf).
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/rivet/0.1.0/src/renderer.typ | typst | Apache License 2.0 | #import "@preview/cetz:0.2.2": canvas, draw
#import "range.typ" as rng
#import "structure.typ"
#import "vec.typ"
#let draw-rect(color, x, y, width, height, thickness: 0) = {
let fill = none
let stroke = color + thickness * 1pt
if thickness == 0 {
fill = color
stroke = none
}
draw.rect((x, -y), (x + width, -y - height), fill: fill, stroke: stroke)
}
#let draw-text(
txt,
color,
x,
y,
anchor: "center",
font: none,
italic: false,
size: 1em,
fill: none
) = {
let text-params = (:)
if font != none {
text-params.insert("font", font)
}
if italic {
text-params.insert("style", "italic")
}
draw.content(
(x, -y),
text(txt, fill: color, size: size, ..text-params),
anchor: anchor,
stroke: none
)
}
#let draw-line(color, a, b) = {
let (x0, y0) = a
let (x1, y1) = b
draw.line((x0, -y0), (x1, -y1), stroke: color)
}
#let draw-lines(color, ..pts) = {
let pts = pts.pos().map(pt => (pt.at(0), -pt.at(1)))
draw.line(..pts, stroke: color)
}
#let draw-poly(color, ..pts, thickness: 0) = {
let pts = pts.pos().map(pt => (pt.at(0), -pt.at(1)))
let params = (
stroke: (paint: color, thickness: thickness),
fill: none
)
if thickness == 0 {
params = (
stroke: none,
fill: color
)
}
draw.line(..pts, ..params)
}
#let draw-underbracket(config, start, end, bits-y) = {
let bit-w = config.bit-width
let bit-h = config.bit-height
let x0 = start + bit-w / 2
let x1 = end - bit-w / 2
let y0 = bits-y + bit-h * 1.25
let y1 = bits-y + bit-h * 1.5
let col = config.link-color
draw-lines(col, (x0, y0), (x0, y1), (x1, y1), (x1, y0))
}
#let draw-link(
config,
start-x,
start-y,
end-x,
end-y
) = {
let bit-h = config.bit-height
let arrow-margin = config.arrow-margin
if end-x > start-x {
end-x -= arrow-margin
} else {
end-x += arrow-margin
}
draw-lines(
config.link-color,
(start-x, start-y + bit-h * 1.5),
(start-x, end-y + bit-h / 2),
(end-x, end-y + bit-h / 2),
)
}
#let draw-values(config, values, desc-x, desc-y) = {
let shapes = ()
let txt-col = config.text-color
let bit-w = config.bit-height // Why ? I don't remember
let gap = config.values-gap
for (val, desc) in values.pairs().sorted(key: p => p.first()) {
desc-y += gap
let txt = val + " = " + desc
shapes += draw-text(
txt, txt-col, desc-x + bit-w / 2, desc-y,
anchor: "north-west",
font: config.italic-font-family,
italic: true,
size: config.italic-font-size
)
desc-y += config.italic-font-size / 1.2pt
}
return (shapes, desc-x, desc-y)
}
#let draw-description(
config,
range_,
start-x,
start-y,
width,
desc-x,
desc-y
) = {
let shapes = ()
let bit-w = config.bit-width
let bit-h = config.bit-height
if config.left-labels {
desc-x = calc.min(desc-x, start-x + width / 2 - bit-w)
} else {
desc-x = calc.max(desc-x, start-x + width / 2 + bit-w)
}
shapes += draw-underbracket(config, start-x, start-x + width, start-y)
let mid-x = start-x + width / 2
shapes += draw-link(config, mid-x, start-y, desc-x, desc-y)
let txt-x = desc-x
if config.left-labels {
txt-x -= range_.description.len() * config.default-font-size / 2pt
}
shapes += draw-text(
range_.description,
config.text-color,
txt-x, desc-y + bit-h / 2,
anchor: "west"
)
desc-y += config.default-font-size / 0.75pt
if range_.values != none and range_.depends-on == none {
let shapes_
(shapes_, _, desc-y) = draw-values(config, range_.values, txt-x, desc-y)
shapes += shapes_
}
desc-y += config.description-margin
return (shapes, desc-x, desc-y)
}
#let draw-arrow(config, start-x, start-y, end-x, end-y, label: "") = {
let shapes = ()
let dash-len = config.dash-length
let dash-space = config.dash-space
let arrow-size = config.arrow-size
let link-col = config.link-color
let txt-col = config.text-color
let arrow-label-dist = config.arrow-label-distance
let start = vec.vec(start-x, start-y)
let end = vec.vec(end-x, end-y)
let start-end = vec.sub(end, start)
let d = vec.normalize(start-end)
let dashes = int(vec.mag(start-end) / (dash-len + dash-space))
for i in range(dashes) {
let a = vec.add(
start,
vec.mul(d, i * (dash-len + dash-space))
)
let b = vec.add(
a,
vec.mul(d, dash-len)
)
shapes += draw-line(link-col, (a.x, a.y), (b.x, b.y))
}
let n = vec.vec(d.y, -d.x)
let width = arrow-size / 1.5
let p1 = vec.sub(
end,
vec.sub(
vec.mul(d, arrow-size),
vec.mul(n, width)
)
)
let p2 = vec.sub(
end,
vec.add(
vec.mul(d, arrow-size),
vec.mul(n, width)
)
)
shapes += draw-poly(
link-col,
(end.x, end.y),
(p1.x, p1.y),
(p2.x, p2.y)
)
if label != "" {
shapes += draw-text(
label,
txt-col,
(start.x + end.x) / 2,
(start.y + end.y) / 2 + arrow-label-dist,
anchor: "north"
)
}
return shapes
}
#let draw-dependency(
draw-struct, config,
struct, schema, bits-x, bits-y, range_, desc-x, desc-y
) = {
let shapes = ()
let bit-w = config.bit-width
let bit-h = config.bit-height
let arrow-margin = config.arrow-margin
let start-i = struct.bits - range_.end - 1
let start-x = bits-x + start-i * bit-w
let width = rng.bits(range_) * bit-w
shapes += draw-underbracket(config, start-x, start-x + width, bits-y)
let depend-key = rng.key(..range_.depends-on)
let depend-range = struct.ranges.at(depend-key)
let prev-range-y = bits-y + bit-h * 1.5
let prev-depend-y = if depend-range.last-value-y == -1 {
bits-y + bit-h * 1.5
} else {
depend-range.last-value-y
}
let depend-start-i = struct.bits - depend-range.end - 1
let depend-start-x = bits-x + depend-start-i * bit-w
let depend-width = rng.bits(depend-range) * bit-w
let depend-mid = depend-start-x + depend-width / 2
shapes += draw-underbracket(config, depend-start-x, depend-start-x + depend-width, bits-y)
for (val, data) in range_.values.pairs().sorted(key: p => p.first()) {
shapes += draw-arrow(config, depend-mid, prev-depend-y, depend-mid, desc-y - arrow-margin)
let val-ranges = (:)
for i in range(rng.bits(depend-range)) {
val-ranges.insert(
str(depend-range.end - i),
(name: val.at(i))
)
}
let val-struct = (
bits: rng.bits(depend-range),
start: depend-range.start,
ranges: val-ranges
)
val-struct = structure.load("", val-struct)
let shapes_
(shapes_, ..) = draw-struct(config, val-struct, schema, ox: depend-start-x, oy: desc-y)
shapes += shapes_
let y = desc-y + bit-h * 1.5
let x1
let x2
// Arrow from left to right
if depend-range.end > range_.start {
x1 = depend-start-x + depend-width + arrow-margin
x2 = start-x - arrow-margin
// Arrow from right to left
} else {
x1 = depend-start-x - arrow-margin
x2 = start-x + width + arrow-margin
}
shapes += draw-arrow(config, x1, y, x2, y, label: data.description)
shapes += draw-arrow(config,
start-x + width - bit-w,
prev-range-y,
start-x + width - bit-w,
desc-y + bit-h - arrow-margin
)
prev-depend-y = desc-y + bit-h * 2 + arrow-margin
prev-range-y = prev-depend-y
depend-range.last-value-y = prev-depend-y
(shapes_, desc-y) = draw-struct(config, schema.structures.at(data.structure), schema, ox: start-x, oy: desc-y)
shapes += shapes_
}
struct.ranges.at(depend-key) = depend-range
return (shapes, desc-x, desc-y, struct)
}
#let draw-structure(config, struct, schema, ox: 0, oy: 0) = {
let shapes
let colors = schema.at("colors", default: (:))
let bg-col = config.background
let txt-col = config.text-color
let border-col = config.border-color
let bit-w = config.bit-width
let bit-h = config.bit-height
let (bits-x, bits-y) = (ox, oy + bit-h)
let bits-width = struct.bits * bit-w
let start-bit = struct.start
let bit-colors = (:)
for i in range(struct.bits) {
bit-colors.insert(str(i), bg-col)
}
if struct.name in colors {
for (s, col) in colors.at(struct.name) {
let (start, end) = rng.parse-span(s)
for i in range(start, end + 1) {
let real-i = struct.bits - i - 1 + start-bit
bit-colors.insert(str(real-i), col)
}
}
}
let range-boundaries = ()
for r in struct.ranges.values() {
let i = struct.bits - r.end - 1 + start-bit
range-boundaries.push(i)
}
// Draw colors
for i in range(struct.bits) {
let bit-x = ox + i * bit-w
shapes += draw-rect(bit-colors.at(str(i)), bit-x, bits-y, bit-w+1, bit-h)
}
// Draw rectangle around structure
shapes += draw-rect(border-col, bits-x, bits-y, bits-width, bit-h, thickness: 2)
let indices = range(struct.bits)
if not config.all-bit-i {
indices = ()
for r in struct.ranges.values() {
indices.push(r.start)
indices.push(r.end)
}
}
for i in range(struct.bits) {
let bit-x = ox + i * bit-w
let real-i = struct.bits - i - 1 + start-bit
if real-i in indices {
shapes += draw-text(
str(real-i),
txt-col,
bit-x + bit-w / 2,
oy + bit-h / 2
)
}
// Draw separator
if i != 0 and not i in range-boundaries {
shapes += draw-line(border-col, (bit-x, bits-y), (bit-x, bits-y + bit-h * 0.2))
shapes += draw-line(border-col, (bit-x, bits-y + bit-h * 0.8), (bit-x, bits-y + bit-h))
}
}
let ranges = structure.get-sorted-ranges(struct)
if config.left-labels {
ranges = ranges.rev()
}
let desc-x
if config.force-descs-on-side {
desc-x = config.margins.at(3) + structures.main.bits * bit-w
if config.left-labels {
desc-x = config.width - desc-x
}
} else {
desc-x = ox
if config.left-labels {
desc-x += struct.bits * bit-w
}
}
let desc-y = bits-y + bit-h * 2
// Names + simple descriptions
for range_ in ranges {
let start-i = struct.bits - range_.end + start-bit - 1
let start-x = bits-x + start-i * bit-w
let width = rng.bits(range_) * bit-w
let name-x = start-x + width / 2
let name-y = bits-y + bit-h / 2
shapes += draw-line(border-col, (start-x, bits-y), (start-x, bits-y + bit-h))
shapes += draw-text(range_.name, txt-col, name-x, name-y, fill: bg-col)
if range_.description != "" {
let shapes_
(shapes_, desc-x, desc-y) = draw-description(
config, range_, start-x, bits-y, width, desc-x, desc-y
)
shapes += shapes_
}
}
// Dependencies
for range_ in ranges {
if range_.values() != none and range_.depends-on != none {
let shapes_
(shapes_, desc-x, desc-y, struct) = draw-dependency(
draw-structure, config,
struct, schema, bits-x, bits-y, range_, desc-x, desc-y,
)
shapes += shapes_
}
}
return (shapes, desc-y)
}
#let render(config, schema, width: 100%) = {
set text(
font: config.default-font-family,
size: config.default-font-size
)
let main = schema.structures.main
let ox = config.margins.at(3)
if config.left-labels {
ox = config.width - ox - main.bits * config.bit-width
}
let params = if config.full-page {
(
width: auto,
height: auto,
fill: config.background,
margin: 0cm
)
} else {
(:)
}
set page(..params)
let cnvs = canvas(length: 1pt, background: config.background, {
let (shapes, _) = draw-structure(
config, main, schema,
ox: ox,
oy: config.margins.at(0)
)
// Workaround for margins
draw.group(name: "g", padding: config.margins, shapes)
draw.line(
"g.north-west",
"g.north-east",
"g.south-east",
"g.south-west",
stroke: none,
fill: none
)
})
if config.full-page {
cnvs
} else {
layout(size => {
let m = measure(cnvs)
let w = m.width
let h = m.height
let base-w = if type(width) == ratio {
size.width * width
} else {
width
}
let r = if w == 0 {
0
} else {
base-w / w
}
let new-w = w * r
let new-h = h * r
r *= 100%
box(
width: new-w,
height: new-h,
scale(x: r, y: r, cnvs, reflow: true)
)
})
}
}
#let make(config) = {
return (
config: config,
render: render.with(config)
)
} |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/wrap-indent/0.1.0/example.typ | typst | Apache License 2.0 |
// Here's a minimal example!
#set page(height: auto, width: 3.5in, margin: 0.25in)
#import "@preview/wrap-indent:0.1.0": wrap-in, allow-wrapping
#show terms.item: allow-wrapping
/ First --:
A normal term list
with multiple paragraphs
But this text is separated
#line(length: 100%)
#let custom-block(content) = rect(content,
fill: orange.lighten(90%),
stroke: 1.5pt + gradient.linear(..color.map.flare)
)
/ #wrap-in(custom-block):
A *custom block* using the `wrap-in` function
with indented text \
over multiple lines
And this text is _still_ separated!
#pagebreak()
// Once more, here's the required initialization:
#import "@preview/wrap-indent:0.1.0": wrap-in, allow-wrapping
#show terms.item: allow-wrapping
// And here's a more complicated example!
#set page(height: auto, width: 4.1in, margin: 0.25in)
#show heading: set text(size: 0.75em)
#show heading: set block(below: 1em)
#set heading(numbering: "1) ")
= Normal function call:
// A function for wrapping some text:
#let custom-quote(body) = rect(
body,
width: 100%,
fill: luma(95%),
stroke: (left: 2pt + luma(30%))
)
#custom-quote[
Some text in a _custom quote_ spread over multiple lines
so it actually looks like it was typed in a document.
]
This text is outside the quote box
= Wrappped function call!
/ #wrap-in(custom-quote):
Some text in a _custom quote_ spread over multiple lines
so it actually looks like it was typed in a document.
This text is _still_ outside the quote box!
= Arbitrary functions should _just work#emoji.tm;_
/ #wrap-in(x => ellipse(align(center, x),
stroke: 3pt + gradient.conic(..color.map.rainbow)
)):
Some text in a _rainbow ellipse_ spread
over multiple lines so it actually looks
like it was typed in a document.
= One-liners look great!
/ #wrap-in(underline): Here's one line underlined
= Let's do some math:
#let named-thm(name) = (content) => {
pad(left: 2em, par(hanging-indent: -2em)[
*Theorem* (#name) #emph(content)
])
}
/ #wrap-in(named-thm("Operational Soundness")):
If $med tack e : tau$ and $e$ reduces to $e'$
by zero or more steps and $"Irred"(e')$,
then $e' in "Val"$ and $med tack e' : tau$.
= In-line styling doesn't create blocks:
/ #wrap-in(highlight):
This text is highlighted.
This text isn't.
Notice how there was *no* paragraph break between the
two sentences? This is a useful result that makes
`wrap-indent` really flexible!
(if you want separate blocks, use `block` in your function)
= Does it work with nesting?
/ #wrap-in(custom-quote):
Testing...
/ #wrap-in(align.with(center)):
/ #wrap-in(rect):
/ #wrap-in(emph):
Signs point to yes!
= Final thoughts
/ Note --:
Regular term lists still work!
/ Disclaimer --:
You may run into issues with other term list
show rules conflicting with this rule. \
(although set rules should be unaffected)
If you run into issues, _let me know!_ I'd love to hear
about it to make this package as robust as possible.
= And
#let big-statement(content) = {
align(center, text(
underline(stroke: 1.5pt, content),
size: 32pt,
weight: "bold",
style: "italic",
fill: eastern,
))
}
/ #wrap-in(big-statement):
That's a wrap!
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/014%20-%20Khans%20of%20Tarkir/002_Awakening%20the%20Bear.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Awakening the Bear",
set_name: "Khans of Tarkir",
story_date: datetime(day: 17, month: 09, year: 2014),
author: "<NAME>",
doc
)
#emph[Perhaps you've seen Surrak Dragonclaw, the khan of the Temur clan. Perhaps you've even seen him punch a bear. But the Temur aren't all face-smashing and bear-punching. They're also a deeply spiritual people, and Surrak represents that duality of reverent respect for the wilds and utter pragmatism in dealing with them.]
#emph[But the position of khan is not hereditary, and Surrak wasn't born into it. He was once just another young Temur warrior trying to make a name for himself. Until one wilderness encounter altered his destiny forever…]
#figure(image("002_Awakening the Bear/01.jpg", width: 100%), caption: [], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The youth hesitated at the entrance to the dark cave. He pulled the fur hood closer to his face. The cold air was hungry and the thin wisp of beard offered no protection from its bite. Surrak could see no light within, but a wild scent chased down his nose and smote it with sturdy blows. An atavistic memory roared through his mind.
A sound reached from the darkness. Or was it a thought? He didn't know if he had heard anything. But it called him onward. It did not comfort. It spoke of fear. But it also whispered of strength.
#figure(image("002_Awakening the Bear/02.jpg", width: 100%), caption: [Heir of the Wilds | Art by <NAME>], supplement: none, numbering: none)
He took a breath, stepped forward. The close air was heavy with animal scent. He moved with the throb that hammered all around, the great heart of the wild. It seemed as though many voices were chanting in weird harmony. The song grew louder. It wrapped him tighter than his furs.
The drumming stopped. Sudden light flared, and he squeezed his eyes tight. The voices rose to a shout. Then silence.
He opened his eyes. A fire was burning, somehow, in the middle of the stony floor. No wood fueled its flames. It flickered, orange, blue. Above him rose a vault of rock. Across it, like a river, streamed a line of creatures. Some he recognized: great elk, white wolves, huge bears, even skulking minks. Some were legends: the ancient mammoths and the mighty dragons whose bones still anchored the clan's tents. More still were amazing beasts that had never lived. He had no name for them. They ran across the ceiling, seemingly alive, their bright colors rippling in the firelight.
He saw no one. But many openings led from the great hall, and now the strange chant started up again. #emph[Look now, young one] , it seemed to say, although it held no words. #emph[See your destiny, heir of the wilds.]
The rhythm seemed to soak into him. As if in dream, he dropped supine on the stony floor. The painted parade shimmered above him. A great bear, roaring on its hind legs, stepped from the ceiling. It swung its heavy paws over a tiny-looking human figure that had not been there a moment before. The human was unarmed. The two met, clashed. Then only the human was left. It lifted a double-bladed staff overhead.
The vision ended. Surrak's eyes grew heavy, and he slipped into blackness.
When he awoke, the cavern was chill and empty. Only faint light from the cave mouth intruded on the dark. The panorama overhead was dim and lifeless. But he still clasped tight the vision of the night. He gathered his fur cloak around himself and stepped into the frozen forest.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
As Surrak grew, he listened to the inward echoes of the chant and let his spirit point the way. He walked where none had gone. He sought the wildest places.
He came upon the paw prints one day as the hidden sun grew high. Each print was as big around as the youth's waist, driven deep into the snow. A rank smell still lingered about them. The beast was near.
Surrak stopped and cocked his head to listen. At first, only the susurrus of snow and the thin wind met his ear. He stood motionless, like a stone-pile guide in the woods. Crystals settled on his shoulders.
Then he heard a hoarse grunting sound. A heavy form breaking through the ice and shoving aside branches. Not far ahead.
He tightened his gloves. Crafted from the hide of some Abzan beast fallen long ago to his clan, they gripped his arms up to the biceps. The claws of wolves thrust from the knuckles. Other than these, Surrak's own bravery and strength were the only weapons he carried.
He shouted a challenge. The words were ancient; he did not know their meaning. The Whisperers said the words once were screamed by dragons. Surrak knew only that they were full of fury and power. Then he hurled himself forward.
#figure(image("002_Awakening the Bear/03.jpg", width: 100%), caption: [Bear token | Art by <NAME>], supplement: none, numbering: none)
The bear reared up before Surrak. It bawled its own challenge in the tongue of its kind, shaking its head and gaping wide. It was nearly twice his height. Surrak could not check his rush in time. A huge paw smashed into him. It was as though the mountain itself struck. He was tossed into the air. He flew backward and crashed into a tree. Ribs gave way. The breath burst from him. He gasped, half buried in the snow.
The creature charged. The ground shook to its bounding gait. Surrak struggled to haul himself to his feet. Too late, he realized he could not avoid the onslaught. Instead, he threw himself to the side as the monstrous creature lunged to crush him in its jaws. A powerful, clawed foot clipped his head. Pain burst in his eye, his brow. His sight was blurred in a film of red.
Surrak shook his head, bearlike. He staggered to his feet and put a thick tree trunk to his back. With one rough glove he scrubbed the gore from his face. He could feel shreds of skin flapping. The bear turned to attack again. Surrak set his feet against the bole.
The bear gathered itself to charge. Surrak roared and sprang at it, driving with his feet from the tree. His gauntleted fist drove into the bear's face like an axe blow. Stunned, the creature dropped to the snow.
#figure(image("002_Awakening the Bear/04.jpg", width: 100%), caption: [Savage Punch | Art by <NAME>urt], supplement: none, numbering: none)
Before the bear could rise, Surrak howled again and threw himself on its back. He gripped its shaggy neck with one hand, and hammered on it with the other. He tore off fistfuls of fur as he struck, again and again, while the beast threw its head about and tried to shake him off. Blood spattered the snow. At last, he let go and jumped away, panting and bloodied, to confront his opponent.
The two brutes stared at each other. Surrak's remaining eye held the other's gaze and dared it to come at him again. The bear's head hung low, an ear torn, teeth shattered from the savage punch. Finally it dropped its gaze and turned aside. It huffed, shook itself, and slowly moved away.
Surrak stood, shouting the chant of triumph, until his enemy was lost to sight. Then he sank to his knees.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Surrak returned to the great camp at Karakyk. The right side of his face was raw and ragged, and he could not see from that eye. He carried tufts of brown fur, a claw that had torn loose from the bear's initial charge, and several broken teeth.
Silently, he presented the trophies to the clan elders. They acknowledged the gifts and bestowed on Surrak the rights and titles of the grown. Into his hands, The One Who Whispers Twice placed a greatspear tipped with flint and bound in blessed strands.
The healers took him and cleansed his wounds. The scars were stark, bone white against his wind-chapped skin, and his right eye was clouded like a winter day. No hair would grow on that side of his face. But Surrak smiled. He bore the marks of a great warrior.
From that day, he led clan fighters to hunt both game and foes. At first, his warriors were few, but as he harvested victories, so too did their numbers swell. Soon, only the Dragonclaw and the Hunt Caller counted more blades.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The cruel winter loosed its claws, if only slightly. Spring crept into the high passes, and the families dispersed to their hunting grounds. But as the weather grew more gentle, the boldness of the clan's enemies swelled. To Surrak, this season seemed worse than many previous years. Raiding parties from other clans, and especially the hated Sultai, continually harried the camps and drove away the game.
The Temur replied in force. Surrak and his kin spent more days in pursuit of two-legged prey than in the hunt for food. His people grew weary and drawn. To their great shame, some began to drop away from the group, too weak to go farther.
The ragged party continued its trek. It moved to the lower slopes, where food might be easier to find. But the land was bare, befouled by the passage of many feet—and things without feet. Surrak scowled and urged his band in pursuit of the raiders.
In a trampled clearing, they caught up to their prey: a huge group of scavengers under the banner of a trio of snake-folk, and a train of the shambling dead. The Temur spat curses as they recognized the emaciated forms of their own clansfolk, lost to hunger and disease.
The hunting party was badly outnumbered. But Temur strength does not come from mere numbers. The fury of the wild erupted from the warriors' breasts, and they fell upon their foes. Claws and axes slashed flesh. Their enemies hurled vile magic and spat venom. Although the stalwart mountain folk slew many, more of them began to fall.
#figure(image("002_Awakening the Bear/05.jpg", width: 100%), caption: [Roar of Challenge | Art by <NAME>], supplement: none, numbering: none)
Surrak had led the charge. He found himself surrounded and jabbed with his spear and clubbed with his fist. Dozens lay dead about him. Wounds gaped on his body. But he would take down as many as he could before he joined the ancestors.
Suddenly, a roar shattered the clash of battle. The earth shook. From the nearby forest rushed a hulking, shaggy form. The cave bear crashed into the ranks of the Sultai, ripping apart the gaunt zombies and bowling over the astonished humans. It forced a path straight through to Surrak. Then it turned and began to rip into another swath of enemies.
Surrak laughed in welcome for his old challenger, his new ally. He waded again into the fight. His companions hesitated only a moment, then redoubled their efforts. The Sultai fell back in terror and amazement. Many broke and ran, leaving their serpent masters undefended. With a massed shout, the Temur overwhelmed the rest.
The battle was won, the enemy ruined. Their foulness would not soon stain the mountains again. Surrak leaned on his spear shaft, breathing hard. He then felt the pain of his many injuries.
He heard a heavy, grunting groan behind him and turned. Splayed on the ground, the mighty bear rolled its head in anguish. Surrak saw the shafts of barbed Sultai arrows sunk in its flanks. Black smears of venom mingled with the dark blood.
The bear turned its eyes toward Surrak. In them he saw a plea. He knew his duty. He bent, removed a gauntlet, and laid his hand on its muzzle. He spoke the ancient chant that sent the fallen to the ancestors. Then he stood and drove his spear through the beast's skull.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
He Who Whispers Twice spoke the invocation that marked Surrak as the First Father of the Temur. About Surrak's shoulders he draped a cloak of bearskin: the preserved hide of the clan's defender. Surrak drew on new gauntlets, crafted from the great beast's paws. He lifted the ancestral Dragonclaw overhead. He and the bear and the clan were one.
#figure(image("002_Awakening the Bear/06.jpg", width: 100%), caption: [Surrak Dragonclaw | Art by <NAME>], supplement: none, numbering: none)
|
|
https://github.com/x14ngch3n/CV | https://raw.githubusercontent.com/x14ngch3n/CV/main/README.md | markdown | # CV
Curriculum Vitae written in Typst
|
|
https://github.com/brayevalerien/Learning-Typst | https://raw.githubusercontent.com/brayevalerien/Learning-Typst/main/README.md | markdown | MIT License | # Learning Typst
[Typst](https://typst.app) is a new typesetting language with interesting capabilities for maths and computer science. It looks quite simple, with readable source code but many cool features. As a [LaTeX](https://en.wikipedia.org/wiki/LaTeX) user, I'm interesting in trying out this new language and see how it compares to [LaTeX](https://en.wikipedia.org/wiki/LaTeX) (and Markdown, my other markup language of choice for simple documents).
This repository contains the documents I write in order to get familiar with [Typst](https://typst.app). The content itself is not that important, it's just to demonstrate things, try the features, learn the language and produce my own examples I can refer to latter on.
# References
- [Typst documentation](https://typst.app/docs/)
- [Typst Github repository](https://github.com/typst/typst)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-00.typ | typst | Other | // Error: 4 expected expression
#(-)
|
https://github.com/yan-aint-nickname/uni | https://raw.githubusercontent.com/yan-aint-nickname/uni/main/oop-matrix-mul-cli/main.typ | typst | MIT License | #import "template.typ": *
#import "@preview/codelst:2.0.1": sourcecode, sourcefile
#import "diagrams/main.typ" as main_algo
#import "diagrams/user_input.typ" as input_algo
#import "diagrams/fill_matrix.typ" as fill_algo
#import "diagrams/count_values.typ" as count_algo
// 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: "Объектно-ориентированное программирование. КМ-4. Более сложные элементы программирования.",
authors: (
"<NAME>",
),
)
#show figure: set block(breakable: true)
#outline()
= Задание
Работа выполняется по заданию из Семинара 3. Написать программу произведения матрицы на вектор.
== Комментарии
- Полный код программы находится в репозитории https://github.com/yan-aint-nickname/uni см.директорию: `oop-matrix-mul-cli`
- Для компиляции я использовал https://ziglang.org/
- Библиотека для тестирования https://github.com/sheredom/utest.h/
- Для дальнейшей работы мне необходимо сделать допущение для векторов, столбцовых и строковых матриц:
/ $n$ : - кол-во строк/столбцов вектора
$ZZ^n tilde.equiv ZZ^(n times 1) tilde.equiv ZZ^(1 times n)$\
Алгоритм перемножения матрицы на вектор:
$
mat(
a_(0 0), a_(0 1), ..., a_(0 n);
a_(1 0), a_(1 1), ..., a_(1 n);
dots.v, dots.v, dots.down, dots.v;
a_(m 0), a_(m 1), ..., a_(m n);
) times vec(b_0, b_1, dots.v, b_n) = vec(
c_0 = a_(0 0) dot.op b_0 + a_(0 1) dot.op b_1 + ... + a_(0 n) dot.op b_n,
c_1 = a_(1 0) dot.op b_0 + a_(1 1) dot.op b_1 + ... + a_(1 n) dot.op b_n,
dots.v,
c_n = a_(m 0) dot.op b_0 + a_(m 1) dot.op b_1 + ... + a_(m n) dot.op b_n)\
c_i = sum^n_(k=0)a_(i k)b_k
$
= Код программы
== Заголовочный файл
#figure(
caption: "Заголовочный файл tool.hh",
sourcefile(
file: "tool.hh",
read("tool.hh"),
)
)
== Реализация
#figure(
caption: "Релазиация методов, алгоритма tool.cc",
sourcefile(
file: "tool.cc",
read("tool.cc"),
)
)
#figure(
caption: "Точка входа программы main.cc",
sourcefile(
file: "main.cc",
read("main.cc"),
)
)
#pagebreak()
== Модульное тестирование
#figure(
caption: "Модульное тестирования с использованием библиотеки utest.h",
sourcefile(
file: "tool_test.cc",
read("tool_test.cc"),
)
)
#pagebreak()
= Ответы на вопросы
1. Что такое дружественная функция? В чем состоит выигрыш от применения дружественных функций?
Дружественная функция в C++ - это функция, которая не является членом класса, но имеет возможность доступа к приватным и защищенным членам класса. Она объявляется с помощью ключевого слова `friend`. Дружественные функции не входят в область видимости класса, но они могут получать доступ к его приватным и защищенным членам. Это может быть особенно полезно в ситуациях, когда необходимо выполнить операции над данными класса, которые логически не принадлежат самому классу.
Преимущества использования дружественных функций:
- Инкапсуляция: Дружественные функции позволяют сохранять инкапсуляцию, но при этом предоставляют необходимый доступ к внешним функциям. Это полезно, когда вы хотите сохранить внутреннюю работу класса скрытой от остальной части программы, но вам нужно выполнить операции, требующие доступа к приватным данным класса.
- Гибкость: Они обеспечивают гибкость при проектировании классов. Иногда логичнее реализовать функцию вне класса, особенно если функция должна обращаться к нескольким классам или если она концептуально не принадлежит ни одному классу.
- Перегрузка операторов: Дружественные функции часто используются для перегрузки операторов класса. Это позволяет использовать класс более интуитивно, поскольку его можно использовать с операторами так же, как и встроенные типы.
2. В каких случаях в классе должен быть конструктор копирования? При выполнении каких инструкций вызывается конструктор копирования?
Класс в C++ должен иметь конструктор копирования, когда конструктор копирования по умолчанию, предоставляемый компилятором, не удовлетворяет потребностям класса. Конструктор копирования по умолчанию выполняет неглубокое копирование объекта, то есть копирует каждый член класса из исходного объекта в новый объект. Это хорошо работает для простых типов данных и для классов, в которых все члены являются либо примитивными типами, либо указателями на объекты, которые должны быть общими для оригинала и копии. Однако для классов, управляющих ресурсами, такими как динамическая память, дескрипторы файлов или сетевые соединения, неглубокое копирование может привести к таким проблемам, как двойное удаление, утечки памяти или проблемы с разделением ресурсов.
Когда использовать конструктор копирования:
- Если при копировании полей необходимо изменять содержимое хотя бы некоторых из них
- Если класс содержит хотя бы одно динамическое поле
Конструктор копирования вызывается в следующих сценариях:
- Инициализация:
```cpp
MyClass obj1;
MyClass obj2 = obj1;
```
- Передача по значению:
```cpp
void someFunction(MyClass obj) {
// Вызывается конструктор копирования, когда объект передаётся по значению
}
MyClass obj;
someFunction(obj);
```
- Возврат по значению:
```cpp
MyClass createObject() {
MyClass obj;
return obj; // Вызов конструктора копирования
}
```
- Инициализация копированием:
```cpp
MyClass obj1;
MyClass obj2(obj1);
```
3. В каких случаях в классе должна быть переопределена операция присваивания? При выполнении каких инструкций вызывается переопределенная операция присваивания?
Когда использовать переопределение операции присваивания:
- Если класс содержит хотя бы одно динамическое поле, так же как и с конструктором копирования
Когда вызывается переопределенная операция присваивания:
- Присваивание экземпляра класса другому экземпляру этого же класса
```cpp
MyClass obj1;
MyClass obj2;
obj2 = obj1;
```
- Возврат по ссылке
```cpp
MyClass& someFunction(MyClass& obj) {
return obj;
}
MyClass obj;
someFunction(obj) = MyClass();
```
4. Как будет выполняться умножение над экземплярами классов Matrix и Vector, если операцию умножение не переопределять?
Для классов определенных пользователем, если они не являются подклассами классов с определенными операторами умножения, будет выводиться ошибка компиляции.
|
https://github.com/piepert/philodidaktik-hro-phf-ifp | https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/descartes/cogito_argument.typ | typst | Other | #import "/src/template.typ": *
#let med(page) = en[Vgl. <NAME>: AT VII. S. #page.]
== #ix("Das cogito-Argument", "cogito-Argument")
Ausgehend vom #ix("methodischen Zweifel", "Zweifel, methodisch") setzt #ix("Descartes", "<NAME>") fort und sucht nach Erkenntnis, an der es nicht möglich ist zu zweifeln. Er kommt zu dem Schluss, dass der Satz "Ich bin, ich existiere"#med[25] nicht falsch werden kann, wenn er ausgesprochen oder gedacht wird. Selbst wenn es einen allmächtigen #ix("Täuschergott", "Genius malignus") gäbe, so wäre auch er in der Lage diesen Satz, wenn er vom Getäuschten gedacht wird, falsch zu machen. Denn wenn ein Täuscher jemanden täuscht, gibt es jemanden, der getäuscht wird. Es handelt sich dabei jedoch nicht um das _#ix("cogito-Argument")_. Der berühmte Satz "Cogito ergo sum." (dt. "Ich denke, also bin/existiere ich.") kommt nicht in en Meditationen vor. Ausschlaggebend ist jedoch, dass #ix("Descartes", "<NAME>") als erste, feste Erkenntnis findet: "Ich existiere."
#set par(justify: false)
#grid(columns: (10%, 45%, 45%).map(e => e - 1.5em),
row-gutter: 1em,
column-gutter: 1.5em,
strong[Stufe], strong[Thema im Rahmenplan], strong[Thema bei Descartes],
[5], align(center + horizon)[/], align(center + horizon)[/],
[6], align(center + horizon)[/], align(center + horizon)[/],
[7], align(center + horizon)[/], align(center + horizon)[/],
[8/9], align(center + horizon)[/], align(center + horizon)[/],
[10], [
- *Regeln logischen Denkens:* Wie urteile und schließe ich korrekt?#en[Vgl. @MBWKMV2002_RP710[S. 34.]]
], [
- Ist das #ix("cogito-Argument") gültig, schlüssig und/oder rein intuitiv?
],
[11/12], [
- *Erkenntnis:* dialektische Auseinandersetzung mit Thesen zur menschlichen Erkenntnis, Rationalismus#en[Vgl. @MBWKMV2019_RP1112[S. 12.]]
], [
- Denken und Vernunft als reine Methode der Erkenntnis
]) |
https://github.com/OCamlPro/ppaqse-lang | https://raw.githubusercontent.com/OCamlPro/ppaqse-lang/master/src/étude/concurrence.typ | typst | #import "defs.typ": *
#import "links.typ": *
= Concurrence
L'utilisation du calcul parallèle au sein d'un même programme se fait
généralement par l'utilisation des _threads_ fournis par le système
d'exploitation sous-jacent. Les threads permettent de lancer plusieurs
fonctions en parallèle en exploitant éventuellement la multiplicité des coeurs
de calcul de la machine. En toute théorie, cela permet d'accélérer le calcul
et de rendre le programme plus réactif.
Pour raisonner avec du calcul parallèle, il est nécessaire de mettre en place
des mécanismes de partage d'information entre les _threads_. Ces mécanismes
sont généralement des variables partagées ou des files de messages. Lorsque
plusieurs _threads_ accèdent à une même variable, il est possible que les
valeurs lues ou écrites soient incohérentes si les _threads_ ne sont pas
synchronisés. Par exemple, si un _thread_ écrit une valeur dans une variable
et que l'autre _thread_ lit cette valeur avant que l'écriture ne soit terminée,
il est possible que le second _thread_ lise une valeur intermédiaire qui n'est
pas celle attendue.
Pour éviter ce genre de problème, il est nécessaire de synchroniser les
_threads_ entre eux. Les mécanismes de synchronisation les plus courants sont
les _mutex_ (verrous) et les _sémaphores_. Toutefois, ces mécanismes se
mettent en place manuellement en fonction de ce que le programmeur imagine
comme étant le bon ordonnancement des _threads_. Or, cet ordonnancement n'est
pas toujours celui qui est effectivement réalisé par le système d'exploitation,
ce qui rend les problèmes de concurrence très difficiles à reproduire et à
corriger.
Certaines analyses statiques peuvent détecter des erreurs de concurrence en
simulant les ordonnancements possibles et en vérifiant que les valeurs lues
et écrites sont cohérentes. En fonction de l'analyse effectuée, il est possible
de détecter deux types d'erreurs :
- les _data races_ (courses critique) qui surviennent lorsqu'un _thread_ lit ou
écrit une valeur partagée sans synchronisation;
- les _deadlocks_ (interblocages) qui surviennent lorsqu'un _thread_ attend une
ressource qui est détenue par un autre _thread_ qui lui-même attend une
ressource détenue par le premier. |
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/050%20-%20Phyrexia%3A%20All%20Will%20Be%20One/007_Episode%204%3A%20Impossible%20Odds.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 4: Impossible Odds",
set_name: "Phyrexia: All Will Be One",
story_date: datetime(day: 16, month: 01, year: 2023),
author: "<NAME>",
doc
)
Elspeth picked up her pace to match Koth's, both moving as quickly as the debris-strewn platform allowed. Nahiri's sacrifice had moved them closer to their goal. It had also slowed them—save for Kaya—considerably, since tripping on the rubble would mean a long fall into the depths of the layer.
The hole in the pristine sky above them was still visible, a jagged wound in the porcelain perfection of this place, boiling with every color of Phyrexia. They hurried through a war, and while no one could have called them untouched by its horrors, for the moment, they were too small to attract attention.
#figure(image("007_Episode 4: Impossible Odds/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Elspeth shot a venomous glance at the warriors overhead. #emph[Just you wait] , she thought, as fiercely as she could. #emph[You'll regret what you've done to us.]
They wouldn't. She knew that. Even if everything went perfectly from here, even if they plucked an impossible victory from this chaos, Phyrexia wouldn't regret destroying Mirrodin. They weren't made for regretting things. Phyrexia moved for the greater good and glory of Phyrexia, and in the end, that was all that mattered. All would be One, or nothing would exist at all.
The high bridge where they'd landed seemed too delicate to have withstood the impact of such a massive piece of Sheoldred's Coliseum. Even if the bridge would normally have been sturdy enough, the nature of their arrival should have lent them even more weight, the magnitude of Nahiri's sacrifice sending them plummeting into the fathomless white depths. Glancing over the edge, Elspeth could see farther into the layer below than seemed entirely possible. A lattice of alabaster platforms spanned the spaces all around them, connected by long bridges of crimson sinew.
After the tarnished necrogen wastes of the Dross Pits, this place reminded Elspeth of blood splashed across the white sands of Theros, sullying what should have been pristine. Koth, Melira, and the goblin engineers were born Mirrans. The Planeswalkers were strangers here, but this was #emph[Mirrodin] , this was #emph[their] plane, not Phyrexia's, no matter how much the glistening oil transformed it. They should never have looked out of place in their own homeland.
Clusters of buildings rose from platforms in the latticework like organic sculptures, blending the sleek curve of machined metal with the organic roughness of bone and sinew. Everything was red against white, a whole plane made over in Elesh Norn's image, like some terrible dream.
For all that the bridges were clearly designed to provide easy passage to multitudes of Phyrexians, they were empty save for the Planeswalkers themselves. The battle raging above them was too far away for even the echoes to drift down to them; they might as well have been alone. A faint song filled the air instead, as if the very structures sang to them, a Phyrexian hymn of horrors.
"Nahiri made a huge sacrifice, for us," said Koth. "We have to keep moving to honor the ending she chose."
"She was infected," said Elspeth. "I saw the changes in her, right before the end. There's no way she hadn't realized it was happening. But she never said anything."
"She told me," said Melira, moving through the group to pace them. "She asked me if I could help her when we were back at the Furnace."
"Could you have?" asked Elspeth.
"I could," said Melira, and took a deep breath. "I could have helped her, but reversing the process of phyresis is like pulling a bramble from fertile soil. It throws down a hundred roots. When you dig out one, you find a hundred more. Repairing her body from the damage already done would have left her incapacitated for days. She would have had to stay behind."
"She would have seen that as wasting time we didn't have," said Elspeth.
They had managed to catch up to Kaya while they were speaking. Kaya looked at them, listening, before she asked, "Could you do that sort of healing for Jace?"
"If he was willing to let me," said Melira.
Kaya looked back to where Jace walked along, reserved, the sylex bouncing in the satchel at his hip. The wound on his arm had turned: wire and bright metal shone through the burn. What flesh remained was raw and wet, blackening as it transmuted to fibrous cable.
"I don't think he's going to let us do that," she said, voice going soft.
#emph["Then you know me better than you think you do,"] said Jace's voice in her head. Melira, who had less experience with telepathy than most of the others, looked surprised. #emph["Really, did you think I wouldn't be paying attention to you debating my future? I'm not risking us all to save my own life, not when we've already lost Vraska. That's more weight than I'm willing to carry."]
"Glad to see you're still with us, Jace," said Kaya.
#emph["For now,"] Jace grimly replied. His mental voice fell silent again, all his energy going to moving onward.
"We honor Nahiri's story, and the ending she wrote for it, by finishing this in victory," said Tyvar, who had been walking close behind with Kaito. "A grand sacrifice demands a grand recounting."
"I just hope she's dead," said Kaito.
Elspeth turned to look at him, stunned. "Explain that," she said.
The lanky Planeswalker shrugged, the tanuki on his shoulder bobbing with the motion. "You have to admit, she's probably the most powerful of us."
"Yes," said Elspeth, slowly.
"She's been traveling for so long I doubt any one of us could take her down," he continued. "Maybe not any two of us. But one on one, that kind of raw power? I'd go down, and so would you. I don't want to face her on the other side of a battlefield. She chose to make sure we could keep moving even when it meant splitting herself off from the one person who might be able to save her. I hope she made that sacrifice all the way and doesn't get caught in the middle and turn against the people she was trying to protect."
"At times it's better to grieve a companion than it is to risk fighting against them," said Tyvar, sounding subdued for once.
It was an unsettling thought, and one Elspeth didn't want to dwell on, even as she knew that it was unavoidable. They hadn't found a body among the debris. Though Nahiri sacrificed herself for them, she might still come back in a changed form, transformed into an inexhaustible enemy.
"Well, that's awful," said Kaya. "Thank you for that."
"This doesn't seem like a good place for pretty illusions." Kaito shrugged. "When we don't see things as they really are, we just wind up getting hurt."
"Uh, what in the hells is #emph[that] ?" asked Kaya, stopping dead in the middle of the pathway and staring, open-mouthed, at a stationary colossus looming up from far below them.
Its head was an inverted teardrop of the white metal, split in the center by a single empty red socket, as if something even larger had come along and plucked out its eye. The form of its body was hunched and elongated, making it all but impossible to draw comparisons between it and any more ordinary body form. It was neither insectile nor reptilian, not humanoid or built along any other predictable plan. All of it was cast in red and white, making it an almost perfect match to the landscape. Before Kaya drew her attention to it, Elspeth had taken it for another monumental building.
"<NAME> doesn't like to give up what she thinks belongs to her," said Koth darkly. "She has her favorites—the ones who serve her best or fight her the most fiercely—ossified. Turned to bone and added to her Fair Basilica." He pointed to the statue. "We should still be careful. I've seen structures like this become animated and kill Mirrans who got too close."
So this could be a statue, or it could be a Phyrexian that was going to strike as soon as they moved closer. Its position put it alongside the bridge, a looming threat. Elspeth grimaced, gripping the hilt of her sword.
"Can we move to a safer bridge?" asked Kaito.
"Not if we want to reach <NAME>'s altar," said Koth. "From there, we can access the Mycosynth Gardens. That's where we get access to the Seedcore, and that's where she's planted her Realmbreaker. That's where we have to go."
"I still fail to understand how she could have planted even a mockery of a World Tree," said Tyvar. The scope of the Fair Basilica stole some of the presence from his normally resonant voice, making him sound reduced.
They were all reduced here. They were lessened in the presence of Phyrexia.
Tyvar continued: "The World Tree grows within the Cosmos itself, linking the realms of Kaldheim. It exists both inside and outside of reality. Even if someone could somehow steal a seed, it should have split this plane in two when it sprouted. The fact that it hasn't is a miracle and a horror."
"We had never seen such a thing before," said Koth. "Most still haven't. Melira is the only spy we have who's made it to the tree and back again."
"Only because they can't infect me," said Melira. "Everyone who'd gone into the gardens with me and survived long enough to make it out again succumbed before we could make it home. Norn's tree is planted below in the Seedcore, where she imprisoned Karn. It's a terrible thing, that tree. Tyvar is right—to look at it, you'd think it would split the plane in two. Its roots drive deep, and its branches reach so high they penetrate into the Mycosynth Gardens." She frowned. "At some point, looking at them is like looking at something underwater. The branches are all funny and distorted, and they're not quite right."
"Omenpaths," said Tyvar. "Somehow, she's generating Omenpaths on the branches of a tree that has no right to be." He scowled, first at nothing, then at the motionless giant looming nearby. "We have to end it."
"That's why we're here," said Kaya. She looked to Koth. "Can we keep going?"
"If it's going to attack, it's going to attack," he said. "Elesh Norn's altar isn't far." He pointed to a building larger than the others, more ornate, stretching toward the sky like a citadel of gleaming white and brutal red, organic and mechanical at once. It was beautiful in its own severe, austere way. It was a monument to a unified Phyrexia.
It hurt Elspeth's eyes if she looked at it for too long. Tightening her grip on her sword, she nodded. "We keep going."
They resumed their walk. They were more together now than they'd been when they started along the bridge. Kaya still kept herself on the other side of the group from Jace, but whatever he'd said to make her give him the sylex, she was no longer outright glowering at him.
The goliath didn't move. They passed under its empty gaze without complication and moved toward the cluster of buildings at the end of the bridge. Kaya remained at the head of their group, phasing through the debris in her path rather than detouring around it, little flecks of purple energy marking her wake.
Koth, Elspeth, and the Mirrans came next, Kaito only a foot or so behind, walking between them and Tyvar, while Jace brought up the rear with the sylex. Tyvar kept glancing back at him, finally saying, "Hurry along, friend Jace. We wouldn't want to lose you now."
"No, I suppose we wouldn't," said Jace, a ribbon of black humor in his tone. "Can't save the Multiverse without me."
The doors of the altar gaped open before them, the terrible maw of an impossible and all-consuming beast. It looked as if it had been frozen between life and death, both stationary architecture and petrified corpse. Looking at it made the flesh on Elspeth's arms crawl. But they kept going, alert and braced for trouble, into the empty foyer.
"I feel very much as if we're walking into a trap right now," said Tyvar, voice hushed less out of respect for the space than out of a very realistic desire not to attract attention. Frozen Phyrexians studded the walls: Elesh Norn's most beloved subjects.
#figure(image("007_Episode 4: Impossible Odds/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"That's because we probably are," said Kaya. "First we get scattered across the surface, then we find Vraska alive and able to hold on just long enough to scream for Jace? With Ajani on their side, they were able to anticipate our plan of attack. He knows too much about us. This Elesh Norn you keep invoking sounds smart enough to use him against us."
"Smart, yes, all-knowing, no," said Melira. "Her forces are distracted by the rebellion. We have to keep moving."
They pressed deeper into the silent building, passing columns made of motionless bodies, walls that wept ivy-like trails of sinew and boasted row upon row of horrifically human-looking teeth, and a thousand other Phyrexian nightmares. The Fair Basilica knew no end, and they were going to see it all.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The winding stairway from the Fair Basilica down into the Mycosynth Gardens was accessed via a chamber below Ele<NAME>'s throne. It, too, was unguarded, and the Planeswalkers clustered together as the feeling of moving into a trap grew stronger. Tyvar fingered his piece of Glimmervoid metal, waiting for the moment when he would need to convert his body to the harder, more resilient substance. Conserving his magic for the moment when it would be needed was harder than he would have expected; this place just made him want to stay armored at all times.
They were heroes all, grand allies in the fight against a terrible enemy, and he was glad beyond measure that his story had led him to their side. In the stories, the greater the losses, the greater the victory to follow. But it was hard to remember that now, under the weight of Phyrexia and the future.
At the base of the stair was a platform of shining blue metal—a small slice of the Fair Basilica that extended into the sphere below. The stairway they had used to descend was an enclosed column behind them, stretching back upward to the distant ceiling.
The column's first half, closest to the Fair Basilica, was white metal. As it approached the ground, it gave way to steely blueish gray, becoming oddly textured, almost pebbled. Kaya blinked, raising her hand as if to touch the wall.
"No," said Melira, harshly. Kaya looked at her in surprise, lowering her hand again. Melira relaxed slightly, and explained, "It's mycosynth. This is how Phyrexia took us in the first place. They invaded Mirrodin's heart and sent their infectious spores cascading through everything we were."
Kaya glanced at the wall again, then stepped closer to Koth and his explosives team. "Good to know," she said.
"Forgive me, Melira, but I see no tree," said Tyvar.
Jace groaned.
The group whipped around to see him clutching his stomach, split skin parting farther as the writhing metallic "veins" beneath fought for dominion over the tissues of his body. He managed to straighten, eyes glowing faintly blue as his voice echoed in their heads.
#emph["Melira said we sought the Seedcore. We must go deeper."]
"Deeper," said Koth. "Yes. <NAME> forbids access to the Seedcore."
"But there #emph[is] still a way," said Melira. "<NAME> can't pass through solid matter like your friend here." She hooked a thumb at Kaya. "We just have to reach the door. And get through it."
The Planeswalkers looked around the metal-laced landscape, columned in delicate mycosynth, but saw no structures aside from the one to their back.
#figure(image("007_Episode 4: Impossible Odds/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"Where?" asked Elspeth.
"This way," said Melira, and set out across the rough ground.
The others followed her, careful to avoid the mycosynth pillars, sticking close together to avoid surprises. She led them to a piled-up structure of fungal strands that twisted into a mimicry of entrails, as if some great beast had been gutted here.
Gesturing to the pile, Melira said, "The gateway into the Seedcore. It infects anything it touches. I guess <NAME> figures any Mirran strong enough to get this far deserves the honor of compleation. Luckily, I'm immune to phyresis—even the glistening oil doesn't stick to me for long."
As she moved closer to the pile, it heaved, pulsing, before opening into a terrible hole into darkness ringed with waving tendrils. An entrance masquerading as a monster anemone. The tendrils reached out, almost caressing her, and left a sheen of glistening oil behind. She wiped it away as she turned back to the rest.
Koth frowned. "Most of us don't have your specific resistance, Melira. We'll have to blow the ground."
"Why are we messing with it? That loses us any cover we have," said Kaito. "Isn't there another way down?"
"I may have another way," said Tyvar. He held up his piece of Glimmervoid metal. "In the coliseum, Kaito removed Phyrexian oil from my skin before it could work its way inside. If he can clean the oil off quickly enough, I can spread my magic through the lot of us while we pass through to the Seedcore. It will have to be quick. Transmuting this many people is a feat even I won't be able to maintain for long. But it should lend us a measure of protection—enough for Kaito to do his part."
"I can do it, but this stuff resists my telekinesis, and it's going to give me a major headache," said Kaito, stepping into position.
Melira frowned. "I suppose we can try," she said. "How does this work?"
"Just give me a moment," said Tyvar. "None of you will be able to access your own magic while mine lays across you, but that only means we move quickly."
Kaito looked alarmed. "How am I supposed to clean the oil off if my magic is out of reach?"
"The Halo you took before should protect you enough for a few seconds," said Koth. "We can buy you that much."
Kaito nodded, and the group coalesced around Tyvar, who took a deep breath. The smell of green growing things swirled around them, cutting through the oily fungal scent of the mycosynth. Of the group, only Kaya recognized it as the smell of Kaldheim air. Metal began to spread across Tyvar's skin, slowly at first, and then faster and faster, until his body was a Glimmervoid metal sculpture.
The metal continued to spread, covering them all without difficulty. Jace was the last to be fully transformed, the injury on his arm appearing to almost resist the process, as if Phyrexia wasn't willing to yield its hold for even a moment.
When the process was done, Tyvar held up his hand and said, "We move."
They proceeded as a group into the caressing mass of tendrils, which brushed their hardened skins and left streaks of oil behind but didn't attack. Ahead of them was a narrow hall that ended in an open vestibule connected to what looked like a single bridge. They hurried on, not wanting to find the limits of Tyvar's magic before they had cleared the hall.
At the end, they emerged not into the terrible Phyrexian landscape they had all become accustomed to but into something vital and alive, and even more horrific because it was growing. Tyvar looked to Kaito. Kaito nodded, and Tyvar released the spell.
The Glimmervoid metal melted away, leaving them all flesh once more, skins glistening with oil. Kaito rolled his shoulders, and the oil lifted away from their bodies, coalescing into a ball that lobbed itself off the edge of the bridge.
"Thanks," said Kaya. "Hey, Tyvar, good show—Tyvar?"
He didn't respond. He was staring at something in the distance, stepping toward the bridge with eyes wide and cheeks gone pale.
Kaya turned and beheld the Phyrexian World Tree. #emph[Realmbreaker.]
It was clear that Elesh Norn had cultivated, nurtured, and corrupted it. Its bark was made of the white porcelain metal they'd seen above, and where growth had opened fissures in its surface, vivid, agonized red gleamed through. It wept glistening oil in place of sap, and strange shadows moved along its surface, confusing until Kaya glanced farther up. Long, white oblongs hung in the air near the highest branches of the impossible tree, fading partially into the distorted distance as they reached for the Blind Eternities.
"Invasion ships," said Koth grimly. "They're almost ready."
"This is a perversion of Kaldheim's very soul," said Tyvar. "I knew this was foul, but this~ this is beyond imagining."
The air was still, eerily so, as if the entire realm was holding its breath. High above, in the distant branches of the reaching tree, a white light bloomed and flashed out, spreading in a horribly symmetrical lattice through the upper reaches of the sky.
"We have to hurry," said Jace.
They ran. The bridge connecting the gardens to the core of New Phyrexia was a narrow line above a bottomless drop; at the other end of the bridge was a dark opening in the tangled roots of the tree. The Planeswalkers were nearly there when the sky flashed again, brighter this time, like a sun exploding in the high reaches.
The cataclysmic explosions filled the air with glistening rainbow distortions, followed by the bright impossibility of the Blind Eternities. Jace moaned. Elspeth stumbled, only saved from going over the bridge's edge by Koth's hand grasping her shoulder and yanking her back.
Kaya only stared upward, expression gone blank. "We're too late," she said.
"Kaya—" said Kaito.
She whipped around to face him. "#emph[It was all for nothing] ," she snapped. "The World Tree has connected to the Multiverse. Elesh Norn can access the Blind Eternities. We #emph[failed] ."
"I refuse to let Kaldheim's heart be the weapon that destroys the Multiverse," said Tyvar. "We can still do our best to undo this."
"Hurry," said Jace, breathless. "We have to hurry." He only made it a few more steps, staggering, before collapsing to the ground.
"Tyvar," said Koth.
Tyvar nodded, and—touching the piece of Glimmervoid metal—rippled to metal as he approached Jace and scooped the other man into his arms. Together, the group continued onward, into the opening, into the dark.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The entryway led into a cavity inside the tree, a great domed room formed from woven roots. Dark passages split off from the chamber, with the large one directly ahead seeming to be the main channel. At the center of the space, atop a low dais, was Karn.
#figure(image("007_Episode 4: Impossible Odds/04.jpg", width: 100%), caption: [Art by: Kasia 'Kafis' Zielińska], supplement: none, numbering: none)
The great silver golem had been broken open, vivisected, and spread across the platform. Most horrifying of all, at the sound of their footsteps, he turned his head and croaked, "You shouldn't have come here. This place isn't for you."
"Karn!" Koth and Elspeth hurried toward him but stopped short of touching him, staring at the damage.
"What have they done?" asked Elspeth.
"Isn't it obvious? They've rejected their Father of Machines." Karn shook his head. It seemed to be all the motion he had left to him. "Hurry. The invasion is still young. You may still be able to save some of the planes. Unless~ no. The sylex was destroyed. All is lost."
"We made another," said Elspeth. "We can still end this."
Karn paused, clearly thinking. "You will need to get to the root source and detonate it."
"But—" began Melira, stopping at a sharp glance from Koth.
"I would take the burden from you if I could," said Karn. "It should have been my task all along. You should be free to go to your homes and protect them from what's about to come."
"You can't, though," said Kaya. "You can't even move."
"It's too late for me," said Karn.
"Not just you," said Jace, pushing against Tyvar's chest. The other man put him down, and he approached Karn, arm turned to show the spreading damage from his injury. "It's too late for me, too. Let me take the Multiverse from them."
He hobbled toward the doorway on the other side of the room. After an uncomfortable pause, Tyvar and Kaya followed.
Melira moved to kneel by Karn's head, wiping away the trails of glistening oil and attempting to shift him into a more comfortable position. Koth and the explosives team fanned out around him and began setting charges to free him from his restraints. Elspeth paused in the doorway, neither following the other Planeswalkers nor aiding Karn, and looked back at him.
"I should—they need—but do you want me to stay?" she asked.
"I want to say yes, out of selfishness, but I can't," Karn rasped. "I never thought you would see this plane again. I'm so sorry. I wish you didn't have to die with us."
"It was my choice, Karn."
"You should go with your friends, and then get off this plane. Find a better place to make a final stand."
"No," said Elspeth. "No more running."
Karn sighed, voice apparently exhausted.
"We'll stay here to help shape the charges and aid Karn once he's free," said Koth. "Go."
"I wish I didn't have to."
"It's all right," said Melira, and summoned up a smile. "We made it farther together than I thought we would."
"I'll see you all soon," said Elspeth, and walked through the doorway toward the root source.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The final bridge was long and white and riddled with red.
So many of her friends, dead or lost. Ajani, his mind warped and his body doomed never to die now that he'd been absorbed into Phyrexia. Karn, possibly damaged beyond repair. Her anger was vast, and more agonizing because it was so new. She had lost more than she would ever have believed possible. She felt like her entire being was an old wound that had been sliced open, larger than ever and unhealable.
Elspeth broke into a run.
She caught up to the others halfway across the bridge, approaching a terrible replica of Ele<NAME>'s altar. This one was made of Realmbreaker's woven roots, rather than ossified Phyrexian bodies, but clearly served the same purpose. It hurt the eye and beguiled the heart at the same time, and Elspeth hated it more than she would have thought possible.
Jace was back on his own feet; he glanced at her as she rejoined the group, giving a small nod of welcome, and said nothing. This place was as alive as the Basilica had been still: the air hummed with an uncanny chorus of discordant voices, layered across each other to form a harmony of inchoate parts, rather than the cacophony it should have been.
"Phyrexians can harmonize?" breathed Kaya.
Static shimmered in the air, which tasted bright with aether. The root ceiling above them gaped as they drew closer to the trunk, a tapestry of finer roots allowing them to look upward at the great bulk of the World Tree itself. It twisted through an open rent into the Blind Eternities, flashes of other planes showing through the haze. The upper branches crackled with the energy Tyvar called "Omenpaths." From this angle, they could see long gangways connecting the oblong white capsules of the invasion vessels to the trees. Phyrexians shuffled along the gangways, readying their assault on the Multiverse.
The smoke the vessels spewed was red. Red as blood, red as contagion.
"How many #emph[are] there?" asked Kaya." There must be millions of them," said Kaito, in quiet horror.
"They only showed us what they thought we were worth," said Jace. The white ships reached all the way into the highest branches, terrible fruit preparing for the harvest. "They've been down here preparing for the real fight all along."
Behind them on the bridge, they heard footsteps, steady and confident. As a group they turned, all with hands on weapons save for Jace, who clutched the sylex and took a half-step back, away from the coming conflict.
There, walking toward them as calmly as if this were a pleasant afternoon meeting in a park, came Ajani and Tibalt, but not as they had known them. Ajani wore a suit of metallic red and white armor that appeared to have grown out of his body. It echoed the Fair Basilica, marking him as one of Elesh Norn's creatures. He carried a massive double-headed axe, the blades reversed in her honor.
Seeing her mentor draped in the livery of her greatest enemy made bile rise in Elspeth's throat, but not nearly as much as the smile that spread across his face at the sight of her. "Welcome," he called, and his voice was the same as it had always been. "Elspeth, my dear, it's wonderful to see you again. I'm so glad you survived to join me."
"I'm not here to join you," she spat, bringing her sword around in front of herself and gripping it tightly. "I'm here to #emph[stop] you."
"Why would you want to do that?" he asked, with honest curiosity. "Now we can be together forever, perfect and harmonious. No more differences, no more conflict, no more pain. You will be home. We'll have the peace we've always sought. All will be One."
"Never," Elspeth said.
Beside him, Tibalt was a nightmare of bony plates and protrusions connected by raw, braided sinew, recognizable as himself only through the smirk on the remaining fleshy portion of his face. His tail, always bifurcated at the tip, had split all the way to the base, and now terminated in two wicked stingers that dripped glistening oil onto the root path behind him.
"You were a monster in Kaldheim, and now you finally look the part," said Tyvar, surprisingly calm.
"Little princeling, too stupid to know when to be afraid," sneered Tibalt. "You were always going to end at my hand."
"Kaito, see the others to their destination," said Tyvar, not taking his eyes off Tibalt. "Elspeth and I will handle the vermin."
"Tyvar—"
"#emph[Go] ," snapped the elf, without turning. "These fights were predestined as ours to win. The skalds will sing of the stand we make today, but only if someone survives to tell our story. #emph[Go] ."
"If you say so," said Kaito, and waved a sad, forced goodbye as he turned to offer his arm to the limping Jace, guiding him toward the doorway at the back of the room. Kaya followed with one last regretful look, and the three vanished, leaving Tyvar and Elspeth alone with their transformed enemies.
"Very well then," said Tyvar, almost formally. "Shall we engage?"
#figure(image("007_Episode 4: Impossible Odds/05.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Ajani roared as Elspeth leapt toward him, and Tibalt lunged for Tyvar as Glimmervoid metal rippled across the hero's skin, and the battle was joined.
The screaming followed not long after.
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/loading/read.typ | typst | --- read-text ---
// Test reading plain text files
#let data = read("/assets/text/hello.txt")
#test(data, "Hello, world!\n")
--- read-file-not-found ---
// Error: 18-44 file not found (searched at assets/text/missing.txt)
#let data = read("/assets/text/missing.txt")
--- read-invalid-utf-8 ---
// Error: 18-40 file is not valid utf-8
#let data = read("/assets/text/bad.txt")
|
|
https://github.com/maxlambertini/troika-srd-typst | https://raw.githubusercontent.com/maxlambertini/troika-srd-typst/main/README.md | markdown | # Troika SRD
This is [Typst](https://typst.app) version of the Troika SRD.
This SRD is relased for free as a community project and is not affiliated with Melsonian Arts Council. If you'd like to contact me, please do this using github's project features.
# Credits:
**[Averia Serif Libre](https://fonts.google.com/specimen/Averia+Serif+Libre)** and **[Bokor](https://fonts.google.com/specimen/Bokor)** are licensed through [SIL Open Font License](https://fonts.google.com/specimen/Bokor).
Page borders and cover are created by me, but you can reuse them freely with no strings attached. |