repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/jamesrswift/chemicoms-paper | https://raw.githubusercontent.com/jamesrswift/chemicoms-paper/main/template/main.typ | typst | #import "@local/chemicoms-paper:0.1.0": template, elements;
#set page(paper: "us-letter", margin: (left: 10mm, right: 10mm, top: 12mm, bottom: 15mm))
#show: template.with(
title: [A typesetting system to untangle the scientific writing process],
abstract: (
[The process of scientific writing is often tangled up with the intricacies of typesetting, leading to frustration and wasted time for researchers. In this paper, we introduce Typst, a new typesetting system designed specifically for scientific writing. Typst untangles the typesetting process, allowing researchers to compose papers faster. In a series of experiments we demonstrate that Typst offers several advantages, including faster document creation, simplified syntax, and increased ease-of-use.],
(
title: "Plain Language Abstract",
content: lorem(50)
)
),
venue: [_Ars Bibliologia_],
header: (
article-color: rgb("#364f66"),
article-type: "Preprint",
article-meta: [Not Peer-Reviewed],
),
authors: (
(
name: "<NAME>",
),
(
name: "<NAME>",
corresponding: true,
orcid: ""
),
),
dates: (
(type: [Received Date], date: 2015),
(type: [Revised Date], date: datetime.today()),
(type: [Accepted Date], date: datetime.today())
),
doi: "00.0000/XXXXXXXXXX",
citation: [<NAME> and <NAME>, _Ars Bibliologia_, 2024, *3*, 1---2]
)
#elements.float(align: bottom, [\*Corresponding author])
= Introduction
Scientific writing is a crucial part of the research process, allowing researchers to share their findings with the wider scientific community. However, the process of typesetting scientific documents can often be a frustrating and time-consuming affair, particularly when using outdated tools such as LaTeX. Despite being over 30 years old, it remains a popular choice for scientific writing due to its power and flexibility. However, it also comes with a steep learning curve, complex syntax, and long compile times, leading to frustration and despair for many researchers. @netwok2020
== Paper overview
In this paper we introduce Typst, a new typesetting system designed to streamline the scientific writing process and provide researchers with a fast, efficient, and easy-to-use alternative to existing systems. Our goal is to shake up the status quo and offer researchers a better way to approach scientific writing.
By leveraging advanced algorithms and a user-friendly interface, Typst offers several advantages over existing typesetting systems, including faster document creation, simplified syntax, and increased ease-of-use.
To demonstrate the potential of Typst, we conducted a series of experiments comparing it to other popular typesetting systems, including LaTeX. Our findings suggest that Typst offers several benefits for scientific writing, particularly for novice users who may struggle with the complexities of LaTeX. Additionally, we demonstrate that Typst offers advanced features for experienced users, allowing for greater customization and flexibility in document creation.
Overall, we believe that Typst represents a significant step forward in the field of scientific writing and typesetting, providing researchers with a valuable tool to streamline their workflow and focus on what really matters: their research. In the following sections, we will introduce Typst in more detail and provide evidence for its superiority over other typesetting systems in a variety of scenarios.
= Methods
#lorem(90)
$ a + b = gamma $
#lorem(200)
#set heading(numbering: none)
= Conflicts of Interest
The authors have no conflicts of interest to declare. All co-authors have seen and agree with the contents of the manuscript and there is no financial interest to report.
= Acknowledgements
#lorem(20)
= Notes and References
#set par(justify: true, first-line-indent: 0pt);
#lorem(20)
#bibliography(title:none, style:"ieee", "references.bib") |
|
https://github.com/WinstonMDP/math | https://raw.githubusercontent.com/WinstonMDP/math/main/exers/3.typ | typst | #import "../cfg.typ": *
#show: cfg
$ "Prove that" sup_(QQ in.rev r < x) a^r = inf_(QQ in.rev r > x) a^r $
Suppose:
- $inf < sup$
$ex(r < x): inf < a^r$
$ex(r' > x): inf < a^r' < a^r$
$r < r'$
$bot$
- $sup < inf$
$sup_(QQ in.rev r < x) r < inf_(QQ in.rev r > x) r$
$x < x$
$bot$
|
|
https://github.com/i-am-wololo/cours | https://raw.githubusercontent.com/i-am-wololo/cours/master/main/parties_i23/axioms_predicats.typ | typst | #import "../templates.typ": *
#title("axiomes et predicats")
= Ensembles
#definition(title:"ensemble")[
Un ensemble est une collection X d'objets _definis_ et _unique_. un objet appartenant a l'ensemble est dit membre de _X_ et on dit que l'objet et membre.
un membre est unique dans un ensemble, il ne peut pas y avoir deux fois le meme element
]
exemple:
$ {a, b, c, a} = {a, b, c} $
sur python, un type ensemble existe qui est appele ```python set```
#definition(title:"Difference")[Soit $X$ et $Y$ deux enembles. la difference entre les ensembles $X$ et $Y$ est l'ensemble ${x in X | x in.not Y}$, qui est l'ensembles qui contients les elements de X mais pas les elements de Y. on note aussi $X\Y$ l'ensemble qui contient seulement les differences d'un ensemble $X sect Y$ est $X Delta Y$]
#definition(title:"Cardinal")[On appelle le cardinal d'un ensemble sa taille. Lorsqu'un ensemble est fini, le cardinal est la longueur de cette ensemble]
= Predicats
#definition(title:"Predicat")[enonce contenant des variables tel qu'en substituant chaque variables par une valeure choisi, on obtient une proposition]
exemple: $x|P(x)$ (se lit x tel que P(x)) est un predicat dans lesquelles la proposition P(x) est vraie pour x
la theorie de ZF distingue deux tyupes de predicats:
- 1. predicat collectivisant: un predicat $P(X)$ tel que les valeurs de x pour lesquelles la proposition P(x) est vrai constituent un enssemble note $(x|P(x))$
- 2. predicat non collectivisant: un predicat P(x) tel que les valeurss x pour lesquelles la prop P(X) est vraie ne constituent pas un ensemble
considerant le predicat $P(x, y)$ defini sur deux variables reelles x et y suivant:
$ x^2-y=1 $
on peut definir le predicat $Q(x)$ de la variable suivante:
$ exists y in RR x^2-y=1 $
= Quantificateurs
#definition(title: "quantificateur")[ Il existe 3 quantificateurs:
- $forall$ qui se lit "pour tout" (appele forall en latex et typst
- $exists$ qui se lit "il existe"
- $exists!$ qui est un "il existe" unique
]
le quantificateur $exists!$ est lui meme une proposition qui est:
$ (exists x in X P(X)) and (forall x in X forall y in X P(x) and P(y) => x = y$
le terme de gauche codel'existence et le terme droit l'unicite en exprimant sous forme contraposee que deux elements distincts $x$ et $y$ de l'ensemble $X$ ne peuvent simultanement satisfaire le predicat $P(x): x != => not(P(x) and P(y))$.
= Axiomes
#definition(title:"axiome")[Soit X et Y deux ensembles. on dit que X est inclus dans Y ou que X est une partie de Y ou encore que X est un sousensemble de Y, ce que l'ont note $X subset.eq Y$ ou $Y supset.eq X$ seulement si
$ forall x x in X => x in Y$
]
// #lorem(500)
// = Arbres de derivation
/*
* (regles de proposition)
* arbre de derivation
* <NAME>
* commutation
*/
= TP
|
|
https://github.com/ufodauge/master_thesis | https://raw.githubusercontent.com/ufodauge/master_thesis/main/src/template/components/common/heading.typ | typst | MIT License | #import "empty.typ" : Empty
#let HeadingWrapper(
body
) = [
#body
#Empty
]
#let H1(
body,
inset: (
top : 54pt,
bottom: 49pt,
left : 1pt,
)
) = HeadingWrapper(
block(
inset: inset,
text(
size : 24pt,
strong(body)
)
)
)
#let H2(body, inset: 0pt) = HeadingWrapper(
block(
inset: inset,
text(
size : 16pt,
strong(body)
)
)
)
#let H3-6(body, inset: 0pt) = HeadingWrapper(
block(
inset: inset,
text(
size : 14pt,
strong(body)
)
)
)
|
https://github.com/rabotaem-incorporated/calculus-notes-2course | https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/06-fourier-series/01-lebesgue-spaces.typ | typst | #import "../../utils/core.typ": *
== Пространства Лебега
#ticket[Пространства Лебега. Существенный супремум. Свойства. Вложение пространств Лебега. Полнота пространств $L^p (E, mu)$ (без доказательства).]
#def[
$(X, Aa, mu)$ --- пространство с мерой, $E in Aa$, $1 <= p < +oo$. Тогда _пространство Лебега $L^p$_ --- это
$
L^p (E, mu) := {
f: E --> overline(RR) "или" overline(CC) "измеримые"
space mid(|) space
integral_E abs(f)^p dif mu < +oo
}.
$
_Нормой_ в этом пространстве является
$
norm(f)_p = norm(f)_(L^p (E, mu)) := (integral_E abs(f)^p dif mu)^(1/p).
$
]
#props[
1. $norm(alpha f)_p = abs(alpha) norm(f)_p$.
2. $norm(f + g)_p <= norm(f)_p + norm(g)_p$.
3. $norm(f)_p >= 0$.
4. Если $norm(f)_p = 0$, то $f = 0$ почти везде на $E$.
]
#notice[
Есть только проблема: не выполняется свойство нормы о том, что норма равна нулю тогда и только тогда, когда функция равна нулю. Но это не так страшно.
Будем рассматривать функции с точностью до совпадения почти везде. На таких классах эквивалентности такая норма --- и правда норма.
]
#notice[
У такого класса эквивалентности не определено значение в точке.
]
#def[
_Существенный супремум_ --- обозначается $esssup$ или $op("vrai sup")$ --- это
$
esssup f := inf { C in RR : f(x) <= C "при почти всех" x }.
$
]
#props[
1. $esssup f <= sup f$.
2. $f(x) <= esssup f$ при почти всех $x$.
]
#proof[
1. Очев.
2. Пусть $a := esssup f$. Тогда $f(x) <= a + 1/n$ при почти всех $x$, то есть существует $e_n$, такие, что $f(x) <= a + 1/n$ при $x in E without e_n$. Тогда если $e := Union_(n = 1)^oo e_n$, то $mu e = 0$ и $f(x) <= a + 1/n$ для любого $x in E without e$. Переходим к пределу по $n$.
]
#def[
$(X, Aa, mu)$ --- пространство с мерой, $E in Aa$. Тогда _пространство Лебега $L^oo$_ --- это
$
L^oo (E, mu) := {
f: E --> overline(RR) "или" overline(CC) "измеримые"
space mid(|) space
esssup abs(f) < +oo
}.
$
_Нормой_ в этом пространстве является
$
norm(f)_oo = norm(f)_(L^oo (E, mu)) := esssup abs(f)
$
на тех же классах эквивалентности.
]
#example(name: "важный частный случай")[
При $E = NN$ получается, что $mu$ --- считающая мера.
Такое пространство обозначается $l^p := L^p (NN, mu)$.
Все функции в таком пространстве --- последовательности. Классы эквивалентности здесь не нужны, потому что мера любой точки равна $1$.
Норма последовательности --- это
$
norm(x)_p := (sum_(n = 1)^oo abs(x_n)^p)^(1/p), quad
norm(x)_oo := sup abs(x_n).
$
]
#th(name: "неравенство Гельдера")[
Пусть $1/p + 1/q = 1$, $1 <= p, q <= +oo$. Тогда для любых $f in L^p (E, mu)$ и $g in L^q (E, mu)$ верно
$
norm(f g)_1 <= norm(f)_p norm(g)_q.
$
]
#proof[
Если $p, q > 1$, то это просто неравенство Гельдера нам уже известное:
$
integral_E abs(f g) dif mu <= (integral_E abs(f)^p dif mu)^(1/p) (integral_E abs(g)^q dif mu)^(1/q).
$
Если $p = +oo$, то это неравенство вида
$
integral_E abs(f g) dif mu <= esssup abs(f) dot integral_E abs(g) dif mu,
$
что, очевидно, верно. Аналогично для $q = +oo$.
]
#th(name: "вложение в пространство Лебега")[
Если $mu E < +oo$, то при $p < q$, $L^q (E, mu) subset L^p (E, mu)$, и норма вложения оценивается как
$
norm(f)_p <= norm(f)_q (mu E)^(1/p - 1/q).
$
]
#proof[
Достаточно доказать неравенство на нормы, так как из него следует вложение по определению.
Воспользуемся неравенством Гельдера для $r = q / p$ и $s = r/(r - 1)$.
$
norm(f)_p^p =
integral_E abs(f)^p dif mu =
integral_E abs(f)^p dot 1 dif mu newline(<=)
(integral_E (abs(f)^p)^r dif mu)^(1/r) dot (integral_E 1^s dif mu)^(1/s) =
(integral_E abs(f)^q dif mu)^(p/q) dot (mu E)^(1 - p/q).
$
Отсюда получаем требуемое.
]
#notice[
Если $mu E = +oo$, то вложения нет.
]
#exercise(plural: true)[
1. Пусть $E = RR$, $mu = lambda_1$, $p < q$. Придумайте пример функции, что $f in L^q$, но $f in.not L^p$.
2. Доказать, что если $p < q$, то $l^p subset l^q$.
]
#ticket[Полнота пространств $L^p (E, mu)$ при $1 <= p < +oo$.]
#remind[
Метрическое пространство называется _полным_, если в нем любая фундаментальная последовательность сходится. В полных метрических пространствах верна куча классных утверждений.
]
#th[
Пространства $L^p (E, mu)$ --- полные.
]
#proof[
Мы будем доказывать теорему для $p < +oo$, хотя для $p = +oo$ теорема тоже верна, просто доказывается противно. К тому же, мы не будем даже пользоваться этой теоремой в таком стремном случае.
Рассмотрим фундаментальную последовательность $f_n$, то есть такую, что
$
forall eps > 0 space exists N space forall n, m >= N space norm(f_n - f_m)_p < eps.
$
Рассмотрим всякие $eps$:
$
eps &= 1/2: quad &&exists n_1 quad &forall n, m >= n_1 quad norm(f_m - f_n)_p &< 1/2, \
eps &= 1/4: quad &&exists n_2 >= n_1 quad &forall n, m >= n_2 quad norm(f_m - f_n)_p &< 1/4, \
eps &= 1/8: quad &&exists n_3 >= n_2 quad &forall n, m >= n_3 quad norm(f_m - f_n)_p &< 1/8, \
#hide[$dots.v$] #place(dy: -0.15cm, stack(spacing: 1cm, dir: ltr, ..for _ in range(9) { ($dots.v$,) })) \
eps &= 1/2^k: quad &&exists n_k >= n_(k - 1) quad &forall n, m >= n_k quad norm(f_m - f_n)_p &< 1/2^k.
$
Тогда $norm(f_(n_k) - f_(n_(k + 1)))_p < 1/2^k$ для любого $k$, а значит $ sum_(k = 1)^oo norm(f_(n_k) - f_(n_(k + 1)))_p < 1. $
Обозначим
$
S(t) &:= sum_(k = 1)^oo abs(f_(n_k) (t) - f_(n_(k + 1)) (t)), \
S_m (t) &:= sum_(k = 1)^m abs(f_(n_k) (t) - f_(n_(k + 1)) (t)).
$
Тогда
$
norm(S_m)_p = norm(sum_(k = 1)^m abs(f_(n_k) - f_(n_(k + 1))))_p <= sum_(k = 1)^m norm(f_(n_k) - f_(n_(k + 1)))_p < 1.
$
И
$
integral_E S^p dif mu = integral_E lim S_m^p dif mu <=^"л. Фату" liminf underbrace(integral_E S_m^p dif mu, norm(S_m)_p^p < 1) <= 1.
$
Значит $S$ почти везде конечна, $sum_(k = 1)^oo abs(f_(n_k) - f_(n_(k + 1)))$ сходится при почти всех $t$, а значит
$
f_(n_1) (t) + sum_(k = 1)^oo (f_(n_(k + 1)) (t) - f_(n_k) (t))
$
сходится при почти всех $t$. А частичная сумма этого ряда --- это $f_(n_m) (t)$, так как все остальные члены ряда сократятся при раскрытии телескопической суммы. Получается, существует
$
lim_(m -> oo) f_(n_m) (t) =: f(t)
$
при почти всех $t$.
Проверим, что это на самом деле сходимость по норме. Мы знаем
$
norm(f_n - f_n_k) < 1/2^m "при всех" n >= n_m, k >= m,
$
или, если раскрыть определение нормы,
$
integral_E abs(f_n (t) - f_n_k (t))^p dif mu < 1/2^(m p),
$
Тогда рассмотрим разность $f_n (t) - f(t)$ и докажем, что ее норма стремится к нулю:
$
integral_E abs(f_n (t) - f(t))^p =
integral_E lim_(k -> oo) abs(f_n (t) - f_n_k (t))^p dif mu newline(<=^"Фату")
liminf_(k -> oo) integral_E abs(f_n (t) - f_n_k (t))^p dif mu <
1/2^(m p) "при" n >= n_m and k >= m.
$
Тогда
$
norm(f_n - f)^p <= 1/2^(m p) "при" n >= n_m ==> norm(f_n - f) < 1/2^m.
$
]
#ticket[Плотность ступенчатых функций в $L^p (E, mu)$.]
#def[
Если $(X, rho)$ --- метрическое пространство, и $A subset X$, то $A$ называют _всюду плотным_, если $Cl A = X$.
]
#example[
В $(RR, abs(x - y))$, $QQ$ --- всюду плотно.
]
#def[
$f: E --> RR$ _ступенчатая_, если она принимает лишь конечное число значений#footnote[Отличие от простых в том, что иногда простыми считают только неотрицательные функции. Мы так не делали, но на всякий случай, чтобы было соответствие понятий с другими источниками, будем говорить так.].
]
#lemma[
Пусть $1 <= p < +oo$. Тогда ступенчатая функция $phi in L^p (E, mu)$ тогда и только тогда, когда $mu E {phi != 0} < +oo$.
]
#proof[
Пусть $a_1$, $a_2$, ..., $a_n$ --- все ненулевые значения $f$. $A_1$, $A_2$, ..., $A_n$ --- множества, на которых они принимаются. Тогда
$
norm(f)_p^p = integral_E abs(f)^p dif mu = sum_(k = 1)^n abs(a_k)^p mu A_k < +oo <==> mu A_k < +oo "для всех" k.
$
Значит, $E{phi != 0} = Union_(k = 1)^n A_k$.
]
#th[
Пусть $1 <= p <= +oo$. Тогда множество ступенчатых функций из $L^p (E, mu)$ всюду плотно в $L^p (E, mu)$.
]
#proof[
- Если $p = +oo$, то берем представителя класса эквивалентности, у которого $abs(f) <= norm(f)_oo$. Про него мы знаем, что найдутся неотрицательные ступенчатые (простые) функции $phi_n arrows f_+$ и $psi_n arrows f_-$. Тогда $phi_n - psi_n arrows f_+ - f_- = f$. Тогда $sup abs((phi_n - psi_n) - f) --> 0$, а значит $esssup abs(...)$ тем более, и $norm((phi_n - psi_n) - f)_oo --> 0$.
- Если $1 <= p < +oo$, то возьмем неотрицательные ступенчатые $phi_n arrow.tr f_+$ и $psi_n arrow.tr f_-$. Тогда $ norm(f_+ - phi_n)_p^p = integral_E (f_+ - phi_n)^p dif mu -->^"<NAME>" 0, $
где $f_+^p <= abs(f)^p$ --- суммируемая Мажоранта. Аналогично, $norm(f_- - psi_n) --> 0$, и
$
norm((f_+ - f_-) - (phi_n - psi_n))_p <= norm(f_+ - phi_n)_p + norm(f_- - psi_n)_p --> 0.
$
]
#ticket[Плотность бесконечно дифференцируемых функций в $L^p (E, mu)$ (без доказательства). Теорема о непрерывности сдвига.]
#def[
$f$ --- _финитная функция_, если $f = 0$ вне какого-то компакта. Равносильно тому, что множество ${f != 0}$ ограничено (в качестве компакта можно взять его замыкание).
]
#th[
Пусть $1 <= p < +oo$ и $E subset RR^m$ измеримое.
Тогда множество бесконечно дифференцируемых финитных функций плотно в $L^p (E, lambda_m)$.
]
#proof[
Без доказательства. Но идея примерно такая: знаем, что ступенчатые функции плотны, поэтому надо приблизить ступенчатую функцию бесконечно дифференцируемой. Для этого надо приблизить одну ступеньку, а ее можно приблизить кучей открытых прямоугольников. Ну их мы придумаем как приближать: надо рассмотреть гладкие функции которые примерно как индикаторы, но на границах вместо скачка делают все более и более быстрый гладкий подъем. Короче, надо возиться, чтобы это формализовывать, мы не будем.
]
#def[
Пусть $f: RR^d --> RR$, $h in RR^d$. Тогда $f_h (x) := f(x + h)$ --- _сдвиг функции_ на вектор $h$.
]
#th(name: "о непрерывности сдвига")[
1. Если $f$ равномерно непрерывна на $RR^d$, то $norm(f - f_h)_oo -->_(h -> 0) 0.$
2. Если $f in C(RR)$ и $2pi$-периодична, то $norm(f - f_h)_oo -->_(h -> 0) 0$.
3. Если $f in L^p (RR^d, lambda_d)$ при $1 <= p < +oo$, то $norm(f - f_h)_p -->_(h -> 0) 0.$
]
#proof[
1. $norm(f - f_h)_oo <= sup_(x in RR^d) abs(f(x) - f(x + h)) --> 0$ из определения равномерной непрерывности.
2. На каждом периоде есть равномерная непрерывность, а значит и везде она есть.
3. Возьмем $eps > 0$ и непрерывную финитную функцию $g$ такую, что $norm(f - g)_p < eps$. Тогда
$
norm(f - f_h)_p <= underbrace(norm(f - g)_p, < eps) + norm(g - g_h)_p + underbrace(norm(g_h - f_h)_p, < eps) = 2 eps + norm(g - g_h)_p.
$
Надо доказать, что $norm(g - g_h)_p < eps$ при малых $h$. Доказываем,
$
norm(g - g_h)_p^p = integral_(RR^d) abs(g (x) - g (x + h))^p dif mu (x).
$
Так как $g$ --- финитная, то $g = 0$ вне шара $B_R (0)$, а так как $g_h$ --- просто немного сдвинутая $g$, она тоже равна нулю вне $B_(R + 1) (0)$. Тогда
$
norm(g - g_h)_p^p =
integral_(RR^d) abs(g (x) - g (x + h))^p dif mu (x) =
integral_(B_(R+1) (0)) abs(g (x) - g (x + h))^p dif mu (x) newline(<=)
lambda B_(R + 1) (0) dot underbrace(sup_(x in B_(R + 1) (0)) abs(g(x) - g(x + h))^p, --> 0).
$
]
|
|
https://github.com/floriandejonckheere/utu-thesis | https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/figures/05-modular-monolith/modular-monolith.typ | typst | #import "@preview/cetz:0.2.2"
#set text(font: "Fira Sans", size: 9pt)
#cetz.canvas(length: 1cm, {
import cetz.draw: *
set-style(
content: (padding: .2),
stroke: black
)
// Monolith
rect(
(0, 0), (4, 3),
radius: 0.1,
fill: orange.lighten(90%),
stroke: (paint: orange.lighten(60%)),
name: "monolith")
content("monolith.south", text: gray, align(center, [#v(3em)Monolith]))
// Modular monolith
rect(
(4.5, 0), (8.5, 3),
radius: 0.1,
fill: orange.lighten(90%),
stroke: (paint: orange.lighten(60%)),
name: "modular_monolith")
content("modular_monolith.south", text: gray, align(center, [#v(5em)Modular\ monolith]))
rect(
(4.75, 0.25), (6, 1),
radius: 0.05,
fill: orange.lighten(70%),
stroke: (paint: orange.lighten(30%)),
name: "modular_monolith_1")
rect(
(7, 0.25), (8.25, 1),
radius: 0.05,
fill: orange.lighten(70%),
stroke: (paint: orange.lighten(30%)),
name: "modular_monolith_2")
rect(
(4.75, 2), (6, 2.75),
radius: 0.05,
fill: orange.lighten(70%),
stroke: (paint: orange.lighten(30%)),
name: "modular_monolith_3")
rect(
(7, 2), (8.25, 2.75),
radius: 0.05,
fill: orange.lighten(70%),
stroke: (paint: orange.lighten(30%)),
name: "modular_monolith_4")
line("modular_monolith_2.west", "modular_monolith_1.east", mark: (end: ">", fill: black))
line("modular_monolith_2.north", "modular_monolith_4.south", mark: (end: ">", fill: black))
line("modular_monolith_4.west", "modular_monolith_3.east", mark: (end: ">", fill: black))
line("modular_monolith_1.north", "modular_monolith_3.south", mark: (end: ">", fill: black))
line("modular_monolith_4.south-west", "modular_monolith_1.north-east", mark: (end: ">", fill: black))
// Microservices
rect(
(9, 0), (13, 4),
radius: 0.1,
stroke: none,
name: "microservices")
content("microservices.south", text: gray, align(center, [#v(3em)Microservices]))
rect(
(9.25, 0.25), (10.5, 1),
radius: 0.05,
fill: orange.lighten(70%),
stroke: (paint: orange.lighten(30%)),
name: "microservices_1")
rect(
(11.25, 0.25), (12.5, 1),
radius: 0.05,
fill: orange.lighten(70%),
stroke: (paint: orange.lighten(30%)),
name: "microservices_2")
rect(
(9.25, 2), (10.5, 2.75),
radius: 0.05,
fill: orange.lighten(70%),
stroke: (paint: orange.lighten(30%)),
name: "microservices_3")
rect(
(11.25, 2), (12.5, 2.75),
radius: 0.05,
fill: orange.lighten(70%),
stroke: (paint: orange.lighten(30%)),
name: "microservices_4")
line("microservices_2.west", "microservices_1.east", mark: (end: ">", fill: black))
line("microservices_2.north", "microservices_4.south", mark: (end: ">", fill: black))
line("microservices_4.west", "microservices_3.east", mark: (end: ">", fill: black))
line("microservices_1.north", "microservices_3.south", mark: (end: ">", fill: black))
line("microservices_4.south-west", "microservices_1.north-east", mark: (end: ">", fill: black))
})
#v(2em)
|
|
https://github.com/UM-nerds/modern-report-umfds | https://raw.githubusercontent.com/UM-nerds/modern-report-umfds/main/src/lib.typ | typst | MIT License | #let umfds(
title: "",
authors: (),
date: none,
img: none,
abstract: none,
bibliography: none,
lang: "en",
body
) = {
set page(paper: "a4", numbering: "1")
set heading(numbering: "1.1 ")
show heading: it => block(below: 1em, it)
set par(justify: true, first-line-indent: 1em)
show par: set block(spacing: 0.65em)
set text(
lang: lang,
)
grid(
columns: (1fr, 4fr, 1fr),
rect(width: 100%, stroke: none)[
#image("assets/um.png", width: 100%)
],
rect(width: 100%, stroke: none),
rect(width: 100%, stroke: none)[
#image("assets/fds.png", width: 100%)
]
)
v(1.5cm)
align(center)[
#text(17pt)[
#block(width: 85%)[
#title
]
]
]
v(.5em)
align(center)[
#grid(
columns: (1fr,) * authors.len(),
..authors
)
]
v(.5em)
align(center)[
#if lang == "en" [
Faculty of Sciences
University of Montpellier
] else [
Faculté des Sciences
Université de Montpellier
]
#v(.5em)
#date
]
v(2em)
if img != none [
#if abstract == none [
#v(3em)
]
#align(center)[
#img
]
#v(2em)
] else [
#v(3em)
]
if abstract != none [
#align(center)[
#block(width: 85%)[
#if lang == "en" [
*Abstract*
] else [
*Résumé*
]
#align(left)[
#abstract
]
]
]
]
pagebreak()
body
if bibliography != none [
#pagebreak()
#bibliography
]
}
|
https://github.com/sabitov-kirill/comp-arch-conspect | https://raw.githubusercontent.com/sabitov-kirill/comp-arch-conspect/master/questions/9_isa.typ | typst | #heading[ISA.]
#emph[ISA (Архитектура фон Неймана и ее альтернативы. Что описывает ISA? Assembler MIPS).]
#import "/commons.typ": imagebox
== Архитектура фон Неймана
#emph[Архитектура фон Неймана (a.k.a. Принстонская архитектура)] — широко известный принцип совместного хранения команд и данных в памяти компьютера. В общем случае, когда говорят об архитектуре фон Неймана, подразумевают принцип хранения данных и инструкций в одной памяти, но вообще она включает в себя пять базисных принципов устройства ЭВМ:
=== Использование двоичной системы счисления
ЭВМ, реализующая архитектуру фон Неймана должна использовать двоичную систему счисления.
_Альтернативы:_
#columns(2)[
#imagebox("difference_engine.jpg", height: 140pt, label: [
_Аналитическая машина Бэббиджа_ --- первая в мире программируемая вычислительная машина, работает на основе десятичной системы счисления.
])
#colbreak()
#imagebox("soviet_setun.jpg", height: 140pt, label: [
_Советская «Сетунь»_ — единственная в мире ЭВМ на основе троичного кода.
])
]
=== Принцип адресности памяти
Структурно основная память состоит из пронумерованных ячеек, причём процессору в произвольный момент доступна любая ячейка. Двоичные коды команд и данных разделяются и хранятся в ячейках памяти, а для доступа к ним используются номера соответствующих ячеек — адреса.
_Альтернативы:_
#columns(2)[
#imagebox("jvm_stack_and_heap.png", label: [
Стековая архитектура\
(«Сетунь», JVM)
])
#colbreak()
#imagebox("turing_machine.jpeg", label: [
Ленточная архитектура\
(машина Алана Тьюринга)
])
]
#pagebreak()
=== Однородность памяти
Код и данные хранятся в одной и той же памяти.
_Альтернативы:_
#imagebox("harvard_architecture.png", height: 150pt, label: [
Гарвардская архитектура\
(память данных и команд раздельна)
])
#columns(2)[
#align(center)[#strong[Архитектура фон Неймана]]
#align(center)[_Плюсы_]
- Можно эффективно использовать всю имеющуюся память.
- Проще контроллер.
- Одна шина.
#align(center)[_Минусы_]
- Так как инструкции хранятся в памяти, их можно случайно испортить во время выполнения программы.
#align(center)[_Непонятно_]
- Однородный доступ к коду и данным.
#colbreak()
#align(center)[#strong[Гарвардская архитектура]]
#align(center)[_Плюсы_]
- Можно одновременно читать и код, и данные.
- Если сделать память кода read-only, то вполне безопасно.
#align(center)[_Минусы_]
- Усложняется контроллер памяти.
- В 2 раза больше шин.
- Память может "простаивать без дела". Наример, если программа маленькая.
#align(center)[_Непонятно_]
- Для данных и инструкций можно использовать память с разными характеристиками.
]
=== Принцип программного управления
ЭВМ выполняет программы, записанные в памяти. Альтернативой были попытки "зашить" программу прямо в железо, но, очевидно, такой подход обречён, так как он предлагает гораздо более маленькую вариативность кода: под конкретную программу нужно собирать свою железку.
=== Принцип последовательного выполнения команд
Казалось бы, понятный принцип, который соблюдается в современных компьютерах: команды выполняются последовательно, одна за другой. Но с появлением многоядерных процессоров возникло многопоточное программирование. Так что, фактически, каждый компьютер, в котором установлен многоядерный процессор, нарушает данный принцип.
== ISA (Instruction Set Architecture)
#emph[ISA] --- это абстрактная модель компьютера. Как правило, #emph[ISA] определяет архитектуру памяти, разрядность адресов, режими адресации, количество регистров, наборы команд машинного языка и их кодирование, типы данных, обработку исключений, etc.
Примеры #emph[ISA]:
- x86
- ARM
- RISC-V
- MIPS
#pagebreak()
=== Огранизация памяти и взаимодействие с памятью
#columns(2)[
#align(center)[*Стековая*]
- Операнды лежат на стеке
- Операция берёт два значения с верхушки стека и возвращает одно
#align(center)[*Reg-Reg*]
- Операнды в регистрах, результат помещается в регистр
#align(center)[*Reg-Mem*]
- Один из операндов может быть из памяти
#colbreak()
#align(center)[*Аккумуляторная*]
- Стек размера 1
- Один операнд из аккумулятора, второй из памяти. Результат помещается в аккумулятор
#align(center)[*Mem-Mem*]
- Оба операнда могут быть из памяти
]
=== Кодирование команд
#columns(2)[
#align(center)[*Команды переменной длины*]
- Команды имеют разную длину
- Частоиспользуемые команды могут кодироваться меньшим количеством байт, что хорошо
- Сложно декодировать
#emph[ISA x86]: команды имеют длину 1-15 байт
#colbreak()
#align(center)[*Команды постоянный длины*]
- Команды имеют постоянную длину
- Иногда приходится разбивать одну команду на две из-за нехватки бит для сложных команд
- Просто декодировать
В #emph[MIPS] все команды по 4 байта
]
=== Наборы команд
#columns(2)[
#align(center)[*CISC - complex instruction set computer*]
- Акцент за железо
- Минимизируется количество инструкций в програиме
- Инструкции могут выполнятся несколько тактов процессора
- Сложнее реализация железа
#colbreak()
#align(center)[*RISC - reduced instruction set computer*]
- Акцент за программы
- Сложные команды реализуются программно через простые
- Все инструкции выполняются за один такт
- Проще реализация железа
]
Архитектура x86 предоставляет программисту интерфейс CISC, но под капотом интерпритирует команды в простейшие RISC инструкции.
=== Режимы адресации
- Register: add r1 r2 r3, _(r1 = r2 + r3)_
- Immediate: add r1 r2 5, _(r1 = r2 + 5)_
- Register inderect: add r1 r2 (r3), _(r1 = r2 + mem\[r3\])_
- Displacement: add r1 r2 100(r3), _(r1 = r2 + mem\[100+r3\])_
- Absolute: add r1 r2 0xabcd, _(r1 = r2 + mem\[0xabcd\])_
#pagebreak()
== Assembler MIPS
=== Регистры
#imagebox("mips_registers.png", height: 200pt)
=== Типы команд
#columns(3)[
#imagebox("mips_r-type.png", width: 170pt, label: [
op - код операции\
rs, rt - регистры операндов\
rd - регистр для результата\
shamt - для побитового сдвига\
funct - доп. код операции\
])
#colbreak()
#imagebox("mips_i-type.png", width: 170pt, label: [
op - код операции\
rs - регистр операнда\
rt - регистр для результата\
imm - 16-и битная константа
])
#colbreak()
#imagebox("mips_j-type.png", width: 170pt, label: [
op - код операции\
addr - адрес, с которого произойдет дальшейшее исполнение инструкций
])
#colbreak()
]
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/01-history/history.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/heading.typ": chapter
#import "/template/components.typ": note
#import "/lib/glossary.typ": tr
#show: web-page-template
#chapter[
// A Brief History of Type
字体简史
]
// Once upon a time, a *font* was a bunch of pieces of metal. The first recorded use of metal type for printing comes from China. In 13th century, banknotes were printed with anti-counterfeit devices printed using blocks of bronze;[^2] the first metal type books were produced in Korea around the same time.[^1] Two hundred years later, Johannes Gutenberg came up with a similar system for creating metal type that would spread rapidly over Europe and continue to be the most common means of printing until the 19th century.
在很久以前,*字体*这个词指的是一堆金属块。关于金属印刷的最早记录来自中国。在13世纪,带有防伪措施的纸币就已经使用铜版来印制@Pan.ZhongGuo.2001[273];几乎同一时间,朝鲜半岛也首次出现了金属印刷的书籍@Park.HistoryPreGutenberg.2014。两百年之后,Johannes Gutenberg发明了一种类似的金属活字系统,它很快传遍了欧洲,并且作为最普遍的印刷技术一直延续到19世纪。
// To create type for printing, engravers would work the images of letters, numbers and so on into punches. Punches would then be struck into a mold called a *matrix*. The typemaker would then use the matrices to cast individual pieces of type (also known as *sorts*). A complete set of type sorts in the same size and style was collected together into a *font* of type.
为了制作印刷用字,刻字师会将字母、数字等的图形雕刻在#tr[punch]上,字冲则会被敲入称为*#tr[matrix]*的模具中。接下来,铸字师会用#tr[matrix]翻刻出一个个的字,这被称为*#tr[sort]*。同样尺寸和样式的一组#tr[sort]就构成了一套*字体*(@figure:fonts)。
#figure(caption: [
// A box of fonts cast by the Australian Type Foundry. The font on the top left is a 14pt Greek typeface by <NAME>.
一套Australian Type Foundry铸造的字体。左上是Eric Gill设计的 14pt 希腊字母。
])[
#image("fonts.jpg")
] <figure:fonts>
// Complete fonts of type would be placed into type cases, from which compositors would then select the sorts required to print a page and arrange them into lines and pages. Next, the printer would cover the face of the metal with ink and impress it onto the paper. With the advent of hot metal typesetting, which combined casting and compositing into one automated activity, the idea of a font of type fell out of fashion.
一套完整的字体会被放在#tr[type case]中,排版工将从中挑选出排版所需的#tr[sort],并将它们逐行、逐页地排好。之后,印刷机会在金属的表面覆盖一层油墨,再压印到纸上。随着将铸字与排版合二为一的#tr[hot metal typesetting]的诞生,成套的印刷字体也逐渐落后于潮流。
// The idea was revived with the advent of digital typography. In 1964, the IBM 2260 Display Station provided one of the first text-based visual interfaces to a computer.[^3] The mainframe computer would generate the video signal and send it to the terminal, pixel by pixel: each character was 9 pixels wide and 14 pixels tall. The choice of bitmaps for each character, what we would now call the font, was hard-wired into the mainframe, and could not be changed.
随着数字印刷术的出现,这个想法又得以复兴。1964年,IBM 2260 Display Station 为计算机提供了第一个基于文本的可视化界面@DaCruz.IBM2260.2001。大型机生成视频信号,并将其逐像素发送到终端:每个字符9像素宽、14像素高。代表字符的这些#tr[bitmap](我们今天称为字体)是被硬编码在大型机中的,无法进行修改。
// Much has changed since the early bitmap fonts, but in a sense one thing has not. The move from Gutenberg's rectangular metal sorts to rectangular 9x14 digital bitmaps ensured that computer typography would be dominated by the alignment of rectangles along a common baseline - an unfortunate situation for writing systems which don't consist of a straight line of rectangles.
从早期的#tr[bitmap]到今天,字体已经有了天翻地覆的变化,但有样东西却从未变过。从Gutenberg使用的矩形金属活字,到9x14的数字#tr[bitmap],它们决定了计算机字体技术的主要实现方式:沿着一条#tr[baseline]排列矩形块。这对那些不依靠直线和矩形的#tr[writing system]来说是一件不幸的事。
#figure(caption: [
// No OpenType for you!
你可没有 OpenType!
])[#image("640px-Ghafeleye_Omr.svg.png")] <figure:Ghafeleye_Omr>
// This is one of the reasons why I'm starting this book with a description of digital font history: the way that our fonts have developed over time also shapes the challenges and difficulties of working with fonts today. At the same time, the history of digital fonts highlights some of the challenges that designers and implementers have needed to overcome, and will equip us with some concepts that we will get further into as we go through this book. So even if you're not a history fan, please don't skip this chapter - I'll try and make it as practical as possible.
这就是我把数字字体的历史作为本书开端的原因。随着时间的推移,字体的发展历程也造就了今天我们设计、实现和使用字体时的困难和挑战。不过通过本书的后续介绍,这段历史更能让我们了解一些在处理这些难题时需要用到的重要概念。所以即使你不是一个历史迷,也请不要跳过这一章——我会让它尽可能的实用。
// For example, then, in the case of the wonderful Nastaleeq script above, we can understand why this is going to be difficult to implement as a digital font. We can understand the historical reasons behind why this situation has come about. At the same time, it highlights a common challenge for the type designer working with global scripts, which is to find ways of usefully mapping the computer's Latin-centered model of baselines, bounding boxes, and so on, onto a design in which these structures may not necessarily apply. Some of these challenges can be overcome through developments in the technology; some of them will need to be worked around. We will look at these challenges in more detail over the course of the book.
例如,在@figure:Ghafeleye_Omr 所示的波斯体#tr[script]例子中,我们将能够理解为什么把它做成数字字体会很困难。我们可以理解这种情况产生的历史原因。与此同时,它也展现了#tr[global scripts]字体设计师经常面临的难题,即寻找一种把计算机中以拉丁字母为中心的模型——包括#tr[baseline]、#tr[bounding box]等——对应到设计中的手段,而这些东西在设计中却不一定适用。其中的一些挑战可以凭借技术的发展来克服,而有些问题则需要找寻变通的方案。在本书中,我们后续会更为详细地探讨这些挑战。
|
https://github.com/TheBotlyNoob/ECE1551 | https://raw.githubusercontent.com/TheBotlyNoob/ECE1551/main/homework/template.typ | typst | #show link: underline
#show link: set text(blue)
= ECE 1551 Assignment Chapter REPLACEME_CHAPTER
|
|
https://github.com/rabotaem-incorporated/calculus-notes-2course | https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/04-parametric-and-curves/04-hypergeometric-function.typ | typst | #import "../../utils/core.typ": *
== Гипергеометрическая функция
#def(label: "def-rising-factorial")[
_Возрастающая факториальная степень_:
$ a^(overline(k)) harpoons.ltrb (a)_k := a (a + 1) (a + 2) ... (a + k - 1) =^rf("gamma-props", "plus-1") (Gamma(a + k)) / (Gamma(a)). $
Здесь $a in CC$. Конечно, наше текущее определение $Gamma$-функции не позволяет работать с комплексными аргументами, но скоро#rf("gamma-continuation") мы сможем аналитически продолжить $Gamma$ на почти всю комплексную плоскость, и определение станет иметь смысл.
]
#notice(label: "rising-factorial-growth")[
$Gamma(a + k) tilde_(k -> oo) k^a Gamma(k)$#rf("gamma-plus-const-growth"), следовательно $a^overline(k) tilde_(k -> +oo) Gamma(k)/Gamma(a) k^a$
]
#example(label: "hypergeometric-1/(1-x)^a")[
Мотивационный пример. Рассмотрим следующую функцию:
$
1/(1 - x)^a
newline(=)
1 + (-a)/(1!)(-x) + ((-a)(-a-1))/(2!)(-x)^2 + ... + ((-a)(-a - 1)...(-a-k + 1))/(k!)(-x)^k + ...
newline(=)
sum_(k = 0)^oo (a^overline(k))/(k!) x^k.
$
Этот ряд, как и многие другие, имеют коэффициенты, выражающиеся через возрастающую факториальную степень#rf("def-rising-factorial").
]
#let hyperg(F: $F$, x: $x$, n: $$, m: $$, top, bot, var) = $
attach(#F, bl: #m, br: #n) (lr(vec(delim: #none, top.join(sym.space), bot.join(sym.space)) space bar) space #var.join(sym.space))
$
#def(label: "def-hypergeometric-series")[
_Гипергеометрический ряд_ $a_1, ..., a_m$, $b_1, ..., b_n in CC$, где $b_j != 0, -1, -2, ...$:
$
hyperg(m: m, n: n, a_1, ..., a_m; b_1, ..., b_n; z) := sum_(k = 0)^oo (a_1^overline(k) ... a_m^overline(k))/(b_1^overline(k) ... b_n^overline(k)) (z^k)/(k!)
$
Альтернативное обозначение: $attach(F, bl: m, br: n) (a_1, ..., a_m; b_1, ..., b_n; z)$
]
#th(label: "hypergeometric-convergence")[
- Если $m <= n$, то радиус сходимости гипергеометрического ряда равен $oo$.
- Если $m > n + 1$, то радиус сходимости гипергеометрического ряда равен $0$.
- Если $m = n + 1$, то радиус сходимости гипергеометрического ряда равен $1$.
]
#proof[
Обозначим члены ряда как $x_i$. Применим признак Даламбера#rf("d'alembert"):
$
lim abs(x_(k + 1))/abs(x_k) = lim (abs(a_1^overline(k+1)) ... abs(a_m^overline(k + 1)))/(abs(b_1^overline(k + 1)) ... abs(b_n^overline(k + 1))) abs(z^cancel((k + 1)))/((k + 1)cancel(!)) dot (abs(b_1^overline(k)) ... abs(b_m^overline(k)))/(abs(a_1^overline(k)) ... abs(a_m^overline(k))) (cancel(k!))/(cancel(abs(z)^k)) = \ = abs(z) lim abs(((a_1 + k)...(a_m + k))/((b_1 + k)...(b_n + k))) dot 1/(k + 1) = cases(
0\, "если" m <= n,
+oo\, "если" m > n + 1,
abs(z)\, "если" m = n + 1
).
$
]
#examples[
Частные случаи:
1. $ 1/(1 - x)^a = hyperg(m: 1, n: 0, a; space; x) = hyperg(a, 1; 1; x). $
2. $ ln(1-x) = -sum_(k = 1)^oo (x^k)/(k) = -x dot sum_(k = 0)^oo (x^k)/(k + 1) = -x hyperg(1, 1; 2; x). $
3. $ ln (1+x)/(1-x) = ln(1 + x) - ln(1 - x) = x sum_(k = 0)^oo ((-x)^k)/(k + 1) + x sum_(k = 0)^oo (x^k)/(k + 1) = 2x sum_(k = 0)^oo (x^(2k))/(2k + 1) = 2x hyperg(1/2, 1; 3/2; x^2). $
4. $ arcsin x = x hyperg(1/2, 1/2; 3/2; x^2). $
5. $ arctan x = x hyperg(1/2, 1; 3/2; -x^2). $
6. $ K(x) = integral_0^1 (dif t)/(sqrt((1-t^2)(1 - x^2 t^2))) = pi/2 hyperg(1/2, 1/2; 1; x^2). $
Эта функция называется _эллиптическим интегралом первого рода_.
]
#th(label: "hypergeometric-criteria")[
Степенной ряд $sum_(k = 0)^oo c_k z^k$ с ненулевыми коэффициентами является гипергеометрическим#rf("def-hypergeometric-series") (то есть вида $c hyperg(...; ...; alpha z)$) тогда и только тогда, когда отношение его соседних коэффициентов $c_(k + 1)/c_k$ является рациональной функцией от $k$.
]
#proof[
- "$==>$": Очевидно: можно просто рассмотреть отношение соседних коэффициентов в гипергеометрическом ряде#rf("def-hypergeometric-series").
- "$<==$": Знаем $c_(k + 1)/c_k = (P(k))/(Q(k))$. Пусть $-a_1, ..., -a_m$ --- все корни $P$, $-b_1, ..., -b_n$ --- все корни $Q$, возможно комплексные. Тогда
$
c_(k + 1)/c_k = (P(k))/(Q(k)) = alpha ((k + a_1)(k + a_2)...(k+a_m))/((k + b_1)(k + b_2)...(k + b_n)),
$
из чего можно вывести общую формулу для коэффициентов $c_k$:
$
c_k = c_0 alpha^(k + 1) (a_1^overline(k + 1)...a_m^overline(k + 1))/(b_1^overline(k + 1)...b_n^overline(k + 1)) dot (1^overline(k + 1))/((k + 1)!),
$
а это коэффициенты гипергеометрического ряда#rf("def-hypergeometric-series")
$
c_0 hyperg(a_1, ..., a_m, 1; b_1, ..., b_n; alpha z)
$
]
#th(name: "Интегральное представление для гипергеометрических функций", label: "hypergeometric-integral")[
$ hyperg(a, b; c; x) = Gamma(c)/(Gamma(b)Gamma(c - b)) integral_0^1 (t^(b - 1) (1 - t)^(c - b - 1))/(1 - x t)^a dif t $
при $0 < b < c$ и $abs(x) < 1$.
]
#proof[
Известно, что
$
1/(1 - x t)^a =^rf("hypergeometric-1/(1-x)^a")
sum_(k = 0)^oo (x t)^k/(k!) a^overline(k).
$
Подставим это в интеграл:
$
integral_0^1 (t^(b - 1) (1 - t)^(c - b - 1))/(1 - x t)^a dif t
=
integral_0^1 sum_(k = 0)^oo t^(k + b - 1) dot (1-t)^(c - b - 1) dot (x^k)/(k!) a^overline(k) dif t
newline(=^*)
sum_(k = 0)^oo integral_0^1 t^(k + b - 1) dot (1-t)^(c - b - 1) dot (x^k)/(k!) a^overline(k) dif t
=
sum_(k = 0)^oo (x^k)/(k!) a^overline(k) dot underbrace(
integral_0^1 t^(k + b - 1) dot (1-t)^(c - b - 1) dif t,
B(k + b, c - b)^rf("def-euler-integrals") =^rf("beta-through-gamma") (Gamma(b + k)Gamma(c - b))/(Gamma(c + k))
)
newline(=)
Gamma(c - b) sum_(k = 0)^oo (a^overline(k) Gamma(b + k))/Gamma(c + k) dot (x^k)/(k!)
=^rf("def-rising-factorial")
(Gamma(c - b) Gamma(b))/Gamma(c) sum_(k = 0)^oo (a^overline(k) b^overline(k))/c^overline(k) dot (x^k)/(k!)
$
Почему можно менять местами интеграл и сумму в $*$? Что такое сумма? Это интеграл по дискретной мере, причем очевидно, что эта дискретная мера полная и $sigma$-конечная. Можно применить теорему Фубини, если покажем, что функция суммируема. Оценим интеграл модуля подынтегрального выражения#rf("sfn-props", "abs-bound"):
$
integral_0^1 sum_(k = 0)^oo abs(t^(k + b - 1) dot (1-t)^(c - b - 1) dot (x^k)/(k!) a^overline(k)) dif t
<=
integral_0^1 sum_(k = 0)^oo t^(b - 1) (1-t)^(c - b - 1) dot t^k dot (abs(x)^k)/(k!) abs(a)^overline(k) dif t.
$
Рассмотим подынтегральное выражение при $k --> +oo$:
$
t^(b - 1) (1-t)^(c - b - 1) dot t^k dot (abs(x)^k)/(k!) abs(a)^overline(k) tilde^rf("rising-factorial-growth")
t^(b - 1) (1-t)^(c - b - 1) dot t^k dot (abs(x)^k)/(k!) dot Gamma(k)/Gamma(abs(a)) k^abs(a) newline(=)
t^(b - 1) (1-t)^(c - b - 1) dot t^k dot (abs(x)^k k^(abs(a) - 1))/Gamma(abs(a)).
$
Эта штука абсолютно сходится, так как доминирующий множитель в ней --- $abs(x)^k$, поэтому при $k --> +oo$, интеграл ограничен суммируемой мажорантой. При небольших $k$ это $Beta$-функция#rf("def-euler-integrals") на константу для любого $k$, поэтому при небольших $k$ тоже есть ограниченность мажорантой. Значит есть суммируемость.
]
#follow(name: "<NAME>", label: "gauss-hypergeometric")[
$ hyperg(a, b; c; 1) = (Gamma(c) Gamma(c - a - b))/(Gamma(c - a) Gamma(c - b)) $
при $c > a + b$ и $0 < b < c$. Вообще, условия можно ослабить, но у нас не хватает iq.
]
#proof[
$ hyperg(a, b; c; 1) = sum_(k = 0)^oo (a^overline(k) b^overline(k))/(c^overline(k)) dot 1/(k!) $
Заметили выше#rf("rising-factorial-growth"), что $a^overline(k) tilde_(k -> +oo) Gamma(k)/Gamma(a) k^a$. Тогда
$
(cancel(a^overline(k)) b^overline(k))/(c^overline(k)) dot (1/k!) tilde ((cancel(Gamma(k)) k^a) / Gamma(a) dot (cancel(Gamma(k)) k^b)/Gamma(b)) / ((cancel(Gamma(k)) k^c)/Gamma(c) dot cancel(Gamma(k)) dot k) = const / (k^(c - a - b + 1)).
$
А значит в единице есть сходимость (у нас сходимость гарантиуется только внутри единичной окружности#rf("hypergeometric-convergence"), а не на ней).
$
hyperg(a, b; c; 1) =
lim_(x -> 1-) hyperg(a, b; c; x) =^rf("hypergeometric-integral")
lim_(x -> 1-) Gamma(c)/(Gamma(b) Gamma(c - b)) integral_0^1 (t^(b - 1) (1 - t)^(c - b - 1))/(1 - x t)^a dif t newline(=^*)
integral_0^1 lim_(x -> 1-) Gamma(c)/(Gamma(b) Gamma(c - b)) (t^(b - 1) (1 - t)^(c - b - 1))/(1 - x t)^a dif t =
Gamma(c)/(Gamma(b) Gamma(c - b)) integral_0^1 t^(b - 1) (1 - t)^(c - a - b - 1) dif t newline(=)
Gamma(c)/(Gamma(b) Gamma(c - b)) Beta(b, c - a - b) =^rf("beta-through-gamma")
(Gamma(c) Gamma(c - a - b))/(Gamma(c - b) Gamma(c - a)).
$
Почему в $*$ можно менять местами предел с интегралом? Оказывается, что $t^(b - 1) (1 - t)^(c - a - b - 1)$ --- суммируемая мажоранта при $a > 0$, а $t^(b-1) (1 - t)^(c - b - 1)$ --- суммируемая мажоранта при $a <= 0$ (упражнение на внимательность). Суммируемая, потому что равна $Beta$-функции, а она суммируема. Поэтому можно применить теорему Лебега о мажорированной сходимости#rf("lebesgue-limit").
]
#th(name: "преобразование Пфаффа", label: "pfaff")[
$0 < x < 1/2$ и $0 < b < c$.
$
hyperg(a, b; c; x) = (1 - x)^(-a) hyperg(a, c - b; c; x / (x - 1))
$
]
#proof[
$
hyperg(a, b; c; x) =^rf("hypergeometric-integral")
Gamma(c)/(Gamma(b) Gamma(c - b)) integral_0^1 (t^(b - 1) (1 - t)^(c - b - 1))/(1 - x t)^a dif t =^(t = 1 - s)
(Gamma(c) (1 - x)^(-a))/(Gamma(b) Gamma(c - b)) integral_0^1 ((1 - s)^(b - 1) s^(c - b - 1)) / (1 - x/(x - 1) s)^a dif s newline(=)
(1 - x)^(-a) dot underbrace((Gamma(c))/(Gamma(b) Gamma(c - b)) integral_0^1 ((1 - s)^(b - 1) s^(c - b - 1)) / (1 - x/(x - 1) s)^a dif s, hyperg(a, c - b; c; x / (x - 1))) =^rf("hypergeometric-integral")
(1 - x)^(-a) hyperg(a, c - b; c; x / (x - 1)).
$
]
#follow(name: "<NAME>", label: "euler-hypergeometric")[
$abs(x) < 1$, $0 < b < c$, $0 < a < c$.
$ hyperg(a, b; c; x) = (1 - x)^(c - a - b) hyperg(c - a, c - b; c; x). $
]
#proof[
Пока считаем $x <= 1/2$.
$
hyperg(a, b; c; x) =^rf("pfaff")
(1 - x)^(-a) hyperg(a, c - b; c; x / (x - 1)). \
hyperg(c - a, c - b; c; x) =^rf("pfaff")
(1 - x)^(-(c - b)) hyperg(c - b, a; c; x/(x - 1))
$
Выражаем первое из второго, получаем что хотели.
Что происходит при остальных $x$? У нас есть две функции, который совпадают на $(0, 1/2)$, и являются степенными рядами. Значит они совпадают на всей области определения. Скоро появится совсем сильный механизм для формализации этого#rf("def-analitical-continuation").
]
#example[
Попробуем воспользоваться всей этой теорией, чтобы что-то доказать.
$ arctan x = x hyperg(1/2, 1; 3/2; -x^2) =_*^rf("pfaff") x dot (1 - (-x^2))^(-1/2) hyperg(1/2, 1/2; 3/2; (x^2)/(x^2 + 1)) = \ = x/sqrt(1 + x^2) hyperg(1/2, 1/2; 3/2; (x/sqrt(x^2 + 1))^2) = arcsin(x / sqrt(x^2 + 1)). $
Под $*$ мы применили преобразование Пфаффа. Опять, мы применили его только на $(0, 1/2)$, но как окажется в дальнейшем#rf("def-analitical-continuation"), можно помахать руками, и окажется, что это верно везде.
]
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10B00.typ | typst | Apache License 2.0 | #let data = (
("AVESTAN LETTER A", "Lo", 0),
("AVESTAN LETTER AA", "Lo", 0),
("AVESTAN LETTER AO", "Lo", 0),
("AVESTAN LETTER AAO", "Lo", 0),
("AVESTAN LETTER AN", "Lo", 0),
("AVESTAN LETTER AAN", "Lo", 0),
("AVESTAN LETTER AE", "Lo", 0),
("AVESTAN LETTER AEE", "Lo", 0),
("AVESTAN LETTER E", "Lo", 0),
("AVESTAN LETTER EE", "Lo", 0),
("AVESTAN LETTER O", "Lo", 0),
("AVESTAN LETTER OO", "Lo", 0),
("AVESTAN LETTER I", "Lo", 0),
("AVESTAN LETTER II", "Lo", 0),
("AVESTAN LETTER U", "Lo", 0),
("AVESTAN LETTER UU", "Lo", 0),
("AVESTAN LETTER KE", "Lo", 0),
("AVESTAN LETTER XE", "Lo", 0),
("AVESTAN LETTER XYE", "Lo", 0),
("AVESTAN LETTER XVE", "Lo", 0),
("AVESTAN LETTER GE", "Lo", 0),
("AVESTAN LETTER GGE", "Lo", 0),
("AVESTAN LETTER GHE", "Lo", 0),
("AVESTAN LETTER CE", "Lo", 0),
("AVESTAN LETTER JE", "Lo", 0),
("AVESTAN LETTER TE", "Lo", 0),
("AVESTAN LETTER THE", "Lo", 0),
("AVESTAN LETTER DE", "Lo", 0),
("AVESTAN LETTER DHE", "Lo", 0),
("AVESTAN LETTER TTE", "Lo", 0),
("AVESTAN LETTER PE", "Lo", 0),
("AVESTAN LETTER FE", "Lo", 0),
("AVESTAN LETTER BE", "Lo", 0),
("AVESTAN LETTER BHE", "Lo", 0),
("AVESTAN LETTER NGE", "Lo", 0),
("AVESTAN LETTER NGYE", "Lo", 0),
("AVESTAN LETTER NGVE", "Lo", 0),
("AVESTAN LETTER NE", "Lo", 0),
("AVESTAN LETTER NYE", "Lo", 0),
("AVESTAN LETTER NNE", "Lo", 0),
("AVESTAN LETTER ME", "Lo", 0),
("AVESTAN LETTER HME", "Lo", 0),
("AVESTAN LETTER YYE", "Lo", 0),
("AVESTAN LETTER YE", "Lo", 0),
("AVESTAN LETTER VE", "Lo", 0),
("AVESTAN LETTER RE", "Lo", 0),
("AVESTAN LETTER LE", "Lo", 0),
("AVESTAN LETTER SE", "Lo", 0),
("AVESTAN LETTER ZE", "Lo", 0),
("AVESTAN LETTER SHE", "Lo", 0),
("AVESTAN LETTER ZHE", "Lo", 0),
("AVESTAN LETTER SHYE", "Lo", 0),
("AVESTAN LETTER SSHE", "Lo", 0),
("AVESTAN LETTER HE", "Lo", 0),
(),
(),
(),
("AVESTAN ABBREVIATION MARK", "Po", 0),
("TINY TWO DOTS OVER ONE DOT PUNCTUATION", "Po", 0),
("SMALL TWO DOTS OVER ONE DOT PUNCTUATION", "Po", 0),
("LARGE TWO DOTS OVER ONE DOT PUNCTUATION", "Po", 0),
("LARGE ONE DOT OVER TWO DOTS PUNCTUATION", "Po", 0),
("LARGE TWO RINGS OVER ONE RING PUNCTUATION", "Po", 0),
("LARGE ONE RING OVER TWO RINGS PUNCTUATION", "Po", 0),
)
|
https://github.com/MHellmund/typst-kbd-cheatsheet | https://raw.githubusercontent.com/MHellmund/typst-kbd-cheatsheet/main/kbdshortcuts.typ | typst | MIT License | #import "@preview/tablex:0.0.5": *
#let mainfont = "<NAME>"
#let color1 = rgb("#6e7b8b") // LightSteelBlue4
#let color2 = rgb("#008b45") // SpringGreen4
#let color3 = rgb("#87ceff") // SkyBlue1
#let colors = (color1, color2, color3)
#set text (font: mainfont, size: 8pt, lang: "en" )
#set page( paper: "a4",
flipped: true,
columns: 3,
margin: (left: 1cm, right: 1cm, top: 0.5cm, bottom: 1cm)
)
#show heading: it => [
#set align(center)
#set text(12pt, weight: "bold", font: mainfont)
#block(it.body)
#v(5pt)
]
#let mytab(header, e, color1, color2) = {
tablex(
columns: (10fr, 7fr),
rows: (13pt, 10pt), // first, repeat for rest
align: left + horizon,
row-gutter: 0pt,
stroke: none,
auto-lines: false,
fill: (col, row) => if calc.even(row) { color2 } else { white },
colspanx(2, fill: color1)[#text(9pt, white)[*#header*]],
..e.map(
row => (
if row.keys().at(0) == "$twocolumn" {
colspanx(2, align: center + horizon)[ #row.values().at(0) ] }
else
{ (row.keys().at(0), row.values().at(0)) } )
).flatten(),
//colspanx(2)[],
hlinex(stroke: color1 + 3pt) //gutter-restrict: top)
)
}
#let k = yaml("keyboard.yaml")
// yaml: dict mit nur einem k-v-pair, der value ist ein array
// Jeder Eintrag im array ist wieder dict mit nur einem k-v-pair, v ist wieder array
#let count=0
#for i in k.Kbd {
let title = i.keys().at(0) // key des 0ten k-v-pairs
let list = i.values().at(0) // value des 0ten k-v-pairs = array
let color1 = colors.at(count)
let color2 = color1.lighten(65%)
count += 1
[ = #title ]
for j in list {
let chap = j.keys().at(0)
let entries = j.values().at(0)
mytab(chap, entries, color1, color2)
v(8pt)
v(1fr)
}
v(3fr)
if count < 3 {colbreak()}
}
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/modules/chap2.typ | typst | Apache License 2.0 | // Ref: false
#let name = "Klaus"
== Chapter 2
Their motivations, however, were pretty descript, so to speak. #name had not yet
conceptualized their consequences, but that should change pretty quickly. #name
approached the center of the field and picked up a 4-foot long disk made from
what could only be cow manure. The hair on the back of #name' neck bristled as
he stared at the unusual sight. After studying the object for a while, he
promptly popped the question, "How much?"
|
https://github.com/tedaco1/typst-example | https://raw.githubusercontent.com/tedaco1/typst-example/main/document-files/more-pretty.typ | typst | MIT License | #let template(doc) = {
set page(
paper: "us-letter",
numbering: "1",
)
set math.equation(numbering: "(1)")
// Heading settings
set heading(numbering: "1.1", supplement: [Heading])
show heading.where(level: 1): i => {
align(smallcaps(i))
}
show heading.where(level: 3): k => {
align(upper(k))
}
show heading.where(level: 4): l => {
align(underline(l))
}
set table(
fill: (_, y) => if y == 0 {rgb("#d6d5d5")}
)
show link: underline
let appendix(body) = {
set heading (numbering: "A", supplement: [Appendix])
counter(heading).update(0)
body
}
set text(
//font: "Chilanka",
size: 11pt
)
doc
} |
https://github.com/noahjutz/AD | https://raw.githubusercontent.com/noahjutz/AD/main/notizen/sortieralgorithmen/heapsort/buildheap_step_0.typ | typst | #import "/components/lefttree.typ": lefttree, draw_node, polygon_around, poly_fill, note
#import "/components/num_row.typ": single_num_row
#import "@preview/cetz:0.3.0"
#let nums = (34, 45, 12, 34, 23, 18, 38, 17, 43, 7)
#single_num_row(
(34, 45, 12, 34, 23, 18, 38, 17, 43, 7),
hl_success: (5, 6, 7, 8, 9)
)
#cetz.canvas({
import cetz.draw: *
import cetz.tree: tree
tree(
lefttree(nums.map(n => str(n))),
draw-node: draw_node,
spread: 1.2,
name: "tree"
)
on-layer(-1, {
polygon_around(
5, 6,
poly_fill
)
polygon_around(
7, 8, 9,
poly_fill
)
})
note(0, ang: 90deg)[`f`]
note(nums.len()-1, ang: -90deg)[`l`]
}) |
|
https://github.com/wenjia03/JSU-Typst-Template | https://raw.githubusercontent.com/wenjia03/JSU-Typst-Template/main/Templates/实验报告(无框)/contents/context.typ | typst | MIT License |
= 吉首大学 Typst 模板
== Typst 优势
Typst 是可用于出版的可编程标记语言,拥有变量、函数与包管理等现代编程语言的特性,注重于科学写作 (science writing),定位与 LaTeX 相似。
- **易用性**:Typst 语法简单,易于上手,无需学习复杂的 LaTeX 语法。
- #text(weight: "bold")[编译快] :Typst 编译速度快,支持实时预览,提高写作效率。其基于`Rust`语言,使用增量编译技术,build 速度快。
- **可扩展性**:Typst 支持自定义宏、函数、包,用户可以根据自己的需求扩展 Typst 的功能。
- **环境搭建简单**:仅需在VS Code中简单配置即可上手使用,且无繁杂多种化的 LaTeX 发行版。
== Typst 劣势
- **生态不完善**:Typst 是一个新兴的科学写作工具,生态尚不完善,缺少大量的模板、包等。
- **功能不完备**:Typst 功能相对较少,不支持 LaTeX 的所有功能。
== 本项目引用项目
- 南京大学学位论文 nju-thesis-typst MIT License #link("https://github.com/nju-lug/nju-thesis-typst")[GitHub]
- SHU-Bachelor-Thesis-Typst (开发ing) Apache-2.0 License #link("https://github.com/shuosc/SHU-Bachelor-Thesis-Typst")[GitHub]
本人使用 Typst 不太熟练,基于大佬的项目学习修改。 |
https://github.com/dipeshkaphle/dipeshkaphle.github.io | https://raw.githubusercontent.com/dipeshkaphle/dipeshkaphle.github.io/main/cv/cv.typ | typst | MIT License | #show heading: set text(font: "Linux Biolinum")
// Uncomment the following lines to adjust the size of text
// The recommend resume text size is from `10pt` to `12pt`
// #set text(
// size: 12pt,
// )
#show link: set text(blue)
// Feel free to change the margin below to best fit your own CV
#set page(
margin: (x: 0.9cm, y: 1.3cm),
)
// For more customizable options, please refer to official reference: https://typst.app/docs/reference/
#set par(justify: true)
#let chiline() = {v(-3pt); line(length: 100%); v(-5pt)}
= <NAME>
#link("mailto:<EMAIL>")[<EMAIL>] |
#link("https://github.com/dipeshkaphle")[github.com/dipeshkaphle] |
#link("https://linkedin.com/in/dipeshk111/")[linkedin.com/in/dipeshk111] |
#link("https://dipeshkaphle.github.io")[dipeshkaphle.github.io]
Curious Software Engineer with a strong interest in Programming Languages, Formal Verification and Systems Programming.
== Education
#chiline()
*National Institute of Technology Tiruchirappalli* #h(1fr) 2019-2023 \
B.Tech in Computer Science and Engineering #h(1fr) CGPA: 8.84/10 \
- Studied algorithms and data structures, discrete mathematics, computer architecture, operating systems, computer networks, databases, theory of computation, and compilers.
== Work Experience
#chiline()
#link("https://uber.com")[*Uber*] #h(1fr) 07/2023 -- Present \
Software Engineer #h(1fr) Bengaluru, India \
- Primarily a backend engineer in the Trip Operations Platform team responsible for HITL(Human In The Loop) workflow orchestration and building a platform for knowledge workers.
- Working mostly with *Java*, *gRPC*, in-house dependency injection framework(based on *Spring Boot*), *Cadence*(A durable workflow orchestration engine), *Kafka* and *distributed databases* in my day to day work.
- Contributing to the frontend side of things as well using *Typescript*, *React* and *GraphQL*.
#link("https://github.com/prismlab")[*IIT Madras*] #h(1fr) 06/2022 -- 07/2023 \
Research Intern #h(1fr) Remote \
- Worked with Dr. <NAME> and Dr. <NAME> alongside a PhD student on a project that aimed to verify an OCaml style garbage collector with F\*/Low\*.
- Helped with the integration of the extracted verified code with the #link("https://github.com/prismlab/ocaml-gc-hacking")[OCaml bytecode interpreter], ran real-world OCaml programs and ran benchmarks to analyze performance.
- Wrote a #link("https://github.com/kayceesrk/ocaml/tree/29e76177c304dfb9fd75440c35ba4fb2744d4d0b/runtime/verified_gc/allocator")[next-fit allocator in Rust] which would then be hooked with the generated verified stop-the-world mark and sweep code. Analyzed performance using this before the bytecode interpreter integration.
- Helped with refactors in F\*/Low\* code.
#link("https://tarides.com")[*Tarides*] #h(1fr) 05/2023 -- 07/23 \
Software Engineering Intern #h(1fr) Remote \
- Worked on developing #link("https://github.com/ocaml-multicore/par_incr")[Par_incr], a library for incremental computation with support for freshly introduced parallelism constructs in OCaml
#link("https://cdac.in/index.aspx?id=BL")[*CDAC Bangalore*] #h(1fr) 02/2023 -- 05/23 \
Research Intern #h(1fr) Remote \
- Developed GCC plugins, performed benchmarks and analysis and explored potential optimizations for ARM HPC architecture.
#link("https://uber.com")[*Uber*] #h(1fr) 06/2022 -- 07/2022 \
Software Engineering Intern #h(1fr) Bengaluru, India \
- Worked on improving reliability and observability of a service, involved setting up alerts and dashboards, integrating and collecting metrics, and error analysis.
== Technical Projects
#chiline()
#link("https://github.com/ocaml-multicore/par_incr")[*Par_incr*] #h(1fr)\
- A library for incremental computation with support for parallelism in *OCaml*. Other similar libraries lack parallelism constructs. The work is based on the paper #link("https://drive.google.com/file/d/130-sCY1YPzo4j3YAJ7EL9-MflK0l8RmJ/view?pli=1")[Efficient Parallel Self-Adjusting Computation]. [#link("https://dipeshkaphle.github.io/par_incr_presentation/presentation.pdf")[Slides]]
- Wrote the library from scratch, thoroughly tested it,
- Identified performance bottlenecks through profiling and applied various optimization techniques in OCaml.
- Wrote benchmarks, compared the performance with other similar libraries, and achieved similar if not better performance on average.
\
#link("https://github.com/orgs/delta/repositories?q=codecharacter&type=all&language=&sort=")[*Code Character*] #h(1fr)\
- A strategy-based programming game where you control troops in a turn-based game with the code you write in one of the multiple programming languages (C++, Python, Java) available in the game.
- Worked on the implementation of the #link("https://github.com/delta/codecharacter-simulator/")[simulator(*C++*)]
- Worked on the #link("https://github.com/delta/codecharacter-driver/")[game driver(*Rust*)]. Implemented the process orchestration, communication among the game processes, concurrent execution of games. Leveraged different system programming concepts, such as inter-process communication, unix processes, epoll, pipes, SPMC channels, etc in the implementation.
#link("https://github.com/dipeshkaphle/enma")[*Enma*] #h(1fr)\
- A toy programming language written in *C++* and *OCaml*.
- The language has a uni-directional type checker and can be transpiled to readable C++ code or compiled to bytecode. The bytecode interpreter is written in OCaml.
#link("https://github.com/dipeshkaphle/brainfuck")[*BF JITs*] #h(1fr)\
- Implemented Just In Time compilers for Brainfuck language using Dynasm crate and Inkwell crate(provides LLVM bindings) in *Rust*.
#link("https://github.com/Jayashrri/PCTF21")[*Pragyan CTF*] #h(1fr)\
- Prepared challenges for Binary Exploitation/Reversing category, involving a small custom memory allocator, reversing SIMD instructions, and other common vulnerabilities.
== Talks and Writings
#chiline()
*Understanding Memory Management* #h(1fr)\
- #link("https://github.com/dipeshkaphle/hackertalk-mem-management")[Slides], #link("https://youtu.be/00Rk3o7Nv54")[Video]
*Personal Blog* #h(1fr)\
- #link("https://dipeshkaphle.github.io/posts/y-combinator/")[What is a Fixed Point Combinator?]
- #link("https://dipeshkaphle.github.io/posts/nonlocaljumps/")[Non Local Jumps with setjmp and longjmp]
== Skills
#chiline()
*Programming:* C, C++, Rust, OCaml, Java, Typescript, Python \
*Areas:* Programming Languages, Systems Programming, Back-End Development, Databases
== Languages
#chiline()
- Nepali: Native proficiency
- Hindi: Native proficiency
- English: Fluent (Professionally)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/name-it/0.1.0/README.md | markdown | Apache License 2.0 | # name-it
Get the English names of integers.
## Example

```typ
#import "@preview/name-it:0.1.0": name-it
#set page(width: auto, height: auto, margin: 1cm)
- #name-it(-5)
- #name-it(-5, negative-prefix: "minus")
- #name-it(0)
- #name-it(1)
- #name-it(10)
- #name-it(11)
- #name-it(42)
- #name-it(100)
- #name-it(110)
- #name-it(1104)
- #name-it(11040)
- #name-it(11000)
- #name-it(110000)
- #name-it(1100004)
- #name-it(10000000000006)
- #name-it(10000000000006, show-and: false)
- #name-it("200000000000000000000000007")
```
## Usage
### `name-it`
Convert the given number into its English word representation.
```typ
#let name-it(num, show-and: true, negative-prefix: "negative") = { .. }
```
**Arguments:**
- `num`: [`int`],[`str`] — The number to name.
- `show-and`: [`bool`] — Whether an “and” should be used in certain
places. For example, “one hundred ten” vs “one hundred and ten”.
- `negative-prefix`: [`str`] — The prefix to use for negative numbers.
[`str`]: https://typst.app/docs/reference/foundations/str/
[`int`]: https://typst.app/docs/reference/foundations/int/
[`bool`]: https://typst.app/docs/reference/foundations/bool/
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/templates/ts-node-next/README.md | markdown | Apache License 2.0 | # Typst Template for Typescript+ts-node
```shell
# Install ts-node globally if you haven't already
npm install -g ts-node
yarn install
ts-node --esm ./src/main.ts
```
|
https://github.com/ckunte/m-one | https://raw.githubusercontent.com/ckunte/m-one/master/inc/ebs.typ | typst | = Shell buckling
I have been evaluating the size of flotation tanks needed to install a large jacket substructure. The circular cylindrical tank sections in my case have a D/t ratio upwards of 300 --- too slender and non-compact to withstand severe buckling hazard under stress. Thin walled large tanks such as these are typically reinforced with uniformly-spaced internal ring frame stiffeners. And so I have been testing to see what ring frame stiffener spacing would be reasonable to maintain sufficient buckling strength for this tank to perform its job as intended, which is to safely assist in floating, upending and in setting-down the jacket structure on sea-bed.
#figure(
image("/img/lfE_6000x20.svg", width: 93%),
caption: [
Effect of ring frame spacing (l) on the buckling strength of a flotation tank, based on DNVGL-RP-C202@dnvgl_rp_c202
]
) <lfe>
For each of the eight hundred ring frame spacing variations, this little script generates elastic buckling strengths for (a) axial stress, (b) bending, (c) torsion and shear force, (d) lateral pressure, and (e) hydrostatic pressure respectively --- all in one go. And it powers through this in 1.0s. The bottleneck is not the speed at which it does this but in validating the results I do by hand for one or two unit values.
#let ebs = read("/src/ebs.py")
#{linebreak();raw(ebs, lang: "python")}
$ - * - $
|
|
https://github.com/ayoubelmhamdi/typst-phd-AI-Medical | https://raw.githubusercontent.com/ayoubelmhamdi/typst-phd-AI-Medical/master/chapters/ch00-rem.typ | typst | MIT License | #import "../functions.typ": heading_center, images, italic,linkb
#let finchapiter = text(fill:rgb("#1E045B"),[■])
= REMERCIEMENTS.
Nous tenons à remercier d'abord toutes les équipes pédagogiques du Master
*Technique des Rayonnements et Physique Médicale* de la Faculté des Sciences à
Meknès, ainsi que les professeurs ayant contribué activement à notre
formation.
Nous profitons de cette occasion, pour remercier vivement notre *Professeur
<NAME>* qui n'a pas cessé de nous encourager tout au long de
l'exécution de notre Projet de Fin d'Études, ainsi que pour sa générosité et ses
compétences en matière de formation et d'encadrement. Nous lui sommes
reconnaissants pour ses aides et conseils précieux qui nous ont permis de mener à
bien le présent projet.
Nous souhaitons également exprimer notre gratitude envers le co-encadrant du Master, *Professeur <NAME>*. Sa présence et son soutien ont été d'une grande valeur pour nous.
De plus, nous voudrions adresser notre franche gratitude au *Professeur <NAME>*,
coordonnateur du Master, ainsi qu’à tous les enseignants, pour leur gentillesse et leur
collaboration. Ils nous ont donné, chacun dans leur domaine, des conseils et des
encouragements aux moments opportuns.
Un remerciement spécial est adressé à *<NAME>*, physicien médical au Centre d’Oncologie ALHAYAT, pour son encadrement, les informations précieuses qu'il nous a apportées et ses conseils avisés. Nous tenons à remercier également le *Dr <NAME>* (radiologue), Dr *<NAME>* (radio-oncologue) et *<NAME>* (directrice) pour leur accueil chaleureux et leur soutien au sein du Centre d’Oncologie ALHAYAT.
Nos vifs remerciements vont aussi aux membres de jury pour avoir accepté de
juger ce travail.
A la même occasion, nous voudrons également remercier chaleureusement nos
parents qui nous ont toujours encouragés durant notre cursus de formation.
Enfin, nos vifs remerciements sont adressés à toutes ces personnes qui nous
ont apporté leur aide précieuse et leur soutien inconditionnel. #finchapiter
|
https://github.com/EunTilofy/Compiler2024 | https://raw.githubusercontent.com/EunTilofy/Compiler2024/main/lab4/Report_of_Lab4.typ | typst | #import "../template.typ": *
#show: project.with(
course: "编译原理",
title: "Compilers Principals - Lab4",
date: "2024.6.8",
authors: "<NAME>, 3210106357",
has_cover: false
)
= 实验内容
本次实验旨在将中间代码(IR)转换为汇编代码。我们首先根据 function 将中间代码划分为不同的块,每个块中都包含若干个 IR 节点;然后,我们对于每个中间代码块,首先处理其中可能包含的函数参数,变量等信息,然后为每其指定其在内存中的位置,该部分为 IR 块的预处理部分;最后,我们根据 IR 节点的不同类型,将其转化为对应的汇编代码(同样由相应的 ASM 节点保存),将汇编节点依次输出为汇编代码。
我们通过
```
make compiler
./compiler <input file> [output file]
```
可以对输入的 sy 文件进行语法和语义的检查,
如果可以正确解析出语法树并且通过类型检查和数组检查,程序将正常退出并返回 0,并且将生成汇编代码保存到 output file(如果没有定义,则默认为 asm.out),
同时在错误流中显示:
```
Parse success!
```
否则,程序将汇报错误。
= 代码实现
== 主接口
main.cc 在lab3的基础上,增加了汇编代码生成的部分:
```cpp
string ASM_OUT = "asm.out";
if (argc >= 3) ASM_OUT = string(argv[2]);
ofstream asm_out(ASM_OUT);
ASM _asm(ir);
_asm.print(asm_out);
```
== 汇编代码存储格式
=== `class _ASM`
`_ASM` 类是汇编指令节点信息的存储基类,定义如下:
```cpp
class _ASM {
public:
string type;
virtual ~_ASM() = default;
virtual void print(ostream& out) = 0;
};
```
=== 相关派生
在此基础上,我们定义了不同类型的汇编指令类,例如二院操作指令类:`ASM_binop`:
```cpp
class ASM_binop : public _ASM {
public:
string lv, rv1, rv2, op;
ASM_binop(string _op, int lv, int rv1, int rv2) : lv(REG(lv)), rv1(REG(rv1)), rv2(REG(rv2)) {
_ASM::type = "binop"s;
op = upd(_op);
}
void print(ostream& out) { out << op << " " << lv << ", " << rv1 << ", " << rv2 << "\n"; }
};
```
== IR 到汇编代码转换
=== `class IRs`
`IRs` 类用于存储中间代码块及其解析方法,解析方法包括,IR块中的函数名,变量,参数提取,IR块中内存分配。
```cpp
class IRs : public IR {
public:
IRs() {}
IRs(const IR &ir) : IR(ir) {}
set<string> var, par;
string fname;
map<string, int> pos;
void get_func_info();
void place_var();
};
```
=== `class ASMs`
ASMs 类用于存储汇编指令块,一个中间代码块将对应地转化为一个汇编指令块。
```cpp
class ASMs {
public:
vector<unique_ptr<_ASM>> child;
string fname;
void print(ostream& out) {
for (auto &e : child) e->print(out);
}
template<typename T>
void push_back(T o) { child.push_back(unique_ptr<_ASM>(o)); }
template<typename... Args> void PUSH(Args... args) {
(child.push_back(unique_ptr<_ASM>(args)), ...);
}
};
```
=== 汇编指令生成
我们使用 `parse_ir` 函数来生成相应的汇编指令。
为了方便生成,我们通过如下方式生成一个 `_ASM` 节点:
```cpp
#define A(type, ...) (new ASM_##type(__VA_ARGS__))
```
例如对于二元运算 (op, lv, v1, v2),我们构造汇编指令:
```cpp
o.PUSH(A(lw, Reg["t0"], Reg["fp"], bl.pos[x->v1]),
A(lw, Reg["t1"], Reg["fp"], bl.pos[x->v2]),
A(binop, x->op, Reg["t2"], Reg["t0"], Reg["t1"]),
A(sw, Reg["t2"], Reg["fp"], bl.pos[x->lv]));
```
这对应指令:
```asm
lw t0, fp, offset(v1)
lw t1, fp, offset(v2)
op t2, t0, t1
sw t2, fp, offset(lv)
```
即分别从内存中取出 $v_1, v_2$,执行运算后保存回 $l v$。
对于自带的的 `read/write` 语句,我们使用 `ecall` 指令:
```cpp
if (x->name == "read")
o.PUSH(A(li, Reg["a0"], 6), A(ecall));
elif (x->name == "write")
o.PUSH(A(li, Reg["a0"], 1), A(lw, Reg["a1"], Reg["sp"], 0), A(ecall));
```
其余实现细节详见代码 `src/asm.hpp`。
= 测试结果
```
python3 test.py ./compiler lab4 -l
```
tests 下的测试样例全部通过:
#figure(
image("1.png", width: 45%),
caption: [
All tests passed!
],
) |
|
https://github.com/normanlorrain/mdtypst | https://raw.githubusercontent.com/normanlorrain/mdtypst/main/README.md | markdown | Apache License 2.0 | # mdtypst
Python library to convert Markdown to Typst
|
https://github.com/AnsgarLichter/hka-thesis-template | https://raw.githubusercontent.com/AnsgarLichter/hka-thesis-template/main/chapters/2_foundations.typ | typst | #import "../common/todo.typ": *
#import "@preview/acrostiche:0.2.0": acr, acrpl
= Foundations
This chapter describes the Foundations.
#lorem(500) |
|
https://github.com/LEXUGE/typst2nix | https://raw.githubusercontent.com/LEXUGE/typst2nix/main/README.md | markdown | MIT License | # typst2nix
Package Management and Tooling for Typst implemented in Nix
|
https://github.com/cronokirby/paper-graphical-framework-for-cryptographic-games | https://raw.githubusercontent.com/cronokirby/paper-graphical-framework-for-cryptographic-games/main/paper.typ | typst | #let defc = counter("definition")
#let thmc = counter("theorem")
#let template(title: none, abstract: none, author: none, doc) = {
set document(title: title, author: author.name)
set page(
paper: "a4",
margin: (x: 1.6in, y: 1in),
numbering: "1"
)
set text(
font: "Stix Two Text",
size: 12pt
)
show heading.where(level: 1): it => {
defc.step(level: 1)
thmc.step(level: 1)
it
}
show math.equation.where(block: false): it => text(font: "Stix Two Math")[
#it
]
show math.equation.where(block: true): it => text(font: "Stix Two Math")[
#v(-0.25em)
#it
#v(-0.5em)
]
show list: it => {
it
v(-0.5em)
}
show heading: it => {
v(0.2em)
it
v(0.2em)
}
set heading(numbering: "1.1")
show par: set block(spacing: 1.5em)
set cite(style: "alphanumeric")
align(center, text(2em, hyphenate: false)[
#title
])
align(center, text(1.2em)[
#author.name \
#author.email \
#parbreak()
#datetime.today().display()
])
set par(
justify: true,
leading: 0.8em
)
align(left, [
#align(center, [
#text(1.0em)[*Abstract*]
])
#v(-0.5em)
#pad(x: 2em, abstract)
])
doc
}
#let definition(break_end: true, title: none, content) = {
defc.step(level: 2)
if title != none {
text(weight: "bold")[Definition #defc.display(): #title]
} else {
text(weight: "bold")[Definition #defc.display()]
}
linebreak()
content
if break_end {
linebreak()
}
[$square.stroked.medium$]
parbreak()
}
#let theorem(content) = {
thmc.step(level: 2)
text(weight: "bold")[Theorem #thmc.display()]
linebreak()
content
linebreak()
}
#let lemma(content) = {
thmc.step(level: 2)
text(weight: "bold")[Lemma #thmc.display()]
linebreak()
content
linebreak()
}
#let claim(content) = {
thmc.step(level: 2)
text(weight: "bold")[Claim #thmc.display()]
linebreak()
content
linebreak()
}
#let proof(content) = {
text(weight: "bold")[Proof]
linebreak()
content
linebreak()
[$square.filled.medium$]
parbreak()
}
|
|
https://github.com/jamesrswift/dining-table | https://raw.githubusercontent.com/jamesrswift/dining-table/main/src/styles.typ | typst | The Unlicense | /// The stroke of the top-rule of a table
/// -> stroke
#let toprule = stroke(0.8pt)
/// The stroke of rules between rows or columns
/// -> stroke
#let lightrule = stroke(0.3pt)
/// The stroke of the rule after the header and before the footer
/// -> stroke
#let midrule = stroke(0.5pt)
/// The stroke of the bottom-rule of a table
/// -> stroke
#let bottomrule = stroke(0.8pt) |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/043%20-%20Innistrad%3A%20Midnight%20Hunt/007_Episode%204%3A%20Harvesttide.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 4: Harvesttide",
set_name: "Innistrad: Midnight Hunt",
story_date: datetime(day: 22, month: 09, year: 2021),
author: "<NAME>",
doc
)
Three knocks on Olivia Voldaren's door put her in a killing mood. Not that she's ever #emph[not ] in a killing mood, of course, but sometimes people take it upon themselves to exacerbate matters, and what is she to do then? You simply can't tolerate these things; it breeds rebelliousness in your servants. And not the fun kind.
"Come in, and do make it worth my time," she calls. "I cannot #emph[bear ] to have my beauty rest interrupted."
She does not open her eyes, for if she does it'll throw the whole thing off. It took her a whole fifteen minutes to flay the face off that maiden; Olivia isn't going to let it go to waste. You must give the blood time to settle in and really lend you color.
"My most illustrious and powerful Lady <NAME>."
Her lips quirk into a small smile. Yes. Good.
"I come bearing news of the humans."
Her smile and good mood, gone. She scowls, careful not to upset the maiden's face overlaid on her own. "Is this #emph[important] news?"
"I think so," says the messenger. From the sound of his voice, it was probably Feuer. Didn't he have some bones he should be reassembling? Olivia never met a finer purveyor of ossuary furniture, but why was he #emph[here] ? "They're up to something. Trying to restore the balance of day and night, I believe."
#figure(image("007_Episode 4: Harvesttide/01.jpg", width: 100%), caption: [Sunset Revelry | Art by: <NAME>], supplement: none, numbering: none)
She starts to groan and then stops herself. Mustn't disturb the mask, Olivia, it was such a pain to extract. "And how do you believe they mean to do this?" she says. As she gestures, the blood she's resting in splashes like bathwater. "Isn't as if they can throw a chain around the sun."
"Most illustrious and powerful Lady Voldaren, I believe they're doing it with a festival."
"A festival."
"Yes, a festival," he repeats, firm even after her disbelief. "I was of late visiting Gavony in pursuit of certain physical resources—"
Why won't he just say bones?
"—when I came across the strangest sights: vampire effigies. Large, abominably decorated versions of ourselves, and even of your vaunted, ineffable personage."
"#emph[My ] personage? That cannot stand."
"So it cannot, my most illustrious and powerful Lady Voldaren, so it cannot. In my clever guise as a wandering sword-for-hire, I asked what the preparations were for. A kind woman told me they were for Harvesttide. Thanking her, I killed her where she stood and burned the effigy."
Olivia frowns. "You burned it? Feuer, have some common sense. You should have brought it back here. We could have used it for the reception."
There's the slightest tremor of fear in his voice. "Very well, my most illustrious and powerful Lady Voldaren, it shall be so next time," he says. He clears his throat. "But it may further interest you to hear the method. As I was excavating a specimen I caught sight of a group of travelers—they seemed outsiders, but I recognized their leader. <NAME>—"
"Ugh. That mongrel."
"The very same. She is leading the search. In addition, there was a woman with burning hair—"
Olivia sighs dramatically.
"—who kept asking after something called the Moonsilver Key. She wanted to get a good look at it, which tells me they already had it."
Ahh, that old thing. The humans must be desperate if they're digging it back up. Olivia sits up. "Harvesttide, is it?"
"Harvesttide, indeed. What shall be done? Shall I speak with our other extraction specialists?"
Olivia touches a knuckle to her lips in thought and consequentially the young maiden's, too. "No need. Let it proceed."
"But <NAME>—"
"Most illustrious and powerful Lady Voldaren," she corrects. "Feuer, if you saw someone extracting a specimen you coveted, what would you do?"
He hums in thought. "I would kill them."
He isn't playing along at all. "Yes. Obviously. But #emph[when ] would you kill them?"
"Immediately," he answers. "It'd be a personal affront."
Olivia laughs. "That's where you're thinking too small, dear little boy," she says. At last, she slides the mask off her skin, rubbing the blood into her thirsty skin. "#emph[Never] interrupt someone when they're doing your work for you."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Among the gathered festivalgoers, a single thought: Innistrad must endure.
From all walks of life, they have come to this place from the nearby foothills of Kessig, from the storied spires and murky moors of Gavony, from the ports and tunnels of Nephalia, from the sunless streets and twisted towers of Stensia, they have come. Beneath the never-turning arms of the ancient Celestus they march their effigies, their candles, their baskets of short-lived flowers and fruits.
Innistrad must endure. This #emph[cannot ] be the last time.
So says the pumpkin carver with a gathered crowd of children before them. "What can I make for you?" they ask, and the children say they would like to see the sun. A sun, then, a sun—the pumpkin carver's hands move with grace and hope and joy. The guts are already hollowed, they explain, and that's the importance of preparation at a time like this, you must think ahead. Make sure to pay attention to your tutors, and they'll tell you the same. Here are the rays, and here is the sun—chunks of pumpkin falling onto the frost-laced earth. A candle in the center. The pumpkin carver, a witch themself, calls down a candle from one of those floating overhead.
"Make a wish," says the pumpkin carver to the child. "It can be for whatever you want, as big as you like."
And the child, of course, wishes that the sun will go on forever, but she does not tell the witch this. If you speak your wishes, they won't come true.
The witch tells the girl to touch the candlewax. A sun and moon engrave themselves on the spot the girl picks, and she draws in a gasp, and the witch smiles. Into the pumpkin, it goes. They hand the girl the finished work.
"Here," they say. "A sun just for you, one that will never go out. Happy Harvesttide!"
And the girl skitters off, carrying her personal sun, thinking that Innistrad is a little brighter. So it is.
Especially when everyone else wants their own personal sun now.
Witch Deidamia watches the girl go and says to themself: this is why Innistrad must endure, this is why it cannot be the last time.
Katilda said it won't be.
Looking up at the Celestus, Deidamia has to hope that's the truth, and they have to nurture that hope, too, have to keep it alight just like the candles.
Even if it's just to amuse these children.
A light frost falls on the proceedings. Only a few yards away, their fellow witches lead defiant songs, coaxing the melodies out from halting voices. Two booths down from Deidamia, their friend Shana holds up a mug of spiced cider. The festival might have a dour cast, and they may well all die in a few months if the sun isn't put back in its proper place, but for now, there is the joy of spiced cider.
Deidamia nods. Shana whispers a quick spell and sends the cup floating onto Deidamia's table, where they take a quick sip in the middle of carving another sun. Shana's eyes say she wants to talk more about what's going on, about how long they're supposed to wait before putting on their masks, but Katilda was clear: wait for the key. Until then, keep your eyes open, and keep the festivalgoers safe.
And so, Deidamia scans the crowd, and the trees, and minds their wards, all as they continue to trap the sun for the children. And, too, for the weary faces of the parents standing behind them.
It is not Deidamia who spots the heroes first, but Shana. Her excited shout gives way to cheers from all around. The bards switch to an upbeat, triumphant tune to welcome them. The crowd becomes so thick that Deidamia cannot even really see the heroes, who have arrived at the other end of the festival, but she sees an exciting gout of flame rise. There was a pyromancer among them, wasn't there?
The boy awaiting his own personal sun shouts for Deidamia to hurry, and so they do—the moment the pumpkin touches the counter, the boy is off to see the heroes. So, too, is the rest of the crowd gone. For the first time all festival, there's an empty table before them.
Shana's table is empty, too. Deidamia can't resist a look at the heroes on their way to the center of the Celestus—a little more cider won't hurt. And Shana will understand, right?
They take a few steps over and pour themselves a new glass, and it's then, as the scent of apples fills the air, that Deidamia feels the too-sharp pain of a ward going down.
The howling starts soon after.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Maybe it was all the apples. Maybe it was all the spices. Maybe it was all the pumpkins. Or maybe it was the collected scent of thousands of humans gathering to stare down their deaths.
Whatever the case, Arlinn doesn't smell them coming.
She doesn't know it's happening until it's too late, doesn't see them beating against the barriers until the shaman-wolves are already upon them, doesn't hear the howling until they're already at the gates. Grateful cheers screech into fearful screams; the children gathered to see them soon return to their mothers' sides.
Witches shout, too, donning their wood and bone masks, directing the crowds further into the imposing arms of the Celestus. "It isn't safe here—you have to go!"
And for the most part, the people listen, becoming a great river of flesh and fear, rushing over the carefully arranged booths and tables, trampling underfoot pumpkins and elders and bottles of cider. Is it blood or wine that soaks the Kessig earth? Who can say? All that matters is that the wolves are at the door, and the Celestus is away from them.
Arlinn can see them now: the howlpack shamans standing among the trees, cloaked in the dyed furs of their kills, the dull scarlet glow of their magic getting brighter and brighter as they chant their spells; the quickest of them running in hungry circles around the edge of the barricade; impossibly large bruisers looming in final threat; wolves in tough, leathered armor.
She can see all of them, and there must be hundreds.
Her chest goes tight.
#figure(image("007_Episode 4: Harvesttide/02.jpg", width: 100%), caption: [Storm the Festival | Art by: Yigit Koroglu], supplement: none, numbering: none)
"Arlinn," says Kaya. "We're in it deep, aren't we?"
"Not as long as we can save the humans," Arlinn says. Her voice comes out more strained than she'd like. Shouldn't a leader sound more confident? "Kaya, take the key. Make sure it gets to Katilda."
"Got it," she says. Kaya doesn't need to be told twice—the second Teferi hands her the key, she's off, fading into the mist. Good, the wolves won't be able to find her.
There's a lump fast forming in Arlinn's throat, but she doesn't have time for that now. Red light's painting the stark fear of the crowd in horrific shadow. A lycanthrope only a little smaller than a siege tower beats a fist against the edge of the magical barrier.
#emph[Crack.]
Arlinn cannot tear her eyes from the horde—from the wolves pacing along with the lycanthropes. If she looks long enough, she is sure to see familiar faces, and the thought fills her with dread. "Chandra, Adeline—"
"You don't need to tell us," says Chandra.
And indeed she doesn't. Adeline, already mounted, throws out a hand for Chandra and helps her into the saddle. The two of them are off to the forefront without another word.
To be in all things a protector and guiding light: that is the core of faith that drives Arlinn forward. And there's no better time to be a protector than this.
So why is it that part of her longs to join them? Why is it that her wild heart beats in her breast, straining against her careful control?
Her gaze soon falls on the answer.
He's here.
#emph[Crack. Crack. Crack.]
Overhead, the magic shatters like stained glass; she looks up at it with blood soaking her vestments and tears streaking down her cheeks.
A wave against the rocks of Nephalia; the wall of werewolves falling upon the straggling festivalgoers. Blood spraying in the air, bones crunching beneath the massive jaws of transformed death, a howl that sets her alight with self-loathing and hunger.
"Arlinn."
The beating of war drums in her ear nearly drowns out Teferi's voice next to her, but his hand squeezing her shoulder brings her back. She shakes her head, presses her eyes together. "Teferi, I have to—there are people I need to—"
"I know," he says. And he sounds afraid, too, but there's a bravery to his voice that lends her some of the same. "I was going to tell you I owed you a long sunset."
She narrows her eyes, but he's already planting his staff in the earth, already giving her a smile that speaks of confidence he's kindled deep within. "Witches of the Dawnheart Coven!" he bellows, "Let's get this ritual started!"
The second his staff hits the earth, a shockwave spreads, and every muscle in Teferi's body goes stiff with effort. This time, when he looks at her, she knows she can't waste this borrowed time.
Her dreams are dying by the second as are the last rays of the last sunset on Innistrad.
She has to do what she can.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Adeline's a natural leader.
Running through the makeshift battle lines, Arlinn sees this clearer than ever: the gathered guards heed her orders as naturally as breathing. Clusters of cathars stand back to back with spears and shields, driving their weapons into the powerful chests of the wolves. When she commands them to hold, they fall back, forming a shield wall behind which the few remaining festivalgoers can hide.
Tovolar gives no such orders. He has no need to, as Arlinn knows well; he is here for the wild hunt, a thing which knows no law. To run with him is to listen to the wild song of your own heart and follow it to its natural end. She learned that hunting with him. People thought he was quiet because he was mute, but the truth was that he's always been happy to let nature run its course.
And run its course it does—here faster than ever. The orders Adeline's shouting, the gouts of fire from Chandra's gauntlets, the impossible golden rays of the sun: without these things, the humans would stand no chance. Even in their human forms, the lycanthropes are too strong to fight back; even in their human forms, the dires are taller than any blacksmith and wider besides. In some sense, it's a blessing that the majority have yet to change: it is one thing to deal with weapons swung by too-strong arms, and another entirely to deal with living walls of muscle.
But that is not to say it's easy. To her right, a dire brings down his hammer upon a cathar shield wall, leaving three men flat on their backs. Again, and again, and again he brings it down; the cathars grunt in pain and effort, curling up as much of themselves beneath their shields as they can.
It is only a curious stuttering that keeps them alive. One of the rare niceties of Arlinn's childhood were the visits from a traveling merchant. Among his stock was a sort of paper lantern with slits cut into the sides. In the center, a mounted cathar. You could spin the lantern and "see" the cathar ride. Not magic, he swore, simply a trick of the light. Arlinn wanted one desperately but knew her parents could never afford it. The strange movements of the cathar beguiled her, the motion's stop-and-start.
The dire is moving much the same way. Raising his hammer overhead, bringing it down—there are precious seconds throughout where he stops moving entirely. Enough for the fallen cathars to wriggle a little out of the way. Even the dire's shadow doesn't match his movements.
Teferi. She has to thank him after this.
#figure(image("007_Episode 4: Harvesttide/03.jpg", width: 100%), caption: [Borrowed Time | Art by: <NAME>atos], supplement: none, numbering: none)
Out of reflex, Arlinn calls for her wolves, but they won't answer, she knows; there are too many wolves among the attackers. Nature's chosen its side.
So she'll choose humanity's.
Scooping up a fallen cathar's mace, she throws herself at the dire. Muscles can lend you all the power they want, but joints will always be weak. He's too busy wailing on his would-be victims to notice the mace coming for the back of his knee. She puts her weight into the blow; a howl and crunch are her rewards. The dire falters, turns, and the cathars stand behind him.
The dire's snarling. Human though his shape may be, the eyes give him away; they're half-changed already, along with his too-long fangs. "You. Tovolar's #emph[favorite] ."
Arlinn scowls. "You don't know anything about me," she answers, hefting the mace. "Get out of here while you can. This isn't a battle you're going to win."
His laugh rumbles out from within his massive chest and distracts him from the coming swords of the cathars. The first through his leg does not stagger him, but the second in his already injured knees sends him howling. The third, between his ribs, bows him but not before he grabs the too-close head of the third cathar in his massive hands.
Arlinn doesn't wait.
The mace meets bone.
Standing in the aftermath, blood on her hands, all she can do is mutter a prayer. When the cathars thank her, it does not feel as if she's done anything just, as if she's done anything right.
None of this is right.
#emph[Tovolar] #emph['s favorite.]
She runs, further into the melee.
She runs because it's wrong, and she knows it's wrong—she's never been his favorite, and how could she be? When after two years under his tutelage, she left him scarred and bleeding then ran away in the middle of the night?
She runs from the memory, but memory is a fine hunter: the blood beneath her feet is just like his blood that night; the screams of the festivalgoers are like the screams of the Kessiger foresters; the blood on her hands has never truly gone away.
"Can't we be more than this?" she'd asked him.
But to him, this is what they were, what she was, what she was always meant to be.
Nothing more than this: blood on the earth, the taste of meat, the scent of fear.
Arlinn swallows. The bodies she sees—the people she sees—they're just like the foresters.
And there's Tovolar again. Amid the chaos of the raid, he stands still. Brighter are his eyes than the fires now set to the forest and focused straight on her.
"Tovolar!" she shouts. "Call this off!"
He smirks, shakes his head. "No."
#figure(image("007_Episode 4: Harvesttide/04.jpg", width: 100%), caption: [Tovolar, the Midnight Scourge | Art by: <NAME>], supplement: none, numbering: none)
The mace still in hand, she marches. Behind her, the chaos continues: cathars slicing at the throats of lycanthropes; witches sheltering the outliers; armored raiders standing tall in the face of their opposition. Chandra's fires cast the scene in an amber glow.
"It's almost sundown, Arlinn. There's still time to join," he says. He takes no notice of the weapon in her hand or else it does not frighten him.
But it should.
With a deep, guttural growl, she swings.
Tovolar catches the head of the mace.
"Why would I ever want to join you?" she snarls. More and more of her weight she presses into the mace, but he holds it with little trouble.
"You did once," he answers. He pushes the mace back, throwing her off balance. "That was your place."
"You don't get to decide my #emph[place,] " she says. Another swing of the mace finds him catching it by the haft and tearing it from her hands. As it falls, it clatters against the shield of a fallen guard, but Tovolar takes no notice.
The sun's sinking lower in the sky. Even Teferi can't hold out forever.
He stares at her, and she stares at him.
"They only like you because they think you're like them," he says. "But I know you aren't."
"You don't know me," she shoots back.
And this time, he's the one who comes at her—a big overhand swipe of his claws. Arlinn ducks out of the way only for him to pull her closer, to bare the edge of the scars running from his shoulder to his waist. "Are you sure?"
"I am," she says, just before her fist connects with his jaw. The shock of impact up her arm is more than worth it when she sees the smug look on his face shrink away. She follows it with another, and another, leaving him staggering back. "Call this off, Tovolar. There's still time."
Blood drips into his teeth. He spits onto the earth. "You're joking."
"I'm not," she says. "Call this off. Let us finish the ritual. Take the nights back, hunt what you can, but leave the humans out of this."
"And how do you think they'd take that?" he says, standing.
"They'd be alive," she answers. "That's what matters."
He comes for her again. This time, she's ready. Arlinn catches both of his fists in her open hands. Her muscles groan with the effort of keeping him at bay, but she digs in her heels—this can't continue.
"See how far that gets you. Your wolves know the truth—it's us versus them. Always has been."
She knows the howls that follow. She knows the growls, knows what she will see if she tears her eyes from his. So she doesn't look, can't bear to; her chest aches enough already with her heart torn out. To see them will only send it rolling around her stomach.
And she can't afford distractions. Squeezing her eyes shut, she bashes her forehead into his nose. He staggers long enough for her to get in another punch.
But the ripple that flows across his body tells her what she dreads to hear: time's running out. Tovolar's bloodied teeth grow longer and longer, his grin all the more discomforting when it's on a muzzle. All around them the howls of the others giving in stoke the chaos of the moment.
"Arlinn! Going to need some help!"
Chandra's voice is easy to pick out. The answer less so. Staring Tovolar down, the most she can offer is, "Working on it, focus on keeping everyone safe!"
Taller and taller he grows. Her own body fights against her control; her teeth ache, her hands tremble with unspent energy as she scrambles for another weapon. The sword clutched in a fallen guard's hand serves well. Later, she'll say a prayer for him.
But for now? Better to live.
There's joy in him as he lunges for her, there's delight in the swipes he makes—all wild and reckless. Each she meets with the flat of her blade. Quick as he is in this form, the best she can do is fend him off, and it isn't long before her arm aches, her shoulder, her back, her tired, tired soul. A faltering guard leaves her open: his claws tear open her cheek. The smell of blood almost overrides the pain; her nostrils flare, she tastes copper; a deep, primal hunger threatens to overwhelm her carefully won control.
But it doesn't.
"You're a wolf, Arlinn," he snarls, the words mangled by the inhuman shape of his mouth. "No matter how hard you keep trying to pretend!"
"I never said I wasn't!" she answers.
He's on her again, pouncing; she just barely makes it out of his reach.
"Then show me!"
He rears up, the scar she gave him now plainly visible, even in the fading light. Seeing it puts her in that place again: Tovolar urging her to kill humans, to prove she was one of them; an impossible choice; an easy and messy solution. All she had to do was kill him, wasn't it? And then she'd be the alpha of the howlpack.
But things didn't go that way. He didn't die, and she didn't win. They both had the scars to prove it.
Hers are burning. All of her is. In the din of battle, she can hear the drums that played that night when she challenged him. Just as then, the eyes of the pack are upon her; just as then, she stands alone and friendless. Just as then, she is right, and he is woefully misguided.
A spasm shakes her arm, the muscles straining to be something more, but she clutches it with her free hand. A prayer drops from her lips. If she is to do this—if she is to show him how wrong he is—then she cannot give in. She cannot allow herself to—
"Give in. Why are you holding back?"
"Because—because there's still~"
The words don't come. It's getting hard to speak. Here, again, the howls: #emph[I am with you, join the hunt. ] Here, again, the call of meat and bone; here, again, the finest freedom she's ever known. So close. So close.
She presses her eyes shut. Sense comes to her, and she opens them only a moment later, but by then, the wolves have closed in.
Streak, Patience, Redtooth, and Boulder.
All staring back at her, all with their teeth bared—except Patience.
She presses herself against Arlinn's leg, tugs on her trousers, looks up at her, and begs: #emph[Be with us. Join the hunt.]
If Tovolar tore her in two, it would hurt less than this. For how can she convey what joining the hunt means? How can she explain to Patience that the humans who look on them with such suspicion are good and the wolves who run and hunt and play with them are in the wrong here?
She staggers. Tears sting her eyes. "I can't," she creaks.
And that is all Boulder needs to hear. True to his name, when he throws his weight against her, she's bowled over, the air gone from her lungs as her ribs crack. Face down in the muck, she can only hear the approach of her wolves, can only feel Tovolar's hands grip her hair.
"We settle this right," he says, "or you die here."
His knee on her back, his claws at her throat. Even to breathe is to risk injury.
"Show me the real Arlinn. We all want to see her."
Is that what he wants, then?
She'll give it to him.
Not because he asks for it, not because her wolves are desperate to see it, not because she wants to prove something.
But because in some ways he's right—the two of them are wolves, and she sees now that it was only ever going to end like this.
By blood, and fang, and claw.
The sun sinks below the horizon. Day changes to night.
And <NAME> changes with it.
#figure(image("007_Episode 4: Harvesttide/05.jpg", width: 100%), caption: [Arlinn, the Moon's Fury | Art by: <NAME>], supplement: none, numbering: none)
|
|
https://github.com/VinEdw/physics-equation-sheets | https://raw.githubusercontent.com/VinEdw/physics-equation-sheets/master/README.md | markdown | # physics-equation-sheets
This repository holds a physics equation sheet I put together.
The document was created using a program called [Typst](https://github.com/typst/typst).
The diagrams were created using a Typst library called [Cetz](https://github.com/cetz-package/cetz).
## Files
- PHYS 2AG
- [Equation Sheet PDF](https://github.com/VinEdw/physics-equation-sheets/blob/master/phys-2ag/phys-2ag-equations.pdf)
- [Typst Source File](https://github.com/VinEdw/physics-equation-sheets/blob/master/phys-2ag/phys-2ag-equations.typ)
|
|
https://github.com/vmysak/modern-cv-typst | https://raw.githubusercontent.com/vmysak/modern-cv-typst/main/README.md | markdown | Apache License 2.0 | # modern-cv-typst
### Template Description
- Generate beautiful CV in minutes
- Written in typst, inspired by LaTeX 'moderncv' package
- Easy to modify, seconds to build
- Color theme and visual style customization
### Template Structure
- ```/src/definitions``` - template itself
- ```/src/resources``` - images, fonts, etc
### CV Structure
- ```/src/my-config.typ``` - configuration file
- ```/src/my-cv.typ``` - CV body file
- ```/target/*.pdf``` - CV pdf file
### Samples
<img src="https://github.com/user-attachments/assets/b69cd33d-0fd4-4f67-a771-a19b70619439" width="30%"></img> <img src="https://github.com/user-attachments/assets/19f5f0cd-63f9-42b9-b187-348772b162a5" width="30%"></img> <img src="https://github.com/user-attachments/assets/af15dc3e-4dba-4eac-854d-37aa89fc1310" width="30%"></img>
## Usage
### Docker Build
- Build Image
```bash
docker build -t cv-builder .
```
(!) First build may take some time because of cargo indexing
- #### Build CV
```
docker run -it --rm \
-v ./src:/opt/cv/src -v ./target:/opt/cv/target \
-e CV_NAME=CV_John_Doe \
cv-builder
```
### IDE (Optional)
- Install ```rust``` version manager:
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustup-init
```
(!) Remove existing rust system installations if any;
- Install ```typst```:
```bash
cargo install typst-cli
cargo install typstyle
```
- Install VSCode Plugins
```
Tinymist Typst
PDF Preview
```
- Configure VSCode Typst plugin:
1. Set typstyle as formatter
2. Disable on-save PDF builds
- #### Hot reload builds:
```bash
export TYPST_CV_NAME="CV_John_Doe" \
typst watch \
./src/my-cv.typ \
./target/$TYPST_CV_NAME.pdf
```
- #### PDF to JPEG
```bash
pdftoppm -jpeg -r 300 ./target/CV_John_Doe_1.pdf ./target CV_John_Doe_1
```
## Troubleshooting
### Fonts
- When changing fonts and font sizes, try to adjust ```*-padding``` variables in the configuration for better results
- If [local build](#hot-reload-builds): fonts are taken from your host OS. Run following command to see fonts installed
```
typst fonts
```
- If [docker build](#docker-build): fonts are taken from the Docker container. Run following command to see fonts installed inside the container
```
docker run -it --rm --entrypoint "typst" cv-builder fonts
```
# Links
- [Typst Docs](https://typst.app/docs/reference/foundations/)
- [Typst Package Repository](https://typst.app/universe/)
- [Some hacks](https://sitandr.github.io/typst-examples-book/book/typstonomicon) |
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/blockchain/weeks/week9.typ | typst | #import "../../utils.typ": *
#section("DHT Algorithms")
#subsection("Searching in DHT")
In order to search a term in a DHT, you need to hash your term and store it in a
hashmap which will then be used to check for matches:
- DHT.get(h(«Institut für Software»))
- In order to find it: DHT.put(h(«Institut für Software»), value)
- drawbacks
- only exact searches
- not all keywords are good -> for, some, one etc are bad
#subsubsection("Combining results")
- OR
- DHT.get(h("firstterm")), DHT.get(h("secondterm")), combine results
- AND variants
+ DHT.get(h("firstterm")), DHT.get(h("secondterm")) -> intersect results
+ DHT.get(h("firstterm") xor h("secondterm"))
- In order to find it:
- DHT.put(h(«Institut») xor h(«Software»), value),
- DHT.put(h(«Institut») xor h(«für»), value)
- DHT.put(h(«für») xor h(«Software»), value)
- Combination needs to be known in advance
+ Bloom Filters
- bf = DHT.getBF(h(«Institut»)) and DHT.get(h(«Software», bf))
- Sequential (less network, slower) vs. parallel (more network, faster)
#subsection("Partial Search")
- FastSS -> made by thomas, krass
- Levenshtein distance
- how far away is word 1 from word 2
#align(
center,
[#image("../../Screenshots/2023_11_13_11_17_17.png", width: 100%)],
)
#text(
teal,
)[The value on the bottom right means that with 2 operations, you can get from
word 1 to word 2.]
#align(
center,
[#image("../../Screenshots/2023_11_13_11_17_57.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_13_11_22_02.png", width: 100%)],
)
- multiple queries -> fest: est, fst, fet, fes
- matches because test also includes est
- d(test, fest) = 1 -> edit distance is 1, since it's on the same deletion
position
- deletion position 4 would mean distance 4
#subsubsection("Partial Search in documents")
#columns(2, [
#align(
center,
[#image("../../Screenshots/2023_11_13_11_43_32.png", width: 100%)],
)
#colbreak()
#align(
center,
[#image("../../Screenshots/2023_11_13_11_43_43.png", width: 100%)],
)
])
#subsubsection("Range Queries")
- multiple things to query for
- can be in sequence or random
- sequence: Insert 10 items: N = 5 → [0, 1, 2, 3, 4], [5, 6, 7, 8, 9] –
sequential, 2 peers
- random: Insert 10 items: N = 5 → [0], [5], [10], [15], [20], [25], [30], [35],
[40], [45] – random, 10 peers
- Over-DHT optimizes range queries
- PHT: trie (prefix tree); DST: segment → tree on top of DHT
- Main idea: hash of tree-node (resp. for range) → DHT
- PHT: Peer stores n data items, if n reached, splits data (moves data across
peers)
- DST: stores data on each level (redundancy) up to a threshold
- No data splitting
- like a tree: [#image("../../Screenshots/2023_11_13_11_50_55.png", width: 30%)],
Example:
#columns(2, [
#align(
center,
[#image("../../Screenshots/2023_11_13_11_51_58.png", width: 100%)],
)
#colbreak()
#align(
center,
[#image("../../Screenshots/2023_11_13_11_52_16.png", width: 100%)],
)
])
#section("P2P Algorithms")
#subsection("Bloom Filter")
- array of n bits
- uses k independent hash functions -> k is a chosen number
- each input is hashed with every hash function
- operations
- Insertion
- The bit A[hi(x)] for 1 < i < k are set to 1
- aka each output of the hash function is set to 1
- Query
- Yes if all of the bits A[hi(x)] are 1, no otherwise
- Deletion
- Removing an element from this simple Bloom filter is
#align(
center,
[#image("../../Screenshots/2023_11_13_12_16_25.png", width: 50%)],
)
Example:
#align(
center,
[#image("../../Screenshots/2023_11_13_12_17_43.png", width: 100%)],
)
#columns(
2,
[
#text(green)[benefits:]
- space efficient
- any bloom filter can represent the entire universe -> just with 100000 false
positives...
- no space constraints
- never fails in the sense of not creating a filter
- simple operations
- no false negatives
#colbreak()
#text(red)[liabilities:]
- false positives
- simple bloom filter can't delete
],
)
#align(
center,
[#image("../../Screenshots/2023_11_13_12_20_34.png", width: 50%)],
)
#subsubsection("Variants")
- Compressed Bloom Filters
- when filter is intended to be passed as a message
- false positive rate is optimized for the compressed bloom filter
- compression/decompression -> more memory
- Generalized Bloom Filters
- Two type of hash functions gi (reset bits to 0) and hj (set bits to 1)
- Start with an arbitrary vector (bits can be either 0 or 1)
- In case of collisions between gi and hj, bit is reset to 0
- Store more info with low false positive
- Produces either false positives or false negatives
- #text(red)[false negative possible because of two types of hashes combined!]
- Counting Bloom Filters
- Entry in the filter not be a single bit but a counter
- Delete operation possible (decrementing counter)
- Variable-Increment Counting Bloom Filter
- Scalable Bloom Filters
- Adapt dynamically to number of elements, consist of regular Bloom filters
- “A SBF is made up of a series of one or more (plain) Bloom Filters; when filters
get full due to the limit on the fill ratio, a new one is added; querying is
made by testing for the presence in each filter”
#subsection("Merkle Trees")
- binary hash tree containing leaf nodes
- constructed bottom-up
- used to summarize all transactions in a block
- To prove that a specific transaction is included in a block, a node only needs
to produce hashes, constituting a merkle path connecting the specific
transaction to the root of the tree.
#align(
center,
[#image("../../Screenshots/2023_11_13_12_28_23.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_13_12_28_36.png", width: 80%)],
)
#subsection("BitTorrent")
#align(
center,
[#image("../../Screenshots/2023_11_13_12_30_20.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_13_12_30_35.png", width: 100%)],
)
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/page_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Just empty page with styles.
// Should result in one conifer-colored A11 page.
#page("a11", flipped: true, fill: conifer)[]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-16A40.typ | typst | Apache License 2.0 | #let data = (
("MRO LETTER TA", "Lo", 0),
("MRO LETTER NGI", "Lo", 0),
("MRO LETTER YO", "Lo", 0),
("MRO LETTER MIM", "Lo", 0),
("MRO LETTER BA", "Lo", 0),
("MRO LETTER DA", "Lo", 0),
("MRO LETTER A", "Lo", 0),
("MRO LETTER PHI", "Lo", 0),
("MRO LETTER KHAI", "Lo", 0),
("MRO LETTER HAO", "Lo", 0),
("MRO LETTER DAI", "Lo", 0),
("MRO LETTER CHU", "Lo", 0),
("MRO LETTER KEAAE", "Lo", 0),
("MRO LETTER OL", "Lo", 0),
("MRO LETTER MAEM", "Lo", 0),
("MRO LETTER NIN", "Lo", 0),
("MRO LETTER PA", "Lo", 0),
("MRO LETTER OO", "Lo", 0),
("MRO LETTER O", "Lo", 0),
("MRO LETTER RO", "Lo", 0),
("MRO LETTER SHI", "Lo", 0),
("MRO LETTER THEA", "Lo", 0),
("MRO LETTER EA", "Lo", 0),
("MRO LETTER WA", "Lo", 0),
("MRO LETTER E", "Lo", 0),
("MRO LETTER KO", "Lo", 0),
("MRO LETTER LAN", "Lo", 0),
("MRO LETTER LA", "Lo", 0),
("MRO LETTER HAI", "Lo", 0),
("MRO LETTER RI", "Lo", 0),
("MRO LETTER TEK", "Lo", 0),
(),
("MRO DIGIT ZERO", "Nd", 0),
("MRO DIGIT ONE", "Nd", 0),
("MRO DIGIT TWO", "Nd", 0),
("MRO DIGIT THREE", "Nd", 0),
("MRO DIGIT FOUR", "Nd", 0),
("MRO DIGIT FIVE", "Nd", 0),
("MRO DIGIT SIX", "Nd", 0),
("MRO DIGIT SEVEN", "Nd", 0),
("MRO DIGIT EIGHT", "Nd", 0),
("MRO DIGIT NINE", "Nd", 0),
(),
(),
(),
(),
("MRO DANDA", "Po", 0),
("MRO DOUBLE DANDA", "Po", 0),
)
|
https://github.com/0x546974616e/typst-resume | https://raw.githubusercontent.com/0x546974616e/typst-resume/main/resume.typ | typst | #import "./template/project.typ": resume
#if not "config" in sys.inputs {
panic("Please provide a config file with --input config=FILE")
}
#if not "lang" in sys.inputs {
panic("Please provide a language with --input lang=LANG")
}
#resume(
yaml(sys.inputs.config),
sys.inputs.lang,
)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/zhconv/0.3.1/README.md | markdown | Apache License 2.0 | # zhconv-typst
zhconv-typst converts Chinese text between Traditional, Simplified and regional variants in typst, utilizing [zhconv-rs](https://github.com/Gowee/zhconv-rs).
## Usage
To use the `zhconv` plugin in your Typst project, import it as follows:
```typst
#import "@preview/zhconv:0.3.1": zhconv
```
### Text Conversion
The primary function provided by this package is `zhconv`, which converts strings or nested contents to a target Chinese variant.
```typst
#zhconv(content, "target-variant", wikitext: false)
```
- `content`: The text or content to be converted.
- `target-variant`: The target Chinese variant (e.g., `"zh-hant"` , `"zh-hans"`, `"zh-cn"`, `"zh-tw"`, `"zh-hk"`).
- `wikitext`: An optional boolean flag to specify if the text should be processed as wikitext (default is `false`).
#### Example
##### Convert a string
```typst
#let text = "互联网"
Original: #text
- #emph([zh-HK]): #zhconv(text, "zh-hk")
- #emph([zh-TW]): #zhconv(text, "zh-tw")
```
##### Convert nested contents
```typst
#zhconv([
柳外輕雷池上雨 \
雨聲滴碎荷聲 \
小樓西角斷虹明 \
闌干倚處 \
待得月華生 \
], "zh-hans")
```
|
https://github.com/vonhyou/typst-resume-template | https://raw.githubusercontent.com/vonhyou/typst-resume-template/master/main.typ | typst | #import "header.typ": header
#import "section.typ": section
#set page("us-letter")
#header(
name: "<NAME>",
address: "6299 South St., Halifax, NS B3H 4R2",
phone: "9021234567",
email: "<EMAIL>",
social: (
("https://github.com/vonhyou", [GitHub]),
("#", [Linkedin]),
("#", [Twitter]),
("#", [Blog])
)
)
#linebreak()
#section(
title: "Education",
items: (
(text(weight: "bold", "Dalhousie University"),
[#text(style: "italic", "Jan. 2022 – Present")\ ]),
([Bachelor of Computer Science with Co-op Education], [GPA 4.21/4.30\ ]),
(lorem(24), [])
)
)
#section(
title: "Experience",
items: (
(text(weight: "bold", "XYZ Company"),
text(style: "italic", "May. 2021 – Aug. 2021")),
([- #lorem(12)
- #lorem(23)], [#v(0pt, weak: true)]),
(text(weight: "bold", "QWERTY Company"),
text(style: "italic", "May. 2021 – Aug. 2021")),
([- #lorem(12)
- #lorem(23)], [#v(0pt, weak: true)]),
(text(weight: "bold", "ABC Company"),
text(style: "italic", "May. 2019 – Aug. 2019")),
([- #lorem(12)
- #lorem(23)], [])
)
)
#section(
title: [Project],
items: (
(text(weight: "bold", "Some Interesting Stuff"),
link("#")[#text(font: "TeX Gyre Cursor", "ProjectHomePage")]),
([- #lorem(12)
- #lorem(23)
- #lorem(12)], [#v(0pt, weak: true)]),
(text(weight: "bold", "Some Interesting Stuff"),
link("#")[#text(font: "TeX Gyre Cursor", "ProjectHomePage")]),
([- #lorem(12)
- #lorem(23)
- #lorem(12)], [#v(0pt, weak: true)])
)
)
#section(
title: [Misc],
items: (
([- #lorem(12)
- #lorem(23)
- #lorem(12)
- #lorem(12)
- #lorem(23)], []),
)
)
|
|
https://github.com/monaqa/typst-easytable | https://raw.githubusercontent.com/monaqa/typst-easytable/master/README.md | markdown | MIT License | # Typst Easytable Package
A Typst library for writing simple tables.
## Usage
```typst
#import "@preview/easytable:0.1.0": easytable, elem
#import elem: *
```
## Manual
- You can create a table by specifying data or layout elements as arguments to the `easytable` function.
- The following elements are provided in the `elem` module.
- `elem.tr`: a data row
- `elem.th`: a header row
- `elem.hline`: a horizontal line
- `elem.vline`: a vertical line
- `elem.cwidth`: a column-width specifier
- `elem.cstyle`: a column-style (font, alignment, etc.) specifier
See [manual](./manual.pdf) in detail.
## Examples
### A Simple Table
```typst
#easytable({
th[Header 1 ][Header 2][Header 3 ]
tr[How ][I ][want ]
tr[a ][drink, ][alcoholic ]
tr[of ][course, ][after ]
tr[the ][heavy ][lectures ]
tr[involving][quantum ][mechanics.]
})
```

### Setting Column Alignment and Width
```typst
#easytable({
cwidth(100pt, 1fr, 20%)
cstyle(left, center, right)
th[Header 1 ][Header 2][Header 3 ]
tr[How ][I ][want ]
tr[a ][drink, ][alcoholic ]
tr[of ][course, ][after ]
tr[the ][heavy ][lectures ]
tr[involving][quantum ][mechanics.]
})
```

### Customizing Styles
```typst
#easytable({
let tr = tr.with(trans: pad.with(x: 3pt))
th[Header 1][Header 2][Header 3]
tr[How][I][want]
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
})
```

```typst
#easytable({
let th = th.with(trans: emph)
let tr = tr.with(
cell_style: (x: none, y: none)
=> (fill: if calc.even(y) {
luma(95%)
} else {
none
})
)
th[Header 1][Header 2][Header 3]
tr[How][I][want]
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
})
```

```typst
#easytable({
th[Header 1][Header 2][Header 3]
tr[How][I][want]
hline(stroke: red)
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
// Specifying the insertion point directly
hline(stroke: 2pt + green, y: 4)
vline(
stroke: (paint: blue, thickness: 1pt, dash: "dashed"),
x: 2,
start: 1,
end: 5,
)
})
```

|
https://github.com/qjcg/awesome-typst | https://raw.githubusercontent.com/qjcg/awesome-typst/main/README.md | markdown | Creative Commons Zero v1.0 Universal | <p align=center>
<a href="README.md" hreflang="en" lang="en">English</a>
| <a href="README_ZH.md" hreflang="zh" lang="zh">简体中文</a>
</p>
# Awesome Typst
[](https://github.com/sindresorhus/awesome#readme)
Curated collection of useful links for [Typst](https://github.com/typst/typst) users.
PRs welcomed!
<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc -->
## Contents
- [Official Project Links](#official-project-links)
- [Unofficial Project Links](#unofficial-project-links)
- [Integrations & Tools](#integrations--tools)
- [Browser Extensions](#browser-extensions)
- [Chatbots](#chatbots)
- [CI/CD](#cicd)
- [CLI Tools](#cli-tools)
- [Editors](#editors)
- [Editor Integrations](#editor-integrations)
- [Online Tools](#online-tools)
- [Programming](#programming)
- [Typst As A Service](#typst-as-a-service)
- [Templates & Libraries](#templates--libraries)
- [Official](#official)
- [General](#general)
- [Assignments](#assignments)
- [CV](#cv)
- [Examples](#examples)
- [Templates](#templates)
- [Calendar / Timetable](#calendar--timetable)
- [Footnotes & Endnotes](#footnotes--endnotes)
- [Formatting](#formatting)
- [Graphics](#graphics)
- [Letters](#letters)
- [Linguistics](#linguistics)
- [Mathematics](#mathematics)
- [Music](#music)
- [Physics](#physics)
- [Conferences](#conferences)
- [Journals](#journals)
- [Grants/Proposals](#grantsproposals)
- [Engineering](#engineering)
- [Plotting](#plotting)
- [Posters](#posters)
- [Scripting](#scripting)
- [Slides](#slides)
<!-- markdown-toc end -->
## Official Project Links
- [typst.app](https://typst.app) - The Typst web app
- [Typst Documentation](https://typst.app/docs)
- [GitHub](https://github.com/typst/typst)
- [Blog](https://typst.app/blog/)
- Social - [Discord] [Instagram] [LinkedIn] [Mastodon] [X]
[discord]: https://discord.com/invite/2uDybryKPe
[instagram]: https://www.instagram.com/typstapp/
[linkedin]: https://www.linkedin.com/company/typst/
[mastodon]: https://mastodon.social/@typst
[X]: https://twitter.com/typstapp/
## Unofficial Project Links
- [Typst-telegram-russian-chat](https://t.me/typst_ru) - chat about Typst in Telegram in russian
- [#typst:matrix.org](https://matrix.to/#/%23typst:matrix.org) - matrix room for Typst
- [Typst Examples Book](https://sitandr.github.io/typst-examples-book/book/) - An online book with Typst snippets, including extended tutorial and useful hacks
## Integrations & Tools
### Browser Extensions
- (FireFox) [bib-kit](https://github.com/MordragT/bib_kit) - Retrieve website information to create citations in the hayagriva format
- (FireFox) [yank](https://addons.mozilla.org/en-US/firefox/addon/yank/) - Yank URL and title of current tab, format to a chosen markup language, and copy to clipboard (supports typst link format)
### Chatbots
- [typst-bot](https://github.com/mattfbacon/typst-bot) - A discord bot to render Typst code
- [typst-bot-telegram](https://t.me/ru_rend_bot) - A telegram bot to render Typst code
- [typst-telegram-bot](https://github.com/daskol/typst-telegram-bot) - A [telegram bot](https://t.me/TypstBot) with focus in rendering math expression in Typst.
### CI/CD
- [gitlab-ci-typst](https://gitlab.com/IvanSanchez/gitlab-ci-typst) - Build Typst documents using GitLab CI pipelines
- [setup-typst](https://github.com/typst-community/setup-typst) - 📑 Install Typst for use in GitHub Actions
- [typst-action](https://github.com/lvignoli/typst-action) - Build Typst documents using GitHub actions
### CLI Tools
- [typstfmt](https://github.com/astrale-sharp/typstfmt/) - Basic formatter for the Typst language with a future!
- [typstyle](https://github.com/Enter-tainer/typstyle) - Opinionated typst code formatter focusing on aesthetic, convergence and correctness.
- [typst-live](https://github.com/ItsEthra/typst-live) - Hot reloading of pdf in web browser
- [typst-pandoc](https://github.com/lvignoli/typst-pandoc) - Typst custom reader and writer for Pandoc
- [utpm](https://github.com/Thumuss/utpm) - Package manager for local and remote packages
### Editors
- [typstudio](https://github.com/Cubxity/typstudio) - An in development desktop editor built using Tauri.
- [Katvan](https://github.com/IgKh/katvan) - A bare-bones editor for Typst files, with a bias for Right-to-Left editing.
- [Typstwriter](https://github.com/Bzero/typstwriter) - An integrated desktop editor for typst projects.
### Editor Integrations
- [SeniorMars/tree-sitter-typst](https://github.com/SeniorMars/tree-sitter-typst) - A TreeSitter parser for the Typst File Format
- [Tinymist VS Code Extension](https://marketplace.visualstudio.com/items?itemName=myriad-dreamin.tinymist) - A vscode extension for Tinymist integration
- [Tinymist](https://github.com/Myriad-Dreamin/tinymist) - A language server for typst with integrations for vscode, zed, neovim, and helix
- [Typst LSP VS Code Extension](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp)
- [Typst Sync](https://github.com/OrangeX4/vscode-typst-sync) - A vscode extension for Typst local packages management and synchronization.
- [frozolotl/tree-sitter-typst](https://github.com/frozolotl/tree-sitter-typst) - A tree-sitter grammar with a focus on correctness.
- [inktyp](https://github.com/herlev/inktyp) - An Inkscape plugin to insert and edit Typst equations
- [obsidian-typst](https://github.com/fenjalien/obsidian-typst) - Renders typst code blocks in Obsidian into images using Typst through the power of WASM!
- [org-typst-preview](https://github.com/remimimimimi/org-typst-preview.el) - Typst preview in org-mode
- [typst-conceal.vim](https://github.com/MrPicklePinosaur/typst-conceal.vim) - Vim/Nvim plugin for replacing long typst symbol names with unicode characters
- [typst-lsp](https://github.com/nvarner/typst-lsp) - A brand-new language server for Typst, plus a VS Code extension
- [typst-math](https://marketplace.visualstudio.com/items?itemName=surv.typst-math) - A VS Code extension to simplify math writing in Typst
- [typst-sympy-calculator](https://github.com/OrangeX4/vscode-typst-sympy-calculator) - VS Code extension for Typst math calculating, includes Arithmetic, Calculus, Matrix, Custom Variances and Functions by yourself
- [typst-ts-mode](https://git.sr.ht/~meow_king/typst-ts-mode) - Typst tree sitter major mode for Emacs
- [typst.nvim](https://github.com/SeniorMars/typst.nvim) - WIP. Goals: Treesitter highlighting, snippets, and a smooth integration with neovim
- [typst.vim](https://github.com/kaarmu/typst.vim) - Vim plugin for Typst
- [typstd](https://github.com/daskol/typstd) - Yet another Typst language server.
- [uben0/tree-sitter-typst](https://github.com/uben0/tree-sitter-typst) - A TreeSitter grammar for the Typst language, used by Helix
### Online Tools
- [Detypify](https://github.com/QuarticCat/detypify) - Typst symbol classifier
### Programming
- [leetcode.typ](https://github.com/lucifer1004/leetcode.typ) - Solving Leetcode problems in Typst
- [Typix](https://github.com/loqusion/typix) - Deterministic Typst compilation with Nix
- [typst-py](https://github.com/messense/typst-py) - Python binding to typst
- [typst-rb](https://github.com/actsasflinn/typst-rb) - Ruby binding to typst
- [Typstry.jl](https://github.com/jakobjpeters/Typstry.jl) - The Julia to Typst interface
- [mpl-typst](https://github.com/daskol/mpl-typst) - A Typst backend for Matplotlib.
### Typst As A Service
- [typst-http-api](https://github.com/slashformotion/typst-http-api) - An simple docker containing an API to compile typst markup
- [typst-telegram-bot](https://github.com/daskol/typst-telegram-bot) - A plain and simple HTTP API for rendering math with Typst.
## Templates & Libraries
### Official
- [typst/templates](https://github.com/typst/templates) - The templates that ship with the Typst web app
### General
- [Data Thinking Report Template](https://github.com/onefact/datathinking.org-report-template) - a template for artificial intelligence whitepapers with collaborative bibliographies using Zotero
- [HSOS-PTP-Typst-Template](https://github.com/mst2k/HSOS-PTP-Typst-Template) - A German template for writing papers, overfitted for the Osnabrück University of Applied Scien
- [INSA Typst Template](https://github.com/SkytAsul/INSA-Typst-Template) - A template for INSA (Institut National des Sciences Appliquées), a french public engineering school.
- [LaPreprint](https://github.com/LaPreprint/typst) - Beautiful preprints for Typst
- [Mantys](https://github.com/jneug/typst-mantys) - A template for writing manuals for Typst packages.
- [Project-Report-Typst](https://github.com/aurghya-0/Project-Report-Typst) - A simple template for college or university level project report.
- [SimplePaper](https://github.com/jinhao-huang/SimplePaper) - A Chinese template for writing simple paper
- [Typst-Paper-Template](https://github.com/jxpeng98/Typst-Paper-Template) - Typst template for Working Paper
- [aiaa-typst-template](https://gitlab.com/waterlubber/aiaa-typst-template) - A template for AIAA (American Institute of Aeronautics and Astronautics) papers.
- [bubble-template](https://github.com/hzkonor/bubble-template) - A simple and colorful template for reports
- [french-association-status](https://github.com/coco33920/typst-association-statuts) - A Template to write status for french associations.
- [gloss-awe](https://github.com/RolfBremer/gloss-awe) - Automatically Generated Glossary Page (renamed from typst-glossary)
- [in-dexter](https://github.com/RolfBremer/in-dexter) - Automatically Generated Index Page (renamed from typst-index)
- [mcm-icm-typst-template](https://github.com/DawnEver/mcm-icm-typst-template) - A template for Mathematical Contest in Modeling (MCM) and the Interdisciplinary Contest in Modeling(ICM).
- [simple-typst-thesis](https://github.com/zagoli/simple-typst-thesis) - A template useful for writing simple thesis in Typst
- [thesis-template-typst](https://github.com/ls1intum/thesis-template-typst) - Technical University of Munich thesis Template with cover, titlepage, tables, figures, appendix, etc.
- [typst-bioinfo-thesis](https://github.com/lkndl/typst-bioinfo-thesis) - Flexible section headers and page numbers; pretty outlines and a `wrapfig`
- [typst-invoice](https://github.com/erictapen/typst-invoice) - Generate invoices from TOML files
- [typst-mla9-template](https://github.com/wychwitch/typst-mla9-template) - An MLA 9th edition template
- [typst-orange-template](https://github.com/flavio20002/typst-orange-template) - A Typst book template inspired by The Legrand Orange Book
- [typst-palettes](https://github.com/kaarmu/splash) - A library of color palettes for Typst
- [typst-templates](https://github.com/daskol/typst-templates) - A templates collection for major venues in machine learning and AI.
- [typst-templates](https://github.com/eigenein/typst-templates) - Templates for Typst
- [typst-templates](https://github.com/haxibami/haxipst) - My typst templates
- [typst-uwthesis](https://github.com/yangwenbo99/typst-uwthesis) - A typst template for writing thesis, featuring a working abbreviation lists.
- [typstry](https://github.com/qjcg/typstry) - A Tapestry of Typst Templates & Examples
- [writable-gm-screen-inserts](https://github.com/LLBlumire/writable-gm-screen-inserts) - Writable Game Master Screen Insertsces
### Assignments
- [OpenBoard](https://github.com/diquah/OpenBoard) - Easily build clean assessments in the style of the College Board.
- [assignment-template](https://github.com/AntoniosBarotsis/typst-assignment-template) - A simple assignment template
- [typst-assignment-template](https://github.com/astrale-sharp/typst-assignement-template) - Yet another simple assignment template
- [typst-assignment-template](https://github.com/gRox167/typst-assignment-template) - Yet another simple assignment template with a cover and several useful math symbols.
- [typst-homework-template](https://github.com/OriginCode/typst-homework-template) - A simple homework template inspired by the LaTeX homework template by Adam Blank
- [typst-teacher-template](https://github.com/jomaway/typst-teacher-templates) - A collection of typst templates. Mainly used to create worksheets and exams for my classes.
### CV
#### Examples
- [bare-bones-cv](https://github.com/caffeinatedgaze/bare-bones-cv) – A single-page minimalistic CV comprising essentials only.
- [cv.typ](https://github.com/jskherman/imprecv) - A no-frills curriculum vitae (CV) template for Typst that uses a YAML file for data input in order to version control CV data easily.
- [chicv](https://github.com/skyzh/chicv) - A minimal and fully-customizable CV template.
#### Templates
- [NNJR](https://github.com/tzx/NNJR) - A resume template inspired by `Jake's Resume` LaTeX template. Uses Typst and YAML.
- [alta-typst](https://github.com/GeorgeHoneywood/alta-typst) - A simple Typst CV template, inspired by AltaCV by <NAME>
- [attractive-typst-resume](https://github.com/Harkunwar/attractive-typst-resume) - A modern looking, attractive CV/Resume template by <NAME>
- [billryan-typst](https://github.com/gvariable/billryan-typst) - A simple and minimalist resume template, inspired by Resume by Billryan.
- [brilliant-CV](https://github.com/mintyfrankie/brilliant-CV) - Another CV template for your job application, yet powered by Typst and more
- [caidan](https://github.com/cu1ch3n/caidan) - A clean and minimal food menu template.
- [cv.typ](https://github.com/jskherman/imprecv) - A no-frills curriculum vitae (CV) template using Typst and YAML to version control CV data.
- [friggeri-cv](https://github.com/olligobber/friggeri-cv) - A slightly modified version of the Friggeri CV, originally created by <NAME> in LaTeX, ported to Typst.
- [modern-cv](https://github.com/peterpf/modern-typst-resume) - A modern resume and coverletter template based on `Awesome CV`
- [modern-typst-template](https://github.com/peterpf/modern-typst-resume) - A modern resume/CV template.
- [moderncv.typst](https://github.com/giovanniberti/moderncv.typst) - A CV template inspired by LaTeX's `moderncv`
- [resume.typ](https://github.com/wusyong/resume.typ) - Simple and ergonomic template to generate resume and CV
- [simplecv](https://github.com/LaurenzV/simplecv) - SimpleCV is a simple and elegant CV template written in Typst
- [typst-academic-cv](https://github.com/DawnEver/typst-academic-cv) - Typst Template for Academic CV
- [typst-cv-miku](https://github.com/ice-kylin/typst-cv-miku) - A simple, elegant, academic style CV template for typst. Support for English and Chinese (and more)
- [typst-cv-resume](https://github.com/jxpeng98/Typst-CV-Resume) - A CV template with Sans font inspired by LaTeX `Deedy-Resume`
- [typst-cv-template1](https://github.com/vaibhavjhawar/typst-cv-template1) - A CV template inspired by <NAME>'s Graduate CV LaTex template
- [typst-cv-template](https://github.com/JCGoran/typst-cv-template) - A CV template inspired by LaTeX's `Awesome CV`
- [typst-cv-template](https://github.com/skyzh/chicv) - Chi CV Template (For Typst)
- [typst-mixed-resume](https://github.com/titaneric/typst-mixed-resume) - A casual and elegant resume template inspired by multiple templates.
- [typst-neat-cv](https://github.com/UntimelyCreation/typst-neat-cv) - A Typst template for modern, minimal and elegant CVs, inspired by mintyfrankie's `Brilliant CV`
- [typst-resume-sans](https://github.com/mizlan/typst-resume-sans) - A sleek and unadorned sans-serif resume template.
- [typst-resume-template](https://github.com/bamboovir/typst-resume-template) - Aesthetic style inspired by the Awesome-CV project
- [typst-resume-template](https://github.com/hexWars/resume) - A pretty resume template designed using typst.
- [typst-twentysecondcv](https://github.com/tomowang/typst-twentysecondcv) - A CV template inspired by LaTeX's `Twenty Seconds Resume/CV`
- [typst-yaml-cv](https://github.com/daxartio/cv) - A simple cv template designed using typst and yaml.
- [vercanard](https://github.com/elegaanz/vercanard) - A colorful resume template for Typst
### Calendar / Timetable
- [typst-timetable](https://github.com/ludwig-austermann/typst-timetable) - A template for timetables
### Footnotes & Endnotes
- [notes.typ](https://github.com/tudborg/notes.typ) - A library for notes with deduplication and customizability.
- [typst-notes](https://github.com/saadulkh/typst-notes) - A library for adding footnotes and endnotes in Typst
### Formatting
- [metro](https://github.com/fenjalien/metro) - A typst package to add typsetting to units!
- [ruby-typ](https://github.com/rinmyo/ruby-typ) - A library to add ruby text
- [showybox](https://github.com/Pablo-Gonzalez-Calderon/showybox-package) - A Typst package for creating colorful and customizable boxes.
- [simple-poem-typst](https://github.com/asibahi/simple-poem-typst) - An application of the `measure` function to set Arabic poetry.
- [syntastica-typst](https://github.com/RubixDev/syntastica-typst/) - Tree-sitter syntax highlighting for code blocks.
- [term](https://github.com/qo/term) - A Typst package for creating figures that emulate terminal screenshots.
- [typst-ansi_render](https://github.com/8LWXpg/typst-ansi-render) - A library to render text with ANSI escape sequences
- [typst-boxes](https://github.com/lkoehl/typst-boxes) - A library to draw colorful boxes.
- [typst-codelst](https://github.com/jneug/typst-codelst) - A Typst package to render source code.
- [typst-diagbox](https://github.com/PgBiel/typst-diagbox) - A library for diagonal line dividers in Typst tables
- [typst-gentle-clues](https://github.com/jomaway/typst-gentle-clues) - A typst package to simply add admonitions.
- [typst-tablem](https://github.com/OrangeX4/typst-tablem) - Write markdown-like tables easily.
- [typst-tablex](https://github.com/PgBiel/typst-tablex) - More powerful and customizable tables in Typst!
### Graphics
- [CeTZ](https://github.com/cetz-package/cetz) - CeTZ (CeTZ, ein Typst Zeichenpacket) is a library for drawing with [Typst](https://typst.app) with an API inspired by TikZ and [Processing](https://processing.org/). It comes with modules for drawing plots, graphs and charts.
- [typst-raytracer](https://github.com/SeniorMars/typst-raytracer) - raytracer in typst
### Letters
- [typst-letter-pro](https://github.com/Sematre/typst-letter-pro) - DIN 5008 letter template for Typst
- [typst-letter](https://github.com/dvdvgt/typst-letter) - A typst letter template inspired by the DIN 5008 norm
- [typst-letter-template](https://github.com/pascal-huber/typst-letter-template) - A customizable typst letter template with different presets (DIN 5008, Swiss C5)
### Linguistics
- [leipzig-gloss](https://gitea.everydayimshuflin.com/greg/typst-lepizig-glossing) - A library that provides primitives for creating glossing rules according to Leipzig.
- [typst-ipa](https://github.com/imatpot/typst-ascii-ipa) - 🔄 ASCII / IPA conversion for Typst
- [typst-dictionary-template](https://kianting.info/wiki/w/Tan_Kian-ting%E7%9A%84%E7%B6%AD%E5%9F%BA:Typst-dictionary-template) - 📕 a template for lexical dictionary/glossary in Typst
- [typst-syntree](https://github.com/lynn/typst-syntree) - Syntax trees for typst
### Mathematics
- [commute](https://gitlab.com/giacomogallina/commute) - A library for creating commutative diagrams
- [typst-algorithms](https://github.com/platformer/typst-algorithms) - A library for writing algorithms
- [typst-himcm-template](https://github.com/EvanLuo42/typst-himcm-template) - An HiMCM template for Typst
- [typst-math-template](https://github.com/matthiasGmayer/typst-math-template) - A simple math template that allows for numbered, referenceable theorems and compilation of subfiles that use references.
- [typst-pf3](https://github.com/maxwell-thum/typst-pf3) - A small package for creating "structured proofs." Essentially a port of Leslie Lamport's [`pf2.sty`](https://lamport.azurewebsites.net/latex/pf2.sty)
- [typst-theorems](https://github.com/sahasatvik/typst-theorems) - A library for creating numbered theorem environments
- [typst-undergradmath](https://github.com/johanvx/typst-undergradmath) - A Typst port of [undergradmath](https://gitlab.com/jim.hefferon/undergradmath)
### Music
- [conchord](https://github.com/sitandr/conchord) - Typst package to easily write lyrics with chords and generate colorful fretboard diagrams
- [typst-chords](https://github.com/ljgago/typst-chords) - A library to write song lyrics with chord diagrams in Typst
### Physics
- [physics](https://github.com/Leedehai/typst-physics) - A library for usual physics notations, e.g. vectors and vector fields, matrices, differentials, derivatives, Dirac brackets, tensors, isotopes, and digital signal sequences.
#### Conferences
- [aiaa-typst](https://github.com/isaacew/aiaa-typst) - A template for creating conference papers in the style of the American Institute of Aeronautics and Astronautics.
- [ieee-conference-typst-template](https://github.com/DawnEver/ieee-conference-typst-template) A template to write IEEE Conference in Typst.
- [ieee-typst-template](https://github.com/bsp0109/ieee-typst-template) - A template to write IEEE Papers in Typst
- [ifacconf-typst](https://github.com/avonmoll/ifacconf-typst) - A template for creating conference papers in the style of the International Federation of Automatic Control
#### Journals
- [ieee-trans-typst](https://github.com/p4perf4ce/typst-ieee-trans-template) - A template that mimic LaTeX IEEE Transaction template (`ieee-trans.cls`)
#### Grants/Proposals
- [typst-nsf-templates](https://github.com/ntjess/typst-nsf-templates) - National Science Foundation (NSF) general template and outlines for popular proposal types.
### Engineering
- [circuitypst](https://github.com/fenjalien/cirCeTZ) - A library for drawing electronic circuit schematics
- [typst-bytefield](https://github.com/jomaway/typst-bytefield) - A library for drawing (network) protocol headers
- [tids](https://github.com/oldrev/tids) - A TI-style datasheet template for electronic component
### Plotting
- [typst-cd](https://gitlab.com/giacomogallina/commute) - Proof of Concept for tikz-like commutative diagrams
- [typst-plot](https://github.com/johannes-wolf/typst-plot) - A library for plotting line charts (deprecated in favor of CeTZ)
- [typst-plotting](https://github.com/Pegacraft/typst-plotting) - A library for drawing a variety of charts and plots like line charts, histograms, and pie charts
### Posters
- [typst-poster](https://github.com/pncnmnp/typst-poster) - An academic poster template
- [science-posters](https://github.com/jonaspleyer/peace-of-posters) - Create academic posters in block style
### Scripting
- [typst-oxifmt](https://github.com/PgBiel/typst-oxifmt) - Convenient Rust-like string formatting in Typst
- [typst-tools4typst](https://github.com/jneug/typst-tools4typst) - Tools for package and template authors.
### Slides
- [diapo](https://github.com/lvignoli/diapo) - A minimal and simplistic presentation template.
- [polylux](https://github.com/andreasKroepelin/polylux) - Create presentation slides in Typst
- [clean-polylux-typst](https://github.com/marcothms/clean-polylux-typst) - A clean and dynamic polylux presentation slide template
- [pinit](https://github.com/OrangeX4/typst-pinit) - Pin things as you like, especially useful for creating slides in typst.
- [touying](https://github.com/touying-typ/touying) - A powerful package for creating presentation slides in Typst
|
https://github.com/FrightenedFoxCN/cetz-cd | https://raw.githubusercontent.com/FrightenedFoxCN/cetz-cd/main/manual.typ | typst | #import "src/cetz-cd.typ": *
#import "src/snipets.typ": *
This is currently more examples than manual.
#cetz-cd(```
$...$ ar[r] & $C_(n + 1)$ ar[r] ar[d] ar[ld] & $C_n$ ar[r] ar[d] ar[ld] & $C_(n - 1)$ ar[r] ar[d] ar[ld] & $...$ ar[ld];
$...$ ar[r] & $D_(n + 1)$ ar[r] & $D_n$ ar[r] & $D_(n - 1)$ ar[r] & $...$
```)
#cetz-cd(```
$A$ ar[r, $g$] ar[rd, $f$, swapped] & $B$ ar[d];
& $D$
```)
// #to-table(```
// $H_* (A)$ ar[r] ar[d] & $H_*^cal(A) (X)$ ar[r] ar[d] & $H_* (S_*^cA (X \/ S_* (A)))$ ar[r] ar[d] & $H_* (A)$ ar[r] ar[d] & $0$ ar[d] ;
// $H_* (A)$ ar[r] & $H_* (X)$ ar[r] & $H_* (X, A)$ ar[r] & $H_* (A)$ ar[r] & $0$
// ```.text)
#cetz-cd(```
$H_* (A)$ ar[r] ar[d] & $H_*^cal(A) (X)$ ar[r] ar[d] & $H_* (S_*^cal(A) (X \/ S_* (A)))$ ar[r] ar[d] & $H_* (A)$ ar[r] ar[d] & $0$ ar[d];
$H_* (A)$ ar[r] & $H_* (X)$ ar[r] & $H_* (X, A)$ ar[r] & $H_* (A)$ ar[r] & $0$
```)
#cetz-cd( ```
$...$ ar[r] & $C_n$ ar[r, $d_(n - 1)$] ar[d, $u_n$, swapped] & $C_(n - 1)$ ar[r] ar[d, $u_(n - 1)$] & $...$;
$...$ ar[r] & $D_n$ ar[r, $d_(n - 1)$] & $D_(n - 1)$ ar[r] & $...$;
```) |
|
https://github.com/jonmatthis/simple-typst | https://raw.githubusercontent.com/jonmatthis/simple-typst/main/README.md | markdown | # simple-typst
A simple-as-possible `typst` template for MystMD
## Usage
```
---
- format: pdf
template: simple-typst
---
|
|
https://github.com/bigskysoftware/hypermedia-systems-book | https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/HypermediaSystems-ebook.typ | typst | Other |
#import "lib/definitions.typ": *
#set document(
title: [Hypermedia Systems],
)
#show figure.where(kind: "image"): box
#page[
#set align(start + horizon)
#set par(leading: 10pt, justify: false)
#show heading: set text(size: 3em, font: display-font)
#skew(
-0.174, // -10deg
upper(
text(style: "oblique", heading(level: 1, outlined: false, [Hypermedia Systems])),
),
)
#box(height: 1em)
#set text(font: secondary-font)
#grid(gutter: 1em, columns: 3 * (auto,),
[<NAME>],
[<NAME>],
[<NAME>],
)
]
#include "-1-copy-ack.typ"
#pagebreak()
= Dedications
#include "-2-dedication.typ"
#pagebreak()
#counter(page).update(0)
#include "-3-foreword.typ"
= Hypermedia Concepts
#include "ch00-introduction.typ"
#include "ch01-hypermedia-a-reintroduction.typ"
#include "ch02-components-of-a-hypermedia-system.typ"
#include "ch03-a-web-1-0-application.typ"
= Hypermedia-Driven Web Applications With Htmx
#include "ch04-extending-html-as-hypermedia.typ"
#include "ch05-htmx-patterns.typ"
#include "ch06-more-htmx-patterns.typ"
#include "ch07-a-dynamic-archive-ui.typ"
#include "ch08-tricks-of-the-htmx-masters.typ"
#include "ch09-client-side-scripting.typ"
#include "ch10-json-data-apis.typ"
= Bringing Hypermedia To Mobile
#include "ch11-hyperview-a-mobile-hypermedia.typ"
#include "ch12-building-a-contacts-app-with-hyperview.typ"
#include "ch13-extending-the-hyperview-client.typ"
= Conclusion
#include "ch14-conclusion.typ"
|
https://github.com/jskherman/jsk-lecnotes | https://raw.githubusercontent.com/jskherman/jsk-lecnotes/main/content/example-doc.typ | typst | Apache License 2.0 | #import "../template.typ": *
= Introduction
Can you then _suppose_ that those heroic men performed their famous deeds *without any motive at all*? In a free hour, when our power of choice is untrammeled and when nothing prevents our being able to do what we like best, _*every pleasure is to be welcomed and for every pain avoided*_ @netwok2020.
- But in certain emergencies and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted.
- #lorem(25)
- Your references to them just now were historically correct, and also showed your kind and friendly feeling towards myself; but all the same I am not to be bribed by your flattery of my family, and you will not find me a less resolute opponent.
== Paper overview
On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of the pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.
#blockquote[
Euler's identity is $e^(pi i) + 1 = 0$. Do you really believe that they charged an armed enemy, or treated their children, their own flesh and blood, so cruelly, without a thought for their own interest or advantage? Such is Schrödinger's equation in @schrodinger:
$ i planck.reduce frac(diff, diff t) Psi lr((x comma t)) eq lr([minus frac(planck.reduce^2, 2 m) frac(diff^2, diff x^2) plus V lr((x comma t))]) Psi lr((x comma t)) $ <schrodinger>
#blockquote[
But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?
]
]
But I must explain to you how all this mistaken idea of reprobating pleasure and extolling pain arose. Increase ease-of-use to where `variable` and `print()` shall be of use.
#figure(caption: [Example `python` code printing text.])[#sourcecode(
```python
if a != b:
print("Hello world!")
else if a == b:
print("Goodbye world!")
else:
print("This is a long sentence where I ramble until I get 80 characters here.")
```
)] <py-test>
To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? @stokes has a nice example.
1. On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of the pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.
2. #lorem(25)
1. #lorem(25)
2. #lorem(25)
#sectionline
= $e^(pi i)$ Methods
#definition(
"Stokes' theorem",
footer: "Information extracted from a well-known public encyclopedia"
)[
Let $Sigma$ be a smooth oriented surface in $RR^3$ with boundary $diff Sigma
equiv Gamma$. If a vector field $iboxed(bold(F)(x,y,z))=(F_x (x,y,z), F_y (x,y,z),
F_z (x,y,z))$ is defined and has continuous first order partial derivatives
in a region containing $Sigma$, then
$ integral.double_Sigma (bold(nabla) times bold(F)) dot bold(Sigma) =
dboxed(integral.cont_(diff Sigma) bold(F) dot dif bold(Gamma)) $
] <stokes>
#lorem(30)
|
https://github.com/El-Naizin/cv | https://raw.githubusercontent.com/El-Naizin/cv/main/modules_en/education.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Education")
#cvEntry(
title: [Computer Science Engineering degree],
society: [Université de Technologie de Compiègne],
date: [2021 - 2024],
location: [Compiègne, France],
//TODO: logo
logo: "../src/logos/utc.svg",
description: list(
[Developped a more in-depth understanding of Computer Science theory],
[Learned new theoretical tools such as Constraint programming, Linear programming], //TODO: développer
[Focused on embedded systems, software development, and cyber-security ],
)
)
#cvEntry(
title: [Technical University diploma in Computer Science],
society: [IUT of La Rochelle],
date: [2019 - 2021],
location: [La Rochelle, France],
//TODO: logo
logo: "../src/logos/larochelle.png",
description: list(
[Specialised in systems programming],
[Learned kernel programming, POSIX, Assembly, 3D graphics, Drivers],
[Focused on C/C++ and Java development],
)
)
|
https://github.com/Walfisch115/thb-typst-template | https://raw.githubusercontent.com/Walfisch115/thb-typst-template/main/presentation/conf.typ | typst | #let conf(
doc
) = {
set page(paper: "presentation-16-9")
set text(lang: "de")
set text(font: "Linux Biolinum")
doc
}
// SLIDES
#let thbBlue = rgb(0, 186, 229, 100%)
#let thbRed = rgb(204, 17, 50, 100%)
// normal slide
#let slide(
title: [Titel hinzufügen],
presentationTitle: none,
date: none,
body: [Text hinzufügen]
) = {
// slide header
let slideHeader = {
// add THB logo in an inline container
box()[
#image("THB_Logo.svg", width: 1cm)
]
// add horizontal padding
h(1cm)
text(size: 21pt, fill: thbRed, weight: "bold")[
#title
]
}
let slideBody = {
// add some vertical padding
v(0.5cm)
pad(left: 2cm)[
#text(size: 18pt)[#body]
]
}
let slideFooter = {
// change text size, weight and color
set text(size: 8pt, fill: white, weight: "bold")
box(
fill: thbBlue,
height: 100%,
width: 100%,
outset: (x: 100%),
)[
// center vertically
#align(horizon)[
#grid(
columns: (1fr, 1fr),
gutter: 0.75em,
align: (left, right),
[#presentationTitle],
[#date],
[Technische Hochschule Brandenburg • University of Applied Sciences],
[#counter(page).display()]
)
]]
}
page(
margin: (top: 3cm, left: 1cm),
header: slideHeader,
footer: slideFooter
)[
#slideBody
]
}
// title slide
#let titleSlide(
title: [Titel],
supervisor: none,
date: none
) = {
let thbLogo = {
place(left + top)[
#image("THB_Logo_mit_Schrift.png", height: 5cm)
]
}
let slideBody = {
set text(fill: white)
box(
fill: thbBlue,
height: 100%,
width: 100%,
inset: (x: 2cm, y: 2cm)
)[
#align(top)[
#text(size: 24pt, weight: "bold")[#title]
]
#align(bottom)[
#text(size: 14pt)[
#supervisor \
#date
]]
]
}
page(
margin: (left: 1cm, top: 4cm, right: 0cm, bottom: 1cm),
foreground: thbLogo
)[
#slideBody
]
} |
|
https://github.com/schmidma/typst-workshop | https://raw.githubusercontent.com/schmidma/typst-workshop/main/examples/08-functions.typ | typst | Creative Commons Zero v1.0 Universal | To go to scripting mode, type `#` and *some function name* after that. We will start with _something dull_:
#lorem(50)
|
https://github.com/FuryMartin/fury-note-typst | https://raw.githubusercontent.com/FuryMartin/fury-note-typst/master/src/lib.typ | typst | MIT License | #let note(
// The Thesis Title
title: [],
// An array of authors. For each author, you can specify a name,
// department, organization, location and email. Everything but the name is optional.
author: (name: "", email: ""),
//Your thesis abstract. Can be omitted if you dont have one.
abstract: none,
// The thesis papersize. Default is A4. Affects margins.
papersize: "a4",
// The result of a call to the `bibliography` function or none
bib: none,
// The language of the document. Default is "de".
lang: "zh",
//The appendix
appendix: none,
// The TOC
toc: true,
// two column layout
column: 1,
// The document's body
body
) = {
set document(title: title, author: author.name)
let main-font = ("Times New Roman", "Family Song")
set text(font: main-font, size: 12pt, lang: lang)
set heading(numbering: "1.1")
show heading: it => [
#block(it)
#v(0.4em)
]
set par(justify: true, leading: 0.8em)
show par: set block(spacing: 1.5em)
set page(
paper: papersize,
numbering: "1"
)
align(center, text(20pt)[*#title\ *])
if author.name != "" and author.email != "" {
align(center)[
#author.name \
#link("mailto:" + author.email) \
]
}
set list(indent: 1.2em)
set math.mat(delim: "[")
set math.vec(delim: "[")
set math.equation(numbering: "(1)")
show link: set text(fill: blue, style: "italic", weight: "bold")
// Configure citations and bibliography style
set bibliography(style: "ieee", title: if lang == "en" { [References] } else { [参考文献] })
// Table of Contents Style
show outline.entry.where(
level: 1,
): it => {
v(15pt, weak: true)
text(font:main-font,[
#strong(it.body)
#box(width: 1fr, repeat[])
#strong(it.page)
])}
show outline.entry.where(
level: 2,
): it => {
it.body
box(width: 1fr, repeat[.])
it.page}
show outline.entry.where(
level: 3,
): it => {
it.body
box(width: 1fr, repeat[.])
it.page}
// Display the table of contents.
if toc == true {
if lang == "zh"{
outline(title: [目录], indent: auto)
} else {
outline(title: [Table of Contents], indent: auto)
}
}
show: rest => columns(column, rest)
body
if bib != none {
set text(lang: "en")
bib
}
// Appendix
if appendix != none {
let appendix_title = if lang == "en" { [Appendix] } else { [附录] }
set heading(numbering: none)
[= Anhang]
set outline(depth: 2)
set heading(numbering: (..nums) => {
nums = nums.pos()
if nums.len() == 1 {
return appendix_title + " " + numbering("A.", ..nums)
} else if nums.len() == 2 {
return numbering("A.1.", ..nums)
} else {
return numbering("A.1.", ..nums)
}
})
show heading.where(level: 3): set heading(numbering: "A.1", outlined: false)
show heading.where(level: 2): set heading(numbering: "A.1", outlined: false)
counter(heading).update(0)
appendix
}
}
#let codecell(
doc,
// Vertical shift (space before cell)
vertical:1em
) = {
if vertical != none {
v(vertical)
}
block(
align(left,doc),
stroke: 0.7pt ,
fill: rgb("#eee"),
outset: 5pt,
radius: 5pt,
width: 95%,
breakable: true
)
}
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/babel/0.1.1/src/baffle.typ | typst | Apache License 2.0 | #import "@preview/mantys:0.1.4": *
#import "@preview/suiji:0.3.0"
#import "alphabets.typ": alphabets
#let punctuation = ("\`\-=~!@#$%^&*()_+\[\]\\\\;':\",./<>?‘’“”·¿¡؟،।॥⟨⟩‽⸘")
#let letter-counter = counter("letter-counter")
#let to-string(content) = {
if type(content) == "string" {
content
}
else if content.has("text") and type(content.text) == "string" {
content.text
}
else if content.has("children") {
content.children.map(to-string).join("")
}
else if content.has("body") {
to-string(content.body)
}
else if content == [ ] {
" "
}
}
#let baffle-letter(
input,
alphabet: "latin-bicameral",
case-sensitive: true,
punctuate: true,
punctuation: punctuation,
input-word-dividers: (" ",),
output-word-divider: " ",
seed: 0,
as-string: false
) = {
let letter = to-string(input)
if letter in input-word-dividers {
return output-word-divider
}
if letter in punctuation and punctuate {
return letter
}
let index = suiji.integers(
if as-string {
suiji.gen-rng(seed)
}
else {
suiji.gen-rng(letter-counter.get().first())
},
low: 0,
high: alphabet.at("lowercase").len()
).at(1)
if case-sensitive {
if letter == lower(letter) { // if the letter is lowercase
alphabet.at("lowercase").at(index)
}
else {
if not alphabet.keys().contains("uppercase") { // if `case-sensitive` is true but the alphabet doesn’t support letter case
alphabet.at("lowercase").at(index)
}
else {
alphabet.at("uppercase").at(index)
}
}
}
else {
return alphabet.at("lowercase").at(index)
}
}
/// #alert(color: gray)[
/// ⚠ A technical note: the default of #arg("punctuation") is #value("\"" + punctuation + "\"") and that of #arg("input-word-dividers") is #value((" ",)) (that is, an array containing only a space, `U+0020`); for reasons that have to do with #package[Mantys] or #package[Tidy] the default values are displayed wrongly in this document as #value("punctuation") and #value("(\" \",)") respectively.
/// ]
///
/// Replaces #arg("input") with random characters chosen from a given #arg("alphabet"). Note that depending on the #arg("alphabet") the output might be longer then the input (in case a single letter is replace by a digraph, for example).
///
/// - input (content):
/// The text to be redacted.
/// #example(```
/// #baffle[A _confidential_ text]
/// ```)
///
/// - alphabet (str,dict):
/// Either a slug (a string identifier) referring to the alphabet to be used for the output (options are listed in @alphabets) or a dictionary describing the alphabet, with the following fields:
/// / `lowercase` #strong(delta: -300)[_(required)_]: an array of strings (each representing one character), from which a random string is drawn for each character in the original text. If the target script is bicameral, use this field for lowercase letters and the `uppercase` field for uppercase ones; otherwise, use only this field.
/// / `uppercase` #strong(delta: -300)[_(optional)_]: an array of the same size as `lowercase`; if the input is bicameral, uppercase letters in the input are matched by uppercase letters from the alphabet.
/// / `font` #strong(delta: -300)[_(optional)_]: the font to typeset the output in.
/// #example(```
/// #baffle(alphabet: "sitelen-pona")[top secret]\
/// #baffle(alphabet: "greek")[top secret]\
/// #baffle(alphabet: (lowercase: ("👍", "👎")))[top secret]
/// ```)
///
/// - case-sensitive (bool):
/// Indicates whether to retain (#value(true)) case sensitivity or ignore (#value(false)) it, making everything lowercase.
/// #example(```
/// #baffle[Hello] vs. #baffle(case-sensitive: false)[Hello]
/// ```)
///
/// - punctuate (bool):
/// Indicates whether to retain (#value(true)) punctuation or ignore (#value(false)) it, treating punctuation marks like regular letters.
/// #example(```
/// #baffle[hello!] vs. #baffle(punctuate: false)[hello!]
/// ```)
///
/// - punctuation (str):
/// A string containing all characters considered a punctuation mark.
///
/// - input-word-dividers (array):
/// The set of characters considered word dividers in the input, to be replaced by #arg("output-word-divider") in the output.
/// #example(```
/// #baffle[hello·world] vs. #baffle(input-word-dividers: ("·",))[hello·world]
/// ```)
/// For writing systems that have spaces between words, leave as it is, but if your input text is Tibetan for example, `("\u{0f0b}", " ")` (_tsek_ and space) might be a better option, otherwise you’d get _very_ long words in the output.
///
/// - output-word-divider (str):
/// A string to which any character in #arg("input-word-dividers") is converted.
/// #example(```
/// #baffle(alphabet: "ugaritic")[два слова] vs. #baffle(alphabet: "ugaritic", output-word-divider: "𐎟")[два слова]
/// ```)
/// Keep `" "` if your target alphabet uses spaces; change to `"\u{200b}"` (zero-width space) if it doesn’t and there is no special word-dividing symbol such is in Ugaritic (zero-width space allows line breaking, whereas an empty string, `""`, does not).
///
/// - set-font (bool):
/// Indicates whether to typeset the output in the surrounding font (#value(false)) or the font suggested by #package[Babel] (#value(true)).
///
/// - seed (int,none):
/// If provided (not #value(none)), used for initialising the random number generator with that seed.
/// #example(```
/// #baffle(seed: 42)[hello] vs. #baffle(seed: 1312)[hello] vs. #baffle(seed: 42)[hello]
/// ```)
///
/// - as-string (bool):
/// Treat the input as a _string_ (as opposed to _content_).
/// This argument exists because of technical limitations of Typst (at least as of version 0.11.0), where some abilities cannot coexist:
/// #let X = redcell[❌]
/// #let V = grncell[⭕]
/// #table(
/// columns: (4fr, 1fr, 1fr),
/// align: (left, center, center),
/// table.header([Feature], [#value(false)], [#value(true)]),
/// table.hline(stroke: 0.05em),
/// [Formatting and complex text capabilities], V, X,
/// [Spaces between formatting groups (see #link("https://github.com/typst/typst/issues/5009")[this issue])], X, [N/A],
/// [Scripts with contextual letter forms], X, V,
/// [Counting of characters], redcell[codepoints], grncell[graphemes],
/// [Changes the table of contents; see @particular-limitations], X, V,
/// )
///
/// The choice between the two modes depends on what you need, and in some cases compromises cannot be avoided; for example, at the moment it’s not possible to apply #cmd("baffle") on a heterogeneous span of formatted Arabic or Devanāgarī text, unless you manually surround each individual homogeneous formatting group with a #cmd("baffle") command where #arg("as-string") is set to #value(true).
///
/// #example(```
/// #table(
/// columns: 3,
/// table.header([Feature], [#arg("as-string")`: `#value(false)], [#arg("as-string")`: `#value(true)]),
/// table.hline(stroke: 0.05em),
/// [Formatting and spaces],
/// ylwcell(baffle(output-word-divider:"@")[one two *three*]),
/// ylwcell(baffle(output-word-divider:"@", as-string: true)[one two *three*]),
/// [Contextual forms],
/// redcell(baffle(alphabet: "arabic")[hello]),
/// grncell(baffle(alphabet: "arabic", as-string: true)[hello]),
/// [Precomposed _â_ (`U+00E2`)],
/// grncell[#baffle(alphabet: "alchemy")[â] (1)],
/// grncell[#baffle(alphabet: "alchemy", as-string: true)[â] (1)],
/// [Combining _â_ (`U+0061 U+0302`)],
/// redcell[#baffle(alphabet: "alchemy")[â] (2)],
/// grncell[#baffle(alphabet: "alchemy", as-string: true)[â] (1)],
/// [Multi-codepoint\ emoji 🇦🇶 (`U+1f1E6 U+1f1F6`)],
/// redcell[#baffle(alphabet: "alchemy")[🇦🇶] (2)],
/// grncell[#baffle(alphabet: "alchemy", as-string: true)[🇦🇶] (1)],
/// )
/// ```)
///
/// -> content
#let baffle(
input,
alphabet: "latin-bicameral",
case-sensitive: true,
punctuate: true,
punctuation: punctuation,
input-word-dividers: (" ",),
output-word-divider: " ",
set-font: true,
seed: none,
as-string: false,
) = {
assert(
alphabet in alphabets.keys() or type(alphabet) != "string",
message: "The alphabet must be one of the following: [" + alphabets.keys().join(", ") + "]"
)
let target-alphabet = if type(alphabet) == "string" {alphabets.at(alphabet)}
else {alphabet}
set text(
font: target-alphabet.font,
fallback: false,
) if set-font and target-alphabet.keys().contains("font")
let baffle-letter-with-conf = baffle-letter.with(
alphabet: target-alphabet,
case-sensitive: case-sensitive,
punctuate: punctuate,
punctuation: punctuation,
input-word-dividers: input-word-dividers,
output-word-divider: output-word-divider,
)
if seed != none {
letter-counter.update(seed)
}
if as-string {
context {
let output = ""
let cnt = letter-counter.get().first()
for letter in to-string(input).clusters() {
output = output + baffle-letter-with-conf(letter, seed: seed+cnt, as-string: true)
cnt = cnt + 1
}
letter-counter.update(it => it+to-string(input).clusters().len())
output
}
}
else {
show regex("."): letter => {
context{
baffle-letter-with-conf(letter)
letter-counter.step()
}
}
input
}
}
/// A synonym of #cmd("baffle") with #arg("alphabet") set to `"redaction"`.
///
/// #example(```
/// This is #redact[confidential].
/// ```)
#let redact = baffle.with(alphabet: "redaction")
/// A synonym of #cmd("baffle") with #arg("alphabet") set to `"tippex"`.
///
/// #example(```
/// This is #tippex[confidential].
/// ```)
#let tippex = baffle.with(alphabet: "tippex")
|
https://github.com/SillyFreak/typst-packages-old | https://raw.githubusercontent.com/SillyFreak/typst-packages-old/main/README.md | markdown | MIT License | # Typst packages
A monorepo of my packages, in the beginning for sure mostly unpublished. Search the official [packages](https://typst.app/docs/packages/) page to find out if something has been published.
This repo contains a few package authoring facilities which are heavily inspired by and based on those of [CeTZ](https://github.com/johannes-wolf/cetz). There is a [package template](./template) utilizing these (based on the [example package](https://github.com/typst/packages/tree/main/packages/preview/example)), and this README will eventually document the most important aspects. Even more fundamental package authoring concepts are documented in the [official Typst package repo](https://github.com/typst/packages).
CeTZ resources (`Justfile` and `scripts/*`) are licensed under the Apache License 2.0, the rest under the MIT license. Packages contain their own licenses. Feel free to clone this repo or its contents to start your own typst package monorepo. You will want to pretty much immediately change the template's author and repository metadata.
## Package structure
Required for all packages in general are
- `typst.toml`: package metadata
- `README.md`
- `LICENSE`
- (some entry point typst file)
The packaging tool is a little more opinionated and requires
- `src/`: containing the entry point and other typst files
- `docs/`: containing the documentation, particularly `manual.typ` (using [`tidy`](https://github.com/Mc-Zen/tidy))
- `gallery/`: for examples (that can at the same time serve as manual tests)
Note that even docs and the gallery are _required_.
When creating a new package by copying the template, at least the following should be checked/adapted:
- `typst.toml`:
- change the package name and description
- change the path in the repository URL
- add keywords
- `typst.toml`, `LICENSE`: check if the license suits your needs
- `README.md`: change the title, add description
- `docs/manual.typ`:
- change the title, abstract, and introduction
- in the lines `#let scope = (template: lib)` and `label-prefix: "template.",` replace `template` with your package's name. These define how you can use the module in documentation comments and reference functions in the manual.
## Building packages
You will need bash and [just](https://just.systems/man/en/).
First, generate the manual and gallery PDFs:
```
just manual template
just gallery template
```
(Replace `template` by the directory name of the package you're building.)
You can install your package locally to use it or perform some final tests:
```
just install template
just install-preview template
```
If you use `install`, the package can be imported as `@local/<package>:<version>`; when using `install-preview`, it can be imported as `@preview/<package>:<version>` instead: **Note** that even after publishing, the version so installed takes precedence over the published version. **TODO** provide a script to uninstall preview packages.
Finally pack it up for publishing, e.g. into a local clone of the typst package registry:
```
just package template ../typst-package-registry/packages/preview
```
... and then create a pull request!
|
https://github.com/TheOnlyMrCat/tree-sitter-typst | https://raw.githubusercontent.com/TheOnlyMrCat/tree-sitter-typst/master/script.typ | typst | Apache License 2.0 | #let function_def(parameter: 2, boolean: false, ..positional) = {
if type(parameter) == "integer" {
let len = parameters
let default_parameters = ($p$, $q$, $r$, $s$, $t$)
parameters = ()
let i = 0
while i != len {
parameters.push(default_parameters.at(i))
i += 1
}
}
let parameter_values = parameters.map(param => rev)
let body_row_idx = 1
let conditions = body.pos()
let cells = ()
while true {
let seen_zero = false
for value in parameter_values {
if value {
cells.push(true_label)
} else {
cells.push(false_label)
}
}
for body in conditions {
if type(body.at(1)) == "function" {
if body.at(1)(..parameter_values) {
cells.push(true_label)
} else {
cells.push(false_label)
}
} else if rev {
cells.push($#conditions.at(conditions.len() - body_row_idx)$)
} else {
cells.push($#body.at(body_row_idx)$)
}
}
if parameter_values.all(value => value == not rev) {
break
}
let next_values = ()
for value in parameter_values.rev() {
if value == not rev and not seen_zero {
next_values.push(rev)
} else if value == rev and not seen_zero {
next_values.push(not rev)
seen_zero = true
} else {
next_values.push(value)
}
}
parameter_values = next_values.rev()
body_row_idx += 1
}
table(
..body.named(),
columns: parameters.len() + conditions.len(),
..parameters, ..conditions.map(arr => [#arr.at(0)]),
..cells
)
}
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/post_type_check/text_font4.typ | typst | Apache License 2.0 | #let fa = /* position after */ ("Test",)
#show raw: set text(font: fa)
|
https://github.com/mental2008/Resume | https://raw.githubusercontent.com/mental2008/Resume/main/Chinese/main.typ | typst | #import "@preview/octique:0.1.0": *
#let font = (
main: "IBM Plex Serif",
mono: "IBM Plex Mono",
cjk: "Noto Serif CJK SC",
)
// #show heading: set text(font: "Linux Biolinum")
#show link: underline
// Uncomment the following lines to adjust the size of text
// The recommend resume text size is from `10pt` to `12pt`
#set text(font: (font.main, font.cjk), size: 10pt, lang: "zh")
// Feel free to change the margin below to best fit your own CV
#set page(
margin: (x: 0.9cm, y: 1.3cm),
)
// For more customizable options, please refer to official reference: https://typst.app/docs/reference/
#set par(justify: true)
#show outline: it => {
show heading: set align(center)
it
}
#let chiline() = {v(-5pt); line(length: 100%); v(-6pt)}
// = <NAME> 杨凌云
#align(center, text(size: 20pt)[
*杨凌云*
])
#align(center, text(10pt)[
#octique-inline("mail") #link("mailto:<EMAIL>") | #octique-inline("globe") #link("https://www.lingyunyang.com")[lingyunyang.com] | #octique-inline("book") #link("https://paper.lingyunyang.com")[论文笔记] | #emoji.phone.receiver (+86) 135-0284-6103 | #octique-inline("location") 香港
])
== 教育背景
#chiline()
#link("https://hkust.edu.hk")[*香港科技大学*] #h(1fr) *香港* \
博士,计算机科学与工程系;博士生导师:*王威* #h(1fr) 2020 年 9 月 -- 至今 \
- 研究领域:集群管理、模型推理系统、资源调度
#link("https://www.scut.edu.cn/")[*华南理工大学*] #h(1fr) *广东省广州市* \
本科,计算机科学与技术全英创新班(GPA: 3.82/4) #h(1fr) 2016 年 9 月 -- 2020 年 7 月 \
- 国家奖学金、校级一等奖学金
== 研究项目
#chiline()
// I have a broad interest in resource management for large-scale data centers / AI infrastructure. Specifically, my research focuses on: (a) improving resource efficiency for AI/GPU clusters; (b) building efficient and low-cost AI model serving systems. \
我关注于大规模数据中心中的资源管理问题,尤其聚焦于 AI 基础设施。过去近 4 年,我在阿里巴巴开展了深入的产学研合作。我的研究工作主要包括两个方面:(一)提高 AI/GPU 集群的资源利用效率;(二)构建高效且低成本的 AI 模型推理系统。
#link("https://arxiv.org/abs/2407.02031")[*SwiftDiffusion:高效的文生图模型推理系统*] #h(1fr) (review, 2407.02031) \
#text(style: "italic", size: 7.4pt)[*Lingyun Yang*, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Wei Wang] \
- 构建了文生图推理系统 SwiftDiffusion,高效整合了 diffusion 模型和 add-on 模块(如 ControlNets、LoRAs)。
- 基于对 50w 条生产请求 trace 的特征研究,提出多个系统设计如:服务化 ControlNet、异步 LoRA 加载、latent 并行计算。
- 在保障图片质量的前提下,能够最多降低 *7.8×* 的推理时延、提高 *1.6×* 的吞吐量。
*Prism:针对深度学习推荐模型的 GPU 分离式推理系统* #h(1fr) (review) \
// *Prism: GPU-Disaggregated Serving for Deep Learning Recommendation Models at Scale* #h(1fr) (review) \
#text(style: "italic", size: 7.4pt)[*<NAME>*, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Wei Wang] \
- 针对在线推荐服务的推理场景,设计了一种 GPU-CPU 分离式异构架构,通过 RDMA 网络拉远部署计算图,消除资源不匹配;支持拓扑感知调度、基于资源消耗的切图策略。
- 在日常调度场景下可减少 *53%* CPU 碎片和 *27%* GPU 碎片;双 11 期间借调训练集群的 GPU 服务器最多可节省 *90%* GPU。
#link("https://www.usenix.org/conference/atc23/presentation/weng")[*FGD:大规模集群中 GPU 资源碎片的量化及调度策略优化*] #h(1fr) (ATC'23) \
#text(style: "italic", size: 7.4pt)[*Lingyun Yang*, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>] #h(1fr) #octique-inline("mark-github") #link("https://github.com/hkust-adsl/kubernetes-scheduler-simulator")[hkust-adsl/kubernetes-scheduler-simulator] \
- 量化分析了大规模 GPU 共享后集群中普遍存在的资源碎片问题,并提出了创新的碎片梯度下降调度算法。
- 相较于最优的调度策略可以显著减少 *49%* 的 GPU 碎片。
*GPU 共享:大规模 GPU 集群的资源共享和超卖*
- 实现大规模集群的 GPU 分时复用,以及不同优先级(如 latency-sensitive、best-effort)作业的混部,日均运行超过 *1w* 个共享 GPU 容器。
- 设计并实现了单机管控 agent 和全局 controller。Agent 周期性上报节点的资源使用情况,动态分配 GPU 资源给容器。中心侧的 Controller 管理集群账本,计算可超卖资源量,为集群调度器提供调度决策指引。
#link("https://dl.acm.org/doi/10.1145/3472883.3486987")[*Morphling:针对通用 AI 推理服务的自动化参数配置框架*] #h(1fr) (SoCC'21) \
#text(style: "italic", size: 7.4pt)[*<NAME>*, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>hang] #h(1fr) #octique-inline("mark-github") #link("https://github.com/kubedl-io/morphling")[kubedl-io/morphling]
- 作为阿里巴巴开源的 #link("https://github.com/kubedl-io/kubedl")[KubeDL] 其中的一个独立子项目,成为云原生计算基金会(CNCF)#link("https://landscape.cncf.io/?item=provisioning--automation-configuration--kubedl")[sandbox] 项目。
- 结合元学习和贝叶斯优化算法,可快速搜索到最优的资源配置(如 CPU 核数、GPU 显存、GPU 时间片、GPU 卡型)和运行时参数(如批处理大小)。
== 工作经验
#chiline()
*阿里巴巴集团* #h(1fr) *浙江省杭州市* \
_研究实习生_,集群管理团队;主管:*余英豪* #h(1fr) 2020 年 12 月 -- 至今 \
- 完成多个研究和工程项目,包括 Morphling、GPU 共享、FGD、Prism、SwiftDiffusion(具体如上所述)。
*微软亚洲研究院* #h(1fr) *北京市* \
_研究实习生_,创新工程组 #h(1fr) 2019 年 7 月 -- 2020 年 6 月 \
- 优化模型结构以提高人脸识别算法的鲁棒性;获“明日之星”杰出实习生奖。
== 技术栈
#chiline()
- *编程语言:*Golang, C++, Python, JavaScript, asynchronous, multithread, multiprocess, distributed, RDMA \
- *机器学习:* PyTorch, TensorFlow, Numpy, Matplotlib, HuggingFace \
- *全栈开发:* Web Frontend, Backend, SQL, Grafana, Docker, Kubernetes, Git, CI/CD \
|
|
https://github.com/noahjutz/AD | https://raw.githubusercontent.com/noahjutz/AD/main/notizen/algorithmen/euclid.typ | typst | #import "@preview/cetz:0.2.2"
#let a = 9
#let b = 2
#let n = 5
#cetz.canvas(length: 10%, {
import cetz.draw: *
import cetz.vector
import cetz.coordinate
set-style(stroke: (thickness: 1pt))
line(
(),
(rel: (a, 0)),
name: "a_0"
)
line(
(rel: (0, -.5), to: "a_0.start"),
(rel: (b, 0)),
name: "b_0"
)
line(
"b_0.end",
("b_0.end", "-|", "a_0.end"),
stroke: (dash: "dashed"),
name: "d_0"
)
content("a_0.start", anchor: "east")[$a_0$]
content("b_0.start", anchor: "east")[$b_0$]
content("d_0.end", anchor: "west")[$d_0$]
for i in range(n) {
let a_prev = "a_" + str(i)
let a = "a_" + str(i + 1)
let b_prev = "b_" + str(i)
let b = "b_" + str(i + 1)
let d_prev = "d_" + str(i)
let d = "d_" + str(i + 1)
get-ctx(ctx => {
let (ctx, b_start, b_end, d_start, d_end) = cetz.coordinate.resolve(ctx,
b_prev + ".start",
b_prev + ".end",
d_prev + ".start",
d_prev + ".end"
)
let len_b_prev = cetz.vector.dist(b_start, b_end)
let len_d_prev = cetz.vector.dist(d_start, d_end)
let len_a = calc.max(len_b_prev, len_d_prev)
let len_b = calc.min(len_b_prev, len_d_prev)
line(
(rel: (0, -1.5), to: a_prev + ".start"),
(rel: (len_a, 0)),
name: a
)
line(
(rel: (0, -2), to: a_prev + ".start"),
(rel: (len_b, 0)),
name: b
)
line(
"b_" + str(i + 1) + ".end",
((), "-|", a + ".end"),
stroke: (dash: "dashed"),
name: d
)
group({
let bp = b_prev + ".start"
let dp = d_prev + ".end"
let is_b_gr = len_b_prev > len_d_prev
let greater = if is_b_gr {bp} else {dp}
let lesser = if is_b_gr {dp} else {bp}
set-style(mark: (end: "straight"), stroke: (paint: gray))
line(greater, a + ".mid")
line(lesser, b + ".mid")
})
content(a + ".start", anchor: "east")[$a_#(i + 1)$]
content(b + ".start", anchor: "east")[$b_#(i + 1)$]
if i + 1 < n {
content(d + ".end", anchor: "west")[$d_#(i + 1)$]
}
})
}
}) |
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/lib/diff.typ | typst | MIT License | // #let values(dict) = for (k, v) in dict { ((k, v), ) }
#let diffarray(a, b) = {
assert(type(a) == array, message: "expected `a` to have type 'array', got " + type(a))
assert(type(b) == array, message: "expected `b` to have type 'array', got " + type(b))
assert(a.len() == b.len(), message: "a.len() != b.len() => " + str(a.len()) + " != " + str(b.len()))
a.zip(b).map(pair => {
let x = pair.at(0)
let y = pair.at(1)
assert(type(x) == type(y))
if type(x) == array {
diffarray(x, y)
} else if type(x) == dictionary {
diffdict(x, y)
} else {
x == y
}
})
}
// #diffarray((1, 2, (3, 4)), (3, 2, (3, 5)))
#let diffdict(a, b) = {
assert(type(a) == dictionary, message: "expected `a` to have type 'dictionary', got " + type(a))
assert(type(b) == dictionary, message: "expected `b` to have type 'dictionary', got " + type(b))
let diff = (:)
for (k, va) in a {
assert(k in b, message: "diffdict only works if both dicts contains, the same keys :(")
let vb = b.at(k)
assert(type(va) == type(vb))
let d = if type(va) == array {
vb.zip(va).map(pair => pair.at(0) != pair.at(1))
} else if type(vb) == dictionary {
diffdict(va, vb)
} else {
va != vb
}
diff.insert(k, d)
}
diff
}
// #let leafflatten(dict) = {
// assert(type(dict) == dictionary, message: "expected `dict` to have type 'dictionary', got " + type(dict))
//
// dict
// .pairs()
// .fold((:), (acc, pair) => {
// let k = pair.at(0)
// let v = pair.at(1)
//
// if type(v) == dictionary {
// acc + leafflatten(v)
// } else {
// acc.insert(k, v)
// acc
// }
// })
// }
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/058%20-%20Duskmourn%3A%20House%20of%20Horror/001_Episode%201%3A%20Don't%20Go%20Past%20the%20Old%20Dark%20House.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 1: Don't Go Past the Old Dark House",
set_name: "Duskmourn: House of Horror",
story_date: datetime(day: 19, month: 08, year: 2024),
author: "<NAME>",
doc
)
#emph[Many years ago] …
Thin clouds hung hazy in the sky, blocking the light from both the greater and lesser suns, turning the street below into a twilit landscape of shifting shadows and uncertain dangers. A wind brushed along the walkways, a skirl of dry autumn leaves spinning orange and brown within its clutches. Despite the gloom, it was midday; most of the houses were empty, their inhabitants off at work or school, leaving the street to rest in uneasy slumber. The gray weight of winter was looming, but for now it was brittle, changeable fall, shifting between clement and chilling in an instant.
For the most part, the homes of this residential neighborhood were unremarkable, single-family structures, standing alone on their little plots of land, isolated in the presence of community. Their yards were tidy, their windows clean—a place for people who wanted to disappear into their surroundings, absorbed by their community. Three colors appeared over and over again on the homes' exteriors—beige, a pleasant sort of neutral green, and a blueish slate gray. Everything was clearly planned, designed for the comfort and conformity of the residents.
Everything, except the old house on the corner where the neighborhood drew nearest to the scrubby woods. This was a towering construct of ornamental flourishes and architectural oddities. Gargoyles peeped from the rafters, and a widow's walk circled the cupola on the roof, which stood slightly askew like a reminder that entropy would come to everyone, in time. The windows were covered in a film of dirt, like cataracts shrouding the house's eyes, and the garden was a riot of weeds and untrimmed hedges. No one lived there. No one had lived there for quite some time.
If the black-shingled roof and gray brick façade of the house hadn't been so out of place when set against their surroundings, it might have been possible to overlook the small sign that had been set up in the yard. It was a plain white piece of wood, with the word "SOLD" scribed across it in meticulous, red-painted letters.
A modern-looking carriage pulled up in front of the house, conspicuous in its lack of draft animals to pull it. Anyone who could afford one of the new, internally powered vehicles would surely fit in with this neighborhood … if only they hadn't stopped in front of the neighborhood's greatest shame.
The carriage doors opened, and a small human family emerged into the wan afternoon light, clutching suitcases in their hands. As they stepped onto the walkway, the curtains in the front window fluttered, like a breeze had managed to work its way into the house, and the door swung open of its own accord, as if to welcome them home. The three shifted all but involuntarily toward each other, briefly unsettled for reasons none of them could articulate.
"The movers must have left it unlocked," said the man, with a note of seemingly sincere joviality in his voice. "Come along, now. It's not going to get any warmer out here."
He was the first through the gate into the yard, and the first up the porch steps, his wife following behind with a little grimace of distaste at the state of the flower beds. She would have that set right in short order, her expression said. Both of them were dressed to fit their new neighborhood, sedate clothing in respectable cuts and colors. Their teenage daughter, who walked slowly after them as she took in her surroundings, was better suited to the house in her elaborate, nearly antique clothing and cobwebby makeup that spread out around her eyes like an intricate stain. Her lips seemed set in a permanent downward curve as she followed her parents into the foyer, cluttered with trunks and boxes holding their worldly possessions.
She put her suitcase down at the bottom of the stairs and ran her hand along the polished oak banister, checking her fingers afterward for dust. They came away covered in glittering dust, like the scales from a moth's wings, and she rubbed them together before wiping her hand on her skirt and continuing deeper into the house, leaving her parents behind as she explored.
The doors she passed were closed, until she reached the basement. That door stood ajar, revealing a thin slice of stairs descending into the darkness. She paused there, as if she had seen something.
"Marina!" called her mother. "Come choose a room, we need to figure out where the furniture's going before the movers come back."
"Coming, Mom," she called back, reluctantly pulling her attention from the open door. Whatever was down there had waited this long. It could wait for her for just a little longer.
She didn't know what it was, but she already knew that it was patient. It could wait.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[Now] …
The sky was never truly dark on Kamigawa, not even above the clouds, not when Otawara was nearby in all its polished glory. Every speck of light from the moon above and the cities below reflected off the glorious Soratami stronghold, transforming glass and chrome into a soaring beacon. Starlight refracted from crystal sculptures and glassine spires, magnified into impossible beauty. This was the pinnacle of the moonfolk's art, and even the devastation wreaked by Realmbreaker hadn't been enough to dim its light. Repairs would be ongoing for years, if not decades, and yet still the city shone.
A shadow moved through the brightly lit streets, somehow avoiding the drones that swept the city in constant arcs. Phyrexia was gone, but the always security-oriented Soratami had yet to stand down from their increased measures. Pressing himself flat against an alley wall, <NAME> watched a drone soar by and thought, not for the first time, that#emph[ this would all have been so much easier if the artifacts recovered after the war had been stored in the Imperial Palace, instead of in the skies.]
But done was done, and he couldn't change it. All that mattered now was the mission and seeing it to its proper conclusion.
The ancient palace of Oboro had sustained some damage during the invasion. While it remained closed to outsiders, many of its treasures had been moved temporarily to a heavily guarded stronghold. Guards stood outside while others patrolled the halls and roof at regular intervals, attention turned outward, waiting for signs of danger. Kaito slipped past them one by one, clinging to the shadows and moving with a silence the moon itself might envy.
At last, he reached a secluded nook from which he could see a barred, guarded door reflected in the polished metal of a flight suit damaged in the invasion that was set up as a display. Breath silent and steady, he crouched there, waiting as the minutes ticked down. Finally, a moonfolk guard approached down the hall, waving the two who flanked the door away. The changing of the guard: it was the best time to move, almost always, for little irregularities could be overlooked in the face of choreographed chaos.
Sliding into the open, Kaito moved behind the guard and hit him on the back of the head with the pommel of his sword. The guard stiffened, then went limp. Kaito caught him before he could fall, lowering him gently to the floor. On Kaito's shoulder, Himoto adjusted her position, unhappy with the assault on a citizen of Kamigawa, even as she understood the need.
Kaito checked the guard's pulse, verifying that he had done no more damage than intended, then turned his attention to the door, extending a seeking spear of telekinetic energy. It slid into the locking mechanism, where he twisted and pulled until the lock clicked softly, and the perfectly weighted door swung far enough open for Kaito to ease his way inside.
The room beyond was a treasure trove of priceless Imperial treasures entrusted to the moonfolk, prototype technologies that had been judged too dangerous to remain accessible, riches beyond all measure. They would be moved back to Oboro and impossible to reach without giving grave insult to the moonfolk by the end of the next moon cycle; he had to act now.
Scanning the shelves as he moved, Kaito stepped into the room, eyes fixed on a lit pedestal at the very back, almost in a corner. An iron scroll rested there, seemingly unremarkable compared to the wonders around it. Attention fixed on the scroll, he moved quickly toward it, one hand reaching out to claim his#linebreak prize—
Only to stop a foot from the pedestal, eyes catching on the final layer of security. A spider kami hung above the scroll in a delicate spirit web, which extended to wrap around the scroll itself. Any attempt to touch it would break the web and attract unwanted attention.
"Himoto," he breathed, voice barely more than a whisper in the still air, "can you unweave this web?"
She nodded and began to inch along his outstretched arm toward the web, intending to free the scroll. She was almost there when a sound broke the silence. A throat being cleared, immediately behind him.
Kaito spun, sword already assembled and in hand, only to find his blade caught against another. The white-haired woman standing behind him offered a slight smile, her sword still lifted to prevent him from completing a stroke. A gold and white dog stood at her heel, tail wagging, and Kaito almost smiled to see Yoshimaru, finally joyous again in the company of his beloved master.
"Hello, <NAME>," she said. "You're as good as you ever were. But when it comes to bladework, I'm still better."
Kaito stared. Asking the Emperor where she had been was a fool's game, as he knew from their most recent encounters; in the absence of her spark, she was finally free to truly learn the plane that was her birthright, no longer hurled across the Blind Eternities without choice or control. As such, she had asked Light-Paws to maintain her regency for now, while she walked among the people she was meant to lead until she understood them better. So he didn't ask. Instead, he took a deep breath, straightened, and lowered his sword.
"I—this isn't Imperial business," he blurted. "This was Tamiyo's. It should never have been confiscated."
"I'm not here to stop you," she said. "I came because I need your help. Nashi's in trouble."
Kaito froze. "And you think mid-robbery is the time to tell me? You need to work on your approach."
The Wanderer smiled. "Finish your business here quickly. I'll meet you on the palace roof." She took a step back, away from him. She was #emph[always] moving away from him. "I'll see you soon."
She turned to leave the room, leaving Kaito staring after her. He returned his attention to the scroll as Himoto finished her journey to the web and began pulling it apart, piece by careful piece.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The wind was cool as it blew across the palace rooftops, scented with cherry blossoms. The occasional pink petal danced on the breeze. Kaito stepped between them almost without thinking about it, the iron scroll a heavy weight in his pouch as he moved across the polished shingles. They used to play here when they were children, a boy and his companion, when they knew they would be subject and emperor one day, in the future, which was as far off as the moon.
The moon wasn't so far away now, and the future had long since arrived. Kaito hopped down onto one of the low, semi-hidden gardens that studded the palace roof, landing silently on the mossy stone ground. The Emperor was there, sitting under one of the cherry trees with one end of a length of silk rope in her hand. Yoshimaru worried at the other end, growling playfully.
She glanced up as Kaito approached. "You were successful?"
"I was." Kaito patted his pouch. "Genku will have his lost wife's scroll back in the library come morning. You say Nashi is in trouble?"
"We don't know for sure, but it seems very likely," said the Emperor. "He's missing. I came looking for you because we need someone who can still walk the planes unassisted to assemble a team that can retrieve him."
Kaito frowned. "The last team I was on didn't do so well. You remember."
"I do," she agreed. "But this is different. This isn't Phyrexia. And you did well enough that we're both still here."
Kaito glanced away. "Not everyone is," he said.
She had no answer to that.
Yoshimaru pulled the rope from her hands and whipped it back and forth, breaking the neck of whatever small opponent he imagined. This accomplished, he dropped the rope in front of Kaito and looked at him with meltingly hopeful eyes.
Kaito sighed and picked up one end of the rope, beginning to play tug of war with the dog.
"How long has Nashi been missing?" he asked.
"Three months."
Kaito stared at the Emperor. "That's not—I would have noticed! Or Genku would have told me!"
"I know we both feel responsible for Nashi," she said. "And at the same time, he blames us both for his mother's death, to varying degrees, and I think we both blame ourselves as well. It's been easy to keep away, thinking that was what he wanted. When was the last time you went to see him? Or spoke to Genku?"
Kaito paused. It had been … "Months," he admitted. "I've been focused on recovering his mother's scrolls. They should never have been taken, and I hoped that having them might ease his heart a fraction, even if it could never be enough."
The Wanderer nodded. "You see? We were all grieving in our own ways, and he slipped away like ripples in the water. Three months ago, he told some of the other Reckoners that the scroll containing his mother's living memory had vanished. He was distraught."
"He should have come to me!"
"He was a heartbroken child, and when he started hearing her voice calling him to come and find her, he answered it. He followed her call to a door covered in strange carvings, one that had no place in Kamigawa. He was clever enough to send in a series of drones through it before attempting to enter on his own, and they transmitted footage from the other side before breaking, one by one. That was when he took a few of his closest friends and traveled through." The Wandered paused. "They never came back out. Worse, the door vanished as soon as Nashi passed through. We have drone recordings of the area. I reviewed them and went to where the door should have been, but there was nothing, only a whisper on the edge of my planar awareness, like something terrible had brushed against our world in that spot.
"No one on Kamigawa could help me, so I was forced to look farther afield. I traveled the Omenpaths seeking the echo of that door, and I found it on Ravnica, being guarded by Niv-Mizzet."
"So, he controls access to this door?"
"Yes."
"And do you trust him?"
"No." The Emperor's smile was brief, and bitter. "I believe he wants to learn the secrets of that door far more than he wants to bring Nashi home. We're all just game pieces to him, things he can summon and sacrifice at will. But I believe he has the resources we need to do this, and it must be done."
Kaito sighed, weary to his bones. "I'll take the scroll to Genku tonight and ask him if he knows anything. Then I'll gather our team, and meet you …" He paused. "Where should I meet you?"
"There's a stable Omenpath near Eiganjo that will take me to Ravnica's Tenth District. Niv-Mizzet is waiting for us there." She reached over, taking the end of the rope from his hand. "Do you know where you're going?"
Kaito nodded without hesitation. "I have a good idea where to start," he said.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
<NAME>, elf prince of Kaldheim, stood shirtless in the snow, feet set in a warrior's stance, a broad smile on his face as he stared down the massive wolf in front of him. It was alone, with no pack to come to its aid. If it had been part of a pack, it wouldn't have been preying on the village for the past several weeks, and he wouldn't have been called to glorious battle.
The wolf growled. Tyvar laughed.
"Well, beast?" he called. "Come at me!"
The wolf, which was easily twice his size, leapt, and Tyvar swung a mighty left hook at the soft underside of its jaw, the power of his punch enhanced by his body becoming living stone midway through the motion. The wolf was knocked backward into the snow, landing without a sound. Tyvar scowled, body bleeding back into flesh.
"Get up," he said. "This is only a hero's battle if you last more than one hit."
"I have to admit, you playing dogcatcher is #emph[not] what I expected," said a voice behind him, welcome and familiar.
Tyvar turned, beaming once again. "Kaito!" he cried, jubilant to the last. "What brings you to Kaldheim, my friend? Seeking grand adventure and glorious danger?"
"Not so much," said Kaito. "I'm not really in the market for danger, glorious or otherwise. I was hoping I could convince you to come and help me with a little problem …"
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Some hours later, Tyvar and Kaito sat inside the feast hall, platters of meat and cheese before them, tankards of hot cider close to hand. The villagers had already skinned the great wolf and hauled its body away; the sheep it had eaten would have clothed many of them for a season. Now, it would serve in place of the missing members of the flock and warm the people through the winter snow.
Tyvar nodded with deep solemnity at Kaito's words, brow furrowed in concentration. "So, you want me to travel via Omenpath to the city of Ravnica, there to pass through a mysterious door into possible doom?"
"That's about the sum of it, yeah."
"When do we leave?"
"I'm supposed to put together a team," said Kaito. "I have stealth handled. The Emperor is planning to accompany us, and she can handle navigation. We're both fair fighters, but you're a one-man wrecking crew. Niv-Mizzet is all but certain to want one of his own people to accompany us; that gives us a scientist. The rest of our former strike team is …"
"Friend Kaya would come, if we knew where to find her, but I fear she may be done with adventures for the moment," said Tyvar. He didn't mention the others. There wasn't any point. Picking up his tankard, he took a swig of cider and asked in a speculative tone, "What needs are yet unfulfilled by the gifts among us?"
"We could use someone with defensive skills," said Kaito. "Someone who's better at shielding and distance engagements. I can't be our only ranged fighter."
Tyvar looked at him gravely. "You anticipate much trouble, then?"
"Better safe than sorry."
To his surprise, Tyvar roared with laughter. "Wonderful!" he said. "More trouble is more drama in the telling! I think I may have just the hero that you need—and best of all, they're currently on Kaldheim, so you won't have to go far."
"You vouch for them?"
"I do. And between you and I, they need to get out more. A trip to a terrifying new place filled with unknown dangers may be precisely the solution to their doldrums."
"Is this someone I've met?"
"I don't believe so." Tyvar's mouth twisted briefly. "<NAME>. They were a Planeswalker, before …"
Before whatever had changed. Before so many sparks blew out like candles in a stiff wind, leaving their former bearers fumbling without a light to see by. Before Phyrexia, before the sylex …
Before they failed.
"I'm sure they'll be a great asset," said Kaito. "Where can we find them?"
Tyvar gestured toward a particularly raucous corner of the feast hall, where a large cluster of local hunters had formed. They had three rough-hewn wooden targets propped against the wall and were alternating throwing small hand axes at their marks, missing as often as not and chopping chunks out of the feast hall's support beams. As Kaito watched, a particularly burly hunter with his beard pulled into three neat, oiled braids stepped forward, weighing an axe in his hand, and tossed it almost nonchalantly toward the smallest target.
It struck dead center, and the other hunters cheered.
"Niko?" asked Kaito.
"No," said Tyvar, laughing. "That's Trygve. His skill with throwing axes is as impressive as his skill with a bow is not. He's a terrible hunter, but a fine sportsman." He nodded at a slimmer figure seated at one of the tables near the axe-throwers. Half their head had been shaved; the hair that remained was long, straight, and dark at the root, paling to silver at the end. As the contestants roared at Trygve's throw, the figure stood, moving smoothly through the crowd, and picked up a pair of axes, one in either hand.
They exchanged a few brief words with someone Kaito assumed was running the game, then tossed both axes at the target, one right after the other. The first struck the handle of Trygve's axe, splitting it lengthwise. The second repeated the trick, splitting the stranger's axe right down the middle.
Tyvar laughed and waved the figure over, receiving a raised finger signaling him to wait. Several purses changed hands, and then the stranger was moving toward their table, looking unmoved by their own impressive victory.
"Kaito, my friend, this is my friend <NAME>," said Tyvar, once the stranger was close enough. "They're originally from Theros, and they're about three nights of gameplay from getting us both thrown out of this feasting hall."
"Only because you insist on wading in when the locals get tired of losing," said Niko. "I can handle my own fights."
"Yes, but when you keep starting them for me, all tempting and enthusiastic, I can't resist joining in." Tyvar beamed at Niko, who scowled at him in response.
"Ah," said Kaito, who didn't want to get stuck in the middle of a brawl, however much Tyvar might have enjoyed it. "You seem to have quite the aim."
"I never miss." Niko pulled what looked like a gleaming shard of magic out of the air, holding it above their palm. "The invasion didn't take that away from me, at least."
"Friend Niko, like myself, no longer feels the Blind Eternities in their bones," said Tyvar.
Niko's scowl deepened. "And I suppose you do?" they asked Kaito, voice sharp.
"I do," said Kaito. "I, and someone I know well, need your help, on Ravnica. Will you come?"
"We found the Omenpath that will carry us there just last week," said Tyvar, joyfully. "Come, Niko! Will you leave these unworthy opponents and follow me into certain danger?"
Niko looked at the shard in their hand, then shrugged and flung it underhand at the axe-throwers' largest target. It embedded itself squarely in the center, gleaming like a sliver of starlight.
"I may as well," said Niko. "Can't let the Planeswalkers have all the fun."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Kaito stepped out of forever onto the streets of Ravnica, looking up at the bruise-purple sky, and wondered—not for the first time—why he retained his spark when so many others didn't. Tyvar was untroubled, and the Emperor relieved, but Niko was clearly angry, bitter on a level Kaito couldn't fully comprehend, having never lost such an essential piece of himself. The former Planeswalker from Theros resented being made less than they had been, even if their fascinating shard magic remained intact, even if the Omenpaths meant they weren't trapped on any one plane. They had trusted in the Blind Eternities, and they had been betrayed.
Kaito couldn't entirely blame them, even as he slowly turned, looking for someone he could ask to take him to this "living Guildpact," whatever that was. He paused at the sight of a slender female human barely taller than Nashi standing at the entrance of a nearby alley, fiddling with a small geometric device with a crystal front that oscillated through colors, like it was somehow reading the local energy levels. Kaito stopped a few feet away from her, frowning.
After a moment, she glanced up, and jumped. "Oh—oh! Hello! You must be Kaito! We've been waiting for you!"
Kaito nodded. "I must be. You are …?"
"Oh! Um." She closed her device, collapsing it into a disk and sliding it into her pocket before offering Kaito her hand. "I'm Zimone. I'm a student? Quandrix College, at Strixhaven University. I'm here to work with the Izzet League on my graduate thesis on theoretical extraplanar spaces. The dragon asked me to wait for you."
"Why?"
"Oh. We've been expecting you." Zimone paused, adjusting her glasses. She seemed to realize that wasn't enough information, then continued: "I'm supposed to take you to him."
"We'll have to wait for my companions. They're traveling via Omenpath."
Zimone looked at him politely, clearly not understanding why that was a problem, and Kaito realized she lacked the certain haunted cast to her eyes that he associated with former Planeswalkers. For her, the advent of the Omenpaths had been the beginning of a bright new era, not the ending of a beloved older one. Together, they turned to watch the square.
Time passed. Eventually, Tyvar came bounding out of another alley, enthusiasm undimmed as ever.
"Why isn't that man wearing a shirt?" asked Zimone.
Kaito just laughed.
Tyvar hurried to join them. "Well met, fond companion! And new face." He turned to Zimone, bowing slightly. "To whom do I speak?"
"<NAME>," she said, sounding more flustered than flattered.
Niko emerged from the same alley, walking like they were seasick and on the verge of keeling over. Slightly greenish with inexplicable nausea, they moved to join the trio.
"Niko, this is Zimone, of Strixhaven," said Kaito. "Zimone, this is Niko. They're originally from Theros, but presently hail from Kaldheim."
"A pleasure," said Niko.
Zimone clapped her hands. "All right, follow me," she said, and scurried off down the alley. The others exchanged a look, shrugged, and followed her.
The alley ended in a small courtyard, dominated by a massive red dragon lounging on the far side like a cat, massive wings furled against his sides. Zimone led them straight to him.
"Mr. Guildpact, I found the search team," she said, as they drew closer.
"So, you did," said the dragon, rising. "Excellently done, <NAME>. <NAME>, I presume."
"Yes, sir," said Kaito, bowing. "These are my selections for the retrieval team, <NAME> and <NAME>."
Niv-Mizzet nodded, massive head generating a brief wind as it moved. "Very well. Follow me."
A line of gleaming white wards appeared ahead of them. Kaito paused. "Azorius work," said Niv-Mizzet. "They'll let us pass."
"Wonderful," said Tyvar, though it wasn't clear he understood what that meant. Then: "Are you to be our host? I have always wished to speak in more depth with a dragon."
"If we have the time, I will gladly speak with you," said Niv-Mizzet dryly. "You're not the first ones here, of course. The Wanderer returned yesterday, following another of your companions."
Kaito blinked. "Our companions?" he asked.
"Yes. A young girl, younger than Zimone here, who calls herself Aminatou. She said you would need her help to succeed."
Niko stopped dead, staring. One by one, the others drifted to a halt and turned to look at them. "Niko?" asked Tyvar.
"Aminatou?" asked Niko.
Niv-Mizzet nodded. "Yes."
"The child who spins cocoons of fate."
Niv-Mizzet blew a thin plume of smoke, looking thoughtful. "That would fit with what she's been seen to do so far, so I believe yes."
"I don't believe in fate."
"But fate believes in you," said Tyvar, clapping Niko on the shoulder. "Come, let us disbelieve this stranger to her face."
They walked on. Kaito frowned again as he spotted a sign on the wall, marked with the sigil of the Boros Legion, warning of necromantic energy in the area and ordering an evacuation. Niv-Mizzet saw him looking and blew another puff of smoke.
"There's no such contamination, of course," he said. "We just needed to clear the area to conduct our research."
They stepped across the wards, which warmed their skins for a moment before letting them pass harmlessly on. Niv-Mizzet continued without slowing until a woman in clothing devoid of guild insignia appeared down a side street, waving one arm for his attention.
"That will be <NAME>," he said. "She and her employer have been handling the arrangement of the researchers who will be remaining here, on Ravnica, while you undertake your work." He led them toward the woman, until they were close enough for her to speak.
"You're late," she said bluntly, with none of the respect Kaito would have expected her to extend to a massive flying predator.
"I'm precisely on time, now that our incursion team is here," he protested, with a growl of warning.
Etrata shrugged.
Niv-Mizzet blew a plume of smoke. "You know, I had hoped your level of respect would rub off on Proft, rather than the other way around."
The group continued down the side street she had emerged from, reaching another courtyard. This one was larger than the first, and more secluded. Researchers in protective gear, marked by the sigils of the Izzet and Simic, bustled to and fro, aiming incomprehensible devices at an unassuming door. A tent had been set up nearby, where the Wanderer sat with Proft, Yoshimaru, and an unfamiliar young girl Kaito assumed to be Aminatou. It was strange to see an actual child here, but he'd seen plenty of strange things before.
The Wanderer stood as they approached, leaving the tent to join them. "Is it time?" she asked.
"Yes," said Niv-Mizzet. "Come along."
Aminatou trailed after her, Yoshimaru close behind, and Niv-Mizzet led the group through the crowd of researchers to the door. Signs surrounded it, declaring "DANGER" and "KEEP OUT" in dozens of languages, only some of which Kaito recognized. Niv-Mizzet gestured grandly to the door. "This is why we're here," he said with sonorous importance.
Tyvar frowned. "This?" he asked. "But it's just a door."
Indeed, there was nothing visibly special about the door, which was made of stained cherry and decorated with an intricate design of carved moths and branches. It looked perfectly innocuous, not radiating hostile magic or anything else of the sort.
And yet, Aminatou gasped and recoiled as her eyes locked on the door. For a moment, her fear and revulsion made her look younger than her actual age, like a terrified toddler who had no business anywhere near this situation. The Wanderer patted her reassuringly on the shoulder, and Aminatou drew back against her, Yoshimaru standing in front of her as if to defend her from the door.
"It hears us," whispered Aminatou. "Mind your words, or it will know our plans."
#emph[That was an unsettling idea,] thought Kaito.
"Come with me," said Niv-Mizzet. He led them back a bit, to the tent. It was a tight squeeze with the dragon among them, but they managed, cramming themselves into an uncomfortable closeness.
"Is it an Omenpath?" asked Niko.
A man in a long brown coat, who had joined Etrata during their return from the door, scoffed. "It has none of the hallmarks of an Omenpath. If it is one, it's entirely unique. We've never seen anything like it."
"We have recordings from inside, Mr. Proft," said Zimone, before Niko could react to the man's tone. "Nashi's drones sent the footage back before they failed. It's a house."
"A house?" asked Kaito.
She nodded. "Just a house, perfectly normal, if in need of a good cleaning service. A little run-down, possibly abandoned, and possessed of some very strange angles. I think space is distorted inside, somehow." She paused, then beamed. "I can't wait to get a closer look."
Kaito met Tyvar's eyes and nodded. This was the researcher he had predicted Niv-Mizzet would embed among them. "All right, <NAME>," he said. "I'm not entirely comfortable with Aminatou joining us, however, given her age."
"I can't," said Aminatou. "What waits for you on the other side of that door would be infinitely more dangerous if it managed to get its hands on me. No. I stay here. This is where you need me. This is where I help you."
"How?" asked Niko.
Aminatou looked at them calmly. "I'm sorry, destiny-called; I understand why you hate me. But my magic and the magic of the house deflect each other, like water deflecting oil. Because of this, I can send you through the door with fateshifters." She paused.
"What are those?" asked Zimone.
Aminatou shrugged. "Tokens, really. Bursts of my power in physical form. They can be used to evade horrifying ends."
Niko straightened, anger coloring their features. "What?" they demanded. "You can do that? Are our lives only game pieces to you?"
Their anger seemed to jump to Tyvar, although not as brightly: "If you have the power to show us these answers, why did you let us march against Phyrexia without them? Why did we lose so many of our own in a fight you could have spared us?"
"Because that's not how my power works," said Aminatou. "It was hard enough to make these. When you make a choice that would lead to your certain death, everyone nearby who holds a token will see the outcome, feel like it's real, and then snap back to the moment before you made the decision, giving you a chance to make it again. But the vision is short—no more than a minute—and only works once for any single person. Even before my spark left me, my power wasn't without limits. I won't force you to take them. I don't take people's choices away like that. But, if you refuse my aid, at least one of you won't come back. That's certain."
The group exchanged looks. Finally, the Wanderer stepped forward.
"We are grateful for your help," she said. "Only the foolish refuse aid freely given."
"Then take these," said Aminatou. She reached into a pouch at her waist and removed a handful of roughly carved figures, none larger than her index finger, and each shaped to give the vague impression of a person's face and form. She handed them around the members of the team, giving the Wanderer a second. "For your friend."
"Thank you," said the Wanderer. "Will you mind Yoshimaru for me? Danger is no place for such a dear and loyal companion."
Kaito, who intended to walk with her into danger, raised an eyebrow and said nothing.
"Take these," said Etrata, picking up a square device from a stack of similar and offering it to Niko. "They'll monitor the energies in the house and help us build a better idea of what sets it so apart."
One by one, they took the monitoring devices and approached the door. It swung open as the Wanderer reached for the knob. On the other side was a foyer, some kind of hallway, but glimpsed through a membrane of strange, fuzzing blue energy. One by one, the group filed inside.
The last thing any of them saw before the door slammed shut was Aminatou, one hand clenched in Yoshimaru's fur, standing with Etrata, Proft, and Niv-Mizzet as she watched them go. They looked like they were much farther away than they should have been. Then the door closed, and the House was all.
#figure(image("001_Episode 1: Don't Go Past the Old Dark House/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
|
|
https://github.com/henry-zwart/uva-report-unofficial | https://raw.githubusercontent.com/henry-zwart/uva-report-unofficial/main/README.md | markdown | MIT License | # UvA-report-unofficial
UvA-report-unofficial is a Typst template for lab reports at the University of Amsterdam.
It's written primarily for my own use, but I've made it open-source in case others find it helpful.
## Dependencies
Using the template requires a local installation of [Typst](https://github.com/typst/typst#installation).
Until the template is listed on the Typst template repository, you'll also need a clone of
this repo in a place Typst can see it. The Typst team recommend:
> `{data-dir}/typst/packages/local/uva-report-unofficial/{version}`
Where `{version}` is the current version as it appears in [typst.toml](typst.toml), and
`{data-dir}` depends on your operating system:
- `~/.local/share` (Linux)
- `~/Library/Application Support` (MacOS)
- `%APPDATA%` (Windows)
## Usage
```zsh
# Navigate to where you'd like the report to live, e.g.,
cd $HOME/reports
# Create the report directory
typst init @local/uva-report-unofficial:{version} {report-directory-name}
```
This will create a new directory at `$HOME/reports/{report-directory-name}`, with
a templated document, `main.typ`, which you can edit.
## Contributing
Pull requests are welcome. For major changes or bugs, please open an issue.
## License
[MIT](https://choosealicense.com/licenses/mit/)
|
https://github.com/dead-summer/math-notes | https://raw.githubusercontent.com/dead-summer/math-notes/main/notes/Analysis/ch1-measures/ch1-measures.typ | typst | #import "/book.typ": book-page
#show: book-page.with(title: "Measures")
In this chapter we set forth the basic concepts of measure theory, develop a general procedure for constructing nontrivial examples of measures, and apply this procedure to construct measures on the real line. |
|
https://github.com/xrarch/books | https://raw.githubusercontent.com/xrarch/books/main/documents/a4xmanual/chapnvram.typ | typst | #import "@preview/tablex:0.0.6": tablex, cellx, colspanx, rowspanx
= NVRAM
XR/computer systems all contain a 4KB non-volatile RAM (NVRAM) which is used by the system firmware to store persistent information in "NVRAM variables". These can be viewed and set by the user from the command monitor. All NVRAM variable contents are ASCII strings, but the internal format is undocumented and liable to change. A table of the currently defined NVRAM variables follows:
#box([
#tablex(
columns: (1fr, 6fr),
cellx([
#set text(fill: white)
#set align(center)
*Name*
], fill: rgb(0,0,0,255)),
cellx([
#set text(fill: white)
#set align(center)
*Function*
], fill: rgb(0,0,0,255)),
[*boot-dev*], [If *auto-boot?* is set to "true", contains the name of a preferred partition to boot from (in *dksXsY* format).],
[*auto-boot?*], [If set to "true", the system will attempt to automatically boot.],
[*boot-args*], [Contains the argument string that will be passed to bootstrap software.],
)
])
Any other variables seen in the `listenv` listing may have been created by the embedded legacy A3X firmware, which is chain-loaded in order to boot legacy operating systems. These variables are undocumented and should be left alone. |
|
https://github.com/cbr9/CV | https://raw.githubusercontent.com/cbr9/CV/main/modules/professional.typ | typst | Apache License 2.0 | #import "../template/template.typ": *
#cvSection("Professional Experience")
#cvEntry(
title: [Master Thesis],
society: [Sony Europe (AI, Speech & Sound Group)],
logo: "../src/logos/sony.jpg",
date: [April 2023 - September 2023],
location: [Stuttgart, Germany],
description: list(
),
tags: ("HuggingFace", "PyTorch", "PyTorch Lightning", "ASR", "Hydra")
)
#cvEntry(
title: [Working Student],
society: [Sony Europe (AI, Speech & Sound Group)],
logo: "../src/logos/sony.jpg",
date: [July 2022 - March 2022],
location: [Stuttgart, Germany],
description: list(
),
tags: ("Label Studio", "Thrax", "WFSTs", "Text Normalization", "Italian Language", "NLP")
)
#cvEntry(
title: [Research Assistant],
society: [Institut für Maschinelle Sprachverarbeitung],
logo: "../src/logos/ims.jpg",
date: [July 2022 - December 2022],
location: [Stuttgart, Germany],
description: list(
),
)
#cvEntry(
title: [Linux System Administrator],
society: [Institut für Maschinelle Sprachverarbeitung],
logo: "../src/logos/ims.jpg",
date: [July 2022 - March 2022],
location: [Stuttgart, Germany],
description: list(
)
)
#cvEntry(
title: [Data Annotator],
society: [Institut für Maschinelle Sprachverarbeitung],
logo: "../src/logos/ims.jpg",
date: [November 2021 - January 2022],
location: [Stuttgart, Germany],
description: list(
)
)
|
https://github.com/barrel111/readings | https://raw.githubusercontent.com/barrel111/readings/main/notes/diestel.typ | typst | #import "@local/preamble:0.1.0": *
#import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge
#import "@preview/commute:0.2.0": node, arr, commutative-diagram
#show: project.with(
course: "Mathematics",
sem: "Summer",
title: "Graph Theory",
subtitle: "from Diestel.",
authors: (
"<NAME>",
),
)
= Basics
== Graphs
Here, we outline a lot of basic definitions.
#definition[A set $cal(A) = {A_1, dots, A_k}$ of disjoint subsets of $A$ is a _partition_ of $A$ if the union $union.big cal(A)$ of all the sets $A_i in cal(A)$ is $A$. Another partition ${A_1', dots, A'_ell}$ of $A$ _refines_ the partition $cal(A)$ if each $A_i'$ is contained in some $A_j$.]
#definition[By $[A]^k$ we denote the set of all _$k$-element subsets_ of $A$. Furthermore, sets with $k$ elements are also known as _$k$-sets_; subsets with $k$ elements are _$k$-subsets_.]
#definition[A _graph_ a pair $G = (V, E)$ such that $E subset.eq [V]^2$. For clarity, we assume that $V sect E = emptyset$. The elements of $V$ are the _vertices_ of the graph $G$ and the elements of $E$ are its _edges_. ]
#definition[The _order_ of a graph, written $abs(G)$, is the number of vertices of $G$. The number of edges of $G$ is denotes by $norm(G)$. Graphs are _finite_, _infinite_, _countable_ and so on according to their order.]
#example[The _empty graph_ is $(emptyset, emptyset)$, also denotes as $emptyset$ simply.]
#example[A graph of order $0$ or $1$ is also known as a _trivial_ graph.]
#definition[A vertex $v$ is _incident_ with an edge $e$ if $v in e$; then $e$ is an edge _at_ $v$. The two vertices incident with an edge are its _endvertices_ or _ends_, and an edge _joins_ its ends.]
#definition[An edge ${x, y}$ is usually written as $x y$ (or $y x$). If $x in X$ and $y in Y$, then $x y$ is an $X"-"Y$ _edge_. The set of all $X"-"Y$ edges in a set $E$ is denoted by $E(X, Y)$. ]
#remark[Instead of $E({x}, Y)$ and $E(X, {y})$, we write $E(x, Y)$ and $E(X, y)$. The set of all the edges in $E$ at a vertex $v$ is denoted by $E(v)$.]
#definition[Two vertices $x, y$ of $G$ are _adjacent_ or _neighbors_ if $x y$ is an edge of $G$. Two edges $e != f$ are adjacent if they have an end in common.]
#example[If all the vertices of $G$ are pairwise adjacent, then $G$ is _complete_. A complete graph on $n$ vertices is denoted $K^n$. ]
#definition[A set of vertices or edges is _independent_ if no two of its elements are adjacent. Independent sets of vertices are also called _stable_.]
#definition[Let $G = (V, E)$ and $G' = (V', E')$. A map $phi: V arrow V'$ is a _homomorphism_ from $G$ to $G'$ if it preserves the adjacency of vertices, that is, if ${phi(x), phi(y)} in E'$ whenever ${x, y} in E$.]
#lemma[For every vertex $x'$ in the image of the homomorphism $phi: G arrow G'$, its inverse image $phi^(-1)(x')$ is an independent set of vertices in $G$.]
#definition[If $phi$ is bijective and its inverse $phi^(-1)$ is also a homomorphism (i.e. $x y in E arrow.r.l.double.long phi(x) phi(y) in E'$ for all $x, y in V$), we call $phi$ an _isomorphism_. We also say $G$ and $G'$ are isomorphic as denoted by $G tilde.eq G'$ (or even simpler, $G = G'$, when we only care about the _isomorphism type_ of a given graph)]
#definition[An isomorphism from $G$ to itself is an _automorphism_ of $G$.]
#definition[A class of graphs that is closed under isomorphism is called a _graph property_.]
#example[Containing a triangle is a graph property.]
#definition[A map taking graphs as arguments is called a _graph invariant_ if it assigns equal values to isomorphic graphs.]
#example[The number of vertices and the number of edges are graph invariants. The greatest number of pairwise adjacent vertices is also another one.]
#definition[We define $G union G' = (V union V', E union E')$ and $G sect G' = (V sect V', E sect E')$. If $G sect G' = emptyset$ then $G$ and $G'$ are _disjoint_.]
#definition[If $V' subset.eq V$ and $E' subset.eq E$, then $G'$ is _subgraph_ of $G$ (and $G$ a _supergraph_ of $G'$), written $G' subset.eq G$. If $G' subset.eq G$ but $G' != G$ then $G'$ is a _proper subgraph_ of $G$.]
#definition[If $G' subset.eq G$ and $G'$ contains all the edges $x y in E$ with $x, y in V'$, then $G'$ is an induced subgraph of $G$; we say that $V'$ _induces_ or _spans_ $G'$ in $G$. We also write $G' = G[V']$.]
#remark[If $U subset.eq V$ is any set of vertices, then $G[U]$ denotes the graph on $U$ whose edges are precisely the edges of $G$ with both ends in $U$. If $H$ is a subgraph of $G$, not necessarily induced, we abbreviate $G[V(H)]$ to $G[H]$.]
#definition[$G' subset.eq G$ is a _spanning subgraph_ of $G$ if $V'$ spans all of $G$, that is if $V' = V$.]
#definition[If $U$ is any set of vertices, we write $G - U$ for $G[V \\ U]$. That is, $G - U$ is obted from $G$ by _deleting_ all the vertices in $U sect V$ and their incident edges.]
#remark[If $U = {v}$ we write $G - v$ instead of $G - {v}$. Furthermore, instead of $G - V(G')$, we simply write $G - G'$.]
#definition[For any subset $F$ of $[V]^2$, we write $G - F = (V, E \\ F)$ and $G + F = (V, E union F)$.]
#remark[We abbreviate $G - {e}$ and $G + {e}$ to $G - e$ and $G + e$.]
#definition[We call $G$ _edge-maximal_ with a given graph property if $G$ itself has the property but no graph $(V, F)$ with $F supset.neq E$ does.]
#remark[When we call a graph _minimal_ or _maximal_ with some property but haven't spevified an ordering, we are referring to the subgraph relation. When we speak of minimal or maximal sets of vertices or edges, the reference is to set inclusion.]
#definition[If $G$ and $G'$ are disjoint, we denote by $G star G'$ the graph obtained from $G union G'$ by joining all the vertices of $G$ to all the vertices of $G'$.]
#definition[The _complement_ $overline(G)$ of $G$ is the graph on $V$ with edge set $[V]^2 \\ E$.]
#definition[The _line graph_ $L(G)$ of $G$ is the graph on $E$ in which $x, y in E$ are adjacent as vertices if and only if they are adjacent as edges.]
== Degrees of a Vertex
Throughout this section let $G = (V, E)$ be a non-empty graph.
#definition[The _set of neighbours_ of a vertex $v$ in $G$ is denoted by $N_G (v)$. More generally, for $U subset.eq V$, the neighbours in $V \/ U$ of vertices in $U$ are called _neighbours of U_, denoted $N(U)$.]
#definition[The _degree_ (or _valency_) $d_G(v) = d(v)$ of a vertex $v$ is the number $|E(v)|$ of edges at $v$. This is equal to the number of neighbors of $v$ (not necessarily true for multigraphs). ]
#definition[A vertex of degree $0$ is _isolated_.]
#definition[We define
+ the _minimum degree of $G$_, $delta(G) = min {d(v) bar v in V}$,
+ the _maximum degree of $G$_, $Delta(G) = max{d(v) bar v in V}$,
+ the _average degree of $G$_, $d(G) = 1/abs(V) sum_(v in V) d(v)$.]
#definition[If all the vertice of $G$ have the same degree $k$, then $G$ is _$k$-regular_ (or even just _regular_).]
#example[A $3$-regular graph is also called _cubic_.]
#lemma[ $ delta(G) <= d(G) <= Delta(G). $]
The average degree captures information about the number of edges of $G$ per vertex. We may be interested in this quantity directly.
#definition[The number of edges of $G$ per vertex is denoted $epsilon(G) = abs(E)/abs(V)$.]
#prop("Handshake Lemma")[ $ sum_(v in V) d(v) = 2 abs(E). $]
#proof[Every edge contributes to the degree of exactly two vertices by $1$. Thus, we count every edge exactly twice in the sum on the left. \ ]
The following are simple consequences of this fact.
#corollary[$ epsilon(G) = 1/2 d(G) $]
#corollary[The number of vertices of odd degree in a graph is always even.]
A graph with large minimum degree (everywhere, locally) also has many edges per vertex globally.
#lemma[$ epsilon(G) >= 1/2 delta(G) $]
On the other hand, average degree may be large even when minimum degree is small. That said, the vertices of large degree cannot be scattered "completely" among vertices of small degree.
#prop[Every graph $G$ with at least one edge has a subgraph $H$ with $ delta(H) > epsilon(H) >= epsilon(G). $]
#proof[The idea is simple: we delete vertices of small degree one by one, until only vertices of large degree remain. We can delete vertices up to $d(v) = epsilon$ as then the number of vertices decreases by $1$ and the number of edges decreases by at most $epsilon$-- so, the overall ratio doesn't decrease.
More formally, construct a sequence $G = G_0 supset.eq G_1 supset.eq .dots $ of induced supgraphs of $G$ as follows: if $G_i$ has a vertex $v_i$ of degree $d(v_i) <= epsilon(G_i)$, we let $G_(i + 1) = G - v_i$; if not we terminate our sequence and set $H = G_i$. By our choices of $v_i$, we have $epsilon(G_(i + 1)) >= epsilon(G_i)$ for all $i$, and hence $epsilon(H) >= epsilon(G)$.
Since $epsilon(G) > 0 = epsilon(K^1)$, none of the graphs in our sequence are trival. Hence, $H != emptyset$. Since $H$ has no vertex suitable for deletion, we must have $delta(H) > epsilon(H)$. \ ]
== Paths and Cycles
#definition[A _path_ is non-empty graph $P = (V, E)$ of the form $ V = {x_0, x_1, dots, x_k} #h(10pt) E = {x_0x_1, x_1x_2, dots, x_(k - 1)x_k} $ where all the $x_i$ are distinct. The vertices $x_0$ and $x_k$ are _linked_ by $P$ and are called its _endvertices_ or _Ends_. The vertices $x_1, dots, x_(k - 1)$ are the _inner_ vertices of $P$. The number of edges of a path is its _length_.]
#example[The path of length $k$ is dentoed by $P^k$. Particularly, we have $P^0 = K^1$.]
#remark[We usually refer to a path by the natural sequence of its vertices. That is, we say $P = x_0x_1 dots x_k$ and call $P$ a path from $x_0$ to $x_k$.]
#definition[We define special _subpaths_ of $P$ for $0 <= i <= j <= k$, $ P x_i = x_0 dots x_i #h(25pt) circle(P) = x_1 dots x_(k - 1) \ x_i P = x_i dots x_k #h(25pt) P circle(x_i) = x_0 dots x_(i - 1) \ x_i P x_j = x_i dots x_j #h(25pt) circle(x_i) P circle(x_j) = x_(i + 1) dots x_(j - 1). $]
#definition[If the union $P x union x Q y union y R$ of three paths is again a path, we simply denote it by $P x Q y R$. This is also known as _concatenation of paths_.]
#definition[Suppose $A, B subset.eq V$. Then $P = x_0 dots x_k$ is an $A$-$B$ _path_ if $V(P) sect A = {x_0}$ and $V(P) sect B = {x_k}$.]
#remark[We write $a"-"B$ instead of ${a}"-"B$.]
#definition[Two or more paths are _independent_ if none of them contains an inner vertex of another.]
#definition[A non-trivial path $P$ is an $A$-_path_ for a set $A$ of vertices if $P$ has its ends but no inner vertex in $A$. It is an $H$-path for a graph $H$ if it is a $V(H)$-path and, if it has length $1$, its edge does not lie in $H$.]
#definition[If $P = x_0 dots x_(k - 1)$ is a path and $k >= 3$ the nthe graph $C = P + x_(k - 1) x_0$ is called a _cycle_. This cycle may also be written as $x_0 dots x_(k - 1) x_0$. The length of a cycle is its number of edges (or vertices).]
#example[The cycle of length $k$ is called a $k$-cycle and denoted by $C^k$.]
#definition[The minimum length of a cycle in a graph $G$ is the _girth_, $g(G)$, of $G$. The maximum length of a cycle in $G$ is its _circumference_. If $G$ contains no cycle the former is $infinity$ and the latter is $0$.]
#definition[An edge which joins two vertices of a cycle but is not itself an edge of the cycle is a _chord_ of that cycle. So, an _induced cycle_ in $G$, a cycle in $G$ forming an induced subgraph, is one that has no chords.]
If a graph has large minimum degree, it has long paths and cycles.
#prop[Every graph $G$ contains a path of length $delta(G)$ and a cycle of length at least $delta(G) + 1$ (provided that $delta(G) >= 2$).]
#proof[Let $x_0 dots x_k$ be a longest path in $G$. Then all the neighbors of $x_k$ lie on this path. Hence, $k >= d(x_k) >= delta(G)$. If $i < k$ is minimal with $x_i x_k in E(G)$, then $x_i dots x_k x_i$ is a cycle of length at least $delta(G) + 1$. \ ]
However, minimum degree and girth are not related unless we fix the number of vertices.
#definition[The _distance_ $d_G (x, y)$ in $G$ of two vertices $x, y$ is the length of a shortest $x"-"y$ path in $G$; if no such path exists, we set $d(x, y) = oo$. The greatest distance between two vertices in $G$ is the _diameter_ of $G$, denoted $"diam"(g)$. ]
Diameter and girth are related.
#prop[Every graph $G$ containing a cycle satisfies $g(G) <= 2 "diam"(G) + 1$.]
#proof[Let $C$ be a shortest cycle in $G$. If $g(G) >= 2 "diam"(G) + 1$ then $C$ has two vertices whose distance in $C$ is at least $"diam"(G) + 1$. In $G$, these vertices have a lesser distance; any shortest path $P$ between them is not a subgraph of $C$. Thus, $P$ contains a $C$-path $x P y$. Together with the shorter of the two $x"-"y$ paths in $C$, this path $x P y$ forms a shorter cycle than $C$, a contradiction. \ ]
#definition[A vertex is _central_ in $G$ if its greatest distance from any other vertex is as small as possible. The distance is the _radius_ of $G$, denoted by $"rad"(G)$. More formally, $ "rad"(G) = min_(x in V(G)) max_(y in V(G)) d_G (x, y). $ ]
#lemma[ $ "rad"(G) <= "diam"(G) <= 2 "rad"(G). $]
Diameter and radius are not related to minimum, average or maximum degree if we say nothing about the order of the graph. Graphs of large diameter and minimum degree must be large and graphs of small diameter and maximum degree must be small.
#prop[A graph $G$ of radius at most $k$ and maximum degree at most $d >= 3$ has fewer than $d/(d - 2) (d - 1)^k$ vertices.]
#proof[Let $Z$ be a central vertex in $G$, and let $D_i$ denote the set of vertices of $G$ at distance $i$ from $z$. Then, $V(G) = union.big_(i = 0)^k D_i$. We have $abs(D_0) = 1$ and $abs(D_1) = 1$. For $i >= 1$, $abs(D_(i + 1)) <= (d - 1) abs(D_i)$ since every vertex in $D_(i + 1)$ is a neighbour of a vertex in $D_i$ and each vertex in $D_i$ has at most $(d - 1)$ neighbours in $D_(i + 1)$. Thus, by induction, for all $i < k$, $abs(D_(i + 1)) <= d(d- 1)^i$. This then gives us, $ abs(G) <= 1 + d sum_(i = 0)^(k - 1) (d - 1)^i = 1 + d/(d - 2) ((d - 1)^k - 1) < d/(d - 2) (d - 1)^k. $]
We can also bound the order of $G$ from below by assuming that both its minimum degree and girth are large. For $d in RR$ and $g in NN$ suppose
$ n_0(d, g) = cases(1 + d sum_(i = 0)^(r - 1) (d - 1)^i #h(15pt) & "if " g = 2r + 1 "is odd;", 2 sum_(i = 0)^(r - 1) (d - 1)^i & "if" g = 2r "is even.") $
#lemma[A graph of minimum degree $delta$ and girth $g$ has at least $n_0(delta, g)$ vertices.]
In fact, we can obtain the same bound for its average degree.
#prop("<NAME> & Linial 2002")[Let $G$ be a graph. If $d(G) >= d >= 2$ and $g(G) >= g in NN$ then $abs(G) >= n_0(d, g)$.]
An interesting consequence of this is that it guarantees the existence of a short cycle compared with $abs(G)$.
#corollary[If $delta(G) >= 3$ then $g(G) < 2 log abs(G)$.]
#proof[If $g = g(G)$ is even then $ n_0(3, g) = 2 (2^(g/2) - 1)/(2 - 1) = 2^(g/2) + (2^(g/2) - 2) > 2^(g/2) $ while if $g$ is odd then $ n_0(3, g) = 1 + 3 (2^((g- 1)/2) - 1)/(2 - 1) = 3/sqrt(2) 2^(g/2) - 2 > 2^(g/2). $ AS $abs(G) >= n_0(3, g)$ the result follows. \ ]
#definition[A _walk_ (of _length_ $k$) is an alternating sequence of $v_0 e_0 v_1 e_1 dots e_(k - 1) v_k$ of vertices and edges in $G$ such that $e_i = {v_i, v_(i + 1)}$ for all $i < k$. If $v_0 = v_k$, the walk is _closed_. If the vertices in a walk are all distinct, it defines an obvious path in $G$.]
#lemma[Every walk between two vertices contains a path between these vertices.]
== Connectivity
#definition[A graph $G$ is called _connected_ if it is non-empty and any two of its vertices are linked by a path in $G$. If $U subset.eq V$ is such that $G[U]$ is connected, we also call $U$ _connected in G_. Rather than not connected we say _disconnected_.]
#prop[The vertices of a connected graph $G$ can always be enumerated, say $v_1, dots, v_n$, so that $G_i = G[v_1, dots, v_i]$ is connected for every $i$.]<enum-complete>
#proof[ Pick any vertex as $v_1$, and assume inductively that $v_1, dots, v_i$ have been chosen for some $i < abs(G)$. Now pick a vertex $v in G - G_i$. As $G$ is connected, it contains a $v"-"v_1$ path $P$. Choose as $v_(i + 1)$ the first vertex of $P$ in $G-G_i$; then $v_(i + 1)$ has a neighbour in $G_i$. The connectedness of every $G_i$ follows by induction on $i$. \ ]
#definition[A maximal connected subgraph of $G$ is a _component_ of $G$.]
#prop[The components of a graph are induced subgraphs and their vertex sets partition $V$.]
#definition[If $A, B subset.eq V$ and $X subset.eq V union E$ are such that every $A"-"B$ path in $G$ contains a vertex or an edge from $X$, we say that $X$ _separates_ the sets $A$ and $B$ in $G$. We say that $X$ separates two vertices $a, b$ if it separates the sets ${a}, {b}$ but $a, b in.not X$.]
#definition[The set $X$ _separates_ $G$, and is a _separator in_ or _of_ $G$, if $X$ separates some two vertices in $G$.]
#definition[A vertex which separates two other vertices in the same component is a _cutvertex_, and an edge separating its ends is a _bridge_.]
#lemma[The _bridges_ in a graph are precisely those edges that do not lie on any cycles.]
#definition[The unordered pair ${A, B}$ is a _separation_ of $G$ if $A union B = V$ and $G$ has no edge between $A \\ B$ and $B \\ A$. This is equivalent to saying $A sect B$ separates $A$ from $B$. If both $A \\ B$ and $B \\ A$ are non-empty, the separation is _proper_. The number $abs(A sect B)$ is the order of the separation of ${A, B}$; the sets $A, B$ are its _sides_.]
#definition[$G$ is called _$k$-connected_ if $abs(G) > k$ and $G - X$ is connected for every set $X subset.eq V$ with $abs(X) < k$. In other words, no two vertices are separated by fewer than $k$ other vertices.]
#example[Every non-trivial graph is $0$-connected. The $1$-connected graphs are the non-trivial connected graphs.]
#definition[The greatest integer $k$ such that $G$ is $k$-connected is the connectivity $kappa(G)$ of $G$.]
#example[$kappa(G) = 0$ if and only if $G$ is diconnected or $K^1$. Furthermore, $kappa(K^n) = n - 1$ for all $n >= 1$.]
#definition[If $abs(G) > 1$ and $G - F$ is connected for every set $F subset.eq E$ of fewer than $ell$ edges, then $G$ is called _$ell$-edge-connected_.]
#definition[The greatest integer $ell$ such that $G$ is $ell$-edge-connected is the _edge-connectivity_ $lambda(G)$ of $G$.]
#example[We have $lambda(G) = 0$ if $G$ is disconnected.]
#prop[If $G$ is non-trivial then $kappa(G) <= lambda(G) <= delta(G)$.]
#proof[The second inequality follows from the fact that all hte edges incident with a fixed vertex separate $G$. For the first inequality, let $F$ be a set of $lambda(G)$ edges such that $G - F$ is disconnected. This set exists by the definition of $lambda$. Furthermore, $F$ is a minimal separating set of edges in $G$. We now show that $kappa(G) <= abs(F)$.
We consider two cases
+ $G$ has a vertex $v$ that is not incident with an edge in $F$. \ Let $C$ be the component of $G - F$ containing $v$. Then the vertices of $C$ that are incident with an edge in $F$ separate $v$ from $G - C$. Since no edge in $F$ has both ends in $C$ (by the minimality of $F$), there are at most $abs(F)$ such vertices, giving $kappa(G) <= abs(F)$ as desired.
+ every vertex is incident with an edge in $F$. \ Let $v$ be any vertex and let $C$ be the component of $G - F$ containing $v$. Then the neighbours $w$ of $v$ with $v w in.not F$ lie in $C$ and are incident with distinct edges in $F$ (by the minimality of $F$) giving $d_G (v) <= abs(F)$. As $N_G (v)$ separates $v$ from any other vertices in $G$, this yields $kappa(G) <= abs(F)$ -- unless there are no other vertices i.e. unless ${v} union N(v) = V$. But $v$ was an abitrary vertex and so, we may assume that $G$ is complete, giving $kappa(G) = lambda(G) = abs(G) - 1$.
]
So, high-connectivity requires large minimum degree. However, large minimum degree does not necessarily ensure high connectivity, not even high edge-connectivity. It does ensure the existence of a highly connected subgraph.
#prop("Mader 1972")[Let $0 != k in NN$. Every graph $G$ with $d(G) >= 4k$ has a $k$-connected subgraph. In fact, every such $G$ has a $(k + 1)$-connected subgraph $H$ such that $d(H) > d(G) - 2k >= 2k$.]
#proof[Let $gamma >= epsilon(G) >= 2k$. Consider the subgraphs $G' subset.eq G$ such that $ abs(G') >= 2k #h(15pt) "and" #h(15pt) norm(G') > gamma(abs(G') - k). #h(30pt) (*) $
Such graphs $G'$ exist since $G$ is one; let $H$ be one of smallest order.
No graph $G'$ as in $(*)$ can have order exactly $2k$, since this would imply that $norm(G') > gamma k >= 2k^2 > binom(abs(G'), 2)$. The minimality of $H$ therefore implies that $delta(H) > gamma$: otherwise we could delete a vertex of degree at most $gamma$ and obtain a graph $G' subset.neq H$ still satisfying $(*)$. Then we have $abs(H) > gamma$. Dividing the inequality of $norm(H) > gamma abs(H) - gamma k$ from $(*)$ by $abs(H)$ therefore yeilds $epsilon(H) > gamma - k$.
Now we must show that $H$ is $(k + 1)$-connected. If not, then $H$ has a proper separation ${U_1, U_2}$ of order at most $k$; let $H[U_i] = H_i$. Since any vertex $v in U_1 \\ U_2$ has all its $d(v) >= delta(H) > gamma$ neighbours from $H$ in $H_1$, we have $abs(H_1) >= gamma >= 2k$. Similarly, $abs(H_2) >= 2k$. By the minimality of $H$, neither $H_1$ nor $H_2$ satisfies $(*)$, we thus have $ norm(H_i) <= gamma(abs(H_i) - k) $ for $i = 1, 2$. But then $ norm(H) &<= norm(H_1) + norm(H_2) \ &<= gamma(abs(H_1) + abs(H_2) - 2k) \ &<= gamma (abs(H) - k) #h(20pt) ("as" norm(H_1 sect H_2) <= k), $
which contradicts $(*)$ for $H$.
\ ]
== Trees and Forests
#definition[An _acyclic_ graph, one not containing any cycles, is called a _forest_.]
#definition[A connected forest is called a _tree_.]
#remark[So, a forest is a graph whose components are trees.]
#definition[The vertices of degree $1$ in a tree are its _leaves_, the others are its _inner vertices_.]
#lemma[Every non-trivial tree has a leaf.]
#lemma[If we remove a leaf from a tree, what remains is still a tree.]
#prop[The following assertions are equivalent for a graph $T$:
+ $T$ is a tree;
+ Any two vertices of $T$ are linked by a unique path in $T$;
+ $T$ is minimally connected, i.e. $T$ is connected but $T - e$ is disconnected for every edge $e in T$;
+ $T$ is maximally acyclic, i.e. $T$ contains no cycle but $T + x y$ does, for any two non-adjacent vertices $x, y in T$.]
#remark[We write $x T y$ for the unique path in a tree $T$ between two vertices $x, y$.]
#lemma[Every connected graph contains a spanning tree.]
#definition[When $T$ is a spanning tree of $G$, the edges in $E(G) \\ E(T)$ are the _chords_ of $T$ in $G$.]
#corollary[A connected graph with $n$ vertices is a tree if and only if it has $n - 1$ edges. ]
#proof[For the forward implication, enumerate the vertices of a tree $T$ as in @enum-complete. As $T$ is acyclic, every vertex is adjacent to only one earlier vertex. Now $|T| = n - 1$ follows by induction on $n$.
Conversely, let $G$ be any connected graph with $n$ vertices and $n - 1$ edges. Let $T$ be a spanning tree in $G$. Since $T$ has $n - 1$ edges by the first implication, it follows that $T = G$. \ ]
#corollary[If $T$ is a tree and $G$ is any graph with $delta(G) >= abs(T) - 1$, then $T$ is (isomorphic to) a subgraph of $G$.]
#proof[ Map the vertices of $T$ to $G$ following their enumeration from @enum-complete applied to $T$. \ ]
#definition[Sometimes it is convenient to consider one vertex of a tree as special; such a vertex is called the _root_ of this tree.]
#definition[A tree $T$ with a fixed root $r$ is a _rooted tree_.]
#definition[We define a partial ordering on $V(T)$, the _tree-order_ associated with $T$ and $r$, by writing $x <= y$ for $x in r T y$. Think of this order as expressing 'height': if $x < y$ we say that $x$ lies _below_ $y$ in $T$. Furthermore, we call $ ceil(y) = {x bar x <= y} #h(10pt) "and" #h(10pt) floor(y) = {y bar y >= x}. $ the _down-closure_ of $y$ and the _up-closure_ of $x$.]
#definition[A set $X subset.eq V(T)$ that equals its up-closure i.e. which satisfies $X = floor(X) = union.big_(x in X) floor(x)$, is _closed upwards_, or an _up-set_ in $T$. Similarly, we define _down-closed_ sets or _down-sets_.]
#remark[The root of $T$ is the least element in its tree-order, the leaves are its maximal elements, the ends of an edge of $T$ are comparable and the down-closure of very vertex is a _chain_, a set of pairwwise comparable elements.]
#definition[The vertices at distance $k$ from the root have _height_ $k$ and form the $k$th _level_ of $T$.]
#definition[A rooted tree $T$ contained in a graph $G$ is called _normal_ in $G$ if the ends of every $T$-path in $G$ are comparable in the tree-order of $T$.]
#remark[If $T$ spans $G$, this amounts to requiring that two vertices of $T$ must be comparable whenever they are adjacent in $G$.]
Normal trees can be a powerfool tool since $G$ reflects the separation properties of $T$.
#lemma[Let $T$ be a normal tree in $G$.
+ Any two vertices $x, y$ of $T$ that are incomparable in its tree order are separated in $G$ by the set $ceil(x) sect ceil(y)$.
+ If $V(T) = V(G) = V$ and $S subset.eq V$ is down-closed, then the components of $G - S$ are spanned by the sets $floor(x)$ with $x$ minimal in $V \\ S$.]
#proof[
+ As $x$ and $y$ are incomparable, neither of them lies in $ceil(x) sect ceil(y)$. Thus, it suffices to show that every $x$-$y$ path $P$ in $G$ meets $ceil(x) sect ceil(y)$. Let $t_1, dots, t_n$ be a minimal sequence of vertices in $P sect T$ such that $t_1 = x$ and $t_n = y$ and $t_i$ and $t_(i + 1)$ are comparable in the tree order of $T$ for all $i$. Such a sequence must exist: the set of all vertices in $P sect T$, in their natural order as they occur in $P$ has this property because $T$ is normal and every segment $t_i P t_(i + 1)$ is either an edge of $T$ or a $T$-path. In our minimal sequence, we cannot have $t_(i - 1) < t_i > t_(i + 1)$ for any $i$ since $t_(i - 1)$ and and $t_(i + 1)$ would then be comparable and deleting $t_i$ would yield a smaller such sequence. Our sequence then must have the form $ x = t_1 > dots > t_k < dots < t_n = y $ for some $k in [n]$ (even with $k<=3$, by the minimality of $n$). As $t_k in ceil(x) sect ceil(y) sect V(P)$, we are done.
+ Every set $floor(x)$ as in $(b)$ is connected in $T$, and hence in $G$. It lies in $V \\ S$, because $x in.not S$ and $S$ is down-closed. As every vertex in $V \\ S$ lies above some minimal such vertex $x$, these sets $floor(x)$ have union $V \\ S$. \ For distinct $x$ and $x'$, the connected sets $floor(x)$ and $floor(x')$ are disjoint, and not joined by an edge of $G$, because $ceil(x) sect ceil(x') subset.eq S$ separates $x$ from $x'$ in $G$. So the sets $floor(x)$ span maximal connected subgraphs, components, in $G - S$, and these are all its components.
]
Normal spanning trees are aso known as _depth-first search trees_ since they arise in the depth-first traversal of graphs. The following constructive proof, however, illuminates better how normal trees capture the structure of their host graphs.
#prop[Every connected graph has a normal spanning tree.]
#proof[Let $G$ be a connected graph. Let $T$ be any maximal normal tree in $G$; we show that $V(T) = V(G)$.
Suppose note, and let $C$ be a component of $G - T$. As $T$ is normal, $N(C)$ is a chain in $T$. Let $x$ be its greatest element, and let $y in C$ be adjacent to $x$. Let $T'$ be the tree obtained from $T$ by joining to $y$ to $x$. The tree order of $T'$ then extends that of $T$. We now work towards a contradiction by showint that $T'$ is also normal in $G$.
Let $P$ be a $T'$-path in $G$. If the ends of $P$ both lie in $T$, then they are comparable in the tree order of $T$ and hence, in that of $T'$ too (by normality of $T$ in $G$). If not, then $y$ is one end of $P$, so $P$ lies in $C$ except for its other end $z$, which lies in $N(C)$. Then $z <= x$ by the choice of $x$. Note that as $y$ is a leaf of $T'$ with neighbour $x$, we have $x < y$ and thus, $z < y$. We have our contradiction!
\ ]
== Bipartite Graphs
#definition[For $r >= 2, r in ZZ$, a graph $G$ is called _$r$-partite_ if $V$ admits a partition into $r$ classes such that every edge has its ends in different classes. That is, vertices in the same partition class must not be adjacent.]
#example[Instead of $2$-partite we say _bipartite_.]
#example[An $r$-partite graph in which every two vertices from different partition classes are adjacent is called _complete_. The complete $r$-partite graphs for all $r$ together are the _complete multipartite_ graphs. The complete $r$-partite graph $overline(K^(n_1)) * dots * overline(K^(n_r))$ is denoted by $K_(n_1, dots, n_r)$. If $n_1 = dots = n_r = s$ we abbreviate this to $K^r_s$. Thus, $K^r_s$ is the complete $r$-partite graph in which every partition class contains exactly $s$ vertices.]
#example[Graphs of the form $K_(1, n)$ are known as _stars_. The vertex in the singleton partition class in $K_(1, n)$ is the star's _centre_.]
#prop[A graph is bipartite if and only if it contains no odd cycle.]
#proof[
For the forward direction, it suffices to show that an odd cycle isn't bipartite as subgraphs of a bipartite graph must also be bipartite. Suppose $x_1 x_2 dots x_n x_1$ is an odd cycle. That is, $n$ is odd. For contradiction, assume $A, B$ is a valid bipartition of the odd cycle. WLOG, we must have $x_i in A$ if $i$ is odd and $x_i in B$ if $i$ is even. So, $x_n, x_1 in A$ but are also adjacent-- a contradiction!
For the backward implication, let $G$ be a graph without odd cycles; we show that $G$ is bipartite. Clearly, a graph is bipartite if all its components are bipartite or trivial. So, we may assume that $G$ is connected. Let $T$ be a spanning tree in $G$, pick a root $r in T$, and denote the associated tree-order on $V$ by $<=_T$. For each $v in V$, the unique path $r T v$ has odd or even length. This defines a bipartition of $V$; we show that $G$ is bipartite with this partition.
Let $e = x y$ be an edge of $G$. If $e in T$, with $x <_T y$, then $r T y = r T x y$ and so, $x$ and $y$ lie in different partition classes. If $e in.not T$ then $C_e = x T y + e$ is a cycle and by the case treated already the vertices along $x T y$ alternate between two classes. Since $C_e$ is even by assumption, $x$ and $y$ lie in different classes.
\ ]
== Contraction and Minors
Throughout this section, let $X$ be a fixed graph.
#definition[A _subdivision_ of $X$ is any graph obtained from $X$ by replacing some edges of $X$ with new paths between their ends, so that none of these paths has an inner vertex in $V(X)$ or on another new path. When $G$ is a subdivision of $X$, we also say that $G$ _is a_ $T X$; its new vertices are called _subdividing vertices_.]
#remark[Formally, $T X$ denotes a whole calss of graphs, the class of all subdivisions of $X$.]
#remark[Subdividing vertices have degree $2$ while branch vertices retain their degree from $X$.]
#definition[If a graph $Y$ contains a $T X$ as a subgraph, then $X$ is a _topological minor_ of $Y$.]
#definition[A graph $G$ _is an $I X$_ if its vertex set admits a partition ${V_x bar x in V(X)}$ into connected subsets $V_x$ such that distinct vertices $x, y in X$ are adjacent in $X$ if and only if $G$ contains a $V_x"-"V_y$ edge. The sets $V_x$ are the _branch sets of the $I X$_. Furthermore, we say $X$ arises from $G$ by _contracting_ the subgraphs $G_x$ and call it a _contraction minor_ of $G$.]
#remark[Informally, we get an $I X$ by replacing the vertices $x$ of $X$ with disjoint connected graphs $G_x$ and the edges $x y$ of $X$ with non-empty sets of $G_x "-" G_y$ edges.]
#definition[If a graph $Y$ contains an $I X$ as a subgraph, then $X$ is a _minor_ of $Y$, the $I X$ is a _model_ of $X$ in $Y$ and we write $X lt.curly.eq Y$.]
#lemma[$X$ is a minor of $Y$ if and only if there is a map $phi$ from a subset of $V(Y)$ onto $V(X)$ such that for every vertex $x in X$ its inverse image $phi^(-1)(x)$ is connected in $Y$ and for ever edge $x x' in X$ there is an edge in $Y$ between the branch sets $phi^(-1)(x)$ and $phi^(-1)(x')$. ]
#definition[If the domain of $phi$ is all of $V(Y)$, and $x x' in X$ whenever $x != x'$ and $Y$ has an edge between $phi^(-1)(x)$ and $phi^(-1)(x')$, we call $phi$ a _contraction_ of $Y$ onto $X$.]
== Euler Tours
#definition[A closed walk in a graph is an _Euler tour_ if it traverses every edge of the graph exactly once. A graph is _Eulerian_ if it admits an Euler tour.]
#prop[A connected graph is Eulerian if and only if every vertex has even degree.]
#proof[First, the forward implication. If a vertex appears in an Euler tour $k$ times (or $(k + 1)$ times if it is the starting and finishing vertex and so, counted twice) must have degree $2 k$.
Conversely, we use induction on $norm(G)$ to show that every connected graph $G$ with all degrees even must have an Euler tour. The induction starts trivially with $norm(G) = 0$. For $norm(G) >= 1$, since all degrees are even, we may find in $G$ a non-trivial closed walk that contains no edge more than once.]
== Some Algebraic Graph Theory
== Other Notions of Graphs
= Matchings, Covering, Packing
== Matching in Bipartite Graphs
== Matching in General Graphs
== The Erdös-Pósa Theorem
== Tree Packing and Arboricity
== Path Covers
= Flows
== Circulations
== Flow in Networks
== Group-valued Flows
== $k$-Flows for small $k$
== Flow-colouring Duality
== Tutte's Flow Conjecture
= Hamilton Cycles
== Sufficient Conditions
== Hamilton Cycles and Degree Sequences
== Hamilton Cycles in the Square of a Graph
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/counter_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Count figures.
#figure(numbering: "A", caption: [Four 'A's], kind: image, supplement: "Figure")[_AAAA!_]
#figure(numbering: none, caption: [Four 'B's], kind: image, supplement: "Figure")[_BBBB!_]
#figure(caption: [Four 'C's], kind: image, supplement: "Figure")[_CCCC!_]
#counter(figure.where(kind: image)).update(n => n + 3)
#figure(caption: [Four 'D's], kind: image, supplement: "Figure")[_DDDD!_]
|
https://github.com/jamesrswift/blog | https://raw.githubusercontent.com/jamesrswift/blog/main/_posts/2024-06-28-tables.md | markdown | MIT License | ---
layout: post
title: "Column-major typst table definitions - a rabbit hole"
---
Foreword: This post pertains to Typst v0.11.1, and the post most likely won't be updated to account for any future Typst changes. So to future netizens: your mileage may vary.

Anything worthy of being displayed in a table is, more likely than not, at least a 2D array and frequently an array of dictionaries. It is probably stored as a csv file, but for the sake of brevity, let us assume that it is encoded in the source field already.
```typ
#table(
columns: (auto,) + (1fr,)*4,
align: center + horizon,
// Header with hlines, ...
// ... followed by body
($ H_v^"pc"times $), ($ 1 $),
($ (rho_"solvent")/(M_"solvent") $),
($ (rho_"solvent")/(M_"solute") $),
($ 1 / ( R T ) $),
($ H_v^"px"times $), ($ (M_"solvent")/(rho_"solvent") $),
($ 1 $),
($ (M_"solvent")/(M_"solute") $),
($ (M_"solvent")/(R T rho_"solvent") $),
($ H_v^"pw"times $), ($ (M_"solute")/(rho_"solvent") $),
($ (M_"solute")/(M_"solvent") $),
($ 1 $),
( $ (M_"solute")/(R T rho_"solvent") $),
($ H_v^"cc"times $), ($ R T$),
($ (R T rho_"solvent")/(M_"solvent") $),
($ (R T rho_"solvent")/(M_"solute") $),
($ 1 $),
)
```
Suppose now you want to remove a column. You have to go through each and every positional argument and check that everything lines up where its meant to. You could check that the output is correct in the preview window, but for complicated maths like shown above, the task is no easier. All of this is without complicating factors like rowspans or colspans (*shudder*) and their associated hlines or vlines. All these problems arrise because we have to chose the order in which we enter information - by row or by column. In Typst, entry is done in row-major (that is, we must fill a row before starting the next). This is useful for cases where you want to remove a row, but removing a row is perhaps done more correctly by removing it from the dataset in the first place.
# Column-major definitions
Refusing to take the L on the problems listed above, I set out to create a function that would translate column-major into row-major. I also wanted to make an easy way of relating the column definitions to how the data is actually laid out. Because I don't want to make life any easier, I wanted nested columns (children) to be grouped with their parent. Lastly, I wanted per-column variables (fill, align, width, gutter) to be grouped together too, plus inheritence. The design I came up with ended up looking like this:
```typ
#let example = (
(
key: "date",
display: [Date],
// fill: bg-fill-1,
// align: left,
width: 5em,
gutter: 0.5em,
),
(
key: "particulars",
display: text(tracking: 5pt)[Particulars],
width: 1fr,
gutter: 0.5em,
),
(
key: "ledger",
display: [Ledger],
// fill: bg-fill-2,
width: 2cm,
// align: center,
gutter: 0.5em,
),
(
key: "amount",
display: align(center)[Amount],
// fill: bg-fill-1,
gutter: 0.5em,
hline: arguments(stroke: booktabs.lightrule),
children: (
(
key: "unit",
display: align(left)[£],
width: 5em,
align: right,
vline: arguments(stroke: booktabs.lightrule),
gutter: 0em,
),
(
key: "decimal",
display: align(right, text(number-type: "old-style")[.00]),
width: 2em,
// align: left
),
)
),
(
key: "total",
display: align(center)[Total],
gutter: 0.5em,
hline: arguments(stroke: booktabs.lightrule),
children: (
(
key: "unit",
display: align(left)[£],
width: 5em,
align: right,
vline: arguments(stroke: booktabs.lightrule),
gutter: 0em,
),
(
key: "decimal",
display: align(right, text(number-type: "old-style")[.00]),
width: 2em,
align: left
),
)
),
)
```
and I want to give it the information in the following form:
```typ
#let data = (
(
date: [00/11/1234],
particulars: lorem(05),
ledger: [JRS123] + booktabs.footnotes.make[Hello World],
amount: (unit: $100$, decimal: $00$),
total: (unit: $99$, decimal: $00$),
),
)*7 +(
(
date: [01/09/1994],
particulars: [Just buying something extra this week before I run out of stuff],
ledger: [JRS123] + booktabs.footnotes.make[Special reference because it has a label],
amount: (unit: $12,222$, decimal: $99$),
total: (unit: $99$, decimal: $00$),
),
)
```
## Recursion
The first step towards implementing this is to deal with nested columns. There isn't a limit on how deep these nests can be (outside of hardware limitations), so this task (and most that follow) will be accomplished using recursion. Recursive functions are functions that end up calling themselves in some circumstances. In our case, we are going to go down each rabit hole, and record the depth of each column aswell as a recursive count of how many child elements it has. Finally, we will also want to know what the maximum depth is a bit later on, so we may aswell calculate that now.
```typ
#let sanitize-input(columns, depth: 0, max-depth: 1, length: 0) = {
// For every column
for (key, entry) in columns.enumerate() {
// if it has children
if "children" in entry {
// Recurse
let (children, child-depth, child-length) = sanitize-input(
entry.children,
depth: depth + 1,
max-depth: max-depth + 1
)
// record the recursive length
columns.at(key).insert("length", child-length)
columns.at(key).children = children
length += child-length
// Keep track of the deepest yet seen rabit hole
max-depth = calc.max(max-depth, child-depth)
// Bottom of the rabit hole, must have a length of 1
} else {
length += 1
columns.at(key).insert("length", 1)
}
// In all cases, keep track of depth
columns.at(key).insert("depth", depth)
}
// Pass the results on
return (columns, max-depth, length)
}
```
All this function does is go through, column by column, row by row, and calculates depths, recursive lengths, and keeps a track of the maximum depth it has come across. We can use this information to build the header:
```typ
#let build-header(columns, max-depth: 1, start: 0) = {
// For every column
for entry in columns {
// Make a cell that spans its recusive length (and limit rowspan if it has children)
(table.cell(
x: start,
y: entry.depth,
rowspan: if entry.length == 1 {max-depth - entry.depth} else {1},
colspan: entry.length,
// Header cells should be horizon aligned. Ideally it should default to `start`
// but I've shadowed that variable.
align: horizon + entry.at("align", default: left),
entry.display
),)
// If it has nested columns, build those too.
// NOTE: Return values are collated using automatic array joining!
if "children" in entry {
build-header(
entry.children,
max-depth: max-depth,
start: start // Pass along
)
}
// If it has a hline, add it under the cell
if ("hline" in entry){
(
table.hline(
y: entry.depth + 1,
start: start,
end: start + entry.length,
..entry.hline
),
)
}
if ("vline" in entry){ (table.vline(x: start + 1, ..entry.vline),) }
// Keep track of which column we are in. This could be precalculated.
start += entry.length
}
}
```
At this point, we are just about ready to start rendering this table, but if you remember those inherited values I mentioned above (fill, align, widith, gutter), we still need to calculate those and have them ready in a data structure that typst can use. Let's implement a general solution which takes the parameter name, a boolean for whether the value should be inherited by its children, and what it should default to if its missing.
```typ
#let recurse-columns(columns, key, default: auto, inherit: true) = {
// For every column
for child in columns {
// If it has children, recurse. If we should inherit, update the default.
if "children" in child {
recurse-columns(
child.children,
key,
inherit: inherit,
default: {
if inherit {child.at(key, default: default)} else {default}
}
)
} else {
// Bottom of rabbit hole: fetch the value (or default) and array join
// everything together
(child.at(key, default: default),)
}
}
}
```
Time to put all of this together into a neat function:
```typ
#let make(
columns: (),
toprule: toprule,
midrule: midrule,
bottomrule: bottomrule,
..args
) = {
// Calculate those useful values I mentioned earlier
let (columns, max-depth, length) = sanitize-input(columns)
table(
stroke: none,
fill: recurse-columns(columns, "fill", default: none),
align: recurse-columns(columns, "align", default: start),
column-gutter: recurse-columns(columns, "gutter", default: 0em),
columns: recurse-columns(columns, "width"),
table.header(
table.hline(stroke: toprule),
..build-header(columns, max-depth: max-depth),
table.hline(stroke: midrule, y: max-depth),
),
..args,
table.hline(stroke: bottomrule)
)
}
```
## Data
Out of this we get a beautiful table, but we still need to enter in the data manually, so lets automate that by creating another recursive function to traverse the columns and the data, and to figure out what needs to be output.
```typ
#let recurse-data(columns, data) = {
// For every column
for column in columns {
// Handle nested columns
if ("children" in column){
recurse-data(
column.children,
// If the parent column has a key, lets assume that its not a mistake, and
// lets use this to slice the data before we pass it onto the child columns.
// If the key is missing, from the data, lets assume it has been removed from
// the data set
if ("key" in column){
data.at(column.key, default: (:))
} else {
data
}
)
} else { // Bottom of the rabbit hole
// Return the data, but if it doesn't exist, return empty content instead so
// we don't mess up our alignments.
// Collate returned values using joined arrays.
if "key" in column {
(data.at(column.key, default: []),)
} else {
([],)
}
}
}
}
```
and lets update `make` so we can put this new function to work. While we are at it, lets allow the user to specify a hline that gets put between rows inside the table body, as this is the best chance we are going to get to make this a smooth thing to do.
```typ
#let make(
columns: (),
data: (), // ADDED
hline: none, // ADDED
toprule: toprule,
midrule: midrule,
bottomrule: bottomrule,
..args
) = {
// Calculate those useful values I mentioned earlier
let (columns, max-depth, length) = sanitize-input(columns, depth: 0)
// footnotes.clear() +
table(
stroke: none,
fill: recurse-columns(columns, "fill", default: none),
align: recurse-columns(columns, "align", default: start),
column-gutter: recurse-columns(columns, "gutter", default: 0em),
columns: recurse-columns(columns, "width"),
table.header(
table.hline(stroke: toprule),
..build-header(columns, max-depth: max-depth),
table.hline(stroke: midrule, y: max-depth),
),
..args,
..( // --- ADDED -------------------------------------->
for entry in data{
recurse-data(columns, entry)
if hline != none {(hline,)}
}
), // <-------------------------------------- ADDED ---
table.hline(stroke: bottomrule)
)
}
```
## Tablenotes
Finally, sometimes we are going to want to attach notes to some of the data we show in our tables. You might consider using `#footnote` however this adds it to the bottom of the page instead of the bottom of the table, which puts distance between the asterix and your words. After all, notes are meant to make the table easier to read, not more difficult, so lets fix that.
Ultimately, tables notes are a combination of two things: a mark at the location of the annotated content, and then at the end of the table, an ordered list with both the mark and the annotation itself. These can be stored in a stateful array, so lets define one (aswell as some helper functions). We want to keep track of an array of content, and the numbering function used to display the mark. We will also want a quick function to clear the list of annotations so we don't end up capturing another tables annotations.
```typ
// I want my argument names to be intuitive, but these sometimes shadow
// important functions, so lets copy them first.
#let std-state = state
#let std-numbering = numbering
// This will store an array of content
#let state = std-state("__booktabs:footnote", ())
#let clear() = state.update(())
// This will store the numbering function
#let numbering = std-state("__booktabs:numbering", "a")
#let set-numbering(new) = numbering.update(new)
```
When we make the footnote, all we need is the corresponding mark. Let's assume that an annotation is numbered based on its order (pretty sensible), and the numbering function won't change between creating the mark and rendering the footnote at the end of the table (somewhat sensible, but lets just say that anything else is outside the scope of this work).
```typ
// as we are rendering the mark before actually storing it, we offset the length of the array by 1.
// I had tried doing it the other way arround, but ran into convergence problems and didn't pursue it much further.
#let make-numbering() = context std-numbering(numbering.get(), state.get().len() + 1)
#let make( body) = {
// Weak horizontal space collapses preceding space, and is followed by a narrow space
// This is so the citation always "hugs" whatever comes before it. This might not be
// appropriate for RTL texts.
h(0em, weak: true) + sym.space.narrow + super(make-numbering())
state.update(it=>{it.push(body);it})
}
```
To render them, we get the state value inside a context block, map the key and the value of each entry into content, and then join that array of content (with an oxford comma).
```typ
#let display-numbering(key) = super(context std-numbering(numbering.get(), key + 1))
#let display-list = context {
state.get()
.enumerate()
.map( ((key, value)) => box[#display-numbering(key) #value]) // Box prevents breaking (perhaps not the best idea)
.join(", ", last: ", and ")
}
```
Lastly, and only because I have several types of tables but I want the tablenotes to be drawn consistently, I've made a helper function to style the footnotes by using some set rules and collapsing some space above it
```typ
#let display-style(notes) = {
v(-0.5em)
set text(0.888em)
set block(spacing: 0.5em)
set par(leading: 0.5em)
align(start, notes)
}
```
Lets do the same as what we did when adding in data, and add these functions to our table `make` definition.
```typ
#let make(
columns: (),
data: (),
hline: none,
toprule: toprule,
midrule: midrule,
bottomrule: bottomrule,
notes: footnotes.display-list, // ADDED
..args
) = {
let (columns, max-depth, length) = sanitize-input(columns, depth: 0)
footnotes.clear() + table( // ADDED
stroke: none,
fill: recurse-columns(columns, "fill", default: none),
align: recurse-columns(columns, "align", default: start),
column-gutter: recurse-columns(columns, "gutter", default: 0em),
columns: recurse-columns(columns, "width"),
table.header(
table.hline(stroke: toprule),
..build-header(columns, max-depth: max-depth),
table.hline(stroke: midrule, y: max-depth),
),
..args,
..(
for entry in data{
recurse-data(columns, entry)
if hline != none {(hline,)}
}
),
table.hline(stroke: bottomrule)
) + if (notes != none) {footnotes.display-style(notes)} // ADDED
}
```
# Further work
For each of "fill", "gap", "width", and "align", we are recursing the columns array anew every time. It would be more sensible to collect this information right at the start in the `sanitize-input` function, however I haven't spent any time on a solution. A similar fact is true with respect to the displaying of data: the columns array is recursively read for each row of data, which is pretty wasteful.
Currently, the column gutters need to be specified manually as I couldn't find a satisfying heuristic for determining the column gutter based on the difference in depths of 2 adjacent columns.
One of the driving forces (outside of a looming deadline for my thesis submission) is that this is a first step towards aligning a column's content by decimal point (like the `S` column type in LaTeX).
Some missing features that would make for excellent quality tables: Sparklines (if we are taking data as a parameter, we might aswell let it be put to good use). Because we now know how long the header is, and how many rows of data we are showing, we have enough information to construct a separate show rule for the header and the body (which previously wasn't possible).
Lastly, while this was pretty fun to make and would probably make for a useful package, I haven't got any interest in maintaining a package for it. Hopefully someone will pick up the task, and if they do, I'll add a link to it's Typst Universe page at the top.
|
https://github.com/jrihon/multi-bibs | https://raw.githubusercontent.com/jrihon/multi-bibs/main/chapters/02_chapter/methods.typ | typst | MIT License | #import "../../lib/multi-bib.typ": *
#import "bib_02_chapter.typ": biblio
== Methods
#lorem(50)
We did the method of _Sega et al_ #mcite(("Sega2011sixring"), biblio).
This lib package is the absolute best !
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/TA/Fall%202023/Math%20314/Assignment%205/Assignment%205%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 curl = $op("curl") thin$
#let vect(symbol) = $upright(bold(symbol))$
#let anglevec(body) = { $lr(angle.l body angle.r)$ }
= Question 1
== Statement
Let $C$ be the positively oriented square with vertices $(0,0)$, $(3,0)$, $(3,3)$, $(0,3)$. Use Green's Theorem to evaluate the line integral $integral_C 5 y^2 x dif x + 5 x^2 y dif y$.
== Solution
Positive orientation for curves means that as you walk along the curve the interior of the curve will be on your left. In our case this means the square is walked along in a counter-clockwise fashion.
Since Green's Theorem requires positive orientation we can apply it directly, first let us compute the curl of this vector field.
$
curl(5 y^2 x, 5x^2 y)
=
(diff (5x^2 y))/(diff x)
-
(diff (5y^2 x))/(diff y)
=
10 x y
-
10 x y
=
0
$
since this is zero we get
$
integral_C 5 y^2 x dif x + 5 x^2 y dif y
=
integral.double_D curl (5 y^2 x, 5x^2 y) dif A
=
integral.double_D 0 dif A
=
0
$
///
///
///
= Question 2
== Statement
Find a parametrization of the curve $x^(2/3) + y^(2/3) = 1$ and use it to find its area.
== Solution
By looking at the equation of this curve we can quickly see that it is very similar to the equation of a circle, which is $x^2 + y^2 = 1$. Due to the similarity we see that if $x = a^3$ and $y = b^3$ for some $a,b$ then
$
x^(2/3) + y^(2/3) = 1 => a^2 + b^2 = 1
$
and so we can parametrize by setting $a = cos(t)$ and $b = sin(t)$ giving us $x = cos^3(t)$ and $y = sin^3(t)$.
By this parametrization we can now find the integral of this
|
|
https://github.com/Tran-Thu-Le/tybank | https://raw.githubusercontent.com/Tran-Thu-Le/tybank/main/readme.md | markdown | # Tybank: A Typst package for creating multiple choices exam
**Author:** <NAME>
**Version:** 0.0.1
## Channel log
- Add variation table (done)
- Add plot (done)
- align(right) figure
- filter questions based on tags
- add other types of questions
- simplify data structure of each question in the bank
- add license
- reorganize repository
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/return-01.typ | typst | Other | // Test return with joining.
#let f(x) = {
"a"
if x == 0 {
return "b"
} else if x == 1 {
"c"
} else {
"d"
return
"e"
}
}
#test(f(0), "b")
#test(f(1), "ac")
#test(f(2), "ad")
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/smartquotes-on-newline.typ | typst | Apache License 2.0 | // Test that smart quotes are inferred correctly across newlines.
---
"test"#linebreak()"test"
"test"\
"test"
|
https://github.com/MultisampledNight/flow | https://raw.githubusercontent.com/MultisampledNight/flow/main/src/gfx/stub/draw.typ | typst | MIT License | #let set-style(..args) = none
#let set-origin(..args) = none
#let scale(..args) = none
#let group(..args) = none
#let line(..args) = none
#let rect(..args) = none
#let circle(..args) = none
#let arc(..args) = none
#let content(..args) = none
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/199.%20richnow.html.typ | typst | richnow.html
How People Get Rich Now
April 2021Every year since 1982, Forbes magazine has published a list of the
richest Americans. If we compare the 100 richest people in 1982 to
the 100 richest in 2020, we notice some big differences.In 1982 the most common source of wealth was inheritance. Of the
100 richest people, 60 inherited from an ancestor. There were 10
du Pont heirs alone. By 2020 the number of heirs had been cut in
half, accounting for only 27 of the biggest 100 fortunes.Why would the percentage of heirs decrease? Not because inheritance
taxes increased. In fact, they decreased significantly during this
period. The reason the percentage of heirs has decreased is not
that fewer people are inheriting great fortunes, but that more
people are making them.How are people making these new fortunes? Roughly 3/4 by starting
companies and 1/4 by investing. Of the 73 new fortunes in 2020, 56
derive from founders' or early employees' equity (52 founders, 2
early employees, and 2 wives of founders), and 17 from managing
investment funds.There were no fund managers among the 100 richest Americans in 1982.
Hedge funds and private equity firms existed in 1982, but none of
their founders were rich enough yet to make it into the top 100.
Two things changed: fund managers discovered new ways to generate
high returns, and more investors were willing to trust them with
their money.
[1]But the main source of new fortunes now is starting companies, and
when you look at the data, you see big changes there too. People
get richer from starting companies now than they did in 1982, because
the companies do different things.In 1982, there were two dominant sources of new wealth: oil and
real estate. Of the 40 new fortunes in 1982, at least 24 were due
primarily to oil or real estate. Now only a small number are: of
the 73 new fortunes in 2020, 4 were due to real estate and only 2
to oil.By 2020 the biggest source of new wealth was what are sometimes
called "tech" companies. Of the 73 new fortunes, about 30 derive
from such companies. These are particularly common among the richest
of the rich: 8 of the top 10 fortunes in 2020 were new fortunes of
this type.Arguably it's slightly misleading to treat tech as a category.
Isn't Amazon really a retailer, and Tesla a car maker? Yes and no.
Maybe in 50 years, when what we call tech is taken for granted, it
won't seem right to put these two businesses in the same category.
But at the moment at least, there is definitely something they share
in common that distinguishes them. What retailer starts AWS? What
car maker is run by someone who also has a rocket company?The tech companies behind the top 100 fortunes also form a
well-differentiated group in the sense that they're all companies
that venture capitalists would readily invest in, and the others
mostly not. And there's a reason why: these are mostly companies
that win by having better technology, rather than just a CEO who's
really driven and good at making deals.To that extent, the rise of the tech companies represents a qualitative
change. The oil and real estate magnates of the 1982 Forbes 400
didn't win by making better technology. They won by being really
driven and good at making deals.
[2]
And indeed, that way of
getting rich is so old that it predates the Industrial Revolution.
The courtiers who got rich in the (nominal) service of European
royal houses in the 16th and 17th centuries were also, as a rule,
really driven and good at making deals.People who don't look any deeper than the Gini coefficient look
back on the world of 1982 as the good old days, because those who
got rich then didn't get as rich. But if you dig into how they
got rich, the old days don't look so good. In 1982, 84% of the
richest 100 people got rich by inheritance, extracting natural
resources, or doing real estate deals. Is that really better than
a world in which the richest people get rich by starting tech
companies?Why are people starting so many more new companies than they used
to, and why are they getting so rich from it? The answer to the
first question, curiously enough, is that it's misphrased. We
shouldn't be asking why people are starting companies, but why
they're starting companies again.
[3]In 1892, the New York Herald Tribune compiled a list of all the
millionaires in America. They found 4047 of them. How many had
inherited their wealth then? Only about 20%, which is less than the
proportion of heirs today. And when you investigate the sources of
the new fortunes, 1892 looks even more like today. <NAME>
found that "many of the richest ... gained their initial edge from
the new technology of mass production."
[4]So it's not 2020 that's the anomaly here, but 1982. The real question
is why so few people had gotten rich from starting companies in
1982. And the answer is that even as the Herald Tribune's list was
being compiled, a wave of consolidation
was sweeping through the
American economy. In the late 19th and early 20th centuries,
financiers like <NAME> combined thousands of smaller companies
into a few hundred giant ones with commanding economies of scale.
By the end of World War II, as <NAME> writes, "the major
sectors of the economy were either organized as government-backed
cartels or dominated by a few oligopolistic corporations."
[5]In 1960, most of the people who start startups today would have
gone to work for one of them. You could get rich from starting your
own company in 1890 and in 2020, but in 1960 it was not really a
viable option. You couldn't break through the oligopolies to get
at the markets. So the prestigious route in 1960 was not to start
your own company, but to work your way up the corporate ladder at
an existing one.
[6]Making everyone a corporate employee decreased economic inequality
(and every other kind of variation), but if your model of normal
is the mid 20th century, you have a very misleading model in that
respect. <NAME>'s economy turned out to be just a phase, and
starting in the 1970s, it began to break up.Why did it break up? Partly senescence. The big companies that
seemed models of scale and efficiency in 1930 had by 1970 become
slack and bloated. By 1970 the rigid structure of the economy was
full of cosy nests that various groups had built to insulate
themselves from market forces. During the Carter administration the
federal government realized something was amiss and began, in a
process they called "deregulation," to roll back the policies that
propped up the oligopolies.But it wasn't just decay from within that broke up J. P. Morgan's
economy. There was also pressure from without, in the form of new
technology, and particularly microelectronics. The best way to
envision what happened is to imagine a pond with a crust of ice on
top. Initially the only way from the bottom to the surface is around
the edges. But as the ice crust weakens, you start to be able to
punch right through the middle.The edges of the pond were pure tech: companies that actually
described themselves as being in the electronics or software business.
When you used the word "startup" in 1990, that was what you meant.
But now startups are punching right through the middle of the ice
crust and displacing incumbents like retailers and TV networks and
car companies.
[7]But though the breakup of <NAME>'s economy created a new world
in the technological sense, it was a reversion to the norm in the
social sense. If you only look back as far as the mid 20th century,
it seems like people getting rich by starting their own companies
is a recent phenomenon. But if you look back further, you realize
it's actually the default. So what we should expect in the future
is more of the same. Indeed, we should expect both the number and
wealth of founders to grow, because every decade it gets easier to
start a startup.Part of the reason it's getting easier to start a startup is social.
Society is (re)assimilating the concept. If you start one now, your
parents won't freak out the way they would have a generation ago,
and knowledge about how to do it is much more widespread. But the
main reason it's easier to start a startup now is that it's cheaper.
Technology has driven down the cost of both building products and
acquiring customers.The decreasing cost of starting a startup has in turn changed the
balance of power between founders and investors. Back when starting
a startup meant building a factory, you needed investors' permission
to do it at all. But now investors need founders more than founders
need investors, and that, combined with the increasing amount of
venture capital available, has driven up valuations.
[8]So the decreasing cost of starting a startup increases the number
of rich people in two ways: it means that more people start them,
and that those who do can raise money on better terms.But there's also a third factor at work: the companies themselves
are more valuable, because newly founded companies grow faster than
they used to. Technology hasn't just made it cheaper to build and
distribute things, but faster too.This trend has been running for a long time. IBM, founded in 1896,
took 45 years to reach a billion 2020 dollars in revenue.
Hewlett-Packard, founded in 1939, took 25 years. Microsoft, founded
in 1975, took 13 years. Now the norm for fast-growing companies is
7 or 8 years.
[9]Fast growth has a double effect on the value of founders' stock.
The value of a company is a function of its revenue and its growth
rate. So if a company grows faster, you not only get to a billion
dollars in revenue sooner, but the company is more valuable when
it reaches that point than it would be if it were growing slower.That's why founders sometimes get so rich so young now. The low
initial cost of starting a startup means founders can start young,
and the fast growth of companies today means that if they succeed
they could be surprisingly rich just a few years later.It's easier now to start and grow a company than it has ever been.
That means more people start them, that those who do get better
terms from investors, and that the resulting companies become more
valuable. Once you understand how these mechanisms work, and that
startups were suppressed for most of the 20th century, you don't
have to resort to some vague right turn the country took under
Reagan to explain why America's Gini coefficient is increasing. Of
course the Gini coefficient is increasing. With more people starting
more valuable companies, how could it not be?Notes[1]
Investment firms grew rapidly after a regulatory change by
the Labor Department in 1978 allowed pension funds to invest in
them, but the effects of this growth were not yet visible in the
top 100 fortunes in 1982.[2]
<NAME> deserves mention as an exception. Though
really driven and good at making deals, he was also the first to
figure out how to use fracking to get natural gas out of shale.[3]
When I say people are starting more companies, I mean the
type of company meant to grow
very big. There has actually been a
decrease in the last couple decades in the overall number of new
companies. But the vast majority of companies are small retail and
service businesses. So what the statistics about the decreasing
number of new businesses mean is that people are starting fewer
shoe stores and barber shops.People sometimes get confused when they see a graph labelled
"startups" that's going down, because there are two senses of the
word "startup": (1) the founding of a company, and (2) a particular
type of company designed to grow big fast. The statistics mean
startup in sense (1), not sense (2).[4]
<NAME>. "Great Fortunes of the Gilded Age." NBER Working
Paper 14555, 2008.[5]
<NAME>. Land of Promise. HarperCollins, 2012.It's also likely that the high tax rates in the mid 20th century
deterred people from starting their own companies. Starting one's
own company is risky, and when risk isn't rewarded, people opt for
safety instead.But it wasn't simply cause and effect. The oligopolies and high tax
rates of the mid 20th century were all of a piece. Lower taxes are
not just a cause of entrepreneurship, but an effect as well: the
people getting rich in the mid 20th century from real estate and
oil exploration lobbied for and got huge tax loopholes that made
their effective tax rate much lower, and presumably if it had been
more common to grow big companies by building new technology, the
people doing that would have lobbied for their own loopholes as
well.[6]
That's why the people who did get rich in the mid 20th century
so often got rich from oil exploration or real estate. Those were
the two big areas of the economy that weren't susceptible to
consolidation.[7]
The pure tech companies used to be called "high technology" startups.
But now that startups can punch through the middle of the ice crust,
we don't need a separate name for the edges, and the term "high-tech"
has a decidedly retro
sound.[8]
Higher valuations mean you either sell less stock to get a
given amount of money, or get more money for a given amount of
stock. The typical startup does some of each. Obviously you end up
richer if you keep more stock, but you should also end up richer
if you raise more money, because (a) it should make the company
more successful, and (b) you should be able to last longer before
the next round, or not even need one. Notice all those shoulds
though. In practice a lot of money slips through them.It might seem that the huge rounds raised by startups nowadays
contradict the claim that it has become cheaper to start one. But
there's no contradiction here; the startups that raise the most are
the ones doing it by choice, in order to grow faster, not the ones
doing it because they need the money to survive. There's nothing
like not needing money to make people offer it to you.You would think, after having been on the side of labor in its fight
with capital for almost two centuries, that the far left would be
happy that labor has finally prevailed. But none of them seem to
be. You can almost hear them saying "No, no, not that way."[9]
IBM was created in 1911 by merging three companies, the most
important of which was <NAME>'s Tabulating Machine Company,
founded in 1896. In 1941 its revenues were $60 million.Hewlett-Packard's revenues in 1964 were $125 million.Microsoft's revenues in 1988 were $590 million.Thanks to <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, and <NAME> for reading drafts of this, and to <NAME> for growth data.
|
|
https://github.com/bigskysoftware/hypermedia-systems-book | https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/ch10-json-data-apis.typ | typst | Other | #import "lib/definitions.typ": *
== JSON Data APIs
So far we have been focusing on using hypermedia to build Hypermedia-Driven
Applications. In doing so we are following and taking advantage of the native
network architecture of the web, and building a RESTful system, in the original
sense of that term.
#index[JSON][Data API]
However, today, we should acknowledge that many web applications are often _not_ built
using this approach. Instead, they use a Single Page Application front end
library such as React to build their application, and they interact with the
server via a JSON API. This JSON API almost never uses hypermedia concepts.
Rather JSON APIs tend to be
_Data APIs_, that is, an API that simply returns structured domain data to the
client without any hypermedia control information. The client itself must know
how to interpret the JSON Data: what end points are associated with the data,
how certain fields should be interpreted, and so on.
Now, believe it or not, we _have_ been creating an API for Contact.app.
This may sound confusing to you: an API? We have just been creating a web
application, with handlers that just return HTML.
How is that an API?
It turns out that Contact.app is, indeed, providing an API. It just happens to
be a _hypermedia_ API that a _hypermedia client_, that is, a browser,
understands. We are building an API for the browser to interact with over HTTP,
and, thanks to the magic of HTML and hypermedia, the browser doesn’t need to
know anything about our hypermedia API beyond an entry point URL: all the
actions and display information comes, self-contained, within the HTML
responses.
Building RESTful web applications like this is so natural and simple that you
might not think of it as an API at all, but we assure you, it is.
=== Hypermedia APIs & JSON Data APIs <_hypermedia_apis_json_data_apis>
So, we have a hypermedia API for Contact.app. Should we include a Data API for
Contact.app as well?
#index[Data API]
Sure! The existence of a hypermedia API _in no way means_ that you can’t _also_ have
a Data API. In fact, this is a common situation in traditional web applications:
there is the "web application" that is entered through that entry point URL, say
`https://mywebapp.example.com/`. And there is also a _separate_
JSON API that is accessible through another URL, perhaps
`https://api.mywebapp.example.com/v1`.
This is a perfectly reasonable way to split up the hypermedia interface to your
application and the Data API you provide to other, non-hypermedia clients.
Why would you want to include a Data API along with a hypermedia API? Well,
because _non-hypermedia clients_ might also want to interact with your
application as well.
For example:
- Perhaps you have a mobile application that isn’t built using Hyperview. That
application will need to interact with your server somehow, and using the
existing HTML API would almost certainly be a poor fit! You want programmatic
access to your system via a Data API, and JSON is a natural choice for this.
- Perhaps you have an automated script that needs to interact with the system on a
regular basis. For example, maybe we have a bulk-import job that runs nightly,
and needs to import/sync thousands of contacts. While it would be possible to
script this against the HTML API, it would also be annoying: parsing HTML in
scripts is error prone and tedious. It would be better to have a simple JSON API
for this use case.
- Perhaps there are 3rd party clients who wish to integrate with your system’s
data in some way. Maybe a partner wants to synchronize data nightly. As with the
bulk-import example, this isn’t a great use case for an HTML-based API, and it
would make more sense to provide something more amenable to scripting.
For all of these use cases, a JSON Data API makes sense: in each case the API is
not being consumed by a hypermedia client, so presenting an HTML-based
hypermedia API would be inefficient and complicated for the client to deal with.
A simple JSON Data API fits the bill for what we want and, as always, we
recommend using the right tool for the job.
#sidebar["What!?! You Want Me To Parse HTML!?!"][ A confusion we often run into in online discussions when we advocate a
hypermedia approach to building web applications is that people think we mean
that they should parse the HTML responses from the server, and then dump the
data into their SPA framework or mobile applications.
This is, of course, silly.
What we mean, instead, is that you should consider using a hypermedia API _with a hypermedia client_,
like the browser, interpreting the hypermedia response itself and presenting it
to the user. A hypermedia API can’t simply be welded on top of an existing SPA
approach. It requires a sophisticated hypermedia client such as the browser to
be consumed effectively.
If you are writing code to tease apart your hypermedia only to then treat as
data to feed into a client-side model, you are probably doing it wrong. ]
==== Differences Between Hypermedia APIs & Data APIs <_differences_between_hypermedia_apis_data_apis>
Let’s accept for a moment that we _are_ going to have a Data API for our
application, in addition to our hypermedia API. At this point, some developers
may be wondering: why have both? Why not have a single API, the JSON Data API,
and have multiple clients use this one API to communicate with it?
Isn’t it redundant to have both types of APIs for our application?
This is a reasonable point: we do advocate having multiple APIs to your web
application if necessary and, yes, this may lead to some redundancy in code.
However, there are distinct advantages to both sorts of APIs and, even more so,
distinct requirements for both sorts of APIs.
By supporting both of these types of APIs separately you can get the strengths
of both, while keeping their varying styles of code and infrastructure needs
cleanly split out.
Let’s contrast the needs of JSON APIs with Hypermedia APIs:
#align(
center,
)[#table(
columns: 2, align: (col, row) => (auto, auto,).at(col), inset: 6pt, [JSON API Needs],
[Hypermedia API], [It must remain stable over time: you cannot change the API willy-nilly or you
risk breaking clients that use the API and expect certain end points to behave
in certain ways.], [There is no need to remain stable over time: all URLs are discovered via HTML
responses, so you can be much more aggressive in changing the shape of a
hypermedia API.], [It must be versioned: related to the first point, when you do make a major
change, you need to version the API so that clients that are using the old API
continue to work.],
[Versioning is not an issue, another strength of the hypermedia approach. ], [It should be rate limited: since data APIs are often used by other clients, not
just your own internal web application, requests should be rate limited, often
by user, in order to avoid a single client overloading the system.], [Rate limiting probably isn’t as important beyond the prevention of Distributed
Denial of Service (DDoS) attacks.], [It should be a general API: since the API is for _all_ clients, not just for
your web application, you should avoid specialized end points that are driven by
your own application needs. Instead, the API should be general and expressive
enough to satisfy as many potential client needs as possible.],
[The API can be _very specific_ to your application needs: since it is designed
only for your particular web application, and since the API is discovered
through hypermedia, you can add and remove highly tuned end points for specific
features or optimization needs in your application.], [Authentication for these sorts of API is typically token based, which we will
discuss in more detail later.], [Authentication is typically managed through a session cookie established by a
login page.],
)]
These two different types of APIs have different strengths and needs, so it
makes sense to use both. The hypermedia approach can be used for your web
application, allowing you to specialize the API for the "shape" of your
application. The Data API approach can be used for other, non-hypermedia clients
like mobile, integration partners, etc.
Note that by splitting these two APIs apart, you reduce the pressure to
constantly change a general Data API to address application needs. Your Data API
can focus on remaining stable and reliable, rather than requiring a new version
with every added feature.
This is the key advantage of splitting your Data API from your Hypermedia API.
#sidebar[JSON Data APIs vs JSON "REST" APIs][
#index[REST API]
Unfortunately, today, for historical reasons, what we are calling JSON Data APIs
are often referred to as "REST APIs" in the industry. This is ironic, because,
by any reasonable reading of Roy Fielding’s work defining what REST means, the
vast majority of JSON APIs are _not_
RESTful. Not even close.
#blockquote(
attribution: [<NAME>,
https:\/\/roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven],
)[
I am getting frustrated by the number of people calling any HTTP-based interface
a REST API. Today’s example is the SocialSite REST API. That is RPC. It screams
RPC. There is so much coupling on display that it should be given an X rating.
What needs to be done to make the REST architectural style clear on the notion
that hypertext is a constraint? In other words, if the engine of application
state (and hence the API) is not being driven by hypertext, then it cannot be
RESTful and cannot be a REST API. Period. Is there some broken manual somewhere
that needs to be fixed?
]
The story of how "REST API" came to mean "JSON APIs" in the industry is a long
and sordid one, and beyond the scope of this book. However, if you are
interested, you can refer to an essay by one of the authors of this book
entitled "How Did REST Come To Mean The Opposite of REST?" on the
#link(
"https://htmx.org/essays/how-did-rest-come-to-mean-the-opposite-of-rest/",
)[htmx website].
In this book we use the term "Data API" to describe these JSON APIs, while
acknowledging that many people in the industry will continue to call them "REST
APIs" for the foreseeable future.
]
=== Adding a JSON Data API To Contact.app <_adding_a_json_data_api_to_contact_app>
Alright, so how are we going to add a JSON Data API to our application? One
approach, popularized by the Ruby on Rails web framework, is to use the same URL
endpoints as your hypermedia application, but use the HTTP
`Accept` header to determine if the client wants a JSON representation or an
HTML representation. The HTTP `Accept` header allows a client to specify what
sort of Multipurpose Internet Mail Extensions (MIME) types, that is file types,
it wants back from the server: JSON, HTML, text and so on.
So, if the client wanted a JSON representation of all contacts, they might issue
a `GET` request that looks like this:
#figure(
caption: [A request for a JSON representation of all contacts],
)[ ```http
Accept: application/json
GET /contacts
``` ]
If we adopted this pattern then our request handler for `/contacts/`
would need to be updated to inspect this header and, depending on the value,
return a JSON rather than HTML representation for the contacts. Ruby on Rails
has support for this pattern baked into the framework, making it very easy to
switch on the requested MIME type.
Unfortunately, our experience with this pattern has not been great, for reasons
that should be clear given the differences we outlined between Data and
hypermedia APIs: they have different needs and often take on very different "shapes",
and trying to pound them into the same set of URLs ends up creating a lot of
tension in the application code.
Given the different needs of the two APIs and our experience managing multiple
APIs like this, we think separating the two, and, therefore, breaking the JSON
Data API out to its own set of URLs is the right choice. This will allow us to
evolve the two APIs separately from one another, and give us room to improve
each independently, in a manner consistent with their own individual strengths.
==== Picking a Root URL For Our API <_picking_a_root_url_for_our_api>
Given that we are going to split our JSON Data API routes out from our regular
hypermedia routes, where should we place them? One important consideration here
is that we want to make sure that we can version our API cleanly in some way,
regardless of the pattern we choose.
Looking around, a lot of places use a subdomain for their APIs, something like `https://api.mywebapp.example.com` and,
in fact, often encode versioning in the subdomain:
`https://v1.api.mywebapp.example.com`.
While this makes sense for large companies, it seems like a bit of overkill for
our modest little Contact.app. Rather than using subdomains, which are a pain
for local development, we will use sub-paths within the existing application:
- We will use `/api` as the root for our Data API functionality
- We will use `/api/v1` as the entry point for version 1 of our Data API
If and when we decide to bump the API version, we can move to `/api/v2`
and so on.
This approach isn’t perfect, of course, but it will work for our simple
application and can be adapted to a subdomain approach or various other methods
at a later point, when our Contact.app has taken over the internet and we can
afford a large team of API developers. :)
==== Our First JSON Endpoint: Listing All Contacts
#index[Data API][endpoint]
#index[JSON][endpoint]
Let’s add our first Data API endpoint. It will handle an HTTP `GET`
request to `/api/v1/contacts`, and return a JSON list of all contacts in the
system. In some ways it will look quite a bit like our initial code for the
hypermedia route `/contacts`: we will load all the contacts from the contacts
database and then render some text as a response.
We are also going to take advantage of a nice feature of Flask: if you simply
return an object from a handler, it will serialize (that is, convert) that
object into a JSON response. This makes it very easy to build simple JSON APIs
in flask!
#figure(caption: [A JSON data API to return all contacts])[ ```python
@app.route("/api/v1/contacts", methods=["GET"]) <1>
def json_contacts():
contacts_set = Contact.all()
contacts_dicts = [c.__dict__ for c in contacts_set] <2>
return {"contacts": contacts_dicts} <3>
``` ]
1. JSON API gets its own path, starting with `/api`.
2. Convert the contacts array into an array of simple dictionary (map) objects.
3. Return a dictionary that contains a `contacts` property of all the contacts.
This Python code might look a little foreign to you if you are not a Python
developer, but all we are doing is converting our contacts into an array of
simple name/value pairs and returning that array in an enclosing object as the `contacts` property.
This object will be serialized into a JSON response automatically by Flask.
With this in place, if we make an HTTP `GET` request to
`/api/v1/contacts`, we will see a response that looks something like this:
#figure(caption: [Some sample data from our API])[ ```json
{
"contacts": [
{
"email": "<EMAIL>",
"errors": {},
"first": "Carson",
"id": 2,
"last": "Gross",
"phone": "123-456-7890"
},
{
"email": "<EMAIL>",
"errors": {},
"first": "",
"id": 3,
"last": "",
"phone": ""
},
...
]
}
``` ]
So, you can see, we now have a way to get a relatively simple JSON
representation of our contacts via an HTTP request. Not perfect, but it’s a good
start. It’s certainly good enough to write some basic automated scripts against.
For example, you could use this Data API to:
- Move your contacts to another system on a nightly basis
- Back your contacts up to a local file
- Automate an email blast to your contacts
Having this small JSON Data API opens up a lot of automation possibilities that
would be messier to achieve with our existing hypermedia API.
==== Adding Contacts
Let’s move on to the next piece of functionality: the ability to add a new
contact. Once again, our code is going to look similar in some ways to the code
that we wrote for our normal web application. However, here we are also going to
see the JSON API and the hypermedia API for our web application begin to
obviously diverge.
In the web application, we needed a separate path, `/contacts/new` to host the
HTML form for creating a new contact. In the web application we made the
decision to issue a `POST` to that same path to keep things consistent.
In the case of the JSON API, there is no such path needed: the JSON API
"just is": it doesn’t need to provide any hypermedia representation for creating
a new contact. You simply know where to issue a `POST` to create a contact ---
likely through some documentation provided about the API --- and that’s it.
Because of that fact, we can put the "create" handler on the same path as the "list"
handler: `/api/v1/contacts`, but have it respond only to HTTP `POST` requests.
The code here is relatively straightforward: populate a new contact with the
information from the `POST` request, attempt to save it, and --- if it is not
successful --- show error messages. Here is the code:
#figure(
caption: [Adding contacts with our JSON API],
)[ ```python
@app.route("/api/v1/contacts", methods=["POST"]) <1>
def json_contacts_new():
c = Contact(None,
request.form.get('first_name'),
request.form.get('last_name'),
request.form.get('phone'),
request.form.get('email')) <2>
if c.save(): <3>
return c.__dict__
else:
return {"errors": c.errors}, 400 <4>
``` ]
1. This handler is on the same path as the first one for our JSON API, but handles `POST` requests.
2. We create a new Contact based on values submitted with the request.
3. We attempt to save the contact and, if successful, render it as a JSON object.
4. If the save is not successful, we render an object showing the errors, with a
response code of `400 (Bad Request)`.
In some ways this is similar to our `contacts_new()` handler from our web
application; we are creating the contact and attempting to save it. In other
ways it is very different:
- There is no redirection happening here on a successful creation, because we are
not dealing with a hypermedia client like the browser.
- In the case of a bad request, we simply return an error response code,
`400 (Bad Request)`. This is in contrast with the web application, where we
re-render the form with error messages in it.
These sorts of differences, over time, build up and make the idea of keeping
your JSON and hypermedia APIs on the same set of URLs less and less appealing.
==== Viewing Contact Details <_viewing_contact_details>
Next, let’s make it possible for a JSON API client to download the details for a
single contact. We will naturally use an HTTP `GET` for this functionality and
will follow the convention we established for our regular web application, and
put the path at
`/api/v1/contacts/<contact id>`. So, for example, if you want to see the details
of the contact with the id `42`, you would issue an HTTP `GET`
to `/api/v1/contacts/42`.
This code is quite simple:
#figure(caption: [Getting the details of a contact in JSON])[ ```python
@app.route("/api/v1/contacts/<contact_id>", methods=["GET"]) <1>
def json_contacts_view(contact_id=0):
contact = Contact.find(contact_id) <2>
return contact.__dict__ <3>
``` ]
1. Add a new `GET` route at the path we want to use for viewing contact details
2. Look the contact up via the id passed in through the path
3. Convert the contact to a dictionary, so it can be rendered as JSON response
Nothing too complicated: we look the contact up by the ID provided in the path
to the controller. We then render it as JSON. You have to appreciate the
simplicity of this code!
Next, let’s add updating and deleting a contact as well.
==== Updating & Deleting Contacts <_updating_deleting_contacts>
As with the create contact API endpoint, because there is no HTML UI to produce
for them, we can reuse the `/api/v1/contacts/<contact id>` path. We will use the `PUT` HTTP
method for updating a contact and the
`DELETE` method for deleting one.
Our update code is going to look nearly identical to the create handler, except
that, rather than creating a new contact, we will look up the contact by ID and
update its fields. In this sense we are just combining the code of the create
handler and the detail view handler.
#figure(
caption: [Updating a contact with our JSON API],
)[ ```python
@app.route("/api/v1/contacts/<contact_id>", methods=["PUT"]) <1>
def json_contacts_edit(contact_id):
c = Contact.find(contact_id) <2>
c.update(
request.form['first_name'],
request.form['last_name'],
request.form['phone'],
request.form['email']) <3>
if c.save(): <4>
return c.__dict__
else:
return {"errors": c.errors}, 400
``` ]
1. We handle `PUT` requests to the URL for a given contact.
2. Look the contact up via the id passed in through the path.
3. We update the contact’s data from the values included in the request.
4. From here on the logic is identical to the `json_contacts_create()`
handler.
Once again, thanks to the built-in functionality in Flask, simple to implement.
Let’s look at deleting a contact now. This turns out to be even simpler: as with
the update handler we are going to look up the contact by id, and then, well,
delete it. At that point we can return a simple JSON object indicating success.
#figure(caption: [Deleting a contact with our JSON API])[ ```python
@app.route("/api/v1/contacts/<contact_id>", methods=["DELETE"]) <1>
def json_contacts_delete(contact_id=0):
contact = Contact.find(contact_id)
contact.delete() <2>
return jsonify({"success": True}) <3>
``` ]
1. We handle `DELETE` requests to the URL for a given contact.
2. Look the contact up and invoke the `delete()` method on it.
3. Return a simple JSON object indicating that the contact was successfully
deleted.
And, with that, we have our simple little JSON Data API to live alongside our
regular web application, nicely separated out from the main web application, so
it can evolve separately as needed.
==== Additional Data API Considerations <_additional_data_api_considerations>
Now, we would have a lot more to do if we wanted to make this a production ready
JSON API. At minimum we would need to add:
- Rate limiting, important for any public-facing Data API to avoid abusive
clients.
- An authentication mechanism. (We don’t have one for our web application either!)
- Support for pagination of our contact data.
- Several small items, such as rendering a proper `404 (Not Found)`
response if someone makes a request with a contact id that doesn’t exist.
These topics are beyond the scope of this book, but we’d like to focus on one in
particular, authentication, in order to show the difference between our
hypermedia and JSON API. In order to secure our application we need to add _authentication_,
some mechanism for determining who a request is coming from, and also _authorization_,
determining if they have the right to perform the request.
We will set authorization aside for now and consider only authentication.
===== Authentication in web applications
#index[authentication]
In the HTML web application world, authentication has traditionally been done
via a login page that asks a user for their username (often their email) and a
password. This password is then checked against a database of (hashed) passwords
to establish that the user is who they say they are. If the password is correct,
then a _session cookie_ is established, indicating who the user is. This cookie
is then sent with every request that the user makes to the web application,
allowing the application to know which user is making a given request.
#sidebar[HTTP Cookies][
#index[HTTP][cookies]
HTTP Cookies are kind of a strange feature of HTTP. In some ways they violate
the goal of remaining stateless, a major component of the RESTful architecture:
a server will often use a session cookie as an index into state kept on the
server "on the side", such as a cache of the last action performed by the user.
]
Nonetheless, cookies have proven extremely useful and so people tend not to
complain about this aspect of them too much (We are not sure what our other
options would be here!) An interesting example of pragmatism gone (relatively)
right in web development.
In comparison with the standard web application approach to authentication, a
JSON API will typically use some sort of _token based_ authentication: an
authentication token will be established via a mechanism like OAuth, and that
authentication token will then be passed, often as an HTTP Header, with every
request that a client makes.
At a high level this is similar to what happens in normal web application
authentication: a token is established somehow and then that token is part of
every request. However, in practice, the mechanics tend to be wildly different:
- Cookies are part of the HTTP specification and can be easily
_set_ by an HTTP Server.
- JSON Authentication tokens, in contrast, often require elaborate exchange
mechanics like OAuth to be established.
These differing mechanics for establishing authentication are yet another good
reason for splitting up our JSON and hypermedia APIs.
==== The "Shape" of Our Two APIs <_the_shape_of_our_two_apis>
When we were building out our API, we noted that in many cases the JSON API
didn’t require as many end points as our hypermedia API did: we didn’t need a `/contacts/new` handler,
for example, to provide a hypermedia representation for creating contacts.
Another aspect of our hypermedia API to consider was the performance improvement
we made: we pulled the total contact count out to a separate endpoint and
implemented the "Lazy Load" pattern, to improve the perceived performance of our
application.
Now, if we had both our hypermedia and JSON API sharing the same paths, would we
want to publish this API as a JSON endpoint as well?
Maybe, but maybe not. This was a pretty specific need for our web application,
and, absent a request from a user of our JSON API, it doesn’t make sense to
include it for JSON consumers.
And what if, by some miracle, the performance issues with
`Contact.count()` that we were addressing with the Lazy Load pattern goes away?
Well, in our Hypermedia-Driven Application we can simply revert to the old code
and include the count directly in the request to
`/contacts`. We can remove the `contacts/count` endpoint and all the logic
associated with it. Because of the uniform interface of hypermedia, the system
will continue to work just fine.
But what if we had tied our JSON API and hypermedia API together, and published `/contacts/count` as
a supported end point for our JSON API? In that case we couldn’t simply remove
the endpoint: a (non-hypermedia) client might be relying on it.
Once again you can see the flexibility of the hypermedia approach and why
separating your JSON API out from your hypermedia API lets you take maximum
advantage of that flexibility.
==== The Model View Controller (MVC) Paradigm <_the_model_view_controller_mvc_paradigm>
One thing you may have noticed about the handlers for our JSON API is that they
are relatively simple and regular. Most of the hard work of updating data and so
forth is done within the contact model itself: the handlers act as simple
connectors that provide a go-between the HTTP requests and the model.
This is the ideal controller of the Model-View-Controller (MVC) paradigm that
was so popular in the early web: a controller should be "thin", with the model
containing the majority of the logic in the system.
#sidebar[The Model View Controller pattern][
#index[Model-View-Controller (MVC)]
The Model View Controller design pattern is a classic architectural pattern in
software development, and was a major influence in early web development. It is
no longer emphasized as heavily, as web development has split into frontend and
backend camps, but most web developers are still familiar with the idea.
Traditionally, the MVC pattern mapped into web development like so:
- Model - A collection of "domain" classes that implement all the logic and rules
for the particular domain your application is designed for. The model typically
provides "resources" that are then presented to clients as HTML "representations."
- View - Typically views would be some sort of client-side templating system, and
would render the aforementioned HTML representation for a given Model instance.
- Controller - The controller’s job is to take HTTP requests, convert them into
sensible requests to the Model and forward those requests on to the appropriate
Model objects. It then passes the HTML representation back to the client as an
HTTP response.
]
Thin controllers make it easy to split your JSON and hypermedia APIs out,
because all the important logic lives in the domain model that is shared by
both. This allows you to evolve both separately, while still keeping logic in
sync with one another.
With properly built "thin" controllers and "fat" models, keeping two separate
APIs both in sync and yet still evolving separately is not as difficult or as
crazy as it might sound.
#html-note[#indexed[Microformats]][
#link("https://microformats.org/")[Microformats] is a standard for embedding
machine-readable structured data in HTML. It uses classes to mark certain
elements as containing information to be extracted, with conventions for
extracting common properties like name, URL and photo without classes. By adding
these classes into the HTML representation of an object, we allow the properties
of the object to be recovered from the HTML. For example, this simple HTML:
#figure(
```html
<a class="h-card" href="https://john.example">
<img src="john.jpg" alt=""> <NAME>
</a>
```)
can be parsed into this JSON-like structure by a microformats parser:
#figure(
```json
{
"type": ["h-card"],
"properties": {
"name": ["<NAME>"],
"photo": ["john.jpg"],
"url": ["https://john.example"]
}
}
```)
Using a variety of properties and nested objects, we could mark up every bit of
information about a contact, for example, in a machine-readable way.
As explained in the above chapter, trying to use the same mechanism for human
and machine interaction is not a good idea. Your human-facing and machine-facing
interfaces may end up being limited by each other. If you want to expose
domain-specific data and actions to users and developers, a JSON API is a great
option.
However, microformats are way easier to adopt. A protocol or standard that
requires websites to implement a JSON API has a high technical barrier. In
comparison, any website can be augmented with microformats simply by adding a
few classes. Other HTML-embedded data formats like microdata, Open Graph are
similarly easy to adopt. This makes microformats useful for cross-website (dare
we say _web-scale_) systems like the #link("https://indieweb.org")[IndieWeb],
which uses it pervasively.
]
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/抽象代数/作业/hw2.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: note.with(
title: "作业2",
author: "YHTQ ",
date: none,
logo: none,
withOutlined: false
)
#set heading(numbering: none, outlined: false)
= P25.16
设 $|G| = 2n$,有:
$
G = union_(a in G) {a, Inv(a)}
$
从而满足 $a = Inv(a)$ 的元素至少有偶数个(否则等式右侧的元素个数为奇数)。\
$
$
因此存在除 $e$ 以外的元素 $a$ 使得 $a = Inv(a)$,即存在 $a != e$ 使得 $a^2 = e$
= 补充题
1. #box[
$(789)(39) = (7893)$\
$(147)(7893) = (147893)$\
$(147893)(942) = (978)(1423)$\
$(978)(1423)(356)=(978)(142356)$ 这就是所求答案
]
2. #box[
考虑最长偶数长度轮换(奇轮换)的长度 $k$
\ $k=0$: 此时型共有三种 $(5, 0, 0, 0, 0), (2, 0, 1, 0, 0), (0, 0, 0, 0, 1)$
\ $k=2$: 此时型共有一种 $(1, 2, 0, 0, 0)$
\ $k=4$: 此时型共有一种 $(1, 0, 0, 1, 0)$,但它不是偶置换,排除
]
3. #box[
#set enum(numbering: "(1).")
+ #box[
断言所有五元偶排列(去除轮换相等的)构成的轮换恰为与 $(12345)$ 共轭的所有元素。\
- 显然$A_5$ 中与 $(12345)$ 共轭的置换仍为五元轮换。
- 首先,由于五元轮换是偶置换,从而序列 $i_1 i_2 i_3 i_4 i_5$ 与序列 $i_5 i_1 i_2 i_3 i_4$ 有相同的奇偶性,因此对应相同轮换的不同五元序列(例如$12345$ 与 $23451$)奇偶性相同。
- 其次,$12345$ 是偶排列,因此若 $rho$ 是偶置换,则 $rho(1)rho(2)rho(3)rho(4)rho(5)$ 也是偶排列,这就证明了$A_5$ 中与 $(12345)$ 共轭的置换只能为$(i_1 i_2 i_3 i_4 i_5)$,其中 $i_1 i_2 i_3 i_4 i_5$ 是一个偶排列。
- 最后,证明所有的这种偶排列对应的轮换均在 $A_5$ 中与 $(12345)$ 共轭。\
设$i_1 i_2 i_3 i_4 i_5$ 是一个偶排列,令 $sigma=mat(1,2,3,4,5;i_1,i_2,i_3,i_4,i_5)$,显有 $sigma in A_5$,且:
$
sigma (12345) Inv(sigma) = (i_1 i_2 i_3 i_4 i_5)
$
这就证明了前述断言。
]
+ #box[
注意到共轭关系是等价的,只需证明:
$
forall i_i,i_2,i_3,i_4, (12)(34) "与" (i_1i_2)(i_3i_4) "相互共轭"
$
即可。事实上,取:
$
sigma_1 = mat(1,2,3,4,5;i_1,i_2,i_3,i_4,i_5)\
sigma_2 = mat(1,2,3,4,5;i_1,i_2,i_4,i_3,i_5)
$
显然 $sigma_1, sigma_2$ 奇偶性相异,从而取其中的偶置换为 $sigma in A_5$,显有$(12)(34) "与" (i_1i_2)(i_3i_4) "关于" sigma "相互共轭"$,证毕
]
+ 由(1) 的结果,答案显然是否定的
]
4.
1. #box[
设四顶点分别为 $V_1, V_2, V_3, V_4$。
注意到
$
V_1 + V_2 + V_3 + V_4 = 0
$
又 $(V_1, V_2, V_3)$ 可逆,从而只需确定正交变换 $A$ 在向量组 $(V_1, V_2, V_3)$ 上的像即可(显然确定了像便唯一确定一个线性变换,其正交性由几何关系易得)。可分为以下情况:
- $A$ 保持 $V_4$ 不动,此时:
$
A(V_1, V_2, V_3) = sigma(V_1, V_2, V_3)
$
其中 $sigma$ 是一个三元置换。由于置换也是正交线性变换,可设:
$
sigma(V_1, V_2, V_3) = (V_1, V_2, V_3)Sigma
$
其中 $Sigma$ 为一矩阵,并且显有 $|A| = |Sigma| = 1$\
满足要求的 $Sigma$ 有 $4$ 个,分别对应 $3$ 个非平凡三元偶置换和 $1$ 个恒等变换(这些置换对应的矩阵恰为对应列的一个置换,从而行列式为 $1$)。更进一步:
$
A(V_1, V_2, V_3, V_4) = (V_1, V_2, V_3, V_4) (Sigma, epsilon_4)\
epsilon_4 = vec(0, 0, 0, 1)
$
它们恰对应四个四元偶置换
- $A$ 交换 $V_4$ 和 $V_1$,此时:
$
A(V_1, V_2, V_3) = (V_4, V_2, V_3)Sigma = (-V_1-V_2-V_3, V_2, V_3)Sigma \ = (V_1, V_2, V_3) mat(-1, 0, 0;-1, 1, 0;-1, 0, 1) Sigma
$
其中 $Sigma$ 为一矩阵,并且显有 $|A| = -|Sigma| = 1$\
满足要求的 $Sigma$ 有 $4$ 个,分别对应 $3$ 个非平凡三元奇置换。更进一步
$
A(V_1, V_2, V_3, V_4) = (V_1, V_2, V_3, V_4) mat(0, 0, 0, 1;0, 1, 0, 0;0, 0, 1, 0;1, 0, 0, 0)Sigma
$
恰对应一个四元偶置换
- $A$ 交换 $V_4$ 和 $V_2, V_3$ 的情形同理
综上,共有 $4 + 4 + 4 = 12$ 个满足要求的正交变换,他们恰对应 $12$ 个四元偶置换
]
2. 显有所有正交变换保持顶点不动,因此等价于正十二边形上的对称(行列式为 $1$ 的保持图形不变的正交变换)。\
类似的,只需确定 $A$ 在 $(V_1, V_2)$ 上的像。
\ $A$ 保持 $V_1$ 不动: 此时只有恒等变换和 $A(V_1, V_2) = A(V_1, V_11)$,但后者是对称变换,行列式为 $-1$
\ $A(V_1, V_2) = A(V_i, V_j)$: 显有 $j = i+1$ 或 $j = i-1$ ($V_13 = V_1$),容易发现前者对应正交变换行列式均为 $1$ 而后者均为 $-1$,因此满足要求的共有 $11$ 个。\
综上,共有 $1 + 11 = 12$ 个满足要求的正交变换,同构于 $ZZ\/12 ZZ$
5. #box[
$D_4$ 可表示为由 $r, s$ 生成的群,满足:
$
ord(r) = 4, s^2 = e, r s = s r^3
$\
从而取
$
a = r, b = s, c = r^3
$
即满足题目要求
] |
|
https://github.com/jasonelaw/bes-typst-memo | https://raw.githubusercontent.com/jasonelaw/bes-typst-memo/main/_extensions/quarto-ext/memo/typst-show.typ | typst | #show: memo.with(
$if(letterhead)$
letterhead: "$letterhead$",
$endif$
$if(sender)$
sender: [$sender$],
$endif$
$if(recipient)$
recipient: [$recipient$],
$endif$
$if(re)$
re: [$re$],
$endif$
$if(date)$
date: [$date$],
$endif$
)
|
|
https://github.com/EpicEricEE/typst-marge | https://raw.githubusercontent.com/EpicEricEE/typst-marge/main/src/sidenote.typ | typst | MIT License | #import "resolve.typ": *
#import "validate.typ": validate
/// Get the margin note state for a specific page.
#let page-state(page) = state("marge:0.1.0/page-" + str(page), ())
/// Get the container mark metadata for a specific page.
#let page-container(page) = metadata("marge:0.1.0/container-" + str(page))
/// The sidenote counter.
#let counter = counter("sidenote")
/// The default format for margin notes.
#let default-format(it) = {
let num = if it.numbering != none {
link(it.source, super(it.counter.display(it.numbering)))
h(0.05em, weak: true)
}
align(start, par(
hanging-indent: par.hanging-indent + measure(num).width,
num + h(0pt, weak: true) + it.body
))
}
/// A container of all margin notes of the current page.
///
/// To be used as the page's `background` or `foreground` parameter when the
/// page width is set to `auto`, as notes then cannot be automatically placed
/// in the right margin.
#let container = context {
page-container(here().page())
for note in page-state(here().page()).final() {
place(top + note.side, note.body, dy: note.position.y)
}
}
/// A sidenote to be placed in the page margin.
///
/// If this note ends up on the right margin of a page with width set to
/// `auto`, it cannot be placed automatically. In this case, the page's
/// `background` or `foreground` should be set to the include the `container`
/// provided by this package.
///
/// There are two correction mechanisms in place:
/// - When two notes would overlap, the second one is moved down to avoid this.
/// - When a note would overflow into the bottom margin, it is moved up. Any
/// previous notes that this note would now overlap with are also moved up.
///
/// # Parameters:
/// - `side`: The margin where the note should be placed.
/// - `dy`: A custom offset by which the note should be moved along the y-axis.
/// - `padding`: The space between the note and the page or content border.
/// - `gap`: The minimum gap between two consecutive notes.
/// - `numbering`: How the note should be numbered.
/// - `counter`: The counter to be used for numbering.
/// - `format`: The "show rule" of the note.
/// - `body`: The body of the note.
#let sidenote(
side: auto,
dy: 0pt,
padding: 2em,
gap: 0.4em,
numbering: none,
counter: counter,
format: it => it.default,
body
) = {
// Validate parameters.
validate(
side: side,
dy: dy,
padding: padding,
gap: gap,
numbering: numbering,
counter: counter,
format: format,
body: body
)
// Place number in paragraph.
if numbering != none {
counter.step()
context {
let state = page-state(here().page())
let note = state.final().at(state.get().len())
let pos = note.position
pos.x += note.padding.left
let num = counter.display(numbering)
h(0pt, weak: true) + link(pos, super(num))
}
}
h(0pt, weak: true) + sym.zwj + context {
// Use side with largest margin if side is `auto`.
let side = if side != auto { side } else {
let margin-left = resolve-margin(left)
let margin-right = resolve-margin(right)
if margin-left > margin-right { left }
else if margin-right > margin-left { right }
else { "outside" }
}
// Resolve values.
let side = resolve-side(side)
let padding = resolve-padding(padding)
let margin = resolve-margin(side)
let bottom-margin = resolve-margin(bottom)
let (width: page-width, height: page-height) = resolve-page-size()
let gap = gap.to-absolute()
let leading = par.leading.to-absolute()
// Create note content.
let note-body = block(inset: padding, width: margin, {
set align(align.alignment)
set text(size: 0.85em)
set par(leading: 0.5em)
let source = here()
context {
let it = (
side: side,
numbering: numbering,
counter: counter,
padding: padding,
margin: margin,
source: source,
body: body,
)
it.default = default-format(it)
format(it)
}
})
// Resolve dy relative to note-height (if given as ratio).
let note-height = measure(note-body).height
let dy = if type(dy) == length { dy }
else if type(dy) == ratio { dy * note-height }
else if type(dy) == relative { dy.ratio * note-height + dy.length }
// Calculate position of note on y-axis. The note is moved up, so that it
// aligns with the line of the paragraph.
let position = here().position()
position.y += dy.to-absolute() - measure[x].height
// Set x-position of note depending on side.
position.x = if side == right and page-width != auto { page-width - margin }
else { 0pt }
page-state(here().page()).update(notes => {
let position = position
// Move note down to avoid overlap with previous one.
let prev = notes.at(-1, default: none)
position.y += if prev != none and prev.side == side {
let gap = calc.max(gap, prev.gap)
let overlap = prev.position.y + prev.height - position.y + leading + gap
calc.max(0pt, overlap)
}
// Move note up to avoid overflow into bottom page margin.
let overflow = position.y + note-height - page-height + bottom-margin
position.y -= calc.max(0pt, overflow)
// Summarize data of the new note.
let new = (
position: position,
height: note-height,
side: side,
gap: gap,
padding: padding,
body: note-body
)
// Move previous notes up to restore the gap and prevent overlap with
// previously moved up notes, starting from the bottom.
let current = new
for (i, prev) in notes.enumerate().rev().filter(((_, note)) => note.side == side) {
let gap = calc.max(current.gap, prev.gap)
let overlap = prev.position.y + prev.height - current.position.y + leading + gap
notes.at(i).position.y -= calc.max(0pt, overlap)
current = notes.at(i)
}
// Append new note to the list of all notes on this page.
notes + (new,)
})
// Place the note on the page. Only use this automatic placement
// if no container is used for this page!
if page-container(here().page()) not in query(metadata) {
let index = page-state(here().page()).get().len()
let final = page-state(here().page()).final().at(index, default: none)
if final != none {
assert(page-width != auto or final.side == left, message: {
"cannot place note on right margin of page with width auto.\n"
"hint: import the `container` value of the package and use it as the "
"page background or foreground"
})
box(place(
final.body,
dx: final.position.x - here().position().x,
dy: final.position.y - here().position().y
))
}
}
}
}
|
https://github.com/matthiasbeyer/ttt | https://raw.githubusercontent.com/matthiasbeyer/ttt/master/README.md | markdown | MIT License | # ttt
transcript-template-typst
Based on the awesome [ilm](https://github.com/talal/ilm) template.
## License
MIT.
|
https://github.com/max-niederman/MATH51 | https://raw.githubusercontent.com/max-niederman/MATH51/main/notes/lecture_2023-08-02.typ | typst | #import "../lib.typ": *
#show: lecture-notes.with(
date: "2023-08-02",
)
= Hyperplane normal with Gram-Schmidt process
An alternative method to find the normal vector of a hyperplane
is to use the Gram-Schmidt process on the set of vectors $ { vname(v)_1, vname(v)_2, ... vname(v)_n, vname(v)' } $
where $vname(v)'$ is a vector that does not lie on the hyperplane.
The vector in the resultant orthogonal basis corresponding to $vname(v)'$
will be the normal vector to the hyperplane.
= Orthogonal complement of a subspace
The orthogonal complement, $V^perp$, of a space $V subset.eq RR^n$ is the set
$ { vname(v)' in RR^n | vname(v) in V implies vname(v) perp vname(v)' } $
The dimension of this space is $n - dim(V)$.
== Proof
Let ${ vname(v)_1, vname(v)_2, ..., vname(v)_k }$ be a basis for $V$,
and ${ vname(v)_1, ... vname(v)_k, vname(v)_(k+1), ... vname(v)_n}$ be a basis for $RR^n$.
We can apply the Gram-Schmidt process to the second set of vectors
to get the orthogonal basis ${ vname(w)_1, vname(w)_2, ..., vname(w)_n }$,
with ${ vname(w)_1, vname(w)_2, ..., vname(w)_k }$ being an orthogonal basis of $V$.
Then for any $vname(x) in V^T$,
we have by the Fourier Formula that
$ vname(x) = sum_(i=1)^k a_i vname(w)_i $
with $a_i = (vname(x) dot vname(w)_i) / (vname(w)_i dot vname(w)_i)$.
This is zero for $i <= k$, so
$
vname(x) &= sum_(i=k+1)^n a_i vname(w)_i \
vname(x) &in span{ vname(w)_(k+1), ..., vname(w)_n }
$.
So ${ vname(w)_(k+1), ..., vname(w)_n }$ is a basis of $V^perp$,
and $V^perp$ has dimension $n - k$.
= Transpose
The matrix transpose moves "across" dot products:
$ A u dot v = u dot A^T v $
= Quadratic forms
Let $A$ be a symmetric $n times n$ matrix, then define the quadratic form $q_A : RR^n -> R$
$ q_A (v) = v^T A v $
|
|
https://github.com/ekmanib/curriculum-vitae | https://raw.githubusercontent.com/ekmanib/curriculum-vitae/main/docs/skills.typ | typst | #text(font: "Jost", size: 16pt)[
Destrezas
]
#text(size: 14pt, stroke: 0.5pt + rgb("a60707"))[_R_]
Programación en R para aplicaciones de estadística y visualización de datos.
#text(size: 14pt, stroke: 0.5pt + rgb("a60707"))[_Python_]
Programación en Python para análisis estadístico, visualización de datos, automatización de tareas y otros etcéteras.
#text(size: 14pt, stroke: 0.5pt + rgb("a60707"))[_SQL_]
Consultas a bases de datos relacionales.
#text(size: 14pt, stroke: 0.5pt + rgb("a60707"))[_MS Suite_]
Manejo intermedio a avanzado de Excel, Power BI, Sharepoint, Teams y otras herramientas de la suite. |
|
https://github.com/ofurtumi/formleg | https://raw.githubusercontent.com/ofurtumi/formleg/main/h07/H7.typ | typst | #import "@templates/ass:0.1.1":*
#import "@preview/finite:0.3.0": *
#import "@preview/cetz:0.1.1": *
#show: doc => template(
class: "TÖL301G",
project: "Homework 7",
doc
)
= Odd Square Machine
Let us consider language $S$ consisting of binary representations of _"odd squares"_, $1^2, 3^2, 5^2,...,$
"On input string $x$:
+ We add a delimiter to keep track of our input
+ After our delimiter we add 1 and another delimeter
+ We square the number behind our first delimiter, and store it after the second delimeter
+ We check if our squared number is equal to our input string, if so we accept
+ We check if our squared number is greater than our input string, if so we reject
+ We remove our squared number
+ We add two to our middle number, and go to state 3"
This implementation tests every odd squared number against our input string and halts if we go over our original input.
= Directory structure
We made this turing machine using only a measly 10 states, originally we drew it up using a state machine where each node transition was denoted by \<token read\>, \<token written \>, \<movement\>
#automaton((
q0: (q1: "(,(,>"),
q1: (q2: "a,a,>", q4: "),x,<"),
q2: (q2: "a,a,>", q3: "(,(,>"),
q3: (q2: "a,a,>", q7: "x,x,>", q4: "),x,<"),
q4: (q4: "x,x,<", q5: "(,x,<"),
q5: (q8: "_,_,>", q6: "a,x,<"),
q6: (q6: "a,x,< / x,x,<", q3: "(,(,>"),
q7: (q2: "a,a,>", q7: "x,x,>", q4: "),x,<"),
q8: (q8: "x,_,>", qf: "_,_,-", ),
qf: ()
),style: (
q1-q2: (curve: 0),
q3-q2: (curve: 0),
q3-q4: (curve: 0),
q4-q5: (curve: 0),
q5-q6: (curve: 0),
q8-qf: (curve: 0),
q7-q2: (curve: 2),
q6-q3: (curve: -2, dist: 0.33),
q1-q4: (curve: 2, dist: 0.5),
))
This is not the original, i forgot to take a picture of it, but it is close enough
= Pop3 Turing
When we started working on this i think we were too stuck in the state machine mindset, we were able to create a state machine using the grammar above however it was huge, then we read the problem description again and found out that we did not need to check for the least common number.
This is the state machine we ended up with, there are some small bugs in it that we fixed directly in the code, but it is mostly correct.
#figure(image("../imgs/h7-v3-a.png"), caption: "This part creates a delimiter between the string and the checksum")
#figure(image("../imgs/h7-v3-b.png"), caption: "This part does all of the rest")
|
|
https://github.com/lyzynec/orr-go-brr | https://raw.githubusercontent.com/lyzynec/orr-go-brr/main/11/main.typ | typst | #import "../lib.typ": *
#knowledge[
#question(name: [Give the general optimization criterion for the
control--design procedure based on minimizing the $cal(H)_oo$--norm of the
mixed sensitivity function.])[
$
min_(K "stabilizing") norm(mat(W_1 S; W_2 K S; W_3 T))_oo
$
$W_i$ are called _shaping filters_ and have to be strictly stable
- $W_1$ expresses our performance requitements, typically a low pass
filter as we do not care about performance at higher frequencies.
- $W_2$ is typically a high pass filter, dampening regulator eagerness
at given frequancies.
- $W_3$ is typically a high pass filter, stating that we want low $T$
(transfer) in higher frequencies for robustness.
]
#question(name: [Explain the control design procedure based on minimizing
the $cal(H)_oo$--norm of the linear fractional transformation (LFT) of a
generalized plant and a stabilizing controller.])[
+ design the plant such that it makes sense I guess
+ $min_(K "stabilizing") norm(F_l (P, K))_oo$
+ cry
]
]
#skills[
#question(name: [Design a robust controller by $cal(H)_oo$ *norm
minimization* (your task is actually just to formulate the control design
problem as the optimization problem, the actual numerical job of
optimization can be relegated to an available numerical solver). Namely, you
should master the technique of control design by minimizing the $cal(H)_oo$
*norm of mixed sensitivity* function but you should also be able to
formulate (and use Matlab to solve) the *general* $cal(H)_oo$*--optimal
control problem*.])[]
]
|
|
https://github.com/Pegacraft/typst-plotting | https://raw.githubusercontent.com/Pegacraft/typst-plotting/master/plotst/axis.typ | typst | MIT License | // This sign can't stop me if I can't read
#import "util/util.typ": *
#import "@preview/oxifmt:0.2.0": strfmt
//------------------
// THIS FILE CONTAINS EVERYTHING TO DRAW AND REPRESENT AXES
//------------------
/// This is the constructor function for creating axes. Most plots/graphs will require axes to function. \ \
/// === Basics
/// The most important parameters are `min`, `max`, `step` and `location`. These need most likely be changed for a functioning axis. If `min`, `max` and `step` are set, the `values` parameter will automatically be filled with the correct values. \
/// _Example:_ \
/// ```js let x_axis = axis(min: 0, max: 11, step: 2, location: "bottom")``` \
/// will cause `values` to look like this: \
/// `(0, 2, 4, 6, 8, 10)` \ \
/// If you want to specify your own values, for example when using text on an axis, you need to specify `values` by yourself. Custom specified values could look like this `("", "male", "female", "divers", "unknown")` (the first empty string is not neccessary, but will make some graphs/plots look a lot better). \ \
/// You can obviously do a lot more than just this, so I recommend taking a look at the examples. \ \
/// === Examples
/// An x-axis for different genders:
/// ```typc
/// let gender_axis_x = axis(
/// values: ("", "m", "w", "d"),
/// location: "bottom",
/// helper_lines: true,
/// invert_markings: false,
/// title: "Gender"
/// )
/// ``` \
/// A y-axis displaying ascending numbers: \
/// ```typc
/// let y_axis_2 = axis(min: 0, max: 41, step: 10,
/// location: "left", show_markings: true, helper_lines: true)```
///
/// *NOTE:* this might change to kebab-case
///
/// - min (integer, float): From where `values` should started generating (inclusive)
/// - max (integer, float): Where `values` should stopped being generated (exclusive)
/// - step (integer, float): The steps that should be taken when generating `values`
/// - values (array): The values of the markings (exclusive with `min`,#sym.space `max` and `step`)
/// - location (string): The position of the axis. Only valid options are: `"top", "bottom", "left", "right"`
/// - show_values (boolean): If the values should be displayed
/// - show_arrows (boolean): If arrows at the end of axis should be displayed
/// - show_markings (boolean): If the markings should be displayed
/// - invert_markings (boolean): If the markins should point away from the data (outwards)
/// - marking_offset_left (integer): Amount of hidden markings from the left or bottom
/// - marking_offset_right (integer): Amount of hidden markings from the right or top
/// - stroke (length, color, dictionary, stroke): The color of the baseline for the axis
/// - marking_color (color): The color of the marking
/// - value_color (color): The color of a value
/// - helper_lines (boolean): If helper lines (to see better alignment of data) should be displayed
/// - helper_line_style (string): The style of the helper lines, valid options are: `"solid", "dotted", "densely-dotted", "loosely-dotted", "dashed", "densely-dashed", "loosely-dashed", "dash-dotted", "densely-dash-dotted", "loosely-dash-dotted"`
/// - helper_line_color (color): The color of the helper line
/// - marking_length (length): The length of a marking in absolute size
/// - marking_number_distance (length): The distance between the marker and the number
/// - title (content): The display name of the axis
/// - value_formatter (string, function): How values get displayed; uses https://github.com/typst/packages/tree/main/packages/preview/oxifmt/0.2.0 or a mapper function
#let axis(min: 0, max: 0, step: 1, values: (), location: "bottom", show_values: true, show_arrows: true, show_markings: true, invert_markings: false, marking_offset_left: 1, marking_offset_right: 0, stroke: black, marking_color: black, value_color: black, helper_lines: false, helper_line_style: "dotted", helper_line_color: gray, marking_length: 5pt, marking_number_distance: 5pt, title: [], value_formatter: i => i) = { // TODO automate? macro-programming?
let axis_data = (
min: min,
max: max,
step: step,
location: location,
show_values: show_values,
show_arrows: show_arrows,
show_markings: show_markings,
invert_markings: invert_markings,
marking_offset_left: marking_offset_left,
marking_offset_right: marking_offset_right,
stroke: stroke,
marking_color: marking_color,
value_color: value_color,
helper_lines: helper_lines,
helper_line_style: helper_line_style,
helper_line_color: helper_line_color,
marking_length: marking_length,
marking_number_distance: marking_number_distance,
title: title,
values: values,
value_formatter: value_formatter,
)
if values.len() == 0 {
axis_data.values = float_range(min, max, step: step)
}
return axis_data
}
#let format(axis, value) = {
let fmt = axis.value_formatter
if type(fmt) == "string" {
return strfmt(fmt, value)
} else if type(fmt) == "function" {
return fmt(value)
}
}
// returns true if and only if the axis is on the left or right, false if top or bottom, panics otherwise
// axis: the axis
#let is_vertical(axis) = {
if axis.location == "left" or axis.location == "right" {return true}
if axis.location == "top" or axis.location == "bottom" {return false}
panic("axis location wrong")
}
// returns the expected need of space as a (width, height) array
// axis: the axis
// style: styling
#let measure_axis(axis, style) = {
let invert_markings = 1
if axis.location == "right" {
invert_markings = -1
}
if axis.location == "top" {
invert_markings = -1
}
let dist = if axis.invert_markings {axis.marking_length + axis.marking_number_distance} else {axis.marking_number_distance}
let inversion = if axis.invert_markings == -1 {dist * 2 + size.width} else {0pt}
let title_extra = measure(axis.title, style).height
let sizes = axis.values.map(it => {
let size = measure([#format(axis, it)], style)
if is_vertical(axis) {
return size.width
} else {
return size.height
}
})
let size = calc.max(..sizes) + inversion + 2 * dist + title_extra
if is_vertical(axis) {
return (size, 0pt)
} else {
return (0pt, size)
}
}
//------------------------------
// AXIS DRAWING
//-------------------------------
// axis: the axis to draw
// length: the length of the axis (mostly gotten from the plot code function; see util.typ, prepare_plot())
// pos: the position offset as an array(x, y)
#let draw_axis(axis, length: 100%, pos: (0pt, 0pt)) = {
let step_length = length / axis.values.len()
let invert_markings = 1
let user_invert_markings = if axis.invert_markings {-1} else {1}
// Changes point of reference if top or right is chosen
if axis.location == "right" {
pos.at(0) = length - pos.at(0)
invert_markings = -1
}
if axis.location == "top" {
pos.at(1) = -length + pos.at(1)
invert_markings = -1
}
let arrow_size = 0pt
if axis.show_arrows {
// sets the size of arrows
arrow_size = 2pt
}
if is_vertical(axis) {
// Places the axis line
place(dx: pos.at(0), dy: pos.at(1), line(angle: -90deg, length: length - arrow_size * 2, stroke: axis.stroke))
// draw the arrow at the end of the axis
if axis.show_arrows {
place(dx: pos.at(0), dy: pos.at(1) - length,
polygon(fill: axis.stroke, (-arrow_size, arrow_size * 2), (0pt, -1pt), (arrow_size, arrow_size * 2))
)
}
// Places the title
//place(dy: -50%, rotate(-90deg, axis.title)) // TODO
style(style => {
let a = measure_axis(axis, style).at(0)
if axis.location == "left" {
place(dy: pos.at(1) - length / 2, dx: -length/2 - a, rotate(-90deg, origin: center + top, box(width: length, height:0pt, align(center+top, axis.title))))
} else {
place(dy: pos.at(1) - length / 2, dx: length/2 +a, rotate(-90deg, origin: center + top, box(width: length, height:0pt, align(center+bottom, axis.title))))
}
})
// Draws step markings
for step in range(axis.marking_offset_left, axis.values.len() - axis.marking_offset_right) {
// Draw helper lines:
if axis.helper_lines {
//place(dx: pos.at(0), dy: pos.at(1) - step_length * step, line(angle: 0deg, length: length * invert_markings, stroke: (paint: axis.helper_line_color, dash: axis.helper_line_style)))
}
// Draw markings
if axis.show_markings {
place(dx: pos.at(0), dy: pos.at(1) - step_length * step, line(angle: 0deg, length: axis.marking_length * invert_markings * user_invert_markings, stroke: axis.marking_color))
}
// Draw numbering
if axis.show_values {
let number = [#format(axis, axis.values.at(step))]
style(styles => {
let size = measure(number, styles)
let dist = if axis.invert_markings {axis.marking_length + axis.marking_number_distance} else {axis.marking_number_distance}
let inversion = if invert_markings == -1 {dist * 2 + size.width} else {0pt}
place(dx: pos.at(0) - dist - size.width + inversion, dy: pos.at(1) - step_length * step - 4pt, text(fill: axis.value_color, number))
})
}
}
} else {
// Places the axis line
place(dx: pos.at(0), dy: pos.at(1), line(angle: 0deg, length: length - arrow_size * 2, stroke: axis.stroke))
// draw the arrow at the end of the axis
if axis.show_arrows {
place(dx: pos.at(0) + length - arrow_size * 2, dy: pos.at(1),
polygon(fill: axis.stroke, (0pt, -arrow_size), (arrow_size * 2, 0pt), (0pt, arrow_size))
)
}
// Places the title
//place(dx: 50%, align(bottom + center, box(width:0pt, height: 0pt, axis.title))) // TODO willbreak
if axis.location == "bottom" {
place(dx: pos.at(0), dy: 3pt, align(top + center, box(width: length, height: 0pt, [\ #axis.title])))
} else {
style(style => {
let a = measure_axis(axis, style).at(1)
layout(size => place(dy: -size.height - a, align(top + center, box(width: length, height: 0pt, [#axis.title]))))
})
}
// Draws step markings
for step in range(axis.marking_offset_left, axis.values.len() - axis.marking_offset_right) {
// Draw helper lines:
if axis.helper_lines {
//place(dx: pos.at(0) + step_length * step, dy: pos.at(1), line(angle: 90deg, length: length * -invert_markings, stroke: (paint: axis.helper_line_color, dash: axis.helper_line_style)))
}
// Draw markings
if axis.show_markings {
place(dx: pos.at(0) + step_length * step, dy: pos.at(1), line(angle: 90deg, length: axis.marking_length * -invert_markings * user_invert_markings, stroke: axis.marking_color))
}
// Show values
if axis.show_values {
let number = axis.values.at(step)
style(styles => {
let size = measure([#number], styles)
let dist = if axis.invert_markings {axis.marking_number_distance + axis.marking_length} else {axis.marking_number_distance}
let inversion = if invert_markings == -1 {-dist * 2 - size.height} else {0pt}
place(dx: pos.at(0) + step_length * step, dy: pos.at(1) + dist + inversion, box(width: 0pt, align(center, text(fill: axis.value_color, str(number)))))
})
}
}
}
}
// Draws the helper lines for an axis. Needs to be seperated for rendering order reasons
#let draw_helper_lines(axis, length: 100%, pos: (0pt, 0pt)) = {
let step_length = length / axis.values.len()
let invert_markings = 1
// Changes point of reference if top or right is chosen
if axis.location == "right" {
pos.at(0) = length - pos.at(0)
invert_markings = -1
}
if axis.location == "top" {
pos.at(1) = -length + pos.at(1)
invert_markings = -1
}
if is_vertical(axis) {
// Draw helper lines:
for step in range(axis.marking_offset_left, axis.values.len() - axis.marking_offset_right) {
if axis.helper_lines {
place(dx: pos.at(0), dy: pos.at(1) - step_length * step, line(angle: 0deg, length: length * invert_markings, stroke: (paint: axis.helper_line_color, dash: axis.helper_line_style)))
}
}
} else {
for step in range(axis.marking_offset_left, axis.values.len() - axis.marking_offset_right) {
if axis.helper_lines {
place(dx: pos.at(0) + step_length * step, dy: pos.at(1), line(angle: 90deg, length: length * -invert_markings, stroke: (paint: axis.helper_line_color, dash: axis.helper_line_style)))
}
}
}
}
// ------------------------
|
https://github.com/mattheww/tyroshup | https://raw.githubusercontent.com/mattheww/tyroshup/funcalls/funcalls/glossary.typ | typst | #import "fns.typ": dt, t, t2
= Glossary <glossary>
A #dt("construct") is a piece of program text that is an instance of a syntactic category
A #dt("keyword") is a word in program text that has special meaning.
== Dummy entries
These entries allow the Expressions chapter to build without failing due to broken links.
#dt("ABI")
#dt("Evaluation")
#dt("adjusted call operand")
#dt("argument operand")
#dt("associated type")
#dt("by move")
#dt("call expression")
#dt("call operand")
#dt("call resolution")
#dt("callee type")
#dt("control flow boundary")
#dt("dereference expression")
#dt("evaluation")
#dt("expression")
#dt("external function item type")
#dt("field")
#dt("function item type")
#dt("function parameter")
#dt("function pointer type")
#dt("function")
#dt("method call expression")
#dt("never type")
#dt("operand")
#dt("passing convention")
#dt("return expression")
#dt("return type")
#dt("trait")
#dt("tuple enum variant value")
#dt("tuple enum variant")
#dt("tuple struct type")
#dt("tuple struct value")
#dt("tuple struct")
#dt("tuple")
#dt("type")
#dt("unifiable")
#dt("unit value")
#dt("unsafe context")
#dt("unsafe function item type")
#dt("unsafe function pointer type")
#dt("value")
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/let-09.typ | typst | Other | // Ref: false
// Destructuring with an empty sink.
#let (a, ..b, c) = (1, 2)
#test(a, 1)
#test(b, ())
#test(c, 2)
|
https://github.com/Karolinskis/KTU-typst | https://raw.githubusercontent.com/Karolinskis/KTU-typst/main/mainPages/TermsList.typ | typst | #page(header: none)[
#align(center)[
= Santrumpų ir terminų sąrašas
]
*Santrumpos:*\
Doc. – docentas;\
Lekt. – lektorius;\
Prof. – profesorius.\
\
*Terminai:*\
*Saityno analitika* – lorem ipsum dolor sit amet, eam ex decore persequeris, sit at illud lobortis atomorum. Sed dolorem quaerendum ne, prompta instructior ne pri. Et mel partiendo suscipiantur, docendi abhorreant ea sit. Recteque imperdiet eum te.\
*Tinklaraštis* – lorem ipsum dolor sit amet, eam ex decore persequeris, sit at illud lobortis atomorum. Sed dolorem quaerendum ne, prompta instructior ne pri. Et mel partiendo suscipiantur, docendi abhorreant ea sit. Recteque imperdiet eum te.
] |
|
https://github.com/isaacholt100/isaacholt100.github.io | https://raw.githubusercontent.com/isaacholt100/isaacholt100.github.io/master/maths-notes/3-durham%3A-year-3/analysis/analysis.typ | typst | #import "../../template.typ": *
#show: doc => template(doc, hidden: (), slides: false)
// FIND: - \*(\w+)\*: ([\s\S]*?)(?=\n-|\n\n)\n
// REPLACE: #$1[\n $2\n]\n
#let indicator(arg) = $bb(1)_arg$
#let ip(a, b) = $angle.l #a, #b angle.r$
= The real numbers
== Conventions on sets and functions
#definition[
For $f: X -> Y$, *preimage* of $Z subset.eq Y$ is $ f^(-1) (Z) := {x in X: f(x) in Z} $
]
#definition[
$f: X -> Y$ *injective* if $ forall y in f(X), exists! x in X: y = f(x) $
]
#definition[
$f: X -> Y$ *surjective* if $Y = f(X)$.
]
#proposition[
Let $f: X -> Y$, $A, B subset.eq X$, then $ f(A sect B) & subset.eq f(A) sect f(B), \ f(A union B) & = f(A) union f(B), \ f(X) - f(A) & subset.eq f(X - A) $
]
#proposition[
Let $f: X -> Y$, $C, D subset.eq Y$, then $ f^(-1)(C sect D) & = f^(-1) (C) sect f^(-1)(D), \ f^(-1)(C union D) & = f^(-1)(C) union f^(-1)(D), \ f^(-1)(Y - C) & = X - f^(-1)(C) $
]
== The real numbers
#definition[
$a in RR$ is an *upper bound* of $E subset.eq RR$ if $forall x in E, x <= a$.
]
#definition[
$c in RR$ is a *least upper bound (supremum)* of $E$, $c = sup(E)$, if $c <= a$ for every upper bound $a$.
]
#definition[
$a in RR$ is an *lower bound* of $E subset.eq RR$ if $forall x in E, x >= a$.
]
#definition[
$c in RR$ is a *greatest lower bound (infimum)*, $c = inf(E)$, if $c >= a$ for every lower bound $a$.
]
#theorem(name: "Completeness axiom of the real numbers")[
Every $E subset.eq RR$ with an upper bound has a least upper bound. Every $E subset.eq RR$ with a lower bound has a greatest lower bound.
]
#proposition(name: "Archimedes' principle")[
$ forall x in RR, exists n in NN: n > x $
]
#remark[
Every non-empty subset of $NN$ has a minimum.
]
#proposition[
$QQ$ is dense in $RR$: $ forall x < y in RR, exists r in QQ: r in (x, y) $
]
== Sequences, limits and series
#definition[
$l in RR$ is *limit* of $(x_n)$ ($(x_n)$ converges to $l$) if $ forall epsilon > 0, exists N in NN: forall n >= N, quad |x_n - l| < epsilon $ A sequence *converges in $RR$ (is convergent)* if it has a limit $l in RR$. Limit $l = lim_(n -> oo) x_n$ is unique.
]
#definition[
$(x_n)$ *tends to infinity* if $ forall K > 0, exists N in NN: forall n >= N, quad x_n > K $
]
#definition[
*Subsequence* of $(x_n)$ is sequence $\(x_(n_j)\)$, $n_1 < n_2 < dots.h.c$.
]
#definition[
*Limit inferior* of sequence $x_n$ is $ liminf_(n -> oo) x_n := sup_(n in NN) {inf_(m >= n) x_m} = lim_(n -> oo) (inf_(m >= n) x_m) $
]
#definition[
*Limit superior* of sequence $x_n$ is $ limsup_(n -> oo) x_n := inf_(n in NN) {sup_(m >= n) x_m} = lim_(n -> oo) (sup_(m >= n) x_m) $
]
#proposition[
Let $(x_n)$ bounded, $l in RR$. Then $l = limsup x_n$ iff both of the following hold:
- $forall epsilon > 0, exists N in NN: forall n >= N, x_n < l + epsilon$.
- $forall epsilon > 0, forall N in NN: exists n >= N: x_n > l - epsilon$.
]
#proposition[
Let $(x_n)$ bounded, $l in RR$. Then $l = liminf x_n$ iff both of the following hold:
- $forall epsilon > 0, exists N in NN: forall n >= N, x_n > l - epsilon$.
- $forall epsilon > 0, forall N in NN: exists n >= N: x_n < l + epsilon$.
]
#theorem(name: "Bolzano-Weierstrass")[
Every bounded sequence has a convergent subsequence.
]
#proposition[
Let $(x_n)$ bounded. There exists convergent subsequence with limit $limsup x_n$ and convergent subsequence with limit $liminf x_n$.
]
#proposition[
Let $(x_n)$ bounded, then $(x_n)$ is convergent iff $limsup x_n = liminf x_n$.
]
#theorem(name: "Monotone convergence theorem for sequences")[
Monotone sequence converges in $RR$ or tends to either $oo$ or $-oo$.
]
#definition[
$(x_n)$ is *Cauchy sequence* if $ forall epsilon > 0, exists N in NN: forall n, m >= N, quad |x_n - x_m| < epsilon $
]
#theorem[
Every Cauchy sequence in $RR$ is convergent.
]
== Open and closed sets
#definition[
$U subset.eq RR$ is *open* if $ forall x in U, exists epsilon > 0: (x - epsilon, x + epsilon) subset.eq U $
]
#proposition[
Arbitrary unions of open sets are open. Finite intersections of open sets are open.
]
#definition[
$x in RR$ is *point of closure (limit point)* for $E subset.eq RR$ if $ forall epsilon > 0, exists y in E: |x - y| < epsilon $ Equivalently, $x$ is point of closure of $E$ if every open interval containing $x$ contains a point of $E$.
]
#definition[
*Closure* of $E$, $overline(E)$, is set of points of closure. Note $E subset.eq overline(E)$.
]
#definition[
$F$ is *closed* if $F = overline(F)$.
]
#proposition[
$overline(A union B) = overline(A) union overline(B)$. If $A subset B subset.eq RR$ then $overline(A) subset overline(B)$.
]
#proposition[
For any set $E$, $overline(E)$ is closed, i.e. $overline(E) = overline(overline(E))$.
]
#proposition[
$E subset.eq RR$ is closed iff $RR - E$ is open.
]
#proposition[
Arbitrary intersections of closed sets are closed. Finite unions of closed sets are closed.
]
#definition[
Collection $C$ of subsets of $RR$ *covers* (is a *covering* of) $F subset.eq RR$ if $F subset.eq union_(S in C) S$. If each $S$ in $C$ open, $C$ is *open covering*. If $C$ is finite, $C$ is *finite covering*.
]
#definition[
Covering $C$ of $F$ *contains a finite subcover* if exists ${S_1, ..., S_n} subset.eq C$ with $F subset.eq union_(i = 1)^n S_i$ (i.e. a finite subset of $C$ covers $F$).
]
#definition[
$F$ is *compact* if any open covering of $F$ contains a finite subcover.
]
#example[
$RR$ is not compact, $[a, b]$ is compact.
]
#theorem(name: "<NAME>")[
$F$ compact iff $F$ closed and bounded.
]
== Continuity, pointwise and uniform convergence of functions
#definition[
Let $E subset.eq RR$. $f: E -> RR$ is *continuous at $a in E$* if $ forall epsilon > 0, exists delta > 0: forall x in E, |x - a| < delta ==> |f(x) - f(a)| < epsilon $ $f$ is *continuous* if continuous at all $y in E$.
]
#definition[
$lim_(x -> a) f(x) = l$ if $ forall epsilon > 0, exists delta > 0: forall x in E, |x - a| < delta ==> |f(x) - l| < epsilon $
]
#proposition[
$lim_(x -> a) f(x) = l$ iff for every sequence $(a_n)$ with $lim_(n -> oo) a_n = a$, $lim_(n -> oo) f(a_n) = l$.
]
#proposition[
$f$ is continuous at $a in E$ iff $lim_(x -> a) f(x) = f(a)$ (and this limit exists).
]
#definition[
$f: E -> RR$ is *uniformly continuous* if $ forall epsilon > 0, exists delta > 0: forall x, y in E, |x - y| < delta ==> |f(x) - f(y)| < epsilon $
]
#proposition[
Let $F$ closed and bounded, $f: F -> RR$ continuous. Then $f$ is uniformly continuous.
]
#definition[
Let $f_n: E -> RR$ sequence of functions, $f: E -> RR$. $(f_n)$ *converges pointwise* to $f$ if $ forall epsilon > 0, forall x in E, exists N in NN: forall n >= N, |f_n (x) - f(x)| < epsilon $ $(f_n)$ *converges uniformly* to $f$ is $ forall epsilon > 0, exists N in NN: forall n >= N, forall x in E, |f_n (x) - f(x)| < epsilon $
]
#theorem[
Let $f_n: E -> RR$ sequence of continuous functions converging uniformly to $f: E -> RR$. Then $f$ is continuous.
]
#definition[
$P = {x_0, ..., x_n}$ is *partition* of $[a, b]$ if $a = x_0 < dots.h.c < x_n = b$.
]
#definition[
$f: [a, b] -> RR$ is *piecewise linear* if there exists partition $P = {x_0, ..., x_n}$ and $m_i, c_i in RR$ such that $ forall i in [n], forall x in \(x_(i - 1), x_i\), quad f(x) = m_i x + c_i $ $f$ is continuous on $[a, b] - P$.
]
#definition[
$g: [a, b] -> RR$ is *step function* if there exists partition $P = {x_0, ..., x_n}$ and $m_i in RR$ such that $ forall i in [n], forall x in \(x_(i - 1), x_i\), quad g(x) = m_i $ $g$ is continuous on $[a, b] - P$.
]
#theorem[
Let $f: E -> RR$ continuous, $E$ closed and bounded. Then there exist continuous piecewise linear $f_n$ with $f_n -> f$ uniformly, and step functions $g_n$ with $g_n -> f$ uniformly.
]
#definition[
$f: E -> RR$ is *Lipschitz* if $ exists C > 0: forall x, y in E, quad |f(x) - f(y)| <= C|x - y| $
]
#definition[
$f: E -> RR$ is *bi-Lipschitz* if $ exists C > 0: forall x, y in E, quad C^(-1)|x - y| <= |f(x) - f(y)| <= C|x - y| $
]
== The extended real numbers
#definition[
*Extended reals* are $RR union {-oo, oo}$ with the order relation $-oo < oo$ and $forall x in RR, -oo < x < oo$. $oo$ is an upper bound and $-oo$ is a lower bound for every $x in RR$, so $sup(RR) = oo$, $inf(RR) = -oo$, $sup(nothing) = -oo$, $inf(nothing) = oo$.
- Addition: $forall a in RR, a + oo = oo and a + (-oo) = -oo$. $oo + oo = oo - (-oo) = oo$. $oo - oo$ is undefined.
- Multiplication: $forall a > 0, a dot.op oo = oo$, $forall a < 0, a dot.op oo = -oo$. Also $oo dot.op oo = oo$.
- $limsup$ and $liminf$ are defined as $ limsup x_n := inf{sup{x_k: k >= n}: n in NN}, quad liminf x_n := sup{inf{x_k: k >= n}: n in NN} $
]
#definition[
Extended real number $l$ is *limit* of $(x_n)$ if either
- $forall epsilon > 0, exists N in NN: forall n >= N, |x_n - l| < epsilon$. Then $(x_n)$ *converges to $l$*. or
- $forall Delta > 0, exists N in NN: forall n >= N, x_n > Delta$ (limit is $oo$) or
- $forall Delta > 0, exists N in NN: forall n >= N, x_n < -Delta$ (limit is $-oo$).
$(x_n)$ *converges in the extended reals* if it has a limit in the extended reals.
]
= Further analysis of subsets of $RR$
== Countability and uncountability
#definition[
$A$ is *countable* if $A = nothing$, $A$ is finite or there is a bijection $phi: NN -> A$ (in which case $A$ is *countably infinite*). Otherwise $A$ is *uncountable*. *Enumeration* is bijection to $A$ from $[n]$ or $NN$.
]
#proposition[
If there is surjection from countable set to $A$, or injection from $A$ to countable set, then $A$ is countable.
]
#proposition[
Any subset of $NN$ is countable.
]
#proposition[
$QQ$ is countable.
]
#proposition[
If $(a_n)$ is a nonnegative sequence and $phi: NN -> NN$ is a bijection then $ sum_(n = 1)^infinity a_n = sum_(n = 1)^infinity a_(phi(n)) $
]
#proposition[
If $\(a_(n, k)\)$ is a nonnegative sequence and $phi: NN -> NN times NN$ is a bijection then $ sum_(n = 1)^infinity sum_(k = 1)^infinity a_(n, k) = sum_(n = 1)^infinity a_(phi(n)) $
]
#definition[
$f: X -> Y$ is *monotone* if $x >= y => f(x) >= f(y)$ or $x <= y => f(x) >= f(y)$.
]
#proposition[
Let $f$ be monotone on $(a, b)$. Then it is discontinuous on a countable set.
]
#lemma[
Set of sequences in ${0, 1}$, $\{(x_n)_(n in NN): forall n in NN, x_n in {0, 1}\}$ is uncountable.
]
#theorem[
$RR$ is uncountable.
]
== The structure theorem for open sets
#definition[
Collection ${A_i: i in I}$ of sets is *(pairwise) disjoint* if $n != m ==> A_n sect A_m = nothing$.
]
#theorem(name: "Structure theorem for open sets")[
Let $U subset.eq RR$ open. Then exists countable collection of disjoint open intervals ${I_n: n in NN}$ such that $U = union_(n in NN) I_n$.
]
== Accumulation points and perfect sets
#definition[
$x in RR$ is *accumulation point* of $E subset.eq RR$ if $x$ is point of closure of $E - {x}$. Equivalently, $x$ is a point of closure if $ forall epsilon > 0, exists y in E: y != x and |x - y| < epsilon $ Equivalently, there exists a sequence of distinct $y_n in E$ with $y_n -> x$ as $n -> oo$.
]
#proposition[
Set of accumulation points of $QQ$ is $RR$.
]
#proposition[
Set of accumulation points $E'$ of $E$ is closed.
]
#definition[
$E subset.eq RR$ is *isolated* if $ forall x in E, exists epsilon > 0: (x - epsilon, x + epsilon) sect E = {x} $
]
#proposition[
$E$ is isolated iff it has no accumulation points.
]
#definition[
Bounded set $E$ is *perfect* if it equals its set of accumulation points.
]
#theorem[
Every non-empty perfect set is uncountable.
]
== The middle-third Cantor set
#proposition[
Let ${F_n: n in NN}$ be collection of non-empty nested closed sets (so $F_(n + 1) subset.eq F_n$), one of which is bounded. Then $ sect.big_(n in NN) F_n != emptyset $
]
#definition[
The *middle third Cantor set* is defined by:
- Define $C_0 := [0, 1]$
- Given $C_n = union_(i = 1)^(2^n) [a_i, b_i]$, $a_1 < b_1 < a_2 < dots.h.c < a_(2^n) < b_(2^n)$, with $|b_i - a_i| = 3^(-n)$, define $ C_(n + 1) := union_(i = 1)^(2^n) [a_i, a_i + 3^(-(n + 1))] union [b_i - 3^(-(n + 1)), b_i] $ which is a union of $2^(n + 1)$ disjoint intervals, with all differences in endpoints equalling $3^(-(n + 1))$.
- The *middle third Cantor set* is $ C := sect.big_(n in NN_0) C_n $ Observe that if $a$ is an endpoint of an interval in $C_n$, it is contained in $C$.
]
#proposition[
The middle third Cantor set is closed, non-empty and equal to its set of accumulation points. Hence it is perfect and so uncountable.
]
#definition[
Let $k in NN - {1}$, $x in lr([0, 1))$. $0.a_1 a_2 ...$, $a_i in {0, ..., k - 1}$, is a *$k$-ary expansion* of $x$ if $ x = sum_(i in NN) a_i / k^i $
]
#remark[
The $k$-ary expansion may not be unique, but there is a countable set $E subset.eq lr([0, 1))$ such that every $x in lr([0, 1)) - E$ has a unique $k$-ary expansion.
]
#remark[
For every $x in C$, the ternary ($k = 3$) expansion of $x$ is unique and $ x = sum_(i in NN) a_i / 3^i, quad a_i in {0, 2} $ Moreover, every choice of sequence $(a_i)$, $a_i in {0, 2}$, gives $x = sum_(i in NN) a_i / 3^i in C$.
]
#definition[
*Cantor-Lebesgue function*, $g: [0, 1] -> [0, 1]$, is defined by $ g(x) := cases(sum_(i in NN) (a_i\/2) / 2^i & "if" x = sum_(i in NN) a_i / 3^i \, a_i in {0, 2}, sup{g(y): y in C, y <= x} & "if" x in.not C) $ $g$ is a surjection, monotone and continuous.
]
== $G_delta, F_sigma$
#definition[
$E subset.eq RR$ is *$G_delta$* if $E = sect_(n in NN) U_n$ with $U_n$ open.
]
#definition[
$E subset.eq RR$ is *$F_sigma$* if $E = union_(n in NN) F_n$ with $F_n$ closed.
]
#lemma[
Set of points where $f: RR -> RR$ is continuous is $G_delta$.
]
= Construction of Lebesgue measure
== Lebesgue outer measure
#definition[
Let $I$ non-empty interval with endpoints $a = inf(I) in {-oo} union RR$ and $b = sup(I) in RR union {oo}$. The *length* of $I$ is $ ell(I) := b - a $ and set $ell(nothing) = 0$.
]
#definition[
Let $A subset.eq RR$. *Lebesgue outer measure* of $A$ is infimum of all sums of lengths of intervals covering $A$: $ mu^*(A) := inf{sum_(k in NN) ell(I_k): A subset.eq union.big_(k in NN) I_k, I_k "intervals"} $ It satisfies *monotonicity*: $A subset.eq B ==> mu^*(A) <= mu^*(B)$.
]
#proposition[
Outer measure is *countably subadditive*: $ mu^*(union.big_(k in NN) E_k) <= sum_(k in NN) mu^*(E_k) $ This implies *finite subadditivity*: $ mu^*(union.big_(k = 1)^n E_k) <= sum_(k = 1)^n mu^*(E_k) $
]
#lemma[
We have $ mu^*(A) = inf{sum_(k in NN) ell(I_k): A subset union.big_(k in NN) I_k, I_k != nothing "open intervals"} $
]
#proposition[
Outer measure of interval is its length: $mu^*(I) = ell(I)$.
]
== Measurable sets
#notation[
$E^c = RR - E$.
]
#proposition[
Let $E = (a, oo)$. Then $ forall A subset.eq RR, quad mu^*(A) = mu^*(A sect E) + mu^*(A sect E^c) $
]
#definition[
$E subset.eq RR$ is *Lebesgue measurable* if $ forall A subset.eq RR, quad mu^*(A) = mu^*(A sect E) + mu^*(A sect E^c) $ Collection of such sets is $cal(F)_(mu^*)$.
]
#lemma(name: "Excision Property")[
Let $E$ Lebesgue measurable set with finite measure and $E subset.eq B$, then $ mu^*(B - E) = mu^*(B) - mu^*(E) $
]
#proposition[
If $E_1, ..., E_n$ Lebesgue measurable then $union_(k = 1)^n E_k$ is Lebesgue measurable. If $E_1, ..., E_n$ disjoint then $ mu^*(A sect union.big_(k = 1)^n E_k) = sum_(k = 1)^n mu^*(A sect E_k) $ for any $A subset.eq RR$. In particular, for $A = RR$, $ mu^*(union.big_(k = 1)^n E_k) = sum_(k = 1)^n mu^*(E_k) $
]
#remark[
Not every set is Lebesgue measurable.
]
#definition[
Collection of subsets of $RR$ is an *algebra* if contains $nothing$ and closed under taking complements and finite unions: if $A, B in cal(A)$ then $RR - A, A union B in cal(A)$.
]
#remark[
A union of a countable collection of Lebesgue measurable sets is also the union of a countable disjoint collection of Lebesgue measurable sets: if ${A_k}_(k in NN)$ is countable collection of Lebesgue measurable sets, then let $A_1 ' := A_1$ and for $k > 1$, define $ A_k ' := A_k - union_(i = 1)^(k - 1) A_i $ then ${A_k '}_(k in NN)$ is disjoint union of Lebesgue measurable sets and $union_(k in NN) A_k ' = union_(k in NN) A_k$.
]
#proposition[
If $E$ is countable union of Lebesgue measurable sets, then $E$ is Lebesgue measurable. Also, if ${E_k}_(k in NN)$ is countable disjoint collection of Lebesgue measurable sets then $ mu (union.big_(k in NN) E_k) = sum_(k in NN) mu (E_k) $
]
== Abstract definition of a measure
#definition[
Let $X subset.eq RR$. Collection of subsets of $cal(F)$ of $X$ is *$sigma$-algebra* if
- $nothing in cal(F)$
- $E in cal(F) ==> E^c in cal(F)$
- If $forall k in NN, E_k in cal(F)$ then $union_(k in NN) E_k in cal(F)$.
]
#example[
- Trivial examples are $cal(F) = {nothing, RR}$ and $cal(F) = cal(P)(RR)$.
- Countable intersections of $sigma$-algebras are $sigma$-algebras.
]
#definition[
Let $cal(F)$ $sigma$-algebra of $X$. $nu: cal(F) -> RR union {plus.minus oo}$ is *measure* satisfying
- $nu(nothing) = 0$
- $forall E in cal(F), nu(E) >= 0$
- *Countable additivity*: if $E_1, E_2, ... in cal(F)$ are disjoint then $ nu(union.big_(k in NN) E_k) = sum_(k in NN) nu(E_k) $
Elements of $cal(F)$ are *measurable* (as they are the only sets on which the measure $nu$ is defined).
]
#proposition[
If $nu$ is measure then it satisfies:
- *Monotonicity*: $A subset.eq B ==> nu(A) <= nu(B)$.
- *Countable subadditivity*: $nu(union_(k in NN) E_k) <= sum_(k in NN) nu(E_k)$.
- *Excision*: if $B$ has finite measure, then $A subset.eq B ==> nu(B - A) = nu(B) - nu(A)$.
]
== Lebesgue measure
#lemma[
$F_(mu^*)$ is $sigma$-algebra and contains every interval.
]
#theorem(name: "Carathéodory Extension")[
Restriction of the $mu^*$ to $F_(mu^*)$ is a measure.
]
#theorem(name: "Hahn extension theorem")[
There exists unique measure $mu$ defined on $cal(F)_(mu^*)$ for which $mu(I) = ell(I)$ for any interval $I$.
]
#definition[
The measure $mu$ of $mu^*$ restricted to $cal(F)_(mu^*)$ is the *Lebesgue measure*. It satisfies $mu(I) = ell(I)$ for any interval $I$ and is translation invariant.
]
== Sets of measure $0$
#proposition[
Middle-third Cantor set is Lebesgue measurable and has Lebesgue measure $0$.
]
#proposition[
Any countable set is Lebesgue measurable and has Lebesgue measure $0$.
]
#proposition[
Any $E$ with $mu^*(E) = 0$ is Lebesgue measurable and has $mu(E) = 0$.
]
#lemma[
Let $E$ Lebesgue measurable set with $mu(E) = 0$, then $forall E' subset.eq E$, $E'$ is Lebesgue measurable.
]
== Continuity of measure
#definition[
Countable collection ${E_k}_(k in NN)$ is *ascending* if $forall k in NN, E_k subset.eq E_(k + 1)$ and *descending* if $forall k in NN, E_(k + 1) subset.eq E_k$.
]
#theorem[
Every measure $m$ satisfies:
- If ${A_k}_(k in NN)$ is ascending collection of measurable sets, then $ m(union.big_(k in NN) A_k) = lim_(k -> oo) m(A_k) $
- If ${B_k}_(k in NN)$ is descending collection of measurable sets and $m(B_1) < oo$, then $ m(sect.big_(k in NN) B_k) = lim_(k -> oo) m(B_k) $
]
== An approximation result for Lebesgue measure
#definition[
*Borel $sigma$-algebra* $cal(B)(RR)$ is smallest $sigma$-algebra containing all intervals: for any other $sigma$-algebra $cal(F)$ containing all intervals, $cal(B)(RR) subset.eq cal(F)$. $ cal(B)(RR) := sect.big {cal(F): cal(F) " " sigma "-algebra containing all intervals"} $ $E in cal(B)(RR)$ is *Borel* or *Borel measurable*.
]
#lemma[
All open subsets of $RR$, closed subsets of $RR$, $G_delta$ sets and $F_sigma$ sets are Borel.
]
#proposition[
The following are equivalent:
- $E$ is Lebesgue measurable
- $forall epsilon > 0, exists "open" G: E subset.eq G and mu^*(G - E) < epsilon$
- $forall epsilon > 0, exists "closed" F: F subset.eq E and mu^*(E - F) < epsilon$
- $exists G in G_delta: E subset.eq G and mu^*(G - E) = 0$
- $exists F in F_sigma: F subset.eq E and mu^*(E - F) = 0$
]
= Measurable functions
== Definition of a measurable function
#proposition[
Let $f: RR -> RR$. $f$ continuous iff $forall "open" U subset.eq RR, f^(-1)(U) subset.eq RR$ is open.
]
#lemma[
Let $f: E -> RR union {plus.minus oo}$ with $E$ Lebesgue measurable. The following are equivalent:
- $forall c in RR, {x in E: f(x) > c}$ is Lebesgue measurable.
- $forall c in RR, {x in E: f(x) >= c}$ is Lebesgue measurable.
- $forall c in RR, {x in E: f(x) < c}$ is Lebesgue measurable.
- $forall c in RR, {x in E: f(x) <= c}$ is Lebesgue measurable.
The same statement holds for Borel measurable sets.
]
#definition[
$f: E -> RR union {plus.minus oo}$ is *(Lebesgue) measurable* if it satisfies any of the above properties and if $E$ is Lebesgue measurable. $f$ being *Borel measurable* is defined similarly.
]
#corollary[
If $f$ is Lebesgue measurable then for every $B in cal(B)(RR)$, $f^(-1)(B)$ is measurable. In particular, if $f$ is Lebesgue measurable, preimage of any interval is measurable.
]
#definition[
*Indicator function* on set $A$, $indicator(A): RR -> {0, 1}$, is $ indicator(A)(x) := cases(1 & "if" x in A, 0 & "if" x in.not A) $
]
#definition[
$phi: RR -> RR$ is *simple (measurable) function* if $phi$ is measurable function that has finite codomain.
]
== Fundamental aspects of measurable functions
#definition[
Let $E subset.eq F subset.eq RR$, let $f: F -> RR$. *Restriction* $f_E$ is function with domain $E$ and for which $forall x in E, f_E (x) = f(x)$.
]
#definition[
Real-valued function which is increasing or decreasing is *monotone*.
]
#definition[
Sequence $(f_n)$ on domain $E$ is increasing if $f_n <= f_(n + 1)$ on $E$ for all $n in NN$.
]
#example[
Continuous functions are measurable.
]
#definition[
For $f_1: E -> RR, ..., f_n: E -> RR$, define $ max{f_1, ..., f_n}(x) := max{f_1 (x), ..., f_n (x)} $ $min{f_1, ..., f_n}$ is defined similarly.
]
#proposition[
For finite family ${f_k}_(k = 1)^n$ of measurable functions with common domain $E$, $max{f_1, ..., f_n}$ and $min{f_1, ..., f_n}$ are measurable.
]
#definition[
For $f: E -> RR$, functions $|f|, f^+, f^-$ defined on $E$ are $ |f|(x) := max{f(x), -f(x)}, quad f^+ (x) := max{f(x), 0}, quad f^- (x) := max{-f(x), 0} $
]
#corollary[
If $f$ measurable on $E$, so are $|f|$, $f^+$ and $f^-$.
]
#proposition[
Let $f: E -> RR union {plus.minus oo}$. For measurable $D subset.eq E$, $f$ measurable on $E$ iff restrictions of $f$ to $D$ and $E - D$ are measurable.
]
#theorem[
Let $f, g: E -> RR$ measurable.
- *Linearity*: $forall alpha, beta in RR, alpha f + beta g$ is measurable.
- *Products*: $f g$ is measurable.
]
#proposition[
Let $f_n: E -> RR union {plus.minus oo}$ be sequence of measurable functions that converges pointwise to $f: E -> RR union {plus.minus oo}$. Then $f$ is measurable.
]
#lemma(name: "Simple approximation lemma")[
Let $f: E -> RR$ measurable and bounded, so $exists M >= 0: forall x in E, |f|(x) < M$. Then $forall epsilon > 0$, there exist simple measurable functions $phi_epsilon, psi_epsilon: E -> RR$ such that $ forall x in E, quad phi_epsilon (x) <= f(x) <= psi_epsilon (x) and 0 <= psi_epsilon (x) - phi_epsilon (x) < epsilon $
]
#theorem(name: "Simple approximation theorem")[
Let $f: E -> RR union {plus.minus oo}$, $E$ measurable. Then $f$ is measurable iff there exists sequence $(phi_n)$ of simple functions on $E$ which converge pointwise on $E$ to $f$ and satisfy $ forall n in NN, forall x in E, |phi_n|(x) <= |f|(x) $ If $f$ is nonnegative, $(phi_n)$ can be chosen to be increasing.
]
#definition[
Let $f, g: E -> RR union {plus.minus oo}$. Then $f = g$ *almost everywhere* if ${x in E: f(x) != g(x)}$ has measure $0$.
]
#proposition[
Let $f_1, f_2, f_3: E -> RR union {plus.minus oo}$ measurable. If $f_1 = f_2$ almost everywhere and $f_2 = f_3$ almost everywhere then $f_1 = f_3$ almost everywhere.
]
#remark[
Lebesgue measurable functions can be modified arbitrarily on a set of measure $0$ without affecting measurability.
]
#proposition[
Let $f_n: E -> RR union {plus.minus oo}$ sequence of measurable functions, $f: E -> RR union {plus.minus oo}$ measurable. Set of points where $(f_n)$ converges pointwise to $f$ is measurable.
]
#proposition[
Let $f, g: E -> RR union {plus.minus oo}$ measurable and finite almost everywhere on $E$.
- *Linearity*: $forall alpha, beta in RR$, there exists function equal to $alpha f + beta g$ almost everywhere on $E$ (any such function is measurable).
- *Products*: there exists function equal to $f g$ almost everywhere on $E$ (any such function is measurable).
]
#definition[
Sequence of functions $(f_n)$ with domain $E$ *converge in measure* to $f$ if $(f_n)$ and $f$ are finite almost everywhere and $ forall epsilon > 0, quad mu({x in E: |f_n (x) - f(x)| > epsilon}) -> 0 "as" n -> oo $
]
= The Lebesgue integral
== The integral of a simple measurable function
#definition[
Let $phi$ be real-valued function taking finitely many values $alpha_1 < dots.h.c < alpha_n$, then *standard representation* of $phi$ is $ phi = sum_(i = 1)^n alpha_i bb(1)_(A_i), quad A_i = phi^(-1)({alpha_i}) $
]
#lemma[
Let $phi = sum_(i = 1)^m beta_i indicator(B_i)$, $B_i$ disjoint measurable collection, $beta_i in RR$, then $phi$ is simple measurable. If $phi$ takes value $0$ outside a set of finite measure then $ sum_(i = 1)^n alpha_i mu(A_i) = sum_(i = 1)^m beta_i mu(B_i) $ where $A_i$ in standard representation.
]
#definition[
Let $phi$ be simple nonnegative measurable function or simple measurable function taking value $0$ outside set of finite measure. *Integral* of $phi$ with respect to $mu$ is $ integral phi = sum_(i = 1)^n alpha_i mu(A_i) $ where $phi = sum_(i = 1)^n alpha_i bb(1)_(A_i)$ is standard representation. Here, use convention $0 dot.op oo = 0$. For measurable $E subset.eq RR$, define $ integral_E phi = integral indicator(E) phi $
]
#example[
- Let $phi_2 = indicator([0, 2]) + indicator([1, 3]) = indicator(lr([0, 1) union lr((2, 3]))) + 2 indicator([1, 2])$ so $integral phi_2 = 4$.
- Let $phi_3 = indicator(RR)$, then $integral phi_3 = 1 dot.op oo = oo$.
- Let $phi_4 = bb(1)_((0, oo)) + (-1) indicator((-oo, 0))$. This can't be integrated.
- Let $phi_5 = indicator((-1, 0)) + (-1) indicator((0, 1))$, then $integral phi_5 = 0$.
]
#lemma[
Let $B_1, ..., B_m$ be measurable sets, $beta_1, ..., beta_m in RR - {0}$. Then $phi = sum_(i = 1)^m beta_i indicator(B_i)$ is simple measurable function. Also, $ mu(union.big_(i = 1)^m B_i) < oo ==> sum_(i = 1)^n alpha_i mu(A_i) = sum_(i = 1)^m beta_i mu(B_i) $ where $A_i$ in standard representation.
]
#proposition[
Let $phi, psi$ be simple measurable functions:
- If $phi, psi$ take value $0$ outside a set of finite measure, then $forall alpha, beta in RR$, $ integral (alpha phi + beta psi) = alpha integral phi + beta integral psi $
- If $phi, psi$ nonnegative, then $forall alpha, beta >= 0$, $ integral (alpha phi + beta psi) = alpha integral phi + beta integral psi $
- *Monotonicity*: $ 0 <= phi <= psi ==> 0 <= integral phi <= integral psi $
]
#corollary[
Let $phi$ nonnegative simple function, then $ integral phi = sup{integral psi: 0 <= psi <= phi, thick psi "simple measurable"} $
]
#lemma[
Let $phi$ simple measurable nonnegative function. $phi$ takes value $0$ outside a set of finite measure iff $integral phi < oo$. Also, $integral phi = oo$ iff there exist $alpha > 0$, measurable $A$ with $mu(A) = oo$ and $forall x in A, phi(x) >= alpha$.
]
#lemma[
Let ${E_n}$ be ascending collection of measurable sets, $union_(n in NN) E_n = RR$. Let $phi$ be simple nonnegative measurable function. Then $ integral_(E_n) phi -> integral phi quad "as" n -> oo $
]
== The integral of a nonnegative function
#notation[
Let $cal(M)^+$ denote collection of nonnegative measurable functions $f: RR -> RR_(>= 0) union {oo}$.
]
#definition[
*Support* of measurable function $f$ with domain $E$ is $"supp"(f) := {x in E: f(x) != 0}$.
]
#definition[
Let $f in cal(M)^+$. *Integral of $f$ with respect to $mu$* is $ integral f := sup{integral phi: 0 <= phi <= f, phi "simple measurable"} in RR union {oo} $ For measurable set $E$, define $ integral_E f := integral indicator(E) f $
]
#proposition(name: "Monotonicity")[
Let $f, g$ measurable, nonnegative. If $g <= f$ then $integral g <= integral f$. Let $E, F$ measurable. If $E subset.eq F$ then $integral_E f <= integral_F f$.
]
#theorem(name: "Monotone convergence theorem")[
Let $(f_n)$ be sequence in $cal(M)^+$. If $(f_n)$ is increasing on measurable set $E$ and converges pointwise to $f$ on $E$ then $ integral_E f_n -> integral_E f quad "as" n -> oo $
]
#corollary[
Restriction of integral to nonnegative functions is linear: $forall f, g in cal(M)^+$, $forall alpha >= 0$, $ integral (f + g) & = integral f + integral g \ integral alpha f & = alpha integral f $
]
#lemma(name: "Fatou's Lemma")[
Let $(f_n)$ be sequence in $cal(M)^+$, then $ integral liminf_(n -> oo) f_n <= liminf_(n -> oo) integral f_n $
]
#lemma[
Let $(f_n) subset cal(M)^+$, then $ integral sum_(n in NN) f_n = sum_(n in NN) integral f_n $
]
#proposition(name: "Chebyshev's inequality")[
Let $f$ be nonnegative measurable function on $E$. Then $ forall lambda > 0, quad mu({x in E: f(x) >= lambda}) <= 1/lambda integral_E f $
]
#proposition[
Let $f$ be nonnegative measurable function on $E$. Then $ integral_E f = 0 <==> f = 0 "almost everywhere on" E $
]
== Integration of measurable functions
#notation[
Let $cal(M)$ denote set of measurable functions.
]
#definition[
$f in cal(M)^+$ is *integrable* if $integral f < oo$. By Chebyshev's inequality, if $f$ is integrable, then $f$ is finite almost everywhere.
]
#definition[
Let $f: RR -> RR union {plus.minus oo}$ measurable function. $f$ is *integrable* if $integral f^+$ and $integral f^-$ are finite. In this case, for any measurable set $E$, define $ integral_E f := integral_E f^+ - integral_E f^- $ Note that if $f$ integrable then $f^+ - f^-$ is well-defined.
]
#proposition[
If $f = f_1 - f_2$, $f_1, f_2 in cal(M)^+$, $f_1, f_2$ integrable, then $ integral f^+ - integral f^- = integral f_1 - integral f_2 $
]
#definition[
$f in cal(M)$ is *integrable over $E$* ($E$ is measurable) if $integral_E f^+$ and $integral_E f^-$ are finite (i.e. $f dot.op indicator(E)$ is integrable).
]
#theorem[
$f in cal(M)$ is integrable iff $|f|$ is integrable. If $f$ integrable, then $ abs(integral f) <= integral abs(f) $
]
#corollary[
Let $f, g in cal(M)$, $|f| <= |g|$. If $g$ integrable then $|f|$ is integrable, and $integral |f| <= integral |g|$.
]
#example[
$sin$ is not integrable over $RR$, but is integrable over $[0, 2pi]$, since $|f_([0, 2pi])| <= indicator([0, 2pi])$.
]
#theorem(name: "Linearity of Integration")[
Let $f, g in cal(M)$ integrable. Then $f + g$ is integrable and $forall alpha in RR$, $alpha f$ is integrable. The integral is linear: $ integral (f + g) & = integral f + integral g \ integral alpha f & = alpha integral f $
]
#theorem(name: "Dominated Convergence Theorem")[
Let $(f_n)$ be sequence of integrable functions. If there exists an integrable $g$ with $forall n in NN, |f_n| <= g$, and $f_n -> f$ pointwise almost everywhere then $f$ is integrable and $ integral f = lim_(n -> oo) integral f_n $
]
== Integrability: Riemann vs Lebesgue
#proposition[
Let $f$ bounded function on bounded measurable domain $E$. Then $f$ is measurable and $integral_E |f| < oo$ iff $ sup{integral_E phi: phi <= f, phi "simple measurable"} = inf{integral_E psi: f <= psi: psi "simple measurable"} $ (If $f$ satisfies either condition then $integral_E f$ is equal to the two above expressions).
]
#definition[
Bounded function $f$ is *Lebesgue integrable* if it satisfies either of the equivalences in the above proposition.
]
#definition[
Let $P = {x_0, ..., x_n}$ partition of $[a, b]$, $f: [a, b] -> RR$ bounded. *Lower and upper Darboux sums* for $f$ with respect to $P$ are $ L(f, P) := sum_(i = 1)^n m_i (x_i - x_(i - 1)), quad U(f, P) := sum_(i = 1)^n M_i (x_i - x_(i - 1)) $ where $ m_i := inf{f(x): x in (x_(i - 1), x_i)}, quad M_i := sup{f(x): x in (x_(i - 1), x_i)} $ If $P subset.eq Q$ ($Q$ is a *refinement of $P$*), then $ L(f, P) <= L(f, Q) <= U(f, Q) <= U(f, P) $
]
#definition[
*Lower and upper Riemann integrals* of $f$ over $[a, b]$ are $ underline(cal(I))_a^b (f) & := sup{L(f, P): P "partition of" [a, b]} \ overline(cal(I))_a^b (f) & := inf{U(f, P): P "partition of" [a, b]} $
]
#definition[
Let $f: [a, b] -> RR$ bounded, then $f$ is *Riemann integrable* ($f in cal(R)$), if $ underline(cal(I))_a^b (f) = overline(cal(I))_a^b (f) $ and common value $cal(I)_a^b (f) = integral_a^b f(x) dif x$ is *Riemann integral* of $f$.
]
#remark[
Let $g: [a, b] -> RR$ step function with discontinuities at $P = {x_0, ..., x_n}$, so $g = sum_(i = 1)^n alpha_i indicator((x_(i - 1), x_i))$ almost everywhere. So $g$ is simple measurable and $ L(g, P) = sum_(i = 1)^n alpha_i (x_i - x_(i - 1)) = U(g, P) = integral g = cal(I)_a^b (g) $ Hence for any bounded $f: [a, b] -> RR$, $ underline(cal(I))_a^b (f) & = sup{integral phi: phi <= f, phi "step function"}, \ overline(cal(I))_a^b (f) & = inf{integral psi: f <= psi, psi "step function"} $
]
#theorem[
Let $f: [a, b] -> RR$ bounded, $a, b != plus.minus oo$. If $f$ Riemann integrable over $[a, b]$ then $f$ Lebesgue integrable over $[a, b]$ and the two integrals are equal.
]
#theorem[
Let $f: [a, b] -> RR$ bounded, $a, b != plus.minus oo$. Then $f$ is Riemann integrable on $[a, b]$ iff $f$ is continuous on $[a, b]$ except on a set of measure zero.
]
#lemma[
Let $(phi_n)$, $(psi_n)$ be sequences of functions, all integrable over $E$, $(phi_n)$ increasing on $E$, $(psi_n)$ decreasing on $E$. Let $f: E -> RR$ with $ forall n in NN, phi_n <= f <= psi_n "on" E, quad lim_(n -> oo) integral_E (psi_n - phi_n) = 0 $ Then $phi_n, psi_n -> f$ pointwise almost everywhere on $E$, $f$ is integrable over $E$ and $ lim_(n -> oo) integral_E phi_n = lim_(n -> oo) integral_E psi_n = integral_E f $
]
#definition[
For partition $P = {x_0, ..., x_n}$, *gap* of $P$ is $ "gap"(P) := max{|x_i - x_(i - 1)|: i in {1, ..., n}} $
]
#lemma[
Let $f: [a, b] -> RR$, $E subset.eq [a, b]$ be set where $f$ is continuous. Let $(P_n)$ be sequence of partitions of $[a, b]$ with $P_(n + 1) subset.eq P_n$ and $"gap"(P_n) -> 0$ as $n -> oo$. Let $phi_n, psi_n: [a, b] -> RR$ step functions with $ phi_n (x) := inf{f(x): x in (x_(i - 1), x_i)}, quad psi_n (x) := sup{f(x): x in (x_(i - 1), x_i)} $ for $P_n = {x_0, ..., x_n}$. Then $forall x in E - union_(n in NN) P_n$, $ phi_n (x), psi_n (x) -> f(x) quad "as" n -> oo $
]
#definition[
Let $f: lr((a, b]) -> RR$, $-oo <= a < b < oo$, $f$ bounded and Riemann integrable on all closed bounded sub-intervals of $lr((a, b])$. If $ lim_(t -> a, t > a) cal(I)_t^b (f) $ exists then this is defined as the *improper Riemann integral* $cal(I)_a^b (f)$. Similar definitions exist for $f: (a, b) -> RR$ and $f: lr([a, b)) -> RR$.
]
#note[
Improper Riemann integral may exist without function being Lebesgue integral.
]
#proposition[
If $f$ is integrable, the improper Riemann integral is equal to the Lebesgue integral whenever the former exists.
]
#definition[
Let $alpha: [a, b] -> RR$ monotonically increasing (and so bounded). For partition $P = {x_0, ..., x_n}$ of $[a, b]$ and bounded $f: [a, b] -> RR$, define $ L(f, P, alpha) := sum_(i = 1)^n m_i (alpha(x_i) - alpha(x_(i - 1))), quad U(f, P, alpha) := sum_(i = 1)^n M_i (alpha(x_i) - alpha(x_(i - 1))) $ where $m_i := inf{f(x): x in (x_(i - 1), x_i)}$, $M_i := sup{f(x): x in (x_(i - 1), x_i)}$. Then $f$ is *integrable with respect to $alpha$*, $f in cal(R)(alpha)$, if $ inf{U(f, P, alpha): P "partition of" [a, b]} = sup{L(f, P, alpha): P "partition of" [a, b]} $ and the common value $integral_a^b f dif alpha$ is the *Riemann-Stieltjes integral* of $f$ with respect to $alpha$.
]
#proposition[
Let $f: (a, b) -> RR$, then set of points where $f$ is differentiable is measurable.
]
#remark[
If $alpha: [0, 1] -> [a, b]$ bijection, then $ integral_0^1 f compose alpha dif alpha = integral_a^b f(x) dif x $
]
#proposition[
Let $alpha$ be monotonically increasing and differentiable with $alpha' in cal(R)$. Then $g in cal(R)(alpha)$ iff $g alpha' in cal(R)$, and in that case, $ integral_a^b g dif alpha = integral_a^b g(x) alpha'(x) dif x $
]
#remark[
When $g = 1$, this says $integral_a^b 1 dif alpha = alpha(b) - alpha(a) = integral alpha'(x) dif x$, similar to the fundamental theorem of calculus.
]
= Lebesgue spaces
== Normed linear spaces
#definition[
Let $X$ be *complex linear space* (vector space over $CC$). $norm(dot.op): X -> RR_(>=0)$ is *norm on $X$* if
- $forall x in X, norm(x) = 0 <==> x = 0$.
- $forall x in X, forall lambda in CC, norm(lambda x) = |lambda| norm(x)$.
- $forall x, y in X, norm(x + y) <= norm(x) + norm(y)$.
$X$ equipped with norm $norm(dot.op)$, $(X, norm(dot.op))$, is called *complex normed linear space*.
]
#example[
- $norm(x) = sqrt(x overline(x))$ is norm on $CC$.
- Let $C[a, b]$ denote linear space of continuous real-valued functions on $[a, b]$. Then $ norm(f)_max := max{|f(x)|: x in [a, b]} $ is norm on $C[a, b]$.
]
#proposition[
Norm induces metric on $X$: $d(x, y) = norm(x - y)$.
]
#definition[
Let $(X, norm(dot.op))$ be normed linear space.
- Sequence $(f_n)$ in $X$ is *Cauchy sequence* in $X$ if $ forall epsilon > 0, exists N in NN: forall n, m >= N, quad norm(f_n - f_m) < epsilon $
- Sequence $(f_n)$ in $X$ *converges in $X$*, $norm(f_n - f) -> 0$ as $n -> oo$, if $ exists f in X: forall epsilon > 0, exists N in NN: forall n >= N, quad norm(f_n - f) < epsilon $
- $(X, norm(dot.op))$ is *complete* if every Cauchy sequence converges in $X$.
- *Banach space* is complete normed linear space.
]
#proposition[
Let $(X, norm(dot.op))$ be normed linear space.
- If $(x_n)$ converges in $X$, $(x_n)$ is Cauchy sequence in $X$.
- Let $(x_n)$ be Cauchy sequence in $X$. If $(x_n)$ has convergent subsequence in $X$ then $(x_n)$ converges in $X$.
]
== Lebesgue spaces $L^p$, $p in lr([1, oo))$
#definition[
Let $p in lr([1, oo))$, $E subset.eq RR$.
- Linear space $L^p (E)$ is defined as $ L^p (E) := {f: E -> CC: f "is measurable and" integral_E |f|^p < oo} \/ tilde.equiv $ where $f tilde.equiv g$ iff $f = g$ almost everywhere: $ f tilde.equiv g <==> exists F subset.eq E: mu(F) = 0 and forall x in E - F, f(x) = g(x) $
- Define $norm(dot.op)_(L^p): L^p (E) -> RR$ as $ norm(f)_(L^p) := (integral_E |f|^p)^(1\/p) $
]
#remark[
- We often consider space $L^p (E)$ of real-valued measurable functions $f: E -> RR$ such that $integral_E |f|^p < oo$.
- For $f: E -> CC$, $f = f_1 + i f_2$, $f$ is measurable iff $f_1: E -> RR$ and $f_2: E -> RR$ are measurable. Also, $ integral_E |f|^p < oo <==> (integral_E |f_1|^p < oo and integral_E |f_2|^p < oo) $
]
#example[
Let $E = RR$, $f(x) = indicator(RR - QQ)(x) + i indicator(QQ)(x)$ and $g(x) = 1$. Then $mu(QQ) = 0$ so $f tilde.equiv g$.
]
#proposition[
Let $(f_n), (g_n)$ sequences of measurable functions, $forall n in NN, f_n tilde.equiv g_n$, $lim_(n -> oo) f_n = f$ and $lim_(n -> oo) g_n = g$. Then $f tilde.equiv g$.
]
#definition[
$p, q in RR$ are *conjugate exponents* if $p > 1$ and $1/p + 1/q = 1$.
]
#lemma(name: "Young's inequality")[
Let $p, q$ conjugate exponents, then $ forall A, B in RR_(>=0), quad A B <= A^p / p + B^q / q $ with equality iff $A^p = B^q$.
]
#lemma(name: "Hölder's inequality")[
Let $p, q$ conjugate exponents. If $f in L^p (E)$, $g in L^q (E)$, then $ integral_E |f g| <= norm(f)_(L^p) norm(g)_(L^q) $
]
#corollary(name: [Cauchy-Schwarz inequality for $L^2 (E)$])[
If $f, g in L^2 (E)$, then $ abs(integral_E f overline(g)) <= integral_E |f g| <= norm(f)_(L^2) norm(g)_(L^2) $
]
#lemma(name: "Minkowski's inequality")[
Let $p in lr([1, oo))$. If $f, g in L^p (E)$ then $f + g in L^p (E)$ and $ norm(f + g)_(L^p) <= norm(f)_(L^p) + norm(g)_(L^p) $
]
#theorem[
For $p in lr([1, oo))$, $\(L^p (E), norm(dot.op)_(L^p)\)$ is normed linear space.
]
#proposition[
Let $1 <= p < q < oo$. If $mu(E) < oo$ then $L^q (E) subset.eq L^p (E)$ and $ norm(f)_(L^p) <= mu(E)^(1/p - 1/q) norm(f)_(L^q) $
]
#remark[
- Convergence in $L^p$ is also called convergence in the mean of order $p$.
- This notion of convergence is different to pointwise convergence, uniform convergence and convergence in measure.
]
#theorem(name: "Riesz-Fischer")[
For $p in lr([1, oo))$, $\(L^p (E), norm(dot.op)_(L^p)\)$ is complete.
]<riesz-fischer>
== Lebesgue space $L^oo$
#definition[
- Let $f: E -> CC$ measurable. $f$ is *essentially bounded* if $ exists M >= 0: |f(x)| <= M quad "almost everywhere on" E $
- $L^oo (E)$ is collection of equivalence classes of essentially bounded functions where $f tilde.equiv g$ iff $f = g$ almost everywhere.
- For $f in L^oo (E)$, define $ norm(f)_(L^oo) := "ess" sup |f| := inf{M in RR: mu({x in E: |f(x)| > M}) = 0} $
]
#proposition[
- $0 <= |f(x)| <= norm(f)_(L^oo)$ almost everywhere.
- $norm(f)_(L^oo)$ is norm on $L^oo (E)$.
- If $f in L^1 (E)$, $g in L^oo (E)$, then $ integral_E |f g| <= norm(f)_(L^1) norm(g)_(L^oo) $
]
#proposition[
Let $(f_n)$ sequence of functions in $L^oo (E)$. Then $(f_n)$ converges to $f in L^oo (E)$ iff there exists $G subset.eq E$ with $mu(G) = 0$ and $(f_n)$ converges to $f$ uniformly on $E - G$.
]
#theorem[
$\(L^oo (E), norm(dot.op)_(L^oo)\)$ is complete.
]
#remark[
If $mu(E) < oo$, then $L^oo (E) subset L^p (E)$ for $p in lr([1, oo))$ and $ norm(f)_(L^p) <= mu(E)^(1\/p) norm(f)_(L^oo) $ since $ norm(f)_(L^p)^p = integral_E |f|^p <= integral_E norm(f)_(L^oo)^p dot.op indicator(E) = norm(f)_(L^oo)^p mu(E) $
]
== Approximation and separability
#definition[
Let $(X, norm(dot.op))$ be normed linear space. Let $F subset.eq G subset.eq X$. $F$ is *dense in $G$* if $ forall g in G, forall epsilon > 0, exists f in F: quad norm(f - g) < epsilon $
]
#proposition[
- $F$ is dense in $G$ iff for every $g in G$, there exists sequence $(f_n)$ in $F$ such that $lim_(n -> oo) f_n = g$ in $X$.
- For $F subset.eq G subset.eq H subset.eq X$, if $F$ dense in $G$ and $G$ dense in $H$, then $F$ dense in $H$.
]
#proposition[
Let $p in [1, oo]$. Then subspace of simple functions in $\(L^p (E), norm(dot.op)_(L^p)\)$ is dense in $\(L^p (E), norm(dot.op)_(L^p)\)$.
]
#definition[
$psi: RR -> RR$ is *step function* if it can be written as $ psi = sum_(k = 1)^N tilde(a)_k indicator((a_k, b_k)) $ where the intervals $(a_k, b_k)$ are disjoint.
]
#proposition[
Let $[a, b]$ be bounded, $p in [1, oo)$. Then subspace of step functions on $[a, b]$ is dense in $\(L^p ([a, b]), norm(dot.op)_(L^p)\)$.
]
#definition[
Normed linear space $(X, norm(dot.op))$ is *separable* if there exists countable, dense subset $X' subset.eq X$.
]
#example[
$RR$ is separable, since $QQ$ is countable and dense in $RR$.
]
#theorem[
Let $E subset.eq RR$ measurable, $p in [1, oo)$. Then $\(L^p (E), norm(dot.op)_(L^p)\)$ is separable. In particular, step functions are dense in $L^p (E)$ for $p in [1, oo)$.
]
#proposition[
Let $epsilon > 0$, $f in L^p (E)$, $p in [1, oo)$. There exists continuous $g in L^p (E)$ such that $norm(f - g)_(L^p) < epsilon$.
]
#remark[
Linear space of continuous functions that vanish outside bounded set is dense in $\(L^p (E), norm(dot.op)_(L^p)\)$ for $p in [1, oo)$.
]
#remark[
Differentiable functions are also dense in $\(L^p (E), norm(dot.op)_(L^p)\)$ for $p in [1, oo)$.
]
#remark[
Step functions and continuous functions are not dense in $\(L^oo (E), norm(dot.op)_(L^oo)\)$.
]
#example[
In general, $\(L^oo (E), norm(dot.op)_(L^oo)\)$ is not separable. Let $[a, b]$ be bounded, $a != b$. Assume there is countable ${f_n: n in NN}$ which is dense in $\(L^oo ([a, b]), norm(dot.op)_(L^oo)\)$. Then for every $x in [a, b]$, can choose $g(x) in NN$ such that $ norm(indicator([a, x]) - f_(g(x)))_(L^oo) < 1/2 $ Also, for $x_1 <= x_2$, $ norm(indicator([a, x_1]) - indicator([a, x_2]))_(L^oo) = cases(1 & quad "if" a <= x_1 < x_2 <= b, 0 & quad "if" x_1 = x_2) $ and $ norm(indicator([a, x_1]) - indicator([a, x_2]))_(L^oo) & <= norm(indicator([a, x_1]) - f_(g(x_1)))_(L^oo) + norm(f_(g(x_1)) - f_(g(x_2)))_(L^oo) + norm(f_(g(x_2)) - indicator([a, x_2]))_(L^oo) \ & < 1 + norm(f_(g(x_1)) - f_(g(x_2)))_(L^oo) $ If $g(x_1) = g(x_2)$ then $norm(indicator([a, x_1]) - indicator([a, x_2]))_(L^oo) = 0$ so $g: [a, b] -> NN$ is injective. But $NN$ is countable and $[a, b]$ is not countable: contradiction.
]
== Riesz representation theorem for $L^p (E)$, $p in [1, oo)$
#definition[
Let $X$ be linear space. $T: X -> RR$ is *linear functional* if $ forall f, g in X, forall a, b in RR, quad T(a f + b g) = a T(f) + b T(g) $ Any linear combination of linear functionals is linear, so set of linear functionals on linear space is also linear space.
]
#definition[
Let $(X, norm(dot.op))$ be normed linear space. $T: X -> RR$ is *bounded functional* if $ exists M >= 0: forall f in X, quad |T(f)| <= M norm(f) $ *Norm* of $T$, $norm(T)_*$, is the smallest such $M$.
]
#remark[
For bounded linear functional $T$ on normed linear space $(X, norm(dot.op))$, $ |T(f) - T(g)| <= norm(T)_* norm(f - g) $ This gives the following continuity property: if $f_n -> f in X$, then $T(f_n) -> T(f)$.
]
#example[
Let $E subset.eq RR$ measurable, $p in [1, oo)$, $q$ conjugate to $p$. Let $h in L^q (E)$. Define $T: L^p (E) -> RR$ by $ T(f) = integral_E h dot.op f $ By Holder's inequality, $ |T(f)| = abs(integral_E h f) <= integral_E abs(h f) <= norm(h)_(L^q) norm(f)_(L^p) $ So $T$ is bounded linear functional.
]
#remark[
We can write $norm(dot.op)_*$ as $ norm(T)_* := inf{M in RR: forall f in X, |T(f)| <= M norm(f)} = sup{|T(f)|: f in X, norm(f) <= 1} $
]
#definition[
*Dual space* of $X$, $X^*$, is set of bounded linear functionals on $X$ with norm $norm(dot.op)_*$.
]
#proposition[
Let $(X, norm(dot.op))$ be normed linear space, then dual space of $X$ is linear space with norm $norm(dot.op)_*$.
]
#remark[
Bounded linear functional is special case of *bounded linear transformation* between normed spaces. $T: X -> Y$ is bounded linear transformation if $T(a f + b g) = a T(f) + b T(g)$ and $exists M >= 0: norm(T(f))_Y <= M norm(f)_X$.
]
#proposition[
Let $E subset.eq RR$ measurable, $p in [1, oo)$, $q$ conjugate to $p$, $h in L^q (E)$. Define $T: L^p (E) -> RR$ by $ T(f) = integral_E h f $ Then $norm(T)_* = norm(h)_(L^q)$.
]
#theorem(name: [Riesz representation theorem for $L^p$])[
Let $p in [1, oo)$, $q$ conjugate to $p$, $E subset.eq RR$ measurable. For $h in L^q (E)$, define bounded linear functional $R_h: L^p (E) -> RR$ by $ R_h (f) = integral_E h f $ Then for every bounded linear functional $T: L_p (E) -> RR$, there is unique $h in L^q (E)$ such that $ R_h = T quad and quad norm(T)_* = norm(h)_(L^q) $
]
#theorem[
Let $[a, b]$ be non-degenerate, bounded interval, $p in [1, oo)$, $q$ conjugate to $p$. If $T$ is bounded linear functional on $L^p ([a, b])$ then there exists $h in L^q ([a, b])$ such that $ T(f) = integral_a^b h f $
]
= Hilbert spaces
== Inner product spaces
#definition[
Let $H$ be complex linear space. *Inner product* on $H$ is function $ip(dot.op, dot.op): H times H -> CC$ such that $forall a, b in CC, forall x, y, z in H$,
- *Linear in first variable*: $ip(a x + b y, z) = a ip(x, z) + b ip(y, z)$.
- *Conjugate symmetric*: $ip(x, y) = overline(ip(y, x))$.
- *Positive*: $x != 0 ==> ip(x, x) in (0, oo)$
- $ip(x, x) = 0 <==> x = 0$.
These imply that $ip(0, x) = 0$ and inner product is conjugate linear in second variable: $ip(z, a x + b y) = overline(a) ip(z, x) + overline(b) ip(z, y)$.
]
#example[
- $RR^n$ has inner product $ip(x, y) = sum_(i = 1)^n x_i y_i$.
- $CC^n$ has inner product $ip(x, y) = sum_(i = 1)^n x_i overline(y_i)$.
- Inner product induces metric on $H$: $ d(x, y) = ip(x - y, x - y)^(1\/2) $
]
#definition[
Complex linear space $H$ with inner product $ip(dot.op, dot.op)$ is called *pre-Hilbert space* or *inner product space*.
]
#definition[
Let $H$ inner product space. For $x in H$, define the norm $ norm(x) = sqrt(ip(x, x)) $
]
#proposition[
$norm(x plus.minus y)^2 = norm(x)^2 plus.minus 2 "Re"(ip(x, y)) + norm(y)^2$.
]
#theorem(name: "Cauchy-Schwarz inequality")[
Let $(H, ip(dot.op, dot.op))$ be pre-Hilbert space. Then $ forall x, y in H, quad |ip(x, y)| <= norm(x) norm(y) $ with equality iff $x$ and $y$ linearly dependent.
]
#theorem(name: "Parallelogram Identity")[
A normed linear space $X$ is an inner product space with norm derived from the inner product (i.e. $norm(dot.op) = sqrt(ip(dot.op, dot.op))$) iff $ forall x, y in X, quad norm(x + y)^2 + norm(x - y)^2 = 2 norm(x)^2 + 2 norm(y)^2 $
]
#definition[
Let $(X, ip(dot.op, dot.op)_X)$, $(Y, ip(dot.op, dot.op)_Y)$ be inner product spaces.
- An inner product on $X times Y$ is $ ip((x_1, y_1), (x_2, y_2))_(X times Y) = ip(x_1, x_2)_X + ip(y_1, y_2)_Y $
- The associated norm on $X times Y$ is $ norm((x, y))_(X times Y) = sqrt(ip((x, y), (x, y))_(X times Y)) = sqrt(norm(x)_X^2 + norm(y)_Y^2) $
]
#theorem[
Let $X$ inner product space, $x_n -> x$, $y_n -> y$ in $X$. Then $ip(x_n, y_n)_X -> ip(x, y)_X$.
]
#proof[
Use $|ip(x_n, y_n) - ip(x, y)| = |ip(x_n - x, y_n) + ip(x, y_n) - ip(x, y_n) + ip(x, y_n - y)|$ and Cauchy-Schwarz, reverse triangle inequality to show $norm(y_n) -> norm(y)$.
]
#proposition[
The norm and inner product are continuous.
]
== Hilbert spaces
#definition[
Hilbert space is inner product space which is complete with respect to norm induced by inner product.
]
#example[
$RR^n$ with standard inner product is Hilbert space.
]
#example[
Define inner product on $L^2 (E)$ $ ip(f, g)_(L^2) := integral_E f overline(g) $ Induced norm is the $L^2$ norm. So by Riesz-Fischer theorem, $\(L^2 (E), ip(dot.op, dot.op)_(L^2)\)$ is Hilbert space.
]
#definition[
Let $H$ Hilbert space with inner product $ip(dot.op, dot.op)$.
- $x, y in H$ are *orthogonal*, $x perp y$ if $ip(x, y) = 0$.
- $A, B subset.eq H$ are *orthogonal*, $A perp B$ if $forall x in A, forall y in B, quad x perp y$.
- *Orthogonal complement* of $A subset.eq H$ is $ A^perp := {x in H: forall y in A, thick thick x perp y} $
]
#theorem(name: "Pythagorean Theorem")[
If $x_1, ..., x_n in H$, $x_i perp x_j$ for $i != j$, then $ norm(sum_(i = 1)^n x_i)^2 = sum_(i = 1)^n norm(x_i)^2 $
]
#proof[
Use linearity of inner product and orthogonal condition.
]
#theorem[
Let $H$ Hilbert space, $A subset.eq H$, then $A^perp$ is closed subspace of $H$.
]
#proof[
- Subspace:
- For $y, z in A^perp$, $lambda, mu in CC$, show $forall x in A$, $lambda y + mu z in A^perp$.
- Closed:
- Show if $(y_n) subset.eq A^perp$, $y_n -> y$, then $y in A^perp$:
- Let $x in A$, then show $|ip(x, y)| -> 0$ by squeezing, triangle inequality and Cauchy-Schwarz.
]
#theorem(name: "Projection")[
Let $M$ closed subspace of Hilbert space $H$.
- For every $x in H$, there exists unique closest point $y in M$: $ forall x in H, exists! y in M: quad norm(x - y) = min{norm(x - z): z in M} $ We say $y$ is "the best approximation" to $x$ in $M$.
- The point $y in M$ closest to $x in H$ is unique element of $M$ such that $(x - y) perp M$.
]
#proof[
- Let $d = inf{norm(x - z): z in M}$. Show that $exists y in M: norm(x - y) = d$:
- There is sequence $(y_n) subset M$ with $norm(x - y_n) -> d$. Show that $(y_n)$ is Cauchy:
- $norm(y_m - y_n)^2 + norm(2x - y_m - y_n)^2 = 2 norm(x - y_m)^2 + 2 norm(x - y_n)^2$ by parallelogram identity.
- $(y_m + y_n)/2 in M$, so $norm(2x - y_m - y_n) >= 2d$.
- Deduce that $y_n -> y in M$ and $norm(x - y) -> d$ by squeezing.
- Uniqueness of $y$:
- Let $norm(x - y) = d = norm(x - y')$.
- By parallelogram identity, $2 norm(x - y)^2 + 2 norm(x - y')^2 = norm(2x - y - y')^2 + norm(y - y')^2$.
- Use that $(y + y')/2 in M$ to show $norm(y - y') = 0$.
- To show $z = x - y perp M$:
- For $w in M$, write $ip(z, w) = |ip(z, w)| lambda$ where $lambda = e^(i theta)$, set $u = lambda w$.
- Define $f(t) = norm(z + t u)^2$, show $t = 0$ is minimum of $f$ and so $0 = f'(0)$, hence $z in M^perp$.
- To show uniqueness of $z$:
- Show for $y, y' in M$ such that $x - y perp M$ and $x - y' perp M$, then $ip(y - y', w) = 0$ for any $w in M$. Set $w = y - y'$ to give $y = y'$.
]
#definition[
*Direct sum* of subspaces $M$ and $N$ of linear space is $ M xor N := {y + z: y in M, z in N} $
]
#corollary[
If $M$ closed subspace of Hilbert space $H$, then $H = M xor M^perp$.
For all $x in H$, $x$ can be written uniquely as $x = y + z$ where $y$ is best approximation to $x$ in $M$ and $z = x - y perp M$.
]
#proof[
By above theorem.
]
#definition[
Let $H$ Hilbert space. ${u_alpha}_(alpha in I)$ is *orthonormal* if it is *orthogonal*: $u_alpha perp u_beta$ for $alpha != beta$, and *normalised*: $forall alpha in I, norm(u_alpha) = 1$.
]
#definition[
Let $X$ Banach space, ${x_alpha in X: alpha in I}$ be indexed set where $I$ is countable or uncountable.
- For each finite $J subset.eq I$, define *partial sum* as $ S_J := sum_(alpha in J) x_alpha $
- Unordered sum of ${x_alpha in X: alpha in I}$ *converges unconditionally* to $x in X$, written $x = sum_(alpha in I) x_alpha$, if $forall epsilon > 0$, there exists finite $J subset.eq I$ such that $norm(S_K - x) < epsilon$ for every finite $J subset.eq K subset.eq I$.
- Unordered sum $sum_(alpha in I) x_alpha$ is *Cauchy* if $forall epsilon > 0$, there exists finite $J subset.eq I$ such that $norm(S_L) < epsilon$ for every finite $L subset.eq I - J$. Note that $ norm(S_L) = norm(sum_(alpha in L union J) x_alpha - sum_(alpha in J) x_alpha) $
- Unordered sum of ${x_alpha in X: alpha in I}$ *converges absolutely* if $sum_(alpha in I) norm(x_alpha)$ converges unconditionally in $RR$.
]
#proposition[
Unordered sum in Banach space converges unconditionally iff it is Cauchy.
]<unordered-sum-converges-iff-cauchy>
#definition[
Let ${c_alpha: alpha in I} subset.eq [0, oo]$. Define $ sum_(alpha in I) c_alpha = sup{sum_(alpha in J) c_alpha: J subset.eq I, J "finite"} $
]
#proposition[
Let ${c_alpha: alpha in I} subset.eq [0, oo]$, $K = {alpha in I: c_alpha > 0}$. If $sum_(alpha in I) c_alpha < oo$, then $K$ is countable.
]
#theorem(name: "Bessel's inequality")[
Let $U = {u_alpha: alpha in I}$ orthonormal in Hilbert space $H$. Then $ forall x in H, quad sum_(alpha in I) |ip(x, u_alpha)|^2 <= norm(x)^2 $ In particular, $forall x in H$, ${alpha in I: ip(x, u_alpha) != 0}$ is countable.
]
#proof[
- Prove for any finite $J subset.eq I$, then take supremum on LHS.
- Show that $ norm(x - sum_(alpha in J) ip(x, u_alpha) u_alpha) = norm(x)^2 - sum_(alpha in J) |ip(x, u_alpha)|^2 $ using equation 2.2 and Pythagorean theorem.
]
#theorem[
If $U = {u_alpha: alpha in I}$ is orthonormal subset of Hilbert space $H$ then the following are equivalent:
- If $forall alpha in I, ip(x, u_alpha) = 0$, then $x = 0$.
- $forall x in H$, $x = sum_(alpha in I) ip(x, u_alpha) u_alpha$ where sum converges unconditionally in $H$ and only has countably many non-zero terms.
- *Parseval's identity*: $ forall x in H, quad norm(x)^2 = sum_(alpha in I) |ip(x, u_alpha)|^2 $
]<parseval>
#proof[
- (i) $==>$ (ii): let ${alpha_j: j in NN}$ be set of indices where $ip(x, u_(alpha_j)) != 0$. Show the partial sums of $sum_(j in NN) ip(x, u_(alpha_j)) u_(alpha_j)$ are Cauchy using Pythagorean theorem and so show converges.
- Set $ y = x - sum_(j in NN) ip(x, u_(alpha_j)) u_(alpha_j) $ and show $ip(y, u_alpha) = 0$.
- (ii) $==>$ (iii): let $epsilon > 0$. Use definition of unconditional convergence of $x$ and Pythagorean theorem to show $norm(x)^2 - sum_(alpha in I) |ip(x, u_alpha)|^2 < epsilon$.
]
#definition[
Orthonormal subset $U = {u_alpha: alpha in I}$ of Hilbert space $H$ is *complete* if it satisfies any of the conditions in @parseval. An *orthonormal basis* of $H$ is a complete orthonormal subset of $H$.
]
#definition[
$U$ is *maximal orthonormal set* if $forall V subset.eq H$ such that $U subset.neq V$, $V$ is not orthonormal.
]
#lemma[
$U$ is maximal orthonormal set iff it is an orthonormal basis.
]<maximal-orthonormal-iff-basis>
#remark[
For orthonormal basis ${u_alpha: alpha in NN}$, representation $x = sum_(alpha in NN) c_alpha u_alpha$ is unique (consider $ip(x - x, u_beta) = lim_(n -> oo) ip(sum_(alpha = 1)^n (c_alpha - d_alpha) u_alpha, u_beta)$).
]
#theorem[
Every Hilbert space $H$ has orthonormal basis. If $V subset.eq H$ is orthonormal set, then $H$ has orthonormal basis containing $V$.
]
#proof[
- Assume $H != {0}$. Use partial ordering $subset.eq$.
- Let ${U_alpha: alpha in I}$ be totally ordered collection of orthonormal sets. Find upper bound of ${U_alpha: alpha in I}$ which is orthonormal.
- Show result using @zorn and @maximal-orthonormal-iff-basis.
- To show orthonormal sets $V$ can be extended to orthonormal bases, use same argument on family of all orthonormal subsets of $H$ containing $V$.
]
#definition[
A set $X$ is *partially ordered* if it is equipped with relation $<=$ satisfying:
- *Reflexivity*: $forall x in X, x <= x$.
- *Transitivity*: $(x <= y and y <= z) ==> x <= z$.
- *Anti-symmetry*: $(x <= y and y <= x) ==> x = y$.
$X$ is *totally ordered* if partially ordered and $forall x, y in X$, either $x <= y$ or $y <= x$.
]
#definition[
Let $X$ totally ordered set with relation $<=$. $x in X$ is *upper bound* for $Y subset.eq X$ if $forall y in Y, y <= x$. $x in X$ is *maximal* if $forall y in X$, $x <= y ==> y = x$.
]
#example[
Let $X$ be non-empty collection of sets. Then $subset.eq$ is partial ordering on $X$. $A in X$ is upper bound for $X' subset.eq X$ if every set in $X'$ is subset of $A$. $M in X$ is maximal if it is not proper subset of any set in $X$.
]
#theorem(name: "Zorn's Lemma")[
A partially ordered set $X$ that has upper bounds for its totally ordered subsets has a maximal element.
]<zorn>
#proposition[
Hilbert space is separable iff it has countable orthonormal basis.
]
#proof[
- $==>$: let $U = {u_n: n in NN}$ countable, dense in $H$. Recursively discard any $u_n$ in linear span of $u_1, ..., u_(n - 1)$ to obtain linearly independent set $V = {v_n: n in NN}$ whose linear span is dense in $H$. Applying Gram-Schmidt, set $ w_1 = v_1 / norm(v_1), ..., w_(n + 1) = c_(n + 1) (v_(n + 1) - sum_(k = 1)^n ip(w_k, v_(n + 1) w_k)) $ where $c_n in CC$ chosen so that $norm(w_n) = 1$. ${w_n: n in NN}$ is countable orthonormal basis.
- $<==$: let ${w_n: n in NN}$ be orthonormal basis, show that $ S_m = {sum_(k = 1)^m c_k w_k: c_k in QQ + i QQ} $ is countable and $union_(m in NN) S_m$ dense in $H$.
]
#theorem(name: "Riesz Representation Theorem for Hilbert Spaces")[
Let $H$ Hilbert space with inner product $ip(dot.op, dot.op)$, $T: H -> RR$ bounded linear functional. Then $ exists! y in H: forall x in H, quad T(x) = ip(x, y) $ Note RHS gives bounded linear functional by Cauchy-Schwarz.
]
#proof[
- Existence:
- Show $N = {x in H: T(x) = 0}$ is closed subspace of $H$, use that $H = N xor N^perp$.
- Assume $N^perp$ contains $v$ with $norm(v) = 1$. For $x in H$, define $u = T(x) v - T(v) x$.
- Show that $ip(u, v) = 0$, deduce a value for $y$ from this.
- Uniqueness: straightforward.
]
= Convergence of Fourier series
#note[
We can view $f: [-pi, pi] -> CC$ as being $2pi$-periodic by extending it on the real line.
]
#definition[
$m$-th *partial Fourier sum* of $2pi$-periodic integrable function $f: [-pi, pi] -> CC$ is given by $ (S_m f)(x) = sum_(k = -m)^m a_k (f) e^(i k x) $ where $ a_k (f) = 1/(2 pi) integral_(-pi)^pi f(y) e^(-i k y) dif y $ are *Fourier coefficients* of $f$.
]
#definition[
Let $f, g: [-pi, pi] -> CC$ be $2pi$-periodic integrable functions. *Convolution* $f * g$ is $ (f * g)(x) = 1/(2pi) integral_(-pi)^pi f(y) g(x - y) dif y $
]
#proposition[
Let $f, g, h: [-pi, pi] -> CC$ be $2pi$-periodic integrable functions, $c in CC$. Then $*$ satisfies:
- *Commutativity*: $f * g = g * f$.
- *Distributivity*: $f * (g + h) = (f * g) + (f * h)$.
- *Homogeneity*: $(c f) * g = c(f * g) = f * (c g)$.
- *Associativity*: $(f * g) * h = f * (g * h)$.
]
== Pointwise convergence of Fourier series via Dirichlet kernel
#definition[
Let $m in NN_0$. The *$m$-th Dirichlet kernel* is $ D_m (x) := sum_(k = -m)^m e^(i k x) $
]
#proposition[
- $D_m$ is trigonometric polynomial of degree $m$ with coefficients equal to $1$ for $k in [-m, m]$ and $0$ otherwise.
- $D_m$ is real-valued and $2pi$-periodic.
- $ 1/(2pi) integral_(-pi)^pi D_m (x) dif x = 1 $
]<dirichlet-kernel-properties>
#proposition[
Let $f: [-pi, pi] -> CC$ be $2pi$-periodic integrable function. Then $ (D_m * f)(x)= sum_(k = -m)^m a_k (f) e^(i k x) = (S_m f)(x) $ where $a_k (f) = 1/(2pi) integral_(-pi)^pi f(y) e^(-i k y) dif y$.
]
#proposition[
$ D_m (x) = sin((m + 1/2) x)/sin(x/2) $
]<dirichlet-kernel-explicit>
#remark[
RHS in @dirichlet-kernel-explicit has removable singularity at $x = 0$, and $D_m (0) = 2m + 1$. Applying l'Hopital's rule to RHS gives $ lim_(x -> 0) sin((m + 1/2) x)/sin(x/2) = 2m + 1 $
]
#theorem(name: "Riemann-Lebesgue Lemma")[
Let $E subset.eq RR$ measurable, $f in L^1 (E)$. Then $ lim_(n -> oo) integral_E f(x) sin(n x) = lim_(n -> oo) integral_E f(x) cos(n x) = lim_(n -> oo) integral_E f(x) e^(-i n x) = 0 $
]
#proof[
- First consider when $f(x) = indicator((a, b))(x)$. Define $I_j = ((2pi j)/n, (2pi(j + 1))/n)$, so integral of $sin(n x)$ over each $I_j$ is $0$.
- Write $ (a, b) = L union union.big_(j = 1)^N I_j union R $ so that $"length"(L), "length"(R) < (2pi)/n$.
- Show that $ abs(integral_E f(x) sin(n x)) < (4pi)/n $
- Deduce the $sin$ result for step functions.
- Use that step functions are dense in $L^1$ to show $sin$ result for $f in L^1 (E)$ by writing $f = (f - psi) + psi$ and finally take $limsup$.
- Same argument works for $cos$.
- Conclude $exp$ result.
]
#theorem[
Let $f in L^1 ([-pi, pi])$ be $2pi$-periodic, assume $f$ differentiable at $b in [-pi, pi]$. Then $
f(b) = lim_(m -> oo) 1/(2pi) integral_(-pi)^pi f(y) D_m (b - y) dif y = lim_(m -> oo) (f * D_m)(b) = lim_(m -> oo) S_m f (b)
$
]
#proof[
- First assume $b = 0$. Let $0 < epsilon < 1$, show that $f(y)\/sin(y\/2)$ is integrable on $[epsilon, pi]$ and show $ lim_(m -> oo) integral_epsilon^pi f(y)/sin(y/2) sin((m + 1/2)y) dif y = 0 $ Conclude the same for $integral_(-pi)^(-epsilon)$.
- Write $f(y) = f(0) + s(y)$ and split the integral $integral_(-pi)^pi$ as such.
- Use @dirichlet-kernel-properties and split integral of $s(y)$ to show $ lim_(m -> oo) 1/(2pi) integral_(-pi)^pi f(y) D_m (y) dif y = f(0) + lim_(m -> oo) 1/(2pi) integral_(-epsilon)^epsilon s(y) D_m (y) dif y $
- Use differentiability at $0$ to show for $epsilon$ small and $y in [-epsilon, epsilon]$, $|s(y)| <= C|y|$.
- Show that $|x|\/|sin(x)| <= 2$ for $x$ small (for $cos(x) >= 1/2$) by considering $g(x) = 2 sin(x) - x$, and then that $ 0 <= abs(lim_(m -> oo) 1/(2pi) integral_(-epsilon)^epsilon s(y) D_m (y) dif y) <= (4 C epsilon)/pi $
- Conclude the result for $b = 0$.
- To show for $b in [-pi, pi]$, define $G(y) = f(b - y)$ and use commutativity of convolution.
]
== Uniform convergence of Cesàro mean Fourier series via Fejér kernel
#definition[
Let $x in RR$, $N in NN$. *Fejér kernel* is $ F_N (x) = 1/N sum_(m = 0)^(N - 1) D_m (x) = 1/N sum_(m = 0)^(N - 1) sum_(k = -m)^m e^(i k x) $
]
#proposition[
- $ 1/(2pi) integral_(-pi)^pi F_N (x) dif x = 1 $
- $ F_N (x) = 1/N (sin(N x\/2)/sin(x\/2))^2 $
- Fejér kernel is non-negative, so $ F_N (x) = |F_N (x)| ==> integral_(-pi)^pi |F_N (x)| dif x = 2pi $
- For $epsilon > 0$ and $epsilon < |x| < pi$, there exists $C_epsilon > 0$ such that $(sin(x\/2))^(-2) <= C_epsilon$, hence $ integral_epsilon^pi |F_N (x)| dif x = 1/N integral_epsilon^pi abs(sin(N x\/2)/sin(x\/2))^2 dif x <= 1/N integral C_epsilon <= (pi C_epsilon) / N -> 0 quad "as" N -> oo $ and similarly for $-pi < x < -epsilon$.
]<fejer-kernel-properties>
#definition[
The *$N$-th Cesàro mean* is the average of the first $N$ partial Fourier sums of $f$: $ 1/N sum_(m = 0)^(N - 1) (S_m f)(x) $
]
#proposition[
Let $f: [-pi, pi] -> CC$ integrable, then convolution of $f$ with Fejér kernel is the Cesàro mean: $ (f * F_N)(x) = 1/N sum_(m = 0)^(N - 1) (S_m f)(x) $
]
#theorem[
Let $f: [-pi, pi] -> CC$ continuous and $2pi$-periodic, then $ forall x in [-pi, pi], quad f(x) = lim_(N -> oo) (f * F_N)(x) = lim_(N -> oo) 1/N sum_(m = 0)^(N - 1) (S_m f)(x) $ and the convergence is uniform.
]<fejer-convolution-approximation>
#proof[
- Reason that $f$ is bounded: $|f| <= B$ on $[-pi, pi]$.
- Let $rho > 0$. Show that $forall x, y in [-pi, pi]$, for some $epsilon > 0$, $|y| < epsilon ==> |f(x - y) - f(x)| < rho$.
- Show that $ & |(f * F_N)(x) - f(x)| \ & <= 1/(2pi) (integral_(-pi)^(-epsilon) + integral_epsilon^pi) |F_N (y)| |f(x - y) - f(x)| dif y + 1/(2pi) integral_(-epsilon)^epsilon |F_N (y)| |f(x - y) - f(x)| dif y $
- Show that first terms of RHS tend to zero as $N -> oo$.
- Show last term on RHS is $< rho$.
- Conclude the result.
]
#remark[
- By above theorem, any $2pi$-periodic continuous function on $[-pi, pi]$ can be uniformly approximated by trigonometric polynomials, i.e. if $epsilon > 0$, then there exists trigonometric polynomial $p$ such that $forall x in [-pi, pi], |f(x) - p(x)| < epsilon$.
- This is analogue of Weierstrass Approximation Theorem for $2pi$-periodic functions. Weierstrass Approximation Theorem states that for continuous function $f: [a, b] -> RR$ and $epsilon > 0$, there exists polynomial $p$ such that $forall x in [a, b]$, $|f(x) - p(x)| < epsilon$.
- Continuous functions are dense in $L^p ([a, b])$ for $p in [1, oo)$. Let $epsilon > 0$, $f in L^p ([a, b])$ and $g: [a, b] -> RR$ continuous such that $norm(f - g)_(L^p) < epsilon$. By Weierstrass Approximation Theorem, there exists polynomial $tilde(p)$ such that $ forall x in [a, b], quad |g(x) - tilde(p)(x)| < epsilon/(b - a)^(1\/p) $ Hence $ integral_a^b |g(x) - tilde(p)(x)|^p < epsilon^p quad "i.e." quad norm(g - tilde(p))_(L^p) < epsilon $ Hence by Minkowski's inequality, $norm(f - tilde(p))_(L^p) < 2epsilon$. Hence polynomials are dense in $L^p ([a, b])$ for $p in [1, oo)$.
- *Note*: for $p = oo$, any continuous function in $L^oo ([a, b])$ can be approximated by polynomials, but continuous functions are not dense in $L^oo ([a, b])$.
- Similarly, trigonometric polynomials are dense in $L^p ([-pi, pi])$ for $p in [1, oo)$.
]
== Mean convergence of Fourier series in $L^2 ([-pi, pi])$
#notation[
Define an inner product on $L^2 ([-pi, pi])$ by $ ip(f, g) = 1/(2pi) integral_([-pi, pi]) f overline(g) $ and denote $norm(dot) = sqrt(ip(dot, dot))$. $(L^2 ([-pi, pi]), ip(dot, dot))$ is Hilbert space by Riesz-Fischer.
For $k in ZZ$, $x in [-pi, pi]$, let $phi_k (x) = e^(i k x)$, then for $2pi$-periodic integrable function $f: [-pi, pi] -> CC$, $ a_k (f) = ip(f, phi_k), quad S_N f (x) = sum_(k = -N)^N ip(f, phi_k) phi_k $
]
#lemma[
Let $f in L^2 ([-pi, pi])$ be $2pi$-periodic, define $ cal(P)_N = {sum_(k = -n)^n c_k phi_k: c_k in CC, n <= N} $ Then:
- ${phi_n: n in ZZ}$ is orthonormal in $L^2 ([-pi, pi])$ with respect to $ip(dot, dot)$.
- $forall p in cal(P)_N$, $f - S_N f$ is orthogonal to $p$.
- $forall N >= 0$, $forall p in cal(P)_N$, $ norm(f - S_N f) <= norm(f - p) $ with equality iff $p = S_N f$.
]<fourier-projection>
#proof[
- Show $1/(2pi) integral_([-pi, pi]) phi_m overline(phi_n) = 0 = delta_(m n)$ (justify use of Riemann integral).
- Show that $(f - S_N f) perp phi_m$ for each $|m| <= N$ to show $(f - S_N f) perp p$ for $p in cal(P)_N$.
- Write $f - p = f - S_N f + S_N f - sum_(k = -N)^N c_k phi_k$, use Pythagoras.
]
#remark[
Above lemma is projection result, i.e. $S_N f$ is best approximation to $f$ in $cal(P)_N$.
]
#theorem[
Let $f in L^2 ([-pi, pi])$ be $2pi$-periodic function. Then Fourier series for $f$ converges to $f$ in $(L^2 ([-pi, pi]), norm(dot))$, i.e. $ lim_(N -> oo) norm(S_N f - f) = 0 $
]
#proof[
- First show if $g: [-pi, pi] -> CC$ continuous, then $norm(S_N g - G) -> 0$ as $N -> oo$.
- Let $epsilon > 0$, then for some $M$, there exists $p in cal(P)_M$ such that $ forall x in [-pi, pi], quad |g(x) - p(x)| < epsilon $
- Use that $g(x) = lim_(N -> oo) (g * F_N)(x)$ and $g * F_(M + 1) in cal(P)_M$.
- Deduce that $norm(g - p)^2 < epsilon^2$.
- Show if $M <= N$ then $norm(g - S_N g) <= norm(g - p) < epsilon$, conclude result for continuous functions.
- Let $f in L^2 ([-pi, pi])$, $epsilon > 0$. Using that continuous functions are dense in $L^2 ([-pi, pi])$, there is $g: [-pi, pi] -> CC$ such that $norm(f - g) < epsilon$.
- Since $g$ continuous, for large enough $M$, $norm(S_M g - g) < epsilon$ by above.
- Use triangle inequality, the fact that $N >= M ==> S_M g in cal(P)_N$ and projection theorem to conclude the result.
]
#lemma[
${phi_n: n in ZZ}$ is orthonormal basis of $(L^2 ([-pi, pi])$ with respect to inner product $ ip(f, g) = 1/(2pi) integral_([-pi, pi]) f overline(g) $
]
#proof[
- Note that $(L^2 ([-pi, pi]), ip(dot, dot))$ is Hilbert space.
- Show Parseval's identity holds.
- Write $f = f - S_N f + S_N f$, use projection theorem, Pythagorean theorem and orthonormality of ${phi_n: n in ZZ}$ to show $ norm(f)^2 = norm(f - S_N f)^2 + sum_(k = -N)^N |ip(f, phi_k)|^2 $
- Take limit as $N -> oo$ to conclude result.
] |
|
https://github.com/Nivaes/Nivaes.Typst | https://raw.githubusercontent.com/Nivaes/Nivaes.Typst/develop/README.md | markdown | MIT License | # Nivaes Typst
Access to typst for dotnet.
## Packages
| NuGet Package | Latest Versions |
| --- | --- |
| [Nivaes.Typst](https://www.nuget.org/packages/Nivaes.Typst) | [](https://www.nuget.org/packages/Nivaes.Typst) |
## Integration
 [](https://codecov.io/gh/Nivaes/Nivaes.Typst)


|
https://github.com/mumblingdrunkard/mscs-thesis | https://raw.githubusercontent.com/mumblingdrunkard/mscs-thesis/master/src/frontmatter/front-page.typ | typst | #import "../utils/latex.typ" as latex
#import "../utils/config.typ" as config
#set page(header: none, footer: none)
#align(center, {
v(4.5em)
image("./images/ntnu-logo-norsk-m-visjon.svg", width: 40%)
v(1cm, weak: true)
smallcaps((latex.size.LARGE)([Department of ] + config.department))
v(1.5cm, weak: true)
smallcaps((latex.size.Large)(config.course.code + [ -- ] + config.course.name))
v(.4cm, weak: true)
v(2em)
v(.6cm, weak: true)
line(length: 150mm, stroke: .5pt)
v(1cm, weak: true)
(latex.size.huge)(text(weight: 500, config.project.name))
v(1cm, weak: true)
line(length: 150mm, stroke: .5pt)
v(1.7cm, weak: true)
(latex.size.large)(
{
emph(if (config.authors.len() > 1) { "Authors:" } else { "Author:" })
table(columns: (1fr,)*2, stroke: none,
..for (name, email) in config.authors {
(table.cell(name, align: right), )
(table.cell(raw("<" + email + ">"), align: left), )
}
)
}
)
place(bottom + center, [#datetime.today().display()])
})
|
|
https://github.com/floriandejonckheere/utu-thesis | https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/Dejonckheere_Florian_Thesis.typ | typst | #import "template.typ": *
#show: template.with(
// Document title
title: "Automated Microservice Identification in Modular Monolith Architectures",
// Document subtitle
subtitle: "Master of Science (Tech.) Thesis",
// Institution
institution: "University of Turku",
// Department
department: "Department of Computing",
// Unit
unit: "Software Engineering",
// Author
author: "<NAME>",
// Date of publication
date: datetime.today().display("[month repr:long] [year]"),
// Bibliography
bibliographies: (
"01-introduction",
"02-methodology",
"03-background",
"04-related-work",
"05-modular-monolith",
"06-automated-modularization",
"07-proposed-solution",
"08-case-study",
"09-conclusion",
),
// Institution logo (SVG)
logo-file: "logo-fi.svg",
// Abstract
abstract: [
// Background
The modular monolith software architecture has recently emerged as a hybrid solution, combining the simplicity and development velocity of the traditional monolith, with the scalability and flexibility of the microservices architecture.
As simple software systems evolve into complex and tightly coupled monoliths, organizations are pivoting towards modular monoliths or full microservices architectures to address the challenges of web-scale software development.
// Objective
This thesis investigates the benefits and drawbacks of the modular monolith architecture, and the challenges faced when migrating monolith applications to a modular software architecture.
It explores the concept of (semi-)automated modularization of software systems, and proposes an approach to automated microservice candidate identification in modular monolith architectures.
// Method
Based on a literature review, a four-step approach is designed, and a case study is conducted to evaluate its effectiveness using the cohesion and coupling quality metrics.
The results indicate that the approach is effective in identifying microservice candidates, and can be used to assist in automating modularization of monolithic applications.
// Results
Reflecting upon the results of the evaluation, a number of optimizations are suggested to improve the effectiveness of the approach.
The study concludes that using automated technologies to reduce the manual effort required for modularization can significantly improve the efficiency and accuracy of the process.
],
// Keywords
keywords: (
"software architecture",
"monolith",
"microservices",
"modular monolith",
"modularization",
),
// Acronyms
acronyms: (
API: ("Application Programming Interface"),
AST: ("Abstract Syntax Tree"),
BPMN: ("Business Process Model and Notation"),
DDD: ("Domain-Driven Design"),
DSRM: ("Design Science Research Methodology"),
DSRP: ("Design Science Research Process"),
ERD: ("Entity-Relationship Diagram"),
SDLC: ("Software Development Life Cycle"),
SLOC: ("Source Lines of Code"),
SLR: ("Systematic Literature Review"),
SRP: ("Single Responsibility Principle"),
SOA: ("Service-Oriented Architecture"),
UML: ("Unified Modeling Language"),
),
// Chapters
chapters: (
"01-introduction",
"02-methodology",
"03-background",
"04-related-work",
"05-modular-monolith",
"06-automated-modularization/01-introduction",
"06-automated-modularization/02-artifacts",
"06-automated-modularization/03-algorithms",
"06-automated-modularization/04-metrics",
"06-automated-modularization/05-conclusion",
"07-proposed-solution/01-introduction",
"07-proposed-solution/02-design",
"07-proposed-solution/03-requirements",
"07-proposed-solution/04-extraction",
"07-proposed-solution/05-decomposition",
"07-proposed-solution/06-visualization",
"07-proposed-solution/07-evaluation",
"07-proposed-solution/08-conclusion",
"08-case-study",
"09-conclusion",
),
// Appendix
appendix: (
"a-literature-review",
),
)
|
|
https://github.com/EunTilofy/Compiler2024 | https://raw.githubusercontent.com/EunTilofy/Compiler2024/main/hw/编译原理-Chapter5&6.typ | typst | #import "template.typ": *
#show: project.with(
course: "编译原理",
title: "Compilers Principals - Chapter5&6",
date: "2024.4.15",
authors: "<NAME>, 3210106357",
has_cover: false
)
*Problems:5.1(a,b),6.3,7(a,b)*
#HWProb(name: "5.1(a,b)")[
Improve the hash table implementation of Program 5.2:
a. Double the size of the array when the average bucket length grows larger than 2 (so table is now a pointer to a dynamically allocated array). To
double an array, allocate a bigger one and rehash the contents of the old
array; then discard the old array.
b. Allow for more than one table to be in use by making the table a param-
eter to insert and lookup.
]
a.
```cpp
#define SIZE 109
#define MAX_LOAD 2
struct bucket **table; unsigned int num_entries = 0, size = SIZE;
void insert(string key, void *binding)
{
if(table == NULL)
{
table = (struct bucket**) malloc (size * sizeof(struct bucket *));
memset(table, 0, size * sizeof(struct buckt * ));
}
int index = hash(key) % size;
table[index] = Bucket(key, binding, table[index]);
num_entries ++;
if(num_entries > MAX_LOAD * size)
{
unsigned int new_size = size << 1;
struct bucket **new_table =
(struct bucket**) malloc (new_size * sizeof(struct bucket *));
memset(new_table, 0, new_size * sizeof(struct buckt * ));
for(unsigned int i = 0; i < size; ++i)
{
while(table[i])
{
struct bucket* t = table[i];
table[i] = table[i]->next;
int new_index = hash(t->key) % new_size;
new_table[index] = Bucket(t->key, t->binding, new_table[new_index]);
free(t);
}
}
free(table);
table = new_table;
}
}
void pop(string key)
{
int index = hash(key) % SIZE;
table[index] = table[index]->next;
num_entries --;
}
```
b.
```cpp
typedef struct {
struct bucket **_table;
unsigned int size;
} Table;
void insert(string key, void *binding, Table* table)
{
if(table->size == 0)
{
table->size = SIZE;
table._table = (struct bucket**) malloc (SIZE * sizeof(struct bucket *));
}
int index = hash(key) % table->size;
table->_table[index] = Bucket(key, binding, table->_table[index]);
}
void *lookup(string key, Table* table)
{
int index = hash(key) % table->size;
struct bucket* b;
for(b=table->_table[index]; b; b=b->next)
{
if(0 == strcmp(b->key, key)) return b->binding;
}
return NULL;
}
```
#HWProb(name: "6.3")[
For each of the variables $a, b, c, d, e$ in this C program, say whether the variable should be kept in memory or a register, and why.
```cpp
int f(int a, int b)
{
int c[3], d, e;
d = a+1;
e = g(c, &b);
return e + c[1] + b;
}
```
]
a:in register. It is the parameters of function f.
b:in memory. Passed by reference, the variable is accessed by a procedure.
c:in memory. It is an array.
d:in register. It is the reusult of expression 'a+1', and there is no use after call the function 'g(c, &b)'.
e:in register. It is the function result of f.
#HWProb(name: "6.7(a,b)")[
A *display* is a data structure that may be used as an alternatives to static links for maintaining access to nonlocal variables. It is an array of frame pointers, indexed by static nesting depth. Element $D_i$ of the display always points to the most recently called function whose static nesting depth is $i$.
The bookkeeping performed by a function $f$, whose static nesting depth is $i$, looks like:
```
Copy D_i to save location in statck frame
Copy frame pointer to D_i
... body of f ...
Copy save location back to D_i
```
In Program 6.3, function prettyprint is at depth 1, write and show are at depth 2, and so on.
a. Show the sequence of machine instructions required to fetch the variable output into a register at line 14 of Program 6.3, using static links.
b. Show the machine instructions required if a display were used instead.
]
```cpp
1 type tree = {key: string, left: tree, right: tree}
3 function prettyprint(tree: tree) : string =
4 let
5 var output := ""
7 function write(s: string) =
8 output := concat(output,s)
10 function show(n:int, t: tree) =
11 let function indent(s: string) =
12 (for i := 1 to n
13 do write(" ");
14 output := concat(output,s); write("\n"))
15 in if t=nil then indent(".")
16 else (indent(t.key);
17 show(n+1,t.left);
18 show(n+1,t.right))
19 end
21 in show(0,tree); output
22 end
```
a. use static links.
```
MOV R1, FP # get the frame pointer to the show
MOV R1, [R1 - K] # fetch show's static link
MOV R1, [R1 - K] # get the frame pointer to the prettyprint
MOV R2, [R1 + OFFSET] # fetchs output
```
b. use display.
```
# get the D2 (the frame pointer of show), variable 'output' not exists
MOV R1, [DISPLAY + 1 * POINTER_SIZE] # get D1 (the frame pointer of prettyprint)
MOV R2, [R1 + OFFSET] # fetch the variable output.
```
|
|
https://github.com/j10ccc/algorithm-analysis-homework-template-typst | https://raw.githubusercontent.com/j10ccc/algorithm-analysis-homework-template-typst/main/workspace/ps0.typ | typst | #import "../main.typ": template
#import "../layout/question.typ": question
#import "@preview/codelst:1.0.0": sourcecode
#let config = (
homework_id: [0],
date: [2023.9.04],
time_consume: [xxx],
deadline: [2023.9.24 : 6 PM],
intro: [本次习题主要涉及递归算法以及递归函数求解。请用 LATEX 编辑所有解答。所有问题请给出简洁的回答,任何冗余的回答可能会得低分。提交文件格式为 PDF。]
)
#show: doc => template(doc, config)
// t1
#question(
homework_id: "0",
title: [
[10 分]
给定集合 $A = {i + binom(5, i)|i in ZZ, 0 <= i <= 4}$,集合 $B = {3i|i in {1,2,4,5}}$。
]
)[
请分别给出以下运算的结果。\
#set enum(numbering: "(a)")
+ $A sect B$
+ $|A union B|$
+ $|A − B|$
]
$ A = {1, 6, 12, 13, 9} \ B = {3, 6, 12, 15} $
所以
$ A sect B &= {6, 12} \
|A union B| &= 7 \
|A − B| &= 3 $
#pagebreak()
// t2
#question(
title: [
[20 分]
有 2 个随机变量 $X$ 和 $Y$ 。其中,$X$ 表示抛无偏硬币三次后看到的人头数。$Y$ 表示掷两个无偏六面骰子并将其值相乘的结果。 请计算以下期望值,
]
)[
#set enum(numbering: "(a)")
+ $E[X]$
+ $E[Y]$
]
#align(center,
table(
columns: (40pt, 40pt, 40pt, 40pt, 40pt),
rows: (auto, auto),
inset: 10pt,
[$X$], [$0$], [$1$], [$2$], [$3$],
[$p$], [$1/8$], [$3/8$], [$3/8$], [$1/8$]
)
)
$ E[X] = 1.5 $
#align(center,
table(
columns: (auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto),
rows: (auto, auto),
inset: 10pt,
[$Y$], [$1$], [$2$], [$3$], [$4$], [$5$], [$6$], [$8$], [$9$], [$10$], [$12$], [$15$], [$16$], [$18$], [$20$], [$24$], [$25$], [$30$], [$36$],
[$p$],
[$1/36$],
[$2/36$],
[$2/36$],
[$3/36$],
[$2/36$],
[$4/36$],
[$2/36$],
[$1/36$],
[$2/36$],
[$4/36$],
[$2/36$],
[$1/36$],
[$2/36$],
[$2/36$],
[$2/36$],
[$1/36$],
[$2/36$],
[$1/36$],
)
)
$ E[Y] = 441 / 26 = 147 / 12 $
#pagebreak()
// t3
#question(
title: [
[15 分]
令 $A = 600\/6$,$B = 60 mod 42$。以下表达式正确的是?
]
)[
#set enum(numbering: "(a)")
+ $A equiv B(mod 2)$
+ $A equiv B(mod 3)$
+ $A equiv B(mod 4)$
]
$ A = 100, B = 18 $
A 选项
$ A mod 2 = 0, B mod 2 = 0 $
B 选项
$ A mod 3 = 1, B mod 3 = 0 $
C 选项
$ A mod 4 = 0, B mod 4 = 2 $
所以选 *A*
#pagebreak()
// t4
#question(
title: [
[20 分]
利用数学归纳法证明 $sum_(i=1)^n i^3 = [ (n(n+1)) / 2]^2$ ,其中 $n >= 1$。
]
)[]
令
$ F_n = sum_(i = 1) ^ n i ^ 3 = [(n(n + 1)) / 2] ^ 2, n >= 1 $
当 $n = 1$ 时
$ F_1 &= 1 dot 1 \
&= [1 dot (1 + (1 + 1)) / 2] ^ 2 \
&= 1 $
命题成立
假设 $n = k$ 时命题成立,则有
$ F_k = sum_(i = 1) ^ k i ^ 3 = [(k(k + 1)) / 2] ^ 2, k >= 1 $
令 $n = k + 1$
$ F_(k + 1) &= F_k + (k + 1) ^ 3 \
&= [(k(k + 1)) / 2] ^ 2 + (k + 1) ^ 3 \
&= 1/4 k^4 + 3 / 2 k ^ 3 + 13 / 4 k ^ 2 + 3k + 1 \
&= [((k + 2)(k + 1)) / 2] ^ 2 \
$
所以命题成立
#pagebreak()
// t5
#question(
title: [
[15 分]
利用数学归纳法证明有 $n$ 个节点的图最多只有 $n(n − 1)\/2$ 条边。
]
)[]
令
$ F_n = n "个节点的边数" $
首先考虑, 有 $1$ 个节点的图,最多有 $0$ 条边, 命题成立。
假设 $n = k$ 时公式成立,则有
$ F_k = k(k - 1) \/ 2 $
当 $n = k + 1$ 时, 加入一个新的节点并使之成为完全图,
我们需要让这个新节点和所有其他 $k$ 个节点相连。所以,
要新加 k 条边
$ F_(k + 1)
&= F_k + k \
&= k(k - 1) \/ 2 + k \
&= (k + 1)k \/ 2 $
所以命题成立。
#pagebreak()
// t6
#question(
title: [
[20 分]
数组中相邻的元素如果依次递增,那么这段递增的元素就称为数组的递增子数组。请给出函数 $"count_long_subarrays"(A)$ 的具体实现,该函数返回数组 A 中最长递增子数组的个数,其中$A$ 包含 $n > 0$ 个正整数。
]
)[
*输入:* $A = (1, 3, 4, 2, 7, 5, 6, 9, 8)$ \
*输出:* $"count" = 2$ \
因为 A 中最长的递增子数组分别为 $(1, 3, 4)$ 和 $(5, 6, 9)$。
]
#sourcecode(
frame: none
)[
```js
const count_long_subarrayus = (arr) => {
if (arr.length < 3) return 0;
let isInArray = false;
let count = 0;
for (let i = 1; i < arr.length - 1; i++) {
if (arr[i - 1] <= arr[i] && arr[i] <= arr[i + 1]) {
if (!isInArray) count++;
isInArray = true;
} else {
isInArray = false;
}
}
return count;
}
```
] |
|
https://github.com/chendaohan/bevy_tutorials_typ | https://raw.githubusercontent.com/chendaohan/bevy_tutorials_typ/main/03_app/app.typ | typst | #set page(fill: rgb(35, 35, 38, 255), height: auto, paper: "a3")
#set text(fill: color.hsv(0deg, 0%, 90%, 100%), size: 22pt, font: "Microsoft YaHei")
#set raw(theme: "themes/Material-Theme.tmTheme")
= 1. App
App 是你定义构成项目的所有事物的方式:插件、系统(运行条件、排序、系统集)、事件类型、状态、调度等。
```Rust
App::new()
.add_plugins(MinimalPlugins)
.register_type::<MyReflectCompoent>()
.register_type_data::<MyReflectCompoent, ReflectMyReflectTrait>()
.init_state::<GameState>()
.insert_state(GameState::Start)
.init_resource::<MyResource>()
.insert_resource(InsertMyResource { field_1: 0., field_2: 0 })
.add_event::<MyEvent>()
.configure_sets(Startup, MySystemSet)
.add_systems(Startup, system.in_set(MySystemSet))
.run()
```
= 2. 内置 Bevy 功能
Bevy 游戏引擎的功能被表示为插件,根据不同的场景将内置插件合成了插件组。
- #[
```Rust DefaultPlugins```:如果你正在制作完整的游戏/应用。
有 日志插件(LogPlugin)、任务池插件(TaskPoolPlugin)、窗口插件(WindowPlugin)、资产插件(AssetPlugin)、窗口管理插件(WinitPlugin)、渲染插件(RenderPlugin)、图片插件(ImagePlugin)、Pbr 插件(PbrPlugin)、Gltf 插件(GltfPlugin)、音频插件(AudioPlugin)等提供配置选项的插件。
]
- #[
```Rust MinimalPlugins```:用于类似无头服务器的东西。
有 任务池插件(TaskPoolPlugin)、类型注册插件(TypeRegistrationPlugin)、帧计数插件(FrameCountPlugin)、时间插件(TimePlugin)、时间表运行器插件(SheduleRunnerPlugin)、CI 测试插件(CiTestingPlugin)全部插件。
] |
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/compiler/weeks/week6.typ | typst | #import "../../utils.typ": *
#section("Code Generation")
#subsection("Evaluation Stack")
Processors use registers in order to execute instructions, meanwhile, virtual
machine languages like jafuck use evaluation stacks in order to evaluate
instructions.
#align(
center,
[#image("../../Screenshots/2023_10_23_08_13_01.png", width: 70%)],
)
- each instruction has a defined amount of
- pop calls
- push calls
- one stack per method call
- stack will be empty at the start and at the end of the method
- stack has no limit on capacity
- for any complexity
- if overflow OS/cpu will restrict
Just like with assembly, you first setup parameters and then local variables:
#align(
center,
[#image("../../Screenshots/2023_10_23_08_16_24.png", width: 70%)],
)
Or here how a while loop would be converted:
#align(
center,
[#image("../../Screenshots/2023_10_23_08_21_49.png", width: 70%)],
)
#subsubsection("Example")
#columns(2, [
#align(
center,
[#image("../../Screenshots/2023_10_23_08_18_20.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_08_18_30.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_08_18_40.png", width: 80%)],
)
#colbreak()
#align(
center,
[#image("../../Screenshots/2023_10_23_08_18_50.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_08_19_08.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_08_19_18.png", width: 80%)],
)
])
#subsection("metadata")
- intermediary language
- knows class names, types, filed, methods
- knows method names, parametertypes, return types
- knows local variables and their types
- no specific memory layout -> it's a virtual machine...
- doesn't include
- names of local variables and parameters -> they are enumerated
- int kappa = 7 > 1: INT -> 7
#subsection("Code Generation Methods")
+ traverse symboltable
- create bytecode metadata
+ traverse AST per method(visit)
- create instructions via bytecode assembler
+ serialize output
#subsection("Instruction Variations")
#align(
center,
[#image("../../Screenshots/2023_10_23_08_44_12.png", width: 90%)],
)
#text(teal)[It's a loop...]
#subsubsection("General")
#align(
center,
[#image("../../Screenshots/2023_10_23_08_14_53.png", width: 70%)],
)
#subsubsection("Negate Instruction")
#align(
center,
[#image("../../Screenshots/2023_10_23_08_21_30.png", width: 70%)],
)
#subsubsection("Compare Instructions")
#align(
center,
[#image("../../Screenshots/2023_10_23_08_21_05.png", width: 70%)],
)
#subsubsection("Branch Instruction")
#align(
center,
[#image("../../Screenshots/2023_10_23_08_22_21.png", width: 70%)],
)
#subsubsection("Returns")
#text(red)[Keyword: ret]
#align(
center,
[#image("../../Screenshots/2023_10_23_08_33_32.png", width: 70%)],
)
#subsubsection("Method Calls")
#align(
center,
[#image("../../Screenshots/2023_10_23_08_28_38.png", width: 70%)],
)
Note, static is exactly what it means -> without object instance, or global
instance, while virtual here means object dependent function -> jafuck is always
virtual cuz we hate performance.
#pagebreak()
#columns(2, [
static:\
#align(
center,
[#image("../../Screenshots/2023_10_23_08_29_59.png", width: 60%)],
)
#colbreak()
virtual/object based:\
#align(
center,
[#image("../../Screenshots/2023_10_23_08_30_31.png", width: 100%)],
)
])
#subsubsection("Backpatching")
Labels as also seen in assembly are only for humans to make it easier to read,
later on these will be replaced with offets:
#align(
center,
[#image("../../Screenshots/2023_10_23_08_47_34.png", width: 40%)],
)
E.g. before the brfalse would have had a proper label
#subsection("Templating ByteCode Generation")
Templating makes code generation easier:
#align(
center,
[#image("../../Screenshots/2023_10_23_08_34_38.png", width: 70%)],
)
#pagebreak()
#subsubsection("Example")
#columns(2, [
#align(
center,
[#image("../../Screenshots/2023_10_23_09_01_29.png", width: 90%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_09_01_36.png", width: 90%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_09_01_46.png", width: 90%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_09_01_58.png", width: 90%)],
)
#colbreak()
#align(
center,
[#image("../../Screenshots/2023_10_23_09_02_05.png", width: 90%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_09_02_12.png", width: 90%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_09_02_39.png", width: 90%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_09_02_58.png", width: 90%)],
)
])
#pagebreak()
#subsubsection("Conditionals")
#align(
center,
[#image("../../Screenshots/2023_10_23_09_04_57.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_09_05_11.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_23_09_05_26.png", width: 80%)],
)
#subsubsection("While in Visitor")
//typstfmt::off
```java
@Override
public void visit(WhileStatementNode node) {
var beginLabel = assembler.createLabel();
var endLabel = assembler.createLabel();
assembler.setLabel(beginLabel);
node.getCondition().accept(this);
assembler.emit(IF_FALSE, endLabel);
node.getBody().accept(this);
assembler.emit(GOTO, beginLabel);
assembler.setLabel(endLabel);
}
```
//typstfmt::on
#subsubsection("Optimization")
Certain parts are handled with constants -> 6+2 somewhere in code can be
redefined to 8, does not need to be run!
#align(
center,
[#image("../../Screenshots/2023_10_23_08_32_42.png", width: 60%)],
)
|
|
https://github.com/Han-duoduo/mathPater-typest-template | https://raw.githubusercontent.com/Han-duoduo/mathPater-typest-template/main/chapter/chap4.typ | typst | Apache License 2.0 | #import "../template/template.typ":*
= 符号说明
#symbolDesc(
syms: (
[$A$],
[$B$],
[$C$],
[$a_(i j)$],
[$b_(i j)$],
[$c_(i j)$],
[$*$],
[$D$],
[$E$],
[$F$],
[$d_(i j)$],
[$e_(i j)$],
[$f_(i j)$]
),
desc: (
[优化小区的冲突矩阵],
[优化小区的混淆矩阵],
[优化小区的干扰矩阵],
[优化小区中的主控小区i是邻小区j的冲突MR数],
[优化小区中的小区i和小区j是另一个邻小区的混淆MR数],
[优化小区中的小区主控小区i是重叠覆盖邻区j的MR数],
[定义为两个同型矩阵的对应元素相乘],
[优化小区和相关联小区的冲突矩阵],
[优化小区和相关联小区的混淆矩阵],
[优化小区和相关联小区的干扰矩阵],
[优化小区和相关联小区中的主控小区i是邻小区j的冲突MR数],
[优化小区和相关联小区中的小区i和小区j是另一个邻小区的混淆MR数],
[优化小区和相关联小区中的小区主控小区i是重叠覆盖邻区j的MR数]
)
) |
https://github.com/pascal-huber/typst-letter-template | https://raw.githubusercontent.com/pascal-huber/typst-letter-template/master/README.md | markdown | MIT License | # typst l<sub>e</sub>tt<sub>e</sub>r
A customizable Typst letter template with some presets for DIN 5008 A/B and
Swiss C5 Letter. Please note that the template is still under development and
subject to breaking changes.

See the [examples](./examples)
## Templates
- `lttr-init` is responsible to compute all values from the parameters and
default values for different formats. It also sets the `page` and `text`
attributes.
- `lttr-preamble` renders:
- `lttr-sender`
- `lttr-receiver`
- `lttr-indicator-lines`
- `lttr-content-offset`
- `lttr-horizontal-table`
- `lttr-date-place`
- `lttr-title`
- `lttr-opening`
- `lttr-closing` renders the closing line and the signature.
## Parameters
All Parameters are optional and will override the global defaults and the
defaults of the chosen format. Some of them allow to either specify the content
directly or use a dict if other settings need to be changed also. For example:
`receiver: "x"` is the same as `receiver: (content: "x")`.
### Basics
- `debug` (`[Bool]`)
Whether or not to show (colorful) debug lines.
- `format` (`[String]`)
Format of the letter (`"DIN-5008-A"`, `"DIN-5008-B"`, `"C5-WINDOW-RIGHT"`,
`"C5-WINDOW-LEFT"`).
- `_page` (`[Dict]`)
Set page settings ([docs](https://typst.app/docs/reference/layout/page/)).
- `_text` (`[Dict]`)
Set text settings ([docs](https://typst.app/docs/reference/text/text/)).
- `settings` (`[Dict]`)
Basic settings.
- `content-spacing` (`[Length]`)
Minimum spacing between sender/receiver and letter content (or the
horizontal table if present) and also the spacing after the horizontal
table.
- `justify-content` (`[Bool]`)
Wheter or not to justify the content.
Example:
```typst
settings: (
content-spacing: 8.46mm,
justify-content: true,
),
```
- `indicator-lines` (`[Dict]`)
Info to render lines for the hole puncher and folding ([see below](#indicator-lines)).
- `fold-marks` (`[Array]`)
Lenghts (`[Length]`) from top of page of the fold marks
- `show-puncher-mark` (`[Bool]`)
Whether or not to show the puncher mark.
Example:
```typst
indicator-lines: (
fold-marks: (87mm, 87mm+105mm),
show-puncher-mark: true,
)
```
### Sender and Receiver
- `receiver` (`[Array, Content, Dict]`)
Info to render the receiver fields.
- `content` (`[Array, Content]`)
Content of the receiver field.
- `dimensions` (`[Dict]`)
Dimensions of the address field (`width: [Length]`, `height: [Length]`)
- `fmt` (`[Function]`)
Rendering function which takes the receiver (`[Dict]`) to format and show
it.
- `position` (`[Dict]`)
Position of the address field (`top: [Length]`, `left: [Length]`)
- `spacing` (`[Length]`)
Spacing before the content.
- `align` (`[Align]`)
Alignment of the receiver field.
Example:
```typst
receiver: (
position: (top: 5cm)
content: (
"<NAME>",
"Somestreet 16",
"1234 New York",
),
),
```
- `return-to` (`[Array, Content, Dict, String]`)
The returning address.
- `content` (`[Array, Content]`)
Content of the return-to field.
- `dimensions` (`[Dict]`)
Dimensions of the return-to field (`width: [Length]`, `height: [Length]`)
- `fmt` (`[Function]`)
Rendering function which takes the return-to (`[Dict]`) to format and show
it.
- `position` (`[Dict]`)
Position of the return-to field (`top: [Length]`, `left: [Length]`)
Example:
```typst
return-to: "Some Address, I don't care...",
```
- `remark-zone` (`[Array, Content, Dict, String]`)
The remark zone.
- `align` (`[Align]`)
Alignment of the remark-zone.
- `content` (`[Array, Content, String]`)
Content of the remark-zone field.
- `dimensions` (`[Dict]`)
Dimensions of the remark-zone field (`width: [Length]`, `height: [Length]`)
- `fmt` (`[Function]`)
Rendering function which takes the remark-zone (`[Dict]`) to format and show
it.
- `position` (`[Dict]`)
Position of the remark-zone field (`top: [Length]`, `left: [Length]`)
```typst
remark-zone: (
"This is a",
"multiline remark",
)
```
- `sender` (`[Array, Content, Dict]`)
Info to render the sender fields.
- `content` (`[Array, Content]`)
Content or array of lines for the sender field.
- `fmt` [Function]
Rendering function which takes the sender (`[Dict]`) to format and show it.
- `position` (`[Dict]`)
Position of the sender field.
- `width` (`[Length]`)
Width of the sender field.
Example:
```typst
sender: (
content: (
"<NAME>",
"Somestreet 15",
"1234 New York",
)
position: (left: 110mm, top: 20mm),
width: 80mm,
),
```
- `horizontal-table` (`[Dict, Array]`)
A table to add before the date, time and title.
- `content` (`[Array]`)
Array of of entries for the table where each entry is itself an array of
exactly two items for title and body (`[Content, String]`)
- `fmt` (`[Function]`)
Formatting function which takes the title and body of a cell to format and
show it.
- `spacing` (`[Lenght]`)
Spacing before the horizontal table.
Example:
```typst
horizontal-table: (
("<NAME>", "Bananalover149"),
("Ihre Nachricht vom", "12.12.2022"),
("<NAME>", "Bananenfabrik"),
("Datum", "12.08.2023"),
)
```
### Letter Beginning
- `opening` (`[Content, Dict, String]`)
Info to render the `title` template ([see below](#opening)).
- `content` (`[Content, String]`)
Content of the opening (e.g. "Dear Sir....").
- `spacing` (`[Length]`)
Spacing before the letter opening.
Example:
```typst
opening: (
content: "Dear Sir or Madam,",
spacing: 2mm,
)
```
- `date-place` (`[Content, Dict, String]`)
Info to render the `date-place` template ([see below](#date-place)).
- `align` (`[Align]`)
Alignment of the place and date
- `date` (`[Content, String]`)
Date of the letter.
- `place` (`[Content, String]`)
Place of the letter.
Example:
```typst
date-place: (
align: left,
date: "20.04.2023",
place: "Weitfortistan",
),
```
- `title` (`[Content, Dict, String]`)
Info to render the `title` template. The title is also set as document
property.
- `content` (`[Content, String]`)
Content of the title.
- `spacing` (`[Length]`)
Spacing before the title.
Example:
```typst
title: (
content: "Writing Letters in Typst is Easy",
spacing: 2mm,
)
```
### Letter Ending
- `closing` (`[Content, Dict, String]`)
Info to render the closing
- `content` (`[Content, String]`)
Content of the closing (e.g. "kind regards").
- `spacing` (`[Length]`)
Spacing before the closing.
Example:
```typst
closing: "kind regards"
```
- `signature` (`[Dict, none]`)
Info to render the signature.
- `content` (`[Content]`)
Content of the signature
- `spacing` (`[Length]`)
Spacing before the signature.
Example:
```typst
signature: (
content: "<NAME> (with the big Signature)",
spacing: 16mm,
)
```
## Other functions
- `lttr-state` prints the entire state used to render the components. This can
be useful for debugging purposes.
## Resources
- [DIN 5008 Form A](https://de.wikipedia.org/wiki/DIN_5008#/media/Datei:DIN_5008,_Form_A.svg)
- [DIN 5008 Form B](https://de.wikipedia.org/wiki/DIN_5008#/media/Datei:DIN_5008_Form_B.svg)
- [Swiss
Addressing](https://www.post.ch/-/media/portal-opp/pm/dokumente/briefe-spezifikation-gestaltung.pdf?sc_lang=de&hash=BB181E74C5D3A0D1D49A954793EA670A)
## Similar Projects
- [dvdvgt/typst-letter](https://github.com/dvdvgt/typst-letter): A typst
template for a DIN 5008 inspired letter with the goal to fit nicely into C6/5
envelops.
- [qjcq/awesome-typst](https://github.com/qjcg/awesome-typst): Awesome Typst
Links
## Development Setup
Currently, I just create a symlink such that I can import it with `#import
"@local/lttr:0.1.0": *` as follows.
```bash
mkdir -p ${XDG_DATA_HOME}/typst/packages/local/lttr/
ln -s /path/to/this/repo ${XDG_DATA_HOME}/typst/packages/local/lttr/0.1.0
```
## Installation
While there exists a first version of typst packages, they do not yet accept
custom templates (afaik). For the meantime, you can download and extract the
release tarball to `${XDG_DATA_HOME}/typst/packages/local/lttr/<version>` and
import it as described in [Development Setup](#development-setup).
## Roadmap
There are a couple of limitations in typst which I hope will be addressed.
- [ ] There is currently no way to query properties set with `set`. This would
be nice to query the document title and author names
[issue](https://github.com/typst/typst/issues/763). Forthermore, it is not
possible to call `set` after the first lttr function has been called (even if
no content was rendered added).
- [ ] datetime with locales settings
Other things:
- [ ] Add more layouts including (us letter, ?)
- [ ] Vertical table for sender field as for example
[here](https://www.onlineprinters.de/magazin/wp-content/uploads/2021/07/Vorlage_Geschaeftsbrief_DIN-5008_Form-A.jpg)
- [ ] Maybe add lines with labels to display measurements/sizes in debug mode
- [ ] Add this to the typst preview packages. Currently, they apparently do not
accept packages.
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/game-rules.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Identify Game Rules",
type: "identify",
date: datetime(year: 2023, month: 4, day: 29),
author: "<NAME>",
witness: "Violet Ridge"
)
= Field Elements #footnote(
[Images sourced from: #link(
"https://content.vexrobotics.com/docs/23-24/vrc-overunder/VRC-Manual-2324-1.1-Release.pdf",
)],
)
#align(center, [
#image("/assets/field-elements/full-field.png")
])
#grid(
columns: (1fr, 1fr),
gutter: 50pt,
image("/assets/field-elements/triballs.png"),
par([
== Triballs
- Can be a total of 60 triballs in play
- 4 alliance triballs
- 44 match loads
- 12 begin on the field
- 7" radius
- 6.18" height
]),
par([
== Goal
- 1 per alliance
- 47" long
- 23.08" wide
- low bar is 5.78" away from tiles
]),
image("/assets/field-elements/goal.png"),
image("/assets/field-elements/barrier.png"),
par([
== Barriers
- 1 long barrier
- 2 short barriers
- long barrier is 94.25" long
- short barrier is 49.13" long
- both barriers are 2.88" tall
]),
par([
== Elevation Bar
- 1 per alliance
- consists of a high bar and a low bar
- both bars are 2.38" in diameter
- low bar is 21.89" long
- low bar is 11.63" away from the tiles
- high bar is 30.23" tall
]),
image("/assets/field-elements/elevation-bar.png"),
image("/assets/field-elements/load-zone.png"),
par([
== Match Load Zones
- 4 total
- two per alliance
- colored bar is 30" long
- colored bar is 14.96" away from back corner of the field
]),
par([
== Offensive Zones
- 1 per alliance
- does not include match load zones
- each zone is 3 tiles by 6 tiles large
]),
image("/assets/field-elements/offensive-zones.svg"),
)
= Scoring
- each triball in a goal is worth 5 points
- triballs in an offensive zone are worth 2 points
- highest climbing robot is worth 20 points
- second highest climbing robot is worth 15 points
- third highest climbing robot is worth 10 points
- lowest climbing robot is worth 5 points
- the autonomous bonus is worth 8 points
= Important Terms
== Double-Zoned
- An alliance is double zoned when both of their robots are in the same offensive
zone
== Elevated
- A robot is considered elevated when the only field element they're touching is
the elevation bar (excluding the elevation cap)
= Important Rules
== SG1
- Once robot of each alliance must start in the other team's offensive zone
== SG2
- Horizontal expansion is limited to 36"
- There is no vertical limit
== SG6
- triballs can be loaded into the field in the match load zone
- triballs can be loaded directly onto the robot if the robot is touching the
match load zone
== SG7
- possession is limited to 1 triball
== SG8
- A robot cannot enter an alliance's goal unless they are double zoned
== SC7
- Alliances get an autonomous win point if they do the following tasks in the
autonomous period:
- Remove triball from alliance match load zone
- Score triball in alliance goal
- End autonomous period with robot touching elevation bar
== R12
- The motors on a robot are limited to a total of 88W. The robot can have any
combination of 11W and 5.5W motors. This means that robots can now have up to 16
motors.
|
https://github.com/danjones1618/presentations | https://raw.githubusercontent.com/danjones1618/presentations/main/template.typ | typst | #import "./catppuccin/src/lib.typ": catppuccin, themes, get-palette as get_palette
#import "./typst-svg-emoji/lib.typ": setup-emoji
#import "@preview/polylux:0.3.1": polylux-slide, uncover, only, side-by-side
#import "@preview/fontawesome:0.1.0": *
#let dan_theme(theme: themes.mocha, body) = {
set page(paper: "presentation-16-9");
let salmon = if theme == themes.latte {rgb("#fa8a90")} else {rgb("#e78388")};
show: catppuccin.with(theme);
show: setup-emoji
let palette = get_palette(theme);
let simple-footer = state("simple-footer", []);
set text(size: 20pt, font: "Open Sans");
show heading: content => text(
font: "Oswald",
tracking: -0.022em,
weight: "medium",
fill: salmon,
content
);
show heading.where(level: 1): set text(size: 2.058em);
show heading.where(level: 2): set text(size: 1.618em);
show heading.where(level: 3): set text(size: 1.272em);
//set text(fill: rgb("#ffffff"))
show raw: set text(font: "FiraCode Nerd Font Mono");
set raw(syntaxes: ("./lark.sublime-syntax"));
show raw.where(block: false): it => {
set text(
fill: palette.colors.peach.rgb,
size: 0.75em,
)
box(
fill: palette.colors.crust.rgb,
inset: 0.25em,
radius: 25%,
baseline: 0.125em,
it
)
}
show raw.where(block: true): it => {
let bg = palette.colors.crust.rgb
let fg = palette.colors.text.rgb
set text(size: 0.8em, fill: fg)
layout(size =>
block(
fill: bg,
inset: 8pt,
radius: 5pt,
width: calc.min(calc.max(measure(it).width, 80% * size.width), size.width),
align(left)[
#box[
#for c in (palette.colors.red.rgb, palette.colors.yellow.rgb, palette.colors.green.rgb) [
#box(circle(fill: c, width: 0.8em))
]
#block(inset: (top: -6pt), clip: true, it)
]
]
)
)
};
body;
};
#let centered-slide(title: "", sub_title: "", body) = {
if title != "" and sub_title != "" {
polylux-slide[
== #{title}
#{sub_title}
#align(center + horizon, body)
]
} else if title != "" {
polylux-slide[
== #{title}
#align(center + horizon, body)
]
} else {
polylux-slide[
#align(center + horizon, body)
]
}
}
#let title-slide(title, author: "") = {
set heading(outlined: false)
centered-slide({
heading(title)
parbreak()
author
})
}
#let focus-slide(background: aqua.darken(50%), foreground: white, body) = {
set page(fill: background)
set text(fill: foreground, size: 1.5em)
polylux-slide(align(center + horizon, body))
}
#let slide(body) = {
let deco-format(it) = text(size: .6em, fill: gray, it)
set page(
header: locate( loc => {
let sections = query(heading.where(level: 1, outlined: true).before(loc), loc)
if sections == () [] else { deco-format(sections.last().body) }
}),
footer-descent: 1em,
header-ascent: 1em,
)
polylux-slide(body)
}
#let column-and-figure-slide(title, column_content: "", figure: "") = slide(
{
set text(size: 0.9em);
let header_cell = heading(level: 2, title);
grid(
columns: (1fr, 2fr),
rows: (1fr),
gutter: 1em,
[
#header_cell
#v(1em)
#column_content
],
align(
center + horizon,
figure,
),
)
}
)
#let main-point-slide(body) = slide(
align(
horizon,
pad(
right: 20%,
body
)
)
)
#let gh_link = (path) => box(link("https://github.com/" + path)[#fa-icon("github", fa-set: "Brands") #path]);
#let gh_user = (user) => gh_link(user);
#let gh_repo = (user, repo) => gh_link(user + "/" + repo);
#let linkedin_user = (user) => box(link("https://linkedin.com/in/danjones1618")[#fa-icon("linkedin", fa-set: "Brands") /in/#user]);
#let end-slide(add_profile_pic: false, body) = {
let name_and_links = {
"<NAME>";
set text(size: 0.75em);
parbreak();
link("danjones.dev");
parbreak();
gh_user("danjones1618");
parbreak();
linkedin_user("danjones1618");
};
let profile_pic = align(
center + horizon,
image("./profile_pic.jpg", width: auto, height: 6em)
)
let aside_content = name_and_links;
if add_profile_pic {
aside_content = grid(
columns: (auto, auto),
gutter: 1em,
name_and_links,
profile_pic,
);
}
slide(
grid(
columns: (1fr, auto),
rows: (1fr),
gutter: 1em,
body,
grid.cell(
align: left,
align(end + bottom, aside_content),
)
)
)
}
|
|
https://github.com/UBOdin/data_structures_book | https://raw.githubusercontent.com/UBOdin/data_structures_book/main/chapters/2-math.typ | typst | = Math Refresher
This section will cover:
- Summation
- Exponentiation / Logarithms
|
|
https://github.com/iceghost/resume | https://raw.githubusercontent.com/iceghost/resume/main/5-projects/3-examinator.typ | typst | === Mock Examinator
#place(right + top)[Jun 2021 - Dec 2021]
/ Links: #link("https://chungtacungtien.vercel.app")[Demo].
/ Role: Frontend Developer in a 4-person team.
This website provides user interfaces for both examinees and exam authors to
organize mock exams. This helps students experience mock examinations when
COVID-19 was still around.
_Result_: \~300 students participated per exam, with 4 exams per semester,
over 2 semesters.
This was my first real-world _team_ project. I learned the basics of working
in a team, such as Git workflows, regular stand-up meetings and how different
people develop software.
|
|
https://github.com/dariakoz/Typst-Template | https://raw.githubusercontent.com/dariakoz/Typst-Template/main/lib/intro.typ | typst | #let data(key, value) = {
table(
columns: (1fr, 3fr),
stroke: none,
align: horizon,
key, stack(
value,
spacing: 8pt,
line(length: 100%),
)
)
v(1em)
}
#let tickbox(numbering, ticked) = {
table(
columns: (auto),
stroke: none,
align: horizon,
numbering,
rect(width: 5mm, height: 5mm, stroke: black, if ticked [✓])
)
}
#let project_number(number) = {
table(
columns: (1fr, 3fr),
stroke: none,
align: horizon,
[Projektarbeit Nr.:], stack(
stack(
dir: ltr,
tickbox("I", number == 1),
tickbox("II", number == 2),
tickbox("III", number == 3),
tickbox("IV", number == 4)
),
spacing: 16pt
)
)
}
#let toc() = {
show outline.entry.where(
level: 1
): it => {
v(12pt, weak: true)
strong(it)
}
hide(
heading("Inhaltsverzeichnis", numbering: none)
)
outline(
title: "Inhaltsverzeichnis",
depth: 3,
indent: 2em
)
} |
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/include.typ | typst | Apache License 2.0 | #include "cond.typ"
#import "cond.typ"
#import "cond.typ" as test
#import "cond.typ": a as c, b as d
|
https://github.com/ilsubyeega/circuits-dalaby | https://raw.githubusercontent.com/ilsubyeega/circuits-dalaby/master/Type%201/2/41.typ | typst | #set enum(numbering: "(a)")
#import "@preview/cetz:0.2.2": *
#import "../common.typ": answer
2.41 다음 회로의 전원에서 공급되는 전력을 구하라.
#answer[
Y to delta, Mesh 방법 중 Y to delta로 각 6개의 저항이 달린 T자를 delta로 변환한다.
$R_a = R_b = R_c = (6 dot 6) dot 3 / 6 = 18 ohm$
$R_(e q) = 10$
$I = V / R = 20 / 10 = 2 A$
$P = V I = 20 dot 2 = 40 W$
] |
|
https://github.com/jneug/schule-typst | https://raw.githubusercontent.com/jneug/schule-typst/main/tests/wp/test.typ | typst | MIT License | #import "@local/schule:1.0.0": wp
#import wp: *
#show: wochenplan.with(
/* @typstyle:off */
titel: "Base template test",
reihe: "TYPST-TEST",
datum: "15.06.2024",
nummer: "1",
fach: "Typst",
kurs: "101",
autor: (
name: "<NAME>",
kuerzel: "Ngb",
),
version: "2024-06-15",
)
#gruppe("Pflichtaufgaben")[
#lorem(10)
][
- #bu((1, 2, 3, 4), (1, 2, 3))
]
#gruppe("Pflichtaufgaben")[
#lorem(10)
][
- #bu((1, 2, 3, 4), (1, 2, 3))
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.