repo
stringlengths 27
90
| file
stringlengths 57
176
| language
stringclasses 2
values | license
stringclasses 13
values | content
stringlengths 25
180k
|
---|---|---|---|---|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/figure_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test localized default separator
#set text(lang: "fr", region: "CH")
#figure(
circle(),
caption: [Un cercle.],
)
#set text(lang: "es")
#figure(
polygon.regular(size: 1cm, vertices: 3),
caption: [Un triángulo.],
)
#set text(lang: "fr", region: "CA")
#figure(
square(),
caption: [Un carré.],
)
|
https://github.com/tfachada/thesist | https://raw.githubusercontent.com/tfachada/thesist/main/template/Chapters/Appendix-B.typ | typst | MIT License | #import "@preview/thesist:0.2.0": flex-caption, subfigure-grid
#import "@preview/glossarium:0.5.0": gls, glspl
= Another appendix
#lorem(300)
#figure(
rect(),
caption: [An appendix image]
)<example_ref_B>
#subfigure-grid(
in-appendix: true,
figure(
rect(),
caption: [An image on the left.]
), <sub-left-example-2>,
figure(
rect(),
caption: [An image on the right.#v(1em)]
), <sub-right-example-2>,
align: top,
columns: (1fr, 1fr),
caption: [An appendix figure with two images],
label: <subfigure-grid-example-2>,
)
|
https://github.com/QuadnucYard/crossregex-typ | https://raw.githubusercontent.com/QuadnucYard/crossregex-typ/main/src/hex.typ | typst | MIT License | #import "layout.typ": *
#import "process.typ": *
#let r3 = calc.sqrt(3)
#let crossregex-hex(
size,
alphabet: regex("[A-Z]"),
constraints: (),
answer: none,
show-whole: true,
show-views: true,
cell: auto,
cell-config: (:),
deco-config: (:),
progress-creator: auto,
page-margin: 0.5em,
) = {
if cell == auto {
cell = rotate(30deg, polygon.regular(size: 2em, vertices: 6, stroke: 0.5pt), origin: center)
}
let cell-config = (size: 1em) + cell-config
let s = cell-config.size
let n1 = size - 1
let n2 = size * 2 - 1
let total = 3 * size * (size - 1) + 1
let (constraints, max-len, answer, filled, a, aa, progress) = process-args(
rows: n2,
row-len: i => n2 - calc.abs(i - n1),
total: 3 * size * (size - 1) + 1,
constraints: constraints,
constraint-size: n2 * 3,
answer: answer,
alphabet: alphabet,
rotators: (
(i, j) => (n2 - 1 - j - calc.max(i - n1, 0), calc.min(calc.min(i + n1, n2 - 1) - j, i)),
((i, j) => (calc.max(n1 - i, 0) + j, calc.min(n2 - 1 - calc.max(i - n1, 0) - j, n2 - i - 1))),
),
progress-creator: progress-creator,
)
let center = (x: (n1 + 0.5) * r3 * s, y: (n1 * 1.5 + 1) * s)
let ext = max-len * 0.5em + 1em // extension by constrains
let (puzzle-whole, puzzle-view) = build-layout(
angle: 120deg,
rows: n2,
row-len: i => n2 - calc.abs(i - n1),
cell: cell,
cell-size: s,
cell-config: cell-config,
alphabet: alphabet,
cell-pos: (i, j) => ((j + calc.abs(i - n1) * 0.5 + 0.5) * r3 * s, (i * 1.5 + 1.0) * s),
char-box-size: (r3 * s, 1.5 * s),
deco-pos: i => (center.x + -calc.abs(i - n1) * 0.5 * r3 * s, (i - n1) * 1.5 * s),
deco-config: deco-config,
center: center,
num-views: 3,
view-size: (center.x * 2 + ext, center.y * 2),
whole-size: (center.x * 2 + ext * 1.5, center.y * 2 + ext * r3),
whole-grid-offset: (ext * 0.5, ext * r3 / 2),
)
doc-layout(
whole-maker: if show-whole {
() => puzzle-whole(constraints, aa)
},
view-maker: if show-views {
k => puzzle-view(constraints.at(k), aa.at(k))
},
num-views: 3,
progress: progress,
margin: page-margin,
)
}
|
https://github.com/EstebanMunoz/typst-template-informe | https://raw.githubusercontent.com/EstebanMunoz/typst-template-informe/main/README.md | markdown | MIT No Attribution | # typst-template-informe
Template para la creación de informes universitarios usando Typst.
|
https://github.com/Ryoga-itf/differential-equations | https://raw.githubusercontent.com/Ryoga-itf/differential-equations/main/report02/report.typ | typst | #import "../template.typ": *
#import "@preview/tenv:0.1.1": parse_dotenv
#import "@preview/physica:0.9.2": *
#let env = parse_dotenv(read("../.env"))
#show: project.with(
week: "第2回",
authors: (
(name: env.STUDENT_NAME, email: "学籍番号:" + env.STUDENT_ID, affiliation: "所属:情報科学類"),
),
date: "2024 年 10 月 10 日",
)
#show math.equation: set text(font: ("New Computer Modern Math", "Noto Serif", "Noto Serif CJK JP"))
== 問題 1
=== (1)
与えられた式の両辺を $y^2$ で割った上で $x$ で積分すると、
$
dv(y, x) = y^2 / x => 1 / y^2 dv(y, x) = 1/x => integral 1 / y^2 dif y = integral 1/x dif x + c
$
だたし、ここで $c$ は任意定数である。
よって、
$
- 1/y = log abs(x) + c \
therefore 1/y = -log abs(x) - c \
therefore y = 1 / (-log abs(x) - c)
therefore y = 1 / (C - log abs(x))
$
ここで、$C$ は $C = -c$ である定数
以上より、以下の解が得られる。
$
y = x / (C - log abs(x))
$
=== (2)
与えられた式の両辺を $y^2$ で割った上で $x$ で積分すると、
$
dv(y, x) = y^2 / x^2 => 1 / y^2 dv(y, x) = 1 / x^2 =>integral 1 / y^2 dif y = integral 1 / x^2 dif x + c
$
ただし、ここで $c$ は任意定数である。
よって、
$
- 1/y = - 1/x + c \
therefore 1/y = 1/x - c \
therefore y = 1 / (1/x - c) = x / (1 - c x) = x / (1 + C x) \
$
ここで、$C$ は $C = -c$ である定数
以上より、以下の解が得られる。
$
y = x / (1 + C x)
$
=== (3)
与えられた式の両辺を $y^2$ で割った上で $x$ で積分すると、
$
dv(y, x) = y^2 / x^n => y^2 dv(y, x) = 1 / x^n => integral y^2 dif y = integral 1 / x^n dif x + c
$
ただし、ここで $c$ は任意定数である。
$n != 1$ であるから、
$
- 1/y = 1 / (1 - n) x^(1 - n) + c \
therefore 1/y = - 1 / (1 - n) x^(1 - n) - c \
therefore 1/y = 1 / (n - 1) x^(1 - n) - c \
therefore y = 1 / (1 / (n - 1) x^(1 - n) - c) = (n - 1) / (x^(1 - n) - (n - 1) c)
$
よって、一般解は
$
y = (n - 1) / (x^(1 - n) - (n - 1) c)
$
また、$(x, y) = (1, -1)$ を満たす解は、
$
-1 = (n - 1) / (1 - (n - 1) c) \
<=> -1 + (n - 1)c = n - 1 \
<=> (n - 1)c = n \
therefore c = n / (n - 1)
$
より、
$
y = (n - 1) / (x^(1 - n) - n)
$
=== (4)
与えられた式を変形すると、
$
(x^2 - x y) dv(y, x) + y^2 = 0 <=> dv(y, x) = -y^2 / (x^2 - x y)
$
右辺の分子と分母を $x^2$ で割ると、
$
dv(y, x) = - (y\/x)^2 / (1 - y\/x)
$
$v = y\/x$ とおく。つまり、$y = x v$ とおくと、$dv(y, x) = v + x dv(v, x)$ であるから、
$
v + x dv(v, x) = -v^2 / (1 - v) => dv(v, x) = 1/x (-v^2 / (1 - v) - v) \
therefore dv(v, x) = -1/x v/(1 - v) \
therefore (1 - v) / v dv(v, x) = - 1/x
$
よって、両辺を $x$ で積分すると、
$
integral (1 - v) / v dif v = integral -1/x dif x \
=> log abs(v) - v = - log abs(x) + c \
=> v e^(-v) = A / x
$
ただし、$A$ は正の実数 $(because A = e^c > 0)$
=== (5)
与えられた式を変形すると、
$
x dv(y, x) - y = 2 x^2 + 3 => dv(y, x) - 1/x y - 2x - 3/x = 0
$
1 階線形微分方程式とみなして、$p(x) = -1/x, q(x) = -2x - 3/x$ とおく。
$
accent(z, macron)(x) &= integral p(x) dif x = -log abs(x) \
z(x) &= e^(-accent(z, macron)(x)) = e^(log abs(x)) = abs(x) \
s(x) &= integral q(x) / z(x) dif x = integral (2x^2 + 3) dif x = 2/3 x^3 + 3x
$
よって、一般解は
$
y = abs(x) ( -2/3 x^3 - 3x + c)
$
=== (6)
与えられた式を変形すると、
$
dv(y, x) - y tan x = cos x <=> dv(y, x) - y tan x - cos x = 0
$
1 階線形微分方程式とみなして、$p(x) = -tan x, q(x) = -cos x$ とおく。
$
accent(z, macron)(x) &= integral p(x) dif x = log abs(cos x) \
z(x) &= e^(-accent(z, macron)(x)) = e^(-log abs(cos x)) = -abs(cos x) \
s(x) &= integral q(x) / z(x) dif x = integral (cos x) / abs(cos x) dif x = x
$
よって、一般解は
$
y = -abs(cos x)( -x + c )
$
=== (7)
$p(x) = 1/x, q(x) = x^2$ とおく。
$z = y^(-2)$ とおき、これを微分すると、
$
z' = -2y^(-3)y' \
therefore y^3 z' = -2y' \
therefore y' = - y^3 / 2 z'
$
よって、
$
- y^3 / 2 z' + p(x) y = q(x) y^3 \
=> -z' / 2 + p(x) y^(-2) = q(x) \
therefore -z'/2 + p(x) z = q(x) \
therefore z' - 2p(x) z + 2 q(x) = 0
$
1 階線形微分方程式とみなして、これを解くと、
$
accent(z, macron)(x) &= integral -2p(x) dif x = -2 log abs(x) \
z(x) &= e^(-accent(z, macron)(x)) = e^(-2 log abs(x)) = 1 / x^2 \
s(x) &= integral q(x) / z(x) dif x = integral -2 x^4 dif x = -2 / 5 x^5
$
よって、
$
z = 1 / x^2 (2 / 5 x^5 + c) <=> y^(-2) = 1 / x^2 (2 / 5 x^5 + c) = 2 / 5 x^3 + c/x^2
$
であるから、一般解は
$
y = -1 / sqrt( 2/5 x^3 + c/x^2 )
$
$(x, y) = (-1, 1)$ を満たす解は、
$
y = -1 / sqrt( 2/5 x^3 + 3 / (5 x^2))
$
== 問題 2
$p(x) = x^2, q(x) = -(1 + 2x^3), r(x) = x^4 + x = 1$ とおく。
$y(x) = Y(x) + x$ とおくと、
$
Y' + (2x p(x) + q(x))Y + p(x) Y^2 = 0
$
よって、
$
dv(z, x) - (2x p(x) + q(x)) z - p(x) = 0
$
1 階線形微分方程式とみなして、これを解くと、
$
accent(z, macron)(x) &= integral -(2x p(x) + q(x)) dif x = x \
z(x) &= e^(-accent(z, macron)(x)) = e^x \
s(x) &= integral -p(x) / z(x) dif x = integral -x^2 / x dif x = -1/2 x^2
$
よって、
$
z &= e^x (1/2 x^2 + c) \
=> 1/Y &= e^x (1/2 x^2 + c) \
=> Y &= 1 / (e^2 (1/2 x^2 + c)) \
=> y - x &= 1 / (e^2 (1/2 x^2 + c)) \
=> y &= 1 / (e^2 (1/2 x^2 + c)) + x \
$
また、$(x, y) = (0, 1)$ を満たす解は、$c = 1$ であるから、
$
y = 1 / (e^2 (1/2 x^2 + 1)) + x
$
|
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/复变函数/main.typ | typst | #import "../template.typ": proof, note, corollary, lemma, theorem, definition, example, proposition, remark, der, partialDer
#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: "复变函数",
author: "YHTQ",
date: none,
logo: none,
withHeadingNumbering: true
)
= 前言
- 教师:李智强
- 成绩:作业 30% 期中 30% 期末 40% 额外激励 10% - 20%
- 周五交一次作业,每周一次
- https://www.math.pku.edu.cn/teachers/lizq/teaching/2024Spring/complex%20variables/course_site.html
- 参考书:
- *复变函数简明教程,谭小江、伍胜健编著,北京大学出版社。*
- *Functions of One Complex Variable,<NAME>,Springer* (GTM)
- Complex Analysis,<NAME>,McGraw-Hill
- Complex Analysis,<NAME> & <NAME>,Princeton University Press
- Real and Complex Analysis,<NAME>,McGraw-Hill
复分析某种意义上是分析学中性质最好的情况下的一些理论
= 复数,复平面拓扑的基本知识
#definition[复数][
称 $CC$ 在集合上为 $RR times RR$,定义运算:
- $(a, b) + (c, d) = (a + b, c + d)$
- $(a, b) times (c, d) = (a c - b d, a d + b c)$
并令 $(Re(a, b), Im(a, b)) = (a, b)$
]
#proposition[][
$(CC, +, times)$ 构成一个域,同时域 $RR$ 可以自然的嵌入 $CC$
]
通常的,$(a, b)$ 可以记作 $a + b i$,其中 $i = (0, 1)$ 被称为虚数根(imaginary unit)。复数的早期起源当然是关于 $sqrt(-1)$ 的可行性的探讨研究。
#definition[复共轭|complex conjugate][
对于 $z = a + b i$,定义其复共轭为 $overline(z) = a - b i$,不难验证它是域自同构
]
#example[][
设 $f(z) = p(z)/q(z)$ 是有理函数,称 $g(z) = overline(f(z))$ 为反有理函数(anti-rational),它也是复动力系统的研究对象之一
]
#definition[模|absolute value/norm][
对于 $z = a + b i$,定义其模为 $norm(z) = sqrt(a^2 + b^2) = z overline(z)$
]
#definition[幅角|argument][
对于 $z = a + b i != 0$,定义:
- 其幅角为 $Arg(z) = {theta in RR | z = norm(z)(cos theta + i sin theta)}$
- 其幅角主值 $arg(z)$ 为 $Arg(z)$ 在 $[0, 2 pi)$ 上唯一的元素
]
#theorem[三角不等式][
由于复平面的模就是欧式平面的模,自然成立三角不等式:
$
|norm(a) -)\
$
]
#theorem[][
- $Arg(z_1 z_2) = Arg(z_1) + Arg(z_2)$
- $Arg(z_1/z_2) = Arg(z_1) - Arg(z_2)$
]
#remark[复平面的曲线方程][
一个复方程对应一个复平面上的曲线,最简单的包括:
- 直线方程:
$
A overline(z) + overline(A) z + b = 0, A in CC, b in RR
$
- 圆方程:
$
|z - a| = r, a in CC, r in RR\
<=> -z overline(z) + A overline(z) + overline(A) z + b = 0, A in CC, b in RR
$
这也表明在复的意义下,直线是圆的某种退化形式
]
#definition[复空间的度量/拓扑][
定义复平面的度量就是欧式度量,具体而言:
$
d(z_1, z_2) = norm(z_1 - z_2)
$
容易验证 $d$ 满足度量公理,从而 $(CC, d)$ 是一个度量空间,由此生成的拓扑成为复平面的拓扑,由此度量/拓扑自然也可生成极限
]
#remark[][
我们也使用通常度量空间的记号,例如:
- $B(z_0, r) := {z in ZZ | d(z_0, z) < r}$
- $overline(B)(z_0, r) := {z in ZZ | d(z_0, z) <= r} = overline(B(z_0, r))$
- $B_o(z_0, r) = B(z_0, r) - {z_0}$
]
#theorem[][
$S$ 连通当且仅当其中既开又闭的集合只有空集和全集
]
#proposition[][
在复平面上,对于开集 $S$ 以下事实等价:
- $S$ 连通
- $S$ 路径连通
- $S$ 中任取两点 $x, y$ 存在分段线性路径将其连接
一般拓扑空间中三者往往都不等价
]
#proof[
- $1 => 3$: 任取 $z in S$,取 $Omega= {x in S | x "与 " z "有分段线性的道路"}$,往证 $Omega$ 既开又闭
- $Omega$ 开:任取 $x in Omega$,由于 $S$ 开,存在 $r > 0$ 使得 $B(x, r) subset S$。在开球中当然可以找到分段线性道路,从而 $B(x, r) subset Omega$
- $Omega$ 闭:往证 $S - Omega$ 是开集。显然任取 $y in S - Omega$ 当且仅当 $y$ 到 $x$ 没有分段线性路径。显然存在 $y$ 的开球 $subset S$,其中任何点到 $x$ 都没有分段线性路径,从而 $S - Omega$ 是开集
- $3 =>2, 2 => 1$ 都是显然的
]
#definition[Cauthy 序列][
若序列 ${x_i}$ 满足:
$
forall epsilon > 0, exists n in NN,\
m, l in NN > n => d(x_m, x_l) < epsilon
$
]
#definition[完备空间|Complete Space][
若度量空间 $(X, d)$ 中任意 Cauthy 序列都收敛,则称其为完备空间
]
#theorem[Cantor][
度量空间是完备的当且仅当闭集套确定唯一公共点,也就是说:\
对于任何非空下降闭集序列 ${F_i}$ 满足 $d(F_i) ->0$,那么恰有 $| sect.big_i F_i | = 1$
]<Cantor>
#proof[
- 假设空间完备,对于某个闭集套 $F_i$ 选出 $x_i in F_i$,由于 $d(F_i) ->0$,当 $i$ 充分大时有 $d(F_i) < epsilon$,进而对 $j > i, x_j in F_i => d(F_j, F_i) < epsilon$,给出 ${x_i}$ 是 Cauthy 序列。从而收敛到 $x$,由于 $F_i$ 都是闭集,故 $x in sect.big_i F_i$\
此外,由直径趋于零显然 $sect.big_i F_i$ 不会有第二个点,否则直径都大于两点间距离
- 假设闭集套成立,任取 Cauthy 序列 ${x_i}$,取 $F_i = overline({x_j | j > i})$,显然 $d(F_i) ->0$(注意到集合在半径为 $r$ 的开球中,它的闭包也在),从而 $sect.big_i F_i$ 是唯一的点 $x$\
$x$ 是所有如上定义的闭包的交点,它一定是序列的极限。(注意到 $F_i$ 的直径趋近于零,因此对于充分大的 $n$,$F_n$ 中每个点到 $x$ 的距离都小于 $epsilon$)
]
#theorem[][
欧式空间是完备的。特别的,复平面是完备的
]
#theorem[][
完备空间的子集完备当且仅当它是闭集
]
#proof[
设 $Y$ 是完备空间 $X$ 的子集
- 若子集完备,对于任何 $Y$ 的极限点 $x$,存在 $x_i in Y -> x in X$。显然 $x_i$ 作为收敛列是柯西列,由 $Y$ 完备知 $x in Y$
- 若 $Y$ 是闭集,其中的柯西列在 $X$ 中也是柯西列,因此收敛于 $x in X$,但 $Y$ 是闭集,其中序列不会有 $Y$ 之外的极限点,从而 $x in Y$\
另证:使用 @Cantor,注意到 $Y$ 之中的闭集在 $X$ 中当然也是闭集
]
#definition[稠密|dense][
称 $Y subset X$ 稠密,如果 $overline(Y) = X$
]
#definition[紧性|compact][
若 $X$ 的任何开覆盖都有有限子覆盖,则称 $X$ 是紧的
]
#theorem[][
- 紧致集一定是闭集
- 紧致集的闭子集仍然紧致
]
#lemma[Lebesgue][
设 $X$ 是列紧的度量空间,$E$ 是开覆盖,则存在 $epsilon > 0$ 使得 $X$ 中每个点的 $epsilon$ 邻域球都在 $E$ 的某一个子集中
]<Lebesgue_Lemma>
#proof[
如若不然,取 $epsilon_n = 1/n$ 下降,可得 $exists x_i, B(x_i, 1/i)$ 不在任何覆盖中。由列紧性,这些 $x$ 有聚点 $x_0$。该聚点当然在某个覆盖中,因此该点的某个开邻域球 $B(x, epsilon)$ 处于某个覆盖中,当 $epsilon > 1/i$ 时,这与 $B(x_i, 1/i)$ 不在任何覆盖中矛盾
]
#theorem[][
设 $X$ 是度量空间,以下命题等价:
- $X$ 是紧致的
- $X$ 的任何无穷子集都有聚点
- $X$ 列紧,也即无穷序列都有收敛子列
- $X$ 是完备的并且完全有界(任何 $epsilon > 0$ 都存在有限个点,使得每个点的 $epsilon$ 闭包覆盖整个空间)
]
#proof[
- $1 => 2$: 反证法,若无穷子集没有聚点,那么每个点都有一个 $epsilon$ 邻域球不包含其他点,从而构成无穷开覆盖,由紧致性有有限子覆盖,矛盾
- $2 => 3$: 假设序列中只有有限多个点,那么显然有收敛子列,否则有无穷多个点,由 $2$ 知有聚点。该聚点就是一个子列的极限
- $3 => 4$:
- 先证明完备性:利用柯西序列有收敛子列,结论是显然的
- 再证明完全有界。如若不然,存在 $epsilon > 0$,任意有限个点的 $epsilon$ 邻域都不能覆盖全空间,如此:
- 任取 $x_0 in X$
- 显然 $B(x_0, epsilon)$ 不能覆盖 $X$,取 $x_1 in X - B(x_0, epsilon)$
- 显然 $B(x_0, epsilon) union B(x_1, epsilon)$ 不能覆盖 $X$,取 $x_2 in X - (B(x_0, epsilon) union B(x_1, epsilon))$
- ...
这就定义了一个序列 $x_i$ 使得:
$
forall i in NN, forall j < i, x_i in.not B(x_j, epsilon)
$
然而由于 $X$ 列紧,我们可以不妨假设 $x_n$ 收敛,上面的事实同样成立,显然产生了矛盾
- $4 => 3$:\
任取序列 $x_n$,由完全有界性,可取有限多个半径为 $1$ 的球覆盖整个 $X$。有限多个球覆盖了 $x_n$ 中无穷多个点,进而可以选出一个覆盖了无穷多个点。选出其再递归进行(选取更小的半径 $1, 1/2, 1/3, ...$ 。\
为了构造收敛子列,先在第一个球中选出 $y_1$,再在更小的第二个球中选出位于 $y_1$ 之后的 $y_2$ 等等。这样构造出的序列显然是柯西序列,进而收敛
- $3 => 1$\
利用 @Lebesgue_Lemma,任取开覆盖 $E$,将存在 $epsilon > 0$ 使得 $X$ 中每个点的 $epsilon$ 邻域球都在 $E$ 的某一个子集中。注意到 3 蕴含了 4, 蕴含了完全有界,对于这个 $epsilon$,存在有限个点的 $epsilon$ 邻域球覆盖了整个空间,从而这有限个点对应的有限个覆盖恰好可以覆盖整个空间
]
#theorem[Heine-Borel][
欧式空间中紧致当且仅当有界闭集
]
#proof[
之前证明了度量空间中紧致当且仅当列紧,而 $RR^n$ 中的列紧与 $RR$ 的列紧是等价的(只需依次取每一维的收敛子列),由一维情形容易验证结论成立
]
#definition[$CC$ 上的曲线][
设:
$
funcDef(gamma, [0,1], CC, t, (x(t), y(t)))
$
- 若 $gamma$ 连续,则称之为连续|continuous/$C^0$曲线
- 若 $x(t), y(t)$ 都连续可导且 $x'(t)^2 + y'(t)^2 != 0$,则称之为光滑|smooth/$C^1$曲线
- 若曲线在有限个段上都是光滑的,则称之为分段光滑曲线
- 若
$
integral_0^1 sqrt(x'(t)^2 + y'(t)^2) dif t
$
存在且有限,则称之为可求长|rectifiable 曲线
]
#definition[区域][
称 $D subset CC$ 为区域,如果 $D$ 是开集且连通(注意到 $RR^n$ 上的开集,连通等价于路径连通,因此也可等价定义为路径连通的开集)
]
#theorem[][
设 $E$ 是一族 $X$ 的连通子集,且两两相交不空,则 $union.big E$ 也连通
]
#definition[连通分支|connection component][
称集合 $S$ 的连通分支是一个极大的连通子集,也就是连通且不被更大的连通子集包含
]
#definition[约当曲线|Jordan curve][
称简单闭曲线为约当曲线,也就是首尾闭合,不经过其他点两次的曲线
]
#theorem[Jordan Curve Theorem][
对于任意 $CC$ 上的约当曲线 $gamma$,$CC - gamma$ 恰有两个连通分支
]
#proof[
它的证明出乎意料的非常困难。Jordan 最初给出了证明,但是并不被认可。具体证明详见见 GTM Conway 2\
Bonus: 找到 Jordan 最初给出的证明其中公认并不正确的一步
]
#definition[单连通][
称区域 $D$ 是单连通的,对于任何 Jordan 曲线 $gamma subset D$,存在 $D_0 subset D$ 使得 $D_0$ 的边界恰为 $gamma$
]
往往复平面会比实数有更好的代数结构和分析结构,然而复平面的拓扑却远比实数复杂。
#definition[函数极限][
设复函数 $f: S -> C$,若:
$
exists A in CC, forall epsilon > 0, exists delta >0:\
z in B(x_0, delta) sect S => f(z) in B(A, epsilon)
$
则称 $f(z)$ 在 $z_0$ 处有极限 $A$|f attach to $A$ at $x_0$,记作 $lim_(z->z_0) f(z) = A$\
注意这里并不要求 $S$ 有任何开闭等性质
]
如无特殊说明,我们说的极限存在都是指有限极限
#theorem[][
函数极限存在当且仅当实部和虚部的极限分别对应存在
]
#definition[连续函数|Continuous Function][
称复函数 $f: S -> CC$ 于 $z_0 in S$ 连续,如果:
- 若 $z_0$ 是 $S$ 的极限点,则 $lim_(z->z_0) f(z) = f(z_0)$
- 若不是极限点,直接称 $f(z)$ 于该点连续
称 $f$ 于 $S$ 连续,如果 $f$ 在 $S$ 的每一点都连续,记 $f in C(S, CC)$ 或 $f in C^0(S, CC)$
]
#proposition[][
设 $f: X -> CC$ 于 $S$ 连续,那么:
- 开集的原像是开集
- 闭集的原像是闭集
- 连通集的像是连通集
- 紧集的像是紧集
- 连续函数与连续函数的复合仍然连续
- 连续函数于紧集上有界且可以取得(模的)最大最小值
- 连续函数在紧集上一致连续
]
#definition[扩充复平面|Extended Complex Sphere/黎曼球面|Riemann Sphere][
定义扩充复平面为 $CC = {infinity} union RR$,其中 $infinity$ 被称为无穷远点,并且定义:
- $a plus.minus infinity = infinity, forall a in CC$
- $a times infinity = infinity, forall a in CC - {0}$
- $a / 0 = infinity, forall a in CC - {0}$
其余的运算无意义
它恰好相当于将球面以北极为中心投影,北极点本身对应无穷远点,以此定义它的拓扑。
其上还可以定义距离,有一些常用的距离包括:
- Chordul metric: 利用两点在黎曼球上三维空间的连线长度
- Spherical metric: 利用两点在黎曼球上三维空间的大圆弧长度
]
= 基础分析
== 解析函数
本节中 $G$ 一般指开集
#definition[可导|differentiable][
-
设 $G$ 是开集,$f: G -> CC$,称 $f$ 在 $z_0$ 可导,如果:
$
lim_(h -> 0) (f(z_0+h)-f(z_0))/h
$
存在且不是无穷,并称其为 $f$ 在 $z_0$ 处的导数,记作 $f'(z_0)$
- 进一步,如 $f$ 在开集 $G$ 内每一点都可导,则称 $f$ 在 $G$ 内可导 / 解析|analytic / 复可导 / 全纯|holomorphic
这里的多种叫法其含义都略有差异,但在这里(集合为开集的情况下)它们都是等价的
]
我们也使用 $o$ 记号,函数可导也可记作:
$
f(x) = f(z_0) + f'(z_0) (z - z_0) + o(z - z_0), z - z_0 -> 0
$
#theorem[][
若 $f: G -> CC$ 于 $x_0$ 可导,则于 $x_0$ 连续
]
#proof[
$
lim_(z -> z_0) norm(f(z) - f(z_0)) = lim_(z -> z_0) norm((f(z) - f(z_0))/(z - z_0)) norm(z-z_0)
$
由极限的乘法法则,前者极限存在,后者趋于零,因此极限为零
]
#proposition[导数的运算法则][
- $(f + g)' = f' + g'$
- $(f g)' = f' g + f g'$
- 若 $g != 0$,则 $(f/g)' = (f' g - f g')/g^2$
- 若 $h$ 于 $f(a)$ 可导,$f$ 于 $a$ 可导,那么 $(h compose f)'(a) = h'(f(a)) f'(a)$
]
#definition[解析 | analytic][
设 $A subset CC$ 是一般集合,称 $f$ 在其上解析,如果存在开集 $G supset A$ 使得 $f$ 在 $G$ 上解析
]
#definition[单叶解析函数 | univalent function][
设 $G$ 是开集,$f$ 在 $G$ 上解析且是单射,则称 $f$ 是单叶(解析)函数\
有时也称之为共形映射 | conformal mapping,但 conformal 有时也也指所有解析的函数,因此可能会产生歧义
]
univalent 可以给出许多几何上有趣的结论
#proposition[][
单叶解析函数具有保角性
]
#proof[
这不是本节的重点,后面有机会会再提到
]
#definition[双全纯函数/全纯同胚 | biholomorphic][
若 $f: G -> CC$ 是双射且 $f, Inv(f)$ 都是全纯的,则称 $f$ 是双全纯函数,也称全纯同胚,有时也称为共形等价或者共形同胚
]
#theorem[][
设 $f: G -> CC$ 是单叶解析的,则:
- $f'(z) != 0, forall z in G$
- $f(G)$ 也是开集
- $Inv(f): f(G) -> G$ 也是解析的
- $(Inv(f))' (f(z)) = 1/(f'(z))$
]
#proof[
]
#theorem[Cauthy-Riemann equation][
设复函数 $f (x+y i)= u(x, y) + i v(x, y)$ 在开集内一点可导,则柯西黎曼公式:
$
partialDer(u, x) = partialDer(v, y)\
partialDer(u, y) = -partialDer(v, x)
$
成立。反之若 $u, v$ 是开集上的连续可微($C^1$)函数且上式成立,则 $f$ 于该点可导
]<C-R>
#proof[
- 若函数可导,考虑导数的极限在 $vec(1, 0), vec(0, 1)$ 两个方向上的子极限,立得:
$
f'(z_0) = partialDer(u, x) (x_0, y_0) + i partialDer(v, x) (x_0, y_0)\
f'(z_0) = partialDer(v, y) (x_0, y_0) - i partialDer(u, y) (x_0, y_0)
$
对比实部虚部分别相等即可
- 若 $u, v$ 是 $C^1$ 的且满足柯西黎曼方程,由可微性:
$
u(x_0 + Delta x, y_0 + Delta y) = u(x_0, y_0) + partialDer(u, x) (x_0, y_0) Delta x + partialDer(u, y) (x_0, y_0) Delta y + o(sqrt(Delta x ^2 + Delta y ^2))\
v(x_0 + Delta x, y_0 + Delta y) = v(x_0, y_0) + partialDer(v, x) (x_0, y_0) Delta x + partialDer(v, y) (x_0, y_0) Delta y + o(sqrt(Delta x ^2 + Delta y ^2))
$
代入 $f((x + Delta x) + (y + Delta y)i) - f(x + y i)$,得:
$
f((x + Delta x) + (y + Delta y)i) - f(x + y i) \
= (partialDer(u, x) (x_0, y_0) Delta x + partialDer(u, y) (x_0, y_0) Delta y + o(sqrt(Delta x ^2 + Delta y ^2))) \
+ i (partialDer(v, x) (x_0, y_0) Delta x + partialDer(v, y) (x_0, y_0) Delta y + o(sqrt(Delta x ^2 + Delta y ^2)))\
= (partialDer(v, y) (x_0, y_0) Delta x + partialDer(u, y) (x_0, y_0) Delta y + o(sqrt(Delta x ^2 + Delta y ^2))) \
+ i (- partialDer(u, y) (x_0, y_0) Delta x + partialDer(v, y) (x_0, y_0) Delta y + o(sqrt(Delta x ^2 + Delta y ^2)))\
= partialDer(v, y)(x_0, y_0) (Delta x + i Delta y) - i partialDer(u, y)(x_0, y_0) (Delta x + i Delta y) + o(sqrt(Delta x ^2 + Delta y ^2))\
= (partialDer(v, y)(x_0, y_0) - i partialDer(u, y)(x_0, y_0))(Delta x + i Delta y) + o(Delta x + i Delta y)
$
最后一式即表示 $f$ 在 $x_0 + y_0 i$ 处可导
]
#theorem[][
设函数 $f$ 在连通区域 $G$ 上解析,且 $f' = 0$,则它是常函数
]
#proof[
利用
]
#theorem[][
设 $f = u + i v$ 可微,$u, v in C^2$,则有:
$
(diff^2 u)/(diff x^2) = (diff^2 v)/(diff x diff y)\
(diff^2 u)/(diff y^2) = -(diff^2 v)/(diff x diff y)\
$
进而拉普拉斯算子 $(diff^2 u)/(diff x^2) + (diff^2 u)/(diff y^2) = 0$,满足前式的 $C^2$ 函数称为 调和|harmonic 函数\
类似的 $v$ 也是调和函数
]
#definition[][
设有两个调和函数 $u, v$ ,称 $v$ 是 $u$ 的 共轭调和函数|harmonic conjugate ,如果 $f = u + i v$ 解析\
]
#theorem[][
在单连通区域上,每个调和函数都有共轭调和函数
]<harmonic_conjugate>
#proof[
注意到复平面的连通区域一定分段路径连通,取定 $P = (x_0, y_0)$,对于任意一点 $z$,找到分段线性的道路 $gamma_1, gamma_2 : P -> z$\
取 $v(z) = integral_(gamma_1) partialDer(u, x) dif y - partialDer(u, y) dif x$,为了验证良定义性,需要计算 $gamma_1, gamma_2$ 给出相同的函数值\
注意到:
$
integral_(gamma_1 + gamma_2) partialDer(u, x) dif y - partialDer(u, y) dif x\
= integral_D ((diff^2 u)/(diff x^2) + (diff^2 u)/(diff y^2)) dif x dif y = 0
$
(利用格林公式,这需要区域的单连通性)\
因此定义是良好的\
只需验证:
$
partialDer(v, y) = partialDer(u, x)\
partialDer(v, x) = -partialDer(u, y)
$
事实上,不难发现:
$
v(x, y + Delta y) - v(x, y) = integral_(0)^(Delta y) partialDer(u, x) dif y\
partialDer(v, y) (x, y) = lim_(Delta y -> 0)1/(Delta y) integral_(0)^(Delta y) partialDer(u, x) dif y = partialDer(u, x)(x, y)
$
另一个同理可得
]
#remark[][
- 注意 $u, v$ 的地位不均等,若 $u + i v$ 可微则 $v + i u$ 往往并不可微,但 $v - i u = -i (u + i v)$ 是可微的
- 若 $v_1, v_2$ 都是 $u$ 的共轭调和函数,则 $v_1 - v_2$ 在各个连通分支上是一个常数,这是因为由柯西黎曼公式 $v_1, v_2$ 的两个偏导都相等,由 $C^2$ 性知它们只差一个常数
- $u(x, y) = ln (x^2 + y^2)$ 在 $CC - 0$ 上调和,但没有共轭调和函数
]
#definition[][
对于复可微函数 $f$,记:
$
partialDer(f, overline(z)) = 1/2 (partialDer(f, x) + partialDer(f, y))\
$
显然 $f$ 可微当且仅当 $partialDer(f, overline(z)) = 0$
]
#theorem[][
设 $Omega$ 单连通,其上的 $C^2$ 解析函数 $f != 0$,则存在解析函数 $g(z)$ 使得 $e^(g(z)) = f(z)$
]
#proof[
令 $u_1(z) = ln norm(f(z))$
- 它是调和函数,因为\
$
ln norm(f(z)) = ln (x(z)^2 + y(z)^2)\
u'_1(a, b) = 1/(x(z)^2 + y(z)^2) (2 x(z) x'(z) + 2 y(z) y'(z))\
u''_1(a, b) = lambda ((x'^T x' + x x'' + y'^T y' + y y'')(x^2 + y^2) -2(x x' + y y')^T (x x' + y y'))\
$
计算得(这里 $x', y'$ 是行向量,$x'', y''$ 是矩阵):
$
tr(u'') = lambda((x^2 + y^2)tr(x'^T x' + x x'' + y'^T y' + y y'') - 2 tr((x x' + y y')^T (x x' + y y'))) \
= lambda ((x^2 + y^2)tr(x'^T x' + y'^T y') - 2 (x x' + y y') (x x' + y y')^T)\
= lambda ((x^2 + y^2)(x' x'^T + y' y'^T) - 2 (x x' + y y') (x x' + y y')^T)\
= lambda (-x^2 norm(x')^2 - y^2 norm(y')^2+ x^2 norm(y')^2 + y^2 norm(x')^2 - 4 x y x' y'^T)\
= 0
$
过程中分别利用了:
$
tr(x'') = tr(y'') = 0\
norm(x') = norm(y')\
x' y'^T = 0\
$
这些性质都来源于 @C-R
进而由之前的结论,存在 $v_1 (z)$ 使得 $h(z) := u_1(z) + i v_1(z)$ 是调和函数\
我们发现:
$
norm(f(z)/e^h(z)) = norm(f(z)/e^(u_1(z))) = 1
$
而上式右侧是解析函数,利用如下引理:
#lemma[][
设 $f$ 于连通区域 $G$ 上解析,且 $norm(f(z)) = 1$,则 $f(z)$ 是常数
]
#proof[
设 $f = u + v i$,则有:
$
1 = u^2 + v^2\
0 = u u' + v v'\
0 = u u'' + u'^T u' + v v'' + v'^T v'\
0 = tr(u u'' + u'^T u' + v v'' + v'^T v') = norm(u')^2 + norm(v')^2 = 0
$
因此 $f' = 0$,结合 $G$ 的连通性得到结论
]
]
#corollary[][
在上面类似的条件下,存在解析函数 $g(z)$ 使得 $(g(z))^n = f(z)$
]
#proof[
在上题给出的 $g(z)$ 中,令 $h = e^(g(z)/n)$ 即可
]
#theorem[][
设 $f$ 在区域 $Omega$ 上解析,称 $f$ 的 Jacobian 矩阵把它看成 $R^2 -> R^2$ 的函数的 Jacobian $J$,有:
$
det(J) = norm(f'(z))^2
$
]<JandD>
#proof[
几何上说,解析映射对于小的长度元是线性的,伸缩率就是 $norm(f'(z))$,对于面积元的伸缩率当然就是 $ norm(f'(z))^2$\
利用@C-R, 计算得:
$
det(J) = partialDer(u, x) partialDer(v, y) - partialDer(u, y) partialDer(v, x) = (partialDer(u, x) partialDer(u, x)) + (partialDer(u, y) partialDer(u, y)) = norm(f'(z))^2
$
]
#lemma[][
设 $C^1$ 函数 $f : R^2 -> R^2$ 的 Jacobian 矩阵为 $J$,则它对应 $CC$ 上的解析函数当且仅当:
$
J = a I + b mat(0, 1;-1, 0)
$
进一步:
$
(a I + b mat(0, 1;-1, 0))(a I - b mat(0, 1;-1, 0)) = (a^2 - b^2)I
$
表明 $a^2 != b^2 <=> J "可逆"$,并且 $J$ 可逆时它的逆也具有类似的的形式
]
#proof[
这就是@C-R
]
#theorem[反函数定理][
设 $f$ 在区域 $Omega$ 上解析,且导数连续,并有 $f'(z_0) != 0$,那么将存在 $z_0$ 的邻域 $D$,使得:
- $f(D)$ 是开集
- $f$ 在 $D$ 上是双全纯的
- $(Inv(f))' (f(z)) = 1/(f'(z))$
]<inverse-theorem>
#proof[
利用实函数的反函数定理,可以得到反函数 $Inv(f)$,且满足:
$
J_(Inv(f)) = Inv((J_f))
$
从而可以通过引理验证 $Inv(f)$ 也是解析的,进而也可以得到计算结果
]
#theorem[中值定理][
设 $f$ 是开的凸集 $Omega$ 上的解析函数,$z_1, z_2 in Omega$,则存在 $z_3 in Omega$ 使得:
$
norm((f(z_1) - f(z_2))/(z_1 - z_2)) <= norm(f'(z_3))
$
]
#proof[
本题中将复数视作列向量处理\
由于 $Omega$ 是凸的,设 $z = (1-t)z_1 + t z_2$,则 $norm(f((1-t)z_1 + t z_2)) := g(t)$ 将是 $[0, 1] -> RR$ 的连续可微函数\
事实上,设 $J$ 给出 $f$ 的 F-导数,则由链式法则:
$
g'(t) = ((f((1-t)z_1 + t z_2))^T)/(norm(f((1-t)z_1 + t z_2))) J((1-t)z_1 + t z_2) (z_2 - z_1)
$
#lemma[][
设 $A$ 是满足@C-R 的偏导矩阵,则:
$
norm(alpha^T A beta) <= sqrt(det(A)) norm(alpha) norm(beta)
$
]
#proof[
由柯西不等式,显然有:
$
norm(alpha^T A beta) <= norm(alpha) norm(A beta)
$
注意到:
$
norm(A beta) = sqrt(beta^T A^T A beta)
$
而:
$
A^T A = (a I + b mat(0, 1;-1, 0))(a I- b mat(0, 1;-1, 0)) = (a^2 + b^2)I = det(A) I
$
给出:
$
norm(alpha) norm(A beta) = norm(alpha) norm(beta) sqrt(det(A))
$
证毕
]
由引理:
$
norm(g'(t)) <= norm(((f((1-t)z_1 + t z_2))^T)/(norm(f((1-t)z_1 + t z_2)))) norm(z_2 - z_1) sqrt(det(J((1-t)z_1 + t z_2))) \
<= norm(z_2 - z_1) sqrt(det(J((1-t)z_1 + t z_2)))
$
结合实函数的中值定理与@JandD 结论成立
]
== 复函数序列,幂级数
在分析学和复分析早期,使用幂级数是一种非常重要的研究方法
#definition[][
设 $a_n in CC$,称幂级数 $sum_(n = 1)^(+infinity) a_n$
- 收敛,如果 $S_k = sum_(n = 1)^(k) a_n$ 收敛
- 绝对收敛,如果 $norm(S_k)$ 收敛
]
#proposition[][
$a_n$ 绝对收敛 $=>$ 收敛
]
#proof[
利用柯西收敛法则即可
]
#definition[][
- 称函数项级数 $sum_(i=1)^(+infinity) f_i (z)$ 一致收敛于 $f(z)$,如果 $sup{norm(f(z) - sum_(i=1)^(n) f_i (z))} -> 0$
- 若幂级数 $sum_(i=1)^(+infinity) a_n (z - z_0)^i$ 则定义收敛半径:
$
R = 1/(limsup_(n -> +infinity) norm(a_n)^(1/n)) in [0, +infinity]
$
]
#theorem[][
设 $R$ 是幂级数 $sum_(i=1)^(+infinity) a_n (z - a)^i$ 的收敛半径,则:
+ 若 $norm(z - a) < R$ 则级数绝对收敛
+ 若 $norm(z - a) > R$ 则级数发散
+ 设 $r < R$,则幂级数在 $overline(B(a, r))$ 一致收敛
同时,$R$ 也是唯一一个满足前两个性质(所有性质)的数
]
#proof[
不妨设 $a = 0$,取定 $0 < r < R$ 及 $r_0 = (r + R)/2$,由收敛半径定义,存在 $N in NN^+$ 使得:
$
forall n > N, norm(a_n)^(1/n) < 1/r_0
$
- 我们直接先证明 3, 进而 1 也是显然的\
在 $overline(B(a, r))$ 内,我们将有:
$
norm(a_n z^n) < (norm(z_n)/r_0)^n <= (r/r_0)^n
$
注意到 $r/r_0 < 1$,因此幂级数被几何级数一致控制,由 Weierstrass 判别法知一致收敛
- 对于 2,可设 $norm(z) > r > R, r_0 = (r + R)/2$,可以取得一列 $n_k$ 使得:
$
norm(a_(n_k))^(1/n) > 1/r_0
$
由于 $r_0 > R, 1/r_0 < R$\
我们发现:
$
norm(a_(n_k) z^(n_k)) > (norm(z) / r_0)^(n_k) > (r / r_0)^(n_k)
$
但上式右侧趋于无穷,显然级数发散
]
#proposition[][
给定幂级数 $sum a_n (z - a)^n$,若 $lim_(n -> infinity) norm(a_n/a_(n+1))$ 存在,则它就是 $R$
]
#definition[][
设两级数 $sum a_n, sum_ b_n$ ,定义它们的乘积为:
$
sum_(n = 0)^(+infinity) (sum_(k = 0)^(n) a_k b_(n-k))
$
]
#proposition[][
若两级数 $sum a_n, sum b_n$ 至少有一个绝对收敛,则它们的乘积也收敛,并且恰有:
$
sum_(n = 0)^(+infinity) (sum_(k = 0)^(n) a_k b_(n-k)) = sum_(n = 0)^(+infinity) a_n sum_(n = 0)^(+infinity) b_n
$
若两个都绝对收敛,则乘积也绝对收敛
]
#proof[
不妨设 $a_n$ 绝对收敛
先考虑有限和,设 $a_n, b_n$ 的前 $n$ 项和分别为 $A_n, B_n$,有:
$
sum_(n = 0)^(N) (sum_(k = 0)^(n) a_k b_(n-k)) = sum_(k = 0)^N (sum_(n=k)^N a_k b_(n - k)) = sum_(k = 0)^N a_k B_(N-k) \
= sum_(k=0)^N a_k B_N + sum_(k = 0)^N a_k (B_(N-k) - B_N)\
= A_N B_N + sum_(k = 0)^N a_k (B_(N-k) - B_N)
$
注意到上式第二项 $B_(N-k) - B_N -> 0, N -> +infinity$,结合 $a_n$ 绝对收敛知该项收敛于零
]
#remark[][
两项都不绝对收敛时,结论当然不成立。例如取
$
a_n = (-1)^n 1/(n^(1/4))\
B_n = (-1)^n 1/(n^(1/4))\
B_(N-k) = (-1)^(N - k) 1/(N - k)^(1/4) \
a_k B_(N-k) = (-1)^N 1/((N - k) k )^(1/4)
$
其中:
$
1/((N - k) k )^(1/4) >= 1/((N/2)^(1/2))\
sum_(k = 1)^(N-1) a_k B_(N - k) >= (N-1)/((N/2)^(1/2))
$
上式右侧趋于无穷,观察证明过程可得结论不成立
]
#corollary[][
设两个幂级数的收敛半径 $>= r$,则幂级数的和/积就是对应系数和/积的幂级数在 $B(a, r)$ 上都成立,且和/积的收敛半径至少为 $r$
]
#theorem[一致收敛与极限][
设 $f_n: G -> CC$ 为一列函数,若 $f_n$ 于 $z_0$ 的某个开邻域(或者去心邻域)一致收敛于 $f$,则:
$
lim_(n -> +infinity) lim_(z -> z_0) f_n (z) = lim_(z -> z_0) lim_(n -> +infinity) f_n (z)
$
]
#proof[
与实函数情景相同
]
#lemma[函数序列的导数][
设 $f_n$ 一致收敛于 $f$, $f'_n$ 一致收敛于 $g$,则 $f' = g$
]
#proof[
考虑 $z$ 处的导数,任取 $epsilon > 0$:
$
(f(z + Delta) - f(z))/Delta = (f_n (z + Delta) - f_n (z))/Delta + (f(z + Delta) - f_n (z + Delta))/Delta\
(f(z + Delta) - f(z))/Delta -g(z) = ((f_n (z + Delta) - f_n (z))/Delta - g(z)) + (f(z + Delta) - f_n (z + Delta))/Delta\
$
取极限得:
$
lim_(Delta -> 0) lim_(n->+infinity) ((f_n (z + Delta) - f_n (z))/Delta - g(z)) \
= lim_(Delta -> 0) lim_(n->+infinity) ((f_n (z + Delta) - f_n (z))/Delta - g(z)) +lim_(Delta -> 0) lim_(n->+infinity) ((f(z + Delta) - f_n (z + Delta))/Delta)
$
只需验证上式为零,而上式右侧第二项恰为零,对于第一项只要极限可交换便也为零,为此,我们希望它一致收敛,利用柯西法则计算:
$
norm((f_n (z + Delta) - f_n (z))/Delta - g(z) - ((f_m (z + Delta) - f_m (z))/Delta - g(z))) \
= norm((f_n (z + Delta) - f_n (z) - f_m (z + Delta) + f_m (z)))/norm(Delta)\
$
由中值定理,存在 $xi$ 使得:
$
norm((f_n (z + Delta) - f_n (z) - f_m (z + Delta) + f_m (z)))/norm(Delta) <= norm(f'_n (xi) - f'_m (xi)) <= sup norm(f'_n - f'_m)
$
由一致收敛性,上式右侧当 $n, m$ 足够大时趋于零,从而完成了验证
]
#theorem[][
设 $f_n$ 每项均可导,$f'_n$ 一致收敛于 $g$,且 $f_n$ 于一点处收敛,则 $f_n$ 一致收敛于 $f$,且 $f' = g$
]
#proposition[][
设 $f(z) = sum a_n (z - a)^n$,后面的幂级数收敛半径为 $R$,则:
$
f'(z) = sum n a_n (z - a)^(n-1), forall z in B(a, R)
$
且上式右侧收敛半径也为 $R$
]
#proof[
首先,$limsup_(n -> +infinity) norm(n a_n)^(1/n) = limsup_(n -> +infinity) norm(a_n)^(1/n)$ 给出它们具有相同的收敛半径\
其次,计算收敛半径幂级数和形式导数将在 $B(a, R)$ 上内闭一致收敛,由前面的命题知结论成立
]
#corollary[][
- 幂级数函数无穷阶可导
- $a_n = 1/(n!) f^(n) (a)$
]
#definition[指数函数][
定义 $e^z = sum_(i=0)^(+infinity) z^n/(n!)$\
当 $z in RR$ 时我们已经熟知,因此在复数上用相同的形式我们扩充定义
]
#corollary[][
设 $x in RR$,则:
$
e^(i x) = cos x + i sin x
$
]
#proof[
用幂级数的加法验证即可
]
== 多值函数
#definition[多值函数|multi valued function][
称一个映射 $F: s -> P(CC)$ 为多值函数 / 对应|correspondence\
若存在解析函数 $f(x): s -> CC$ 使得:
$
f(x) in F(x), forall x in s
$
则称 $f(x)$ 是 $F(x)$ 的解析分支
]
#let Log = "Log"
#definition[对数函数][
定义:
$
Log x = {z in CC: e^z = x},forall x in CC - {z | z <= 0}
$
为多值函数,显然有:
$
Log x = {x_0 + 2 k i pi | k in ZZ}, forall x_0 in Log x
$
]
#remark[][
多值函数某种意义上可以理解为无穷维复平面 $CC^infinity$ 到 $CC$ 的函数
]
== 分式线性变换
#definition[分式线性变换/莫比乌斯变换 | linear fractional transformation/Mobius Transformation][\
称 $f: CC -> CC$ 为分式线性变换,如果存在 $a, b, c, d in CC$ 使得:
$
f(z) = (a z + b)/(c z + d)
$
当 $a d - b c != 0$ 时,称之为莫比乌斯变换
]
#proposition[][
- 分式线性变换的逆映射还是分式线性变换
- 分式线性变换的复合还是分式线性变换
- 分式线性变换由三点的像唯一确定
]
= 积分
== 有界变差
#definition[][
称一个实函数 $f: [a, b] -> RR$ 是有界变差函数,如果对于任意划分 $P : x_0 = a < x_1 < x_2 <...< x_n = b$,均有:
$
v(f;P) := sum_(i=1)^(n) abs(f(x_i) - f(x_(i-1))) < M
$
其中 $M$ 是与 $P$ 无关的常数,此时记:
$
v(f) = sup_P v(f;P)
$
称一个曲线是可求长的,如果函数是有界变差函数
]
#proposition[][
分段光滑曲线是有界变差的,且:
$
v(f) = integral_a^b abs(f'(x)) dif x
$
]
#definition[积分][
设 $f$ 是连续实值函数,$gamma$ 是有界变差曲线,则存在唯一的复数 $I$ 使得对于任意 $epsilon > 0$,存在 $delta > 0$ 及分划 $P$ 满足 $norm(P) < delta$,且:
$
norm(I - sum_i f(tau_i)(gamma(t_k) - gamma(t_(k-1)))) < epsilon
$
此时,记 $I = integral_(gamma)^() f dif z$
]
#proposition[][
设 $f$ 是连续实值函数,$gamma$ 是分段光滑曲线,则:
$
integral_(gamma)^() f dif z = integral_a^b f(gamma(t)) gamma'(t) dif t
$
]
#definition[积分][
设 $f$ 是复连续函数,$gamma$ 是可求长曲线,则称:
$
integral_(gamma)^() f(gamma(t)) dif gamma(t)
$
为函数在曲线上的积分,也记作 $integral_(gamma)^() f(z) dif z$ 或 $integral_(gamma) f$
]
#definition[][
设 $abs(gamma)(t) = sup{sum_(k=1)^n abs(gamma(t_k) - gamma(t_(k-1))), t_i "is partition of "[a, t]}$,则它是单调函数,继而有界变差,记:
$
integral_(gamma)^() f abs(dif z) = integral_a^b f(gamma(t)) dif abs(gamma)(t)
$
]
#proposition[][
$
norm(integral_(gamma)^() f ) <= integral_(gamma)^() norm(f) abs(dif z) <= V(gamma) sup_{z in gamma} norm(f(z))
$
]
#theorem[Cauthy 1][
设 $G$ 是有界区域,其边界是有限多条光滑曲线。$f$ 在区域内解析,在区域的闭包上连续,则有:
$
integral_(diff G) f(z) dif z = 0
$
]
#proof[
- 首先,先放松一点条件,假设 $G$ 是三角形区域,而 $f$ 在区域的闭包上解析。\
设三角形为 $A B C$,取三边的中点 $A', B', C'$,注意到积分恰可以分到四个三角形上,也即:
$
integral_(diff G) f(z) dif z = sum_(i=1)^4 integral_(triangle.t_i) f(z) dif z
$
以三角形 $A C' B'$ 为例,注意到 $f$ 解析,有:
$
integral_(diff A C' B) f(z) dif z = integral_(diff A C' B) f(z_0) + (z-z_0) f'(z_0) + o(z- z_0) dif z\
= integral_(diff A C' B) o(z- z_0) dif z
$
这里的 $z_0$ 可以任取\
假设积分非零,不妨设为 $M > 0$,则四个三角形中总有一个积分的绝对值大于等于 $M/4$,记为 $triangle.t_1$\
接下来,再次四分并取其中一个积分大于等于 $M/16$,记为 $triangle.t_2$,如此下去,我们得到一个序列 $triangle.t_i$,使得:
$
abs(integral_(diff triangle.t_i) f(z) dif z) >= abs(M/4^i)\
integral_(diff triangle.t_i) abs(f(z)) >= M/4^i
$
另一方面,注意到:
$
integral_(diff triangle.t_i) abs(f(z)) <= integral_(diff triangle.t_i) abs(o(z- z_0)) dif z <= c(triangle.t_i) d(triangle.t_i) a_i
$
其中 $c$ 是周长,$d$ 是直径,$a_i -> 0$,有:
$
c(triangle.t_i) d(triangle.t_i) a_i = b_i 1/(4^i), b_i -> 0
$
两式结合即得 $M <= b_i => M <= 0$,矛盾!
- 下一步,对于一般的多边形,它可以进行三角剖分(证明略显复杂和初等,这里不证),对每个三角形应用之前的结论便可得证
- 对于一般的区域 $G$,我们希望对于任意 $epsilon > 0$,取得多边形区域 $D$,它的闭包含于 $G$,而:
$
abs(integral_(diff G)^() f(z) dif z - integral_(diff D) f(z) dif z) < epsilon
$
假若能取得,由引理立得结论成立。\
该命题作为 bonus question\
首先处理单个光滑曲线 $S$:
$
forall t in [0, 1]
cases(
x = u(t),
y = v(t)
)\
$
目标相当于构造相同起点的终点的分段线性曲线使得 $f$ 在两者上积分的差足够小。取分段线性曲线一致收敛于原曲线是容易的,但一致收敛不能保证曲线积分收敛(这就是楼梯悖论),因此需要更精细的估计。\
先给出如下引理:
#lemmaLinear[][
设 $T_n subset G$:
$
forall t in [0, 1]
cases(
x = x_n (t),
y = y_n (t)
)
$
是一族分段线性曲线,且有:
$
x_n arrows.rr u, y_n arrows.rr v\
x'_(n-) arrows.rr u', y'_(n-) arrows.rr v'
$
(分量左导数一致收敛于原曲线分量的导数)\
则有:
$
lim_(n -> infinity) integral_(T_n) f(z) dif z = integral_(S) f(z) dif z
$
]
#proof[
// 注意到 $u'(t)^2 + v'(t)^2 != 0$,从而将有正下界\
// 同时由一致收敛性,$x'_(n-)^2 + y'_(n-)^2$ 与 $u'(t)^2 + v'(t)^2$ 将有共同的一致正下界,不妨设为 $m'$\
由 $sqrt(x)$ 在 $[0, +infinity)$ 上的一致连续性(有限区间由连续函数一致连续给出,之后的无穷区间由导数有界给出)可以得到:
$
sqrt(x'_(n-)^2 + y'_(n-)^2) arrows.rr sqrt(u'^2 + v'^2)
$
同时由 $f$ 在有界闭集上的连续性,它也一致连续,进而:
$
f(x_n (t) + i y_n (t)) arrows.rr f(u(t) + i v(t))
$
注意到 $f(u(t) + i v(t)), sqrt(u'^2 + v'^2)$ 都是有界闭集上的连续函数,继而有界。\
由此 $f(x_n (t) + i y_n (t)), sqrt(x'_(n-)^2 + y'_(n-)^2)$ 也有公共上界,由两个一致有界,一致收敛的函数列相乘的性质可得:
$
f(x_n (t) + i y_n (t)) sqrt(x'_(n-)^2 + y'_(n-)^2) arrows.rr f(u(t) + i v(t)) sqrt(u'^2 + v'^2)
$
进而利用一致收敛性保持积分的性质:
$
lim_(n -> infinity) integral_(0)^1 f(x_n (t) + i y_n (t)) sqrt(x'_(n-)^2 + y'_(n-)^2) dif t = integral_(0)^1 f(u(t) + i v (t)) sqrt(u'^2 + v'^2) dif t
$
而:
$
integral_(0)^1 f(u(t) + i v (t)) sqrt(u'^2 + v'^2) dif t = integral_(S) f(z) dif z\
integral_(0)^1 f(x_n (t) + i y_n (t)) sqrt(x'_(n-)^2 + y'_(n-)^2) dif t = integral_(T_n) f(z) dif z
$
前项成立是定义,后项成立是仅差有限个点的积分有相等的值,得证\
(证明未完成)
]
]
#corollary[][
单连通区域上的解析函数有原函数
]
#theorem[Cauthy 2][
设 $G$ 是有界区域,其边界是有限多条光滑曲线。$f$ 在区域内解析,在区域的闭包上连续,则对任意 $z in G$,$omega$ 是任意一个将 $z$ 包括在内的简单闭曲线,有:
$
f(z) = 1/(2 pi i) integral_(diff omega) f(w)/(w - z) dif w
$
]<Cauthy-value>
#proof[
由之前的 Cauthy 定理,只需要考虑 $omega$ 是某个任意小的球形开邻域,则:
$
1/(2 pi i) integral_(diff omega) f(w)/(w - z) dif w = 1/(2 pi i) integral_(diff omega) f(z)/(w - z) + f'(z) + o(1) dif z\
= f(z) + 1/(2 pi i) integral_(diff omega) o(1) dif w\
$
注意到 $delta$ 可以任意小,因此上式右侧可以任意小,进而得证
]
#theorem[Cauthy 3][
设 $G$ 是开球 $B(a, r)$ ,$f$ 在 $G$ 上解析,则 $f$ 有级数表达:
$
f(z) = sum_(n=0)^(+infinity) a_n (z - a)^n
$
且级数的收敛半径至少为 $r$
]
#proof[
无妨设 $a = 0$ 我们有:
$
f(z) = 1/(2 pi i)integral_(diff G)^() f(w)/(w - z) dif w\
= 1/(2 pi i)integral_(diff G)^() - 1/w f(w)(sum_(k=0)^infinity (z/w)^k ) dif w\
= sum_(k=0)^infinity (1/(2 pi i)integral_(diff G)^() - 1/w f(w) 1/w^k dif w) z^k\
$
不难看出上式右侧恰为幂级数,得证
]
#corollary[][
开集上的解析函数无穷阶可导
]
= 整函数与解析函数的基本定理
== 基本定理
#definition[整函数][
称一个 $CC -> CC$ 的解析函数是整函数。等价的,它的幂级数表示的收敛半径为正无穷
]
#theorem[Liouville][
设 $f$ 是整函数,且有界,则 $f$ 是常数
]<Liouville>
#proof[
假设 $sup norm(f) = M < +infinity$,由柯西估计,有:
$
norm(f'(z)) <= M / r, forall r in CC
$
]
#corollary[代数基本定理][
设 $p(z)$ 是非常数多项式,则 $p(z)$ 有根
]
#proof[
如若不然,此时可设 $norm(p(z)) > c > 0$,
这是因为可以验证 $lim_(z -> infinity) norm(p(z)) = +infinity$,而在任何有限闭区域上,函数有最小值 $m > 0$\
则:
$
1/(p(z))
$
是整函数,并且有界 $1/c$,由 Liouville 定理知它是常数,矛盾
]
#theorem[][
设 $f: Omega -> CC$ 是解析函数,以下事实等价:
- $f= 0$
- $exists z in Omega, forall n in NN, f^((n))(z) = 0$
- $Inv(f)(0)$ 有极限点
]
#proof[
略
]
#theorem[开映射原理][
非常数的解析函数是开映射,也即将开集映成开集
]
#proof[
这个定理的证明比较复杂,留在下节
]
#theorem[最大模原理][
设 $f: Omega -> f$ 是开区域上的解析函数,并且存在 $a$ 使得:
$
norm(f(z)) <= norm(f(a)), forall z in Omega
$
则 $a$ 是常数
]
#proof[
如若不然,注意到 $f(B(a, r))$ 是开集,显然矛盾!
]
== 缠绕数,柯西积分定理
#definition[Index/winding number of a closed curve][
设 $gamma: [0, 1] -> CC$ 是一个可求长闭曲线,任取 $a in.not gamma$,则称:
$
1/(2 pi i) integral_(gamma)^() 1/(z-a) dif z
$
为曲线的缠绕数 $b(gamma, a)$
]
对于可求长曲线,这个数字描述了曲线绕着 $a$ 的次数,如果是正数,那么曲线绕着 $a$ 逆时针旋转,否则顺时针旋转。颇为神奇的是,我们有:
#proposition[][
缠绕数为一个整数
]
#proof[
不失一般性,设曲线是光滑的(否则可以取得远离 $a$ 的曲线使得积分逼近)\
定义:
$
g(t) := integral_(0)^(t) (gamma'(s))/(gamma(s) - a) dif s
$
则:
$
g'(t) = (gamma'(t))/(gamma(t) - a)\
(e^(-g)(gamma - a))' = e^(-g) gamma' - e^(-g) g'(gamma - a) = 0
$
从而 $e^(-g)(gamma - a) = e^(-g(0))(gamma(0) - a) = gamma(0) - a = e^(-g(1))(gamma(1) - a)$
注意到 $gamma(0) = gamma(1) != a$,故 $g(1) = 2 k pi i, k in ZZ$\
这就给出了:
$
1/(2 pi i) integral_(gamma)^() 1/(z-a) dif z = 1/(2 pi i) g(1) = k in ZZ
$
]
#example[][
- 由柯西积分定理,简单闭曲线对于内部点的缠绕数当然就是 $1$
]
#proposition[][
- $n(gamma, a) = -n(-gamma, a)$
- $n(gamma + sigma, a) = n(gamma, a) + n(sigma, a)$
- 在 $gamma$ 产生的每个连通分支上,缠绕数是常数
- 在 $gamma$ 唯一一个非有界连通分支上,缠绕数为 $0$
]
#proof[
- 积分的定义
- 同样利用定义
- 注意到积分是连续函数,而值域是离散的,因此只能在每个连通分支上是常数
- 首先说明非有界连通分支唯一。由于 $gamma$ 是紧集上的连续函数,当然有界 $M$ 。无界连通分支当然有 $M$ 之外的点,因此只能是唯一一个。\
其次,$a$ 充分大时积分当然趋于零,而在该连通分支上享有相同的值,因此只能是零
]
#lemma[][
设 $gamma$ 是可求长曲线,$phi: gamma -> CC$ 连续,$m in NN$,则:
$
F_m (z) = 1/(2 pi i) integral_(gamma)^() phi(w)/(w - z)^m dif w, forall z in CC -gamma
$
是解析函数,且:
$
F'_m (z) = m F_(m+1) (z)
$
]<lemma-der>
#proof[
- 由积分的性质知道它是连续函数,固定 $z, a in CC - gamma$,计算:
$
1/(w-z)^m - 1/(w - a)^m = (1/(w-z) - 1/(w-a))(sum_(k=0)^(m-1) 1/(w-z)^k 1/(w-a)^(m-1-k))\
= (z-a) sum_(k=0)^(m-1) 1/(w-z)^(k+1) 1/(w-a)^(m-k)
$
- 则:
$
(F_m (z) - F_m (a))/(z-a) = 1/(2 pi i) integral_(gamma)^() phi(w) sum_(k=0)^(m-1) 1/(w-z)^(k+1) 1/(w-a)^(m-k) dif w\
$
令 $z -> a$,上式右侧当然趋于(这里一致性可以保证):
$
1/(2 pi i) integral_(gamma)^() phi(w) sum_(k=0)^(m-1) 1/(w-a)^(m+1) dif w\
= m F_(m+1) (a)
$
]
#theorem[Cauthy Integral formula 1][
设 $G subset CC$ 是开集,$f: G -> CC$ 解析,$gamma subset G$ 可求长并且:
$
n(gamma, w) = 0, forall w in CC - G
$
则对于任意 $a in G - gamma$,有:
$
n(gamma, a) f(a) = 1/(2 pi i) integral_(gamma)^() f(w)/(w - a) dif w
$
]
#proof[
定义:
$
funcDef(phi, G times G, CC, (z, w) , cases(
(f(w) - f(z))/(w - z) "if" w != z,
f'(z) "if" w = z
))
$
断言 $phi$ 是连续函数,且任给 $z$,$phi(z)$ 是解析函数\
再定义:
$
funcDef(g, CC, CC, z, cases(
integral_(gamma)^() phi(z, w) dif w "if" z in G,
integral_(gamma)^() f(w)/(w - z) dif w "if" n(gamma, z) = 0
))
$
为了证明它是良定义的,取 $z in G$ 使得 $n(gamma, w) = 0$,此时:
$
integral_(gamma)^() (f(w) - f(z))/(w - z) dif w = integral_(gamma)^() f(w)/(w-z) dif w - 2 pi i f(z) n(gamma, w) = integral_(gamma)^() f(w)/(w-z) dif w
$
可以验证 $g$ 是解析的,然而有界并在 $z$ 充分大时趋于零,因此就是 $0$\
换言之:
$
0 = integral_(gamma)^() (f(w) - f(z))/(w - z) dif w = integral_(gamma)^() f(w)/(w-z) dif w - 2 pi i f(z) n(gamma, w)
$
]
#theorem[Cauthy Integral formula 2][
设 $G subset CC$ 是开集,$f: G -> CC$ 解析,$gamma_i subset G$ 可求长并且:
$
sum_i n(gamma_i, w) = 0, forall w in CC - G
$
则对于任意 $a in G - union_i gamma$,有:
$
sum_k n(gamma_k, a) f(a) = sum_k 1/(2 pi i) integral_(gamma_k)^() f(w)/(w - a) dif w
$
]
#theorem[Cauthy theorem 1][
设 $G, f, gamma_i$ 条件同上,则:
$
sum_k integral_(gamma)^() f dif z = 0
$
]
#proof[
任取 $a$,对 $f(z) (z-a)$ 利用积分公式 2 即可
]
#theorem[][
设 $G, f, gamma_i$ 条件同上,则对于任意 $a in G - union_i gamma$,有:
$
sum_k n(gamma_k, w) f^(k)(a) = k! sum_k 1/(2 pi i) integral_(gamma_k)^() f(w)/(w - a)^(k+1) dif w
$
]
#proof[
由 @lemma-der,上式右侧就是 $F_(k+1) (a)$,归纳即可
]
#definition[zero][
设 $G$ 是开集,$f: G -> CC$ 解析,将 $f$ 在 $G$ 内的零点带重数排成 $x_1, x_2, ..., x_n$,称为零点集。
]
#proposition[][
设 $x_i$ 是所有零点,若闭的可求长曲线 $gamma$ 满足:
$
forall z in CC - G, n(gamma, z) = 0\
forall i, x_i in.not gamma
$
则有积分公式:
$
1/(2 pi i) integral_(gamma)^() (f'(w))/f(w) dif w = sum_k n(gamma, x_k)
$
]
#proof[
可设:
$
f(z) = (product_i (z - x_i)) g(z)
$
则 $g(z)$ 解析且非零。将有:
$
1/(2 pi i) integral_(gamma)^() (f'(w))/f(w) dif w\
= 1/(2 pi i) integral_(gamma)^() sum_k 1/(z - x_k) + (g'(z))/g(z) dif w
$
利用柯西定理即得
]
#corollary[][
设 $x_i$ 是 $f(x) = lambda$ 在 $G$ 上的带重数零点,则:
$
1/(2 pi i) integral_(gamma)^() (f'(w))/(f(omega) - lambda)dif w = sum_k n(gamma, x_k)
$
]
#proof[
对 $f(x) - lambda$ 利用上面的命题即可
]
#theorem[][
设 $f: B(a, R) -> CC$ 解析,$alpha = f(a),$若 $f(x) - f(a)$ 有 $m >= 1$ 重零点,则存在 $alpha$ 的开邻域 $B_alpha$ 和 $a$ 的开邻域 $B_a$,使得:
$
forall beta in B, f(z) - beta 在 B_a "上恰有" m "个简单零点(重数为 1 的零点)"
$
]
#proof[
先取 $epsilon_1 in B(z, 1/2 R)$,满足:
$
forall z in B(a, 2 epsilon_1) - {a}, f(z) != alpha and f'(z) != 0
$
这样的 $epsilon$ 存在是因为注意到 $Inv(f)(0)$ 在 $G$ 内是离散的,$Inv(f')(0)$ 也是,从而 $a$ 不是两者的聚点,当然有去心邻域与两者不交
定义:
$
gamma(t) = a + epsilon e^(2 pi i t), t in [0, 1]\
sigma(t) = f(gamma(t))
$
注意到 $alpha in.not sigma$,故存在 $alpha$ 的开邻域 $B_alpha$ 与 $gamma$ 不交,这个邻域当然属于 $sigma$ 分割出的同一个连通分支,进而缠绕数是常数。事实上,有:
$
n(sigma, alpha) = n(sigma, beta)
$
然而:
$
n(sigma, alpha) &= integral_(f compose gamma)^() 1/(z - alpha) dif z \
&= 1/(2 pi i) integral_(gamma)^() 1/(f(z) - alpha) f'(z) dif z\
&= m
$
取 $G = B(a, 2 epsilon)$,应用之前的定理得:
$
n(sigma, beta) = sum_(k=1)^p n(gamma, z_k) = m
$
$z_k$ 是 $f(z) - beta$ 在 $G$ 中的所有零点,注意到这里 $n(gamma, z_k)$ 只能为 $0, 1$(既然 $epsilon$ 的取法保证了导数非零,进而没有重根。\
同时,观察曲线的取法可得 $gamma subset B(a, epsilon)$,因此所有 $z_k in B(a, 2 epsilon) - B(a, epsilon)$ 对应的缠绕数都是零,由上面的等式看出 $B(a, epsilon)$ 上恰有 $m$ 个一重零点,证毕
]
终于可以回到开映射定理的证明:
#corollary[开映射原理][]
#proof[
任取 $a, alpha = f(a)$,由上面的定理,存在 $B_a, B_alpha$ 使得:
$
B_alpha subset f(B_a)
$
因此 $f$ 将内点映成内点,进而是开映射
]
上面的定理还给出了如下有用的推论
#corollary[][
设 $f$ 是 $omega -> omega'$ 的满的单叶解析函数,则 $f' != 0$,且 $f$ 有解析的逆映射,满足:
$
(Inv(f))'(f(z)) = 1/(f'(z))
$
]<univalent-is-homeomorphism>
#proof[
- 先证明导数非零,假设 $f'(a) = 0$,则 $f(z) - f(a)$ 有二重零点,由上面的定理知道存在 $beta$,$f - beta$ 至少有两个零点,矛盾!
- 既然是双射,当然有逆映射。注意到 $f$ 是开映射,因此逆映射当然也连续。
]
== 其他常用定理
#theorem[Weierstrass][
设 $f$ 是非常值的整函数,则有:
$
overline(f(CC)) = CC
$
]
#proof[
如若不然,存在 $z in CC$ 使得 $norm(f(x) - z) > epsilon$,此时:
$
1/(f(x) - z), forall x in CC
$
成为有界的整函数,继而是常数,矛盾!
]
#theorem[<NAME>][
设整函数 $f$ 不是多项式,则称之为 transcendental entire function|超越整函数。对于超越整函数,它的像集至多比 $CC$ 少一个点
]
#proof[
有时间的话稍后进行证明
]
#theorem[Mean Value theorem|平均值定理][
\
设 $f: Omega -> CC$,$forall z in Omega, r > 0 with overline(B(z, r)) subset Omega$,有:
$
f(z) = 1/(2 pi) integral_(0)^(2 pi) f(z + r e^(i theta)) dif theta\
norm(f(z)) <= 1/(2 pi) integral_(0)^(2 pi) norm(f(z + r e^(i theta))) dif theta
$
换言之,$f(z)$ 就是周围值的平均值\
更进一步,还有:
$
norm(f(z)) <= 1/(pi r^2) integral_(B(z, r))^() norm(f(z)) dif z
$
(实平面上的二重积分)
]<integral-mean>
#proof[
由柯西积分:
$
f(z)
&= 1/(2 pi i) integral_(diff B(z, r))^() f(w)/(w - z) dif w \
&= 1/(2 pi i) integral_(0)^(2pi) f(z + r e^(i theta))/(r e^(i theta)) dif (z + r e^(i theta))\
&= 1/(2 pi) integral_(0)^(2pi) f(z + r e^(i theta)) dif theta
$
]
== 与几何与分析有关的定理
#lemma[Schwarz][
设 $f: B(0, 1) -> B(0, 1)$ 解析,且 $f(0) = 0$,则:
- $forall z in B(0, 1), norm(f(z)) <= norm(z), norm(f'(0)) <=1$
- 以下事实等价:
- 存在 $z_0 != 0$,使得 $norm(f(z_0)) = norm(z_0)$
- $f'(0) = 1$
- 存在 $theta$ 使得 $f(z) = z e^(i theta)$
]<Schwarz>
#proof[
- 对它做级数展开得到:
$
f(z)/z = sum a_i z^i
$
若它是常数已经证毕,否则根据最大模原理,$forall 0 < r < 1$ 它的模在 $B(0, r)$ 上不能取最大值,在 $overline(B(0, r))$ 上的最大值只能在边界处取得,继而:
$
norm(f(z)/z) <= norm(f(z_r)/r) <= 1/r , forall z in B(0, r)
$
令 $r -> 1$ 即得第一条。特别的,$f'(0) = a_0$ 满足 $norm(f'(0)) <= 1$
- 直接利用最大模原理即可
]
#lemma[][
设 $g$ 是 $B(0, 1)$ 上的双全纯映射,则:
$
g(z) = e^(i theta) (z - z_0)/(1 - overline(z_0) z)
$
其中 $z_0$ 是 $B(0, 1)$ 上的一个点
]
#proof[
设 $l_(z_0) (z) = e^(i theta) (z - z_0)/(1 - overline(z_0) z_)$,可以检查 $l_(z_0) compose l_(-z_0) = 0$,进而双全纯\
令 $l = l_(g(0)), l(g(0)) = 0$\
令 $f = l(g(z))$,则:
$
f(0) = 0
$
利用之前的 Schwarz,将有:
$
norm(f'(0)) <= 1\
norm(f^(-1)(0)) <= 1
$
从而取等,进而 $f$ 是旋转,倒回即可
]
#lemma[Schwarz(更强的版本)][
设 $f: B(0, 1) -> B(0, 1)$ 解析,则:
$
norm(f(z_1) - f(z_2))/norm(1-overline(f(z_1)) f(z_2)) <= norm(z_1 - z_2)/(norm(1 - overline(z_1) z_2))
$
取等当且仅当双全纯
]
#corollary[][
令 $z_1 -> z_2 -> z$,得:
$
norm(f'(z))/(1 - norm(f(z))^2) <= 1/(1 - norm(z)^2)
$
]
#definition[庞加莱圆盘][
在圆盘 $B(0, 1)$ 上定义长度微元:
$
dif s = (norm(dif z))/(1 - norm(z)^2)
$
]
== 双曲几何
设 $g$ 是 $B(0, 1)$ 上的双全纯映射,则:
$
g(z) = e^(i theta) (z - z_0)/(1 - overline(z_0) z)
$
其中 $z_0$ 是 $B(0, 1)$ 上的一个点
设 $l_(z_0) (z) = e^(i theta) (z - z_0)/(1 - overline(z_0) z_)$,可以检查 $l_(z_0) compose l_(-z_0) = 0$,进而双全纯\
令 $l = l_(g(0)), l(g(0)) = 0$\
令 $f = l(g(z))$,则:
$
f(0) = 0
$
利用之前的 Schwarz,将有:
$
norm(f'(0)) <= 1\
norm(f^(-1)(0)) <= 1
$
从而取等,进而 $f$ 是旋转,倒回即可
Schwarz(更强的版本):
设 $f: B(0, 1) -> B(0, 1)$ 解析,则:
$
norm(f(z_1) - f(z_2))/norm(1-overline(f(z_1)) f(z_2)) <= norm(z_1 - z_2)/(norm(1 - overline(z_1) z_2))
$
推论:令 $z_1 -> z_2 -> z$,得:
$
norm(f'(z))/(1 - norm(f(z))^2) <= 1/(1 - norm(z)^2)
$
在给定长度微元下,两点间最短的曲线称为测地线,两点的距离定为测地线的长度。可以证明测地线是唯一的,且过原点的直径都是测地线。
显然,上面的引理表示了任何解析函数将曲线映成更短的曲线
= 奇点
== 奇点(Singularity)
#definition[][
$z$ 是函数的孤立奇点,如果$f$ 在某个去心邻域上有定义并解析,但在任何一个邻域上无定义或者不解析。本门课程中我们所说的奇点都是孤立奇点
- 称 $z$ 是可去的|removable,如果存在某个邻域上的解析函数 $g$ 使得 $f$ 是它的限制
例:$0$ 是 $1/z, e^(1/z), z / (sin z)$ 的孤立奇点,但其中只对 $z / (sin z)$ 是可去奇点
- 称 $z$ 是极点|pole,如果 $lim_(z - > a) f(a) = infinity$
- 如果都不是,则称 $a$ 是本性奇点|essential singularity
]
#theorem[Morera][
设 $f: G -> CC$ 连续,$G$ 是区域。若 $f$ 在任何三角形边界上的积分为零,则它是解析的
]<Morera>
#proof[
不妨假设 $G$ 是开圆盘,圆心为 $a$ 。为了证明它是解析的,我们试图找到一个解析的原函数。定义:
$
F(z) := integral_(a -> z) f dif z
$
注意到任取 $z_0$,由条件一定有:
$
integral_(a -> z) f dif z = integral_(a -> z_0) f dif z
+ integral_(z_0 -> z) f dif z
$
表明 $F(z) - F(z_0) = integral_(z_0 -> z) f dif z$,继而:
$
norm((F(z) - F(z_0))/(z - z_0) - f(z_0))\
= 1/norm(z - z_0) norm(integral_(z_0 -> z) (f(z) - f(z_0)) dif z)\
<= sup(norm(f(z) - f(z_0)))
$
当然趋于零,得证
]
#theorem[][$a$ 是可去奇点当且仅当 $lim_(z -> a) (z-a)f(z) = 0$]
#proof[一方面是容易的,另一方面,令:
$
g(z) = (z-a)f(z)
$
容易验证 $g$ 是连续函数\
#lemmaLinear[][
$g(z)$ 在 $a$ 处解析
]
#proof[我们希望利用 Morera,设某个去心邻域上 $f$ 解析,进而 $g$ 解析。任取三角形
- 若 $a$ 在三角形外部,利用柯西定理即可
- 否则,可能在边上或者角上,而边的情况可以通过分割化成角的情形,角的情形可以用外部梯形逼近。这个逼近成立利用了 $g$ 在 $a$ 的某个邻域内有界,而三角形的边长任意小]
由引理及 $g(z)$ 解析性,可设:
$
g(z) = h(z) (z - a)
$
从而 $z != a$ 时都有 $h = f$,$h$ 就是我们找的函数]
#theorem[][若 $a$ 是极点,则存在 $n in NN, g$ 解析,使得:
$
f(z) = g(z)/(z - a)^n, space forall z in G - {a}
$
$G$ 是某个开邻域使得 $f$ 在其中除了 $a$ 点处外都解析]<pole>
#proof[选取某个开邻域使得 $f != 0$,令 $h = 1/(f(z))$,$a$ 成为可去奇点,将其去掉后找零点的阶,有:
$
h = (z-a)^n g\
f(z) = 1/(z-a)^n 1/g
$
在开邻域之外,$(z-a)^n f$ 有自然的定义,它们当然是一致的]
#definition[][使得上面的式子成立的最小的 $n$ 称为极点的阶|order of pole]
接下来,我们可以考虑双向无穷的序列/级数
#definition[][称 ${z_n}_(n in ZZ)$ 是双向的序列,称:
$
sum_(n=-infinity)^(+infinity) z_n
$
收敛/绝对收敛,如果:
$
sum_(n=0)^(+infinity) z_n\
sum_(n=-1)^(-infinity) z_n
$
收敛/绝对收敛,并定义级数的值就是上面两式的和
对于函数序列,类似定义收敛/绝对收敛/一致收敛]
#theorem[Laurent 级数][设 $0 <= R_1 < R_2 <= +infinity$,定义:
$
"ann"(a, R_1, R_2) = B(a, R_2) - B(a, R_1)
$
若 $f$ 在上面的区域内解析,则它有级数表达:
$
f(z) = sum_(n=-infinity)^(+infinity) a_n (z-a)^n
$
并且上式右侧在该区域内闭绝对一致收敛,且其系数是唯一的,有:
$
a_n = 1/(2 pi i) integral_gamma (f(z))/(z-a)^(n+1) dif z
$
其中 $gamma$ 是任意在圆弧区域内部的圆]
#proof[
首先要证明 $a_n$ 是良定义的,事实上由柯西定理立得积分值应与曲线的具体选取无关。\
任取 $z_0 in "ann"(a, R_1, R_2)$, 不妨取 $gamma_1, gamma_2$ 是两个圆弧,$gamma_2$ 更大并将 $z_0$ 夹在其中,由柯西积分定理有:
$
(n(-gamma_1, z_0) + n(gamma_2, z_0)) f(z_0) = 1/(2 pi i) integral_(gamma_2) f(w)/(w - z_0) dif w + 1/(2 pi i) integral_(-gamma_1) f(w)/(w - z_0) dif w\
f(z_0) = 1/(2 pi i) integral_(gamma_2) f(w)/(w - z_0) dif w - 1/(2 pi i) integral_(gamma_1) f(w)/(w - z_0) dif w
$
注意到 $1/(2 pi i) integral_(gamma_2) f(w)/(w - z) dif w, 1/(2 pi i) integral_(gamma_1) f(w)/(w - z) dif w$ 由 @lemma-der 在不在曲线上的所有点处解析,令:
$
f_2 (z) = 1/(2 pi i) integral_(gamma_2) f(w)/(w - z) dif w\
f_1 (z) = 1/(2 pi i) integral_(gamma_1) f(w)/(w - z) dif w
$
$z_0$ 分别落在 $f_1 (z)$ 的 $gamma_1$ 之外的连通分支,$f_2 (z)$ 的 $gamma_2$ 之内的连通分支,我们的目标是各自做幂级数展开\
- 对于 $gamma_2$,做直接的展开就有:
$
f_2 (z) = sum_(n = 0)^(+infinity) b_n (z - a)^n\
where b_n = 1/n! f_2^(n)(a) = 1/(2 pi i) integral_(gamma) f(w)/(w - a)^(n+1) dif w
$
- 对于 $gamma_1$,我们希望先取倒数再做展开。具体来说,令:
$
h(z) = f_1 (a + 1/z)
$
断言 $0$ 是 $h(z)$ 的可去零点,这是因为观察 $f_1 (z)$ 的定义式即可看出 $z$ 充分大时 $f_1(z) -> 0$,
故可将其在 $0$ 附近展开,将有:
$
h(z) = sum_(n = 1)^(+infinity) c_n z^n\
where c_n = 1/(2 pi i) integral_(1/(gamma- a)) h(w)/w^(n+1) dif w\
=^(w = 1/(u - a)) 1/(2 pi i) integral_(gamma) f_1(u) (u - a)^(n+1) dif u\
= 1/(2 pi i) integral_(gamma) f(w) (w - a)^(n+1) dif w - 1/(2 pi i) integral_(gamma) f_2(w) (w - a)^(n+1) dif w
$
反解得:
$
f_1 (z) = sum_(n = 0)^(+infinity) c_n (1/(z - a))^n\
$
最后只需证明 $integral_(gamma) f_2(w) (w - a)^(n+1) dif w = 0$ 即可,既然 $f_2(w) (w - a)^(n+1)$ 在整个 $gamma$ 内部都是解析的,由柯西定理这个积分当然为零
两式求和即得 $f(z)$ 的一个展开式,反推也可得到唯一性
]
#corollary[][
设 $a$ 是孤立奇点,设 $f(z) = sum_(n = - infinity)^(+infinity) a_n (z - a)^n$,则
- 以下事实等价:
+ $a$ 是可去奇点
+ $lim_(z -> a) f(z)$ 存在
+ $f(z)$ 在某个 $B(a, epsilon)$ 上有界
+ $a_n = 0, forall n <= -1$
- $a$ 是 $m$ 阶极点当且仅当 $forall n <= -(m+1), a_n = 0$
- $a$ 是本质零点,如果有无穷多个 $n <0, a_n != 0$
]<singularity>
#proof[
- $3 => 4$:\
由 @integral-mean,注意到:
$
norm(a_n) <= 1/(2 pi) integral_(norm(z - a) < epsilon) norm(f(z))/(norm(z - a))^(n+1) dif s <= M epsilon^n
$
令 $epsilon -> 0$ 即得 $a_n = 0, forall n <= -1$\
$4 => 1$:\
显然级数在整个 $B(a, epsilon)$ 上由定义且解析,这个级数当然就是可去奇点定义中的延拓\
其他方向是显然的。
- $a$ 是 $m$ 阶零点当且仅当 $(z-a)^m f(z)$ 中 $a$ 成为可去零点,因此结论成立
- 由前两者可得
]
#theorem[][
设 $a$ 是 $f$ 的孤立本性奇点,则对任意 $epsilon > 0$,只要 $f$ 在 $B(a, epsilon) - {a}$ 解析,都有 $f(B(a, epsilon) - {a})$ 在 $CC$ 中稠密
]<C-W>
#proof[
如若不然,设 $b in CC$ 不是 $Inv(f)(B(a, epsilon))$ 的极限点,继而存在邻域 $B'$ 与 $B$ 不交\
观察:
$
1/(f(z) - b)
$
它将解析并且有上界(当然 $a$ 仍是它的奇点),由 @singularity 得 $a$ 将是它的可去奇点\
但是反过来计算得:
$
f(z) = 1/(g(z)) + b
$
不难发现 $a$ 要么是 $f$ 的可去奇点,要么是极点,矛盾!
]
#theorem[Picard 大定理][
设 $a$ 是 $f$ 的孤立本性奇点,则对任意 $epsilon > 0$,只要 $f$ 在 $B(a, epsilon) - {a}$ 解析,都有 $CC - f(B(a, epsilon) - {a})$ 中至多只有一个点
]
#proof[
它的证明颇为复杂,这里不证明
]
== 无穷远点
#definition[][
称 $infinity$ 是 $f$ 的孤立奇点,如果存在 $f$ 在充分大的无穷区域上解析,此时设 $f(z) = sum_(n = - infinity)^(+infinity) a_n (z - a)^n$
- 若 $forall n >= 1, a_n = 0$,则称 $infinity$ 为可去奇点
- 若仅有有限多个 $n>0$ 使得 $a_n != 0$,则称 $infinity$ 为极点
- 若有无穷多个 $n>0$ 使得 $a_n != 0$,则称 $infinity$ 为本性奇点
]
对于无穷远点,上面的定理都类似成立
#theorem[整双全纯函数的刻画][
设 $f: CC-> CC$ 是双全纯的,则存在 $a, b in CC$ 使得:
$
f(z) = a z + b
$
]
#proof[
线性函数当然双全纯。反之可以发现,$infinity$ 成为孤立奇点,考虑:
- 如果可去,将有 $f$ 在整个平面上有界,由 @Liouville 可得它是常数,这是荒谬的
- 如果是本性零点,由 @C-W 可得 $f(CC - overline(B(0, A)))$ 稠密,然而 $overline(f(B(0, A)))$ 是含有内部点的非空闭集,这是荒谬的
- 因此一定是极点。然而观察到 $f$ 在 $0$ 处的泰勒级数和在 $infinity$ 处的 Laurent 级数形式上应该一致,因此可得泰勒级数仅有有限项非零,换言之将有 $f$ 是多项式
最后,由代数基本定理知多项式是单射当且仅当多项式是一次多项式,证毕
]
== 亚纯函数|Meromorphic functions
#definition[亚纯函数][
设 $Omega$ 是区域(可能含有 $infinity$),若 $f: Omega -> CC$ 除了若干极点外都解析,则称 $f$ 为亚纯函数\
有时,也将 $f$ 在极点处的像定义为正无穷,此时也称 $f: Omega -> CC union {infinity}$ 在黎曼面 $CC union {infinity}$ 上解析。
一般的,称符合上面条件且不恒为 $infinity$ 的函数为 $Omega -> CC union {infinity}$ 的解析函数
]
#proposition[][
亚纯函数构成域,其零元是零函数,其余元素均可逆
]
#theorem[][
设 $f, g$ 是 $Omega$ 上的亚纯函数,若存在集合 $S$ 使得:
- $f|_S = g|_S$
- $S$ 在 $Omega$ 上有聚点
则 $f = g$
]
#proof[
设 $S$ 有聚点 $x$,考虑 $h = f -g$\
显然 $h(x) = 0$,由连续性知存在一个邻域使得其中没有 $h$ 的奇点,$h$ 成为一般的解析函数,而这样的函数零点集有聚点除非恒零,故 $h = 0$,由 $Omega$ 的连通性知结论成立
]
#theorem[][
亚纯函数 $f: Omega -> C union infinity$ 在 $Omega$ 内部的紧集上仅有有限多个奇点
]
#proof[
如果有无穷多个奇点,则将有聚点。由连续性极点的聚点还是极点,这与极点的孤立性矛盾!
]
#theorem[Mitting-Leffler][
设有离散的点列 $z_i -> infinity$ 以及 $m_n in NN, forall n in NN$,令:
$
L_n (z) = (a_(n, 1))/(z-z_n) + (a_(n, 2))/(z-z_n)^2 + ... + (a_(n, m_n))/(z-z_n)^(m_n)
$
则存在 $f$ 使得在任意一个 $z_n$ 处的 Laurent 展开的负项恰为 $L_n (z)$,且这样的 $f$ 在差一个解析函数的意义下唯一
]
#proof[
我们不证明
]
#theorem[][
黎曼球面 $hat(CC)$ 上的亚纯函数就是有理函数 $(P(z))/(Q(z))$
]
#proof[
不妨设 $z_1, z_2, ..., z_n, infinity$ 是所有极点,令:
$
L_k (z) = (a_(k, 1))/(z-z_k) + (a_(k, 2))/(z-z_k)^2 + ... + (a_(k, m_k))/(z-z_k)^(m_k)\
L_infinity (z) = b_1 + b_2 z + ... + b_n z^n + ...
$
是在所有极点处的 Laurent 展开\
则 $f - sum_k L_k - L_infinity$ 就是 $hat(CC) -> CC$ 解析函数,然而 $hat(CC)$ 是紧集,函数的模将有最大值,由 @Liouville 可得函数是常数\
由此,计算得 $f$ 当然就是有理函数
]
#corollary[][
双全纯函数 $f: hat(CC) -> hat(CC)$ 一定是莫比乌斯变换
]
#proof[
莫比乌斯变换当然是双全纯的。而假设 $f$ 是双全纯的,由上面的定理 $f$ 一定是有理函数。另一方面,$f$ 只能有唯一的零点和极点,自然分母分子都只能至多一次,意味着 $f$ 就是分式线性的。\
另一方面,显然 $f$ 不恒为常数,当然不能是退化的情形
]
#theorem[Cousin question][
设有离散的点列 $z_i -> infinity$ 以及 $m_n in NN, forall n in NN$,令 $m_n$ 是一列整数,则存在解析函数 $f: CC -> CC$ 使得恰以 $z_i$ 为 $m_i$ 阶零点
]
#proof[
同样的证明过于繁琐我们不证明
]
#corollary[][
设 $f: CC -> CC$ 是亚纯函数,则存在解析函数 $g, h : CC -> CC$ 使得 $f = g/h$
]
#proof[
设 $f$ 的极点为 ${z_n}_(n in A)$ 以及各自的阶 ${m_n}_(n in A)$,易知 $A$ 一定可数。\
由上面的定理,存在解析函数 $h$ 使得恰以 $z_n$ 为 $m_n$ 阶零点,由 @pole 一定有 $f h$ 没有任何极点也即解析,证毕
]
== 留数
#let Res = math.op("Res")
#definition[留数|residue][
设 $a$ 是 $f$ 的孤立零点,其 Laurent 展开为:
$
sum_(n = -infinity)^(+infinity) a_n (z-a)^n
$
则称 $f$ 于 $a$ 处的留数为
$
Res(f, a) := a_(-1) = 1/(2 pi i) integral_(partial B(0, epsilon)) f(z) dif z
$
其中 $epsilon$ 任意充分小
类似的,称 $f$ 在无穷远处的留数为:
$
Res(f, infinity) := - 1/(2 pi i) integral_(partial B(0, X)) f dif z
$
其中 $X$ 充分大
]
#theorem[][
设 $f$ 在区域 $Omega subset hat(CC)$ 上除去有限个孤立奇点 $a_1, ..., a_n$ 上解析,设 $gamma_i$ 是有限条 $Omega$ 上的可求长曲线,且对任意 $z in CC - Omega$ 均有:
$
sum_i n(gamma_i, z) = 0
$
且 $gamma_i$ 不经过任意一个奇点 $a_k$,则:
$
sum_j 1/(2 pi i) integral_gamma_j f dif z = sum_(k)(sum_j n(gamma_j, a_k)) Res(f, a_k)
$
]<residue>
#proof[
#let tg = $tilde(gamma)$
证明颇为复杂,我们需要分情况讨论:
+ 假设 $infinity$ 不是奇点,令:
$
tg_k (t) = a_k + r_k e^(-2 pi i t sum_j n(gamma_j, a_k)), t in [0, 1]
$
其中 $r_k$ 足够小\
检验:
$
sum_j n(gamma_j, z) + sum_k n(tg_k, z) = 0, forall z in CC - (Omega - union_k B(a_k, r_k))
$
因此可以使用柯西定理得:
$
sum_j 1/(2 pi i) integral_(gamma_j) f dif z = - sum_k 1/(2 pi i) integral_(tg_k) f dif z
$
这里的柯西定理是在 $G$ 中除去每个奇点附近的小邻域中使用的\
同时,不难计算得到:
$
1/(2pi i) integral_tg_k f dif z = - sum_j n(gamma_j, a_k) Res(f, a_k)
$
代入上式即得定理
+ 若 $infinity$ 是奇点,证明是类似的
]
#corollary[][
设 $z_k$ 是 $f: CC -> CC$ 的有限多个奇点,且 $infinity$ 也是奇点,将有:
$
sum_k Res(f, z_k) + Res(f, infinity) = 0
$
]
#proof[
在 @residue 中取曲线族为空集,区域为 $hat(CC)$ 即可
]
#proposition[][
设 $a$ 是 $f$ 的 $m$ 阶极点,且 $g(z) = (z-a)^m f(z)$,则 $Res(f, a) = 1/((m-1)!) g^((m-1)) (a)$
]
#proof[
写下 Laurent 级数并计算即可
]
#example[][
留数在实际计算中非常有效,试举几例:
- $integral_0^(+infinity) (sin x)/x = pi/2$\
令 $f(z) = e^(i z)/z$,则被积函数是它的虚部。此外,$f$ 仅在 $0$ 处有一个奇点\
取 $0 < r < R$ 并考虑轨迹 $-R -> -r ->^(circle) r -> R ->^(circle) -R$,可以利用柯西定理有:
$
integral_(- R -> -r + r -> R) f dif z + integral_(-r ->^(circle) r + R ->^(circle) -R) f dif z\
= (integral_(-R)^(-r) + integral_r^R) (cos x + i sin x)/x dif z + integral_(-r ->^(circle) r + R ->^(circle) -R) f dif z\
= 2 i integral_r^R (sin x)/x dif z + integral_(-r ->^(circle) r + R ->^(circle) -R) f dif z\
$
此外:
- $
integral_(-r ->^(circle) r) e^(i z)/z dif z = integral_(-pi)^0 e^(i r e^(i theta))/(r e^(i theta)) i r e^(i theta) dif theta\
= i integral_(-pi)^0 e^(i r e^(i theta)) dif theta
$
当 $r -> 0$ 时被积函数 $-> 1$,因此上式 $-> - i pi$
- $
integral_(R ->^(circle) -R) e^(i z)/z dif z\
= integral_(0)^pi e^(i R e^(i theta)) dif theta\
$<int1>
#lemmaLinear[][
设 $norm(f(z)) <= 1, forall z in gamma$ 且仅在有限个点上取等,则:
$
lim_(R -> +infinity) integral_gamma norm(f(z))^R dif z = 0
$
]
#proof[
令:
$
f_n (z) = f(z) + epsilon_n
$
其中 $epsilon_n -> 0$ 足够小使得 $norm(f_n) < 1$,由于 $norm(f(z)) = 1$ 的点仅有有限个,这是可以实现的\
不难验证 $f_n (x)$ 一致收敛于 $f(x)$ 且对每个 $f_n$ ,$norm(f_n (gamma))$ 有正上界 $M_n < 1$(注意到连续函数于紧集上有最大值),由此:
$
norm(integral_gamma f(z)^R dif z) <= integral_gamma norm(f(z))^R dif z <= integral_gamma M^R dif z
$
因此:
$
lim_(R -> +infinity) integral_gamma norm(f_n (z))^R dif z &= 0\
lim_(R -> +infinity) integral_gamma norm(f (z))^R dif z &= lim_(R -> +infinity) lim_(n->+infinity) integral_gamma norm(f_n (z))^R dif z = 0\
&= lim_(n->+infinity) lim_(R -> +infinity) integral_gamma norm(f_n (z))^R dif z = 0\
&= 0
$
证毕
]
由引理,立得@int1 趋于零
]
== 幅角原理
#theorem[幅角原理|The Argument Principle][
设 $f$ 是 $G subset CC$ 上的亚纯函数,以 $p_1, ..., p_m$ 为极点(多重重复记)和 $z_1, z_2, ..., z_n$ 为零点(多重重复记),$gamma$ 是 $G$ 上与这些零点,极点不交的可求长曲线,并且:
$
n(gamma, z) = 0, forall z in CC - G
$
此时:
$
1/(2 pi i) integral_gamma (f'(z))/(f(z)) dif z = sum_(k=1)^n n(gamma, z_k) - sum_(k=1)^m n(gamma, p_k)
$
]
#proof[
令:
$
g(z) = f(z) (product_(k=1)^n (z - p_k))/ (product_(k=1)^m (z - z_k))
$
它是解析函数,计算并利用柯西定理即得结论
]
#remark[][
某种意义上,有:
$
integral_gamma (f'(z))/(f(z)) dif z = integral_gamma dif ("Ln"(f(z)))
$
几何意义上,就是 $gamma$ 绕 $z$ 一圈时对幅角的积分
]
#theorem[幅角原理2][
设 $f$ 是 $G subset CC$ 上的亚纯函数,以 $p_1, ..., p_m$ 为极点(多重重复记)和 $z_1, z_2, ..., z_n$ 为零点(多重重复记),$gamma$ 是 $G$ 上与这些零点,极点不交的可求长曲线,$g$ 是区域上的解析函数,并且:
$
n(gamma, z) = 0, forall z in CC - G
$
此时:
$
1/(2 pi i) integral_gamma g(z) (f'(z))/(f(z)) dif z = sum_(k=1)^n g(z_k) n(gamma, z_k) - sum_(k=1)^m g(p_k) n(gamma, p_k)
$
]<arg-principle2>
#proposition[][
设 $f$ 在包含 $closedBall(a, R)$ 的开集上是解析的,在 $B(a; R)$ 上是一一的。设 $Omega = f(B(a; R))$ 则有:
$
Inv(f) (omega) = 1/(2 pi i) integral_(diff B(a; R))^() (z f'(z))/(f(z) - omega) dif z
$
]
#proof[
注意到解析的一一映射只能有简单零点,记 $z_0 = Inv(f)(omega)$,它是 $f - omega$ 的简单零点,利用 @arg-principle2 有:
$
z_0 = 1/(2 pi i) integral_(diff B(a; R))^() (z f'(z))/(f(z) - omega) dif z
$
证毕
]
#theorem[Rouche][
设 $f, g$ 在包含 $closedBall(a, R)$ 的开集上是解析的,在 $diff B(a; R)$ 上无零点/极点,设 $Z_f, Z_g, P_f, P_g$ 分别是 $f, g$ 在 $B(a; R)$ 中的零点/极点个数,并且设:
$
abs(f(z) + g(z)) < abs(f(z)) + abs(g(z)), forall z in diff B(a; R)
$
则有:
$
Z_f - P_f = Z_g - P_g
$
]
#remark[][
使用时,往往以下加强的条件已经足够:
$
abs(f(z) + g(z)) < abs(g(z))
$
]
= 解析延拓 Continuation
== 沿曲线的解析延拓
今晚调课:6:40 - 8:40 理教 103
#definition[][
- 称一个解析元素是二元组 $(f, G)$ 其中 $G$ 是区域,$f: G -> CC$ 是解析函数。
- 称 $(f', G'), (f, G)$ 互相是直接延拓|direct continuation,如果 $G' sect G != emptyset andC f|_(G' sect G) = f_(G' sect G)$
- 设有一列(有限个)解析元素 $C_n = (f_n, G_n), n = 0, 1, ..., N$ 其中 $G_n$ 都是开圆盘。若 $C_n$ 总与 $C_(n-1)$ 是直接延拓,则称 $C_N$ 是沿着链 ${D_i}$ 的 $D_0$ 的解析延拓。
- 给定曲线 $gamma: [0, 1] -> CC$,称有限长圆盘链 $l = {D_i}$ 覆盖 $gamma$,如果:
- $D_0$ 的圆心是 $gamma(0)$
- $D_N$ 的圆心是 $gamma(1)$
- 存在 $0 = s_0 < s_1 < ... < s_N = 1$ 使得对每个 $i$ 均有:
$
gamma([s_(i), s_(i+1)]) subset D_i, forall i = 0, 1, ..., N-1
$
- 若圆盘链 $D_i$ 覆盖 $gamma$, 则沿着 $D_i$ 的解析延拓被称为沿着 $gamma$ 的解析延拓。注意这个定义中曲线上的圆盘链当然不唯一,最终的解析元素也不唯一。
]
#proposition[][
- 设 $(f', G'), (f, G), (g, G)$ 互相是直接延拓,则 $f = g$
- 固定起点 $(f_0, G_0)$ 和圆盘链 $l$,则沿着 $l$ 的解析延拓(若存在)是唯一的
]
#proof[
- $f, g$ 在 $G' sect G$ 上相等,这是 $G$ 中非空开集,当然就有 $f = g$
- 利用归纳法和上一问立得
]
#proposition[][
任给曲线 $gamma$ ,存在圆盘链覆盖 $gamma$
]
#proof[
注意到 $gamma$ 是紧集,利用有限覆盖原理即可
]
#theorem[Thm 16.11 Rudin][
设曲线 $gamma$ 上有两个覆盖它的圆盘链 $A_i, B_i$ 和对应的解析元素链 $(f_i, A_i), (g_i, B_i)$,若 $(f_0, A_0), (g_0, B_0)$ 互为直接延拓,那么之后的解析元素都互为直接延拓
]
#theorem[单值性定理][
设 $D$ 是单连通区域,$Delta = B(a, r) subset D$. 设 $(f, Delta)$ 是解析元素,若该元素沿着 $D$ 内每一条以 $a$ 为起点的曲线都有解析延拓,则 $f$ 可以被解析延拓到 $D$ 上
]
#proof[
-
若设 $D = B(0, 1), Delta = B(0, r)$,设 $f$ 在 $Delta$ 上泰勒展开式的收敛半径为 $R >= r$,往证 $R >= 1$ 继而结论成立。如若不然则 $R < 1$,先将 $f$ 延拓到 $B(0, R)$ 上,由假设 $diff B(0, R)$ 上有一点 $z_0$ 使得:
$
lim_(z -> z_0) f(z) "不存在"
$
(这里利用了之前习题证明的幂级数的性质,若极限存在则幂级数在该点收敛,但由假设不可能在 $diff B(0, R)$ 上每个点都收敛)\
此时,取 $gamma = 0 -> z_0$ 线段,这条线段上当然不可能有 $f$ 的解析延拓。
- 若 $D = CC$ 证明是类似的
- 一般的,假设 $D != CC$ ,利用之后的 @Riemann-mapping 和开映射原理的推论 @univalent-is-homeomorphism,@Riemann-mapping 给出的 $g$ 是 $D -> g(D)$ 的解析同胚。注意到 $g(Delta)$ 当然是开集,取 $B(0, r) subset g(Delta)$,令:
$
h = f Inv(g): B(0, r) -> CC
$
注意到条件当然被解析延拓保持,利用情形 1 的结论知存在 $h': B(0, 1) -> CC$ 是 $h$ 的解析延拓,并且:
$
h' g = h g = f, forall z in B(0, r)
$
同时 $h' g$ 的定义域为 $D$,继而它就是 $f$ 的一个解析延拓,证毕
]
== 施瓦兹反射定理|Schwarz Reflection Principle
#definition[][
- 对任何开区域 $Omega$,记:
- $Omega_+$ 是 $Omega$ 为与上半平面 ${z | Im z > 0}$ 的部分
- $Omega_-$ 是 $Omega$ 为与下半平面 ${z | Im z < 0}$ 的部分
- $Omega_0 = Omega sect RR$
- $Omega^* = overline(Omega)$
]
#theorem[Schwarz Reflection Principle][
设 $Omega$ 是区域并且满足 $Omega^* = Omega$,设 $f: Omega_+ union Omega_0$ 是连续函数且在 $Omega_+$ 上解析,并且:
$
f(Omega_0) subset RR
$
则 $f$ 可被解析延拓到 $Omega$ 上
]
#proof[
令:
$
F(z) = cases(
f(z) quad z in Omega_+ union Omega_0,
overline(f(overline(z))) quad z in Omega_-
)
$
- 先证明 $F$ 在下半平面解析,设 $z_0$ 在下半平面,进而可设 $z$ 也是,从而:
$
lim_(z -> z_0) (F(z) - F(z_0))/(z - z_0)\
= lim_(z -> z_0) (overline(f(overline(z))) - overline(f(overline(z_0))))/(z - z_0)\
= lim_(z -> z_0) overline((f(overline(z)) - f(overline(z_0)))/(overline(z) - overline(z_0)))\
$
利用上半平面的解析性上面的极限当然存在
- 再证明 $F$ 在实轴连续,由 $f$ 的连续性及 $f(Omega_0) subset RR$ 结论是显然的
- 最后,之前 @Morera 的习题告诉我们这样的函数在 $Omega$ 上一定是解析的
]
#corollary[一般球上的推广][
设 $D = B(a, r),D' = (b, R), Omega$ 是区域,令:
$
Omega_D = Omega sect D\
Omega_(D^c) = Omega sect D^c\
Omega_(diff D) = Omega sect (diff D)
Omega^*_D "是关于圆周" D "的对称点"
$
若 $Omega = Omega^*_D$,并且:
$
f: Omega_D union Omega_(diff D)\
g: Omega_(D^c) union Omega_(diff D)
$
连续
#TODO
]
= 黎曼映射定理
本章的目的是证明黎曼映射定理。它的目的是分类所有的单连通的区域。最终的结果是单连通区域只可能是整个复平面或者与单位圆盘双全纯等价。
== 双全纯函数
#remark[][
$CC$ 当然不可能与任何有界区域双全纯等价,否则与整函数无界矛盾。
]
@univalent-is-homeomorphism 与 @inverse-theorem 表明任何解析函数在导数不为零的局部都是双全纯的,这个事实非常重要。
#lemma[][
设 $f: Omega -> CC$ 是单叶解析函数,$Omega$ 单连通,则 $f(Omega)$ 也单连通
]
#proof[
运用一个非常简单的事实,对于任何可求长曲线 $gamma$ 都有:
$
n(gamma, a) = cases(
1 quad a in gamma "内部",
0 quad a in gamma "外部"
)
$
这个事实需要 Jordan 曲线定理,这里不再说明。
我们证明的思路是先对 $f(Omega)$ 内部较为光滑的曲线做证明。对于一般的曲线,找一个略大的可求长曲线将其包含,由可求长曲线的情形,其内部都在集合中,当然小曲线的内部也在集合中。
#lemmaLinear[][
设 $G$ 是区域,$gamma$ 是简单闭曲线,则存在可求长简单闭曲线 $gamma'$ 使得 $gamma'$ 的内部包含 $gamma$ 的内部
]
#proof[
对 $gamma$ 做有限覆盖,这些圆盘组成的区域的边界一部分在曲线的外部,另一部分在曲线的内部,取所有外部部分可以证明这写部分构成可求长的简单闭曲线。
]
根据引理和上面的陈述,我们只需要考虑可求长曲线足以。对于这样的曲线我们可以用缠绕数和幅角原理来转换,两者的形式是积分,它当然在双全纯变换下不变,因此经过来回变换不难证明 $f$ 把曲线的内部映到内部,外部映到外部,进而结论成立。
]
== 拓扑和实分析工具
#lemma[][
设 $G$ 是开集,则存在递增的紧集链 $A <= A <= ... <= A <= ...$ 使得:
- $union A_i = G$
- $A_n subset A_(n+1)$ 的内部
- 若 $K subset G$ 是紧集,则存在 $i$ 使得 $K subset A_i$
- $hat(CC) - A_n$ 都有一个连通分支包含 $hat(CC) - G$
]
#proof[
$
A_n = {z in CC | norm(z) <= n andC d(z, CC - G) >= 1/n}
$
检验性质是容易的
]
#lemma[][
设 $G$ 是开集,$X$ 是完备度量空间,$f, g: C(G, X)$,令:
$
d_n (f, g) = sup {d(f(z), g(z)) | z in A_n}
$
其中 $A_n$ 上面引理给出的紧集链。最终令:
$
d (f, g) = sum_(n=1)^infinity (1/2)^n (d_n (f, g))/(1 + d_n (f, g))
$
则上面的级数收敛,且 $d$ 是一个度量。进一步,$C(G, X)$ 是完备的,且其拓扑与 $A_n$ 的选择无关。
]
#proof[
这个证明有些繁琐且更多利用实分析和拓扑的技巧,在此略过。
]
#proposition[][
在上面的度量空间中,$f_n -> f$ 当且仅当 $f_n$ 在每个 $A_i$ 上一致收敛于 $f$,换言之,在 $G$ 上内闭一致收敛。
]
#definition[][
称 $A subset C(G, X)$ 是正规的,如果其中任何序列都有收敛子列。
]
#theorem[][
$A$ 是正规的当且仅当 $A$ 是预紧的(也即它的闭包是紧的)
]
#proof[
利用闭集列紧当且仅当是紧集即可。
]
#definition[][
- 称 $A subset C(G, X)$ 在 $z_0$ 等度连续|equicontinous的,如果:
$
forall epsilon > 0, exists delta > 0, forall z in B(z_0, delta), forall f in A, d(f(z), f(z_0)) < epsilon
$
- 称 $A$ 在 $E subset G$ 上等度连续,如果:
$
forall epsilon > 0, exists delta > 0, forall z, z' in E, norm(z - z') < delta => forall f in A, d(f(z), f(z')) < epsilon
$
]
#proposition[][
设 $A$ 在 $G$ 中每一个点上等度连续,则 $A$ 在 $G$ 的每一个紧子集上等度连续(也称为内闭等度连续)
]
#proof[
首先在每一个点处由条件构造一个邻域球,再在每个紧集中使用 @Lebesgue_Lemma,即可得到结论。
]
#theorem[Arzela-Ascds][
$A subset C(G, X)$ 正规当且仅当以下条件成立:
- $forall z in G, A z = {f(z) | f in A}$ 预紧
- $A$ 在 $G$ 的每一个紧子集上等度连续(等价于在 $G$ 中每一个点上等度连续)
]<A-A-theorem>
#definition[][
记:
- $H(G)$ 是 $C(G, CC)$ 中解析函数
- $A(G) = {f in C(overline(G), CC) | f_G in H(G)}$
]
== 复分析的预备工作
#definition[][
- 称 $FF subset H(G)$ 局部有界(locally bounded)如果:
$
forall a in G, exists M > 0, exists r > 0, forall z in B(a, r) sect G, forall f in FF, norm(f(z)) < M
$
- 称 $FF$ 内闭一致有界,如果在每个 $G$ 的紧子集上都一致有界
]
#proposition[][
$FF subset H(G)$ 局部有界当且仅当 $FF$ 内闭一致有界
]
#theorem[Montel][
$FF subset H(G)$ 是正规的当且仅当 $FF$ 局部有界
]<Montel>
#proof[
设正规性成立,假设不局部有界,则可得到点 $z_0$ 使得 $FF$ 中有一列函数使得:
$
exists z_n in B(z_0, 1/n), norm(f_n (z_n)) > n
$
然而由正规性,不妨设 $f_n$ 收敛于 $f$,进而在 $z_0$ 某个闭有界邻域一致收敛,上式将导致 $f(z_0)$ 无法定义,这是荒谬的。
另一方面,设局部有界成立,@A-A-theorem 的条件 1 显然满足,往证条件 2 也即任取 $z_0$ 都有在该点处等度连续即可。\
注意到由局部有界条件,不妨设:
$
forall z in overline(B(z_0, delta)), forall f in FF: norm(f(z)) < M
$
如此,利用柯西定理:
$
norm(f(z) - f(z_0)) = 1/(2 pi) norm(integral_(diff overline(B(z_0, delta/2)))^() (f(w))/(w - z_0) dif w - integral_(diff overline(B(z_0, delta/2)))^() (f(w))/(w - z) dif w)\
= 1/(2 pi) norm(integral_(diff overline(B(z_0, delta/2)))^() (f(w) (z_0 - z))/((w - z_0)(w - z)) dif w)\
<= 1/(2 pi) integral_(diff overline(B(z_0, delta/2)))^() norm(f(w) (z_0 - z)/((w - z_0)(w - z))) dif w\
<= 1/(2 pi) integral_(diff overline(B(z_0, delta/2)))^() M norm( (z_0 - z)/((w - z_0)(w - z))) dif w\
$
其余部分分母有界,因此可以控制到分子的线性式,当然就蕴含着等度连续
]
#theorem[][
设 ${f_n} subset C(G, CC)$ 在 $G$ 上内闭一致收敛于 $f in C(G, CC)$,且 $f_n in H(G)$,则 $f in H(G)$,且 $f$ 的 $k$ 阶导数就是 $f_n$ 的 $k$ 阶导数的极限
]<analytic-continuity>
#proof[
$f$ 的连续性是显然的。至于解析性,利用 @Morera 定理,只需证明内部某个三角形边界上的积分为零即可。可以找到一个略大的紧集,函数列一致收敛,进而由积分极限的换序性质,积分为零。
至于积分值,由一致收敛的结论和归纳法证明 $f'_n$ 在任意闭球 $B(a, r)$ 上收敛即可。注意到由柯西积分公式的推论:
$
norm(f'_n (z) - f'(z)) <= norm(1/(2 pi) integral_(diff B(a, R))^() (f_n (w))/(w-z)^2 - (f'(w))/(w - z)^2 dif w) \
<= 1/(2 pi (R - r)^2) integral_(diff B(a, R))^() norm(f_n (w)- f'(w)) dif w\
$
利用积分极限换序即可得到结论。
]
#theorem[Harwitz][
设 ${f_n} subset C(G, CC)$ 在 $G$ 上内闭一致收敛于 $f in H(G)$,设 $f$ 不恒为零,$closedBall(a, r) subset G$,$f(z) !=0, forall z in diff closedBall(a, r)$,则:
$
exists N in NN, forall n > N, f, f_n "在 " B(a, r) "内有相同的零点个数"
$
]<Harwitz>
#proof[
设 $m = inf_(diff closedBall(a, r)) norm(f(z)) > 0$,由一致收敛性,当 $n$ 充分大时有:
$
norm(f_n (z) - f(z)) < m/2 <= norm(f(z)), forall z in diff closedBall(a, r)
$
根据 Roache's Theorem,结论成立
]
Bonus: 利用上面定理导出小黄书定理 8.1.4
#corollary[][
设 ${f_n} subset C(G, CC)$ 在 $G$ 上内闭一致收敛于 $f in H(G)$,且 $f_n$ 在 $G$ 上无零点,则要么 $f$ 恒为零,要么恒不为零。
]
== 黎曼映射定理
#theorem[黎曼映射定理|Riemann mapping][
设 $D$ 是单连通区域且不为 $CC$ ,$a in D$,则存在唯一的双全纯同胚 $f: D -> B(0, 1)$ 使得 $f(a) = 0, f'(a) > 0 in RR$,这个 $f$ 也被称为黎曼映射
]<Riemann-mapping>
#proof[
先证明比较简单的唯一性,假设有两个函数 $f, g$ 满足条件,则 $h := g Inv(f) : B(0, 1) -> B(0, 1)$ 也是双全纯的,且:
$
h(0) = 0\
h'(0) = g'(a) 1/(f'(a)) > 0
$
由对称性,不妨设 $norm(h'(0)) >= 1$,由 @Schwarz 可得 $norm(h'(0)) = 1$,继而:
$
exists c, norm(c) = 1 , h(z) = c z\
h'(0) = c > 0
$
从而 $c = 1$ ,证毕
再证明比较复杂的存在性:
定义:
$
FF = {f in H(G) | f: G -> B(0, 1) "是单叶解析的且" f(a) = 0, f'(a) > 0}
$
显然 $FF$ 是(局部)有界的,根据 @Montel 它是正规族\
#lemmaLinear[][
$FF != emptyset$
]<lem-1>
#proof[
由于 $G != CC$,任取 $b in CC - G$,利用单连通性可以构造 $g: G -> CC$ 使得:
$
g^2 = z - b
$
(注意到 $z - b$ 在 $G$ 上不零化,结合单连通性即可找到平方根)\
同时上式右侧是单射,导出 $g$ 是单射。事实上,$g(z_1) + g(z_2) = 0$ 也能导出 $z_1 = z_2$,因此任意两个关于原点对称的点至多一个落在 $g(G)$ 中。我们接下来的目标便是证明 $g(G)$ 确实落在某个半平面之中。
由开映射原理,设 $B(g(a), r) subset g(G)$,上面结论表明 $B(-g(a), r) subset CC - g(G)$(同时也表明不可能 $g(a) = 0$)几何上来说,由于 $g(G)$ 也是单连通区域,当然会落在某个方向上的一半平面中,而半平面与 $B(0, 1)$ 的共形同胚是熟知的。
]
#lemmaLinear[][
$overline(FF) = FF union {0}$
]<lem-2>
#proof[
注意到 $FF$ 中函数的极限首先当然解析,且 $f(a) = 0, f'(a) >= 0$\
假设 $f != 0$,我们需要证明:
- $f(G) subset B(0, 1)$,既然 $f(G) subset diff(B(0, 1))$ 且是开集,当然应该 $f(G) subset B(0, 1)$
- $f$ 是单射,既然任取 $z_1, z_2$ 假设 $f(z_1) = f(z_2)$,总可找到 $r$ 使得:
$
z_2 in.not B(z_1, r)
$
考虑 $f_n (z) - f_n (z_2)$,利用 @Harwitz 可得 $f$ 与 $f_n$ 在 $B(z_1, r)$ 上有相同的零点个数,进而它们都没有零点。进而就有:
$
f(z_1) != f(z_2)
$
- $f'(a) > 0$,既然 $f$ 是单射这就是 @univalent-is-homeomorphism
]
考虑求导算子:
$
funcDef(D, H(G), CC, f, f'(a))
$
@analytic-continuity 给出了它的连续性。如此,在 $overline(FF)$ 中取得 $D(FF)$ 的最大值点(注意到 $D(overline(FF)) subset RR^+$,且连续函数在紧集上可以取得最大值)并有 $f != 0 => f in FF$,断言这个 $f$ 满足 $f(G) = B(0, 1)$ 进而就是我们要找的 $f$\
如若不然,则可设 $w in B(0, 1) - f(G)$,令:
$
h_2 (z) = (f(z) - w)/(1 - overline(w) f(z))
$
显然它是解析函数,且在 $G$ 上无零点。既然 $G$ 是单连通的,我们可以获得它的平方根,也即:
$
exists h(z), h^2 (z) = h_2 (z)
$<h-def>
注意到:
$
phi(z) := (z - h(a))/(1 - z overline(h(a)))
$
是 $B(0, 1)$ 到自身的共形同胚,定义:
$
g(z) = norm(h'(a))/(h'(a)) (h(z) - h(a))/(1 - overline(h(a)) h(z)) := norm(h'(a))/(h'(a)) phi(h(z))
$
可以验证:
- $g(G) subset B(0, 1)$
- $g(a) = 0$
- $g$ 是单射,既然莫比乌斯变换是双射,只需 $h$ 单 $arrow.l.double h_2$ 单,利用莫比乌斯变换和 $f$ 单可知结论成立
同时,计算得:
$
g'(a) = norm(h'(a))/(1 - norm(h(a))^2)
$
在@h-def 中求导,得:
$
2 h(a) h'(a) = f'(a) (1 - norm(w)^2)
$
同时注意到 $norm(h'(a)) = norm(w)$,一番计算最终可得:
$
g'(a) = (f'(a) (1 + norm(w)))/(2 sqrt(norm(w))) >= f'(a)
$
上面利用了均值不等式,取等当且仅当 $norm(w) = 1$,这是不可能的,因此:
$
g'(a) > f'(a)
$
以上所有推理导出 $g in FF, D(g) > D(f)$,与 $f$ 的最大性矛盾!
]
#remark[][
一个可能的推广是所谓的 quasi-conformal mapping (类似于共形映射把圆映成圆,拟共形映射将圆映成椭圆),这是一种共形映射的推广,也可以对黎曼映射定理作出推广。另一个方向是考虑黎曼映射是否能连续延拓到边界上(当然,一般来说是不行的),但是在一些条件下确实可以:
#theorem[][
假设单连通区域 $G$ 的边界是一个简单闭曲线,则黎曼映射可以连续延拓到:
$
f: overline(G) -> overline(B(0, 1))
$
]<Riemann-mapping-extension>
然而许多时候简单闭曲线的条件是过强的,例如上半平面中随便删去一条从 $RR$ 上出发的简单曲线,得到的区域仍是单连通区域,然而黎曼映射当然难以进行连续延拓。此时可以推广到 prime ends 的语言上进行解释
]
= 调和函数|Harmonic function
== 泊松核
#let suminf(n) = $sum_(#n = - infinity)^(+infinity)$
#definition[][
设 $G subset CC, f: G -> CC$ 称 $f$ 为调和函数,如果 $f$ 有连续偏导且:
$
Delta u = (diff^2 u) / (diff x^2) + (diff^2 u) / (diff y^2) = 0
$<Laplace-equation>
]
#definition[泊松核][
定义:
$
P_(r) (theta) = suminf(n) r^(abs(n)) e^(i n theta), where r in [0, 1)
$
称为泊松核
]
#lemma[][
$
Re (
(1 + r e^(i theta))
/
(1 - r e^(i theta))
)
= P_r (theta)\
= (1 - r^2)/(1 - 2 r cos theta + r^2)
$
]
#proof[
对:
$
(1 + r e^(i theta))
/
(1 - r e^(i theta))
$
做级数展开,可以写成:
$
(1 + r e^(i theta))
/
(1 - r e^(i theta))
= (1 + r e^(i theta)) sum_(n=0)^(+infinity) r^n e^(i n theta)\
= 1 + 2 sum_(n=1)^(+infinity) r^n e^(i n theta)\
$
取实部,有:
$
Re (1 + r e^(i theta))
/
(1 - r e^(i theta))
= 1 + sum_(n=1)^(+infinity) r^n( e^(i n theta) + e^(-i n theta))\
= suminf(n) r^(abs(n)) e^(i n theta)
$
证毕
]
#lemma[][
- $1/(2 pi) integral_(-pi)^(pi) P_r (theta) dif theta = 1$
- $P_r (theta) > 0, forall theta$
- $P_r (theta) < P_r (delta) where 0 < theta < abs(delta) <= pi$
- 对于 $theta in [delta, pi] union [-pi, -delta] where delta in (0, pi)$,有:
$
lim_(r -> 1^-) P_r (theta) = 0
$
且是一致收敛
]
== Dirichlet Problem
#definition[][
设 $G$ 满足 $forall f in C(diff G, RR), exists u in C(overline(G), RR), u|_(diff G) = f$ 且 $u$ 在 $G$ 中调和,则称 $G$ 是 Dirichlet 区域
]
在 Dirichlet 研究太阳系的稳定性时,提出了什么区域是 Dirichlet 区域的问题,这个问题在数学上被称为 Dirichlet Problem。一般的解决方法非常困难,我们只对单位圆盘解决,也已经十分困难了。
#lemma[Leibniz' s rule][
设 $gamma subset G$ 是可求长曲线,$G$ 是区域,$phi in C(gamma times G, C)$,令:
$
g(z) = integral_(gamma) phi(z, w) dif w
$
则 $g$ 在 $G$ 上连续。若 $partialDer(phi, z)$ 连续,则 $g$ 是解析函数且:
$
g(z) = integral_(gamma) partialDer(phi, z)(w, z) dif w
$
]<Leibniz-rule>
#proof[
将实分析中同样的定理证明搬到复数域即可
]
#theorem[][
单位圆盘 $D = B(0, 1)$ 是 Dirichlet 区域,更进一步,$u$ 是唯一存在的,且形如:
$
u(r e^(i theta)) = 1/(2 pi) integral_(-pi)^(pi) P_r (theta - t) f(e^(i t)) dif t, forall r in [0, 1), theta in [0, 2pi)
$
]
#proof[
#let ze = $e^(i theta)$
令:
$
u(r e^(i theta)) = cases(
1/(2 pi) integral_(-pi)^(pi) P_r (theta - t) f(e^(i t)) dif t quad r in [0, 1),
f(e^(i theta)) quad r = 1
)
$
设 $z = ze$,将有:
$
u(z) = 1/(2 pi) Re (integral_(-pi)^(pi) (1 + r ei((theta - t))) / (1 - r ei((theta - t))) f(e^(i t)) dif t)\
= 1/(2 pi) Re (integral_(-pi)^(pi) (ei(t) + z) / (ei(t) - z) f(e^(i t)) dif t)\
$
- @Leibniz-rule 给出:
$
integral_(-pi)^(pi) (ei(t) + z) / (ei(t) - z) f(e^(i t)) dif t
$
关于 $z$ 解析,因此 $u(z)$ 作为解析函数的实部确实是调和函数。
- 接下来证明 $u$ 在边界上的连续性。不失一般性,只需计算在 $1$ 处的连续性即可,也即对于 $forall epsilon > 0$ 估计:
$
norm(u (ei(theta)) - f(1)) = norm(1/(2 pi) integral_(-pi)^(pi) P_r (theta - t) (f(e^(i t)) - f(1)) dif t)\
$
注意到泊松核在远离 $0$ 处一致收敛于零,只需对任意小的 $delta$ 估计:
$
norm(1/(2 pi) integral_(-epsilon)^(epsilon) P_r (theta - t) (f(e^(i t)) - f(1)) dif t)\
<= 1/(2 pi) integral_(-epsilon)^(epsilon) P_r (theta - t) norm(f(e^(i t)) - f(1)) dif t\
$
显然取得 $delta$ 足够小可以使得:
$
norm(f(e^(i t)) - f(1)) < epsilon
$
将有上式:
$
&<= ( 1/(2pi) integral_(-epsilon)^(epsilon) P_r (theta - t) dif t) epsilon\
&<= ( 1/(2pi) integral_(-pi)^(pi) P_r (theta - t) dif t) epsilon\
&= epsilon
$
边界上的连续性证毕
- 最后验证唯一性。来自于以下的引理:
#lemma[][
设 $u$ 在 $B(0, 1)$ 上调和,在边界处连续且为零,则 $u = 0$
]<lemma-harmonic-zero>
#proof[
有许多种证明方法,例如 @harmonic_conjugate 给出 $u$ 可以补充为解析函数 $f$\
再利用 @Cauthy-value 可得 $u = 0$\
或者取 $u$ 在区域闭包上的最大值和最小值,利用下面的 @Maximum-Minimal-principle 即可
]
]
#remark[][
黎曼映射定理告诉我们,单位圆盘的内部与任何非 $CC$ 的单连通区域都差不多。如果黎曼映射可以连续延拓到边界,容易想到单连通区域的 Dirichlet 性立刻化归到单位圆盘上。@Riemann-mapping-extension 给出至少边界是约当曲线时上面说的连续延拓是成立的。
]
#corollary[][
设 $u$ 在 $B(a, R)$ 上调和,在边界处连续,则有 $forall r < R$:
$
u(a + r ei(theta)) = 1/(2 pi) integral_(-pi)^(pi) P_r (theta - t) u(a + R e^(i t)) dif t\
= 1/(2 pi) integral_(-pi)^(pi) (R^2 - r^2)/(R^2 - 2 r R cos theta + r^2) u(a + R e^(i t)) dif t\
$
更进一步,若 $u(x) >= 0$,则有:
$
(R - r)/(R + r) u(a) <= u(a + r ei(theta)) <= (R + r)/(R - r) u(a)
$
]
#proof[
公式的成立性由上面定理立得。至于不等式,注意到:
$
(R - r)/(R + r)u(a + R e^(i t)) <= (R^2 - r^2)/(R^2 - 2 r R cos theta + r^2) u(a + R e^(i t)) <= (R + r)/(R - r) u(a + R e^(i t))
$
两边积分并注意到:
$
1/(2 pi) integral_(-pi)^(pi) u(a + R e^(i t)) dif t = u(a)
$
来自于在原来公式中取 $r = 0$ ,即可得到结论
]
== 平均值定理与最大/最小值原理
#theorem[Mean Value][
设 $u: G -> RR$ 上调和,$closedBall(a, r) subset G$,则:
$
u(a) = 1/(2 pi) integral_(-pi)^(pi) u(a + r e^(i theta)) dif theta
$<mean-value-equation>
]<mean-value-harmonic>
#proof[
类似 @lemma-harmonic-zero 的证明,化归到复解析情形即可
]
#theorem[Maximum/Minimal Principle][
设 $u: G -> RR$ 是连续函数,且满足@mean-value-equation 给出的平均值条件。若 $exists a in G$ 使得 $u(a)$ 是区域上的最大值(或最小值),则 $u(a)$ 是常数
]<Maximum-Minimal-principle>
#proof[
只证最大值情形,最小值取负即可。假设 $a$ 是最大值点,由 @mean-value-equation 有:
$
u(a) = 1/(2 pi) integral_(-pi)^(pi) u(a + r e^(i theta)) dif theta
$
借用下面的引理:
#lemma[][
设 $f: [0, 1] -> RR$ 是连续函数,且:
$
f(x) <= M\
integral_(0)^(1) f(x) dif x = M
$
则 $f(x) = M$
]
#proof[
也就是证明若 $f(x) >= 0, integral_(0)^(1) f(x) dif x = 0$ 则 $f(x) = 0$,这是实分析的经典结论
]
可得 $forall z in diff B(a, r), u(z) = u(a)$,进而 $f$ 在 $a$ 附近任何一个圆盘上是解析函数。\
对于区域内任意一点,找到一个路径并对路径做有限覆盖,不断利用上面的结论可得区域内任何一点处的函数值都是 $u(a)$
]
#theorem[][
满足@mean-value-equation 的连续函数一定是调和函数
]
#proof[
有些复杂,我们不证明,但是结论需要了解
]
#definition[次/超调和函数|subharmonic/super harmonic function][
设 $u: G -> RR$ 上连续,且有:
$
u(a) <= 1/(2 pi) integral_(-pi)^(pi) u(a + r e^(i theta)) dif theta
$
则称 $u$ 是次调和函数。类似地,若不等号反向,则称 $u$ 是超调和函数
]
考试内容到此为止
= 黎曼 $zeta$ 函数
#definition[黎曼 $zeta$ 函数][
定义:
$
zeta(s) = sum_(n=1)^(+infinity) 1/n^s = product_(p "is prime" ) (1 - p^(-s))^(-1), Re s > 1
$
]
#theorem[素数定理][
设 $pi(T)$ 是不超过 $T$ 的素数个数,则有:
$
pi(T) tilde "Li"(T) = integral_(2)^(T) 1 / (ln u) dif u tilde T / (ln T)
$
20世纪的工作表明:
$
pi(T) = "Li"(T) + O(sqrt(T) ln T)
$
等价于黎曼猜想
]
#theorem[Hober][
设 $M$ 是有常曲率 $-1$ 的紧 Riemann 曲面,
$
pi(T) = {gamma "是素的闭测地线" | l(gamma) <= T}
$
则 $exists alpha in (0, 1)$,有:
$
pi(T) = "Li"(e^T) + O(e^(alpha T))
$
] |
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/其它/Git.typ | typst | #import "/src/components/TypstTemplate/lib.typ": *
#show: project.with(
title: none,
lang: "zh",
)
#warning()[
- 当你在实现一个大功能时,请将它分成小块并定期提交
- 长时间工作而不做提交并不是一个好主意
- 慎用复杂 or 不熟的 git 命令
- 实在不行你先 `mkdir ~/backrepo && cp -r ./* ~/backrepo/` 一下(不会匹配 `.git` 目录哒)
]
- 基础的东西不谈,记录一些(可能)比较危险的操作,多人情况下慎用
- *修改最近一次提交*(常用)
- `git commit --amend -m "new message"`
- 本质上是用新的提交,替换掉最近的提交
- 如果已经推送到远程怎么办?本地处理好然后 `git push -f` \u{1F608}
- *修改更久之前的提交*(更灵活)
- `git rebase -i HEAD~n`,从 `HEAD` 开始往前数 `n` 个提交
- 或者 copy 要修改的提交的 hash,然后 `git rebase -i <hash>`
- 会弹出一个编辑器选择对每个提交的操作
+ `pick` (p): 保留该 commit,默认操作。
+ `reword` (r): 保留该 commit,但允许修改其提交信息。
+ `edit` (e): 保留该 commit,暂停以便进行修改(不仅限于提交信息)。
+ `squash` (s): 将该 commit 合并到前一个 commit,同时保留合并后的提交信息。
+ `fixup` (f): 将该 commit 合并到前一个 commit,但不保留该 commit 的提交信息。
+ `exec` (x): 执行 Shell 命令。
+ `drop` (d): 删除该 commit,不保留其记录。
- 通过 `rebase` 还可以达成许许多多奇怪的效果,但是慎用
- e.g.
- 我想要调转 $A -> B -> C -> D("HEAD")$ 中 $B$ 和 $C$ 的顺序,可以 `git rebase -i HEAD~3`,然后把在弹出的交互界面 (vim or nano, or GitLens Interactive Rebase for me) $B$ 和 $C$ 的顺序调换
- 我想要把现在暂存区里的内容提交到上上次 commit 里,可以先 `git commit -m "to be merged"`,然后 `git rebase -i HEAD~2`,把新的 commit 往下拖一格,把 `pick` 改成 `squash`(合并到 `HEAD~2` 去),然后保存退出,再次弹出的界面里可以编辑 commit message,保存退出即可
- *删除某个提交*
- `git reset HEAD^`,删除最近的一个提交
- 有 $3$ 个选项
+ `--soft`:上次 commit 的提交被撤回到暂存区,当前暂存区的内容依旧在暂存区,工作区内容依旧在工作区
+ `--mixed`(默认):上次 commit 的提交被撤回到工作区,当前暂存区的内容也被退回到工作区,工作区内容依旧在工作区
+ `--hard`:上次 commit 的提交被完全删除,当前暂存区的内容也没了,工作区内容依旧在工作区
- *恢复丢弃了的修改*
- 比如说你一个手贱 `git stash drop` 了,文件可能并没有被彻底删除,还是有补救机会的
- `git fsck` + `--dangling` or `--unreachable` or `--lost-found`
- 比如说 `git fsck --unreachable` 会列出无法通过任何引用(如分支、标签、HEAD 指针等)访问的对象,当然这只是 hash 看不到内容。可以用 `git fsck --unreachable | awk '{print $3}' | xargs git show >> find.txt`,然后在 txt 里找一找你想要的东西
- 最后 `git merge <hash>`(`git stash apply <hash>`) 把它应用回来
#hline()
- 在多人协作的时候,直接 `git pull` 可能并不是一个好选择
- 因为 `pull` = `fetch` + `merge`,如果你 merge 没配置好的话,可能就导致过多无用的 merge 信息
- 一般来说 merge 的 `fast-forward only` 和 `rebase true` 是更好的选择
- 如果不确信的话,就先 `git fetch` 然后手动操作吧 |
|
https://github.com/CreakZ/mirea-algorithms | https://raw.githubusercontent.com/CreakZ/mirea-algorithms/master/README.md | markdown |
# Введение
В данном репозитории собраны <strike>все</strike> (кроме 6-й, не спрашивайте, как так получилось, быть может, она когда-нибудь будет сделана) работы по дисциплине СиАОД (вариант №22), встречающейся на пути студентов направления "Программная инженерия" (и, почти наверняка, каких-то еще) РТУ МИРЭА. <br>
Сразу скажу: на правильность кода и отчетов не претендую 💋. <br>
Все отчеты сделаны при помощи [Typst](https://typst.app/).
# Описание
В репозитории содержатся 2 основные директории `src` и `reports`.<br>
Внутри `src` в директориях `work_{n}` (вместо `n` вставить номер работы, от 1 до 8) содержится код соответствующих работ. В каждой работе `.h` и `.cpp` файлы разделены в разные директории (`headers` и `source` соответственно), файл `main.cpp` лежит в корне директории. Если работа предусматривает подзадания, то они также разделены по разным директориям.<br>
Внутри `reports` в директориях `work_{n}` содержатся Typst проекты отчетов. В директории `docs` находятся примеры сгенерированных pdf-отчетов (все работы, кроме 6).
# TODOs
1. [CMake](https://cmake.org/) для всех работ
# Пасхалка 🥶 💦🗣🔥
ДЕТКА 💦 Я 👶 ВАМПИР 🧛 КАКАЯ 😕 ТВОЯ 👉 ГРУППА 👨❤️👨 КРОВИ 🩸 ДАЙ 🥢 МНЕ 👕 УКУСИТЬ 🦟 Я 👖 КЛЯНУСЬ🤝 НЕ 🔞 БУДЕТ 😡 БОЛЬНО 😭 ПРИХОДИ 🚶♂️ КО 💍 МНЕ 👴 Я 👨🎓 НЕ 🔞 ХОЧУ 👾 БЫТЬ 😇 ОДИНОКИМ 🥶 НОЖ 🔪 В 😨 МОИХ 👐 РУКАХ 🖐 ПОМОЖЕТ 😤 МНЕ 😉 ЧЕРТИТЬ ✒️ ДОРОГИ 🛣
|
|
https://github.com/howardlau1999/sysu-thesis-typst | https://raw.githubusercontent.com/howardlau1999/sysu-thesis-typst/master/chapters/ch01.typ | typst | MIT License | #import "../functions/allinone.typ": *
#import "../info.typ": *
= 基本功能 <intro>
== 标题
Typst 中的标题使用 `=` 表示,其后跟着标题的内容。`=` 的数量对应于标题的级别。
除了这一简略方式,也可以通过 `heading` 函数自定义标题的更多属性。具体可以参考#link("https://typst.app/docs/reference/meta/heading/", [文档中的有关内容])。
下面是一个示例:
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
```typ
#heading(level: 2, numbering: none, outlined: false, "二级标题")
#heading(level: 3, numbering: none, outlined: false, "三级标题")
#heading(level: 4, numbering: none, outlined: false, "四级标题")
#heading(level: 5, numbering: none, outlined: false, "五级标题")
```,
[
#heading(level: 2, numbering: none, outlined: false, "二级标题")
#heading(level: 3, numbering: none, outlined: false, "三级标题")
#heading(level: 4, numbering: none, outlined: false, "四级标题")
#heading(level: 5, numbering: none, outlined: false, "五级标题")
]
)\
需要注意的是,这里的样式经过了本模板的一些定制,并非 Typst 的默认样式。
=== 三级标题
这是三级标题下的正文。#lorem(100)
==== 四级标题
本模板目录的默认最大深度为 3,即只有前三级标题会出现在目录中。如果需要更深的目录,可以更改 `outlinedepth` 设置。
== 粗体与斜体
与 Markdown 类似,在 Typst 中,使用 `*` 表示粗体,使用 `_` 表示斜体。下面是一个示例:
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
```typ
遵循 sysu-thesis 的惯例,使用 *黑体* 表示粗体,_楷体_ 表示斜体。
*bold* and _italic_ are very simple.
```,
[
遵循 sysu-thesis 的惯例,使用 *黑体* 表示粗体,_楷体_ 表示斜体。
*bold* and _italic_ are very simple.
]
)\
由于绝大部分中文字体只有单一字形,这里遵循 `sysu-thesis` 的惯例,使用#strong[黑体]表示粗体,#emph[楷体]表示斜体。但需要注意的是,由于语法解析的问题, `*...*` 和 `_..._` 的前后可能需要空格分隔,而这有时会导致不必要的空白。 如果不希望出现这一空白,可以直接采用 `#strong` 或 `#emph`。
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
```typ
对于中文情形,*使用 \* 加粗* 会导致额外的空白,#strong[使用 \#strong 加粗]则不会。
```,
[
对于中文情形,*使用 \* 加粗* 会导致额外的空白,#strong[使用 \#strong 加粗]则不会。
]
)\
== 脚注
从 v0.4 版本开始,Typst 原生支持了脚注功能。本模板中,默认每一章节的脚注编号从 1 开始。
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
```typ
Typst 支持添加脚注#footnote[这是一个脚注。]。
```,
[
Typst 支持添加脚注#footnote[这是一个脚注。]。
]
)\
== 图片
在 Typst 中插入图片的默认方式是 `image` 函数。如果需要给图片增加标题,或者在文章中引用图片,则需要将其放置在 `figure` 中,就像下面这样:
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
```typ
#figure(
image("images/chapter1/1-writing-app.png", width: 100%),
caption: "Typst 网页版界面",
) <web>
```,
[
#figure(
image("../images/chapter1/1-writing-app.png", width: 100%),
caption: "Typst 网页版界面",
) <web>
]
)\
@web 展示了 Typst 网页版的界面。更多有关内容,可以参考 @about。@developers 中介绍了 Typst 的主要开发者。代码中的 `<web>` 是这一图片的标签,可以在文中通过 `@web` 来引用。
== 表格
在 Typst 中,定义表格的默认方式是 `table` 函数。但如果需要给表格增加标题,或者在文章中引用表格,则需要将其放置在 `figure` 中,就像下面这样:
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
codeblock(
```typ
#figure(
tablex(
columns: (auto, auto, auto, auto),
inset: 10pt,
align: horizon,
[*姓名*],[*职称*],[*工作单位*],[*职责*],
[李四],[教授],[#(学校)],[主席],
[王五],[教授],[#(学校)],[成员],
[赵六],[教授],[#(学校)],[成员],
[钱七],[教授],[#(学校)],[成员],
[孙八],[教授],[#(学校)],[成员],
),
caption: "答辩委员会名单",
) <table>
```,
caption: "默认表格",
),
[
#figure(
tablex(
columns: (auto, auto, auto, auto),
inset: 10pt,
align: horizon,
[*姓名*],[*职称*],[*工作单位*],[*职责*],
[李四],[教授],[#(学校)],[主席],
[王五],[教授],[#(学校)],[成员],
[赵六],[教授],[#(学校)],[成员],
[钱七],[教授],[#(学校)],[成员],
[孙八],[教授],[#(学校)],[成员],
),
caption: "答辩委员会名单",
) <table>
]
)
对应的渲染结果如 @table 所示。代码中的 `<table>` 是这一表格的标签,可以在文中通过 `@table` 来引用。
默认的表格不是特别美观,本模板中提供了 `booktab` 函数用于生成三线表,@booktab 是一个示例。代码中的 `<booktab>` 是这一表格的标签,可以在文中通过 `@booktab` 来引用。
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
```typ
#booktab(
width: 100%,
aligns: (left, center, right),
columns: (1fr, 1fr, 1fr),
caption: [`booktab` 示例],
[左对齐], [居中], [右对齐],
[4], [5], [6],
[7], [8], [9],
[10], [], [11],
) <booktab>
```,
[
#booktab(
width: 100%,
aligns: (left, center, right),
columns: (1fr, 1fr, 1fr),
caption: [`booktab` 示例],
[左对齐], [居中], [右对齐],
[4], [5], [6],
[7], [8], [9],
[10], [], [11],
) <booktab>
]
)
== 公式
@eq 是一个公式。代码中的 `<eq>` 是这一公式的标签,可以在文中通过 `@eq` 来引用。
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
```typ
$ E = m c^2 $ <eq>
```,
[
$ E = m c^2 $ <eq>
]
)\
@eq2 是一个多行公式。
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
```typ
$ sum_(k=0)^n k
&= 1 + ... + n \
&= (n(n+1)) / 2 $ <eq2> ```,
[
$ sum_(k=0)^n k
&= 1 + ... + n \
&= (n(n+1)) / 2 $ <eq2>
]
)\
@eq3 到 @eq6 中给出了更多的示例。
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
```typ
$ frac(a^2, 2) $ <eq3>
$ vec(1, 2, delim: "[") $
$ mat(1, 2; 3, 4) $
$ lim_x =
op("lim", limits: #true)_x $ <eq6>
```,
[
$ frac(a^2, 2) $ <eq3>
$ vec(1, 2, delim: "[") $
$ mat(1, 2; 3, 4) $
$ lim_x =
op("lim", limits: #true)_x $ <eq6>
]
)
== 代码块
像 Markdown 一样,我们可以在文档中插入代码块:
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
````typ
```c
int main() {
printf("Hello, world!");
return 0;
}
```
````,
[
```c
int main() {
printf("Hello, world!");
return 0;
}
```
]
)\
如果想要给代码块加上标题,并在文章中引用代码块,可以使用本模板中定义的 `codeblock` 命令。其中,`caption` 参数用于指定代码块的标题,`outline` 参数用于指定代码块显示时是否使用边框。下面给出的 @code 是一个简单的 Python 程序。其中的 `<code>` 是这一代码块的标签,意味着这一代码块可以在文档中通过 `@code` 来引用。
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
````typ
#codeblock(
```python
def main():
print("Hello, world!")
```,
caption: "一个简单的 Python 程序",
outline: true,
) <code>
````,
[
#codeblock(
```python
def main():
print("Hello, world!")
```,
caption: "一个简单的 Python 程序",
outline: true,
) <code>
]
)\
@codeblock_definition 中给出了本模板中定义的 `codeblock` 命令的实现。
#codeblock(
```typ
#let codeblock(raw, caption: none, outline: false) = {
figure(
if outline {
rect(width: 100%)[
#set align(left)
#raw
]
} else {
set align(left)
raw
},
caption: caption, kind: "code", supplement: "代码"
)
}
```,
caption: [`codeblock` 命令的实现],
) <codeblock_definition>
== 参考文献
Typst 支持 BibLaTeX 格式的 `.bib` 文件,同时也新定义了一种基于 YAML 的文献引用格式。要想在文档中引用参考文献,需要在文档中通过调用 `bibliography` 函数来引用参考文献文件。下面是一个示例:
#pagebreak()
#tablex(
columns: (1fr, 1fr),
[
#set align(center)
代码
],
[
#set align(center)
渲染结果
],
```typ
可以像这样引用参考文献: @wang2010guide 和 @kopka2004guide。
#bibliography("ref.bib",
style: "ieee"
)
```,
[
可以像这样引用参考文献: @wang2010guide 和 @kopka2004guide。
]
)
注意代码中的 `"ref.bib"` 也可以是一个数组,比如 `("ref1.bib", "ref2.bib")`。 |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/linebreak_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Multiline yet inline does not linebreak
#let hrule(x) = box(line(length: x))
#hrule(80pt)$a + b \ c + d$\
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/grid/positioning.typ | typst | // Test cell positioning in grids.
--- grid-cell-show-x-y ---
#{
show grid.cell: it => (it.x, it.y)
grid(
columns: 2,
inset: 5pt,
fill: aqua,
gutter: 3pt,
[Hello], [World],
[Sweet], [Home]
)
}
#{
show table.cell: it => pad(rest: it.inset)[#(it.x, it.y)]
table(
columns: 2,
gutter: 3pt,
[Hello], [World],
[Sweet], [Home]
)
}
--- grid-cell-position-out-of-order ---
// Positioning cells in a different order than they appear
#grid(
columns: 2,
[A], [B],
grid.cell(x: 1, y: 2)[C], grid.cell(x: 0, y: 2)[D],
grid.cell(x: 1, y: 1)[E], grid.cell(x: 0, y: 1)[F],
)
--- grid-cell-position-extra-rows ---
// Creating more rows by positioning out of bounds
#grid(
columns: 3,
rows: 1.5em,
inset: 5pt,
fill: (x, y) => if (x, y) == (0, 0) { blue } else if (x, y) == (2, 3) { red } else { green },
[A],
grid.cell(x: 2, y: 3)[B]
)
#table(
columns: (3em, 1em, 3em),
rows: 1.5em,
inset: (top: 0pt, bottom: 0pt, rest: 5pt),
fill: (x, y) => if (x, y) == (0, 0) { blue } else if (x, y) == (2, 3) { red } else { green },
align: (x, y) => (left, center, right).at(x),
[A],
table.cell(x: 2, y: 3)[B]
)
--- grid-cell-position-collide ---
// Error: 3:3-3:42 attempted to place a second cell at column 0, row 0
// Hint: 3:3-3:42 try specifying your cells in a different order
#grid(
[A],
grid.cell(x: 0, y: 0)[This shall error]
)
--- table-cell-position-collide ---
// Error: 3:3-3:43 attempted to place a second cell at column 0, row 0
// Hint: 3:3-3:43 try specifying your cells in a different order
#table(
[A],
table.cell(x: 0, y: 0)[This shall error]
)
--- grid-cell-position-automatic-skip-manual ---
// Automatic position cell skips custom position cell
#grid(
grid.cell(x: 0, y: 0)[This shall not error],
[A]
)
--- grid-cell-position-x-out-of-bounds ---
// Error: 4:3-4:36 cell could not be placed at invalid column 2
#grid(
columns: 2,
[A],
grid.cell(x: 2)[This shall error]
)
--- grid-cell-position-partial ---
// Partial positioning
#grid(
columns: 3,
rows: 1.5em,
inset: 5pt,
fill: aqua,
[A], grid.cell(y: 1, fill: green)[B], [C], grid.cell(x: auto, y: 1, fill: green)[D], [E],
grid.cell(y: 2, fill: green)[F], grid.cell(x: 0, fill: orange)[G], grid.cell(x: 0, y: auto, fill: orange)[H],
grid.cell(x: 1, fill: orange)[I]
)
#table(
columns: 3,
rows: 1.5em,
inset: 5pt,
fill: aqua,
[A], table.cell(y: 1, fill: green)[B], [C], table.cell(x: auto, y: 1, fill: green)[D], [E],
table.cell(y: 2, fill: green)[F], table.cell(x: 0, fill: orange)[G], table.cell(x: 0, y: auto, fill: orange)[H],
table.cell(x: 1, fill: orange)[I]
)
--- grid-cell-position-partial-collide ---
// Error: 4:3-4:21 cell could not be placed in row 0 because it was full
// Hint: 4:3-4:21 try specifying your cells in a different order
#grid(
columns: 2,
[A], [B],
grid.cell(y: 0)[C]
)
--- table-cell-position-partial-collide ---
// Error: 4:3-4:22 cell could not be placed in row 0 because it was full
// Hint: 4:3-4:22 try specifying your cells in a different order
#table(
columns: 2,
[A], [B],
table.cell(y: 0)[C]
)
--- grid-calendar ---
#set page(width: auto)
#show grid.cell: it => {
if it.y == 0 {
set text(white)
strong(it)
} else {
// For the second row and beyond, we will write the day number for each
// cell.
// In general, a cell's index is given by cell.x + columns * cell.y.
// Days start in the second grid row, so we subtract 1 row.
// But the first day is day 1, not day 0, so we add 1.
let day = it.x + 7 * (it.y - 1) + 1
if day <= 31 {
// Place the day's number at the top left of the cell.
// Only if the day is valid for this month (not 32 or higher).
place(top + left, dx: 2pt, dy: 2pt, text(8pt, red.darken(40%))[#day])
}
it
}
}
#grid(
fill: (x, y) => if y == 0 { gray.darken(50%) },
columns: (30pt,) * 7,
rows: (auto, 30pt),
// Events will be written at the bottom of each day square.
align: bottom,
inset: 5pt,
stroke: (thickness: 0.5pt, dash: "densely-dotted"),
[Sun], [Mon], [Tue], [Wed], [Thu], [Fri], [Sat],
// This event will occur on the first Friday (sixth column).
grid.cell(x: 5, fill: yellow.darken(10%))[Call],
// This event will occur every Monday (second column).
// We have to repeat it 5 times so it occurs every week.
..(grid.cell(x: 1, fill: red.lighten(50%))[Meet],) * 5,
// This event will occur at day 19.
grid.cell(x: 4, y: 3, fill: orange.lighten(25%))[Talk],
// These events will occur at the second week, where available.
grid.cell(y: 2, fill: aqua)[Chat],
grid.cell(y: 2, fill: aqua)[Walk],
)
--- grid-exam ---
#set page(width: auto)
#show table.cell: it => {
if it.x == 0 or it.y == 0 {
set text(white)
strong(it)
} else if it.body == [] {
// Replace empty cells with 'N/A'
pad(rest: it.inset)[_N/A_]
} else {
it
}
}
#table(
fill: (x, y) => if x == 0 or y == 0 { gray.darken(50%) },
columns: 4,
[], [Exam 1], [Exam 2], [Exam 3],
..([John], [Mary], [Jake], [Robert]).map(table.cell.with(x: 0)),
// Mary got grade A on Exam 3.
table.cell(x: 3, y: 2, fill: green)[A],
// Everyone got grade A on Exam 2.
..(table.cell(x: 2, fill: green)[A],) * 4,
// Robert got grade B on other exams.
..(table.cell(y: 4, fill: aqua)[B],) * 2,
)
|
|
https://github.com/FinleyGe/typst-profile | https://raw.githubusercontent.com/FinleyGe/typst-profile/main/template/lib.typ | typst | #let container(
title: "Title",
body
) = {
[
#set align(left)
#grid(
rows: 2,
gutter: 0cm,
row-gutter: 0cm,
rect(
outset: 0pt,
width: 100%,
fill: blue,
radius: (
top: 0.1cm,
),
text(size: 16pt, fill: white, title),
),
rect(
inset: 20pt,
width: 100%,
fill: aqua,
text(size: 14pt,
grid(
columns: 1,
gutter: 0.5cm,
body,
)
),
)
)
]
}
#let pair(
key,
value
) = {
[
#grid(
columns: 2,
gutter: 0.5cm,
text(
key + ":",
size: 14pt,
),
text(
value,
size: 14pt,
)
)
]
}
#let triple(
key,
value,
unit
) = {
[
#grid(
columns: (1fr, 1fr, 1fr),
gutter: 0.5cm,
text(
key,
size: 14pt,
),
text(
value,
size: 14pt,
),
text(
unit,
size: 14pt,
)
)
]
}
#let conf(
pic: str,
name: str,
sex: str,
birthday: str,
phone: str,
email: str,
address: str,
doc) = {
set page(
paper: "a4",
)
[
#set align(center)
#set text(size: 20pt)
个人简历
]
container(
title: "基本信息",
[
#grid(
columns: (3cm, 1fr),
gutter: 0.5cm,
image(
pic,
width: 2.5cm,
height: 3.5cm,
),
grid(
gutter: 0.5cm,
grid(
columns: (1fr, 1fr),
gutter: 0.5cm,
pair(
"姓名",
name,
),
pair(
"性别",
sex
),
pair(
"生日",
birthday,
),
pair(
"电话",
phone,
),
),
pair(
"邮箱",
email,
),
pair(
"住址",
address,
),
)
)
]
)
doc
}
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/georges-yetyp/0.1.0/README.fr.md | markdown | Apache License 2.0 | # Georges Yétyp
[Version anglaise](README.md)
Modèle Typst pour les rapports de stage à Polytech (Grenoble).
[![Exemple de page de garde](thumbnail.png)](thumbnail.png)
## Utilisation
On peut soit passer par [l'application web Typst](https://typst.app/?template=georges-yetyp&version=0.1.0), ou utiliser la ligne de commande pour commencer un nouveau projet qui utilise ce modèle:
```bash
typst init @preview/georges-yetyp
```
Ensuite, il faut remplacer `logo.png` avec le logo de l'entreprise dans laquelle vous avez travailler, remplir les détails dans les paramètres de la fonction `rapport`, et commencer à écrire en dessous.
## Autres écoles
Supporter d'autres écoles du réseau Polytech devrait être relativement simple, si vous voulez réutiliser ce modèle. Il y a seulement besoin du logo de l'école (avec l'autorisation de l'utiliser). Les contributions sont les bienvenues. |
https://github.com/a-dixon/typst-template-ieee | https://raw.githubusercontent.com/a-dixon/typst-template-ieee/main/chapters/introduction.typ | typst | #import "../template.typ": *
= Introduction
// your introduction goes here
#lorem(100)
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/07-localisation/other-scripts.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/components.typ": note
#import "/template/lang.typ": devanagari
#import "/lib/glossary.typ": tr
#show: web-page-template
// ## Other complex scripts
== 其他复杂#tr[scripts]
// Designing for Indic scripts such as Devanagari is pretty much the same as any other script: know your script, do your research, read the Microsoft [script development guidelines](https://docs.microsoft.com/en-gb/typography/script-development/devanagari). In terms of OpenType Layout, these guidelines contain a helpful list of features you will need to implement, and some hints for [how you should implement them]([https://docs.microsoft.com/en-gb/typography/script-development/devanagari#feature-examples).
为天城文等印度系#tr[scripts]设计字体的步骤也类似,首先要了解这种#tr[script]并进行相关研究,阅读微软的字体开发规范@Microsoft.DevelopingDevanagari。这个指导性文件内包含一个很有用的列表,列出了你需要实现的OpenType#tr[layout]特性。它还会提供一些关于如何实现这些特性的提示和帮助。
// But this is made complicated by the fact that the shaping engine contributes its own knowledge to the process. Just as how, in Arabic, the shaping engine will automatically "call" the `init`, `medi` and `fina` features to obtain the correct glyphs for characters in certain positions, Shaping engines like Harfbuzz and Uniscribe contain code which handle various special cases required by different script systems - syllable reordering in Indic scripts, *jamo* composition in Hangul, presentation forms in Hebrew, adjustment of tone mark placement in Thai, and so on.
但现实有时候会更复杂一些,因为#tr[shaping]引擎会根据它对相关领域知识的了解程度而在#tr[shaping]流程上有所不同。比如对于阿拉伯文,#tr[shaping]引擎就可能会自动调用`init`、`medi`、`fina`特性,来将词中各个位置的#tr[character]转换为正确的#tr[glyph]。HarfBuzz 和 Uniscribe 中还会有一些代码专门用于处理各种不同书写系统的特殊需求。比如印度系#tr[scripts]需要的音节重排,韩语中谚文字母的#tr[compose],希伯来语中表达形式的字母,泰语中的音调处理等等。
// As we've already mentioned, OpenType Layout is a collaborative process, and this is especially true for complex scripts. There is a complex dance between what the shaper signals to your font and what your font signals to the shaper. To create a font which performs correctly, you need to have knowledge both of what the shaper is going to do on your behalf, and also how you are going to respond to what the shaper does.
我们重复提到过一点,OpenType的处理流程采用的是一种合作模型,对于复杂#tr[scripts]来说更是如此。这整个过程就像是一场#tr[shaper]和字体之间的复杂舞蹈,它们需要能互相理解对方发出的眼神信号并完成配合。为了能做出一个好的字体,你需要了解#tr[shaper]的工作原理,以及要怎么作才能正确配合它。
// Let's take Devanagari as an example.
我们这次用天城文作为例子。
// First, the shaper will move pre-base matras (such as the "i" vowel) before the base consonant, and any marks after the base. But what is the base consonant, and what is a mark? Here's the thing: your font helps the shaper decide.
首先,#tr[shaper]将会去掉基本辅音#tr[glyph]之前的所有matra(比如元音i)和之后的所有符号。但什么是基本辅音,什么又是符号呢?这就是互相配合的地方了,你需要告诉#tr[shaper]这些信息。
// Consider the made-up syllable "kgi" - ka, virama, ga, i-matra. Without special treatment, we can expect the vowel to apply to the base consonant "ga", like so:
考虑组成音节`kgi`的#tr[character]序列 `ka virama ga i-matra`。如果不经过特殊处理,那么元音将会附加在基本辅音`ga`上,就像这样:
#let broken = body => devanagari(text(features: ("half": 0), body))
#figure(
placement: none,
)[#block(inset: (y: 1em))[
#broken[#text(size: 5em)[क्गि]]
]]
// But if the ka takes a half-form, (which of course it should in this case) then the matra applies to the whole cluster and should appear at the beginning. By adding the half-form *feature* to your font
但是如果 `ka` 使用半字形式(在这个例子里肯定是应该使用的)的话,那么`matra`就可以覆盖整个音节,从而应该出现在最开始的位置。通过添加`half`特性,我们可以实现这一功能:
```fea
feature half {
sub ka-deva halant-deva by k-deva;
} half;
```
// you signal to the layout engine that the matra should cover the whole cluster:
通过这个特性,你就给了#tr[layout]引擎一个明确希望`matra`覆盖整个音节的信息:
#figure(
placement: none,
)[#block(inset: (top: 1em))[
#devanagari[#text(size: 5em)[क्गि]]
]]
// Again, this is something we can see clearly with the `hb-shape` utility:
我们可以用`hb-shape`工具来清晰地展示它的工作情况:
#[
#show regex(`\p{Devanagari}+`.text) : devanagari
```bash
$ hb-shape --features='-half' Hind-Regular.otf 'क्गि'
[dvKA=0+771|dvVirama=0@-253,0+0|dvmI.a05=2+265|dvGA=2+574]
$ hb-shape --features='+half' Hind-Regular.otf 'क्गि'
[dvmI=0+265|dvK=0+519|dvGA=0+574]
```
]
// So the features defined in your font will change the way that the shaper applies glyph reordering - the script development specs calls this "dynamic character properties" - and conversely, if you do *not* provide appropriate substitutions for half-forms then your glyphs may not appear in the order you expect!
所以在字体中定义的特性会改变#tr[shaper]进行#tr[glyph]重排的方式,这在字体开发中称为“动态#tr[character]属性”。反过来,如果你*没有*进行半字形式的#tr[substitution],那么可能#tr[glyph]的顺序就不符合你的预期了。
// Similar dynamic properties apply in other features too. The shaper will test each consonant-halant pair to see if the `half` or `rphf` (reph form, above-base form of the letter ra) features apply to them and create a ligature. If they do, the consonant is not considered a base.
// if the reph form is part of a mark class, it will be moved to *after* the base.
其他特性也会影响这些动态属性。#tr[shaper]会测试文本中的每个辅音-半音对,看`half`特性是否会将它们#tr[substitution]成#tr[ligature]形式。如果发生了#tr[substitution],那么这个辅音就不被认为是基本辅音。它也会尝试应用`rphf`特性,这个特性用于将`ra`#tr[glyph]转换一个基本字符之上的的连接符,称为 reph。如果这个#tr[substitution]发生了,而且结果是属于符号类的#tr[glyph],那么就会把它移动到基本#tr[character]之后。
// To see these reorderings in action, I created a dummy font which simply encodes each glyph by its Unicode codepoint. I then added the following features:
为了亲眼看到这种重排的发生,我制作了一个测试字体。这个字体将每个Unicode#tr[codepoint]的数字直接转换为#tr[glyph]。然后我添加了如下特性代码:
```fea
languagesystem DFLT dflt;
languagesystem dev2 dflt;
feature half {
# ka virama -> k
sub uni0915 uni094D by glyph01;
} half;
feature rphf {
# ra virama -> reph
sub uni0930 uni094D by glyph02;
} rphf;
```
// Let's use this to shape the syllable "rkki" (ra, virama, ka, virama, ka, i-matra):
我们用这个字体来对音节`rkki`(`ra virama ka virama ka i-matra`)进行#tr[shaping]:
#[
#show regex(`\p{Devanagari}+`.text) : devanagari
```bash
$ hb-shape Devanagari-Test.otf 'र्क्कि'
[glyph02=0+600|uni093F=2+600|glyph01=2+600|uni0915=2+600]
```
]
// The ra-virama turned into our reph form; the ka-virama turned into a half form; and the sequence was reordered to be "reph i-matra k ka". Oops, that's not quite right. We want the reph form to appear at the end of the sequence. We'll add another line to our feature file, stating that `glyph02` (our "reph" form) should be interpreted as a mark:
你会发现 `ra virama` 变成了reph,`ka virama`变成了半字 k,然后这个序列被重新排序为`reph i-matra k ka`。但是这个结果不太对,我们希望 reph 能够出现在序列的最后。这可以在特性文件里加一行代码来解决,我们需要将`glyph02`(它代表reph)视为符号:
```fea
markClass glyph02 <anchor 0 0> @reph_is_mark;
```
// How does that change things?
这会改变结果吗?
#[
#show regex(`\p{Devanagari}+`.text) : devanagari
```bash
$ hb-shape Devanagari-Test.otf 'र्क्कि'
[uni093F=0+600|glyph01=0+600|uni0915=0+600|glyph02=0+600]
```
]
// That's fixed it - the "mark" reph form is moved to the end of the syllable cluster, where we want it.
果然,它修复了上面的问题。reph符号现在在音节的末尾了,这就是我们所期望的结果。
#note[
// > If you want to get clever and have a variant reph form to match the i-matra, have a look at the [feature file](https://github.com/itfoundry/hind/blob/master/family.fea) for Indian Type Foundry's Hind family.
如果你想更智能地处理reph的各种变体,让它能和`i-matra`匹配起来,则可以参考Indian Type Foundry 的 Hind 字体源码中的特性文件@IndianTypeFoundry.HindFamily。
]
// The `rphf` and `half` features are tested against consonant-virama pairs; when a virama appears *before* a consonant, the pair is tested to see if any pre-base forms (`pref` feature), below-base forms (`blwf`) or post-base forms (`pstf`) are substituted; if so, these forms will not be considered the base consonant. Pre-base consonants identified by substitutions in the `pref` feature will also be reordered.
`rphf`和`half`特性会尝试匹配辅音-半音#tr[character]对,但如果`virama`出现在辅音之前呢?这时起作用的就会是`pref`/`blwf`/`pstf`这三个特性了,它们分别表示这个辅音应该被显示为基前/基下/基后形式。如果这些特性中的某个成功应用,那么匹配上的辅音就不被视为基本辅音。被`pref`中的#tr[substitution]命中的基前辅音也会被重新排序。
// The script development specs advise that all consonants should have a nukta form, implemented in the `nukt` feature. While you could do this by providing positioning information for the nukta on the base, the Indian Type Foundry recommends providing substitution glyphs with nuktas in order to avoid problems when forming ligatures. You will also want to provide rakaar forms using the `rkrf` feature; these will be processed after the nukta and akhand ligatures are processed, so will take the output of these features:
字体开发规范建议我们,所有的辅音都应该有对应的加点(nukta)形式,用`nukt`特性实现。你可以用提供 `nukta` 在基本辅音上的锚点位置的方式来实现它,但 Indian Type Foundry 的建议是将辅音#tr[substitution]为带有`nukta`的#tr[glyph],以避免在后续制作#tr[ligature]时的问题。你还可以使用`rkrf`特性来制作辅音连写形式,这个特性的处理顺序在`nukt`和不可分割#tr[ligature]之后,所以它得到的输入是这些特性的输出:
```fea
feature nukt {
sub ka-deva nukta-deva by kxa-deva;
}
feature rkrf {
sub ka-deva halant-deva ra-deva by kra-deva;
# 也把 nukta 特性输出的字形纳入考虑范围
sub kxa-deva halant-deva ra-deva by kxra-deva;
}
```
|
https://github.com/poopsicles/bachelors-typst-template | https://raw.githubusercontent.com/poopsicles/bachelors-typst-template/main/covenant.typ | typst | MIT License | #import "@preview/i-figured:0.2.4"
// if none, give "blank page template"
#let blankify(thing) = {
if thing == none {
align(horizon + center)[
This page has been intentionally left blank.\
// Except for the line above this.\
// And this.
// You get the idea.
]
} else {
par[#thing]
}
}
// #let x(x: "") = {
// label(x)
// figure("hi")
// }
// make a figure of code and pretend it's an image
#let code-figure(caption, code) = {
set par(justify: false, leading: 0.75em)
figure(
block(fill: luma(240), width: 90%, inset: 10pt, radius: 5pt, code),
caption: caption,
kind: image,
supplement: "Figure",
)
}
#let code-figure2(caption, code, lab) = [
// #show figure: i-figured.show-figure
#set par(justify: false, leading: 0.75em)
#let f = [
#figure(
block(fill: luma(240), width: 90%, inset: 10pt, radius: 5pt, code),
caption: caption,
kind: image,
supplement: "Figure",
) label(lab)
]
#repr(
// f.children.at(1)
i-figured.show-figure(f.children.at(1))
)
]
// make a table figure and break it across a page if need be
#let table-figure(caption, table) = {
set par(justify: false)
show figure: set block(breakable: true)
figure(table, caption: caption)
}
// convert num to string for chapter headings
#let stringify(num) = {
(
(num == "1.", "One"),
(num == [1.], "One"),
(num == "2.", "Two"),
(num == [2.], "Two"),
(num == "3.", "Three"),
(num == [3.], "Three"),
(num == "4.", "Four"),
(num == [4.], "Four"),
(num == "5.", "Five"),
(num == [5.], "Five"),
).find(x => x.at(0)).at(1)
}
// template
#let bach(
title: none,
surname: none,
names: none,
matric: none,
abstract: none,
abbreviations: none,
supervisor: none,
dedication: none,
acknowledgements: none,
reference-path: none,
date: datetime.today(),
content,
) = {
set page(paper: "a4", margin: (left: 1.25in, right: 1in, top: 1in, bottom: 1in))
// text is times new roman
set text(font: "Times New Roman", size: 12pt, hyphenate: true, kerning: true)
set par(justify: true, leading: 12.6pt)
set heading(numbering: "1.")
// show heading: set block(below: 13pt)
set enum(numbering: (it => strong[#numbering("(i)", it)]), indent: 1cm, body-indent: 0.5cm, number-align: start)
// code block font
show raw: set text(font: "FiraCode Nerd Font Mono")
// table headings bold
show table.cell.where(y: 0): set text(weight: "bold")
show table.cell: set par(leading: 0.7em)
// make tables cute
set table(stroke: (x, y) => (
left: if x > 0 {
1pt
},
top: 1pt,
bottom: 1pt,
))
// make heading refs. say chapter
set ref(supplement: it => {
if it.func() == heading {
"Chapter"
}
})
// heading sizes
show heading.where(level: 1): set text(size: 14pt)
show heading.where(level: 2): set text(size: 13pt)
show heading.where(level: 3): set text(size: 13pt)
// fix for nbhyp
show "-": sym.hyph.nobreak
// special figure numbering
show heading: i-figured.reset-counters
show figure: i-figured.show-figure
// table captions top
show figure.where(kind: table): set figure.caption(position: top)
//igure captions bold
show figure.caption: strong
show figure.caption.where(kind: "i-figured-table"): it => align(left)[#it]
// make heading be all caps (when pretty)
show heading.where(level: 1): it => [
#i-figured.reset-counters(it, return-orig-heading: false)
#set par(justify: false)
#set align(center)
#upper(it.body)
#linebreak()
#linebreak()
]
// title page
align(
horizon + center,
[
#set text(weight: "bold", size: 16pt)
#set par(justify: false)
#upper([
#title
#linebreak()
#linebreak()
#linebreak()
by
#linebreak()
#linebreak()
#linebreak()
#surname, #text(weight: "regular")[#names]
#linebreak()
(#matric)
#linebreak()
A Project Submitted to the Department of Computer and Information Sciences,
College of Science and Technology, Covenant University Ota, Ogun State.
#linebreak()
In Partial Fulfilment of the Requirements for the Award of the Bachelor of
Science (Honours) Degree in Computer Science.
#linebreak()
#date.display("[month repr:long] [year]")
])
],
)
pagebreak(weak: true)
set page(
numbering: "i",
number-align: center,
)
// certification
heading("Certification", numbering: none)
par[
I hereby certify that this project was carried out by #names #upper[#surname] in the
Department of Computer and Information Sciences, College of Science and
Technology, Covenant University, Ogun State, Nigeria, under my supervision.
]
linebreak()
linebreak()
linebreak()
linebreak()
linebreak()
linebreak()
grid(
columns: (55%, auto),
gutter: 6pt,
[*#supervisor*], align(bottom)[#line(length: 100%)],
[_Supervisor_], align(center)[*Signature and Date*],
)
linebreak()
linebreak()
linebreak()
linebreak()
linebreak()
grid(
columns: (55%, auto),
gutter: 6pt,
[*Prof. <NAME>*], align(bottom)[#line(length: 100%)],
[_Head of Department_], align(center)[*Signature and Date*],
)
pagebreak(weak: true)
// dedication
heading("Dedication", numbering: none)
[
// setting paragraph spacing in here
// so that it doesnt affect headings
#show par: set block(below: 18pt)
#blankify(dedication)
]
pagebreak(weak: true)
// acknowledgements
heading("Acknowledgements", numbering: none)
[
#show par: set block(below: 18pt)
#blankify(acknowledgements)
]
pagebreak(weak: true)
// no more dots
set outline(fill: none, title: none)
// table of contents
[
#set par(leading: 0.8em)
// add some spacing. do it the way they want
#show outline.entry.where(level: 1): it => {
let x = it.body.fields().at("text", default: "THISISAHACK")
if x == "THISISAHACK" {
x = it.body.fields().at("children")
v(13pt)
x = "Chapter " + stringify(x.at(0)) + ": " + x.at(2)
}
if x == "References" {
v(13pt)
}
link(it.element.location())[#strong(upper(x))]
box(width: 1fr)
link(it.element.location())[#strong(it.page)]
}
#show outline.entry.where(level: 2).or(outline.entry.where(level: 3)): it => {
link(it.element.location())[#it.body.fields().at("children").at(0)]
box(width: 1.5em)
link(it.element.location())[#it.body.fields().at("children").at(2)]
box(width: 1fr)
link(it.element.location())[#it.page]
}
#heading(numbering: none)[TABLE OF CONTENTS]
*CONTENT*
#box(width: 1fr)
*PAGES*
*COVER PAGE*
#box(width: 1fr)
*i*
#v(-5pt)
#outline(indent: n => if n != 1 {
box(width: 1.5em) * n
})
#pagebreak(weak: true)
]
// table of figures
[
#show table.cell.where(y: 0): set text(weight: "regular")
#set table.cell(inset: 0pt)
#set par(leading: 0.8em)
#show outline.entry: it => {
let c = []
for value in it.body.fields().at("children").slice(4) {
c += value
}
show table: set block(below: 12pt, above: 0pt)
table(
columns: (15%, 70%, 10%),
inset: 10pt,
stroke: 0pt,
align: (left, left, right),
)[#link(it.element.location())[#it.body.at("children").at(2)]][#link(it.element.location())[#c]][#link(
it.element.location(),
)[#it.page]]
v(-10pt)
}
#heading(numbering: none)[List of Figures]
#show table: set block(below: 14pt, above: 0pt)
#table(
columns: (15%, 70%, 10%),
inset: 0pt,
stroke: 0pt,
align: (left, center, right),
)[*FIGURES*][*TITLE OF FIGURES*][*PAGES*]
#i-figured.outline(target-kind: image, title: none)
#pagebreak(weak: true)
]
// list of tables
[
#show table.cell.where(y: 0): set text(weight: "regular")
#set table.cell(inset: 0pt)
#set par(leading: 0.8em)
#show outline.entry: it => {
let c = []
for value in it.body.fields().at("children").slice(4) {
c += value
}
show table: set block(below: 12pt, above: 0pt)
table(
columns: (15%, 70%, 10%),
inset: 10pt,
stroke: 0pt,
align: (left, left, right),
)[#link(it.element.location())[#it.body.at("children").at(2)]][#link(it.element.location())[#c]][#link(
it.element.location(),
)[#it.page]]
v(-10pt)
}
#heading(numbering: none)[List of Tables]
#show table: set block(below: 14pt, above: 0pt)
#table(
columns: (15%, 70%, 10%),
stroke: 0pt,
align: (left, center, right),
)[*TABLES*][*TITLE OF TABLES*][*PAGES*]
#i-figured.outline(target-kind: table, title: none)
#pagebreak(weak: true)
]
// abbreviations = ("a: dddd", "b: sjsjsjs")
// abbreviations
[
#show table.cell.where(y: 0): set text(weight: "regular")
#set table.cell(inset: 5pt)
#set par(leading: 0.8em)
#heading("Abbreviations", numbering: none)
#if abbreviations != none {
table(
columns: (1fr),
align: (left),
stroke: 0pt,
..(abbreviations.sorted()),
)
}
]
pagebreak(weak: true)
// abstract
heading("Abstract", numbering: none)
[
// #show par: set block(below: 18pt)
#set par(leading: 0.5em)
#blankify(abstract)
]
pagebreak(weak: true)
// make heading have "chapter x" on top and caps
show heading.where(level: 1): it => [
#i-figured.reset-counters(it, return-orig-heading: false)
#set par(justify: false)
#set align(center)
#linebreak()
#upper("Chapter " + stringify(counter(heading).display()))
#linebreak()
#upper(it.body)
#linebreak()
#linebreak()
]
[
#show heading: set block(below: 13pt)
#show par: set block(below: 18pt)
#set page(numbering: "1")
#content
]
// references
// make heading be smallcaps
show heading.where(level: 1): it => [
#i-figured.reset-counters(it, return-orig-heading: false)
#set par(justify: false)
#set align(center)
#upper(it.body)
#linebreak()
#linebreak()
]
pagebreak(weak: true)
bibliography(
reference-path,
title: "References",
style: "american-psychological-association",
)
}
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/meta/footnote-table.typ | typst | Apache License 2.0 | // Test footnotes in tables. When the table spans multiple pages, the footnotes
// will all be after the table, but it shouldn't create any empty pages.
---
#set page(height: 100pt)
= Tables
#table(
columns: 2,
[Hello footnote #footnote[This is a footnote.]],
[This is more text],
[This cell
#footnote[This footnote is not on the same page]
breaks over multiple pages.],
image("/files/tiger.jpg"),
)
#table(
columns: 3,
..range(1, 10)
.map(numbering.with("a"))
.map(v => upper(v) + footnote(v))
)
|
https://github.com/skylee03/skylee-homework-typst | https://raw.githubusercontent.com/skylee03/skylee-homework-typst/main/README.md | markdown | MIT License | # Skylee's Typst Homework Template
A template & library for typesetting homework assignment submissions in Typst.
## Installation
To install, download the [`skylee-hw.typ`](./skylee-hw.typ) file and import it into your Typst document.
## Usage
Refer to [`example.typ`](./example.typ) and [`example.pdf`](./example.pdf) for sample usage.
1. Import the required functions from the [`skylee-hw.typ`](./skylee-hw.typ) file:
```typst
#import "skylee-hw.typ": *
```
1. Set up the document using a show rule and the `skylee-hw()` function:
```typst
#show: skylee-hw.with(
institute: [Course institute],
course: [Course name],
session: [Course session],
title: [Assignment title],
author: [Author name],
)
```
This will generate a document header with the specified information and the current date.
### Problems
To format a problem, use the `problem()` function:
```typst
#problem[
Problem text
]
```
The problems will be automatically numbered.
### Multi-part problems
For multi-part problems, employ the `parts()` function:
```typst
#problem[
Problem text
#parts[
Part 1 text
][
Part 2 text
]
]
```
The parts will also be automatically numbered.
### Solutions
To format solutions, use the `solution()` function:
```typst
#problem[
Problem text
#solution[Solution text]
]
```
For multi-part problems, you can also use the `problem()` function under each part.
```typst
#problem[
Problem text
#parts[
Part 1 text
#solution[Part 1 solution]
][
Part 2 text
#solution[Part 2 solution]
]
]
``` |
https://github.com/elteammate/typst-compiler | https://raw.githubusercontent.com/elteammate/typst-compiler/main/deobfuscated/ir-gen.typ | typst | #import "reflection-ast.typ": *
#import "reflection.typ": *
#import "pprint.typ": *
#import "typesystem.typ": *
#import "ir-def.typ": *
//#define RECURSE $AST
//# let __a = context.ast
//# context.ast = $AST
//# context = ir_from_ast_(context)
//# if context.errors.len() > 0 { return context }
//# let __b = context.ast
//# context.ast = __a
//# $AST = __b
//#define COUNTER
//# { context.counter += 1; context.counter }!
//#define ADD_IR $INSTRUCTION
//# context.functions.at(context.current_function).code.push($INSTRUCTION)!
//#define IR $I $T $ARGS
//# {let __a = "%" + str(COUNTER[]); ADD_IR[mk_ir(__a, ir_instruction.$I, $T, $ARGS)]; __a}!
//#define ERROR $MSG
//# {context.errors.push($MSG); return context}!
//#define LABEL $NAME
//# context.functions.at(context.current_function).labels.insert(
//# $NAME, context.functions.at(context.current_function).code.len()
//# )
//#define DERIVE_FLAGS $FROM
//# if flags.terminates_function in $FROM { context.ast.terminates_function = true }!
#let ir_from_ast_(context) = {
if context.errors.len() > 0 { return context }
if context.ast.type == ast_node_type.content {
let entry_point = context.counter == 0
context.ast.ty = types.content
context.ast.val = IR[const; ptype.content; ""]
for i, piece in context.ast.fields.pieces {
RECURSE[context.ast.fields.pieces.at(i)]
if context.ast.fields.pieces.at(i).ty == types.content {
context.ast.val = IR[join; ptype.content; context.ast.val, context.ast.fields.pieces.at(i).val]
} else if context.ast.fields.pieces.at(i).ty != types.none_ {
ERROR["Type error when joining content pieces"]
}
if flags.terminates_function in context.ast.fields.pieces.at(i) {
context.ast.terminates_function = true
break
}
}
if entry_point {
IR[return_; ptype.content; context.ast.val]
}
} else if context.ast.type == ast_node_type.content_block {
context.ast.ty = types.content
RECURSE[context.ast.fields.content]
context.ast.val = context.ast.fields.content.val
} else if context.ast.type == ast_node_type.code_block {
//#define POP_SCOPE
//# let scope = context.scope_stack.pop()
//# for _, var in scope {
//# let lvar = context.functions.at(context.current_function).locals.at(var.name)
//# context.functions.at(context.current_function).stack_occupancy.at(lvar.stack_pos) = false
//# }
let block_type = types.none_
let val = none
context.scope_stack.push((:))
for i, expr in context.ast.fields.statements {
RECURSE[context.ast.fields.statements.at(i)]
block_type = type_of_join(block_type, context.ast.fields.statements.at(i).ty)
if block_type == none {
ERROR["Type error when joining statements of block"]
} else if block_type.at(0) != ptype.none_ {
if val == none {
val = context.ast.fields.statements.at(i).val
} else if context.ast.fields.statements.at(i).ty != types.none_ {
val = IR[join; block_type.at(0); val, context.ast.fields.statements.at(i).val]
}
}
if flags.terminates_function in context.ast.fields.statements.at(i) {
context.ast.terminates_function = true
break
}
}
POP_SCOPE[]
context.ast.ty = block_type
context.ast.val = val
} else if context.ast.type == ast_node_type.unknown {
context.ast.ty = types.content
context.ast.val = IR[const; ptype.content; context.ast.fields.value]
} else if context.ast.type == ast_node_type.literal_int {
context.ast.ty = types.int
context.ast.val = IR[const; ptype.int; context.ast.fields.value]
} else if context.ast.type == ast_node_type.literal_float {
context.ast.ty = types.float
context.ast.val = IR[const; ptype.float; context.ast.fields.value]
} else if context.ast.type == ast_node_type.literal_bool {
context.ast.ty = types.bool
context.ast.val = IR[const; ptype.bool; context.ast.fields.value]
} else if context.ast.type == ast_node_type.literal_string {
context.ast.ty = types.string
context.ast.val = IR[const; ptype.string; context.ast.fields.value]
//#define BINOP_ $TYPES $INSTRUCTION
//# if context.ast.fields.lhs.ty != context.ast.fields.rhs.ty or context.ast.fields.lhs.ty.at(0) not in ($TYPES) {
//# ERROR["Type error when adding expressions (op $INSTRUCTION, allowed types: $TYPES, got: " + repr(context.ast.fields.lhs.ty.at(0)) + " and " + repr(context.ast.fields.rhs.ty.at(0)) + ")"]
//# }
//# context.ast.ty = context.ast.fields.lhs.ty
//# context.ast.val = IR[$INSTRUCTION; context.ast.ty.at(0); context.ast.fields.lhs.val, context.ast.fields.rhs.val]
//# DERIVE_FLAGS[context.ast.fields.lhs]
//# DERIVE_FLAGS[context.ast.fields.rhs]
//#define BINOP $TYPES $INSTRUCTION
//# RECURSE[context.ast.fields.lhs]
//# RECURSE[context.ast.fields.rhs]
//# BINOP_[$TYPES; $INSTRUCTION]
} else if context.ast.type == ast_node_type.binary_add {
BINOP[ptype.content, ptype.string, ptype.float, ptype.int, ptype.array, ptype.dictionary; add]
} else if context.ast.type == ast_node_type.binary_sub {
BINOP[ptype.float, ptype.int; sub]
} else if context.ast.type == ast_node_type.binary_div {
BINOP[ptype.float; div]
} else if context.ast.type == ast_node_type.binary_mul {
RECURSE[context.ast.fields.lhs]
RECURSE[context.ast.fields.rhs]
if context.ast.fields.lhs.ty.at(0) in (
ptype.content,
ptype.string,
ptype.array,
) and context.ast.fields.rhs.ty.at(0) == ptype.int {
ERROR["Not implemented"]
}
BINOP_[ptype.float, ptype.int; mul]
} else if context.ast.type == ast_node_type.stmt {
if context.ast.fields.expr == none {
context.ast.ty = types.none_
} else {
RECURSE[context.ast.fields.expr]
context.ast.ty = context.ast.fields.expr.ty
if context.ast.ty != types.none_ {
context.ast.val = context.ast.fields.expr.val
}
DERIVE_FLAGS[context.ast.fields.expr]
}
} else if context.ast.type == ast_node_type.hash_expr {
RECURSE[context.ast.fields.expr]
if context.ast.fields.expr.ty == types.none_ {
context.ast.ty = types.none_
} else {
context.ast.ty = types.content
if context.ast.fields.expr.ty.at(0) == ptype.content {
context.ast.val = context.ast.fields.expr.val
} else if context.ast.fields.expr.ty.at(0) == ptype.int {
context.ast.val = IR[cast; ptype.content; context.ast.fields.expr.val]
} else {
ERROR["Not implemented (cast from " + repr(context.ast.fields.expr.ty.at(0)) + " to content)"]
}
}
DERIVE_FLAGS[context.ast.fields.expr]
} else if context.ast.type == ast_node_type.paren {
RECURSE[context.ast.fields.expr]
context.ast.ty = context.ast.fields.expr.ty
if context.ast.ty != types.none_ {
context.ast.val = context.ast.fields.expr.val
}
DERIVE_FLAGS[context.ast.fields.expr]
} else if context.ast.type == ast_node_type.ident {
let pname = context.ast.fields.name
let found = false
for scope in context.scope_stack.rev() {
if pname in scope {
let var = scope.at(pname)
if var.function == context.current_function {
context.ast.ty = var.ty
context.ast.val = IR[load; var.ty.at(0); var.name]
found = true
break
} else {
ERROR["Not implemented (captured variable from other function)"]
}
}
}
if not found {
ERROR["Variable not found: " + pname]
}
} else if context.ast.type == ast_node_type.type_cast {
RECURSE[context.ast.fields.expr]
context.ast.ty = type_from_string(context.ast.fields.type)
if context.ast.ty not in (
types.none_,
types.int,
types.float,
types.string,
types.content,
types.any,
) {
ERROR["Invalid type for cast"]
}
if context.ast.fields.expr.ty != types.int {
ERROR["Not implemented (cast from " + repr(context.ast.ty) + ")"]
}
context.ast.val = IR[cast; context.ast.ty.at(0); context.ast.fields.expr.val]
DERIVE_FLAGS[context.ast.fields.expr]
} else if context.ast.type == ast_node_type.let_ {
//#define REGISTER_LOCAL_IN_FUNCTION $NAME $TYPE
//# let stack_pos = context.functions.at(context.current_function).stack_occupancy.position(x => not x)
//# if stack_pos == none {
//# stack_pos = context.functions.at(context.current_function).stack_occupancy.len()
//# context.functions.at(context.current_function).stack_occupancy.push(true)
//# } else {
//# context.functions.at(context.current_function).stack_occupancy.at(stack_pos) = true
//# }
//# context.functions.at(context.current_function).locals.insert(
//# $NAME, (ty: $TYPE, stack_pos: stack_pos)
//# )!
//#define ADD_LOCAL $NAME $TYPE $VALUE
//# {
//# let pname = $NAME
//# let ty = $TYPE
//# let name = "@" + pname + "." + str(COUNTER[])
//# REGISTER_LOCAL_IN_FUNCTION[name; ty]
//# context.scope_stack.last().insert(pname, (
//# ty: ty,
//# function: context.current_function,
//# name: name,
//# ))
//# IR[store_fast; ty.at(0); name, $VALUE]
//# }!
if context.ast.fields.params == none {
RECURSE[context.ast.fields.expr]
ADD_LOCAL[context.ast.fields.ident.fields.name;
context.ast.fields.expr.ty; context.ast.fields.expr.val]
context.ast.ty = types.none_
} else {
let old_function = context.current_function
let pname = context.ast.fields.ident.fields.name
let name = "@" + pname + "." + str(COUNTER[])
context.functions.insert(name, mk_function())
context.current_function = name
context.scope_stack.push((:))
let params = context.ast.fields.params.fields.args
let positional_param_types = ()
for i, param in params {
if param.sink {
ERROR["Not implemented (sink parameters)"]
}
if param.key != none {
ERROR["Not implemented (keyword parameters)"]
}
if param.value.type == ast_node_type.ident {
let ty = types.any
let pref = IR[move_param; ty.at(0); i]
ADD_LOCAL[param.value.fields.name; ty; pref]
context.functions.at(name).params.push((
ty: ty,
name: param.value.fields.name,
index: i,
))
positional_param_types.push(ty)
} else if param.value.type == ast_node_type.type_cast {
let ty = type_from_string(param.value.fields.type)
let pref = IR[move_param; ty.at(0); i]
let param_name_ = param.value.fields.expr.fields.name
ADD_LOCAL[param_name_; ty; pref]
context.functions.at(name).params.push((
ty: ty,
name: param_name_,
index: i,
))
positional_param_types.push(ty)
} else {
ERROR["Invalid parameter"]
}
}
RECURSE[context.ast.fields.expr]
let ty = context.ast.fields.expr.ty
let ret_ty = context.functions.at(name).return_ty
if (flags.terminates_function not in context.ast.fields.expr
and context.ast.fields.expr.ty != types.none_) {
IR[return_; ty.at(0); context.ast.fields.expr.val]
} else if ty != ret_ty and ret_ty != none {
ERROR["Return type mismatch: " + type_to_string(ty) + " != " + type_to_string(ret_ty)]
}
context.functions.at(name).return_ty = if ty == none and ret_ty == none {
types.none_
} else if ty == none {
ret_ty
} else {
ty
}
POP_SCOPE[]
context.current_function = old_function
if context.functions.at(name).slots != (:) {
ERROR["Not implemented (slots)"]
}
let fn_object = IR[mk_function; ptype.none_; name, 0]
// todo: loading slots here
ADD_LOCAL[pname; mk_type(
ptype.function,
context.functions.at(name).return_ty,
..positional_param_types,
slotless: true, // todo: slots
positional_only: true, // todo: keyword parameters
); fn_object]
context.ast.ty = types.none_
}
} else if context.ast.type == ast_node_type.call {
RECURSE[context.ast.fields.func]
let func_ty = context.ast.fields.func.ty
if not func_ty.at(2).positional_only or not func_ty.at(2).slotless {
ERROR["Not implemented (keyword parameters or slots)"]
}
let return_ty = func_ty.at(1).at(0)
let positional_param_types = func_ty.at(1).slice(1)
let args = context.ast.fields.args.fields.args
if args.len() != positional_param_types.len() {
ERROR["Invalid number of arguments: " + str(args.len()) +
" != " + str(positional_param_types.len())]
}
let arg_vals = ()
for i, arg in args {
if arg.sink {
ERROR["Not implemented (sink parameters)"]
}
if arg.key != none {
ERROR["Not implemented (keyword parameters)"]
}
RECURSE[arg.value]
let ty = arg.value.ty
let param_ty = positional_param_types.at(i)
if ty != param_ty {
ERROR["Type mismatch in argument: got " +
type_to_string(ty) + " expected " + type_to_string(param_ty)]
}
arg_vals.push(arg.value.val)
}
let val = IR[call_fast; return_ty.at(0); context.ast.fields.func.val, ..arg_vals]
context.ast.ty = return_ty
context.ast.val = val
} else if context.ast.type == ast_node_type.return_ {
if context.ast.fields.expr == none {
ERROR["Not implemented " +
"(Valueless return is a nightmare and I hate the person who invented it)"]
} else {
RECURSE[context.ast.fields.expr]
context.ast.ty = types.none_
let prev_return_ty = context.functions.at(context.current_function).return_ty
let new_ty = context.ast.fields.expr.ty
if prev_return_ty != none and prev_return_ty != new_ty {
ERROR["Return type mismatch: previous: " +
type_to_string(prev_return_ty) + " new: " +
type_to_string(new_ty)]
}
context.functions.at(context.current_function).return_ty = new_ty
if new_ty != types.none_ {
IR[return_; new_ty.at(0); context.ast.fields.expr.val]
}
context.ast.terminates_function = true
}
} else if context.ast.type == ast_node_type.assign {
RECURSE[context.ast.fields.rhs]
//#define LOAD_IDENT $NAME $TY
//# {let found = false; let val = none; let name = $NAME
//# for scope in context.scope_stack.rev() {
//# if name in scope {
//# let var = scope.at(name)
//# if var.function == context.current_function {
//# if ($TY) != var.ty { ERROR["Type mismatch"] }
//# val = IR[load_addr; var.ty.at(0); var.name]
//# found = true
//# break
//# } else {
//# break
//# }
//# }
//# }
//# if not found {
//# ERROR["Variable not found: " + name]
//# }
//# val }!
context.ast.ty = types.none_
if context.ast.fields.lhs.type == ast_node_type.ident {
IR[store_fast; context.ast.fields.rhs.ty.at(0);
context.ast.fields.lhs.fields.name, context.ast.fields.rhs.val]
} else {
ERROR["Not implemented"]
}
DERIVE_FLAGS[context.ast.fields.rhs]
} else if context.ast.type == ast_node_type.add_assign {
//#define REWRITE_ASSIGN $op
//# context.ast = mk_node(
//# ast_node_type.assign,
//# lhs: context.ast.fields.lhs,
//# rhs: mk_node(
//# ast_node_type.$op,
//# lhs: context.ast.fields.lhs,
//# rhs: context.ast.fields.rhs,
//# ),
//# )
//# RECURSE[context.ast]
REWRITE_ASSIGN[binary_add]
} else if context.ast.type == ast_node_type.sub_assign {
REWRITE_ASSIGN[binary_sub]
} else if context.ast.type == ast_node_type.mul_assign {
REWRITE_ASSIGN[binary_mul]
} else if context.ast.type == ast_node_type.div_assign {
REWRITE_ASSIGN[binary_div]
} else if context.ast.type == ast_node_type.if_ {
RECURSE[context.ast.fields.expr]
if context.ast.fields.expr.ty != types.bool {
ERROR["If condition must be a boolean"]
}
//#define TEMP_VAR
//# ("@temp." + str(COUNTER[]))!
let temp_var = TEMP_VAR[]
let false_label = ".FALSE." + str(COUNTER[])
let end_label = ".END." + str(COUNTER[])
IR[goto_if_not; ptype.none_; context.ast.fields.expr.val, false_label]
RECURSE[context.ast.fields.block]
context.ast.ty = types.none_
if context.ast.fields.else_ == none {
if context.ast.fields.block.ty != types.none_ {
ERROR["If block can't return a value if there is no else block, returned: " +
type_to_string(context.ast.fields.block.ty)]
}
LABEL[false_label]
} else {
if (
context.ast.fields.block.ty != types.none_ and
flags.terminates_function not in context.ast.fields.block
) {
IR[store_fast; context.ast.fields.block.ty.at(0); temp_var, context.ast.fields.block.val]
context.ast.ty = context.ast.fields.block.ty
}
IR[goto; ptype.none_; end_label]
LABEL[false_label]
RECURSE[context.ast.fields.else_]
if (
context.ast.fields.else_.ty != context.ast.fields.block.ty and
flags.terminates_function not in context.ast.fields.block and
flags.terminates_function not in context.ast.fields.else_
) {
ERROR["If and else blocks must return the same type, returned: " +
type_to_string(context.ast.fields.block.ty) + " and " +
type_to_string(context.ast.fields.else_.ty)]
}
if (
context.ast.fields.else_.ty != types.none_ and
flags.terminates_function not in context.ast.fields.else_
) {
IR[store_fast; context.ast.fields.else_.ty.at(0); temp_var, context.ast.fields.else_.val]
context.ast.ty = context.ast.fields.else_.ty
}
LABEL[end_label]
if (flags.terminates_function in context.ast.fields.block
and flags.terminates_function in context.ast.fields.else_) {
context.ast.terminates_function = true
}
}
if context.ast.ty != types.none_ {
context.ast.val = IR[load; context.ast.ty.at(0); temp_var]
REGISTER_LOCAL_IN_FUNCTION[temp_var; context.ast.ty]
}
} else if context.ast.type == ast_node_type.while_ {
let start_label = ".WHILE_START." + str(COUNTER[])
let end_label = ".WHILE_END." + str(COUNTER[])
context.loop_stack.push((start: start_label, end: end_label))
// let temp_var = TEMP_VAR[]
LABEL[start_label]
RECURSE[context.ast.fields.expr]
if context.ast.fields.expr.ty != types.bool {
ERROR["While condition must be a boolean"]
}
IR[goto_if_not; ptype.none_; context.ast.fields.expr.val, end_label]
RECURSE[context.ast.fields.block]
IR[goto; ptype.none_; start_label]
LABEL[end_label]
let _ = context.loop_stack.pop()
context.ast.ty = types.none_
} else if context.ast.type == ast_node_type.continue_ {
if context.loop_stack.len() == 0 {
ERROR["Continue outside of loop"]
}
let loop = context.loop_stack.last()
IR[goto; ptype.none_; loop.start]
context.ast.ty = types.none_
} else if context.ast.type == ast_node_type.break_ {
if context.loop_stack.len() == 0 {
ERROR["Break outside of loop"]
}
let loop = context.loop_stack.last()
IR[goto; ptype.none_; loop.end]
context.ast.ty = types.none_
} else {
ERROR["Unknown AST node type"]
}
return context
}
#let ir_from_ast(ast) = ir_from_ast_((
ast: ast,
functions: (entry: mk_function()),
errors: (),
scope_stack: ((:), ),
loop_stack: (),
counter: 0,
current_function: "entry",
))
#{
let ast = parse("#let f(/*int*/x, /*bool*/y) = { [base: ]; if y { [1] } else { return [2] } };#f(5,false)")
// pprint(ast)
let ir = ir_from_ast(ast)
pprint(ir)
}
|
|
https://github.com/topdeoo/Course-Slides | https://raw.githubusercontent.com/topdeoo/Course-Slides/master/Seminar/2024-01-12/main.typ | typst | #import "../../theme/iTalk.typ": *
#import "@preview/algo:0.3.3": algo, i, d, comment, code
#show: nenu-theme.with(
short-title: "PMSCP",
short-date: "24-01-12",
short-author: "Virgil"
)
#let argmax = math.op("arg max", limits: true)
#let argmin = math.op("arg min", limits: true)
#title-slide(
title: "Learning-based Multi-Start ILS for PMSCP",
authors: (name: "凌典", email: "<EMAIL>"),
logo: image("../template/fig/nenu-logo-title.png", width: 30%),
institution: "Northeast Normal University",
date: "2024-01-12"
)
#slide(
session: "Problem Description",
title: "Formulation",
)[
#only((1, 2))[给定一个全集 $E = {e_1, e_2, dots, e_m}$
一个集合 $S = {s_1, s_2, dots, s_n}$,其中 $s_i subset.eq E and s_i != emptyset.rev$
一个集合 $G = {g_1, g_2, dots, g_q}$,其中 $q_i subset.eq S and q_i != emptyset.rev and q_i sect q_j = emptyset.rev$]
#only((2, 3, 4))[
$E$ 中的每个元素 $e_i$ 有其对应的利润 $a_i$
$S$ 中的每个元素 $s_j$ 有对应的代价 $b_j$
$G$ 中的每个元素 $g_k$ 有对应的代价 $c_k$
于是,问题描述为:找到 $S$ 的一个子集 $X^* subset.eq S, X^* != emptyset.rev$
使得目标函数 $f = $ #pin(1) $sum_(s_i in X^* and e_j in s_i) a_j - sum_(s_i in X^*) b_i - sum_(g_k in G and s_i in X^* and s_i in g_k) c_k$ #pin(2) 最大
#only((3, 4))[
#pinit-highlight(1, 2)
#only(4)[
#pinit-point-from(
pin-dx: 20pt,
pin-dy: 130pt,
body-dx: 0pt,
body-dy: 0pt,
offset-dx: 300pt,
offset-dy: 200pt,
1)[
注意,这里的所有 \
可能重复的覆盖都 \
只计算一次
]
]
]
]
#only(5)[
我们考虑如下例子,$E = {e_1, dots, e_5}, S = {s_1, dots, s_5}, G = {g_1, g_2}$,考虑一个可行解为:$X^* = {s_4}$,则 $f = a_1 + a_4 + e_5 - b_4 - c_2 = 5 + 3 + 6 - 5 - 3 = 6$
#figure(
image("fig/Instance-example.png", height:75%, fit: "contain"),
)
]
]
#slide(
session: "Related Work",
title: "Related Work"
)[
对比的三种 SOTA 算法如下:
+ MILP(CPLEX)
+ ITS
+ Parallel ITS
本文提出的算法为 LMSILS
#only(2)[
// TODO complete the parallel ITS algorithm
并行的 ITS 做法简单表述为
]
]
#slide(
session: "LMSILS",
title: "LMSILS Framework"
)[
#only(1)[
算法采用的为 学习驱动 + 多启动,考虑原本的多启动框架:
#algo(
title: "Multi-Start",
parameters: ([Instance $I$],),
)[
$X^* arrow.l emptyset.rev$\
while not terminated #i\
$X_0 arrow.l $ Initial_Solotion($I$)\
$X_0 arrow.l$ Local_Search($X_0$)\
if $f(X_0) > f(X^*)$#i\
$X^* arrow.l X_0$#d#d\
return $X^*$
]
+ _Initial_Solotion_ 替换为学习驱动的初始化算法
+ _Local_Search_ 替换为一个两阶段局部搜索算法
]
#only(2)[
整体框架如下所示:
#algo(
title: "LMSILS",
parameters: ([Instance $I$],),
)[
$I^prime arrow.l $Reduction($I$)\
$X^* arrow.l emptyset.rev$\
$(epsilon.alt, eta, beta, omega, gamma) arrow.l $Initial_Parameter() \
while not terminated #i\
$X_0 arrow.l $ Learning_Driven_Initialization($I^prime, eta, epsilon.alt$)\
$(X_0, eta, gamma) arrow.l$ Intensification_Driven_Iterated_Local_Search($X_0, omega, beta, eta, gamma$)\
if $f(X_0) > f(X^*)$#i\
$X^* arrow.l X_0$#d#d\
return $X^*$
]
]
]
#slide(
session: "LMSILS",
title: "Reduction"
)[
考虑集合 $S$ 中的元素 $s_i$
如果对于 $forall e_j in s_i$,我们有 $sum_(e_j in s_i) a_j lt.eq b_i$,换而言之,选择 $s_i$ 不会带来任何的正收益(甚至在没有计算组的代价的情况下),那么显然我们在任何情况下都不可能选择 $s_i$ ,因此,我们可以将 $s_i$ 直接删除。
#only(2)[
于是,我们可以得到如下的简化后的问题:
$I^prime = (E, S_0, G)$
]
]
#slide(
session: "LMSILS",
title: "Learning Driven Initialization"
)[
#only((1, 2))[
文章中的学习,指代从历史解中学习出更可能在最优解中的那部分
我们通过一个向量 $eta in bb(R)^(|S_0|)$ 来实现,其中,向量的分量 $eta_i$ 表示 $s_i$ 在最优解#footnote[在论文中,其表述为 “下一次的初始解” ]中的概率(此概率最开始均为 $0.5$),概率会通过在局部搜索中进行更新。
]
#only(2)[
而另一个参数 $epsilon.alt$ 用于控制贪心的概率,我们根据此概率进行贪心的选择顶点进入解集中,从而初始化一个解。
具体来说,初始化的算法如下所示:
]
#only((3, 4))[
#algo(
title: "Learning_Driven_Initialization",
parameters: ([Instance $I^prime$, $eta$, $epsilon.alt$],),
)[
$X_0 arrow.l emptyset.rev$\
$S^prime arrow.l S_0$\
while $S^prime != emptyset.rev$ #i\
$"index"$ = -1 \
if #pin(3) rand(0, 1) < $epsilon.alt$#pin(4)#i \
index = $op("arg max",
limits: #true)_limits(i in [|S^prime|]) eta_i$#d \
else #i\
index = rand(1, $|S^prime|$)#d\
$S^prime arrow.l S^prime - {s_"index"}$\
if #pin(5)$sum_(e_i in s_("index") and e_i in.not union.big_(s_l in X_0)s_l) a_i - b_("index") > 0$ && rand(0, 1) < $eta_("index")$ #pin(6) #i\
$X_0 arrow.l X_0 union {s_("index")}$#d#d\
]
#pinit-highlight(3, 4)
#only(4)[
#pinit-highlight(5, 6, fill: rgb(0, 0, 255, 20))
]
]
#only(5)[
加入解集的条件为:
+ $sum_(e_i in s_("index") and e_i in.not union.big_(s_l in X_0)s_l) a_i - b_("index") > 0$
+ rand(0, 1) < $eta_("index")$
注意条件1所计算的是 *新* 被覆盖的元素 $e_i$ 所带来的利润
本质上来说是以 $eta_("index")$ 的概率将为解集带来正收益的 $s_("index")$ 加入到解集中
显然,构造初始解的时间复杂度为 $cal(O)(n^2)$
]
]
#slide(
session: "LMSILS",
title: "ILS"
)[
#only(1)[
构造完初始解后,进入到迭代局部搜索的过程,这个过程通过迭代执行一个两阶段的禁忌局部搜索算法完成
整体的框架如下所示, 其中,$omega$ 表示迭代搜索的深度,$beta$ 表示禁忌搜索的深度,$gamma$ 表示扰动系数
]
#only(2)[
#algo(
title: "ILS",
parameters: ([$X_0$, $omega$, $beta$ ,$eta$, $epsilon.alt$, $gamma$],),
breakable: true,
row-gutter: 4mm,
)[
$X arrow.l X_0$\
$X_"best" arrow.l X$\
non_improve $arrow.l 0$\
while non_improve < $omega$#i\
$X arrow.l $ TwoPhase_LocalSearch(X, $beta$)\
if $f(X) > f(X_"best")$#i\
Update $eta "and" gamma$\
$X_"best" arrow.l X$\
non_improve $arrow.l 0$#d\
else #i\
non_improve $arrow.l$ non_improve + 1#d\
$X arrow.l$ Perturbation($X_"best", gamma$)
]
]
#only(3)[
可以发现,主要问题集中在:
+ 两阶段的局部搜索过程
+ 如何更新 $eta$ 和 $epsilon.alt$
+ 如何做扰动
]
]
#slide(
session: "LMSILS",
title: "Two Phase Local Search"
)[
#only(1)[
我们首先引入一个算子 _Flip_,$"Flip"(s_i)$ 表示为将集合 $S_0$ 中的 $s_i$ 的状态进行反转,也就是说:
如果 $s_i$ 在解集 $X$ 中,那么我们将其移除,否则,我们将 $s_i$ 加入到解集 $X$ 中
]
#only((1, 2))[
我们将通过 _Flip_ 算子变化后的解集用 $X xor "Flip"(X, i)$ 来表示
]
#only((2, 3))[
那么,一个可行解的邻域就可以显然的表示为:
$cal(N)(X) = {X xor "Flip"(X, i), s_i in S_0}$
于是,我们可以得到如下的两阶段局部搜索算法#footnote[注意,这里是分阶段进行的,我们首先进行翻转,然后再进行交换,而不是两个过程交替进行]:
+ 从翻转一次的邻域 $cal(N)_1(X)$ 中找到目标函数值最大的一个可行解,记为 $X^prime$,并更新最优解(如果 $X^prime$ 更优的话)
+ 从翻转两次的领域中 #pin(1)$cal(N)_2(X)$ #pin(2) 中找到目标函数值最大的一个可行解,记为 $X^prime$,并更新最优解(如果 $X^prime$ 更优的话)
#only(3)[
#pinit-highlight(1, 2)
这里的 $cal(N)_2(X)$ 可以看作是一次交换的过程,使用 _Flip_ 算子表示为: $cal(N)_2(X) = {X xor "Flip"(X, i) xor "Flip"(X, j), s_i in X, s_j in.not X}$
]
]
#only(4)[
#set text(size: .9em)
#grid(
columns: (50%, 50%),
column-gutter: 5mm,
algo(
title: "TwoPhase_LocalSearch",
parameters: ([$X$, $beta$],),
)[
$X_b arrow.l X$\
non_improve $arrow.l 0$\
while non_improve = 0#i\
non_improve $arrow.l 1$\
$X arrow.l $ Flip_Tabu_Search($X$, $beta$)\
$X arrow.l $ Swap_Search($X$)\
if $f(X) > f(X_b)$#i\
$X_b arrow.l X$\
non_improve $arrow.l 0$#d#d\
],
text(size: .8em)[
#grid(
rows: (70%, 30%),
algo(
title: "Flip_Tabu_Search",
parameters: ([$X$, $beta$],),
)[
$X_b arrow.l X$\
non_improve $arrow.l 0$\
while non_improve $lt.eq beta$#i\
$X^prime arrow.l cal(N)_1(X)$\
$X arrow.l X^prime$\
Update tabu list\
if $f(X) > f(X_b)$#i\
$X_b arrow.l X$\
non_improve $arrow.l 0$#d\
else#i\
non_improve $arrow.l$ non_improve + 1#d#d\
],
algo(
title: "Swap_Search",
parameters: ([$X$],),
)[
non_improve $arrow.l 1$\
while non_improve = 0 #i\
$X^prime arrow.l cal(N)_2(X)$\
if ...
]
)
]
)
]
#only(5)[
问题在与:
+ 禁忌搜索是如何工作的
+ 如何减小时间复杂度
]
]
#slide(
session: "LMSILS",
title: "Tabu Search"
)[
#only(1)[
我们只在第一阶段存在禁忌搜索,而这里有两种禁忌搜索策略:
+ 搜索深度的禁忌
+ 禁忌列表的禁忌
对于深度的禁忌,十分容易理解,本质上就是多少次解没有更新,那么直接退出。
]
#only(2)[
第二种禁忌显然是为了避免我们重复访问邻域的解,于是,我们使用一个向量 $T in RR^n$,这个向量用于记录哪些子集已经使用过 _Flip_ 算子,其中:
$T_i = cases(
"Iter" + "rand"(0, 5) ", if" s_i "is added to " X,
"Iter" + |S_0| ", if" s_i "is removed from " X,
)$
这里,Iter 为当前的迭代数(也就是 `non_improve` 的值)
禁忌策略为:如果当前的 $"Iter" < T_i$,除非翻转 $s_i$ 所获得的可行解比 $X_"best"$ 更好,否则 $s_i$ 被禁忌。
]
]
#slide(
session: "LMSILS",
title: "Fast Evaluation"
)[
#only(1)[
我们如何快速计算出 _Flip_ 算子为目标函数所带来的变化?
在这里,我们维护一个向量 $delta in RR^n$,其中 $delta_i$ 表示 $s_i$ 在 _Flip_ 算子下的变化,也就是说:
$Delta f("Flip"(X, i)) = f(X xor "Flip"(X, i)) - f(X) = delta_i$
其计算公式为:
]
#only((1, 2))[
$delta_i = cases(
sum_(e_j in s_i, |R_j sect X| = 0)a_j - b_i - theta_1 times c_k ", if" s_i in.not X,
-sum_(e_j in s_i, |R_j sect X| = 1)a_j + b_i + theta_2 times c_k ", if" s_i in X,
)$
而 $theta_1 = cases(
1 ", if" g_k sect X = emptyset.rev,
0 ", otherwise"
)$, $theta_2 = cases(
1 ", if " g_k sect X = s_i,
0 ", otherwise"
)$, $e_j$ 表示 $s_i$ 中的元素,$R_j$ 表示含有 $e_j$ 的 $s_i$ 的并
]
#only(2)[
简而言之,当我们需要对 $s_i$ 进行一次翻转操作时,我们做如下操作:
+ $delta_i = -delta_i$
+ $forall s_j in g_k:(s_i in g_k)$,$delta_j = cases(
delta_j - c_k ", if " (X sect g_k = {s_i} and s_i in X) or (X sect g_k = {s_j} and s_i in.not X),
delta_j + c_k ", if " (X sect g_k = {s_i, s_j} and s_i in X) or (X sect g_k = emptyset.rev and s_i in.not X),
)$
+ 对所有与 $s_i$ 中有相同元素 $e_j$ 的集合 $s_l$,
$delta_l = cases(
delta_l - a_j ", if " (X sect R_j = {s_i} and s_i in X) or (X sect R_j = {s_l} and s_i in.not X),
delta_l + a_j ", if " (X sect R_j = {s_l, s_i} and s_i in X) or (X sect R_j = emptyset.rev and s_i in.not X),
)$
]
#only(3)[
可以发现,维护 $delta$ 的时间复杂度为 $cal(O)(n times m)$
]
]
#slide(
session: "LMSILS",
title: "Update Learning Parameters"
)[
#only((1, 2))[
#grid(
columns: 2,
column-gutter: 5em,
text(size: .9em)[
我们回到算法框架:
#only(2)[
当结束两阶段局部搜索后\
如果我们得到了一个更好的解\
$X$,我们根据如下规则更新\
$eta, epsilon.alt$
其中 $eta_i$ 表示下一次初始化时\
$s_i$ 在解中的概率
$gamma$ 表示扰动系数
]
],
text(size: .9em)[
#algo(
title: "ILS",
parameters: ([$X_0$, $omega$, $beta$ ,$eta$, $epsilon.alt$, $gamma$],),
breakable: true,
row-gutter: 4mm,
)[
$X arrow.l X_0$\
$X_"best" arrow.l X$\
non_improve $arrow.l 0$\
while non_improve < $omega$#i\
$X arrow.l $ TwoPhase_LocalSearch(X, $beta$)\
if $f(X) > f(X_"best")$#i\
Update $eta "and" gamma$\
$X_"best" arrow.l X$\
non_improve $arrow.l 0$#d\
else #i\
non_improve $arrow.l$ non_improve + 1#d\
$X arrow.l$ Perturbation($X_"best", gamma$)
]
]
)
]
#only(3)[
更新的原理为:如果 $X$ 优于 $X_"best"$,则提高当前解 $X$ 中 $s_i$ 被选中的概率:
#set align(center)
$eta_i = cases(
phi.alt_1 + (1 - phi.alt_1) times eta_i ", if" s_i in X and s_i in X_"best",
phi.alt_2 + (1 - phi.alt_2) times eta_i ", if" s_i in X and s_i in.not X_"best",
(1 - phi.alt_1) times eta_i ", if" s_i in.not X and s_i in.not X_"best",
(1 - phi.alt_2) times eta_i ", if" s_i in.not X and s_i in X_"best",
)$
#set align(left)
其中,$phi.alt_1 = 0.2, phi.alt_2 = 0.3$,并且,我们为此概率添加了平滑技术,用以避免历史信息的过度影响:
#set align(center)
$eta_i = cases(
phi.alt_3 + (1 - phi.alt_3) times eta_i ", if" eta_i < 1- alpha,
(1 - phi.alt_3) times eta_i ", if" eta_i > alpha
)$
#set align(left)
这里的 $alpha = 0.95, phi.alt_3 = 0.3$
]
#only(4)[
关于扰动系数的更新,首先我们先看扰动的过程是什么样的
]
]
#slide(
session: "LMSILS",
title: "Perturbation"
)[
#only((1, 2, 4, 6))[文中提出了两种扰动类型:
+ `Set_Perturbation`
+ `Group_Perturbation`
]
#only(2)[
`Set_Perturbation` 的做法为:
+ 令 $X = X_("best")$
+ 以概率 $p = 0.3$ 删除最优解 $X$ 的每个元素 $s_i$,设 $h$ 表示被删除的元素个数
+ 随机从 $S_0$ 中选择 $h$ 个元素,如果选择的元素不在 $X$ 中的话,则将其加入,否则跳过。
]
#only(3)[
#figure(
image("fig/set_perturbation.png", height: 80%, fit: "contain"),
caption: [$X_("best") = {s_2, s_3, s_5, s_6} arrow.r X = {s_2, s_3, s_6, s_9}$]
)
]
#only(4)[
`Group_Perturbation` 首先定义集合 $Z = {g_k|g_k sect X eq.not emptyset.rev, g_k in G}$
+ 令 $X = X_("best")$
+ 从 $Z$ 中随机选择 $max(p times |Z|, 1)$ 个元素,我们用 $z_j$ 来表示这些组
+ 假设 $z_j sect X_("best") = s_i$,那么我们从 $X$ 中删除这些元素
+ 随机从 $G - Z$ 中选择 $max(p times |Z|, 1)$ 个组
+ 从这些组中,随机翻转 $floor((|X_"best"|)/(|Z|))$ 个元素 $s_k$
过程如下图所示
]
#only(5)[
#figure(
image("fig/group_perturbation.png", height: 80%, fit: "contain"),
caption: [$Z = {g_1, g_2} arrow.r "choose" g_1 arrow.r "choose" G-Z = {g_3}$]
)
]
#only(6)[
算法表示为:
#algo(
title: "Perturbation",
parameters: ([$X$, $gamma = {gamma_1, gamma_2}$],),
)[
if rand(0, 1) < $gamma_1$ #i\
$X arrow.l$ Set_Perturbation($X_"best"$)#d\
else #i\
$X arrow.l$ Group_Perturbation($X_"best"$)#d\
]
这里的 $sum_(t=1)^2 gamma_t = 1$,最开始时 $gamma_t = 1/2$
]
]
#slide(
session: "LMSILS",
title: "Update Perturbation Ratio"
)[
#only(1)[
而对于扰动系数 $gamma in RR^2$,其更新规则如下:
#set align(center)
$gamma_t = (d_0 + d_t) / (2 times d_0 + d_1 + d_2)$
#set align(left)
其中 $t in {1, 2}$ 是扰动策略的编号,$d_0$ 为适应参数,$d_t$ 是采用第 $t$ 种扰动策略更新 $X_"best"$ 的次数
文中,$d_0 = 50$
]
]
#slide(
session: "LMSILS",
title: "Experimental Evaluation"
)[
#only(1)[
实例:
+ 10个小型实例($A^*, B^*$), $|E| = 1000, |S| in [3493, 82635], |G| in [100, 300]$
+ 10个中型实例($C^*, D^*$),$|E| = 5192, |S| in {6633, 117274}, |G| in {31, 62}$
+ 10个大型实例($E^*, F^*$),$|E| = 15625, |S| in [10325, 462666], |G| in {96, 100}$
对比算法为:
+ MILP(CPLEX)
+ ITS
+ Parallel ITS
+ LMSILS(this paper)
]
#only(2)[
#figure(
image("fig/small-instance.png", height: 80%, fit: "contain"),
caption: [$A^*, B^*$ 小型实例]
)
]
#only(3)[
#figure(
image("fig/medium-instance.png", height: 80%, fit: "contain"),
caption: [$C^*, D^*$ 中型实例]
)
]
#only(4)[
#figure(
image("fig/big-instance.png", height: 80%, fit: "contain"),
caption: [$E^*, F^*$ 大型实例]
)
]
]
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/mitex/0.1.0/examples/example.typ | typst | Apache License 2.0 | #import "../lib.typ": *
#set page(width: 500pt, height: auto, margin: 1em)
#assert.eq(mitex-convert("\alpha x"), "alpha x ")
Write inline equations like #mi("x") or #mi[y].
Also block equations (this case is from #text(blue.lighten(20%), link("https://katex.org/")[katex.org])):
#mitex(`
f(x) = \int_{-\infty}^\infty
\hat f(\xi)\,e^{2 \pi i \xi x}
\,d\xi
`)
|
https://github.com/SidneyLYZhang/learnTypst | https://raw.githubusercontent.com/SidneyLYZhang/learnTypst/main/Documentation/Sources/011_guide-for-latex-users.typ | typst | #set text(font:("Consolas", "Source Han Sans SC"))
#set text(lang: "zh")
#show emph: text.with(font: ("Linux Libertine","STKaiti"))
#show link: text.with(fill: color.blue)
= LaTeX用户指南
|
|
https://github.com/Personal-Data-Acquisition/PDA_paperwork | https://raw.githubusercontent.com/Personal-Data-Acquisition/PDA_paperwork/main/SDP/sdp.typ | typst | = Software Development Process(SDP)
#strong[Authors:] <NAME>, <NAME>, <NAME>, <NAME>
#strong[DATE:] 2023-11-16
= Principles
- We will respond to asynchronous communication within 24 hours
- We will be at meetings on time and pay attention
- All changes need to be isolated to their own git branch
- Each work item need a corresponding GitHub issue
- Pull Requests have to be reviewed by at least one team member
- We will use a kanban board to continuously work on the backlog
- Once a work item is complete, a pull request is created
- Blocks need to be discussed as soon as possible
= Process
Task Selection: \* Kanban style \* Select highest priority item within
your role’s domain
To Solve an Issue and Meet Acceptance Criteria: 1. Write failing tests.
2. Write code to pass tests. 3. Repeat. 4. Open a pull-request and merge
== Steps in software development
+ Create a github issue/milestone.
+ Assign github task/issue.
+ Create fork of repo.
+ Write tests using the test framework.
+ Push the tests to the fork (optional).
+ Write Code to pass the tests.
+ Test the code.
+ Push to the fork repo.
+ Create a pull request with description.
+ Get approval for the PR(pull request).
== Goals & Objectives
Develop a personal data acquisition system that records all the data a
user might want, and is cheap and easy to set up and use. \* Record data
on acceleration, force, position, etc. \* Minimal setup \* Can be hooked
up to bike, go-kart, etc.
== Project Scope
- Design of simple UI to display data.
- Design of hardware/schematics for system.
- Firmware for sensor modules in rust.
- SBC with rust software to store/log sensor data over CAN.
= Roles
#figure(
align(center)[#table(
columns: 3,
align: (col, row) => (auto,auto,auto,).at(col),
inset: 6pt,
[ROLE], [PERSON], [RESPONSIBILITIES],
[UI],
[Blake],
[Develops the web page front end],
[SBC/SW],
[Aidian],
[Develop logic to relay sensor data to UI],
[FIRMWARE],
[Patrick],
[Develop firmware for microcontrollers],
[HARDWARE],
[Jake],
[Design schematics, wiring diagrams & PCB files],
)]
)
These are the general outlines for the four different roles in the
project. We have a verbal agreement at the moment that we will help out
with parts of the project outside our roles as needed.
= Tooling
#figure(
align(center)[#table(
columns: 2,
align: (col, row) => (auto,auto,).at(col),
inset: 6pt,
[Purpose], [Name],
[Version Control],
[Git],
[Project Management],
[GitHub Projects],
[Documentation],
[Rustdocs & MD],
[Test framework],
[Rust & Cmocka],
[Editor],
[ANY],
[Schematics & PCB],
[KiCAD],
[Communication],
[Discord/Teams/Email],
[],
[],
)]
)
== Version Control
Git will allow our team to track changes in the projects files over
time. Also prevents the loss of work from hardware failures.
== Project Management
GitHub projects is integrated into github organizations as well as git.
The project management software makes the collaboration between
developers easy and will make tracking milestones and issues for the
entire project across multiple repositories a possibility.
== Documentation
Documentation will primaily be done through the built-in rust-docs
feature. This is accesiable via the CLI(command line interface) tooling.
This will encapsulate how the code itself and any interfaces are
documented.
Because the documentation is genreated as part of the code this will
ensure that up to date and accurate documentatio is always availble.
Secondary documentation meant for non-developers will be done using a
combination of markdown and LaTex where needed. This will be availble
usally in a PDF format.
== Schematics & PCB
The KiCAD program gives access to the schematics and PCB designs to all
team members due to the software begin free and open-source.
It will allow us to comment, label and design the needed circuits for
the physical hardware of the system; providing a good troubleshooting
resource as well.
== Communication
#strong[Discord:] \* Used to coordinate team meetings. \* To share
ideas/brainstorm \* give updates on project.
#strong[Teams:] \* TA meetings.
#strong[GITHUB:] \* To discuss project issues. \* share documentation.
= Definition of Done(DOD)
- Acceptance criteria all satisfied by code changes
- Changes have been merged to master after completing the Pull Request
Process
- A completed Pull Request has at least one approval and no marks for
"Needs Work"
- All tests pass with changes implemented and no reversion is required
- Relevant documentation for the feature has been updated
- Discussion points are prepared for next meeting
== TESTING
#strong[Rust:]
The testing for all code repositories will be done using a testing
harness or framework. For rust this takes the form of the `cargo test`
command, which is part of the package managment system(tool-chain).
These tests will be used as one of acceptance critera for a branch to be
pulled into the main branch.
#strong[C:]
Some libraries or areas where the use of C code is needed we plan to use
cmocka as the unit testing framework. This combined with Cmake as the
build system will give us a host agnostic development cycle.
=== Quality Assurance
Quality assurance will mostly be handled by adhearance to style
standards enforced by the lanuages LSP(language server protocol)
servers. The two that will see extensive use in this project being:
+ Rust-analyzer
+ clangd
=== Feedback
Feedback on the work done will take place in the github projects. The
issues and discussion boards are the main locations for this, with the
weekly meetings and discord being a secondary and informal medium for
minor feedback.
= Release Cycle
For the moment we will used semantic versioning with the standard
Major.minor.patch format. This will help when it comes to dealing with
any major changes that break APIs.
== Contingency Plans
Feedback can be shared during weekly standup with the TA, or over
Discord if they are more time-sensitive, after which it should be
reviewed by the whole team, and then incorporated. Changes to the whole
process will require more comprehensive feedback and approval from the
team before going into effect, after which related documents should be
modified as soon as possible.
In the event of unexpected challenges, the team should be notified
immediately, and if serious enough should be brought up with the TA,
project partner or instructor, otherwise they should be brought up
during regular meetings.
= Timeline
- 12/15/2023: Version 0 complete with breadboard organized hardware and
visual UI elements
- 03/22/2023: Version 1 complete with functionality between firmware,
SBC, and UI
= Environments
#figure(
align(center)[#table(
columns: 5,
align: (col, row) => (auto,auto,auto,auto,auto,).at(col),
inset: 6pt,
[Environment], [Infrastructure], [Deployment], [What is it for?],
[Monitoring],
[Production],
[Github releases],
[Release],
[Packaging install files.],
[N/A],
[Staging],
[Github actions],
[],
[],
[Github Pull requests],
[Development],
[Local],
[Github commits],
[Development and unit tests of microcontroller-based sensors],
[Manual],
)]
)
|
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/components/TypstTemplate/math.typ | typst | #import "@preview/quick-maths:0.1.0": shorthands
#import "@preview/mitex:0.2.4": *
// 以类似格式添加符号缩写
#let shorthand = shorthands.with(
($+-$, $plus.minus$),
($|-$, math.tack),
($=<$, $<=$), // =< becomes '≤'
($<==$, math.arrow.l.double), // Replaces '≤',似乎需要某一边有东西才能正常工作,原因未知
($~$, $med$),
)
// 文本运算符
#let argmax = math.op("argmax", limits: true)
#let argmin = math.op("argmin", limits: true)
#let dcases(..args) = math.cases(..args.pos().map(math.display)) // cases with display style
#let cnum(num) = str.from-unicode(9311 + num) // 带圈数字
// 以类似格式添加文本缩写
#let le = $<=$
#let ge = $>=$
#let Pi = $product$ // big pi as product
#let infty = $infinity$
#let int = $integral$
#let wave = $tilde$ // alternative to ~
// $wave$, $prop$, $approx$
#let na = $nabla$
#let di = $dif$
#let pa = $diff$ // partial
#let ij = $i j$
#let ji = $j i$
// 希腊字母
#let r1 = $rho_1$
#let r2 = $rho_2$
#let si = $sigma$
#let Si = $Sigma$
#let s1 = $sigma_1$
#let s2 = $sigma_2$
#let de = $delta$
#let De = $Delta$
#let d1 = $delta_1$
#let D1 = $Delta_1$
#let d2 = $delta_2$
#let D2 = $Delta_2$
#let al = $alpha$
#let a1 = $alpha_1$
#let a2 = $alpha_2$
#let an = $alpha_n$
#let aN = $alpha_N$
#let ta = $tau$
#let th = $theta$
#let t1 = $theta_1$
#let t2 = $theta_2$
#let tn = $theta_n$
#let tN = $theta_N$
#let ep = $epsilon$
#let ep1 = $epsilon_1$
#let ep2 = $epsilon_2$
#let ga = $gamma$
#let Ga = $Gamma$
#let g1 = $gamma_1$
#let g2 = $gamma_2$
#let la = $lambda$
#let l1 = $lambda_1$
#let l2 = $lambda_2$
#let ln = $lambda_n$
#let lN = $lambda_N$
#let La = $Lambda$
#let L1 = $Lambda_1$
#let L2 = $Lambda_2$
#let Ln = $Lambda_n$
#let LN = $Lambda_N$
#let p1 = $pi_1$
#let p2 = $pi_2$
#let pn = $pi_n$
#let pN = $pi_N$
// bold, cal, hat, tilde, arrow letters
// bold and cal letters
#let bx = math.bold("x")
#let by = math.bold("y")
#let bz = math.bold("z")
#let bs = math.bold("s")
#let bt = math.bold("t")
#let bu = math.bold("u")
#let bv = math.bold("v")
#let bw = math.bold("w")
#let ba = math.bold("a")
#let bb = math.bold("b")
#let bc = math.bold("c")
#let bd = math.bold("d")
#let be = math.bold("e")
#let bf = math.bold("f")
#let bg = math.bold("g")
#let bh = math.bold("h")
#let bi = math.bold("i")
#let bj = math.bold("j")
#let bk = math.bold("k")
#let cN = math.cal("N")
#let cL = math.cal("L")
#let cD = math.cal("D")
// letters with hat
#let hx = $hat(x)$
#let hy = $hat(y)$
#let hz = $hat(z)$
#let hs = $hat(s)$
#let ht = $hat(t)$
#let hu = $hat(u)$
#let hv = $hat(v)$
#let hw = $hat(w)$
#let ha = $hat(a)$
#let hb = $hat(b)$
#let hc = $hat(c)$
#let hd = $hat(d)$
#let he = $hat(e)$
#let hf = $hat(f)$
#let hg = $hat(g)$
#let hh = $hat(h)$
#let hi = $hat(i)$
#let hj = $hat(j)$
#let hk = $hat(k)$
// letters with tilde
#let tx = $tilde(x)$
#let ty = $tilde(y)$
#let tz = $tilde(z)$
#let ts = $tilde(s)$
#let tt = $tilde(t)$
#let tu = $tilde(u)$
#let tv = $tilde(v)$
#let tw = $tilde(w)$
// #let ta = $tilde(a)$ // 'ta' used for tau
#let tb = $tilde(b)$
#let tc = $tilde(c)$
#let td = $tilde(d)$
#let te = $tilde(e)$
#let tf = $tilde(f)$
#let tg = $tilde(g)$
// #let th = $tilde(h)$ // 'th' used for theta
#let ti = $tilde(i)$
#let tj = $tilde(j)$
#let tk = $tilde(k)$
// letters with arrow
#let ax = $arrow(x)$
#let ay = $arrow(y)$
#let az = $arrow(z)$
// #let as = $arrow(s)$ // 'as' is a keyword
#let at = $arrow(t)$
#let au = $arrow(u)$
#let av = $arrow(v)$
#let aw = $arrow(w)$
#let aa = $arrow(a)$
#let ab = $arrow(b)$
#let ac = $arrow(c)$
#let ad = $arrow(d)$
#let ae = $arrow(e)$
#let af = $arrow(f)$
#let ag = $arrow(g)$
#let ah = $arrow(h)$
#let ai = $arrow(i)$
#let aj = $arrow(j)$
#let ak = $arrow(k)$
#let x1 = $x_1$
#let x2 = $x_2$
// #let xi = $x_i$ // 'xi' used for xi
#let xj = $x_j$
#let xn = $x_n$
#let xN = $x_N$
#let y1 = $y_1$
#let y2 = $y_2$
#let yi = $y_i$
#let yj = $y_j$
#let yn = $y_n$
#let yN = $y_N$
#let z1 = $z_1$
#let z2 = $z_2$
#let zi = $z_i$
#let zj = $z_j$
#let zn = $z_n$
#let zN = $z_N$
// #let s1 = $s_1$
// #let s2 = $s_2$
// #let sn = $s_n$
// #let sN = $s_N$
// #let t1 = $t_1$
// #let t2 = $t_2$
// #let tn = $t_n$
// #let tN = $t_N$ // 's' and 't' used for sigma and tau
#let u1 = $u_1$
#let u2 = $u_2$
#let ui = $u_i$
#let uj = $u_j$
#let un = $u_n$
#let uN = $u_N$
#let v1 = $v_1$
#let v2 = $v_2$
#let vi = $v_i$
#let vj = $v_j$
#let vn = $v_n$
#let vN = $v_N$
#let w1 = $w_1$
#let w2 = $w_2$
#let wi = $w_i$
#let wj = $w_j$
#let wn = $w_n$
#let wN = $w_N$
// #let a1 = $a_1$
// #let a2 = $a_2$
// #let an = $a_n$
// #let aN = $a_N$ // 'a' used for alpha
#let b1 = $b_1$
#let b2 = $b_2$
// #let bi = $b_i$
// #let bj = $b_j$ // b is used for bold
#let bn = $b_n$
#let bN = $b_N$
#let c1 = $c_1$
#let c2 = $c_2$
#let ci = $c_i$
#let cj = $c_j$
#let cn = $c_n$
#let cN = $c_N$
// #let d1 = $d_1$
// #let d2 = $d_2$
// #let dn = $d_n$
// #let dN = $d_N$ // 'd' used for delta
#let e1 = $e_1$
#let e2 = $e_2$
#let ei = $e_i$
#let ej = $e_j$
#let en = $e_n$
#let eN = $e_N$
#let f1 = $f_1$
#let f2 = $f_2$
#let fi = $f_i$
#let fj = $f_j$
#let fn = $f_n$
#let fN = $f_N$
// #let g1 = $g_1$
// #let g2 = $g_2$
// #let gn = $g_n$
// #let gN = $g_N$ // 'g' used for gamma
#let h1 = $h_1$
#let h2 = $h_2$
#let hi = $h_i$
#let hj = $h_j$
#let hn = $h_n$
#let hN = $h_N$
#let i1 = $i_1$
#let i2 = $i_2$
#let ii = $i_i$
// #let ij = $i_j$ 'ij' used for i j with backspace between
// #let in = $i_n$ // 'in' is a keyword
#let iN = $i_N$
#let j1 = $j_1$
#let j2 = $j_2$
// #let ji = $j_i$ // 'ji' used for j i with backspace between
#let jj = $j_j$
#let jn = $j_n$
#let jN = $j_N$
#let k1 = $k_1$
#let k2 = $k_2$
#let ki = $k_i$
#let kj = $k_j$
#let kn = $k_n$
#let kN = $k_N$
|
|
https://github.com/MatheSchool/typst-g-exam | https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/src/g-sugar.typ | typst | MIT License | #import "./g-question.typ": *
#import "./g-solution.typ": *
#import "./g-clarification.typ": *
#let __sugar(content) = {
show regex("=\?"): it => {
let (sugar, ..rest) = it.text.split("?")
if sugar == "=" {
g-question[]
}
else {
[#it]
}
}
show regex("=\?(.+)"): it => {
let (sugar, ..rest) = it.text.split("?")
if sugar == "=" {
g-question[#rest.join("?").trim()]
}
else {
[#it]
}
}
show regex("=(\d+\.?\d*)\?"): it => {
let (sugar, ..rest) = it.text.split("?")
if sugar.starts-with("=") {
let points = float(sugar.slice(1))
g-question(points: points)[]
}
else {
[#it]
}
}
show regex("=(\d+\.?\d*)\?(.+)"): it => {
let (sugar, ..rest) = it.text.split("?")
if sugar.starts-with("=") {
let points = float(sugar.slice(1))
g-question(points: points)[#rest.join("?")]
}
else {
[#it]
}
}
show regex("==\?"): it => {
let (sugar, ..rest) = it.text.split("?")
if sugar == "==" {
g-subquestion[]
}
else {
[#it]
}
}
show regex("==\?(.+)"): it => {
let (sugar, ..rest) = it.text.split("?")
if sugar == "==" {
g-subquestion[#rest.join("?").trim()]
}
else {
[#it]
}
}
show regex("==(\d+\.?\d*)\?"): it => {
let (sugar, ..rest) = it.text.split("?")
if sugar.starts-with("==") {
let points = float(sugar.slice(2))
g-subquestion(points: points)[]
}
else {
[#it]
}
}
show regex("==(\d+\.?\d*)\?(.+)"): it => {
let (sugar, ..rest) = it.text.split("?")
if sugar.starts-with("==") {
let points = float(sugar.slice(2))
g-subquestion(points: points)[#rest.join("?")]
}
else {
[#it]
}
}
show regex("=\!"): it => {
let (sugar, ..rest) = it.text.split("!")
if(sugar == "=") {
g-solution[]
}
else {
[#it]
}
}
show regex("=\!(.+)"): it => {
let (sugar, ..rest) = it.text.split("!")
if(sugar == "=") {
g-solution[#rest.join("!").trim()]
}
else {
[#it]
}
}
show regex("=\%"): it => {
let (sugar, ..rest) = it.text.split("%")
if(sugar == "=") {
g-clarification[]
}
else {
[#it]
}
}
show regex("=\%(.+)"): it => {
let (sugar, ..rest) = it.text.split("%")
if(sugar == "=") {
g-clarification[#rest.join("%").trim()]
}
else {
[#it]
}
}
content
} |
https://github.com/OCamlPro/ppaqse-lang | https://raw.githubusercontent.com/OCamlPro/ppaqse-lang/master/src/étude/analyseurs.typ | typst | #import "defs.typ": *
#import "links.typ": *
= Analyseurs statiques <A-static>
== Généralités
Pour chaque langage étudié dans le rapport, nous présentons des outils d'analyse
statique permettant de déduire de l'information par une
interprétation abstraite du programme.
Les analyseurs statiques peuvent établir des métriques sur le code ou faire
de la rétro-ingénierie pour en déduire des propriétés (et en vérifier). Ils
peuvent également détecter des erreurs de programmation par heuristique ou
vérifier le respect de normes de codage.
Étant donné le volume d'analyseurs sur le marché, le rapport ne prend en compte
que les analyseurs dits _corrects_.
Un analyseur statique est dit _correct_ s'il ne donne pas de faux-négatif
pour un programme sans _bug_. _A contrario_, il indiquera au moins un _bug_
pour un programme qui en comporte. Cette garantie n'est donnée que par rapport
à la modélisation mathématique qui en est faite et il est donc important que ce
modèle soit raisonnablement proche de la réalité.
Chaque analyseur est étudié par rapport aux ressources publiques disponibles.
Cela comprend le manuel utilisateur, les publications scientifiques, les
brochures commerciales ou le site internet dédié.
Les types d'erreurs détectées dépendent des analyses effectuées par chaque
outils et tous n'utilisent pas toujours la même terminologie pour désigner un
type d'erreur. En conséquence, l'absence d'indication sur la présence d'une
analyse particulière ne signifie pas que l'outil ne la fasse pas mais seulement
que nous n'avons pas trouvé d'information à ce sujet.
== Notes sur les analyseurs statiques
=== Frama-C
Parmi les analyseurs statiques étudiés, #framac#cite(<framac>) a la
particularité de
fonctionner avec des _plugins_ dédiés à un type d'analyse particulier. La
complétion de l'analyse globale considérée dans les comparatifs du document
suppose que les _plugins_ usuels soient utilisés, notamment :
- Eva ;
- Wp ;
- Mthread.
Certaines analyses complémentaires peuvent être proposées par l'outil via des
plugins payants ou réalisés _ad hoc_.
=== Polyspace
Polyspace désigne une gamme de produit de la société MathWorks
#footnote[#link("https://fr.mathworks.com")] qui propose différentes solutions
autour de l'analyse statique.
Dans le cadre de cette étude, nous désignons par Polyspace la solution
_Polyspace Code Prover_.
=== TIS Analyser
_TrustInSoft Analyser_ est un outil d'analyse statique développé par la société
_TrustInSoft_#footnote[#link("https://trust-in-soft.com")]. C'est un _fork_
de Frama-C qui utilise un ancien plugin _value_ basé sur le calcul
d'intervalles. _TrustInSoft_ a amélioré le plugin, la traçabilité des erreurs
et l'expérience utilisateur. |
|
https://github.com/kdog3682/2024-typst | https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/archive.typ | typst |
---------------------------------------------------------------
// a cool way of drawing triangles
// a curved arrow
#inline-canvas({
import cetz.draw: *
let curved-arrow(a, b) = {
let c1x = calc.abs(a.at(0) - b.at(0)) / 2
let c1y = a.at(1) - 1
let c1 = (c1x, c1y)
let c2 = b
let c = c1
let d1y = a.at(1) - 1
let d = (d1y, c1x)
bezier(a, b, c, d, mark: (end: ">", fill: black))
}
grid((-2,-2), (2,2), stroke: (thickness: 0.05pt))
//curved-arrow((-2,2), (-1, -1))
set-style(radius: 1)
intersections("i", {
circle((0,0), name: "a")
circle((1,2), name: "b")
// Use a hidden line to find the border intersections
hide(line("a.north", "a.east", "b.center", close: true, fill: none, name: "triangle"))
//line("a.east", "b.center")
//line("a.north", "b.center")
//line("a.north", "a.east")
})
for-each-anchor("i", (name) => {
set-style(radius: 0.05, fill: black)
circle("i." + name)
let s = text(name, size: 5pt)
// content("i." + name, s, anchor: "west")
})
//arc("a.east", start: 0deg, delta: 90deg, mode: "CLOSE", fill: yellow)
// arc("b.center", start: 220deg, stop: 270deg, mode: "PIE", fill: green)
//mark((0,0), (-1,-1), symbol: ">", scale: 3, fill: black)
})
---------------------------------------------------------------
|
|
https://github.com/sa-concept-refactoring/doc | https://raw.githubusercontent.com/sa-concept-refactoring/doc/main/chapters/abstract.typ | typst | = Abstract <abstract>
With C++20, template parameter constraints @concept_iso_standard were introduced that allow to specify the expected functionality of the template parameters.
The objective of this project was to find novel refactoring operations related to concepts and to implement them as part of a language server.
An analysis has been performed on the language server protocol, concepts, and the clangd language server.
This resulted in a few potential refactoring operations, two of which have been implemented as a tweak in the clangd language server.
The first implemented refactoring enables inlining _requires_ clauses into the template declaration.
It reduces the amount of code and, in most cases, makes the function signature easier to read.
The second implemented refactoring allows converting explicit template declarations into their abbreviated form using _auto_ parameters, thus eliminating the template header above the function.
The two implemented refactor operations have been submitted upstream as pull requests to the LLVM repository and, as of the writing of this paper (#datetime.today().display("[month repr:long] [year]")), are awaiting review.
Once approved and merged, these new refactoring operations will become available to anyone using the clangd language server.
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/math/accent.typ | typst | // Test math accents.
--- math-accent-sym-call ---
// Test function call.
$grave(a), acute(b), hat(f), tilde(§), macron(ä), diaer(a), ä \
breve(\&), dot(!), circle(a), caron(@), arrow(Z), arrow.l(Z)$
--- math-accent-align ---
$ x &= p \ dot(x) &= v \ dot.double(x) &= a \ dot.triple(x) &= j \ dot.quad(x) &= s $
--- math-accent-func ---
// Test `accent` function.
$accent(ö, .), accent(v, <-), accent(ZZ, \u{0303})$
--- math-accent-bounds ---
// Test accent bounds.
$sqrt(tilde(T)) + hat(f)/hat(g)$
--- math-accent-wide-base ---
// Test wide base.
$arrow("ABC" + d), tilde(sum)$
--- math-accent-superscript ---
// Test effect of accent on superscript.
$A^x != hat(A)^x != hat(hat(A))^x$
--- math-accent-high-base ---
// Test high base.
$ tilde(integral), tilde(integral)_a^b, tilde(integral_a^b) $
--- math-accent-sized ---
// Test accent size.
$tilde(sum), tilde(sum, size: #50%), accent(H, hat, size: #200%)$
|
|
https://github.com/jamesrswift/typst-chem-par | https://raw.githubusercontent.com/jamesrswift/typst-chem-par/main/src/rules.typ | typst | MIT License | #import "rules/formulae.typ": formulae
#import "rules/isomers.typ": isomers
#import "rules/enantiomers.typ": enantiomers
#import "rules/greek.typ": greek
#import "rules/dropcaps.typ": fischer-dropcaps
#import "rules/deuterated.typ": deuterated |
https://github.com/morel-olivier/template-typst | https://raw.githubusercontent.com/morel-olivier/template-typst/master/basic-report/main.typ | typst | #import "conf.typ": conf
#show: doc => conf(
fontSize: 12pt,
title: "Mon Document",
company: "Ma Société",
authors: ("<NAME>", "<NAME>"),
frontPagePicture: none,
doc
)
= Introduction <intro>
#lorem(100)
#lorem(60)
== Sous-section 1
#lorem(50)
@intro is a test
== Sous-section 2
=== Sous-sous-section 1
#lorem(50)
==== Sous-sous-sous-section 1
= Conclusion
#lorem(100)
#context [
#let previousHeadings = query(selector(heading).before(here()))
[#previousHeadings]
] |
|
https://github.com/thomasschuiki/thomasschuiki | https://raw.githubusercontent.com/thomasschuiki/thomasschuiki/main/cv/metadata.typ | typst | #import "fontawesome.typ": *
#let lang = sys.inputs.LANG
#let data = yaml("vitae."+lang+".yml")
/* Personal Information */
#let firstName = data.Personal.FirstName
#let lastName = data.Personal.LastName
#let personalInfo = (
github: "thomasschuiki",
gitlab: "thomasschuiki",
email: data.Contact.email,
linkedin: "thomas-s-6a743967",
//custom-1: (icon: "", text: "example", link: "https://example.com"),
//homepage: "jd.me.org",
//orcid: "0000-0000-0000-0000",
//researchgate: "John-Doe",
//extraInfo: "",
)
/* Language-specific */
// Add your own languages while the keys must match the varLanguage variable
#let headerQuoteInternational = (
"": [#data.Personal.Tagline],
"en": [#data.Personal.Tagline],
)
#let cvFooterInternational = (
"": "Curriculum vitae",
"en": "Curriculum vitae",
)
#let letterFooterInternational = (
"": "Cover Letter",
"en": "Cover Letter",
)
#let nonLatinOverwriteInfo = (
"customFont": "Heiti SC",
"firstName": "王道尔",
"lastName": "",
// submit an issue if you think other variables should be in this array
)
/* Layout Setting */
#let awesomeColor = "darknight" // Optional: skyblue, red, nephritis, concrete, darknight
#let profilePhoto = "../img/a.jpg" // Leave blank if profil photo is not needed
#let varLanguage = "" // INFO: value must matches folder suffix; i.e "zh" -> "./modules_zh"
#let varEntrySocietyFirst = false // Decide if you want to put your company in bold or your position in bold
#let varDisplayLogo = false // Decide if you want to display organisation logo or not
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/dict-01.typ | typst | Other | // Test lvalue and rvalue access.
#{
let dict = (a: 1, "b b": 1)
dict.at("b b") += 1
dict.state = (ok: true, err: false)
test(dict, (a: 1, "b b": 2, state: (ok: true, err: false)))
test(dict.state.ok, true)
dict.at("state").ok = false
test(dict.state.ok, false)
test(dict.state.err, false)
}
|
https://github.com/rdboyes/resume | https://raw.githubusercontent.com/rdboyes/resume/main/modules_fr/skills.typ | typst | // Imports
#import "@preview/brilliant-cv:2.0.2": cvSection, cvSkill, hBar
#let metadata = toml("../metadata.toml")
#let cvSection = cvSection.with(metadata: metadata)
#cvSection("Compétences")
#cvSkill(
type: [Langues],
info: [Anglais #hBar() Français #hBar() Chinois],
)
#cvSkill(
type: [Tech Stack],
info: [Tableau #hBar() Python (Pandas/Numpy) #hBar() PostgreSQL],
)
#cvSkill(
type: [Centres d'intérêt],
info: [Natation #hBar() Cuisine #hBar() Lecture],
)
|
|
https://github.com/jneug/schule-typst | https://raw.githubusercontent.com/jneug/schule-typst/main/tests/combine-range/test.typ | typst | MIT License | #import "../../src/util/util.typ": combine-ranges
#let cases = (
(1,),
(1, 2),
(1, 2, 3),
(1, 2, 3, 4),
(1, 2, 4, 6),
(1, 2, 4, 5, 6),
(3, 4, 5, 6),
(2, 3, 4, 5, 6, 12, 13, 14, 15, 16),
(1, 2, 3, 4, 5, 6),
(100, 100, 105, 104, 102, 103),
)
#for case in cases [
- #case #sym.arrow.r #combine-ranges(case)
]
#for case in cases [
- #case #sym.arrow.r #combine-ranges(case, sep: "; ", range-sep: h(.2em) + sym.arrow.double.r + h(.2em), last: ", ")
]
#for case in cases [
- #case #sym.arrow.r #combine-ranges(case, max-items: 4)
]
|
https://github.com/ahxt/typst-TMLR | https://raw.githubusercontent.com/ahxt/typst-TMLR/main/typst_TMLR.typ | typst | #import "tmlr.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: tmlr.with(
title: "Formatting Instructions for TMLR
Journal Submissions",
authors: (
(name: "<NAME>", email: "<EMAIL>", affiliation: "Department of Computer Science
University of New York"),
(name: "<NAME>", email: "<EMAIL>", affiliation: "DeepMind"),
(name: "<NAME>", email: "<EMAIL>", affiliation: "Google Research"),
),
abstract:"The abstract paragraph should be indented 1/2~inch on both left and right-hand margins. Use 10~point type, with a vertical spacing of 11~points. The word Abstract must be centered, in bold, and in point size 12. Two line spaces precede the abstract. The abstract must be limited to one paragraph.",
type: "accepted", //submission accepted preprint
bibliography-file: "ref.bib"
)
= Introduction
#lorem(100)
== In this paper
#lorem(100)
=== Contributions
#lorem(40)
= Related Work
#lorem(100)@Bengio_chapter2007
#lorem(100)@Hinton06
#lorem(100)@goodfellow2016deep
= Conclusion
#lorem(100)
|
|
https://github.com/jamesrswift/musicaux | https://raw.githubusercontent.com/jamesrswift/musicaux/main/tests/test.typ | typst | #import "/src/lib.typ": *
#set text(font: "New Computer Modern", size: 20pt)
#show: score.with(
//title: [Dance in D Major],
//subtitle: [Op 8 No. 3 Mov. 1--3],
author: [<NAME>]
)
#group({
notation(
{
cmd.bars.double-bold-open()
cmd.common.trebble()
cmd.common.key-signature(pitch: -4)
cmd.time.signature("4", "4")
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-text(size: 20pt)[#symbols.pedal]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.env.crescendo(
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
})
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.env.decrescendo(
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
})
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-text(size: 20pt)[#symbols.pedal.release]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(1fr)
cmd.basic-content(pitch: 3)[#symbols.bar.double.bold]
})
v(1em)
notation(
{
cmd.bars.double-bold-open()
cmd.common.bass()
cmd.common.key-signature(pitch: -4)
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
/*cmd.env.tie(
angle: 30deg, dy: -2.2em, dx: 0em,
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 2)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.basic-content(pitch: 4)[#symbols.note.crotchet]
})*/
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(1fr)
cmd.basic-content(pitch: 3)[#symbols.bar.double.bold]
})
})
#v(1em)
#group({
notation(
{
cmd.bars.double-bold-open()
cmd.common.trebble()
cmd.common.key-signature(pitch: -4)
cmd.time.signature("4", "4")
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-text(size: 20pt)[#symbols.pedal]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.env.crescendo(
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
})
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.env.decrescendo(
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
})
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-text(size: 20pt)[#symbols.pedal.release]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(1fr)
cmd.basic-content(pitch: 3)[#symbols.bar.double.bold]
})
v(1em)
notation(
{
cmd.bars.double-bold-open()
cmd.common.bass()
cmd.common.key-signature(pitch: -4)
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
/*cmd.env.tie(
angle: 30deg, dy: -2.2em, dx: 0em,
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 2)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.basic-content(pitch: 4)[#symbols.note.crotchet]
})*/
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(1fr)
cmd.basic-content(pitch: 3)[#symbols.bar.double.bold]
})
})
#v(1em)
#group({
notation(
{
cmd.bars.double-bold-open()
cmd.common.trebble()
cmd.common.key-signature(pitch: -4)
cmd.time.signature("4", "4")
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-text(size: 20pt)[#symbols.pedal]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.env.crescendo(
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
})
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.env.decrescendo(
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
})
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-text(size: 20pt)[#symbols.pedal.release]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(1fr)
cmd.basic-content(pitch: 3)[#symbols.bar.double.bold]
})
v(1em)
notation(
{
cmd.bars.double-bold-open()
cmd.common.bass()
cmd.common.key-signature(pitch: -4)
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
/*cmd.env.tie(
angle: 30deg, dy: -2.2em, dx: 0em,
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 2)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.basic-content(pitch: 4)[#symbols.note.crotchet]
})*/
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(1fr)
cmd.basic-content(pitch: 3)[#symbols.bar.double.bold]
})
})
#v(1em)
#group({
notation(
{
cmd.bars.double-bold-open()
cmd.common.trebble()
cmd.common.key-signature(pitch: -4)
cmd.time.signature("4", "4")
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-text(size: 20pt)[#symbols.pedal]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.env.crescendo(
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
})
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.env.decrescendo(
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
})
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-text(size: 20pt)[#symbols.pedal.release]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(1fr)
cmd.basic-content(pitch: 3)[#symbols.bar.double.bold]
})
v(1em)
notation(
{
cmd.bars.double-bold-open()
cmd.common.bass()
cmd.common.key-signature(pitch: -4)
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
/*cmd.env.tie(
angle: 30deg, dy: -2.2em, dx: 0em,
{
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 2)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.basic-content(pitch: 4)[#symbols.note.crotchet]
})*/
cmd.space(0.3em)
cmd.bars.single()
cmd.space(0.3em)
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 1)[#symbols.note.crotchet]
cmd.basic-content(pitch: 3)[#symbols.note.crotchet]
cmd.space(1fr)
cmd.basic-content(pitch: 3)[#symbols.bar.double.bold]
})
})
#v(1em)
|
|
https://github.com/liuguangxi/suiji | https://raw.githubusercontent.com/liuguangxi/suiji/main/src/random-fast.typ | typst | MIT License | //==============================================================================
// Random number generator (fast version)
//
// Public functions:
// gen-rng-f
// randi-f, integers-f, random-f, uniform-f, normal-f
// discrete-preproc-f, discrete-f
// shuffle-f, choice-f
//==============================================================================
#import "lcg.typ": lcg-get, lcg-get-float, lcg-set
//----------------------------------------------------------
// Private functions
//----------------------------------------------------------
// Return random integers from [0, n), 1 <= n <= 0x80000000
#let _uniform-int(rng, n) = {
let scale = calc.quo(0x80000000, n)
while true {
rng = lcg-get(rng)
let k = calc.quo(rng, scale)
if k < n {return (rng, k)}
}
}
//----------------------------------------------------------
// Public functions
//----------------------------------------------------------
// Construct a new random number generator with a seed
//
// Arguments:
// seed: value of seed, effective value is an integer from [0, 2^32-1]
//
// Returns:
// rng: generated object of random number generator
#let gen-rng-f(seed) = {
assert(type(seed) == int, message: "`seed` should be an integer")
lcg-set(seed)
}
// Return a raw random integer from [0, 2^31)
//
// Arguments:
// rng: object of random number generator
//
// Returns:
// rng-out: updated object of random number generator (random integer from the interval [0, 2^31-1])
#let randi-f = lcg-get
// Return random integers from low (inclusive) to high (exclusive)
//
// Arguments:
// rng: object of random number generator
// low: lowest (signed) integers to be drawn from the distribution, optional
// high: one above the largest (signed) integer to be drawn from the distribution, optional
// size: returned array size, must be none or non-negative integer, optional
// endpoint: if true, sample from the interval [low, high] instead of the default [low, high), optional
//
// Returns:
// array of (rng, arr)
// rng: updated object of random number generator
// arr: array of random numbers
#let integers-f(rng, low: 0, high: 100, size: none, endpoint: false) = {
assert((size == none) or (type(size) == int and size >= 0), message: "`size` should be non-negative")
assert(type(endpoint) == bool, message: "`endpoint` should be bool")
let n = if size == none {1} else {size}
let gap = high - low
if endpoint {gap += 1}
assert(gap >= 1 and gap <= 0x80000000, message: "invalid range between `low` and `high`")
let val = 0
let a = ()
for i in range(n) {
(rng, val) = _uniform-int(rng, gap)
a.push(val + low)
}
if size == none {
return (rng, a.at(0))
} else {
return (rng, a)
}
}
// Return random floats in the half-open interval [0.0, 1.0)
//
// Arguments:
// rng: object of random number generator
// size: returned array size, must be none or non-negative integer, optional
//
// Returns:
// array of (rng, arr)
// rng: updated object of random number generator
// arr: array of random numbers
#let random-f(rng, size: none) = {
assert((size == none) or (type(size) == int and size >= 0), message: "`size` should be non-negative")
let n = if size == none {1} else {size}
let val = 0
let a = ()
for i in range(n) {
(rng, val) = lcg-get-float(rng)
a.push(val)
}
if size == none {
return (rng, a.at(0))
} else {
return (rng, a)
}
}
// Draw samples from a uniform distribution of half-open interval [low, high) (includes low, but excludes high)
//
// Arguments:
// rng: object of random number generator
// low: lower boundary of the output interval, optional
// high: upper boundary of the output interval, optional
// size: returned array size, must be none or non-negative integer, optional
//
// Returns:
// array of (rng, arr)
// rng: updated object of random number generator
// arr: array of random numbers
#let uniform-f(rng, low: 0.0, high: 1.0, size: none) = {
assert((size == none) or (type(size) == int and size >= 0), message: "`size` should be non-negative")
let n = if size == none {1} else {size}
let val = 0
let a = ()
for i in range(n) {
(rng, val) = lcg-get-float(rng)
a.push(low * (1 - val) + high * val)
}
if size == none {
return (rng, a.at(0))
} else {
return (rng, a)
}
}
// Draw random samples from a normal (Gaussian) distribution
//
// Arguments:
// rng: object of random number generator
// loc: float, mean (centre) of the distribution, optional
// scale: float, standard deviation (spread or width) of the distribution, must be non-negative, optional
// size: returned array size, must be none or non-negative integer, optional
//
// Returns:
// array of (rng, arr)
// rng: updated object of random number generator
// arr: array of random numbers
#let normal-f(rng, loc: 0.0, scale: 1.0, size: none) = {
assert((size == none) or (type(size) == int and size >= 0), message: "`size` should be non-negative")
assert(scale >= 0, message: "`scale` should be non-negative")
let n = if size == none {1} else {size}
let x = 0
let y = 0
let r2 = 0
let val = 0
let a = ()
for i in range(n) {
while true {
// Choose x and y in uniform square (-1,-1) to (+1,+1)
(rng, val) = lcg-get-float(rng)
x = -1 + 2 * val
(rng, val) = lcg-get-float(rng)
y = -1 + 2 * val
// See if it is in the unit circle
r2 = x * x + y * y
if r2 <= 1.0 and r2 != 0 {break}
}
// Box-Muller transform
a.push(loc + scale * y * calc.sqrt(-2.0 * calc.ln(r2) / r2));
}
if size == none {
return (rng, a.at(0))
} else {
return (rng, a)
}
}
// Preprocess the given probalilities of the discrete events and return a object that contains the lookup table for the discrete random number generator
//
// Arguments:
// p: the array of probalilities of the discrete events, probalilities must be non-negative
//
// Returns:
// g: generated object that contains the lookup table
#let discrete-preproc-f(p) = {
assert(type(p) == array, message: "`p` should be arrry type")
let k-event = p.len()
assert(k-event >= 1, message: "`k-event` should be positive")
let p-tot = 0.0;
for k in range(k-event) {
assert(p.at(k) >= 0, message: "probalilities must be non-negative")
p-tot += p.at(k)
}
if p-tot == 0 {p-tot = 2.22e-16}
for k in range(k-event) {p.at(k) /= p-tot}
let a = (0,) * k-event
let f = (0,) * k-event
let mean = 1.0 / k-event
let n-small = 0
let n-big = 0
for k in range(k-event) {
if p.at(k) < mean {
n-small += 1
a.at(k) = 0
} else {
n-big += 1
a.at(k) = 1
}
}
let bigs = ()
let smalls = ()
for k in range(k-event) {
if a.at(k) == 1 {
bigs.push(k)
} else {
smalls.push(k)
}
}
while smalls.len() > 0 {
let s = smalls.pop()
if bigs.len() == 0 {
a.at(s) = s
f.at(s) = 1.0
continue
}
let b = bigs.pop()
a.at(s) = b
f.at(s) = k-event * p.at(s)
let d = mean - p.at(s)
p.at(s) += d
p.at(b) -= d
if p.at(b) < mean {
smalls.push(b)
} else if p.at(b) > mean {
bigs.push(b)
} else {
a.at(b) = b
f.at(b) = 1.0
}
}
while bigs.len() > 0 {
let b = bigs.pop()
a.at(b) = b
f.at(b) = 1.0
}
for k in range(k-event) {
f.at(k) += k
f.at(k) /= k-event
}
return (K: k-event, A: a, F: f)
}
// Return random indices from the given probalilities of the discrete events
// Require preprocessed probalilities of the discrete events
//
// Arguments:
// rng: object of random number generator
// g: generated object that contains the lookup table by `discrete-preproc` function
// size: returned array size, must be none or non-negative integer, optional
//
// Returns:
// array of (rng, arr)
// rng: updated object of random number generator
// arr: array of random indices
#let discrete-f(rng, g, size: none) = {
assert((size == none) or (type(size) == int and size >= 0), message: "`size` should be non-negative")
let n = if size == none {1} else {size}
let u = 0
let a = ()
for i in range(n) {
(rng, u) = lcg-get-float(rng)
let c = calc.floor(u * g.K)
let f = g.F.at(c)
if f == 1.0 {
a.push(c)
} else if u < f {
a.push(c)
} else {
a.push(g.A.at(c))
}
}
if size == none {
return (rng, a.at(0))
} else {
return (rng, a)
}
}
// Randomly shuffle a given array
//
// Arguments:
// rng: object of random number generator
// arr: the array to be shuffled
//
// Returns:
// array of (rng, arr)
// rng: updated object of random number generator
// arr: shuffled array
#let shuffle-f(rng, arr) = {
assert(type(arr) == array, message: "`arr` should be arrry type")
let n = arr.len()
let j = 0
for i in range(n - 1, 0, step: -1) {
(rng, j) = _uniform-int(rng, i + 1)
if i != j {
(arr.at(i), arr.at(j)) = (arr.at(j), arr.at(i))
}
}
return (rng, arr)
}
// Generate random samples from a given array
// The sample assumes a uniform distribution over all entries in the array
//
// Arguments:
// rng: object of random number generator
// arr: the array to be sampled
// size: returned array size, must be non-negative integer, optional
// replacement: whether the sample is with or without replacement, optional; default is true, meaning that a value of arr can be selected multiple times.
// permutation: whether the sample is permuted when sampling without replacement, optional; default is true, false provides a speedup.
//
// Returns:
// array of (rng, arr)
// rng: updated object of random number generator
// arr: generated random samples
#let choice-f(rng, arr, size: none, replacement: true, permutation: true) = {
assert(type(arr) == array, message: "`arr` should be arrry type")
assert((size == none) or (type(size) == int and size >= 0), message: "`size` should be non-negative")
assert(type(replacement) == bool, message: "`replacement` should be boolean")
assert(type(permutation) == bool, message: "`permutation` should be boolean")
let n = arr.len()
assert(n >= 1, message: "size of `arr` should be positive")
let n-out = if size == none {1} else {size}
let val = 0
let a = ()
if replacement { // sample with replacement
for i in range(n-out) {
(rng, val) = _uniform-int(rng, n)
a.push(arr.at(val))
}
} else { // sample without replacement
assert(n-out <= n, message: "`size` should be no more than input array size when `replacement` is false")
let i = 0
let j = 0
while i < n and j < n-out {
(rng, val) = lcg-get-float(rng)
if (n - i) * val < n-out - j {
a.push(arr.at(i))
j += 1
}
i += 1
}
if permutation {
(rng, a) = shuffle-f(rng, a)
}
}
if size == none {
return (rng, a.at(0))
} else {
return (rng, a)
}
}
|
https://github.com/cnaak/blindex.typ | https://raw.githubusercontent.com/cnaak/blindex.typ/main/test/test-01-readme.typ | typst | MIT License | #set page(paper: "a7", fill: rgb("#eec"))
#import "lib.typ": iQuot, mkIndex
The Septuagint (LXX) starts with #iQuot([ΕΝ ἀρχῇ ἐποίησεν ὁ Θεὸς τὸν οὐρανὸν καὶ τὴν γῆν.],
"Gen", "en-logos", [1.1], "LXX", label("2012-LXX-SBB")).
#pagebreak()
Moreover, the book of Odes begins with: #iQuot([ᾠδὴ Μωυσέως ἐν τῇ ἐξόδῳ], "Ode", "en-logos",
[1.0], "LXX", label("2012-LXX-SBB")).
#pagebreak()
= Biblical Citations
Books are sorted following the LXX ordering.
#mkIndex(cols: 1, sorting-tradition: "LXX")
#pagebreak()
#bibliography("test-01-readme.yml", title: "References", style: "ieee")
|
https://github.com/daskol/typst-templates | https://raw.githubusercontent.com/daskol/typst-templates/main/iclr/iclr2025.typ | typst | MIT License | /**
* iclr2025.typ
*/
#let std-bibliography = bibliography // Due to argument shadowing.
#let font-family = ("Times New Roman", "CMU Serif", "Latin Modern Roman",
"New Computer Modern", "Times", "Serif")
#let font-family-sans = ("Nimbus Sans", "CMU Sans Serif", "Latin Modern Sans",
"New Computer Modern Sans", "Sans")
#let font-family-mono = ("CMU Typewriter Text", "Latin Modern Mono",
"New Computer Modern Mono", "Mono")
#let font-family-link = ("Courier New", "Nimbus Mono PS") + font-family-mono
#let font-size = (
normal: 10pt,
small: 9pt,
footnote: 8pt,
script: 7pt,
tiny: 5pt,
large: 12pt,
Large: 14.4pt,
LARGE: 17pt,
huge: 20pt,
Huge: 25pt,
)
/*
* Customized text elements.
*/
#let header-title = (
[Under review as a conference paper at ICLR 2025],
[Published as a conference paper at ICLR 2025], // accepted
)
#let author-anon = [*Anonymous authors*\ Paper under double-blind review]
/**
* Ruler definition.
*/
#let lineno = counter("lineno")
#let lineno-fmt(numb, width: 3) = {
let value = str(numb)
let prefix-len = width - value.len()
let prefix = ""
for _ in range(prefix-len) {
prefix = prefix + "0"
}
return prefix + value
}
#let ruler-color = rgb(70%, 70%, 70%)
#let ruler-style = body => {
set text(size: 8pt, font: font-family-sans, weight: "bold", fill: ruler-color)
set par(leading: 6.22pt)
body
}
#let xruler(side, dx, dy, width, height, offset, num-lines) = {
let alignment = if side == left {
right
} else {
left
}
let numbs = range(0, num-lines).map(ix => {
let anchor = lineno.step()
let index = lineno-fmt(offset + ix)
return [#anchor#index]
})
let ruler = block(width: width, height: height, spacing: 0pt, {
show: ruler-style
set align(alignment)
numbs.join([\ ])
})
return place(left + top, dx: dx, dy: dy, ruler)
}
#let make-ruler(
num-lines: 54,
margin: auto,
width: auto,
height: 8.875in,
gap: 30pt,
) = locate(loc => {
let margin = if margin == auto {
(top: 1in - 0.5pt + 9.5pt, left: 1.75in - 1em, right: 1.75in) // ICLR 2025 defaults.
} else {
margin
}
let width = if width == auto {
(left: margin.left - gap, right: margin.right - gap)
} else {
width
}
// Only left ruler.
let dx = 0pt
let dy = margin.top
let offset = lineno.get().at(0)
xruler(left, dx, dy, width.left, height, offset, num-lines)
})
#let ruler = make-ruler() // Default CVPR 2022 ruler.
#let make-title(title) = {
align(left, {
v(0.5pt)
v(0.3pt)
set text(size: 17.28pt)
set par(leading: 8.4pt)
smallcaps(title)
})
}
#let make-author-block(authors) = {
assert(
"names" in authors,
message: "Missing mandatory field `names` in author specification.")
let author_names = authors.names.join([, ], last: [ & ])
let lines = ([*#author_names*], )
if "affilation" in authors {
lines.push(authors.affilation)
}
if "address" in authors {
lines.push(authors.address)
}
if "email" in authors {
lines.push(link(authors.email, raw(authors.email)))
}
block(width: 100%, spacing: 0pt, lines.join([\ ]))
}
#let make-authors(authors, accepted) = {
v(14.7pt)
if accepted != none and not accepted {
set par(first-line-indent: 0pt)
author-anon
} else {
// We use *-like footnote markers in author section.
set footnote(numbering: "*")
authors
.map(make-author-block)
.join(v(22pt, weak: true))
v(3pt)
// Thus we should reset footnote counter at the end of authors section.
counter(footnote).update(0)
}
v(27.95pt)
}
#let make-abstract(abstract) = {
set block(spacing: 0pt)
v(0.075in, weak: true)
block(width: 100%, {
set align(center)
set text(size: font-size.large)
smallcaps[Abstract]
})
v(16.4pt)
pad(left: 0.5in, right: 0.5in, {
set text(size: 10pt)
set par(leading: 4.35pt)
abstract
})
v(3.8pt, weak: false)
}
/**
* Utility routine to convert authors (array of content) to authors (array of
* strings).
*
* https://github.com/jgm/pandoc/blob/0e92d9483ce55ca2dc3a7a2d12897ac0e25f4dbd/test/writer.typst
*/
#let content-to-string(content) = {
if content.has("text") {
content.text
} else if content.has("children") {
content.children.map(content-to-string).at(0)
} else if content.has("body") {
content-to-string(content.body)
} else if content == [ ] {
" "
}
}
/**
* iclr2025 - Template for International Conference on Learning Representations
* (ICLR) 2025.
*
* Args:
* title: Paper title.
* authors: Tuple of author objects and affilation dictionary.
* keywords: Publication keywords (used in PDF metadata).
* date: Creation date (used in PDF metadata).
* abstract: Paper abstract.
* bibliography: Bibliography content. If it is not specified then there is
* not reference section.
* appendix: Content to append after bibliography section.
* accepted: Valid values are `none`, `false`, and `true`. Missing value
* (`none`) is designed to prepare arxiv publication. Default is `false`.
* id: Submission identifier.
*/
#let iclr2025(
title: [],
authors: (),
keywords: (),
date: auto,
abstract: [],
bibliography: none,
appendix: none,
accepted: false,
id: none,
body,
) = {
let meta-authors = if accepted == none or accepted {
authors.map(it => it.names.map(content-to-string)).join()
} else {
()
}
set document(
title: title,
author: meta-authors,
keywords: keywords,
date: date)
set page(
paper: "us-letter",
margin: (left: 1.5in, right: 1.5in, top: 1in + 9.5pt, bottom: 1in - 9.5pt),
background: if accepted != none and not accepted {
ruler // Rullers on sides.
},
header-ascent: 32.9pt + 9.5pt,
header: {
set block(spacing: 3.7pt)
set text(size: font-size.normal)
set align(left)
let header-text = if accepted == none {
[]
} else if not accepted {
header-title.at(0)
} else if accepted {
header-title.at(1)
}
block(header-text)
line(length: 100%, stroke: 0.4pt)
},
footer-descent: 23.5pt, // Visually perfect.
footer: locate(loc => {
let ix = counter(page).at(loc).first()
return align(center, text(size: font-size.normal, [#ix]))
}),
)
set text(font: font-family, size: font-size.normal)
set par(justify: true, leading: 4.3pt)
show par: set block(spacing: 10pt) // \topsep + \parskip + \partopsep
show raw: set text(font: font-family-mono, size: font-size.normal)
// Configure heading appearence and numbering.
set heading(numbering: "1.1")
show heading: set text(font: font-family, weight: "regular")
show heading: it => {
// Create the heading numbering.
let number = if it.numbering != none {
counter(heading).display(it.numbering)
}
// Render section with such names without numbering as level 3 heading.
let unnumbered = (
[Broader Impact Statement],
[Author Contributions],
[Acknowledgments],
)
let level = it.level
let prefix = [#number ]
if unnumbered.any(name => name == it.body) {
level = 2
prefix = []
}
// TODO(@daskol): Use styles + measure to estimate ex.
set align(left)
let gap = h(1em, weak: true)
if level == 1 {
text(size: font-size.large, context {
let ex = measure(smallcaps[x]).height
v(2 * ex + 5pt, weak: true)
smallcaps[#prefix#gap#it.body]
v(1.5 * ex + 5pt, weak: true) // 1.5ex + \topsep + \partopsep
})
} else if level == 2 {
text(size: font-size.normal, context {
let ex = measure(smallcaps[x]).height
v(1.8 * ex + 7pt, weak: true)
smallcaps[#prefix#gap#it.body]
v(0.8 * ex + 8.5pt, weak: true)
})
} else if level == 3 {
text(size: font-size.normal, context {
let ex = measure(smallcaps[x]).height
v(1.5 * ex + 7pt, weak: true)
smallcaps[#prefix#gap#it.body]
v(0.5 * ex + 9.5pt, weak: true)
})
} else if level == 4 {
text(size: font-size.normal, {
v(5pt, weak: true) // Visually perfect.
smallcaps[#prefix#gap#it.body]
})
}
}
// Configure footnote (almost default).
show footnote.entry: set text(size: font-size.small)
set footnote.entry(
separator: line(length: 2in, stroke: 0.35pt),
clearance: 6.65pt,
gap: 0.40em,
indent: 12pt)
// All captions either centered or aligned to the left.
show figure.caption: set align(left)
// Configure figures.
show figure.where(kind: image): set figure.caption(position: bottom)
show figure.where(kind: image): set figure(gap: 16pt)
show figure.where(kind: image): it => {
let render() = {
set align(center)
it.body
v(it.gap, weak: true)
block(spacing: 0pt, {
it.caption
})
}
if it.placement == none {
render()
} else {
place(it.placement, float: true,
block(width: 100%, spacing: 0pt, render()))
}
}
// Configure tables.
show figure.where(kind: table): set figure.caption(position: top)
show figure.where(kind: table): set figure(gap: 6pt)
show figure.where(kind: table): it => {
let render() = {
set align(center)
block(spacing: 0pt, {
it.caption
})
v(it.gap, weak: true)
it.body
}
if it.placement == none {
render()
} else {
place(it.placement, float: true,
block(width: 100%, spacing: 0pt, render()))
}
}
// Configure numbered lists.
set enum(indent: 2.4em, spacing: 0.9em)
show enum: set block(above: 1.63em)
// Configure bullet lists.
set list(indent: 2.4em, spacing: 0.9em, marker: ([•], [‣], [⁃]))
show list: set block(above: 1.63em)
// Configure math numbering and referencing.
set math.equation(numbering: "(1)", supplement: [])
show ref: it => {
let eq = math.equation
let el = it.element
if el != none and el.func() == eq {
let numb = numbering(
"1",
..counter(eq).at(el.location())
)
let content = link(el.location(), numb)
[(#content)]
} else {
it
}
}
make-title(title)
make-authors(authors, accepted)
make-abstract(abstract)
body
if bibliography != none {
set std-bibliography(title: [References], style: "iclr.csl")
bibliography
}
if appendix != none {
set heading(numbering: "A.1")
counter(heading).update(0)
appendix
}
}
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/操作系统(选修)/实验/4.typ | typst | The Unlicense | #import "template.typ": *
#show: project.with(
title: "实验四 进程调度模拟程序",
authors: (
"absolutex",
)
)
#align(right)[]
+ *实验目的*
理解Linux系统中时间片轮转调度算法。
+ 实验内容:
编写程序完成单处理机系统中的进程调度,要求采用固定时间片轮转调度算法。实验具体包括:首先确定进程控制块的内容,进程控制块的组成方式,然后完成进程创建函数和进程调度函数,最后编写主函数对所做工作进行测试。要求:创建多个进程(所需执行时间不同),按照时间片轮转的调度算法将进程的执行顺序显示出来。程序写在实验报告上,并写出运行结果。
进程调度模拟程序主要要考虑三个问题:如何组织进程、如何创建进程和如何实现处理器调度。
为了简化,将进程控制块结构定义如下:
```c
struct pcb
{
int name;//进程标识符
int time ;//进程执行所需时间
}
```
操作系统的实现中,系统往往在主存中划分出一个连续的专门区域存放系统的进程控制块,实验中应该用数组模拟这个专门的进程控制块区域。
#include_code("src/4.c")
执行结果:
```
Initial pool:
Queue 0: (0, 7) -> (1, 11)
Queue 1:
Queue 2:
Queue 3:
Run process 0 at time 0
time: 2
Queue 0: (1, 11)
Queue 1: (0, 5)
Queue 2:
Queue 3:
Run process 1 at time 2
time: 4
Queue 0:
Queue 1: (0, 5) -> (1, 9)
Queue 2:
Queue 3:
Run process 0 at time 4
time: 7
Queue 0:
Queue 1: (1, 9)
Queue 2: (0, 2)
Queue 3:
Run process 1 at time 7
time: 10
Add process 11 in waitlist 1th at time 10
Queue 0: (11, 5)
Queue 1:
Queue 2: (0, 2) -> (1, 6)
Queue 3:
Run process 11 at time 10
time: 12
Queue 0:
Queue 1: (11, 3)
Queue 2: (0, 2) -> (1, 6)
Queue 3:
Run process 11 at time 12
Finish process 11 at time 15
time: 15
Queue 0:
Queue 1:
Queue 2: (0, 2) -> (1, 6)
Queue 3:
Run process 0 at time 15
Finish process 0 at time 17
time: 17
Add process 12 in waitlist 2th at time 17
Queue 0: (12, 7)
Queue 1:
Queue 2: (1, 6)
Queue 3:
Run process 12 at time 17
time: 19
Queue 0:
Queue 1: (12, 5)
Queue 2: (1, 6)
Queue 3:
Run process 12 at time 19
time: 22
Queue 0:
Queue 1:
Queue 2: (1, 6) -> (12, 2)
Queue 3:
Run process 1 at time 22
Finish process 1 at time 28
time: 28
Add process 13 in waitlist 3th at time 28
Queue 0: (13, 9)
Queue 1:
Queue 2: (12, 2)
Queue 3:
Run process 13 at time 28
time: 30
Queue 0:
Queue 1: (13, 7)
Queue 2: (12, 2)
Queue 3:
Run process 13 at time 30
time: 33
Queue 0:
Queue 1:
Queue 2: (12, 2) -> (13, 4)
Queue 3:
Run process 12 at time 33
Finish process 12 at time 35
time: 35
Queue 0:
Queue 1:
Queue 2: (13, 4)
Queue 3:
Run process 13 at time 35
Finish process 13 at time 39
time: 39
Queue 0:
Queue 1:
Queue 2:
Queue 3:
```
该程序还存在一个问题,即当 pool中新增一个进程时,将不会打断低优先级的正在执行中的进程。这是因为在此程序中,时间片并不是离散独立的。 |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/057%20-%20Bloomburrow/005_Episode%205%3A%20Nightfall%20in%20Fountainport.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 5: Nightfall in Fountainport",
set_name: "Bloomburrow",
story_date: datetime(day: 08, month: 07, year: 2024),
author: "<NAME>",
doc
)
#strong[Helga]
Fountainport loomed over the largest pond in Valley. The graceful spire of water magically spouting from a carved lily above the throne room was visible long before Helga and the others reached the Tadpool Harbor District at the base. Each level was a work of art, three basins carved from soapstone and embellished with curved designs: flower petals, lapping waves, stylized frogfolk faces. Large portcullises beneath the city allowed animalfolk to stream into the docks, eager to join year-round celebrations encouraged or directly sponsored by <NAME> himself.
#figure(image("005_Episode 5: Nightfall in Fountainport/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Thoughts of her former mentor seasoned Helga with a dash of anxiety and a heaping spoonful of shame. While her allies admired the floating market beneath the lowest tier of the city, eateries and shops stacked in a jumble of water-stained wood and round windows, she floundered in her mind's muck. While they stared at the blue light shimmering through the ceiling of water held aloft by powerful weaving, surrounded by glass bubbles as large as a house, she hunched as if waiting for a blow to fall.
"This place is incredible," Finneas said, awed. "Three Tree City might be bigger, but my head's about to twist clean off here from looking."
"I prefer less water," Gev griped. "After this, I will holiday at the Ever-Burning Oak."
"Work before sightseeing," Ral said.
Mabel sidestepped a blue-feathered birdfolk fleeing an otter with a broom. "I'm not certain where to begin. We can ask after Cruelclaw, but he may have allies hiding him."
Helga inhaled, held it, then forced herself to exhale. "Maybe, possibly, I could get us in to see <NAME>, and ask for his help?"
"Of course!" said Mabel. "You were his apprentice."
"Yes, but we … didn't part on the best terms."
"Did he try to kill you?" Ral asked.
"Of course not!" Helga exclaimed.
"Did you steal anything from him?"
"I would never!"
Ral shrugged. "Then you're fine. How do we get in to see him?"
Helga hugged herself. "In theory, we ask his aides for an audience. He's usually busy, but under the circumstances, he would probably want to know what's happened."
"Lead the way," Mabel said.
Helga considered asking a frogfolk weaver to open a portal to the topmost level, but the long way was more scenic—and delayed the inevitable. She led them to the glass elevators at the center of the tier, resting atop pools of water, attended by frogfolk or otterfolk wearing silky blue uniforms with matching hats. When enough animalfolk crowded onto a platform, the attendant sent a flow of magic into the water, pushing the elevator up to the next level.
They climbed onto a disc, and with a gentle lurch, the elevator rose. Helga peered down through the blue-tinted glass. The boats drifting between docks and lily pads shrank, roofs receding, then obscured by the bubbles hovering beneath the ceiling. The enchanted water that separated the tiers parted, and they soon found themselves resting on a pool like the one on the level below.
"Going up or stopping?" the attendant asked.
"Up," Helga replied.
They continued, the view beneath them changing. Here, buildings in the preferred frogfolk style sat atop individual bowls, their domes tinted glass or porcelain-thin soapstone. The boats gliding between them were more elegant, intricately carved and decorated with rich embellishments. Some flaunted sails embroidered with silver thread, while others were propelled by water cantrips.
At last, they ascended to the top level. More weaving supplemented mundane construction methods: walls of shimmering, falling water instead of glass, colors shifting like rainbow hues in a bubble of soap. Small fountains imitated the massive one at the center, where <NAME>'s throne room overlooked not only all of Fountainport, but the entire pond around it and beyond.
"The view is breathtaking," Mabel said as they stepped off the elevator.
"Wait until I tell my sisters," Finneas whispered. "They won't believe me."
Helga tried to appreciate the birdfolk's-eye view of far-off forests and mountains, plains spread like a quilt of flowers and crops. Instead, she trembled at their impending meeting. #emph[Would <NAME> remember her?] Perhaps she'd be simply one face among many apprentices, her departure unremarked, her name faded into obscurity.
Or perhaps he would remember precisely why he'd banished her.
In the throne room's antechamber, animalfolk lounged on gilded lily pads and petal-upholstered divans or swam in the clear water. A king's aide, identifiable by his tall, creamy white hat and robes, approached and bowed politely.
"May I assist you folk with something?" the aide asked, his tone suggesting he most certainly could not.
Helga must have taken too long to respond because Mabel sniffed and elbowed her.
"We're here to see <NAME>, please?" Helga said, wishing she didn't sound so small and breathless.
The aide smiled. "His Moistness is indisposed today, and likely tomorrow, but next week—"
"Helga was his apprentice," Mabel interjected. "Perhaps the king might be amenable to seeing her sooner?"
"An apprentice?" The aide peered at Helga more pointedly. "I doubt it, but—wait, did you say Helga?"
Helga's stomach attempted to hide between her toe webbing.
"This is urgent," Mabel insisted. "We would prefer to discuss it with the king directly, to avoid a potential panic."
"Panic?"
"Relating to Calamity Beasts."
"Calamity Beasts?" The aide's eyes bulged, and his voice rose in pitch to a near-squeal. "I see. I'll return presently." He hopped toward the throne room.
"Helga," Mabel said, in the sort of parental voice that conveyed impending disappointment, "what precisely did you do to be released from your apprenticeship?"
Helga gripped her wand as if it could shield her from her own inadequacies. "There was … an incident. It wasn't the first—I often struggled to stay attentive. But this one was worse."
"I can't imagine it was so bad," Finneas said encouragingly.
"We were practicing waterspout cantrips. King Glarb's aide released a swarm of gnats, and we were supposed to hit them with the spouts."
"You hit something else?" Ral asked.
Helga winced. "I hit King Glarb. Or rather, his staff. I was looking the wrong way, and—it doesn't matter. We were near the edge of the tier, and the staff fell."
"Oh no," Mabel said.
"I opened a portal under it, and another next to me, so it would fall into my hand." Helga closed her eyes. "Except the king was standing there, and he'd sent out a water whip to catch the staff—"
Ral made a choking sound.
"—so <NAME> hit himself with his own water whip through the portal. Then the staff fell on his head. It was falling so fast …" Helga swallowed. "He spent days recovering from the concussion. And the staff broke."
"Oh, Helga." Mabel patted her arm. "You mustn't dwell on past embarrassments."
"How can I not?" Helga demanded. "I never do anything right. I nearly dropped you the last time I tried a spell."
"Strictly speaking," Gev said, blinking his third eyelid, "your last spell kept the rain off when we ran from the dragon-hawk."
Helga opened her mouth to argue but closed it. He was right. She'd managed that cantrip fine. "Still, that was only the one time."
"What about the augury?" Finneas asked. "That worked, too."
"None of us is perfect," Mabel said. "My first attempt at blurring? I ran straight into a thistle."
"But now look at you! You're amazing, and I'm still … me." Helga pressed her lips together, not wanting more sorrow or venom to fall out.
"You must forgive yourself, Helga," Mabel said gently. "The past informs who we are, but it need not define us. Look into your future and see a brighter path."
#emph[If only it were so easy] , Helga thought miserably. #emph[Perhaps it was like her water stair cantrip: if she took one step at a time, soon she'd be higher than she started. But she'd have farther to fall …]
The aide returned and led them into the throne room, encased in pillars of water weaving that supported the soapstone flower and its liquid spire above. Lily-pads carpeted the basin, some rising to form pedestals that provided shade or perches. They bloomed in an array of colors, from creamy white to sunrise pink, bright yellow filaments at their cores like tiny suns. At the end of the room, on a massive throne of delicate floral tracery, the silk-robed king regarded Helga with open disdain.
"The prodigal apprentice returns," <NAME> said, his voice deep and resonant. "I'm told you bring word of a Calamity Beast?"
"Yes," Helga croaked, then cleared her throat. "Maha attacked my village, so I went for help, and we—"
"That is a shame." King Glarb leaned his chin on his fist. "But such Calamities are unpredictable, or we wouldn't need augurs."
"It wasn't only my village. The Night Owl destroyed others, and the Flood Gar drowned the Docklands in Three Tree City."
"A weaselfolk called Cruelclaw stole a Calamity Beast egg," Mabel explained. "We believe this is causing the attacks. We tracked him and his mercenaries here to Fountainport."
If Helga hadn't been staring at the king, she might not have noticed the shift in his gaze. She followed it to the left of the throne, where dim light emanated from behind an oddly placed leaf screen.
"You tracked him here?" King Glarb asked. "Does anyone else know of this?"
"A group of lorekeepers," Mabel said. "Their own folk are looking for the egg as well."
King Glarb steepled his fingers. "This does present a problem."
Helga squinted at the partition, extending her senses toward it through the water beneath. Whatever was behind it felt powerful, magic pulsing from it like a heartbeat.
"If you can find the egg," Mabel said, "we can return it to wherever it came from, and hopefully stop the attacks."
"I have a rather … different solution in mind. I don't expect a simple mousefolk like yourself to understand, but sometimes sacrifices must be made for the greater good."
"Sacrifices?" Finneas exclaimed.
"The greater good?" Mabel repeated slowly.
Dread flooded Helga's limbs in a cold, burning rush. With a tendril of water, she pulled down the screen to reveal what it hid.
A massive egg sat within an ornate lattice nest, its velvety blue shell swirled with specks that glittered like stars.
"The Calamity Beast egg?" Helga reeled from shock. "#emph[You] have it?"
"I should hope so," <NAME> replied. "I paid Cruelclaw extremely well to bring it here."
A red-coated weaselfolk emerged from behind the throne looking just as he had in Coffey's spelled image, one eye scored by scars, a rapier hanging from his belt. "The Direshade Company fulfills its contracts," Cruelclaw said, his voice rough as limestone.
"You see, little Helga," the king continued, "with the right weaving, I can control the Calamity Beast within that egg. Imagine never again fretting about sudden changes in seasons, or drought, or plague. Our very own champion would defend all animalfolk in Valley, repelling the other Calamity Beasts by my command."
Helga struggled to contain her anger. "You've caused so much destruction–—not only my village, but others. Three Tree City flooded! The Calamity Beasts are too dangerous for anyone to control. Do you want to be like the weavers of old who became mindless monsters?"
"History will vindicate my actions," <NAME> scoffed. "I will be remembered as a pragmatist—nay, a visionary, who ushered in a new era of peace and prosperity."
"You've let your fears overcome your good sense," Mabel said.
"The ends don't always justify the means," Ral added. "Believe me, I know."
King Glarb waved dismissively. "Your opinions matter not; you won't be alive for long to continue espousing them. Or I'll seal you away in some deep hole, so you can repent when my plans come to fruition."
"You're welcome to try," Mabel said, a hand on her sword hilt.
"Who are you to defy me?" <NAME> said. "A pack of farmers and a failed weaver? And …" He peered at Ral. "Whatever is that contraption on your arm? Bah, it matters not." His eyes glowed blue, like the depths of a pond, and water ropes wrapped around Helga and the others. "Cruelclaw, dispose of these pests."
"Direshades, take them," Cruelclaw ordered. A dozen armed mercenaries emerged from a side room. Helga struggled against the bonds, pliant yet unbreakable.
Zoraline awoke and tried to stretch. "Why am I tied up?"
"Can you free us with a spell, Helga?" Mabel asked.
<NAME> warbled a laugh. "You imagine Helga's magic could surpass my own? Stuff and nonsense. She can barely manage simple cantrips. As weavers go, she's an utter failure."
Hearing the same words she'd told herself, spoken bluntly by her former mentor, struck Helga with the force of a blow. She sank to her knees, the water constricting her, mocking her shortcomings.
"Don't listen to him, Helga," Mabel insisted. "We wouldn't be here without your augury. You're only a failure if you give up!"
Helga stared into the obsidian eyes of the mousefolk who had trusted her from the beginning, who defended her against doubters and detractors, who always encouraged her to keep trying. It didn't matter what the voices in her mind said. It didn't matter that her family never supported her, or that <NAME> thought her a fool. Mabel believed in her. Mabel needed her help.
Helga only knew a few minor cantrips, but sometimes, small magic was big enough.
As Cruelclaw approached her, sword drawn, Helga focused on his feet. Beneath them, she weaved her water step spell. With a jerk of her chin, she sent him sliding toward <NAME>, who raised his hands to ward off the impact. His weaving failed, liquid bonds dissolving into the floor of the throne room.
Mabel drew her sword, which flared orange. Gev pulled out his fire maces, flames dancing along their heads. Finneas nocked three arrows, while Hugs stretched to his full height and cracked his neck. Even Zoraline spread her wings menacingly, snub nose tilted up in scorn.
"Come on, then." Helga formed a rotating shield of water around herself. "Let's show His Moistness what a pack of farmers can do."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#strong[Mabel]
Much as she would have loved to dwell on her pride at Helga's bold pronouncement, Mabel stored that sentiment in her mental pantry and focused on the fight ahead. She needed to stop King Glarb's mad plan, protect her allies—no, her friends—and return to her family in Goodhill.
A rabbitfolk thrust his spear at her, taking advantage of his longer reach. Sidestepping, Mabel cut through the haft with her glowing blade, the spear's point splashing to the floor. She blurred out of the way of a volley of knives, then a staff swipe. Every enemy who sought to strike her found only empty air as her magic obscured her movements.
Even as she fought, Mabel watched the others. Hugs and Gev faced two snarling raccoonfolk, one punching with spiked knuckles, the other weaving a whirlwind of objects—teapots, sharpened mussel shells, smooth stones, and more. Hugs slapped the aerial detritus aside or caught it and threw it back. Gev leaped off Hugs's shoulder and swung his fiery maces in a deadly figure eight. The weaver's missiles burned to a crisp, or broke into smaller pieces with sharper edges.
Overhead, Zoraline engaged in aerial battle with a vicious songbird wielding a sword with two blades extending from a central haft. Zoraline evaded, twisting her wings backward on the upstroke to hover in place while the birdfolk swept past. With a keening cry, she unleashed a prayer-spell that blew her enemy past the edge of the basin.
A skunkfolk pursued Finneas, who zigzagged around her, too quick to catch. She unleashed a putrid spray spell, friend and foe alike staggering from the stench. Finneas leaped up and back, loosing his trio of arrows. The ends, tipped with spiked burrs, wedged in his opponent's furry backside, making her yelp in surprise and pain.
Gev spat flame at the stink cloud, which flared into a ball of fire before dissipating. "You give Striped Rapscallions everywhere a bad name," he hissed at the skunkfolk.
Ral sighed and sent a bolt of lightning arcing at a lizardfolk in mid-leap. She recoiled and landed awkwardly in the water, wisps of smoke emanating from her scaled armor. "Always with the fighting," Ral muttered.
King Glarb stood in front of the Calamity Beast egg as Cruelclaw advanced on Mabel, his gaze murderous.
#figure(image("005_Episode 5: Nightfall in Fountainport/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"I know your type," Cruelclaw rasped, cracking his neck. "You think because you helped fend off some starving bandits once, it makes you a hero. You're not. I'm a professional, and you're an amateur. I'm a fighter, and you're a farmer. Leave with your life and make better choices."
"I'm not a farmer," Mabel replied, "I'm a baker."
Cruelclaw thrust sharply with his rapier, a blow Mabel sidestepped. The next she parried with her shield; the thin sword glanced off, leaving an acrid green streak across the surface. Poison. If he hit her, the fight would end quickly, and not in her favor.
The weaselfolk bore down relentlessly, slashing and thrusting with pure malice. She dodged and blurred around him, hoping he would tire. Her sword, glowing dimly at first, brightened and trailed streaks of orange light, as if rending the air with fiery claws. Still Cruelclaw sliced and stabbed, his breath even, as if he could fight for hours.
Mabel stepped to her left … but found herself back where she'd started. <NAME> had opened a portal, and she'd blundered into it. Cruelclaw's blade fell toward her head, and she raised her sword and shield to block the strike. They landed in a bind, blade to blade, hilt to hilt. He pressed down, the poisoned edge of his weapon shifting closer to her face, her neck. In moments, he would end her.
#emph[She's always been my hero] . Clem spoke from the depths of her memory.
#emph[She's going to be a hero, Pip] , Foggy added. #emph[She's going to have an adventure and do swordfights and use magic and then come back and tell us all her stories!]
Her story couldn't end now. King Glarb couldn't succeed, for the sake of Valley and all of Bloomburrow beyond. Mabel could almost feel her family's hands joining hers, their arms lending her strength.
Her blade burst into flame, bright as the heart of a bonfire. Cruelclaw gasped as the sword singed his fur, stumbling back. Fear glittered in his good eye. Mabel swung, sending an arc of fire toward him, driving him toward the edge of the basin. Soon he stood on the precipice of death by burn or a long fall. With a flick of her wrist, she disarmed him, his weapon tumbling toward the clear water far below.
Cruelclaw bared his teeth. "Do it, baker," he snarled. "End this."
The runes on her blade flashed. She could end him. #emph[But should she? Was this the tale she wanted to tell her children? No.]
"Leave with your life," Mabel said. "Make better choices. It's never too late to do good instead of harm."
Cruelclaw's retort was lost as a croaky shout drew their attention. King Glarb's hands formed complex patterns in the air, and before him Helga struggled vainly to free herself from a block of ice.
#figure(image("005_Episode 5: Nightfall in Fountainport/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Righteous fury filled Mabel. She blurred toward the king, sword swinging, hoping its fire would distract him and break his weaving. Instead of a slice of flame, a huge blaze roared from the blade. It looked like a wolf in mid-leap, the form gone too quickly for her to be certain.
King Glarb flung his arms up with a shout of fear. Mabel reached Helga's side in a few steps and jammed her flaming blade into the frozen block. It melted like sugar in hot water.
Shivering, Helga stood beside Mabel, who raised her shield. King Glarb, composure recovered, formed the liquid beneath his feet into a platform that lifted him into the air. He gestured to his right and left as if conducting an orchestra, streams of water arcing out and down from his pedestal like fishing line. Their ends curved into hooks, ready to snare Mabel and the others like minnows.
Above him, storm clouds gathered.
"If you only possessed some #emph[true ] vision," <NAME> bellowed. "We could have celebrated the birth of a new Valley together."
"A Valley of bones and ashes!" Helga screamed back. "Who would celebrate that?"
The clouds darkened, blotting out the sun. The wind shifted, from gentle breeze to frantic frenzy.
King Glarb's hooked lines began to spin around his platform. "A failure like you cannot possibly understand my genius!"
Ral sidled up to Mabel. "We have a problem."
"Only one?" Mabel retorted.
"A bigger one."
"This ends now!" King Glarb shouted.
Lightning cracked the sky like a dropped plate. From between streaks of electricity, the Storm Hawk emerged with a deafening roar. Folding its four wings against its body, it plummeted toward the king like a lance.
King Glarb vanished into a portal as deadly claws raked the space where he'd stood. Individual fights ceased as animalfolk fled this new enemy. Mabel dragged Helga to the relative shelter of the vast covered throne, Ral close behind.
"Can you try the same spell as before?" Mabel asked him.
"Probably a bad idea," Ral replied. "I zap that water spire, it could electrocute anyone touching water in Fountainport."
"So could the Hawk."
Ral peered at the sky. "I can try to calm the storm. Could be wasted energy if the dragon keeps stirring it up."
"Do your best." Mabel's sword pulsed, heat surging up her arm and through her body. This was her fight. She needed to protect her friends, and the city.
Mabel charged out from beneath her cover. A roar split the air as the creature dove, barely missing a birdfolk who flung himself over the side of the basin. If she wanted to reach the dragon-hawk, she needed to get higher.
There. The stone lily.
"Helga!" Mabel called. "I need your step cantrip."
She pointed with her sword; understanding dawned in Helga's expression. Stairs of water slid out from one of the magical arches holding up the lily. Mabel blurred toward them and began to climb.
She reached the stone flower, droplets spraying her as the wind tugged her armor. Thunder boomed. Mabel raised her flaming blade, a beacon daring the Storm Hawk to attack her.
Eyes bright with lightning, it swooped, talons extended. Mabel prepared to mete out justice or meet her death.
A shriek rent the air as the dragon-bird tumbled sideways, struck by a new foe: Maha, the Night Owl, trailing a curtain of darkness.
Blue-black ribbons streaked with glittering stars split the gray clouds. The two enormous raptors appeared evenly matched, gliding through a lightning-wracked sky. However, the Calamity Beast seemed to predict the hawk's movements, even guiding them with practiced maneuvers. Its glowing turquoise markings blurred into streaks of twilight, circling, chasing, vanishing like the moon behind clouds only to reappear in front of the dragon-bird.
Inexorably, foul weather gave way to clear night. The Night Owl's talons closed on the Storm Hawk's tail feathers, wrenching one free. The creature's roar rose sharply in pitch, in surprise or pain. The dragon-bird beat its four massive wings and soared into the star-strewn sky. Soon, it disappeared, taking all remnants of foul weather with it.
The Night Owl didn't give chase. It perched on the edge of the basin, the bright beams of its eyes gazing at Mabel expectantly.
In that moment, Mabel felt as if she understood precisely what had occurred, and how to make it right.
She scrambled down the water steps held in place by Helga's cantrip, racing toward the giant egg in its magic nest. Carrying it proved awkward; it was larger than her and surprisingly heavy. Cautiously, Mabel brought the precious cargo toward the unmoving, unblinking Night Owl.
#figure(image("005_Episode 5: Nightfall in Fountainport/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Soon, Mabel stood close enough to the Calamity Beast that, if it so chose, it could grasp her in its terrifying talons or consume her in a single gulp. Her heart fluttered faster than a dragonfly's wings as she offered the egg to the creature.
"This is yours, isn't it?" Mabel murmured. "You must have been beside yourself with worry. I would be, too."
#emph[Could the creature understand her? Could a storm, or a wildfire?] Mabel didn't know, but she hoped.
The Night Owl gingerly took the egg. Its fathomless eyes softened; its feathers relaxed. Still silent, it spread vast wings and took to the air on a gust of cool wind. The dark in its wake now felt peaceful rather than malevolent, the domain of batfolk and glowing insects and flowers that blessed the shadows with their sweet perfume.
"How did you know?" Ral asked.
"I didn't," Mabel replied. "But if I followed the egg all this way to protect my own family, why not the other way around?"
Ral's whiskers twitched. "That may be the most motherly thing you've said since I met you."
"I think I can do better than that." Mabel turned to her companions and the remnants of Cruelclaw's mercenary band, raising her voice to be heard throughout the throne room. "Come on, everyone, let's clean up this mess!"
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
King Glarb not only fled the immediate area, he left Fountainport entirely, his whereabouts unknown. Cruelclaw, too, escaped, and his minions surrendered or followed his example. City officials promised investigations and justice for the egg thieves, but Mabel considered her part in the story to have reached its conclusion with the threat of the Calamity Beast settled.
A cabbage transport was summoned to carry the group home—big enough to fit even Hugs comfortably. The construct bobbed less than an otterfolk's boat as it skittered on spiderlike legs along the main roads toward Goodhill. Ral, of all folk, found it unsettling, asking more than once if Mabel was quite sure they wouldn't be suffocated by moldering produce. She assured him they were safe.
"This was quite an adventure," Finneas said, scratching his ear, "but I'm happy to go home again."
"The Striped Rapscallions add another accomplishment to a list already long," Gev said. "I did not even lose my tail, as I did when—"
Hugs interrupted with a low growl, and Gev's mouth clapped shut.
Zoraline yawned. "I can take word to the village tonight. Then everyone will know to expect us." Before Mabel could reply, the batfolk returned to sleep.
Helga stared pensively at the passing scenery. Mabel, loath to interrupt the frogfolk's melancholy musings, turned her attention to Ral.
"What of you?" Mabel asked him. "Your own quest remains incomplete."
"I'll see you home," Ral replied. "From there, I'm not sure. I have to tell people about that wayward dragon."
"Your husband?"
"Among others."
Mabel's heart ached on his behalf. "I hope you can return to him soon."
A spark lit Ral's eyes, but he said nothing.
The rest of the journey was spent in idle chatter and quiet contemplation, and the growing yearning for the road to reach its end.
And so it did, the outskirts of Goodhill coming into view near the second sunset, its verdant fields and windmills and bat towers a sweet, familiar sight. Even sweeter, folk lined the roads, waving, banging pots and pans, treating their arrival as an impromptu parade. Many gathered outside Mabel's home, raising a raucous cheer as she and the others climbed out of the transport. Pip and Foggy flung themselves at her as Clem and Rosalyn waited patiently at the front door. Above them, a sign read, "WELCOME BACK MAM" with "and everyone else" scrawled below as an afterthought.
"How I missed you all," Mabel said, voice raw as she drew her husband and daughter into the family hug.
"Nothing for it," Clem said. "We'll go with you next time, so we won't miss each other."
Mabel nuzzled his nose in reply.
"I helped hang the sign!" Pip shrieked.
"He poked my eye again," Foggy complained.
Rosalyn shook her head ruefully, and Clem squeezed Mabel, his eyes filled with laughter.
Finneas was passed around by his family, his sisters fussing over him mercilessly. Gev, perched atop Hugs's shoulder, told their story—with surprising accuracy—to an awestruck audience. Zoraline stood beside them, her diaphanous robes fluttering as she raised a wing to cover her yawn.
Oliver's reedy voice cut through the general din as he hopped to be seen, finally climbing onto a handy box. "Brave heroes, you have returned to us victorious!"
"Now you've done it," Clem murmured. "Another speech for us all."
Indeed, Oliver delivered an impassioned soliloquy, the details of their journey embellished by his imagination. Many listened with only half an ear because tables were being laid with food. Rosalyn brought out baskets of strawberry rhubarb muffins and sunflower seed scones with cherry jam, and all present filled plates and stomachs.
Helga stood apart, still a stranger to all but the folk she'd fought beside. Ral lurked nearby, another outsider, his expression irritated as he accidentally struck someone with his tail.
"Why don't you two get some treats," Mabel told Pip and Foggy, who were briefly torn before relinquishing her in favor of baked goods. She embraced Clem once more, then skirted scores of well-wishers to reach the awkward pair.
"You should eat," Mabel said. "Troubles fade when the stomach is full, as my mother says."
"She sounds wise," Helga replied, anxious smile firmly in place.
"Will you return to your parents now, or to Pondside, or Haymeadow?"
Helga hesitated. "I thought maybe I could … stay here? As a hedgewitch, to do weather auguries and cantrips. If it isn't too much trouble. My family would have me, but …"
"No need to justify it," Mabel said gently. "I'm sure Oliver will be delighted to add another hero to the town roster."
"Me, a hero?" Helga's anxious expression shifted to a startled, genuine smile.
"You'll have to become accustomed to hearing the moniker on your birthday." Mabel turned a questioning gaze to Ral.
"I'm leaving," he said brusquely. "Beleren clearly isn't here, and it's not like a clue is going to fall on my head while I eat a muffin."
"Perhaps not," Mabel said, "but then at least you'll have a muffin."
Before he could retort, Helga gasped, her eyes glowing like a mirror reflecting the sun. The voice that spilled from her mouth sounded distant, as if from the bottom of a pond.
"The kings in the dark will return," she intoned. "The mage in blue will bring about the end."
#figure(image("005_Episode 5: Nightfall in Fountainport/05.jpg", width: 100%), caption: [Art by: <NAME>ay], supplement: none, numbering: none)
The light left her eyes, and Helga blinked as if nothing untoward had occurred. "What kind of muffins?"
Ral huffed a laugh. "I stand corrected. And I wasn't even eating."
"The kings in the dark," Mabel murmured, uneasy. "What does that mean?"
"It means I have a new question to answer. Throw it on top of the pile. Well, thanks for the tip, augur." Ral began to walk away.
Mabel rested a hand on his arm. "Wait. I have something I want to give you before you leave."
She raced past a curious Clem, into the house. Up to the attic, where she rummaged in a chest until she found what she sought. Down again, pleased Ral remained where she'd left him, posture tense with impatience.
"For you and your husband," she said, offering him a pair of ironsap buttons embossed with holly leaves. She'd meant to work them into cloaks for herself and Clem, but never made the time. Ral took them with a curt nod, and she followed as he stalked between houses to a garden purpled by woolly thyme.
"You'll always be welcome here," Mabel told him, stroking the gray, fuzzy leaves. "Perhaps we'll journey together again."
"Stranger things have happened," Ral replied. "Can't say I've loved having a tail, though."
#emph[What?]
Mabel's question went unvoiced as Ral vanished in an explosion of lightning sparks that lit the evening, quickly fading into afterimages.
A shriek behind her alerted Mabel to the presence of a pair of naughty mouselings, staring at the garden in shock.
"Did that otterfolk disappear?" Pip squeaked, grabbing Mabel's leg.
"Folk can't disappear," Foggy said. "He must have made a portal."
Mabel knew enough of portals to be sure he'd done something else entirely. Her children didn't need their peace ruffled, though.
"Come near to me, my little mischief makers," Mabel said, gathering her children close. "What precisely have you been about while I was off adventuring, hmm?"
Her littles began to talk over each other, eager to bask in the warmth of their mother's attention and affection. They rejoined Clem and Rosalyn, who snuggled up as well, tails tangling together as the party around them grew more cheerful and raucous. Soon the sun slept and the moon awoke to the deepening night, a shooting star blazing across the blackberry sky like a wish granted—which, considering Mabel was home safe and snug, it surely must be.
|
|
https://github.com/qlaush/template_thesis_stuttgart_imvt | https://raw.githubusercontent.com/qlaush/template_thesis_stuttgart_imvt/main/proposal.typ | typst | MIT License | #import "/layout/proposal_template.typ": *
#import "/metadata.typ": *
#set document(title: titleEnglish, author: author)
#show: proposal.with(
title: titleEnglish,
titleGerman: titleGerman,
degree: degree,
program: program,
supervisor: supervisor,
advisors: advisors,
author: author,
startDate: startDate,
submissionDate: submissionDate
)
#include "/content/proposal.typ" |
https://github.com/wuc9521/CS-scholars-report | https://raw.githubusercontent.com/wuc9521/CS-scholars-report/main/main.typ | typst | #set page(
paper: "a4",
margin: (top: 2.5cm, left: 2.5cm, right: 2.5cm, bottom: 2.5cm),
numbering: "1",
)
#set text(font: "Times New Roman", size: 11pt)
#set heading(numbering: "1.1.")
#set raw(tab-size: 4)
#show link: it => {
set text(fill: rgb(0, 0, 128))
underline(it)
}
#[
#set align(center)
#set text(font: "Times New Roman")
#block(height: 40%)
#block(text(weight: 700, size: 20pt)[Final Report])
#v(1cm)
#text(size: 14pt)[<NAME>, <NAME>]
#v(0.5cm)
#text(size: 12pt)[Date: #datetime.today().display()]
]
#pagebreak()
#outline(
title: "Table of Contents",
indent: true,
)
#pagebreak()
#let _DIR = "sections/"
#let _EXT = ".typ"
#let _FILES = ("intro", "impl", "conclusion")
#for __ in _FILES {
include _DIR + __ + _EXT
} |
|
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/main.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial: radial-theme, components
#show: notebook.with(theme: radial-theme, cover: align(center + horizon)[
#text(size: 24pt, font: "Tele-Marines")[
#text(size: 28pt)[
Engineering Notebook
]
#image("./assets/53E-logo-jank.png", height: 70%)
2023 - 2024
#line(length: 50%, stroke: (thickness: 2.5pt, cap: "round"))
Over Under
]
])
#include "/frontmatter.typ"
#include "entries/entries.typ"
#include "./appendix.typ"
|
https://github.com/genericusername3/structogrammer | https://raw.githubusercontent.com/genericusername3/structogrammer/master/README.md | markdown | MIT License | # [structogrammer](https://gitlab.com/czarlie/structogrammer)
Draw Nassi-Shneiderman diagrams, also called structograms, in Typst.
## Basic Usage
Import with:
```typ
#import "@preview/structogrammer:0.1.1": structogram
```
You can then draw structograms, like so:
```typ
#structogram(
width: 30em,
title: "merge_sort(list)",
(
(If: "list empty", Then: (Break: "exit (return list)")),
"left = []",
"right = []",
(For: "element with index i", In: "list", Do: (
(If: "i < list.length / 2", Then: (
"left.add(element)"
), Else: (
"right.add(element)"
))
)),
"left = merge_sort(left)",
"right = merge_sort(right)",
(Break: "return with merge(left, right)")
)
)
```
which yields:<br>
![The structogram specified by the code above](https://gitlab.com/czarlie/structogrammer/-/raw/master/examples/merge-sort.svg)
If `text.lang` is set to another language, this package will try to match inserted text to it. Currently, only `"en"` and `"de"` are supported
## Advanced usage
`structogram()` takes the following named arguments:
- `columns`: If you already allocated wide and narrow columns, `to-elements`
can use them. Useful for sub-specs, as you'd usually generate
allocations first and then do another recursive pass to fill them. <br>
The default, `auto` does exactly this on the highest recursion level.
- `stroke`: The stroke to use between cells, or for control blocks.
Note: to avoid duplicate strokes, every cell only adds strokes to
its top and left side. Put the resulting cells in a container with
bottom and right strokes for a finished diagram. See `structogram()`. <br>
Default: `0.5pt + black`
- `inset`: How much to pad each cell. <br> Default: `0.5em`
- `segment-height`: How high each row should be. <br> Default: `2em`
- `narrow-width`: The width that narrow columns will be. Needed for diagonals in
conditional blocks. <br>
Default: 1em
A `spec` (the positional argument to `structogram()`) can be one of the following:
- `none` or an emtpy [`array`](https://typst.app/docs/reference/foundations/array/) `()`:
An empty cell,
taking up at least a narrow column
- a [`string`](https://typst.app/docs/reference/foundations/str/) or [`content`](https://typst.app/docs/reference/foundations/content/):
A cell containing that string or content,
taking up at least a wide column
- A [`dictionary`](https://typst.app/docs/reference/foundations/dictionary/):
Control block ([see below](#control-blocks))
- An [`array`](https://typst.app/docs/reference/foundations/array/) of specs:
The cells that each element produced,
stacked on top of each other. Wide columns
are aligned to wide columns of other element
specs and narrow columns consumed as needed.
### Control blocks
Specs can contain the following control blocks, as dictionaries:
#### 1. `If`/`Then`/`Else`:
A conditional with the following keys:
- `If`: The condition on which to branch
- `Then`: A diagram spec for the "yes"-branch
- `Else`: A diagram spec for the "no"-branch
`Then` and `Else` are both optional, but at least one must be present
Examples: <ul>
<li><details>
<summary><code>(If: "debug mode", Then: ("print debug message"))</code></summary>
<img src="https://gitlab.com/czarlie/structogrammer/-/raw/master/examples/if-then.svg", alt="Structogram with an if-branch that prints a debug message if the condition debug mode is met">
</details></li>
<li><details>
<summary><code>(If: "x > 5", Then: ("x = x - 1", "print x"), Else: "print x")</code></summary>
<img src="https://gitlab.com/czarlie/structogrammer/-/raw/master/examples/if-then-else.svg", alt="Structogram with an if-branch that decrements and prints x if x is smaller than 5 or else just prints x">
</details></li>
</ul>
Columns: Takes up columns according to its contents next to one another,
inserting narrow columns for empty branches
#### 2. `For`/`Do`, `For`/`To`/`Do`, `For`/`In`/`Do`, `While`/`Do`, `Do`/`While`:
A loop, with the loop control either at the top or bottom.
- `For`/`Do` formats the control as "For $For",
- `For`/`To`/`Do` as "For $For to $To",
- `For`/`In`/`Do` as "For each $For in $In",
- `While`/`Do` and `Do`/`While` as "While $While".
Order of specified keys matters.
Examples:<ul>
<li><details>
<summary><code>(While: "true", Do: "print \"endless loop\"")</code></summary>
<img src="https://gitlab.com/czarlie/structogrammer/-/raw/master/examples/while-do.svg", alt="Structogram that prints "endless loop" forever (while condition true). This is an entry-controlled loop">
</details></li>
<li><details>
<summary><code>(Do: "print \"endless loop\"", While: "true")</code></summary>
<img src="https://gitlab.com/czarlie/structogrammer/-/raw/master/examples/do-while.svg", alt="Structogram that does the same but with an exit-controlled loop">
</details></li>
<li><details>
<summary><code>(For: "item", In: "Container", Do: "print item.name")</code></summary>
<img src="https://gitlab.com/czarlie/structogrammer/-/raw/master/examples/for-in.svg", alt="Structogram that iterates over each item in a container and prints the item name">
</details></li>
</ul>
Columns: Inserts a narrow column left to its content.
#### 3. Method call (`Call`)
A block indicating that a subroutine is executed here.
Only accepts the key `Call`, which is the string name
Example:<ul>
<li><details>
<summary><code>(Call: "func()")</code></summary>
<img src="https://gitlab.com/czarlie/structogrammer/-/raw/master/examples/call.svg", alt="Structogram that calls the "func" function">
</details></li>
</ul>
Columns: One wide column
#### 4. Break/Return (`Break`)
A block indicating that a subroutine is executed here.
Only accepts the key `Break`, which is the target to break to
Examples:<ul>
<li><details>
<summary><code>(Break: "")</code></summary>
<img src="https://gitlab.com/czarlie/structogrammer/-/raw/master/examples/break.svg", alt="Structogram that indicates interrupting the control flow">
</details></li>
<li><details>
<summary><code>(Break: "to enclosing loop")</code></summary>
<img src="https://gitlab.com/czarlie/structogrammer/-/raw/master/examples/break-to.svg", alt="Structogram that indicates interrupting the control flow, returning to the enclosing loop">
</details></li>
</ul>
Columns: One wide column |
https://github.com/Dherse/codly | https://raw.githubusercontent.com/Dherse/codly/main/args.typ | typst | MIT License |
#let type_check(
ty,
function,
) = {
if type(ty) == array {
let tys = ty.map(t => eval(t, mode: "code"))
(value, use) => {
let value_ty = type(value)
value_ty in tys or (function and (not use) and value_ty == function)
}
} else {
let ty = eval(ty, mode: "code")
(value, use) => {
let value_ty = type(value)
value_ty == ty or (function and (not use) and value_ty == function)
}
}
}
#let type_check_str(
ty,
function,
) = {
if type(ty) == array {
let tys = ty.map(t => {
let t = eval(t, mode: "code");
if t == none {
"none"
} else {
str(t)
}
})
let out = "either a " + tys.join(", a ", last: ", or a ")
let out_function = if function {
"either a " + tys.join(", a ") + ", or a function that returns one of the previous types"
} else {
out
}
(use) => {
if function and (not use) {
out_function
} else {
out
}
}
} else {
(_) => ("a " + str(eval(ty, mode: "code")))
}
}
#let state_with_type(
name,
type_check,
type_check_str,
default,
allow-fn,
) = {
let state = state("codly-" + name, default)
(
get: () => {
let value = state.get()
assert(
type_check(value, true),
message: "codly: `" + name + "` must be " + type_check_str(true) + ", found: " + str(type(value)),
)
if type(value) == function and allow-fn {
value()
} else {
value
}
},
get-raw: () => {
state.get()
},
set-raw: (value) => {
state.update((_) => value)
},
update: (value) => {
assert(
type_check(value, false),
message: "codly: `" + name + "` must be " + type_check_str(false) + ", found: " + str(type(value)),
)
state.update((_) => value)
},
reset: () => {
state.update((_) => default)
},
)
}
#let __codly-args = {
let out = (:)
let args = json("args.json")
for (key, arg) in args {
if arg.function and function in arg.ty {
panic("codly: `function` is not a valid type for an argument")
}
out.insert(
key,
state_with_type(
key,
type_check(arg.ty, arg.function),
type_check_str(arg.ty, arg.function),
eval(arg.default, mode: "code"),
arg.function,
)
)
}
out
}
// Must be called in a context!
#let __codly-save() = {
let out = (:)
for (key, value) in __codly-args {
out.insert(key, (value.get-raw)())
}
return out
}
// Must be called after `__codly_save`!
#let __codly-load(stored) = {
for (key, value) in __codly-args {
(value.set-raw)(stored.at(key))
}
} |
https://github.com/BoostCookie/systemd-tshirtd | https://raw.githubusercontent.com/BoostCookie/systemd-tshirtd/main/src/common.newlogo.typ | typst | //#set page(fill: rgb("#201a26"))
#set page(width: 256mm, height: auto, margin: (top: 0em, right: 0em, bottom: 2em, left: 0em))
#set align(center)
#set text(font: "Roboto", fill: white, weight: "bold")
#let brace_angle = 30deg
#let logo_height = 80%
#let line_width = 1.5em
#grid(
columns: (1fr, 38%, 1fr),
rows: 12em,
align: (bottom+right, top+center, bottom+left),
rotate(-brace_angle, image("./systemd-dark-logo-braceopen.svg", height: logo_height)),
image("./systemd-dark-logo-inner.svg", height: logo_height),
rotate(brace_angle, image("./systemd-dark-logo-braceclose.svg", height: logo_height)),
"",
grid.cell[#v(-1.57em)#box(rect(fill: white, width: line_width, height: 50%))#h(17.75em)#box(rect(fill: white, width: line_width, height: 50%))],
"",
)
#v(-12em)
#text(size: 9em)[systemd-tshirtd]
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.4.3/README.template.md | markdown | Apache License 2.0 | # fletcher
[![Manual](https://img.shields.io/badge/latest-manual.pdf-green)](https://github.com/Jollywatt/typst-fletcher/raw/latest/docs/manual.pdf)
![Version](https://img.shields.io/badge/dynamic/toml?url=https%3A%2F%2Fgithub.com%2FJollywatt%2Farrow-diagrams%2Fraw%2Flatest%2Ftypst.toml&query=package.version&label=latest&color=green)
![Version](https://img.shields.io/badge/dynamic/toml?url=https%3A%2F%2Fgithub.com%2FJollywatt%2Farrow-diagrams%2Fraw%2Fmaster%2Ftypst.toml&query=package.version&label=dev)
[![Repo](https://img.shields.io/badge/GitHub-repo-blue)](https://github.com/Jollywatt/typst-fletcher)
_**fletcher** (noun) a maker of arrows_
A [Typst](https://typst.app/) package for drawing diagrams with arrows,
built on top of [CeTZ](https://github.com/johannes-wolf/cetz).
See the [manual](https://github.com/Jollywatt/typst-fletcher/raw/latest/docs/manual.pdf) for documentation.
````python
f"""
```typ
#import "@preview/fletcher:{get_version()}" as fletcher: diagram, node, edge
```
"""
````
```python
# These are examples in `docs/example-gallery/*.typ`
'\n'.join(insert_example_block(name) for name in [
"first-isomorphism-theorem",
"flowchart-trap",
"state-machine",
"feynman-diagram",
])
```
# More examples
Pull requests are most welcome!
```python
# These are examples in `docs/gallery/*.typ`
insert_example_table([
"commutative",
"algebra-cube",
"ml-architecture",
"io-flowchart",
])
```
## Change log
### 0.4.3
- Fixed edge crossing backgrounds being drawn above nodes (#14).
- Added `fletcher.hide()` to hide elements with/without affecting layout, useful for incremental diagrams in slides (#15).
- Support `shift`ing edges by coordinate deltas as well as absolute lengths (#13).
- Support node names (#8).
### 0.4.2
- Improve edge-to-node snapping. Edges can terminate anywhere near a node (not just at its center) and will automatically snap to the node outline. Added `snap-to` option to `edge()`.
- Fixed node `inset` being half the amount specified. If upgrading from previous version, you will need to divide node `inset` values by two to preserve diagram layout.
- Add `decorations` option to `edge()` for CeTZ path decorations (`"wave"`, `"zigzag"`, and `"coil"`, also accepted as positional string arguments).
### 0.4.1
- Support custom node shapes! Edges connect to node outlines automatically.
- New `shapes` submodule, containing `diamond`, `pill`, `parallelogram`, `hexagon`, and other node shapes.
- Allow edges to have multiple segments.
- Add `vertices` an `corner-radius` options to `edge()`.
- Relative coordinate shorthands may be comma separated to signify multiple segments, e.g., `"r,u,ll"`.
- Add `dodge` option to `edge()` to adjust end points.
- Support `cetz:0.2.0`.
### 0.4.0
- Add ability to specify diagrams in math-mode, using `&` to separate nodes.
- Allow implicit and relative edge coordinates, e.g., `edge("d")` becomes `edge(prev-node, (0, 1))`.
- Add ability to place marks anywhere along an edge. Shorthands now accept an optional middle mark, for example `|->-|` and `hook-/->>`.
- Add “hanging tail” correction to marks on curved edges. Marks now rotate a bit to fit more comfortably along tightly curving arcs.
- Add more arrowheads for the sake of it: `}>`, `<{`, `/`, `\`, `x`, `X`, `*` (solid dot), `@` (solid circle).
- Add `axes` option to `diagram()` to control the direction of each axis in the diagram's coordinate system.
- Add `width`, `height` and `radius` options to `node()` for explicit control over size.
- Add `corner-radius` option to `node()`.
- Add `stroke` option to `edge()` replacing `thickness` and `paint` options.
- Add `edge-stroke` option to `diagram()` replacing `edge-thickness`.
### 0.3.0
- Make round-style arrow heads better approximate the default math font.
- Add solid arrow heads with shorthand `<|-`, `-|>` and double-bar `||-`, `-||`.
- Add an `extrude` option to `node()` which duplicates and extrudes the node's stroke, enabling double stroke effects.
### 0.2.0
- Experimental support for customising arrowheads.
- Add right-angled edges with `edge(..., corner: left/right)`.
|
https://github.com/joelakuhn/php-ext-typst | https://raw.githubusercontent.com/joelakuhn/php-ext-typst/master/README.md | markdown | Apache License 2.0 | # php-ext-typst
This is a PHP extension for integrating the typst compiler with the PHP language.
Features:
- compile typst in-memory from PHP
- populate typst variables directly from PHP Values
## Building
You must have PHP headers installed in order to build. You can select a php version to build against by setting the `PHP` and `PHP_CONFIG` variables to specific instances of php and php-config.
```shell
$ cargo build --release
```
## Installation
Check `php-config` to locate the `--extension-dir` where the built extension should be installed.
## Testing
You can test the plugin with the PHP cli by adding the flag `-d extension=<path to extension>`.
## API
The `Typst` class is used to build the compiler environment, which includes the template body and all variables passed to the compiler.
```php
class Typst {
// Creates a Typst class with an optional body.
public function __construct(?string $body = null);
// Set or overwrite the typst template body.
public function body(string $body);
// Set a json-encoded variable in the typst environment.
public function json(string $key, string $value);
// Set a csv-encoded variable in the typst environment.
// If $use_headers is false, the typst variable will be an array of arrays.
// If $use_headers is true, the typst variable will be an array of dict, using the headers as keys.
public function csv(string $key, string $value, string $delimiter = ',', bool $use_headers = false);
// Set a php variable in the typst environment.
public function var(string $key, mixed $value);
// Compile the current environment to PDF.
// This will return a binary string on success or null on error.
// This function can throw an Error on compilation failure.
public function compile(): ?string;
}
```
## Example
```typst
Invoice #invoice_num
#client.name
#client.address.join("\n")
#table(
columns: (1fr, 60pt, 60pt),
..services.map((line) => (
line.title,
str(line.rate),
str(line.quantity),
)).flatten()
)
```
```php
// Primitives
$invoice_num = 2091;
// Nested associative and numerically indexed arrays
$client = [
'name' => 'ABC Corp',
'address' => [
'1000 Maple Ave',
'Test Town, TN 12345',
],
];
// Object data
$services = [
(object)[ 'title' => 'Example Service', 'rate' => 125, 'quantity' => 9.5 ],
(object)[ 'title' => 'Example Service 2', 'rate' => 125, 'quantity' => 2 ],
];
$builder = new Typst(file_get_contents("./invoice.typ"));
$builder->var('invoice_num', $invoice_num);
$builder->var('client', $client);
$builder->var('services', $services);
try {
$pdf_result = $builder->compile();
header('Content-Disposition: inline; filename="invoice-' . $invoice_num . '.pdf"');
header('Content-Type: application/pdf');
echo $pdf_result;
}
catch (Exception $e) {
echo $e;
}
```
## File System
For security, the extension does not allow reading arbitrary files from the file system. This means that typst functions like `json` and `csv` will not load data. However, these functions are reproduced through the extension, so you are still able to load files from PHP and pass them to the compiler.
|
https://github.com/codevbus/resume | https://raw.githubusercontent.com/codevbus/resume/main/mv_cv.typ | typst | MIT License | #import "alta-typst.typ": alta, term, skill, styled-link
#alta(
name: "<NAME>",
links: (
(name: "email", link: "mailto:<EMAIL>"),
(name: "website", link: "https://mikevanbuskirk.io/", display: "mikevanbuskirk.io"),
(name: "github", link: "https://github.com/codevbus", display: "codevbus"),
(name: "linkedin", link: "https://www.linkedin.com/in/mikevanbuskirk/", display: "Mike Vanbuskirk"),
),
tagline: [DevOps Engineer],
[
== Experience
=== Senior DevOps Engineer \
_RedZone Software_\
#term[Apr 2024 --- Current][Remote | Grand Rapids, MI]
- Deploy and manage microservice application on ECS.
- GitOps with Pulumi and GitHub Actions.
=== Senior DevOps Engineer \
_Truffle Security_\
#term[Nov 2022 --- Feb 2024][Remote | Grand Rapids, MI]
- Deployed and configured production alerting and visualizations in Grafana.
- Configured and deployed production workloads on Kubernetes and GKE
- Performed backend feature work in Golang.
- Automated Google Cloud deployments with Terraform and GitHub Actions.
- Engineered a 300% improvement in pipeline run times.
=== Senior DevOps Engineer \
_CoinList_\
#term[Mar 2022 --- Oct 2022][Remote | Grand Rapids, MI]
- Deployed data warehouse infrastructure using Terraform, GitHub Actions, and AWS Redshift.
- Assisted with SOC2 compliance and analysis for all infrastructure.
=== Lead Infrastructure Engineer \
_Altitude Networks_\
#term[May 2021 --- Mar 2022][Remote | Grand Rapids, MI]
- Managed and modernized large AWS serverless infrastructure deployment with Terraform.
- Assisted with SOC2 compliance and analysis for all infrastructure.
=== Freelance Technical Writer \
_Self-Employed_\
#term[May 2020 - Present][Remote | Grand Rapids, MI]
- Developed expert-level, marketing-focused technical content on DevOps, DevSecOps, Cloud, and Software Engineering topics.
- Implemented process automation workflows using Zapier and Integromat.
=== Lead DevOps Engineer \
_Salesforce_\
#term[Feb 2019 --- May 2021][Remote | Grand Rapids, MI]
- Supported two, large-scale customer-facing SaaS products.
- Designed and deployed a cost analytics ETL platform using Terraform, DynamoDB, AWS serverless, and Salesforce Einstein.
=== Senior DevOps Engineer \
_Apptio_\
#term[Dec 2017 --- Feb 2019][Remote | Grand Rapids, MI]
- Supported multiple development teams in building AWS-based applications.
- Designed and deployed multi-account IAM SSO infrastructure.
=== Senior Systems Engineer \
_The Walt Disney Company_\
#term[Jul 2016 --- Nov 2017][Remote | Seattle, WA]
- Built greenfield infrastructure deployments using Chef, Terraform, Datadog, and AWS.
- Provided operational support to Tier-1 services used by multiple Disney properties.
=== Operations Engineer \
_Amazon_\
#term[Aug 2014 --- Jul 2016][Seattle, WA]
- Provided operational support and contributed to service infrastructure build-out of Tier-0 Amazon services like DynamoDB and AWS Shield.
== Education
=== University \
_Western Governors University_\
#term[Sep 2009 --- May 2012][Salt Lake City, UT]
BSc Networks Design & Management \
== Skills
AWS, Google Cloud, Terraform, Grafana, Golang, GitHub Actions, Kubernetes GitOps, Redshift, SOC2 compliance, serverless, Salesforce Einstein, Chef, Datadog, DynamoDB, Linux, Zapier, Integromat, Python, Bash, NodeJS
== Languages
#skill("HCL/Terraform", 5)
#skill("Python", 4)
#skill("Bash", 4)
#skill("Golang", 3)
#skill("NodeJS", 2)
],
)
|
https://github.com/wangjiezhe/typst-syntax | https://raw.githubusercontent.com/wangjiezhe/typst-syntax/main/CHANGELOG.md | markdown | Apache License 2.0 | # Change Log
All notable changes to the "typst-syntax" extension will be documented in this file.
Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.
## v0.0.1
- Initial release |
https://github.com/mem-courses/calculus | https://raw.githubusercontent.com/mem-courses/calculus/main/recourses-2/quiz-1-2022.typ | typst | #import "../template.typ": *
#show: project.with(
course: "Calculus II",
course_fullname: "Calculus (A) II",
course_code: "821T0160",
title: "Quiz #1 (Spring-Summer 2023 ver.)",
authors: ((
name: "memset0",
email: "https://mem.ac/",
id: [_<EMAIL>_],
),),
semester: "Spring-Summer 2024",
date: "April 9, 2024",
)
#let int = math.integral
#let divider = [#v(12em)$ "" $]
*Problem 1.* 设 $f(x) = display(cases(sin pi x\, quad& 0 <= x <= display(1/2), 0\,quad & display(1/2<=x<=1)))$。记 $display(b_n=2 int_0^1 f(x) sin (n pi x) dif x)$,$S(x) = display(sum_(n=1)^(+oo) b_n sin (n pi x))$。求 $S(0),space S(display(3/2))$。
#divider
*Problem 2.* 求过点 $(1,2,5)$ 与直线 $display(cases(x+y-z=1,2x+z=3))$ 的平面的方程。
#divider
*Problem 3.* 已知平行四边形 $A B C D$ 中,$arrow(A C) = {2,1,3}$,$arrow(B D) = {2,-3,1}$,求平行四边形 $A B C D$ 的面积。
#divider
*Problem 4.* 设 $display(sum_(n=1)^(+oo) a_n (x-1)^n)$ 的收敛半径为 $1$。判断 $display(sum_(n=1)^(+oo) (-1)^n (3^n a_n)/(n+1))$ 的敛散性。(条件收敛 / 绝对收敛 / 发散)
#divider
*Problem 5.* 设 $x in (-1,1)$,有 $display(1/(x^2-x+1) = sum_(n=0)^(+oo) a_n x^n)$,求 $a_0,a_1,a_2,dots.c,a_7$ 的每一项。
#divider
*Problem 6.* 求直线 $display((x-3)/1 = (y-1)/2 = z/(-1))$ 绕 $z$ 轴旋转一周得到的曲面方程,并判断曲面类型。
#divider
*Problem 7.* 求 $display(sum_(n=1)^(+oo) n x^(n-1))$ 的和函数与收敛域。
#divider
*Problem 8.* 设 $alpha in RR$,且已知 $display(sum_(n=1)^(+oo) (-1)^n sqrt(n) sin (1/(n^alpha)))$ 条件收敛,$display(sum_(n=1)^(+oo) ((-1)^(n-1))/(n^(2-alpha)))$ 绝对收敛,求 $alpha$ 的范围。
#divider
*Problem 9.* 求过点 $(1,-1,1)$ 与直线 $display(cases(x-y+z=1,3x-4y+2z=0))$ 垂直的平面方程。
#divider
*Problem 10.* 判断以下对错:
(1) 若 $a_n > 0$,$display(sum_(n=1)^(+oo) sqrt(a_n a_(n+1)))$ 收敛,则 $display(sum_(n=1)^(+oo) a_n)$ 收敛。
(2) 若 $a_n > 0$,$display(sum_(n=1)^(+oo) a_n)$ 收敛,则 $display(sum_(n=1)^(+oo) a_n^2)$ 收敛。
(3) 若 $a_n > 0$,$display(sum_(n=1)^(+oo) a_n)$ 发散,则 $display(sum_(n=1)^(+oo) (a_n)/(1+n^2 a_n))$ 发散。
(4) 若 $display(sum_(n=1)^(+oo) a_n)$ 条件收敛,则 $display(sum_(n=1)^(+oo) (|a_n| + a_n))$ 发散。 |
|
https://github.com/mriganksagar/cv | https://raw.githubusercontent.com/mriganksagar/cv/main/modules/professional.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Experience")
#cvEntry(
title: [Full Stack Software Engineer],
society: [Optum (UHG)],
logo: "../src/logos/optum-logo.png",
date: [2021 - Present],
location: [Gurugram, India],
description: list(
[#strong[Role and Project]: Key contributor in the development of a comprehensive service platform that integrates gym memberships, vendor shopping, and search functionalities. Additionally spearheaded the development of an operations platform designed to streamline client partner onboarding and management with features to improve project operations, and empower customer service teams with tools to efficiently resolve member issues.],
[#strong[Backend Development]: Engineered microservices for RESTful and GraphQL APIs. Leveraged Scala with Play Framework, Cats-Effects, and Quill to create highly concurrent, resilient and scalable microservices. Resulting in quick response time even under high traffic conditions, with services efficiently sustaining higher loads. Additionally, employed Spring with Java for building middleware microservices, and developed Node.js microservices using Nest.js to provide GraphQL APIs to the UI application while ensuring minimum overhead and seamless integration across the system.],
[#strong[UI and Frontend Development]: Engineered a dynamic and responsive user interface with React.js and Next.js, incorporating Redux for efficient state management. Spearheaded the rebranding of the product to implement a modern and attractive UI, resulting in a 30% increase in user retention. Implemented server-side rendering with Next.js to enhance load times and SEO. Focused on optimization, accessibility, and user engagement. Additionally, developed a cross-platform mobile application using React Native.],
[#strong[Engineering Support]: Resolved critical bugs related to payment processing and member eligibility, significantly improving system reliability and contributing to increased customer retention.]
),
tags: ("Scala", "Java", "Spring", "Play", "JavaScript", "TypeScript", "React.js", "Next.js", "React-Native")
)
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/042%20-%20Strixhaven%3A%20School%20of%20Mages/009_Blue-Green%20Ribbons.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Blue-Green Ribbons",
set_name: "Strixhaven: School of Mages",
story_date: datetime(day: 23, month: 04, year: 2021),
author: "<NAME>",
doc
)
#align(center)[#strong[I.]]
#emph[One, one, two. . .]
<NAME> counts the clusters of bubbles floating in her glass of Kiwano Fizzy Pop. Firejolt Café begins to fill up as news that Ellina, the resident barista, is giving out free drinks to mages to commemorate the end of session exams. An abundance of cackles and a cloud of chitter-chatter hang thick above the mages twittering about the week-long exams, how difficult or breezy some of the questions and tasks were, and, most importantly, the end-of-the-session Mage Tower game later this evening.
#figure(image("009_Blue-Green Ribbons/01.jpg", width: 100%), caption: [Zimone, Quandrix Prodigy | Art by: Ryan Pancoast], supplement: none, numbering: none)
Zimone stops counting.
She directs her gaze around the rim of the glass with laser focus, splitting the drink into three overlapping, swirling hexagons. She then slows the hexagons' swirls until they crash into each other. No spill. No crack on the glass. De<NAME> will definitely give her a perfect score for this. The girl smiles as she remembers the dean's first class with them mid-semester, Introduction to Forms and Fractals, and how she was the first person in her class to perfect sculpting solid shapes from water. Kianne had lowered the bridge of her thick glasses to the tip of her nose and said, "Please tell me you are considering Quandrix College for next year."
#emph[Three, five. . .] Zimone resumes counting the clusters of bubbles.
"Zimone. Zimone. #emph[Zimone!!!] "
On the third call, Zimone looks up to see her friends, Amaka and Nnanyielugo, waving at her as they squish into the café through the crowded doorway. Zimone's eyes light up as she beckons her friends over.
"How many stuck-up second-year mages did you have to fight to save these seats for us?" Nnanyielugo says as they grab Zimone into a hug.
"Please tell me we're not going to be stuck-up next session when the new mages come to Strixhaven." Amaka settles into the chair beside Zimone and signals to Ellina to send over one of her waiter-imps to take their order.
"Oh, we're definitely going to be stuck-up," Zimone says as she breaks free from Nnanyielugo's hug. "What kept you two so long?"
"You didn't hear?" Nnanyielugo whispers, then more audibly to the waiter-imp who has just arrived at their table, "Two Kiwano Fizzy Pops, please."
"Didn't hear what?" Zimone asks.
"Of course you didn't, because you ran off immediately after you handed in your script," Amaka cuts in.
"I wanted to come here to save seats for us." Zimone pouts.
"Anyway, all ten deans from the five colleges had a magical showoff for us. One last push to #emph[nudge us to the right college] ."
The waiter-imp returns with the drink and recites the #emph[All Drinks Are on the House Today ] mantra Ellina has programmed it to do.
"You may have even changed your mind about Quandrix~"
Amaka chews up the remaining words on noticing Zimone's glare. Zimone bursts into laughter, and Nnanyielugo joins her. In no time, the three friends are laughing and talking loudly between sips. Nnanyielugo, Amaka, and Zimone met a week after they got into Strixhaven, at the Biblioplex. They were studying for their very first telekinesis task but soon got into a heated argument over which of the elements—fire, air, water, or earth—was the most important. The trio argued so loudly that the treefolk librarian, Isabough, had to ask them to leave. Now, with the year ending, the friends worry if they will still be close, as they have chosen different colleges: Zimone chose Quandrix, <NAME>, and <NAME>.
"Are you <NAME>?" a squiggly voice asks.
Zimone, Amaka, and Nnanyielugo pause their chitter-chatter.
"Are you <NAME>?" the voice asks again.
This time the friends know for sure the voice is coming from the café's floor. It is Wallader the Eventual, his chestnut portmanteau filled with yet-to-be-delivered packages.
"Yes, I am <NAME>."
Wallader squints his eyes upward to meet Zimone's as if this will ascertain if the girl is telling the truth. Satisfied for whatever reason that this girl with yellow stains from her drink splattered around her necktie is indeed <NAME>, Wallader says, "A package came in for you two weeks ago. No sender's name or address. Lightweight. Wrapped with an optical illusive paper of spiraling bricks. I would have delivered it earlier, but, you know~"
The diminutive turtlefolk loves indulging anyone who cares to listen to #emph[how things are in the office] , why some packages end up delayed, how taxing it is to walk around the length and breadth of Strixhaven. Doubtless his job would be easier and more efficient if he decided to use magic or imps like everyone else at Strixhaven, but Wallader never mentions that.
"A mystery package," Nnanyielugo's eyes widen.
"Your birthday was two weeks ago, Zimone," Amaka says, nudging Zimone's hands that are now clasped around her drink.
Zimone swallows the last gulp of her drink and belches into the cup of her mouth. She certainly knows who sent the package—she has received the same package, just like the one Wallader described, for seven years now.
"They shouldn't be making café stools this high," Wallader grunts. "You don't need to reach for the ceiling for the drink to slap." His shell scrapes against one of the stools' legs as he adjusts his stance to open the portmanteau. "You'd have to get down from that stool to sign off and collect your package, Ms. Zimone."
"Zimone," Amaka tippy-taps at the table. "Let's hurry up. The Mage Tower game is about to start."
"Yes, people are already trooping to the stadium," Nnanyielugo adds.
"The two of you should head off without me so you can snatch up seats in the front row." The café is emptying out now. Zimone's eyes, ponderous with a mixture of expectation and dread, follow Wallader as he rummages inside the portmanteau for her package.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[II.]]
The first time Zimone received a mystery package from her grandmother, <NAME>, she was seven. It was her birthday. Her parents, Zihir and Dipo, had thrown her a big party and shown her to her new room. She was seven and could finally have a room to herself! Zihir kept whimpering beside the doorway about how #emph[his little girl was growing up fast ] and that Zimone should not be scared because #emph[he and Dipo were just down the hall ] while Dipo double-checked the locks on the window and inspected the bed for any wrinkles on the sheets, before finally drawing his daughter and Zihir into a long hug. When the door clicked shut, Zimone dived into the bed, flung the sheets into the air, and wrapped them around herself. This was one thing she always wanted to do: sleep in an unmade bed.
Something scratched against the window. Squirrels, the little girl guessed, as she crawled to the window on her knees, forgetting everything Zihir and Dipo told her about keeping it closed. She opened the window to see a package wrapped with a holographic paper of spiraling bricks crested at the corner of the windowsill. The night wind was starting to tip the package over, so Zimone scooped it up and closed the window. Thinking the package was one of the many gifts people brought her at the party, she tore it open. Inside the velveteen-lined box were eight green-and-blue-striped ribbons and a note:
#emph[Happy birthday Zimone,Let this be our little secret.Nimiroti.]
Before that night, Zimone had heard of Nimiroti in snippets; tiny bits of stories Zihir and Dipo whispered about #emph[Grandma] . There used to be a framed picture of a woman with her back turned, the graying locks of her dreads arched like a bow, hanging in the parlor. Dipo had removed it after Zimone asked who was in the picture. From the story bits, Zimone could piece together that her grandmother was an esteemed professor at Strixhaven, that something happened—she started forgetting things, mixing up spells, drifting off in the middle of classes, almost slammed an urn against a mage's skull—and that she left Strixhaven and was never seen again. Six years after that night, when two brown-nosed imps delivered Zimone's Strixhaven admission letter, Dipo had objected about Zimone going. It took weeks for Zihir to convince him Zimone was beyond her years and could protect herself.
The next year, another package came in with the same note, but with thirteen ribbons. Then it was twenty ribbons the year after that, then thirty-four, fifty-five~now, Zimone stares at the ribbons and note inside the velveteen-lined box on her bed. The dormitory is almost empty; most of the mages are still outside arguing about the Mage Tower game. Silverquill College won even though one of their players hypnotized Quandrix College's captain at the finals. The Mage Tower Referee Council refused to flag this clear violation as a foul. Zimone puffs hot air from her mouth before she starts counting the ribbons. #emph[Eighty-nine, one hundred forty-four, two hundred thirty-three. . .]
She cracks her cramped knuckles when she counts the three-hundred-seventy-seventh ribbon. Then she picks up the note:
#emph[Happy birthday Zimone,]
#emph[It's going to be hard getting these packages to you now that you're in Strixhaven. With all the eyes lurking in the shadows.]
#emph[So, this will be the last one. I hope you put the ribbons to good use.]
#emph[Nimiroti]
Zimone folds the ribbons and the handwritten note into the box as the dorm's door creaks open and the other students begin to troop in. Once everyone is asleep, she will plait them into the braid she's made from all her previous birthday gifts that's stashed under her pillow.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[III.]]
<NAME> squints at the array of numbers running along countless serpentine paths on the board. He mumbles to himself, wiping his sweating brow with both his wings. Then he turns back to the book he suspended in the air and ripples the surrounding wind until the book opens to a coffee-stained page. The dean snaps the chalk in his hands, flings it through the window, and then bows his head. A murmur spreads around the class but quiets as soon as Imbraham shoots up his head.
"The most important thing you have to know about #emph[theory] is that it is just #emph[substance] we haven't figured out yet," begins the dean. "I know, second-year Quandrix College mages, you expect to be spending your time conjuring fractals. #emph[Real stuff] , right?" He smirks. "But you're stuck with me learning theories. Why do you think this class is necessary? Anyone?"
"Because #emph[theory] is the building block of #emph[substance] ," a tiny voice sandwiched in the middle of the class answers.
<NAME> gasps. He'd heard a similar answer from another student, long ago. "Who said that?" He scans the room, his eyeballs almost popping out. Resigned that none of the mages will own up to the answer, he slams the book closed. "We've been on this for almost an hour. Class dismissed. See you next week, when we'll try and fail again to figure out the Vorzani Conjecture. Just like we've been doing at Quandrix for decades."
The second-year mages shuffle their feet, shoving their tables and chairs as they scramble out of Torus Hall for their next class, Intermediate Forms & Fractals (Conjuring & Counter-Conjuring) by <NAME>, at the Cultivarium. Imbraham waves to Zimone, who is trying to slip past him unnoticed. The girl's knees buckle, and her hands, clasping a pile of books to her chest, tighten.
"<NAME>," Zimone says as she begins to walk toward the dean.
"You look just like her," he notes, arching his wings.
"Like whom?"
"Your grandmother, <NAME>. Taught her in this same class many years ago."
Zimone slackens her shoulders to ease the weight of the books. Dean Imbraham makes to continue speaking but stops as the air between student and dean becomes tense. Dean Kianne, swirling past the hallway to the Cultivarium on a ball of air for her class, softens the tension and gives Imbraham something else to talk about.
"Ah, you should be going. Kianne doesn't like mages coming late for her class."
The girl nods and begins to walk away but stops at the doorway and turns to Dean Imbraham. "How was she? My grandmother, what was she like?"
"The best student I've ever taught. And when she became a professor, an even better colleague. We all loved her until~until she left."
"Thank you."
"She was also not afraid of owning up to her answers in class."
The two exchange a knowing smile before Zimone rushes out of Torus Hall. She gets to the Cultivarium just in time to catch Dean Kianne asking the mages to introduce themselves. Zimone squeezes herself into the semicircle where all the mages are sitting, with Kianne in the middle.
"<NAME>, late on your first day," Kianne says. "Care to introduce yourself to the class?"
Flustered at the sudden attention, Zimone stands up for the introduction.
"My name is <NAME> and I~"
"Is your name #emph[Zimone Wola] , or are you #emph[Zimone Wola] ?" Kianne snaps her fingers. "Young mages always struggle to embody who they are. At this point, #emph[Zimone Wola ] is more than your name. It is now who you are."
After the introductions, the dean begins her class with a recap of their first-year lectures before moving on to the intricacies of conjuring more complex forms from water: animals, plants, and architecture. She gathers the mages around the southern water fountain for practice.
"Remember, the trick is to mold with your eyes and not your hands," Kianne echoes as she walks each mage through their first complex conjuring.
#figure(image("009_Blue-Green Ribbons/02.jpg", width: 100%), caption: [Basic Conjuration | Art by: <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[IV.]]
The pages of the book are blotted at the edges with red ink, and the text is fading gradually; she has to tilt some of the pages toward the sunlight to read. Zimone wipes off the dust on the ripped cover jacket, opens #emph[The Vorzani Conjecture: Extended Reading on Fractal Theory] , and settles into a chair. She remembers the look Isabough gave her when she requested the book; the librarian's branches drooped and her rust-colored leaves folded in. Zimone had peeped into the record scroll as Isabough's branches reached to the farthest shelves to find the book. The last person to sign it out was#emph[ Nimiroti Wola] , fourteen years ago. She opens her jotter to where she scribbled #emph[VC ] on top. Dean Imbraham has ended their study on the Vorzani Conjecture and moved on to another topic because, yet again, he and the mages have failed to solve it.
Zimone mutters the words on her jotter to herself:
#emph[The Vorzani Conjecture is an ancient magical\/mathematical ritual concerning infinite sequences of unpredictable forms of mana (Dean Imbraham)]
#emph[???It holds the key to unlocking the very essence of the universe; a boundless infiniteness. Never solved. Most Strixhaven professors have since stopped studying it (only Dean Imbraham teaches it for one week to second-year Quandrix College mages). Because of how powerful and disastrous it could be???]
A minute crawls into an hour, and an hour to four. By the time the noon bell rings for lunch, Zimone is way past the middle of the book. Isabough, rustling her leaves to remind the mages to turn in their books before going for lunch, jolts Zimone from a world of unresolved equations and postulations to the present. She closes her jotter, ready for lunch, until her eye catches a strange paper's edge between the unread pages of the book. Zimone tugs at it. It's a handwritten note:
#emph[Packages of Ribbons. Numbers one step backward to go on forever. Living books that talk to you on the pathway of light.]
There is no doubt that this is Nimiroti's handwriting. Zimone folds the note into crisp quarters, tucks it into her jotter, and hurries toward Isabough to turn in the book.
Outside, she bumps into Amaka and Nnanyielugo at the stairs. The three friends squeal as they hug each other. They have barely seen one another since the semester started. It's been from one lecture to the next assignment. When they finally quiet, they begin asking each other about their new colleges, if it is everything they dreamed of, and gripe about how deep they are buried in lectures as they head toward the Dining Hall.
"Zimone, what were you reading up on?" Amaka asks.
Zimone does not answer. Her mind has wandered back to the note inside her jotter and what Nimiroti might have meant by "living books."
"Zimone!" Nnanyielugo nudges Zimone back to the present. "Amaka was asking~"
"Nnanyielugo, don't bother. She's somewhere in her Quandrix mind conjuring fractals."
Zimone rustles up a smile, masking the one-thousand-one uncertainties boiling inside her.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[V.]]
The woman is sitting in front of the fountain with her back turned, braiding stripes of blue-green ribbons into her graying locks. Zimone races toward her to save her, because the Arithmodrome is crumbling. The towers are ripping up in the middle, and the sculptures are erupting to dust. Something keeps pulling her back, until she grabs on to one of the woman's graying locks. The crumbling stops. Just as the woman tilts her head to reveal her face, Zimone's eyes flutter open. She sighs and goes back to sleep, drenched in her own sweat.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[VI.]]
Kianne's office is walled by twisted shelves weighed down by volumes of books. The professor is sitting at her table, scribbling notes for her next class, when Zimone walks in. Without looking up from her writing, she gestures for Zimone to sit. Kianne fills up another page before setting down her quill.
"Zimone. You decided to grace me with your presence today. How lucky of me!"
The gibe is evident in the professor's tone. It has been more than a week since she told Zimone to come see her after class.
"I~"
"I know. Classes. Assignments. Fear."
"Fear?"
"Yes, fear." Kianne stands up and draws the window curtains open. "Fear that I will find out what you and <NAME> have been up to."
"<NAME>?"
"Yes, he's leading you on about the Vorzani Conjecture, isn't he?"
"No, <NAME>. In fact, <NAME> has moved on to another topic in our Magical Theory class."
"Then why did you request #emph[The Vorzani Conjecture: Extended Reading on Fractal Theory ] at the Biblioplex two days ago?"
Zimone stands from her chair. "May I be excused?"
"What?"
"I don't think I want to continue this conversation. My personal study is #emph[my ] life and shouldn't be subject to faculty scrutiny."
Kianne sits back in her chair and regards the young mage in front of her. She sighs. "You may be excused, Zimone."
"Thank you." Zimone gathers her jacket around her and makes to leave.
"You know, this is the same thing he did to your grandmother—egged her on until the Oriq got hold of her." Kianne pauses to assess the weight of her words on Zimone. "You have a brilliant mind, Zimone, and you're going to make a powerful mage one day. But you need to leave the unknown. There is a reason why no one has unraveled the Vorzani Conjecture."
"Again, <NAME> has nothing to do with this."
Zimone closes the door behind her until it laps to the doorframe, quietly, like still air.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[VII.]]
The moon tonight is shy. It is hiding behind the clouds, biding its time for all of Strixhaven to drift to sleep before it comes out. Zimone looks around to ensure no one is following her. Students are not supposed to be outside the dorms at this hour, and she may get into trouble if anyone sees her. The Torches of Enlightenment are a stone's throw ahead. This is where the book is supposed to talk to her, if Nimiroti's note is right. Zimone sits at the stairs under the fourth tower and waits, twirling the braid of blue-green ribbons around her frame. An owl hoots in the distance. The night air begins to spiral around her feet.
"<NAME>, granddaughter of <NAME>, what brings you here on a dark and eerie night?" The voice comes from a dusty tome carried on four skittering metal legs.
Zimone stands. "Are you the one they call the Codex Vocifera?"
#figure(image("009_Blue-Green Ribbons/03.jpg", width: 100%), caption: [Codie, Vociferous Codex | Art by: <NAME>], supplement: none, numbering: none)
"Yes," the Codex bows closely. "You look just like her, your grandmother. We used to spend so much time together on these stairs until, you know~"
"Until #emph[what] ?" Zimone asks. "Everybody keeps insinuating that something terrible happened to my grandmother, but no one ever tells me the full story."
"Wait, nobody has told you what befell Nimiroti? Not even <NAME> and Kianne?"
Zimone shakes her head.
"Nimiroti figured out the Vorzani Conjecture. When the Oriq learned about it from their spies in Strixhaven, they captured her. She came back to Strixhaven, but we noticed that the once-esteemed Professor Nimiroti was no longer herself. She had cast a memory-loss spell on herself because if she couldn't remember the Vorzani Conjecture, then there would be nothing to tell the Oriq. And then she left Strixhaven, and never came back."
Zimone rubs her palms to keep warm from the numbing cold, silently reflecting on her grandmother, her courage to stand up to the Oriq. Another thought flickers in her mind. What if the Codex is lying? What if all these things—the mystery notes, the ribbons, the dreams—were lies?
The Codex suddenly pivots, as if "looking" at something else. "My wisdom has been requested elsewhere. Good night, Zimone."
"Wait. My grandmother's note led me here. Aren't you supposed to reveal the Vorzani Conjecture to me?"
The Codex cackles, "There is no more revealing to be done," and vanishes in a puff of mist.
Zimone begins to climb down the stairs. One step forward, one step backward. Two steps forward, one step backward. Three steps forward, one step backward. Five steps forward, three steps backward. She continues, focusing on the stairs even as the winds begin to spin around her and a laser-like power sears down her spine, until a dark shadow falls over the Torches of Enlightenment. Zimone untwirls the braid of blue-green ribbons around her body. The braid, as if it has a mind of its own, weaves into countless patterns. Finally, the weaving stops and the braid glides into Zimone's hands; she swirls it and then aims at the suns Karu and Ezza, shrouded by purple clouds.
A rustling sound in the shadows startles Zimone. She spins to investigate but trips and slams her head against one of the torches. As her consciousness fades, she wonders with horror if the same spies who watched her grandmother have found her, too.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[VIII.]]
Hot bolts course from Zimone's head into her spine. She groans and tries to open her eyes, met with blinding pain. She concedes and eases into the darkness.
"She's awake now, Extus?"
"No, she's not. Give her time."
"But we don't have time."
"We waited for fourteen years, Pita; I'm sure we can wait a little longer."
One of the men in the room pulls up a chair beside the bed Zimone is lying on. The other leans on the wall and adjusts his mask. The room is stuffy, even with all the windows open. The only source of light is the purple smoke swirling out of the men's masks.
"Where am I?" Zimone asks after some time. The throbbing pain has faded a bit. She tries to cough, but her chest hurts, as if someone stuffed tatashe inside it. Extus and Pita spring up.
"Hello Zimone," Extus begins. "My name is Extus, and I~"
"I know who you are. Your reputation precedes you." Zimone pulls herself up to a sitting position. "We're taught not to like you at Strixhaven."
Extus snickers. "I'm sorry. The Mage Hunter we sent startled you. We are usually more delicate about bringing in new recruits. But the thing is, you possess so much power, so—"
"You still haven't answered my question. #emph[Where am I?] " Zimone's eyes spot the braid of blue-green ribbons heaped at the foot of the bed.
"You are where you need to be. We have followed you for years. We know about the packages and the notes."
"You sent them?"
"No, Nimiroti is always a step ahead of us. She tailors the packages and the notes so that only you can receive and read them."
"Is this the point—you torture me until I tell you about what I know?"
"No, the Oriq doesn't torture people to join us or do our bidding. We respect everyone's free will."
"What, then, did you do to my grandmother?"
"We didn't do anything. The weight of the Vorzani Conjecture was too heavy for Nimiroti to bear. It drove her into a delirium. We tried to help her relieve the burden, but she wouldn't hear any of it." Extus pauses to catch his breath and gauge Zimone's reaction.
Zimone springs up from the bed and grabs the braid of ribbons.
"Zimone, easy, we're not here to fight."
Extus and Pita raise both their hands into the air.
"Tell us what you know," Extus continues. "And we'll tell you what we know, and together, we can control the universe. We can control time and space."
"Trading with the devil," Zimone snarls, and whips the braid of blue-green ribbons at the two men, sending them crashing into the wall at the far end of the room. "You would grind Strixhaven to dust if you possessed such power."
#figure(image("009_Blue-Green Ribbons/04.jpg", width: 100%), caption: [Decisive Denial | Art by: Lorenzo Mastroianni], supplement: none, numbering: none)
"Wouldn't it be for the best?" Pita cuts in. "Strixhaven hoards magic, clenches it with glued palms. If we destroy it, then anyone anywhere in the world can practice magic. Imagine a world like that—where magic is not left in the hands of the few."
A blast of wind rips the door off its hinges.
"Get away from her!" Dean Kianne's voice thunders. Behind her are Nnanyielugo and Amaka.
"Easy, easy," Extus whispers, his voice tepid, his stance disarming.
With lightning speed, Extus forms a ball of fire and hurls it at Kianne, who stops it midway. The dean spins the fireball, fanning its embers to make it even more menacing, before redirecting it back at Extus. Zimone swirls the braid of blue-green ribbons, weaving it into the tiny cracks of time and space, until it stops the fireball a hairbreadth away from Extus. She then draws water from the aloes and ferns on the windowsill to dissipate the fireball.
"None of this is necessary," Zimone says to Dean Kianne. "He was just about to let me go."
Kianne's eyes dart across the room, from the Oriq to Nnanyielugo and Amaka, and then to Zimone. She sees the wry smile forming at the ends of Extus's lips and then a measured glance between Zimone and Pita.
"Of course," the Oriq says. "Though I trust we'll meet again, <NAME>."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[IX.]]
Nimiroti is sitting beside the window with her back turned, braiding stripes of blue-green ribbons into her graying locks.
"She's not lucid today," the sanctuary attendant says to Zimone. "On days when things make sense to her, she keeps talking about her granddaughter, the best mage in the whole world." The sanctuary attendant smiles at her before heading off to help an old man untangle his ball of yarn so he can continue crocheting. "Just call if she needs my attention."
Zimone remembers the excitement that coursed through her when a note came from Nimiroti telling her to come visit her at The Sanctuary of the Lost, a safe haven for those affected by magic. The note was the only thing that had brought Zimone joy since her ordeal with Extus Narr. De<NAME> and <NAME> had grilled her with questions on what transpired between her and the Oriq leader; somehow, the rumor of her being an Oriq recruit spread around Strixhaven, and her friends Nnanyielugo and Amaka started avoiding her when they would bump into each other at the Biblioplex.
Zimone trudges to the window and places her hand gently on Nimiroti's shoulder. The old woman startles, then turns to her and smiles.
"Hello," Zimone says. "My name is <NAME>."
"Who are you?" The old woman asks through her toothy smile.
"Your granddaughter. See, I have ribbons just like yours. You sent them to me~"
Nimiroti gazes at the girl sitting beside her and rummages through the blank slate of her present memory. She tries, again, to remember where she has stashed this name Zimone, so familiar and yet so strange. Nimiroti sighs in defeat and says, "I don't know who you are, but I know you're someone I love."
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/006.%20popular.html.typ | typst | #set page(
paper: "a5",
margin: (x: 1.8cm, y: 1.5cm),
)
#set text(
font: "Liberation Serif",
size: 10pt,
hyphenate: false
)
#set par(justify: true)
#set quote(block: true)
#v(10pt)
= Being Popular
#v(10pt)
_May 2001_
_(This article was written as a kind of business plan for a new language. So it is missing (because it takes for granted) the most important feature of a good programming language: very powerful abstractions.)_
A friend of mine once told an eminent operating systems expert that he wanted to design a really good programming language. The expert told him that it would be a waste of time, that programming languages don't become popular or unpopular based on their merits, and so no matter how good his language was, no one would use it. At least, that was what had happened to the language he had designed.
What does make a language popular? Do popular languages deserve their popularity? Is it worth trying to define a good programming language? How would you do it?
I think the answers to these questions can be found by looking at _hackers_, and learning what they want. Programming languages are _for_ hackers, and a programming language is good as a programming language (rather than, say, an exercise in denotational semantics or compiler design) if and only if hackers like it.
== The Mechanics of Popularity
It's true, certainly, that most people don't choose programming languages simply based on their merits. Most programmers are told what language to use by someone else. And yet I think the effect of such external factors on the popularity of programming languages is not as great as it's sometimes thought to be. I think a bigger problem is that a hacker's idea of a good programming language is not the same as most language designers'.
Between the two, the hacker's opinion is the one that matters. Programming languages are not theorems. They're tools, designed for people, and they have to be designed to suit human strengths and weaknesses as much as shoes have to be designed for human feet. If a shoe pinches when you put it on, it's a bad shoe, however elegant it may be as a piece of sculpture.
It may be that the majority of programmers can't tell a good language from a bad one. But that's no different with any other tool. It doesn't mean that it's a waste of time to try designing a good language. Expert hackers can tell a good language when they see one, and they'll use it. Expert hackers are a tiny minority, admittedly, but that tiny minority write all the good software, and their influence is such that the rest of the programmers will tend to use whatever language they use. Often, indeed, it is not merely influence but command: often the expert hackers are the very people who, as their bosses or faculty advisors, tell the other programmers what language to use.
The opinion of expert hackers is not the only force that determines the relative popularity of programming languages — legacy software (Cobol) and hype (Ada, Java) also play a role — but I think it is the most powerful force over the long term. Given an initial critical mass and enough time, a programming language probably becomes about as popular as it deserves to be. And popularity further separates good languages from bad ones, because feedback from real live users always leads to improvements. Look at how much any popular language has changed during its life. Perl and Fortran are extreme cases, but even Lisp has changed a lot. Lisp 1.5 didn't have macros, for example; these evolved later, after hackers at MIT had spent a couple years using Lisp to write real programs. #footnote[Macros very close to the modern idea were proposed by <NAME> in 1964, two years after Lisp 1.5 was released. What was missing, initially, were ways to avoid variable capture and multiple evaluation; Hart's examples are subject to both.]
So whether or not a language has to be good to be popular, I think a language has to be popular to be good. And it has to stay popular to stay good. The state of the art in programming languages doesn't stand still. And yet the Lisps we have today are still pretty much what they had at MIT in the mid-1980s, because that's the last time Lisp had a sufficiently large and demanding user base.
Of course, hackers have to know about a language before they can use it. How are they to hear? From other hackers. But there has to be some initial group of hackers using the language for others even to hear about it. I wonder how large this group has to be; how many users make a critical mass? Off the top of my head, I'd say twenty. If a language had twenty separate users, meaning twenty users who decided on their own to use it, I'd consider it to be real.
Getting there can't be easy. I would not be surprised if it is harder to get from zero to twenty than from twenty to a thousand. The best way to get those initial twenty users is probably to use a trojan horse: to give people an application they want, which happens to be written in the new language.
== External Factors
Let's start by acknowledging one external factor that does affect the popularity of a programming language. To become popular, a programming language has to be the scripting language of a popular system. Fortran and Cobol were the scripting languages of early IBM mainframes. C was the scripting language of Unix, and so, later, was Perl. Tcl is the scripting language of Tk. Java and Javascript are intended to be the scripting languages of web browsers.
Lisp is not a massively popular language because it is not the scripting language of a massively popular system. What popularity it retains dates back to the 1960s and 1970s, when it was the scripting language of MIT. A lot of the great programmers of the day were associated with MIT at some point. And in the early 1970s, before C, MIT's dialect of Lisp, called MacLisp, was one of the only programming languages a serious hacker would want to use.
Today Lisp is the scripting language of two moderately popular systems, Emacs and Autocad, and for that reason I suspect that most of the Lisp programming done today is done in Emacs Lisp or AutoLisp.
Programming languages don't exist in isolation. To hack is a transitive verb — hackers are usually hacking something — and in practice languages are judged relative to whatever they're used to hack. So if you want to design a popular language, you either have to supply more than a language, or you have to design your language to replace the scripting language of some existing system.
Common Lisp is unpopular partly because it's an orphan. It did originally come with a system to hack: the Lisp Machine. But Lisp Machines (along with parallel computers) were steamrollered by the increasing power of general purpose processors in the 1980s. Common Lisp might have remained popular if it had been a good scripting language for Unix. It is, alas, an atrociously bad one.
One way to describe this situation is to say that a language isn't judged on its own merits. Another view is that a programming language really isn't a programming language unless it's also the scripting language of something. This only seems unfair if it comes as a surprise. I think it's no more unfair than expecting a programming language to have, say, an implementation. It's just part of what
a programming language is.
A programming language does need a good implementation, of course, and this must be free. Companies will pay for software, but individual hackers won't, and it's the hackers you need to attract.
A language also needs to have a book about it. The book should be thin, well-written, and full of good examples. K&R is the ideal here. At the moment I'd almost say that a language has to have a book published by O'Reilly. That's becoming the test of mattering to hackers. There should be online documentation as well. In fact, the book can start as online documentation. But I don't think that physical books are outmoded yet. Their format is convenient, and the de facto censorship imposed by publishers is a useful if imperfect filter. Bookstores are one of the most important places for learning about new languages.
== Brevity
Given that you can supply the three things any language needs — a free implementation, a book, and something to hack — how do you make a language that hackers will like?
One thing hackers like is brevity. Hackers are lazy, in the same way that mathematicians and modernist architects are lazy: they hate anything extraneous. It would not be far from the truth to say that a hacker about to write a program decides what language to use, at least subconsciously, based on the total number of characters he'll have to type. If this isn't precisely how hackers think, a language designer would do well to act as if it were.
It is a mistake to try to baby the user with long-winded expressions that are meant to resemble English. Cobol is notorious for this flaw. A hacker would consider being asked to write
```
add x to y giving z
```
instead of
```
z = x + y
```
as something between an insult to his intelligence and a sin against
God.
It has sometimes been said that Lisp should use _first_ and _rest_ instead of _car_ and _cdr_, because it would make programs easier to read. Maybe for the first couple hours. But a hacker can learn quickly enough that _car_ means the first element of a list and _cdr_ means the rest. Using first and rest means 50% more typing. And they are also different lengths, meaning that the arguments won't line up when they're called, as car and cdr often are, in successive lines. I've found that it matters a lot how code lines up on the page. I can barely read Lisp code when it is set in a variable-width font, and friends say this is true for other languages too.
Brevity is one place where strongly typed languages lose. All other things being equal, no one wants to begin a program with a bunch of declarations. Anything that can be implicit, should be.
The individual tokens should be short as well. Perl and Common Lisp occupy opposite poles on this question. Perl programs can be almost cryptically dense, while the names of built-in Common Lisp operators are comically long. The designers of Common Lisp probably expected users to have text editors that would type these long names for them. But the cost of a long name is not just the cost of typing it. There is also the cost of reading it, and the cost of the space it takes up on your screen.
== Hackability
There is one thing more important than brevity to a hacker: being able to do what you want. In the history of programming languages a surprising amount of effort has gone into preventing programmers from doing things considered to be improper. This is a dangerously presumptuous plan. How can the language designer know what the programmer is going to need to do? I think language designers would do better to consider their target user to be a genius who will need to do things they never anticipated, rather than a bumbler who needs to be protected from himself. The bumbler will shoot himself in the foot anyway. You may save him from referring to variables in another package, but you can't save him from writing a badly designed program to solve the wrong problem, and taking forever to do it.
Good programmers often want to do dangerous and unsavory things. By unsavory I mean things that go behind whatever semantic facade the language is trying to present: getting hold of the internal representation of some high-level abstraction, for example. Hackers like to hack, and hacking means getting inside things and second guessing the original designer.
_Let yourself be second guessed_. When you make any tool, people use it in ways you didn't intend, and this is especially true of a highly articulated tool like a programming language. Many a hacker will want to tweak your semantic model in a way that you never imagined. I say, let them; give the programmer access to as much internal stuff as you can without endangering runtime systems like the garbage collector.
In Common Lisp I have often wanted to iterate through the fields of a struct — to comb out references to a deleted object, for example, or find fields that are uninitialized. I know the structs are just vectors underneath. And yet I can't write a general purpose function that I can call on any struct. I can only access the fields by name, because that's what a struct is supposed to mean.
A hacker may only want to subvert the intended model of things once or twice in a big program. But what a difference it makes to be able to. And it may be more than a question of just solving a problem. There is a kind of pleasure here too. Hackers share the surgeon's secret pleasure in poking about in gross innards, the teenager's secret pleasure in popping zits. #footnote[In _When the Air Hits Your Brain_, neurosurgeon <NAME> recounts a conversation in which his chief resident, Gary, talks about the difference between surgeons and internists ("fleas"):
#quote[Gary and I ordered a large pizza and found an open booth. The chief lit a cigarette. "Look at those goddamn fleas, jabbering about some disease they'll see once in their lifetimes. That's the trouble with fleas, they only like the bizarre stuff. They hate their bread and butter cases. That's the difference between us and the fucking fleas. See, we love big juicy lumbar disc herniations, but they hate hypertension...."]
It's hard to think of a lumbar disc herniation as juicy (except literally). And yet I think I know what they mean. I've often had a juicy bug to track down. Someone who's not a programmer would find it hard to imagine that there could be pleasure in a bug. Surely it's better if everything just works. In one way, it is. And yet there is undeniably a grim satisfaction in hunting down certain sorts of bugs.
] For boys, at least, certain kinds of horrors are fascinating. Maxim magazine publishes an annual volume of photographs, containing a mix of pin-ups and grisly accidents. They know their audience.
Historically, Lisp has been good at letting hackers have their way. The political correctness of Common Lisp is an aberration. Early Lisps let you get your hands on everything. A good deal of that spirit is, fortunately, preserved in macros. What a wonderful thing, to be able to make arbitrary transformations on the source code.
Classic macros are a real hacker's tool — simple, powerful, and dangerous. It's so easy to understand what they do: you call a function on the macro's arguments, and whatever it returns gets inserted in place of the macro call. Hygienic macros embody the opposite principle. They try to protect you from understanding what they're doing. I have never heard hygienic macros explained in one sentence. And they are a classic example of the dangers of deciding what programmers are allowed to want. Hygienic macros are intended to protect me from variable capture, among other things, but variable capture is exactly what I want in some macros.
A really good language should be both clean and dirty: cleanly designed, with a small core of well understood and highly orthogonal operators, but dirty in the sense that it lets hackers have their way with it. C is like this. So were the early Lisps. A real hacker's language will always have a slightly raffish character.
A good programming language should have features that make the kind of people who use the phrase "software engineering" shake their heads disapprovingly. At the other end of the continuum are languages like Ada and Pascal, models of propriety that are good for teaching and not much else.
== Throwaway Programs
To be attractive to hackers, a language must be good for writing the kinds of programs they want to write. And that means, perhaps surprisingly, that it has to be good for writing throwaway programs.
A throwaway program is a program you write quickly for some limited task: a program to automate some system administration task, or generate test data for a simulation, or convert data from one format to another. The surprising thing about throwaway programs is that, like the "temporary" buildings built at so many American universities during World War II, they often don't get thrown away. Many evolve into real programs, with real features and real users.
I have a hunch that the best big programs begin life this way, rather than being designed big from the start, like the Hoover Dam. It's terrifying to build something big from scratch. When people take on a project that's too big, they become overwhelmed. The project either gets bogged down, or the result is sterile and wooden: a shopping mall rather than a real downtown, Brasilia rather than Rome, Ada rather than C.
Another way to get a big program is to start with a throwaway program and keep improving it. This approach is less daunting, and the design of the program benefits from evolution. I think, if one looked, that this would turn out to be the way most big programs were developed. And those that did evolve this way are probably still written in whatever language they were first written in, because it's rare for a program to be ported, except for political reasons. And so, paradoxically, if you want to make a language that is used for big systems, you have to make it good for writing throwaway programs, because that's where big systems come from.
Perl is a striking example of this idea. It was not only designed for writing throwaway programs, but was pretty much a throwaway program itself. Perl began life as a collection of utilities for generating reports, and only evolved into a programming language as the throwaway programs people wrote in it grew larger. It was not until Perl 5 (if then) that the language was suitable for writing serious programs, and yet it was already massively popular.
What makes a language good for throwaway programs? To start with, it must be readily available. A throwaway program is something that you expect to write in an hour. So the language probably must already be installed on the computer you're using. It can't be something you have to install before you use it. It has to be there. C was there because it came with the operating system. Perl was there because it was originally a tool for system administrators, and yours had already installed it.
Being available means more than being installed, though. An interactive language, with a command-line interface, is more available than one that you have to compile and run separately. A popular programming language should be interactive, and start up fast.
Another thing you want in a throwaway program is brevity. Brevity is always attractive to hackers, and never more so than in a program they expect to turn out in an hour.
== Libraries
Of course the ultimate in brevity is to have the program already written for you, and merely to call it. And this brings us to what I think will be an increasingly important feature of programming languages: library functions. Perl wins because it has large libraries for manipulating strings. This class of library functions are especially important for throwaway programs, which are often originally written for converting or extracting data. Many Perl programs probably begin as just a couple library calls stuck together.
I think a lot of the advances that happen in programming languages in the next fifty years will have to do with library functions. I think future programming languages will have libraries that are as carefully designed as the core language. Programming language design will not be about whether to make your language strongly or weakly typed, or object oriented, or functional, or whatever, but about how to design great libraries. The kind of language designers who like to think about how to design type systems may shudder at this. It's almost like writing applications! Too bad. Languages are for programmers, and libraries are what programmers need.
It's hard to design good libraries. It's not simply a matter of writing a lot of code. Once the libraries get too big, it can sometimes take longer to find the function you need than to write the code yourself. Libraries need to be designed using a small set of orthogonal operators, just like the core language. It ought to be possible for the programmer to guess what library call will do what he needs.
Libraries are one place Common Lisp falls short. There are only rudimentary libraries for manipulating strings, and almost none for talking to the operating system. For historical reasons, Common Lisp tries to pretend that the OS doesn't exist. And because you can't talk to the OS, you're unlikely to be able to write a serious program using only the built-in operators in Common Lisp. You have to use some implementation-specific hacks as well, and in practice these tend not to give you everything you want. Hackers would think a lot more highly of Lisp if Common Lisp had powerful string libraries and good OS support.
== Syntax
Could a language with Lisp's syntax, or more precisely, lack of syntax, ever become popular? I don't know the answer to this question. I do think that syntax is not the main reason Lisp isn't currently popular. Common Lisp has worse problems than unfamiliar syntax. I know several programmers who are comfortable with prefix syntax and yet use Perl by default, because it has powerful string libraries and can talk to the os.
There are two possible problems with prefix notation: that it is unfamiliar to programmers, and that it is not dense enough. The conventional wisdom in the Lisp world is that the first problem is the real one. I'm not so sure. Yes, prefix notation makes ordinary programmers panic. But I don't think ordinary programmers' opinions matter. Languages become popular or unpopular based on what expert hackers think of them, and I think expert hackers might be able to deal with prefix notation. Perl syntax can be pretty incomprehensible, but that has not stood in the way of Perl's popularity. If anything it may have helped foster a Perl cult.
A more serious problem is the diffuseness of prefix notation. For expert hackers, that really is a problem. No one wants to write `(aref a x y)` when they could write `a[x,y]`.
In this particular case there is a way to finesse our way out of the problem. If we treat data structures as if they were functions on indexes, we could write `(a x y)` instead, which is even shorter than the Perl form. Similar tricks may shorten other types of expressions.
We can get rid of (or make optional) a lot of parentheses by making indentation significant. That's how programmers read code anyway: when indentation says one thing and delimiters say another, we go by the indentation. Treating indentation as significant would eliminate this common source of bugs as well as making programs shorter.
Sometimes infix syntax is easier to read. This is especially true for math expressions. I've used Lisp my whole programming life and I still don't find prefix math expressions natural. And yet it is convenient, especially when you're generating code, to have operators that take any number of arguments. So if we do have infix syntax, it should probably be implemented as some kind of read-macro.
I don't think we should be religiously opposed to introducing syntax into Lisp, as long as it translates in a well-understood way into underlying s-expressions. There is already a good deal of syntax in Lisp. It's not necessarily bad to introduce more, as long as no one is forced to use it. In Common Lisp, some delimiters are reserved for the language, suggesting that at least some of the designers intended to have more syntax in the future.
One of the most egregiously unlispy pieces of syntax in Common Lisp occurs in format strings; format is a language in its own right, and that language is not Lisp. If there were a plan for introducing more syntax into Lisp, format specifiers might be able to be included in it. It would be a good thing if macros could generate format specifiers the way they generate any other kind of code.
An eminent Lisp hacker told me that his copy of CLTL falls open to the section format. Mine too. This probably indicates room for improvement. It may also mean that programs do a lot of I/O.
== Efficiency
A good language, as everyone knows, should generate fast code. But in practice I don't think fast code comes primarily from things you do in the design of the language. As Knuth pointed out long ago, speed only matters in certain critical bottlenecks. And as many programmers have observed since, one is very often mistaken about where these bottlenecks are.
So, in practice, the way to get fast code is to have a very good profiler, rather than by, say, making the language strongly typed. You don't need to know the type of every argument in every call in the program. You do need to be able to declare the types of arguments in the bottlenecks. And even more, you need to be able to find out where the bottlenecks are.
One complaint people have had with Lisp is that it's hard to tell what's expensive. This might be true. It might also be inevitable, if you want to have a very abstract language. And in any case I think good profiling would go a long way toward fixing the problem: you'd soon learn what was expensive.
Part of the problem here is social. Language designers like to write fast compilers. That's how they measure their skill. They think of the profiler as an add-on, at best. But in practice a good profiler may do more to improve the speed of actual programs written in the language than a compiler that generates fast code. Here, again, language designers are somewhat out of touch with their users. They do a really good job of solving slightly the wrong problem.
It might be a good idea to have an active profiler — to push performance data to the programmer instead of waiting for him to come asking for it. For example, the editor could display bottlenecks in red when the programmer edits the source code. Another approach would be to somehow represent what's happening in running programs. This would be an especially big win in server-based applications, where you have lots of running programs to look at. An active profiler could show graphically what's happening in memory as a program's running, or even make sounds that tell what's happening.
Sound is a good cue to problems. In one place I worked, we had a big board of dials showing what was happening to our web servers. The hands were moved by little servomotors that made a slight noise when they turned. I couldn't see the board from my desk, but I found that I could tell immediately, by the sound, when there was a problem with a server.
It might even be possible to write a profiler that would automatically detect inefficient algorithms. I would not be surprised if certain patterns of memory access turned out to be sure signs of bad algorithms. If there were a little guy running around inside the computer executing our programs, he would probably have as long and plaintive a tale to tell about his job as a federal government employee. I often have a feeling that I'm sending the processor on a lot of wild goose chases, but I've never had a good way to look at what it's doing.
A number of Lisps now compile into byte code, which is then executed by an interpreter. This is usually done to make the implementation easier to port, but it could be a useful language feature. It might be a good idea to make the byte code an official part of the language, and to allow programmers to use inline byte code in bottlenecks. Then such optimizations would be portable too.
The nature of speed, as perceived by the end-user, may be changing. With the rise of server-based applications, more and more programs may turn out to be i/o-bound. It will be worth making i/o fast. The language can help with straightforward measures like simple, fast, formatted output functions, and also with deep structural changes like caching and persistent objects.
Users are interested in response time. But another kind of efficiency will be increasingly important: the number of simultaneous users you can support per processor. Many of the interesting applications written in the near future will be server-based, and the number of users per server is the critical question for anyone hosting such applications. In the capital cost of a business offering a server-based application, this is the divisor.
For years, efficiency hasn't mattered much in most end-user applications. Developers have been able to assume that each user would have an increasingly powerful processor sitting on their desk. And by Parkinson's Law, software has expanded to use the resources available. That will change with server-based applications. In that world, the hardware and software will be supplied together. For companies that offer server-based applications, it will make a very big difference to the bottom line how many users they can support per server.
In some applications, the processor will be the limiting factor, and execution speed will be the most important thing to optimize. But often memory will be the limit; the number of simultaneous users will be determined by the amount of memory you need for each user's data. The language can help here too. Good support for threads will enable all the users to share a single heap. It may also help to have persistent objects and/or language level support for lazy loading.
== Time
The last ingredient a popular language needs is time. No one wants to write programs in a language that might go away, as so many programming languages do. So most hackers will tend to wait until a language has been around for a couple years before even considering using it.
Inventors of wonderful new things are often surprised to discover this, but you need time to get any message through to people. A friend of mine rarely does anything the first time someone asks him. He knows that people sometimes ask for things that they turn out not to want. To avoid wasting his time, he waits till the third or fourth time he's asked to do something; by then, whoever's asking him may be fairly annoyed, but at least they probably really do want whatever they're asking for.
Most people have learned to do a similar sort of filtering on new things they hear about. They don't even start paying attention until they've heard about something ten times. They're perfectly justified: the majority of hot new whatevers do turn out to be a waste of time, and eventually go away. By delaying learning VRML, I avoided having to learn it at all.
So anyone who invents something new has to expect to keep repeating
their message for years before people will start to get it. We
wrote what was, as far as I know, the first web-server based
application, and it took us years to get it through to people that
it didn't have to be downloaded. It wasn't that they were stupid.
They just had us tuned out.
The good news is, simple repetition solves the problem. All you have to do is keep telling your story, and eventually people will start to hear. It's not when people notice you're there that they pay attention; it's when they notice you're still there.
It's just as well that it usually takes a while to gain momentum. Most technologies evolve a good deal even after they're first launched — programming languages especially. Nothing could be better, for a new techology, than a few years of being used only by a small number of early adopters. Early adopters are sophisticated and demanding, and quickly flush out whatever flaws remain in your technology. When you only have a few users you can be in close contact with all of them. And early adopters are forgiving when you improve your system, even if this causes some breakage.
There are two ways new technology gets introduced: the organic growth method, and the big bang method. The organic growth method is exemplified by the classic seat-of-the-pants underfunded garage startup. A couple guys, working in obscurity, develop some new technology. They launch it with no marketing and initially have only a few (fanatically devoted) users. They continue to improve the technology, and meanwhile their user base grows by word of mouth. Before they know it, they're big.
The other approach, the big bang method, is exemplified by the VC-backed, heavily marketed startup. They rush to develop a product, launch it with great publicity, and immediately (they hope) have a large user base.
Generally, the garage guys envy the big bang guys. The big bang guys are smooth and confident and respected by the VCs. They can afford the best of everything, and the PR campaign surrounding the launch has the side effect of making them celebrities. The organic growth guys, sitting in their garage, feel poor and unloved. And yet I think they are often mistaken to feel sorry for themselves. Organic growth seems to yield better technology and richer founders than the big bang method. If you look at the dominant technologies today, you'll find that most of them grew organically.
This pattern doesn't only apply to companies. You see it in sponsored research too. Multics and Common Lisp were big-bang projects, and Unix and MacLisp were organic growth projects.
== Redesign
"The best writing is rewriting," wrote <NAME>. Every good writer knows this, and it's true for software too. The most important part of design is redesign. Programming languages, especially, don't get redesigned enough.
To write good software you must simultaneously keep two opposing ideas in your head. You need the young hacker's naive faith in his abilities, and at the same time the veteran's skepticism. You have to be able to think _how hard can it be?_ with one half of your brain while thinking _it will never work_ with the other.
The trick is to realize that there's no real contradiction here. You want to be optimistic and skeptical about two different things. You have to be optimistic about the possibility of solving the problem, but skeptical about the value of whatever solution you've got so far.
People who do good work often think that whatever they're working on is no good. Others see what they've done and are full of wonder, but the creator is full of worry. This pattern is no coincidence: it is the worry that made the work good.
If you can keep hope and worry balanced, they will drive a project forward the same way your two legs drive a bicycle forward. In the first phase of the two-cycle innovation engine, you work furiously on some problem, inspired by your confidence that you'll be able to solve it. In the second phase, you look at what you've done in the cold light of morning, and see all its flaws very clearly. But as long as your critical spirit doesn't outweigh your hope, you'll be able to look at your admittedly incomplete system, and think, how hard can it be to get the rest of the way?, thereby continuing the cycle.
It's tricky to keep the two forces balanced. In young hackers, optimism predominates. They produce something, are convinced it's great, and never improve it. In old hackers, skepticism predominates, and they won't even dare to take on ambitious projects.
Anything you can do to keep the redesign cycle going is good. Prose can be rewritten over and over until you're happy with it. But software, as a rule, doesn't get redesigned enough. Prose has readers, but software has users. If a writer rewrites an essay, people who read the old version are unlikely to complain that their thoughts have been broken by some newly introduced incompatibility.
Users are a double-edged sword. They can help you improve your language, but they can also deter you from improving it. So choose your users carefully, and be slow to grow their number. Having users is like optimization: the wise course is to delay it. Also, as a general rule, you can at any given time get away with changing more than you think. Introducing change is like pulling off a bandage: the pain is a memory almost as soon as you feel it.
Everyone knows that it's not a good idea to have a language designed by a committee. Committees yield bad design. But I think the worst danger of committees is that they interfere with redesign. It is so much work to introduce changes that no one wants to bother. Whatever a committee decides tends to stay that way, even if most of the members don't like it.
Even a committee of two gets in the way of redesign. This happens particularly in the interfaces between pieces of software written by two different people. To change the interface both have to agree to change it at once. And so interfaces tend not to change at all, which is a problem because they tend to be one of the most ad hoc parts of any system.
One solution here might be to design systems so that interfaces are horizontal instead of vertical — so that modules are always vertically stacked strata of abstraction. Then the interface will tend to be owned by one of them. The lower of two levels will either be a language in which the upper is written, in which case the lower level will own the interface, or it will be a slave, in which case the interface can be dictated by the upper level.
== Lisp
What all this implies is that there is hope for a new Lisp. There is hope for any language that gives hackers what they want, including Lisp. I think we may have made a mistake in thinking that hackers are turned off by Lisp's strangeness. This comforting illusion may have prevented us from seeing the real problem with Lisp, or at least Common Lisp, which is that it sucks for doing what hackers want to do. A hacker's language needs powerful libraries and something to hack. Common Lisp has neither. A hacker's language is terse and hackable. Common Lisp is not.
The good news is, it's not Lisp that sucks, but Common Lisp. If we can develop a new Lisp that is a real hacker's language, I think hackers will use it. They will use whatever language does the job. All we have to do is make sure this new Lisp does some important job better than other languages.
History offers some encouragement. Over time, successive new programming languages have taken more and more features from Lisp. There is no longer much left to copy before the language you've made is Lisp. The latest hot language, Python, is a watered-down Lisp with infix syntax and no macros. A new Lisp would be a natural step in this progression.
I sometimes think that it would be a good marketing trick to call it an improved version of Python. That sounds hipper than Lisp. To many people, Lisp is a slow AI language with a lot of parentheses. <NAME>'s official biography carefully avoids mentioning the L-word. But my guess is that we shouldn't be afraid to call the new Lisp Lisp. Lisp still has a lot of latent respect among the very best hackers — the ones who took 6.001 and understood it, for example. And those are the users you need to win.
In "How to Become a Hacker," <NAME> describes Lisp as something like Latin or Greek — a language you should learn as an intellectual exercise, even though you won't actually use it:
#quote(attribution: [<NAME>])[
Lisp is worth learning for the profound enlightenment experience you will have when you finally get it; that experience will make you a better programmer for the rest of your days, even if you never actually use Lisp itself a lot.
]
If I didn't know Lisp, reading this would set me asking questions. A language that would make me a better programmer, if it means anything at all, means a language that would be better for programming. And that is in fact the implication of what Eric is saying.
As long as that idea is still floating around, I think hackers will be receptive enough to a new Lisp, even if it is called Lisp. But this Lisp must be a hacker's language, like the classic Lisps of the 1970s. It must be terse, simple, and hackable. And it must have powerful libraries for doing what hackers want to do now.
In the matter of libraries I think there is room to beat languages like Perl and Python at their own game. A lot of the new applications that will need to be written in the coming years will be server-based applications. There's no reason a new Lisp shouldn't have string libraries as good as Perl, and if this new Lisp also had powerful libraries for server-based applications, it could be very popular. Real hackers won't turn up their noses at a new tool that will let them solve hard problems with a few library calls. Remember, hackers are lazy.
It could be an even bigger win to have core language support for server-based applications. For example, explicit support for programs with multiple users, or data ownership at the level of type tags.
Server-based applications also give us the answer to the question of what this new Lisp will be used to hack. It would not hurt to make Lisp better as a scripting language for Unix. (It would be hard to make it worse.) But I think there are areas where existing languages would be easier to beat. I think it might be better to follow the model of Tcl, and supply the Lisp together with a complete system for supporting server-based applications. Lisp is a natural fit for server-based applications. Lexical closures provide a way to get the effect of subroutines when the ui is just a series of web pages. S-expressions map nicely onto html, and macros are good at generating it. There need to be better tools for writing server-based applications, and there needs to be a new Lisp, and the two would work very well together.
== The Dream Language
By way of summary, let's try describing the hacker's dream language. The dream language is beautiful, clean, and terse. It has an interactive toplevel that starts up fast. You can write programs to solve common problems with very little code. Nearly all the code in any program you write is code that's specific to your application. Everything else has been done for you.
The syntax of the language is brief to a fault. You never have to type an unnecessary character, or even to use the shift key much.
Using big abstractions you can write the first version of a program very quickly. Later, when you want to optimize, there's a really good profiler that tells you where to focus your attention. You can make inner loops blindingly fast, even writing inline byte code if you need to.
There are lots of good examples to learn from, and the language is intuitive enough that you can learn how to use it from examples in a couple minutes. You don't need to look in the manual much. The manual is thin, and has few warnings and qualifications.
The language has a small core, and powerful, highly orthogonal libraries that are as carefully designed as the core language. The libraries all work well together; everything in the language fits together like the parts in a fine camera. Nothing is deprecated, or retained for compatibility. The source code of all the libraries is readily available. It's easy to talk to the operating system and to applications written in other languages.
The language is built in layers. The higher-level abstractions are built in a very transparent way out of lower-level abstractions, which you can get hold of if you want.
Nothing is hidden from you that doesn't absolutely have to be. The language offers abstractions only as a way of saving you work, rather than as a way of telling you what to do. In fact, the language encourages you to be an equal participant in its design. You can change everything about it, including even its syntax, and anything you write has, as much as possible, the same status as what comes predefined.
|
|
https://github.com/RolfBremer/in-dexter | https://raw.githubusercontent.com/RolfBremer/in-dexter/main/in-dexter.typ | typst | Apache License 2.0 | // Copyright 2023, 2024 <NAME>, <NAME>
// Use of this code is governed by the License in the LICENSE.txt file.
// For a 'how to use this package', see the accompanying .md, .pdf + .typ documents.
#let indexTypes = (
Start: "Start",
End: "End",
Cardinal: "Cardinal",
)
// Adds a new entry to the index
// @param fmt: function: content -> content
// @param indexType: indexTypes.Cardinal, indexTypes.Start, indexTypes.End.
// @param initial: "letter" to sort entries under - otherwise first letter of entry is used,
// useful for indexing umlauts or accented letters with their unaccented versions or
// symbols under a common "Symbols" headline
// @param index: Name of the index to add the entry to. Default is "Default".
// @param display: If given, this will be the displayed content in the index page (instead of the key entry).
// @param apply-casing: If set to auto (default) the parameter from make-index is used.
// Otherwise it overwrites the setting. Set to false for entries starting with a formula!
// @param ..entry, variable argument to nest index entries (left to right). Only the last, rightmost
// entry is the key for the entry. The others are used for grouping.
#let index(
fmt: it => it,
indexType: indexTypes.Cardinal,
initial: none,
index: "Default",
display: auto,
apply-casing: auto,
..entry,
) = (
context {
let loc = here()
[#metadata((
fmt: fmt,
indexType: indexType,
initial: initial,
index-name: index,
location: loc.position(),
page-counter: counter(page).at(loc).at(0),
page-counter-end: counter(page).at(loc).at(0),
page-numbering: loc.page-numbering(),
entry: entry,
display: display,
apply-casing: apply-casing,
))<jkrb_index>]
}
)
// Default function to semantically mark main entries in the index
#let index-main = index.with(fmt: strong)
#let as-text(input) = {
let t = type(input)
if input == none or input == auto {
""
} else if t == str {
input
} else if t == label {
repr(input)
} else if t == int {
str(input)
} else if t == content {
if input.has("text") {
input.text
} else if input.has("children") {
if input.children.len() == 0 {
""
} else {
input.children.map(child => as-text(child)).join("")
}
} else if input.has("body") {
as-text(input.body)
} else {
" "
}
} else {
panic("Unexpected entry type " + t + " of " + repr(input))
}
}
// Internal function to set plain and nested entries
#let make-entries(
entries,
page-link,
reg-entry,
use-bang-grouping,
apply-casing,
) = {
// Handling LaTeX nested entry syntax (only if it is the last entry)
if use-bang-grouping and entries.len() == 1 {
let entry = entries.at(0)
if type(entry.key) == str and entry.key.len() > 0 {
let disp = entry.display
entries = entry.key.split("!").map(e => {
let d = if type(disp) == str and disp.contains(regex("!\w+")) {
e
} else {
disp
}
(display: d, key: e)
})
if entries.last().key == "" {
let emptyKeyIndex = entries.position(e => e.key == "")
let bangCount = 0
if emptyKeyIndex != none {
bangCount = entries.len() - emptyKeyIndex
}
entries = entries.filter(e => e.key != "")
entries.last() = (display: entries.last().display + "!" * bangCount, key: entries.last().key)
}
}
}
let (entry, ..rest) = entries
if rest.len() > 0 {
let nested-entries = reg-entry.at(entry.key, default: (:))
let ref = make-entries(
rest,
page-link,
nested-entries.at("nested", default: (:)),
use-bang-grouping,
apply-casing,
)
nested-entries.insert("nested", ref)
reg-entry.insert(entry.key, nested-entries)
} else {
let key = if type(entry.key) == str {
entry.key
} else {
as-text(entry.key)
}
if type(key) == content {
panic("Entry must be string compatible. Consider specifying as display parameter.")
}
let current-entry = reg-entry.at(
key,
default: (
display: entry.display,
pages: (),
apply-casing: apply-casing,
),
)
let pages = current-entry.at("pages", default: ())
let pageRanges = pages.map(p => {
if p.indexType == indexTypes.Start and page-link.indexType == indexTypes.End {
p.indexType = "Range"
p.rangeEnd = page-link.page
p.page-counter-end = page-link.page-counter
}
return p
})
let searchFunc = p => {
p.indexType == "Range" and p.rangeEnd == page-link.page or p.indexType == indexTypes.Cardinal and p.page == page-link.page and p.fmt == page-link.fmt
}
let foundRange = pageRanges.find(searchFunc)
if foundRange == none {
pageRanges.push(page-link)
}
current-entry.insert("pages", pageRanges)
reg-entry.insert(key, current-entry)
}
reg-entry
}
// Internal function to collect plain and nested entries into the index
#let references(indexes, use-bang-grouping, sort-order) = {
let register = (:)
let initials = (:)
for indexed in query(<jkrb_index>) {
let (
fmt,
indexType,
initial,
index-name,
location,
page-counter,
page-counter-end,
page-numbering,
entry,
display,
apply-casing,
) = indexed.value
if (indexes != auto) and (not indexes.contains(index-name)) {
continue
}
// Handle tuple as (display, key)
let entries = entry.pos().map(e => {
if type(e) == content {
e = as-text(e)
}
let disp = if display == auto {
e
} else {
display
}
let k = none
if type(e) == array {
if e.len() == 2 {
disp = e.at(0)
k = e.at(1)
}
} else {
k = as-text(e)
}
(display: disp, key: k)
})
if entries.len() == 0 {
panic("expected entry to have at least one entry to add to the index")
} else {
let initial-letter = if initial == none {
let fe = sort-order(entries.first().at("key", default: "?"))
let fe2 = if type(fe) == str {
fe
} else {
as-text(fe)
}
if type(fe2) != str {
panic("Content cannot be converted to string. Use `initial` or `display` parameter for the entry.")
}
let first-letter = fe2.first()
initials.insert(first-letter, first-letter)
first-letter
} else {
if (type(initial) == dictionary) {
let letter = sort-order(initial.at("letter"))
let sort-by = initial.at("sort-by", default: letter)
initials.insert(sort-by, letter)
letter
} else if (type(initial) == str) {
let first-letter = sort-order(initial.first())
initials.insert(first-letter, first-letter)
first-letter
} else {
panic("Expected initial to be either a 'string' or '(letter: <string>, sort-by: <none|string>)'")
}
}
let reg-entry = register.at(initial-letter, default: (:))
register.insert(
initial-letter,
make-entries(
entries,
(
page: location.page,
rangeEnd: location.page,
fmt: fmt,
indexType: indexType,
page-counter: page-counter,
page-counter-end: page-counter-end,
page-numbering: page-numbering,
),
reg-entry,
use-bang-grouping,
apply-casing,
),
)
}
}
(register: register, initials: initials)
}
// Internal function to format a page link
#let render-link(
use-page-counter,
range-delimiter,
spc,
mpc,
(page, rangeEnd, indexType, fmt, page-counter, page-counter-end, page-numbering),
) = {
if page-numbering == none {
page-numbering = "1"
}
let resPage = if use-page-counter {
numbering(page-numbering, page-counter)
} else {
str(page)
}
let resEndPage = if use-page-counter {
numbering(page-numbering, page-counter-end)
} else {
str(rangeEnd)
}
let t = if indexType == "Range" {
if rangeEnd - page == 1 {
if spc != none {
resPage + spc
} else {
resPage + range-delimiter + resEndPage
}
} else if rangeEnd == page {
resPage
} else {
resPage + range-delimiter + resEndPage
}
} else if indexType == indexTypes.Start {
resPage + mpc
} else {
resPage
}
link((page: page, x: 0pt, y: 0pt), fmt[#t])
}
// First letter casing
#let first-letter-up(entry) = {
if type(entry) == str and entry.len() > 0 {
upper(entry.first()) + entry.clusters().slice(1).join()
}
}
#let apply-entry-casing(display, entry-casing, apply-casing) = {
let applied = state("applied", false)
applied.update(false)
show text: it => (
context {
let t = it.text
let transformed = entry-casing(t)
if t == transformed or applied.get() == true {
it
} else {
if apply-casing == false {
it
} else {
let t2 = entry-casing(transformed)
if t2 != transformed {
panic("entry-casing not idempotent:" + repr(t) + "~>" + repr(transformed) + "~>" + repr(t2))
}
applied.update(true)
transformed
}
}
}
)
display
}
// Internal function to format a plain or nested entry
#let render-entry(idx, entry, lvl, use-page-counter, sort-order, entry-casing, range-delimiter, spc, mpc) = {
let pages = entry.at("pages", default: ())
let display = entry.at("display", default: idx)
let render-function = render-link.with(use-page-counter, range-delimiter, spc, mpc)
let rendered-pages = [
#let p = pages.map(render-function)
#box(width: lvl * 1em)#apply-entry-casing(
display,
entry-casing,
entry.at("apply-casing", default: auto),
)#box(width: 1fr)#p.join(", ") \
]
let sub-entries = entry.at("nested", default: (:))
let rendered-entries = if sub-entries.keys().len() > 0 [
#for key in sub-entries.keys().sorted(key: sort-order) [
#render-entry(key, sub-entries.at(key), lvl + 1, use-page-counter, sort-order, entry-casing, range-delimiter, spc, mpc)
]
]
[
#rendered-pages
#rendered-entries
]
}
// Inserts the index into the document
// @param title (default: none) sets the title of the index to use.
// @param outlined (default: false) if index is shown in outline (table of contents).
// @param use-page-counter (default: false) use the value of the page counter for page number text.
// @param use-bang-grouping (default: false) support the LaTeX bang grouping syntax.
// @param sort-order (default: upper) a function to control how the entry is sorted.
// @param entry-casing (default: first-letter-up) a function to control how the
// entry key is displayed (when no display parameter is provided).
// @param range-delimiter (default: [--]) the delimiter to use in ranges, like the
// em-dash in "1--42".
// @param spc (default: "f.") Symbol(s) to mark a Single-Page-Continuation.
// If set to none, a numeric range is used instead, like "42-43".
// @param mpc (default: "ff.") Symbol(s) to mark a Multi-Page-Continuation.
// @param indexes (default: auto) optional name(s) of the index(es) to use. Auto uses all indexes.
#let make-index(
title: none,
outlined: false,
use-page-counter: false,
use-bang-grouping: false,
sort-order: k => upper(k),
entry-casing: k => first-letter-up(k),
spc: "f.",
mpc: "ff.",
range-delimiter: [--],
indexes: auto,
) = (
context {
let (register, initials) = references(indexes, use-bang-grouping, sort-order)
if title != none {
heading(
outlined: outlined,
numbering: none,
title,
)
}
let lastPage = counter(page).get().last()
let effective-mpc = if mpc == none {
range-delimiter + str(lastPage)
} else {
mpc
}
for initial in initials.keys().sorted() {
let letter = initials.at(initial)
heading(level: 2, numbering: none, outlined: false, letter)
let entry = register.at(letter)
// sort entries
for idx in entry.keys().sorted(key: sort-order) {
render-entry(idx, entry.at(idx), 0, use-page-counter, sort-order, entry-casing, range-delimiter, spc, effective-mpc)
}
}
}
) |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/op-02.typ | typst | Other | // Test scripts vs limits.
#set text(font: "New Computer Modern")
Discuss $lim_(n->oo) 1/n$ now.
$ lim_(n->infinity) 1/n = 0 $
|
https://github.com/denizenging/site | https://raw.githubusercontent.com/denizenging/site/master/page/home/_index.tr.typ | typst | #import "@local/pub-page:0.0.0": *
#show: template(title: "<NAME>", menu: (1, "home")) |
|
https://github.com/1sSay/USPTU_conspects | https://raw.githubusercontent.com/1sSay/USPTU_conspects/main/src/discrete_math/GraphTheoryIntroduction.typ | typst | // Global settings and templates
#set text(14pt)
#let def(term, color: black) = {
box(stroke: color, inset: 7pt, text()[ #term ])
}
// Lecture header and date
#let lecture_header = text()[Основы теории графов]
#let date = text()[27.09.2024]
// Header
#align(center, heading(level: 1)[Дискретная математика. \ #lecture_header ])
#align(center, text(weight: "thin")[#date])
#align(center, text(weight: "thin")[Конспект Сайфуллина Искандара БПО09-01-24])
// Content
= Конструкция графа
#def[Бинарное отношение на дискретном множестве называется *графом*]
Вершины графа: $ V = {v_1, v_2, ..., v_k } $
$ E subset.eq V times V = {(v_i, v_j) | v_i, v_j in V} $
$ G = <V, E> $
== Способы задать граф
- Списки множеств
- Списки рёбер
- Диаграмма
- Матрица смежности
= Некоторые определения
#def[*Дуга* -- направленое ребро]
#def[*Петля* -- начало и конец ребра совпадают]
#def[*Псевдограф* -- граф с петлёй]
#def[*Мультиграф* -- граф с кратными рёбрами]
#def[] |
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/025.%20gba.html.typ | typst | gba.html
The Word "Hacker"
April 2004To the popular press, "hacker" means someone who breaks
into computers. Among programmers it means a good programmer.
But the two meanings are connected. To programmers,
"hacker" connotes mastery in the most literal sense: someone
who can make a computer do what he wants—whether the computer
wants to or not.To add to the confusion, the noun "hack" also has two senses. It can
be either a compliment or an insult. It's called a hack when
you do something in an ugly way. But when you do something
so clever that you somehow beat the system, that's also
called a hack. The word is used more often in the former than
the latter sense, probably because ugly solutions are more
common than brilliant ones.Believe it or not, the two senses of "hack" are also
connected. Ugly and imaginative solutions have something in
common: they both break the rules. And there is a gradual
continuum between rule breaking that's merely ugly (using
duct tape to attach something to your bike) and rule breaking
that is brilliantly imaginative (discarding Euclidean space).Hacking predates computers. When he
was working on the Manhattan Project, <NAME> used to
amuse himself by breaking into safes containing secret documents.
This tradition continues today.
When we were in grad school, a hacker friend of mine who spent too much
time around MIT had
his own lock picking kit.
(He now runs a hedge fund, a not unrelated enterprise.)It is sometimes hard to explain to authorities why one would
want to do such things.
Another friend of mine once got in trouble with the government for
breaking into computers. This had only recently been declared
a crime, and the FBI found that their usual investigative
technique didn't work. Police investigation apparently begins with
a motive. The usual motives are few: drugs, money, sex,
revenge. Intellectual curiosity was not one of the motives on
the FBI's list. Indeed, the whole concept seemed foreign to
them.Those in authority tend to be annoyed by hackers'
general attitude of disobedience. But that disobedience is
a byproduct of the qualities that make them good programmers.
They may laugh at the CEO when he talks in generic corporate
newspeech, but they also laugh at someone who tells them
a certain problem can't be solved.
Suppress one, and you suppress the other.This attitude is sometimes affected. Sometimes young programmers
notice the eccentricities of eminent hackers and decide to
adopt some of their own in order to seem smarter.
The fake version is not merely
annoying; the prickly attitude of these posers
can actually slow the process of innovation.But even factoring in their annoying eccentricities,
the disobedient attitude of hackers is a net win. I wish its
advantages were better understood.For example, I suspect people in Hollywood are
simply mystified by
hackers' attitudes toward copyrights. They are a perennial
topic of heated discussion on Slashdot.
But why should people who program computers
be so concerned about copyrights, of all things?Partly because some companies use mechanisms to prevent
copying. Show any hacker a lock and his first thought is
how to pick it. But there is a deeper reason that
hackers are alarmed by measures like copyrights and patents.
They see increasingly aggressive measures to protect
"intellectual property"
as a threat to the intellectual
freedom they need to do their job.
And they are right.It is by poking about inside current technology that
hackers get ideas for the next generation. No thanks,
intellectual homeowners may say, we don't need any
outside help. But they're wrong.
The next generation of computer technology has
often—perhaps more often than not—been developed by outsiders.In 1977 there was no doubt some group within IBM developing
what they expected to be
the next generation of business computer. They were mistaken.
The next generation of business computer was
being developed on entirely different lines by two long-haired
guys called Steve in a garage in Los Altos. At about the
same time, the powers that be
were cooperating to develop the
official next generation operating system, Multics.
But two guys who thought Multics excessively complex went off
and wrote their own. They gave it a name that
was a joking reference to Multics: Unix.The latest intellectual property laws impose
unprecedented restrictions on the sort of poking around that
leads to new ideas. In the past, a competitor might use patents
to prevent you from selling a copy of something they
made, but they couldn't prevent you from
taking one apart to see how it worked. The latest
laws make this a crime. How are we
to develop new technology if we can't study current
technology to figure out how to improve it?Ironically, hackers have brought this on themselves.
Computers are responsible for the problem. The control systems
inside machines used to be physical: gears and levers and cams.
Increasingly, the brains (and thus the value) of products is
in software. And by this I mean software in the general sense:
i.e. data. A song on an LP is physically stamped into the
plastic. A song on an iPod's disk is merely stored on it.Data is by definition easy to copy. And the Internet
makes copies easy to distribute. So it is no wonder
companies are afraid. But, as so often happens, fear has
clouded their judgement. The government has responded
with draconian laws to protect intellectual property.
They probably mean well. But
they may not realize that such laws will do more harm
than good.Why are programmers so violently opposed to these laws?
If I were a legislator, I'd be interested in this
mystery—for the same reason that, if I were a farmer and suddenly
heard a lot of squawking coming from my hen house one night,
I'd want to go out and investigate. Hackers are not stupid,
and unanimity is very rare in this world.
So if they're all squawking,
perhaps there is something amiss.Could it be that such laws, though intended to protect America,
will actually harm it? Think about it. There is something
very American about Feynman breaking into safes during
the Manhattan Project. It's hard to imagine the authorities
having a sense of humor about such things over
in Germany at that time. Maybe it's not a coincidence.Hackers are unruly. That is the essence of hacking. And it
is also the essence of Americanness. It is no accident
that Silicon Valley
is in America, and not France, or Germany,
or England, or Japan. In those countries, people color inside
the lines.I lived for a while in Florence. But after I'd been there
a few months I realized that what I'd been unconsciously hoping
to find there was back in the place I'd just left.
The reason Florence is famous is that in 1450, it was New York.
In 1450 it was filled with the kind of turbulent and ambitious
people you find now in America. (So I went back to America.)It is greatly to America's advantage that it is
a congenial atmosphere for the right sort of unruliness—that
it is a home not just for the smart, but for smart-alecks.
And hackers are invariably smart-alecks. If we had a national
holiday, it would be April 1st. It says a great deal about
our work that we use the same word for a brilliant or a
horribly cheesy solution. When we cook one up we're not
always 100% sure which kind it is. But as long as it has
the right sort of wrongness, that's a promising sign.
It's odd that people
think of programming as precise and methodical. Computers
are precise and methodical. Hacking is something you do
with a gleeful laugh.In our world some of the most characteristic solutions
are not far removed from practical
jokes. IBM was no doubt rather surprised by the consequences
of the licensing deal for DOS, just as the hypothetical
"adversary" must be when <NAME> solves a problem by
redefining it as one that's easier to solve.Smart-alecks have to develop a keen sense of how much they
can get away with. And lately hackers
have sensed a change
in the atmosphere.
Lately hackerliness seems rather frowned upon.To hackers the recent contraction in civil liberties seems
especially ominous. That must also mystify outsiders.
Why should we care especially about civil
liberties? Why programmers, more than
dentists or salesmen or landscapers?Let me put the case in terms a government official would appreciate.
Civil liberties are not just an ornament, or a quaint
American tradition. Civil liberties make countries rich.
If you made a graph of
GNP per capita vs. civil liberties, you'd notice a definite
trend. Could civil liberties really be a cause, rather
than just an effect? I think so. I think a society in which
people can do and say what they want will also tend to
be one in which the most efficient solutions win, rather than
those sponsored by the most influential people.
Authoritarian countries become corrupt;
corrupt countries become poor; and poor countries are weak.
It seems to me there is
a Laffer curve for government power, just as for
tax revenues. At least, it seems likely enough that it
would be stupid to try the experiment and find out. Unlike
high tax rates, you can't repeal totalitarianism if it
turns out to be a mistake.This is why hackers worry. The government spying on people doesn't
literally make programmers write worse code. It just leads
eventually to a world in which bad ideas win. And because
this is so important to hackers, they're especially sensitive
to it. They can sense totalitarianism approaching from a
distance, as animals can sense an approaching
thunderstorm.It would be ironic if, as hackers fear, recent measures
intended to protect national security and intellectual property
turned out to be a missile aimed right at what makes
America successful. But it would not be the first time that
measures taken in an atmosphere of panic had
the opposite of the intended effect.There is such a thing as Americanness.
There's nothing like living abroad to teach you that.
And if you want to know whether something will nurture or squash
this quality, it would be hard to find a better focus
group than hackers, because they come closest of any group
I know to embodying it. Closer, probably, than
the men running our government,
who for all their talk of patriotism
remind me more of Richelieu or Mazarin
than <NAME> or <NAME>.When you read what the founding fathers had to say for
themselves, they sound more like hackers.
"The spirit of resistance to government,"
Jefferson wrote, "is so valuable on certain occasions, that I wish
it always to be kept alive."Imagine an American president saying that today.
Like the remarks of an outspoken old grandmother, the sayings of
the founding fathers have embarrassed generations of
their less confident successors. They remind us where we come from.
They remind us that it is the people who break rules that are
the source of America's wealth and power.Those in a position to impose rules naturally want them to be
obeyed. But be careful what you ask for. You might get it.Thanks to <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>, Matz,
<NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, and
<NAME> for reading drafts of this essay.
(The image shows <NAME> and Wozniak
with a "blue box."
Photo by <NAME>. Reproduced by permission of Steve
Wozniak.)Portuguese TranslationHebrew TranslationRomanian Translation
You'll find this essay and 14 others in
Hackers & Painters.
|
|
https://github.com/christopherkenny/tufte | https://raw.githubusercontent.com/christopherkenny/tufte/main/_extensions/tufte/typst-show.typ | typst | Other | #show: doc => tufte(
$if(title)$
title: [$title$],
$endif$
$if(subtitle)$
subtitle: [$subtitle$],
$endif$
$if(shorttitle)$
shorttitle: [$shorttitle$],
$endif$
$if(document-number)$
document-number: [$document-number$],
$endif$
$if(by-author)$
authors: (
$for(by-author)$
$if(it.name.literal)$
( name: [$it.name.literal$],
last: [$it.name.family$],
$for(it.affiliations/first)$
department: $if(it.department)$[$it.department$]$else$none$endif$,
university: $if(it.name)$[$it.name$]$else$none$endif$,
location: [$if(it.city)$$it.city$$if(it.country)$, $endif$$endif$$if(it.country)$$it.country$$endif$],
$endfor$
$if(it.email)$
email: [$it.email$],
$endif$
$if(it.orcid)$
orcid: "$it.orcid$"
$endif$
),
$endif$
$endfor$
),
$endif$
$if(date)$
date: [$date$],
$endif$
$if(lang)$
lang: "$lang$",
$endif$
$if(region)$
region: "$region$",
$endif$
$if(abstract)$
abstract: [$abstract$],
abstract-title: "$labels.abstract$",
$endif$
$if(margin)$
margin: ($for(margin/pairs)$$margin.key$: $margin.value$,$endfor$),
$endif$
$if(papersize)$
paper: "$papersize$",
$endif$
$if(mainfont)$
font: ($for(mainfont)$"$mainfont$",$endfor$),
$endif$
$if(fontsize)$
fontsize: $fontsize$,
$endif$
$if(codefont)$
codefont: ($for(codefont)$"$codefont$",$endfor$),
$endif$
$if(sansfont)$
sansfont: ($for(sansfont)$"$sansfont$",$endfor$),
$endif$
$if(section-numbering)$
sectionnumbering: "$section-numbering$",
$endif$
$if(toc)$
toc: $toc$,
$endif$
$if(toc-title)$
toc_title: [$toc-title$],
$endif$
$if(toc-indent)$
toc_indent: $toc-indent$,
$endif$
toc_depth: $toc-depth$,
draft: $if(draft)$true$else$false$endif$,
$if(footer-content)$
footer-content: $footer-content$,
$endif$
$if(distribution)$
distribution: $distribution$,
$endif$
doc,
)
|
https://github.com/huyufeifei/grad | https://raw.githubusercontent.com/huyufeifei/grad/master/docs/paper/src/ch4.typ | typst | = 在Alien中的适配
以上的驱动为满足通用性,都完全仅使用Rust库中所定义的结构写成,只依赖了一些在官方仓库中存在的包,而没有依赖任何操作系统中的结构。因此保证了该驱动的通用性,能够被多个系统代码级的复用。为验证其在实际操作系统中的可用性,在Alien中以隔离域的形式加入这些驱动并测试系统功能。这需要对驱动进行包装,使其满足隔离域的约束,能够与Alien系统进行交互。
== Alien结构
Alien是一个着眼于使用语言机制提高操作系统的健壮性与安全性,并加入多种实验性新功能的微内核操作系统。它使用了多种设计模式和约束。如模块化操作系统各组件、严格的隔离机制、各部分的动态加载与替换。这些新概念的引入使探究下一代操作系统可能的形式变得可行,为用户带来更加优秀的使用体验。
=== 模块化
Alien采用了微内核的设计,因此可以把文件系统、驱动等部分从内核中独立出来,内核中仅含有必要部分。而在这之上,微内核本身的功能也被划分为内存管理、任务调度、系统调用等多个不同的部分。
在内核中使用模块化的好处与在应用软件中使用模块化的好处一致:内核的各个部分将会高内聚和低耦合。(1)模块之间的分离带来了更小的开发和编译单元,这使得每个单元内部独立的测试会更加容易,减少了出现错误的可能性,同时在出现问题进行调试的时候,也可以快速直观的通过检查穿过接口的数据来对错误进行定位,让开发过程更有效率;(2)让代码各部分的分工更加明确,易于阅读,提高设计和实现的一致性;(3)可以拥有更加细粒度的权限赋予、功能划分。这使得完成某一功能的代码不会被授予需要之外的权限。权限的最小化降低了漏洞和恶意代码带来的风险。
Alien中被划分出来的各模块包括内存管理、互斥锁、常量与类型定义、系统配置、架构、硬件平台、文件系统、各设备驱动、任务调度器、系统调用、日志等。其中部分模块可以在 #link("https://github.com/os-module")[github/os-module] 中找到。
=== 隔离域
隔离域是Alien中的一个隔离单位。它将会被独立编译,并且需要满足开发者规定的一些安全性约束,如内存、接口、源码层面的。在Alien中,大量的模块都被写成了隔离域。而剩下一些无法作为隔离域存在的模块则归入可信代码块(TCB)。
内核中对于隔离域的处理使用了一个加载器模块。同时,为了给隔离域提供它所要依赖的功能,还有专门的一个包用于隔离域和内核的交互。隔离域所需的函数有申请可交互结构(在共享堆上分配内存)、读取系统设置、向系统输出日志等,这部分内容由内核核心部分完成并可以被隔离域调用。
此系统设计的目标是,每个隔离域内出现的任何问题都不会影响到系统的其他部分,从而保证系统的健壮性。为了实现这一目标,对于每个隔离域,都需要满足如下约束:
1. 故障隔离:一个隔离域程序出现无法恢复的故障时,内核不会停止运行,而是可以对此情况进行处理。
2. 内存隔离:一个隔离域内不能有指针指向其他隔离域中的对象。这能让系统回收任何一个隔离域时都无需担心其他隔离域受影响。
3. 动态加载:在系统运行时,对于崩溃的隔离域需要进行重启或更换。这需要系统有在运行时加载并使用一个隔离域的能力。
为了满足以上约束,设计了对于接口定义和内存使用的一些机制。
==== 交互接口
交互接口是每个隔离域与域外任何部分(包括内核和其他隔离域)进行通信时必须要使用的交互方式。在一个普通的操作系统中,各部分之间的交互是通过函数调用实现的。即被依赖的部分实现一个函数,内部完成所需功能,并且把函数的入口暴露出来,允许其他部分在代码中调用这个函数,从而完成功能。这一点在Alien中也是一样的。但是由于Alien为每个隔离域额外规定了安全约束,因此系统在进行域和其他部分之间的交互时,不能进行任何可能使安全约束遭到破坏的函数调用。
从具体的安全约束出发,对交互接口的规定为了满足内存隔离约束,需要在跨越域边界进行函数调用时,传递的参数和返回值只含有实现了`Copy` `trait`的类型(这使得该参数的数据可以直接通过逐字节拷贝来复制,而不影响其内容的有效性)或存在于共享堆上。任何存在于某一个域私有堆上的数据都不能通过函数调用的参数或返回值方式穿越域边界。通过这种方式,构造出了能够满足内存隔离的接口要求。
同时为了满足故障隔离,接口的返回值要做好收到错误的准备。因此需要所有的返回值都必须被放置于定义好的类型`RpcResult<T>`中。因此在域崩溃而无法正常返回所需值的时候,调用者可以收到一个错误而不是跟着一起崩溃。这使得隔离域的交互接口同样满足了故障隔离要求。
==== 内存隔离
不同部分所使用的内存相互暴露经常带来严重的安全问题。在现代操作系统中,一种常见的保护内存方式是使用虚拟地址空间,当一个用户程序尝试访问不属于它的地址时,操作系统或硬件会检测到这个非法操作并产生错误。而在Alien中不仅对于用户程序进行了内存隔离,对于内核的部分组成模块也进行了隔离域化,为其带来了内存隔离特性。
每个隔离域都会拥有一个单独的堆作为数据存放位置,它被叫做私有堆。同时,存在一个所有隔离域都可能访问的堆,称为公有堆。任何隔离域都不被允许访问其他隔离域的私有堆,任何可能产生这一后果的行为(如在域交互接口中传递指针或引用、从地址直接构建出指针)都会被编译器拒绝。借由这点,Alien操作系统确保了各个隔离域之间堆内存的独立性。此举带来的好处是,它在任何时候都可以安全的释放一个隔离域所拥有的所有内存,因为没有该隔离域外的指向此处的指针存在,因此把私有堆释放不会带来任何垂悬指针问题。这为域崩溃后的回收和重载提供了基础。
对于有大量数据需要在域之间进行传递的情况,系统提供了一个共享堆用于处理。借助传递指向共享堆上数据的指针,可以实现大量数据的0拷贝传递。共享堆上的数据也必须满足对于故障隔离的约束,即当某个域崩溃时,它所遗留下的对象不会对其他任何域产生影响。因此,每个共享堆上的对象都必须满足如下原则:(1)它在任何时刻拥有且只拥有一个所有权域。(2)它不能存在任何形式的可变引用,只能有不可变引用和所有权转移发生。
系统提供了一种独特的类型`RRef<T>`。它实际上是共享堆中的物体在代码中的对应,该类型相关的API也是隔离域被允许使用共享堆的唯一方式。当隔离域尝试构建一个`RRef<T>`对象时,系统会在共享堆中分配一块内存,构建出一个`T`对象,并记录该对象现在属于哪个隔离域。在跨域进行调用,使用`RRef<T>`作为参数或者返回值时,系统会自动的更新该对象的所有权域。当一个域崩溃时,检查它拥有的所有共享堆对象,这些对象此时所有权都在崩溃的域中,并且其他域对它不可能有可变引用,只有不可变引用。因此该对象能够在所有对于它的引用都结束后安全的被释放。如果崩溃的域正在尝试对其进行修改,那么由于编译器的限制,其他域不可能拥有对它的任何引用。而如果其他的域对其有不可变引用,那么该对象的值不会改变,将会一直维持直到所有的引用消失。这整个过程中对象的值都与此时第一个不可变引用出现时对象的值相一致,满足其他域对其的读取要求。
==== 故障隔离
故障隔离的主要特点是,可以在某一个隔离域崩溃时,正常地向内核其他部分返回一个`Error`类型的错误,而不是让系统出现无法运行的严重错误。系统随后可以对于该域进行重载等操作。
一个正常程序崩溃可能会有很多原因,但是一个共同点是它将被视为无法靠其自己的逻辑解决此错误。在这种情况下,rust程序在收到崩溃的通知后,会跳转到一个特殊的函数入口,被称为`panic_handle()` @reb 。通常情况下,这个函数会打印出崩溃时的调用栈和寄存器信息,供开发人员分析崩溃发生的原因。在no_std环境中,这个函数需要程序员自己实现,而Alien对于每个隔离域,都会自动生成一个错误处理函数,它干的事除了打印相关信息之外,还会让处理器跳转回到这次对于隔离域的调用之前的状态,这是通过记录即将进行调用时的寄存器信息并将其在错误处理函数中恢复而实现的。在恢复之后,本来处理器将要执行的程序应该是隔离域内的该函数,但是由于隔离域已崩溃,处理器应该转而执行一个专门返回错误的函数。这样就防止了隔离域的崩溃带来的整体系统崩溃,而能让系统继续运行。
因此调用者可能收到的回复除了正常时候的返回值以外,还可能是一个错误。这通过Rust语言提供的`Result`类型来实现。`Result`是rust预定义的一种`enum`类型,可以存放正常执行代码后得到的结果或者代码故障产生的错误。通过强制所有域接口都返回一个经过包装过的`RpcResult<T>`类型,可以确保隔离域在崩溃时调用者收到合适的返回值,做到故障隔离。
当一个域崩溃后,可能还有一些部分的代码存有该域对象,并且想要使用其完成一些工作。此时由于该对象实际已经不存在并且被回收了,因此对其的任何调用都将是错误的。为了避免这种情况,系统需要在该域被调用的时候进行一次判断,验证其是否正常存在。如果不存在,则得益于上文提到的返回值约束,可以直接向调用者返回一个错误表明域已经崩溃。否则,再把调用请求传递给域让其完成功能。这部分功能通过使用域之外的一层代理来实现。该代理内会引用开发者实际编写的域,任何尝试对域的调用都会通过代理来交互。让代理和原隔离域之间感受不到差异的透明度主要依靠Rust的`trait`系统实现。任何域提供的函数接口都是以一个`trait`的形式展现,而只要代理实现了这个`trait`,那么对于调用者来说它的行为就与原隔离域没有区别。调用者不会关注`trait`之下是什么结构如何实现的。同时,代理也需要接受域执行一个函数调用的中途可能发生的崩溃并准备好一个返回错误的函数供`panic_handle`处理时使用,向调用者返回错误。
==== 动态加载
在某个隔离域发生崩溃之后,系统不仅需要能够继续运行,还希望能在调用者没有感知的情况下对崩溃的域进行恢复。这就要求系统具有动态卸载、加载隔离域的能力,同时还需要能够保存某次调用时传入的参数。这样在收到域崩溃的信息时,系统不仅可以选择直接向调用者返回一个错误,还可以选择重新加载一次崩溃的域或者使用其他功能相同的域对它进行替换,然后再执行之前引起崩溃的那次函数调用,向调用者返回正确的结果。
为了达到这一目标,可以使用一个影子域,它的作用是保存调用时传入的参数并尝试恢复该崩溃的域。@shadow 由于传入域的参数的所有权在到达代理域的时候就已经被转移了,因此这一工作需要在外部影子处来完成。通过新的这一层封装,可以实现隔离域的透明故障恢复,同时也可以支持了用户在运行时对某个隔离域进行切换。
为了使各个隔离域能够动态加载和切换,对其他隔离域的依赖不能通过简单的传入一个该域的对象来完成。这是因为当想要替换该作为依赖的域时,使用它的域没有高效的方法得知这一消息并进行替换,因此Alien使用另一种方案,以使使用者不直接持有被依赖域的对象。使用一个BTreeMap数据结构存放所有域对象和它的标识。当某个域想要使用另一个域的功能时,只需使用系统给隔离提供的系统调用之一,从标识符从BTreeMap处获取当前系统中使用的该功能域的具体对象即可。这使得系统的灵活性增加,能够支持动态切换隔离域。
== 适配
为了在Alien中新加入一个隔离域来实现驱动功能,首先需要在Alien中新建一个结构,作为系统的驱动域实体。该结构将会被隔离域传递给系统,系统视此结构为一个驱动程序,而它实际做的工作是在驱动的Rust标准结构和Alien中特有的结构之间提供转化层。该结构将会引用并创建一个经过安全化的标准驱动作为静态对象。系统对设备的操作通过这个结构中介,转发到静态全局变量的驱动中。随后中介结构处理驱动传递回来的结果并返回给系统。当一个Alien特有的结构(如`RRef<T>`)穿越域边界来到中介结构时,它干的第一件工作是取得该参数内部的实际数据,并把拆装后的实际参数传递给自身所拥有的静态实际驱动。驱动返回的结果通常是直接的返回值或者伴随有驱动内定义的错误类型。代理结构把驱动的错误类型映射为Alien系统内的错误类型,如果是存在于共享堆上的数据指针,则还需要用共享堆封装结构`RRef<T>`将其保存,随后用隔离域必须要的返回值类型`RpcResult<T>`将其包装,最后传递回系统。这个过程提供了安全驱动和Alien之间的对接。
通过对驱动的隔离域化包装,Alien隔离域的故障恢复与动态加载功能都能够被应用在驱动上。这为驱动带来了额外的特性。与驱动直接使用Alien中的结构进行编写相比,它的缺点是多了一层函数调用,这会带来额外的开销。但是它的好处是可以将驱动程序与Alien完全独立,提高了驱动的通用性。这被认为是非常有意义的工作,可以参与进社区的相互参考、学习、改进过程中,最终推动更优秀的成果出现。因此该方案在驱动与Alien的整合形式的取舍中胜出。同时,实际使用时的情形也表明,由于对驱动的操作性能瓶颈通常不在函数的调用时间,增加的开销几乎无法感知。该方案可以作为很好的驱动与操作系统整合的示例。类似的方案可以被用于多个操作系统中。
|
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/数学模型/作业/hw5.typ | typst | #import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark, proposition,der, partialDer, Spec
#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: "作业5",
author: "YHTQ",
date: none,
logo: none,
withOutlined : false,
withTitle :false,
)
#set heading(numbering: none)
= 4.1
== 1
设 $N = 2^k$, 目标是计算:
$
sum_(s=-N)^N sum_(t = - N)^N X_(s t) e^(-(2 pi i(s u + t v))/(2 N)), forall u, v = -N, ..., N
$
令 $omega = e^(-(2 pi i)/(2 N))$,上式变为:
$
sum_(s=-N)^N sum_(t = - N)^N X_(s t) omega^(s u) omega^(t v)\
// = sum_(s=0)^N sum_(t = 0)^N X_(s t) omega^(s u) omega^(t v) + sum_(s=0)^N sum_(t = -N)^0 X_(s t) omega^(s u) omega^(t v) + sum_(s=-N)^0 sum_(t = 0)^N X_(s t) omega^(s u) omega^(t v) + sum_(s=-N)^0 sum_(t = -N)^0 X_(s t) omega^(s u) omega^(t v)\
// = sum_(s=0)^N sum_(t = 0)^N X_(s t) omega^(s u) omega^(t v) + sum_(s=0)^N sum_(t = 0)^N X_(s (t - N)) omega^(s u) omega^((t - N) v) + sum_(s=0)^N sum_(t = 0)^N X_((s - N) t) omega^(s - N) u) omega^(t v) + sum_(s=0)^N sum_(t = 0)^N X_((s - N) (t - N)) omega^((s - N) u) omega^((t - N) v)\
// = sum_(s=0)^N sum_(t = 0)^N X_(s t) omega^(s u) omega^(t v) + sum_(s=0)^N sum_(t = 0)^N X_(s (t - N)) omega^(s u) omega^((t - N) v) + sum_(s=0)^N sum_(t = 0)^N X_((s - N) t) omega^(s u) omega^(t v) + sum_(s=0)^N sum_(t = 0)^N X_((s - N) (t - N)) omega^(s u) omega^(t v)\
= sum_(s = -N/2)^(N/2) sum_(t = -N/2)^(N/2) X_(2s 2t) omega^(2 s u) omega^(2 t v) + sum_(s = -N/2)^(N/2) sum_(t = -N/2)^(N/2 - 1) X_(2s 2t-1) omega^(2 s u) omega^((2 t - 1) v) \
+ sum_(s = -N/2)^(N/2 - 1) sum_(t = -N/2)^(N/2) X_(2s-1 2t) omega^((2 s - 1) u) omega^(2 t v) + sum_(s = -N/2)^(N/2 - 1) sum_(t = -N/2)^(N/2 - 1) X_(2s-1 2t-1) omega^((2 s - 1) u) omega^((2 t - 1) v)\
= sum_(s = -N/2)^(N/2) sum_(t = -N/2)^(N/2) X_(2s 2t) omega^(2 s u) omega^(2 t v)
+ omega^(-v) sum_(s = -N/2)^(N/2) sum_(t = -N/2)^(N/2 - 1) X_(2s 2t-1) omega^(2 s u) omega^(2 t) \
+ omega^(-s) sum_(s = -N/2)^(N/2 - 1) sum_(t = -N/2)^(N/2) X_(2s-1 2t) omega^(2 s u) omega^(2 t v)
+ omega^(-v) omega^(-s) sum_(s = -N/2)^(N/2 - 1) sum_(t = -N/2)^(N/2 - 1) X_(2s-1 2t-1) omega^(2 s u) omega^(2 t v)\
$
此外,当然有 $omega^(v - N) = - omega^v, omega^(u - N) = -omega^N$,因此只需对 $u, v in [0, N]^2 sect ZZ^2$ 计算上面四个子二维傅里叶变换,然后将结果合并即可。\
方便起见,设加法和乘法的时间代价均为 $1$,$N = 2^k$ 对应二维傅里叶展开的计算次数约为:
$
a_(2^k) = 4 a_(2^(k-1)) + 7 dot 4 dot 2^(2 k)
$
令 $b_k = 2^(-k) a_(2^k)$,将有:
$
2^k b_k = 2^(k+1) b_(k-1) + 7 dot 4 dot 2^(2 k)\
b_k = 2 b_(k-1) + 28 2^k\
2^(-k) b_k = 2^(-(k-1)) b_(k-1) + 28\
2^(-k) b_k = 28 k + A\
b_k = 28 k 2^k + A 2^k\
a_(2^k) = 28 k 2^(2 k) + A 2^(2 k)\
$
总之,时间复杂度为 $O(N^2 log N)$
= 4.22
== 1
#let xi2 = $x_i$
#let xi1 = $x_(i-1)$
#let uxi2 = $u(xi2)$
#let uxi1 = $u(xi1)$
#let di = $x_(i) - x_(i-1)$
#let din = $x_(i-1) - x_i$
任取 $x$ 使得 $x_(i-1) <= x <= x_i$,将有:
$
&quad abs(u(x) - u_I (x)) = abs(u(x) - (x - x_i)/(x_(i-1) - x_i) u(x_(i-1)) - (x - x_(i-1))/(x_i - x_(i-1)) u(x_i))\
&= abs(((x - x_(i-1))/(x_i - x_(i-1)) + (x - x_i)/(x_(i-1) - x_i))u(x) - (x - x_i)/(x_(i-1) - x_i) u(x_(i-1)) - (x - x_(i-1))/(x_i - x_(i-1)) u(x_i))\
&= abs((x - x_i)/(x_(i-1) - x_i)(u(x) - u(x_(i-1))) + (x - x_(i-1))/(x_i - x_(i-1))(u(x) - u(x_i)))\
&= abs((x - x_i)/(x_(i-1) - x_i)(u(x_(i-1)) - u(x)) + (x - x_(i-1))/(x_i - x_(i-1))(u(x_i) - u(x)))\
&= abs((x - x_i)/(x_(i-1) - x_i)((x_(i-1) - x) u'(x) + 1/2 (x_(i-1) - x) u''(xi_1)) \
&quad + (x - x_(i-1))/(x_i - x_(i-1))((x_i - x)u'(x) + 1/2 (x_i - x)^2 u''(xi_2)))\
&= 1/2 abs(((x-x_i)(x-x_(i-1)))/(x_(i-1) - x_i)) abs((x - x_(i-1)) u''(xi_1) - (x_i - x) u''(xi_2))\
&<= 1/2 abs(((x-x_i)(x-x_(i-1)))/(x_(i-1) - x_i)) abs(x - x_(i-1) + x_i - x) norm(u'')_infinity\
&<= 1/2 abs(((x_i - x)(x-x_(i-1)))) norm(u'')_infinity\
&<= 1/8 h^2 norm(u'')_infinity
//= abs(((x-x_i)(x-x_(i-1)))/(x_(i-1) - x_i)) abs(u'(xi_1) - u'(xi_2))\
//= abs(((x-x_i)(x-x_(i-1)))/(x_(i-1) - x_i)) abs(xi_1 - xi_2) abs(u''(xi_3))\
//= abs(((x_i - x)(x-x_(i-1)))/(x_(i-1) - x_i)) abs(xi_1 - xi_2) abs(u''(xi_3))\
//<= 1/4 h^2 abs((xi_1 - xi_2)/(x_(i-1) - x_i)) norm(u'')_infinity
$
$
u'_I (x) &= uxi1/din + uxi2/di\
abs(u'_I (x) - u'(x)) &= abs(uxi1/din + uxi2/di - u'(x))\
&= abs(((xi1 - x)u'(x) + 1/2 (xi1 - x)^2 u''(xi_1))/din + ((xi2 - x)u'(x) + 1/2 (xi2 - x)^2 u''(xi_2))/di - u'(x))\
&= 1/2 1/abs(di) abs((xi2 - x)^2 u''(xi_2) - (xi1 - x)^2 u''(xi_1))\
&<= 1/2 1/abs(di) abs((xi2 - x)^2 + (xi1 - x)^2) norm(u'')_infinity\
$
其中 $(xi2 - x)^2 + (xi1 - x)^2$ 是正的,最大值在边界处取得,为 $(di)^2$,上式不超过:
$
1/2 abs(di) <= 1/2 h norm(u'')_infinity
$
(不确定何处会引入 $sqrt(b-a)$,看起来也不是很合理,在每个点处的近似似乎应该和区间大小没有什么关系)
= 5.6
== 1
#answer[
对于中点公式 $Q f = (b - a) f((a + b) / 2)$ 和梯形公式 $Q f = (b - a) (f(a) + f(b)) / 2$,不难验证它们在线性函数上的估计都是准确的,而设:
$
f = (x - 1/2)^2
g = x(1-x)
$
均考虑 $[0, 1]$ 上的积分,则中点公式显然在 $f$ 上不准确,梯形公式在 $g$ 上不准确,因此两者恰有一阶代数精度
对于辛普森公式:
$
Q f = (b - a) (f(a) + 4 f((a + b) / 2) + f(b)) / 6
$
同样不妨简化为 $[0, 1]$ 上积分,公式变为:
$
Q f = 1/6 (f(0) + 4 f(1/2) + f(1))
$
容易验证它对线性函数估计是准确的,而取 $f = x(1-x)$ 有:
$
integral_(0)^(1) x(1-x) dif x = 1/6 = 1/6 (0 + 4 * 1/4 + 0)
$
任做线性组合可得辛普森公式对于任何不超过二次的多项式都是准确的。\
再取 $f = x^3$,有:
$
integral_(0)^(1) x^3 dif x = 1/4 = 1/6 (0 + 4 * 1/8 + 1)
$
类似的对于任何不超过三次的多项式都是准确的。\
再取 $f = x^4$,有:
$
integral_(0)^(1) x^4 dif x = 1/5 != 1/6 (0 + 4 * 1/16 + 1)
$
从而恰好有三阶代数精度
]
== 2
#answer[
#lemmaLinear[][
+ 每个 $p_n (x)$ 都是首项为 $k_n$ 的 $n$ 次多项式
+ 每个 $p_n (x)$ 都与 $p_i (x), i < n$ 正交
]
#proofLinear[
归纳证明,以上性质当然对 $n = 0, 1$ 正确,假设它们对 $0, 1, 2, ..., n$ 都正确,对 $n + 1$ 时情形分别证明三者:
+ 由递推式 $p_(n+1) (x) = (a_n x - b_n) p_n (x) - c_n p_(n-1) (x)$ 及归纳假设,当然 $p_(n+1) (x)$ 是首项为 $k_n$ 的 $n$ 次多项式
+ 计算:
-
$
inner(p_(n+1), p_n) &= inner((a_n x - b_n) p_n , p_n)\
&= a_n inner(x p_n, p_n) - b_n inner(p_n, p_n)\
&= a_n inner(x p_n, p_n) - a_n inner(x p_n, p_n)/inner(p_n, p_n) inner(p_n, p_n)\
&= 0
$
-
$
inner(p_(n+1), p_(n-1))
&= a_n inner(x p_n, p_(n-1)) - c_n inner(p_(n-1), p_(n-1))\
&= a_n inner(x p_n, p_(n-1)) - a_n/a_(n-1) inner(p_n ,p_n)\
&= a_n/a_(n-1) (inner(p_n, a_(n-1) x p_(n-1)) - inner(p_n ,p_n))\
&= a_n/a_(n-1) inner(p_n, a_(n-1) x p_(n-1) - p_n)\
&= a_n/a_(n-1) inner(p_n, b_n p_(n-1) + c_n p_(n-2))\
&= 0
$
证毕
]
由引理,$p_0, p_1, ..., p_n$ 一定构成 $generatedBy(1\, x\, ... \, x^n)$ 的一组基,进而 $p_(n+1)$ 与其中元素都正交,当然是正交多项式,证毕
]
|
|
https://github.com/drunkenQCat/typst-arknights-simulator | https://raw.githubusercontent.com/drunkenQCat/typst-arknights-simulator/master/README.md | markdown | # Typst Arknights Simulator
一个基于typst,用于生成明日方舟剧情文本风格图片的小项目。
生成效果如下:
![丰川祥子](test_output2.png)
## 配置需求
1. typst 0.10.0以上
2. [HarmonyOS Sans SC](https://github.com/ajacocks/harmonyos-sans-font)字体库
## 使用方法
1. 安装typst
2. 克隆本仓库
3. 在typst代码中引用
```latex
#import "typst arknights simulator/template.typ": arknights_sim
```
4. 如果想要直接查看输出效果,可以进入`typst arknights simulator`目录,将`template.typ`中注释的代码取消注释,并运行
> typst c -f png .\template.typ "output{n}.png"
## 文件目录说明
```text
filetree
├── README.md
├── template.typ //模板文件
├── LICENSE.txt
├── /pics/
│ ├── ...
│ ├── dialog_background.png //对话框黑条
│ ├── ...
```
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/field-00.typ | typst | Other | // Test field on dictionary.
#let dict = (nothing: "ness", hello: "world")
#test(dict.nothing, "ness")
#{
let world = dict
.hello
test(world, "world")
}
|
https://github.com/kotatsuyaki/canonical-nthu-thesis | https://raw.githubusercontent.com/kotatsuyaki/canonical-nthu-thesis/main/README.md | markdown | MIT License | # canonical-nthu-thesis
A [Typst](https://typst.app/docs/) template for master theses and doctoral dissertations for NTHU (National Tsing Hua University).
國立清華大學碩士(博士)論文[Typst](https://typst.app/docs/)模板。
- [Typst Universe Package](https://typst.app/universe/package/canonical-nthu-thesis)
- [Codeberg Repo](https://codeberg.org/kotatsuyaki/canonical-nthu-thesis)
![](./covers.png)
## Usage
### Installing the Chinese fonts
This template uses the official fonts from the Ministry of Education of Taiwan (Edukai/TW-MOE-Std-Kai), which are required to be downloaded and installed manually from [language.moe.gov.tw](https://language.moe.gov.tw/001/Upload/Files/site_content/M0001/edukai-5.0.zip). For the Typst web app, upload the font to the project directory.
此模板中文部分使用教育部標準楷書字體(Edukai/TW-MOE-Std-Kai),在編譯文件前需要自[language.moe.gov.tw](https://language.moe.gov.tw/001/Upload/Files/site_content/M0001/edukai-5.0.zip)下載並手動安裝。若使用的是Typst web app,則需要下載後上傳至Typst專案內。
### Editing
All the content of the thesis are in the `thesis.typ` file.
In the beginning of `thesis.typ`, there is a call to the `setup-thesis(info, style)` function that configures the metadata (the titles and the author etc.) and the styling of the thesis document.
Replace the values with your own.
所有論文內容皆位於`thesis.typ`檔案內。該檔案前段的部分呼叫了`setup-thesis(info, style)`函式,設置論文的雜項資訊(標題及作者等)及外觀選項,請置換為自己的資訊。
### Local usage
```sh
$ typst init @preview/canonical-nthu-thesis:0.1.0 my-thesis
$ cd my-thesis
$ typst watch thesis.typ
```
## Development
Development and issue tracking happens on the [repository on Codeberg](https://codeberg.org/kotatsuyaki/canonical-nthu-thesis).
## License
This project is licensed under the MIT License.
|
https://github.com/quicktus/book-notes-template | https://raw.githubusercontent.com/quicktus/book-notes-template/main/template.typ | typst | #import grid : cell
#set page(
paper: "a4",
margin: (x: 1.5cm, y: 1.2cm),
)
#set text(
font: "Open Sans",
lang: "en",
size: 10pt,
fill: rgb("#5d5d5d")
)
#set rect(
inset: 10pt,
fill: rgb("#dbdbdb"),
width: 100%,
height: 50pt
)
// form box
#grid(
columns: (1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr,),
rows: 2,
align: center + horizon,
gutter: 4pt,
cell(
align: top + left,
colspan: 1,
[#rect[NR]],
),
cell(
align: top + left,
colspan: 7,
[#rect[TITLE]],
),
cell(
align: top + left,
colspan: 4,
[#rect[AUTHOR]],
),
cell(
align: top + left,
colspan: 2,
[#rect[DATE READ]],
),
cell(
align: top + left,
colspan: 7,
[#rect[VERDICT]],
),
cell(
align: top + left,
colspan: 3,
[#rect[RECOMMENDED BY]],
),
)
#let pat = pattern(
size: (20pt, 20pt),
relative: "parent",
place(
dx: 5pt,
dy: 5pt,
rotate(45deg, square(
size: 3pt,
fill: rgb("#dbdbdb"),
)),
),
)
#rect(width: 100%, height: 650pt, fill: pat)
|
|
https://github.com/ScaleXY/pp03-laravel-typst | https://raw.githubusercontent.com/ScaleXY/pp03-laravel-typst/main/CHANGELOG.md | markdown | MIT License | # Changelog
All notable changes to `laravel-typst` will be documented in this file.
|
https://github.com/arthurcadore/eng-telecom-workbook | https://raw.githubusercontent.com/arthurcadore/eng-telecom-workbook/main/semester-7/COM_1/homework9/homework.typ | typst | MIT License | #import "@preview/klaro-ifsc-sj:0.1.0": report
#import "@preview/codelst:2.0.1": sourcecode
#show heading: set block(below: 1.5em)
#show par: set block(spacing: 1.5em)
#set text(font: "Arial", size: 12pt)
#set highlight(
fill: rgb("#c1c7c3"),
stroke: rgb("#6b6a6a"),
extent: 2pt,
radius: 0.2em,
)
#show: doc => report(
title: "Modulações GMSK e CPM",
subtitle: "Sistemas de Comunicação I",
authors: ("<NAME>",),
date: "19 de Agosto de 2024",
doc,
)
= Introdução:
Neste relatório, iremos abordar as modulações GMSK (Gaussian Minimum Shift Keying) e CPM (Continuous Phase Modulation), que são técnicas de modulação digital utilizadas em sistemas de comunicação móveis e sem fio.
= Modulação GMSK:
A modulação GMSK (Gaussian Minimum Shift Keying) é uma técnica de modulação digital que é utilizada em sistemas de comunicação móveis, como o GSM (Global System for Mobile Communications), implementado na técnologia do 2G.
A modulação GMSK é uma variação da modulação MSK (Minimum Shif Keying) desenvolvida na década de 50 pelos desenvolvedores da Collins Radio. A MSK é caracterisada por ser uma modulação de deslocamento mínimo de frequência, onde a frequência da portadora é deslocada de acordo com os bits de entrada. Vamos verificar suas princiapais vantagens e desvantagens em relação a modulação MSK.
== Desvantagens:
Uma das principais desvantagens, segundo [1] _In GMSK systems the BTb product refers to the pre-modulation Gaussian filter cut-off frequency. A BTb = 0.3 and BTb = 0.39 will lead to an increased spectral efficiency, as compared to BTb = 0.5, however, a more complex implementation and increased sensitivity to CII and to radio propagation_, a utilização do filtro gaussiano para a suavização das transições de fase no GMSK aumenta a memória de modulação no sistema e assim, podendo causar uma maior interferência intersimbólica.
#figure(
figure(
rect(image("./pictures/3.png")),
numbering: none,
caption: [Suavização das transições GMSK causada pela memoria do filtro gaussiano]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Como apresentado acima, podemos verificar que a utilização do filtro gaussiano tornam mais suaves as transições entre os bits, oque pode dificultar a identificação do sinal recebido especialmente em sistemas com alta taxa de transmissão e com escorregamento de fase, onde pode-se coletar amostras do sinal em momentos incorretos.
Dessa forma, fica mais difícil a diferenciação entre diferentes valores de dados transmitidos e necessitando de algoritmos de equalização de canal mais complexos.
== Vantagens:
A principal vatagem da modulação GMSK em relação a MSK é a utilização de um filtro gaussiano para suavizar as transições de fase, o que resulta em uma *maior eficiência espectral e uma melhor imunidade a interferências*.
O livro [1] também apresenta uma relação entre a relação entre a densidade espectral de potência e diferentes valores de BT (bandwidth-time product) para a modulação GMSK.
#figure(
figure(
rect(image("./pictures/2.png")),
numbering: none,
caption: [Comparativo entre a modulação MSK e GMSK]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Nota-se pelos valores apresentados nas linhas 11 e 12, que quanto menor o valor de BT, maior a eficiência espectral da modulação, pois sua densidade espectral de potência é mais concentrada em torno da frequência central.
#figure(
figure(
rect(image("./pictures/1.png")),
numbering: none,
caption: [Comparativo entre a modulação MSK e GMSK]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Essa relação torna-se bastante visivel na imagem apresentada acima, onde os valores de BT "0.3" e "0.5" apresentam uma maior eficiência espectral em relação a modulação MSK.
Segundo o livro [1] _Use of NLA power amplifier efficiency reasonably robust performance (Le., BER = 10-3; CIN = 30 dB) coherent and noncoherent detection possible; chips (silicon VLSI) available European standards use GMSK; and potential for simplified (somewhat) CR - synchronization. _, outra grande vantagem da modulação GMSK é a possibilidade de utilização de amplificadores de potência não lineares, o que resulta em uma maior eficiência energética do sistema.
= Modulação CPM:
A modulação CPM (Continuous Phase Modulation) é uma técnica de modulação digital que tem como principal caracteristica a continuidade da fase do sinal modulado. A modulação CPM é uma variação da modulação MSK, onde a continuidade da fase é mantida entre os símbolos transmitidos.
Segundo [2] _"Each symbol is modulated by gradually changing the phase of the carrier from the starting value to the final value, over the symbol duration. The modulation and demodulation of CPM is complicated by the fact that the initial phase of each symbol is determined by the cumulative total phase of all previous transmitted symbols, which is known as the phase memory."_ Essa modulação utiliza uma memoria de fase para gradualmente alterar a fase do sinal modulado, o que resulta em uma maior imunidade a interferências e uma maior eficiência espectral.
#figure(
figure(
rect(image("./pictures/4.png")),
numbering: none,
caption: [Diagrama de blocos de um sistema de comunicação CPM]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Como apresentado na imagem acima, o processo de modulação CPM é bastante similar ao processo de modulação MSK, onde a fase do sinal modulado é alterada de acordo com os bits de entrada.
== Destavanagens:
A principal desvantagem segundo a wikipedia [2] _"Therefore, the optimal receiver cannot make decisions on any isolated symbol without taking the entire sequence of transmitted symbols into account."_ é a necessidade de se levar em conta todos os símbolos transmitidos para a tomada de decisão no lado do receptor, o que por consequência necessita de uma mémoria para guardar todos os simbolos recebidos e assim, aumentando a complexidade do sistema.
== Vantagens:
A principal vantagem da modulação CPM é a sua caracteristica de suavidade na variação da fase na transmissão do sinal pelo meio, isso resulta em uma maior imunidade a interferências causadas por componentes de alta frequência geradas pela variação abrupta de potência e também lhe conferem uma maior eficiência espectral.
Segundo o livro [4] _"The CPFSK modulation in this paper is a special case of the more general class of continuous phase modulation (CPM) [9]. Because the signals defined in (1) are zero outside the symbol epoch [0, Ts), the CPFSK modulation in this paper is full-response."_a modulação CPM pode também ser aplicada junto a FSK (Frequency Shift Keying) para gerar uma outra técnica de modulaçã denominiada (CPFSK) que é utilizada em sistemas de comunicação.
Essa técnica de modulação pode ser aplicada em diversos sistemas de comunicação baseados em FHSS (Frequency Hopping Spread Spectrum) e DSSS (Direct Sequence Spread Spectrum) para gerar uma maior eficiência espectral e uma maior imunidade a interferências, como comentado pelo autor [2] _"While the CPFSK modulation described in this paper can
be used for a variety of applications, it is especially attractive for frequency hopping spread spectrum (FHSS) systems"_
= Conclusão:
A partir do estudo das modulações GMSK e CPM, podemos concluir que ambas as técnicas de modulação apresentam vantagens e desvantagens.
A modulação GMSK é uma técnica de modulação que utiliza um filtro gaussiano para suavizar as transições de fase, o que resulta em uma maior eficiência espectral e uma maior imunidade a interferências. Já a modulação CPM é uma técnica de modulação que mantém a continuidade da fase do sinal modulado, o que resulta em uma maior imunidade a interferências e uma maior eficiência espectral.
= Referências Bibliográficas:
- [1] - #link("https://www.ieee802.org/11/Documents/DocumentArchives/1993_docs/1193097_scan.pdf")[<NAME>. (1993, July). FQPSK: A modulation-power efficient RF amplification proposal for increased spectral efficiency and capacity GMSK and Π/4-QPSK compatible PHY standard. In IEEE 802.11 Wireless Access Methods Phys. Layer Spec. Doc.]
- [2] - #link("https://en.wikipedia.org/wiki/Continuous_phase_modulation")[wikipedia - Continuous_phase_modulation]
- [3] - #link("https://www.electronics-notes.com/articles/radio/modulation/what-is-gmsk-gaussian-minimum-shift-keying.php")[Gaussian Minimum Shift Keying, GMSK is a form of modulation based on frequency shift keying that has no phase discontinuities and provides efficient use of spectrum as well as enabling high efficiency radio power amplifiers.]
- [4] - #link("https://web.archive.org/web/20121119032946/http://csee.wvu.edu:80/~mvalenti/documents/49IyerSeshadriCISS2k7.pdf")[<NAME>, <NAME>, <NAME>, and <NAME>, The capacity of noncoherent continuous-phase frequency shift keying, in Proc. Conf. on Info. Sci. and Sys (CISS), (Baltimore, MD), Mar. 2007.] |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/construct-02.typ | typst | Other | // The inner rectangle should also be yellow here.
// (and therefore invisible)
#[#set rect(fill: yellow);#text(1em, rect(inset: 5pt, rect()))]
|
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/01-number-theory/02-equiv-relation.typ | typst | Other | #import "../../utils/core.typ": *
== Отношение эквивалентности и разбиение на классы
#def[
Отношение эквивалентности --- бинарное отношение,
удовлетворяющее следующим свойствам: рефлексивность, симметричность, транзитивность.
]
#def[
Разбиение на классы множества $M$ --- это представление $M$ в виде
$M = limits(union.big)_(i in I) M_i$,
где $M_i$ --- классы, $I$ --- индексное множество,
$M_i sect M_j = nothing$ при $i eq.not j$.
]
#th[
Пусть $M = limits(union.big)_(i in I) M_i$ --- разбиение на классы.
Введем отношение $sim$ над $M$ так, что $a sim b <==> exists i in I : a, b in M_i$.
Тогда $sim$ --- отношение эквивалентности.
]
#proof[
Рефлексивность и симметричность очевидны. Докажем транзитивность.
$
a sim b, b sim c ==>
exists i, j : cases(a\, b in M_i, b\, c in M_j)
$
Тогда $b in M_i sect M_j$, но так как $M_i sect M_j eq.not nothing$ при неравных $i$ и $j$,
$i = j$. Значит $a, b, c in M_i$.
]
#th[
Пусть $sim$ --- отношение эквивалентности на $M$.
Значит существует разбиение на классы $M = limits(union.big)_(i in I) M_i$ такое,
что $forall a, b in M: a sim b <==> exists i : a, b in M_i$.
]
#proof[
Рассмотрим $a in M$. Назовем классом элемента $a$ множество
$ [a] = {b in M divides a sim b}. $
Докажем, что для любых элементов $a$ и $b$, либо $[a] = [b]$, либо $[a] sect [b] = nothing$.
Пусть $[a] sect [b] eq.not nothing$. Тогда
$
exists x in [a] sect [b]
==> cases(
x in [a],
x in [b]
)
limits(==>)^("опр. класса") cases(
x sim a,
x sim b
)
limits(==>)^("транзитивность" sim) a sim b.
$
$
(forall c in [a] space c sim a limits(==>)^(a sim b) c sim b) & ==> c in [b]\
(forall c in [b] space c sim b limits(==>)^(a sim b) c sim a) & ==> c in [a]
$
Из $(1)$ и $(2)$ получаем $[a] = [b]$.
Тогда искомое разбиение можно построить как
$
X = {[a] divides a in M}.
$
Действительно $forall a in M$, так как $a in [a]$, то $M = limits(union.big)_(alpha in I) M_i$,
а так как различные классы не пересекаются (доказано выше) $forall a, b$ $[a] eq.not [b]$.
]
#def[
Построенное множество $X$ называют _фактор-множеством_ множества $M$
по отношению эквивалентности $sim$, обозначение: $factor(M, sim)$.
]
#example[
$factor(ZZ, sim) = {[z] divides z in ZZ } = {[0], [1], [2], ...}$
] |
https://github.com/jrihon/multi-bibs | https://raw.githubusercontent.com/jrihon/multi-bibs/main/chapters/01_chapter/bib_01_chapter.typ | typst | MIT License | #let dict_01_chapter = (
"Iupac1983nucleicacids": 1,
"Neese2021orca": 2,
"Cremer1975general": 3,
)
#let biblio = (
bibchapter: dict_01_chapter,
bibyml: "../chapters/01_chapter/01_chapter.yml",
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/songb/0.1.0/tests/autobreak2.typ | typst | Apache License 2.0 | // SPDX-FileCopyrightText: 2024 <NAME> <<EMAIL>>
//
// SPDX-License-Identifier: CC0-1.0
#import "../autobreak.typ": autobreak;
#set page(paper: "a6",margin: (inside: 14mm, outside: 6mm, y: 10mm))
#pagebreak()
#autobreak[
== Allzeit bereit
#lorem(180)
]
#autobreak[
== <NAME>
#lorem(240)
]
#autobreak[
== Schoschonen
#lorem(120)
]
#autobreak[
== Raubritter
#lorem(120)
]
#autobreak[
== <NAME>
#lorem(240)
]
#autobreak[
== Die Affen
#lorem(240)
]
#autobreak[
== Zwei k<NAME>
#lorem(80)
]
#autobreak[
== Nehmt Abschied
#lorem(240)
]
#autobreak[
== Allzeit bereit
#lorem(180)
]
#autobreak[
== <NAME>
#lorem(240)
]
|
https://github.com/VadimYarovoy/Networks2 | https://raw.githubusercontent.com/VadimYarovoy/Networks2/main/lab3/report/typ/questions.typ | typst | #import "@preview/colorful-boxes:1.2.0": *
= Ответы на вопросы
== Вопрос 1
#colorbox(
title: "TODO",
color: "blue",
radius: 2pt,
width: auto
)[
Зачем нужен протокол HTTP, принцип работы
]
- Назначение HTTP: Протокол передачи гипертекста (HTTP) является основным протоколом передачи данных в сети Интернет. Он используется для обмена информацией между веб-браузерами и веб-серверами, позволяя загружать веб-страницы, изображения, видео и другие ресурсы.
- Принцип работы: Клиент (обычно веб-браузер) отправляет HTTP-запросы к серверу, запрашивая определенные ресурсы. Сервер отвечает HTTP-ответами, предоставляя запрошенные данные. Взаимодействие происходит по принципу "запрос-ответ", и каждое сообщение состоит из заголовка и (возможно) тела сообщения.
== Вопрос 2
#colorbox(
title: "TODO",
color: "blue",
radius: 2pt,
width: auto
)[
Формат HTTP-сообщения, HTTP-запросы, HTTP-ответы
]
- Формат HTTP-сообщения: HTTP-сообщение состоит из двух частей - заголовка и (опционально) тела. Заголовок содержит мета-информацию о сообщении, такую как метод запроса, код ответа, тип содержимого и другие параметры. Тело содержит собственно данные сообщения.
- HTTP-запросы: HTTP-запрос отправляется клиентом к серверу для запроса определенного ресурса.
Пример запроса:
```
GET /index.html HTTP/1.1
Host: www.example.com
```
Заголовки (Headers)
```
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
```
HTTP-ответы: HTTP-ответ возвращается сервером клиенту, содержащий статус выполнения запроса и, при необходимости, данные. Пример ответа:
```
HTTP/1.1 200 OK
Content-Type: text/html
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
```
== Вопрос 3
#colorbox(
title: "TODO",
color: "blue",
radius: 2pt,
width: auto
)[
HTTP-серверы, HTTP-клиенты, прокси-серверы
]
- HTTP-серверы: Это программы или устройства, которые принимают HTTP-запросы от клиентов и отправляют HTTP-ответы с запрошенными данными. Примеры: Apache, Nginx, Microsoft IIS.
- HTTP-клиенты: Это программы или браузеры, которые отправляют HTTP-запросы к серверам и обрабатывают HTTP-ответы. Примеры: браузеры (Chrome, Firefox), утилиты командной строки (cURL).
- Прокси-серверы: Это серверы, которые действуют как посредники между клиентами и серверами. Они могут кэшировать ресурсы, фильтровать трафик, улучшать безопасность и управлять доступом. Примеры: Squid, Nginx (в режиме прокси).
#pagebreak() |
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/context.typ | typst | Apache License 2.0 | #set text(lang: "de")
#context [
#set text(lang: "fr")
#text.lang \
#context text.lang
]
|
https://github.com/MyPedagogicalRessources/BUT1-R1-01-Initiation-developpement | https://raw.githubusercontent.com/MyPedagogicalRessources/BUT1-R1-01-Initiation-developpement/main/TD/TD2-Trace-dessins-correction.typ | typst | #import "TD2-Trace-dessins.typ":*
#td2(isCorrection: true)
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-19.typ | typst | Other | // Error: 10-25 the result is too large
#calc.pow(2, 2147483647)
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/modules/cycle2.typ | typst | Apache License 2.0 | // Ref: false
#import "cycle1.typ": *
#let val = "much cycle"
This is the second element of an import cycle.
|
https://github.com/Canadauni/typst-static-dashboard | https://raw.githubusercontent.com/Canadauni/typst-static-dashboard/main/_extensions/typst_static_dashboard/typst-show.typ | typst | // Typst custom formats typically consist of a 'typst-template.typ' (which is
// the source code for a typst template) and a 'typst-show.typ' which calls the
// template's function (forwarding Pandoc metadata values as required)
//
// This is an example 'typst-show.typ' file (based on the default template
// that ships with Quarto). It calls the typst function named 'article' which
// is defined in the 'typst-template.typ' file.
//
// If you are creating or packaging a custom typst template you will likely
// want to replace this file and 'typst-template.typ' entirely. You can find
// documentation on creating typst templates here and some examples here:
// - https://typst.app/docs/tutorial/making-a-template/
// - https://github.com/typst/templates
#show: dashboard.with(
$if(title)$
title: [$title$],
$endif$
$if(grid-cols)$
grid-cols: $grid-cols$,
$endif$
$if(grid-rows)$
grid-rows: $grid-rows$,
$endif$
$if(font-size)$
font-size: $font-size$,
$endif$
$if(font-col)$
font-col: "$font-col$",
$endif$
$if(paper)$
paper: "$paper$",
$endif$
$if(flipped)$
flipped: "$flipped$",
$endif$
$if(margin)$
margin: ($for(margin/pairs)$$margin.key$: $margin.value$,$endfor$),
$endif$
$if(header-col)$
header-col: "$header-col$",
$endif$
$if(logo-path)$
logo-path: "$logo-path$",
$endif$
)
|
|
https://github.com/0x6e66/hbrs-typst | https://raw.githubusercontent.com/0x6e66/hbrs-typst/main/README.md | markdown | # A [Typst](https://typst.app/) template for [HBRS](https://www.h-brs.de/)-theses
## Usage
Without changing the template, the only files you need to modify are:
- `ads/`
- `acronyms.typ`: define acronyms
- `abstract.typ`: define abstract in multiple languages
- `meta.typ`: set personal information and general metadata about your thesis
- `module_de/`: the actual content of the thesis in german
- `module_en/`: the actual content of the thesis in english
### Compile
```bash
typst compile main.typ
```
## Example
<img src="https://github.com/0x6e66/hbrs-typst/assets/21971085/c4480e3b-3317-4eda-bf2c-36615c378300" width="49%">
<img src="https://github.com/0x6e66/hbrs-typst/assets/21971085/266cdfe6-048b-4858-9ff4-a35c2e19e067" width="49%">
<img src="https://github.com/0x6e66/hbrs-typst/assets/21971085/dfba6426-37f6-4d17-a7d1-89f97b6e699b" width="49%">
<img src="https://github.com/0x6e66/hbrs-typst/assets/21971085/984779ee-c2d0-440a-b71c-720987c92218" width="49%">
|
|
https://github.com/jakoblistabarth/tud-corporate-design-slides-typst | https://raw.githubusercontent.com/jakoblistabarth/tud-corporate-design-slides-typst/main/README.md | markdown | MIT No Attribution | # Typst template for slide in TU Dresden's the corporate design :microphone:
This template can be used to create presentations in [Typst](https://github.com/typst/typst) with the corporate design of [TU Dresden](https://www.tu-dresden.de/).
## Usage
Create a new typst project based on this template locally.
```bash
typst init @preview/tud-corporate-design-slides
cd tud-corporate-design-slides
```
Or create a project on the typst web app based on this template.
### Font setup
The fonts `Open Sans` needs to be installed on your system:
You can download the fonts from the [TU Dresden website](https://tu-dresden.de/intern/services-und-hilfe/ressourcen/dateien/kommunizieren_und_publizieren/corporate-design/cd-elemente/schrift-tud-open-sans).
Once you download the fonts, make sure to install and activate them on your system.
### Compile (and watch) your typst file
```bash
typst w main.typ
```
This will watch your file and recompile it to a pdf when the file is saved. For writing, you can use [Vscode](https://code.visualstudio.com/) with these extensions: [Typst LSP](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp) and [Typst Preview](https://marketplace.visualstudio.com/items?itemName=mgt19937.typst-preview). Or use the [typst web app](https://typst.app/) (here you need to upload the fonts).
## Todos
- [ ] Add more slide layouts (e.g. 2-column layout)
- [ ] Port to [touying](https://github.com/touying-typ/touying)
|
https://github.com/El-Naizin/cv | https://raw.githubusercontent.com/El-Naizin/cv/main/modules/publications.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Publications")
#cvPublication(
bibPath: "../src/publications.bib",
keyList: (
"smith2020",
"jones2021",
"wilson2022"),
refStyle: "apa"
) |
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/代数学二/作业/hw1.typ | typst | #import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark, proposition,der, partialDer, Spec
#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: "作业1",
author: "YHTQ",
date: none,
logo: none,
withOutlined : false,
withTitle :false,
)
(应交时间为3月5日)
#set heading(numbering: none)
= 2.
== i)
- 若 $a_0$ 是单位,其余 $a_i$ 是幂零元,将有:
- $a_i x^i, i = 1, 2, ..., n$ 是幂零元
- $sum_(i=1)^n a_i x^i$ 作为幂零元的和是幂零元
- $a_0 + sum_(i=1)^n a_i x^i$ 作为单位 + 幂零元是单位
- 若 $f$ 是单位:
- 任取 $A$ 的素理想 $P$,取自然同态 $pi: A[x] -> (A quo P)[x]$,将有 $pi(f)$ 成为 $(A quo P)[x]$ 的单位\
然而注意到 $A quo P$ 是整环,因此 $(A quo P)[x]$ 上的单位只能是 $A quo P$ 中单位,这就给出 $a_i in P, i = 1, 2, ..., n$\
因此这些 $a_i$ 属于所有素理想,自然是幂零元
- 此外,这给出 $a_0$ 在所有素理想的商环中都是单位。假如 $a_0$ 在 $A$ 中不是单位,考虑 $(a_0)$ 扩充成的极大理想 $I$,这是素理想但 $a_0 + I = 0 + I$ 不可能是单位,矛盾。故 $a_0$ 是单位
== ii)
- 若 $a_i, i = 0, 1, 2, ..., n$ 都幂零,则 $a_i x^i$ 也幂零,它们的和当然也幂零,因此 $f$ 是幂零元
- 若 $f$ 是幂零元,类似的任取 $A$ 中素理想 $P$ 和自然同态 $pi: A[x] -> (A quo P)[x]$,$pi(f)$ 也幂零。然而 $(A quo P)[x]$ 是整环,因此 $pi(f) = 0$。\
因此 $f$ 的所有系数都在 $P$ 之中。由于 $P$ 是任取的,因此 $f$ 的所有系数都是幂零元
== iii)
- 假如存在 $a in A - {0}$ 使得 $a f = 0$,则 $f$ 当然是零因子
- 反之,设 $f$ 是零因子,则 $I = {g in A[x] | f g = 0}$ 是 $A[x]$ 中的理想。只需证明 $I sect A != emptyset$\
如若不然,取 $g in I - {0}$ 是 $I$ 中最低次元素之一,设:
$
f(x) = sum_(i = 0)^n a_i x^i, g(x) = sum_(i = 0)^m b_i x^i
$
则观察得 $a_n b_m = 0$\
因此 $a_n g in I$ 的次数比 $g$ 更低,因此 $a_n g = 0$\
以此类推可得 $a_i g = 0, i = 0, 1, 2, .., n$\
特别的,$a_i b_0 = 0, i = 0, 1, 2, ..., n$,故 $b_0 f = 0$,证毕
== iv)
记多项式 $f$ 的所有系数生成的理想为 $I_f$
- 若 $f, g$ 都是本原多项式,假设 $f g$ 不是本原多项式,设其系数生成的非平凡理想为 $I := I_(f g)$ 并取自然同态 $pi: A[x] -> (A quo I)[x]$\
显然将有 $pi(f g) = 0$
+ $pi(f), pi(g) != 0$,这表明 $pi(f), pi(g)$ 是 $(A quo I)[x]$ 中的零因子,由上题结论知存在 $a + I, b + I != 0 in A quo I$ 使得:
$
(a + I) pi(f) = 0, (b + I) pi(g) = 0\
<=> a f in I[x], b g in I[x]\
=> a I_f, b I_g subset I\
=> (a), (b) subset I\
=> a, b in I
$
矛盾!
+ $pi(f) = 0 or pi(g) = 0$,不妨设 $pi(f) = 0$,此时有:
$
pi(f) = 0 => f in I[x] => A = I_f subset I => I = A
$
这与 $I$ 非平凡矛盾
- 若 $f g$ 是本原多项式,若 $f, g$ 不都是本原多项式,不妨设 $f$ 不是本原多项式,取 $pi: A[x] -> (A quo I_f)[x]$,有:
$
pi(f) = 0 => pi(f g) = 0 => f g in I_f[x] => A = I_(f g) subset I_f
$
这将导出 $I_f = A$,矛盾
= 4
记幂零根为 $Re_p$,Jacobson 根为 $Re_m$
- 一方面,交换环中的极大理想都是素理想,$Re_m supset Re_p$
- 另一方面,任取 $f in Re_m$ 往证 $f in Re_p$\
注意到 $f := sum_(i=0)^n a_i x^i in Re_m => 1 - f(x) g(x) in U(A[x]), forall g in A[x]$,只需取 $g(x) = x$,将有:
$
1 - x f(x) in U(A[x])
$
由之前习题结论,这给出 $a_i, i = 0, 1, 2, 3, ... ,n$ 在 $A$ 中幂零,因此 $f in Re_p$,证毕
= 6
类似的,只需任取 $f in Re_m$ 往证 $f in Re_p$,换言之,只需证明:
$
1 - f g in U(A), forall g in A => f "幂零"
$
如若不然,$(f) subset.not Re_p$,取 $(f)$ 中的非零幂等元 $e = g f$,将有:
$
g f = g^2 f^2 => g f(1 - g f) = 0 => g f = 0 => e = 0
$
(注意到 $1 - g f$ 是单位)\
矛盾!
= 7
任取 $A$ 中素理想 $P$,$A' := A quo P$ 是整环,同时满足 $forall x in A', exists n in NN, x^n = x$,但注意到:
$
x^n = x => x(x^(n-1) -1) = 0 => x = 0 or x^(n-1) = 1 => x = 0 or x in U(A')
$
这说明 $A'$ 是域,进而 $P$ 是极大理想
= 8
在包含关系上,幂零根当然就是所有素理想构成集合的最小元
= 9
- 设 $alpha = r(alpha)$,注意到 $r(alpha)$ 是所有包含 $alpha$ 的素理想的交,因此 $alpha = r(alpha)$ 当然也是素理想的交
- 设 $alpha = sect.big_(i in I) P_i$,则 $r(alpha) = r(sect.big_(i in I) P_i) subset sect.big_(i in I)r(P_i) = sect.big_(i in I)P_i = alpha$,同时显有 $alpha subset r(alpha)$,因此 $alpha = r(alpha)$,证毕
= 14
- 首先证明 $Sigma$ 中有极大元。对于 $Sigma$ 的某个全序子集 $S$,$union.big S$ 是同样满足要求的理想,因此成为 $S$ 在 $Sigma$ 中的上界。由 Zorn 引理,$Sigma$ 中有极大元
- 任取 $Sigma$ 中的极大元 $P$,往证它是素理想\
注意到若 $I_1, I_2 in Sigma$,则 $I_1 + I_2 in Sigma$
- 设 $x y in P$,验证 $x in P or y in P$\
注意到 $x y$ 是零因子,因此 $exists f: f x y = 0$,表明 $x, y$ 都是零因子
- 此时 $P + (x), P + (y) in Sigma$,由 $P$ 的极大性有 $x, y in P$,证毕
= 15
== i)
- 显然 $forall P in Spec(A), E subset P <=> alpha subset P$,当然有 $V(E) = V(alpha)$
- 此外,显有 $r(alpha) supset alpha => V(r(alpha)) subset V(alpha)$,往证 $V(alpha) subset V(r(alpha))$\
事实上,我们有:
$
forall P in Spec(A), alpha subset P => r(alpha) subset r(P) = P
$
这就是说 $V(alpha) subset V(r(alpha))$,证毕
== ii)
- 显然所有素理想都包含 $0$,因此 $V(0) = Spec(A)$
- 任何素理想都不含 $1$,否则成为 $A$,但 $A$ 不是素理想
== iii)
$
forall P in Spec(A):\
P in V(union.big_(i in I) E_i)
&<=> union.big_(i in I) E_i subset P\
&<=> forall i in I, E_i subset P\
&<=> forall i in I, P in V(E_i)\
$
== iv)
$
forall P in Spec(A):\
P in V(a sect b)
&<=> a sect b subset P\
&<=> a subset P or b subset P\
&<=> P in V(a) or P in V(b)\
&<=> P in V(a) union V(b)
$
此外,注意到 $a b subset P <=> a subset P or b subset P$,因此同理可证 $V(a b) = V(a) union V(b)$
= 17
注意到任何开集均形如:
$
S = Spec(A) - V(E) = Spec(A) - V(union.big_(x in E) {x})\
= Spec(A) - sect.big_(x in E) V(x)\
= union.big_(x in E) (Spec(A) - V(x))\
= union.big_(x in E) X_x
$
== i)
$
X_f sect X_g &= (Spec(A) - V(f)) sect (Spec(A) - V(g))\
&= Spec(A) - (V(f) union V(g))\
&= Spec(A) - V((f) sect (g))\
&= Spec(A) - V((f g))\
&= X_(f g)
$
== ii)
$
X_f = emptyset &<=> V(f) = Spec(A)\
&<=> forall P in Spec(A), f in P \
&<=> f "幂零"
$
== iii)
$
X_f = X &<=> V(f) = emptyset\
&<=> forall P in Spec(A), f in.not P\
&<=> f in U(A)
$
(注意到若 $f$ 不是单位,则 $(f)$ 扩充成的极大理想作为素理想包含 $f$,因此存在素理想包含 $f$)
== iv)
$
X_f = X_g &<=> V(f) = V(g)\
&<=> V(r(f)) = V(r(g))\
$
(运用 $V(alpha) = V(r(alpha))$
== v), vi)
直接证明 vi)\
- 先证明一个引理:$V(a) subset V(b) <=> r(b) subset r(a)$\
- 一方面,$r(b) subset r(a) => V(r(a)) = V(a) subset V(r(b)) = V(b) $
- 另一方面:
$
V(a) subset V(b) => sect.big V(a) = r(a) supset sect.big V(b) = r(b)
$
由于所有 $X_f$ 构成拓扑基,因此不妨设开覆盖是拓扑基构成的,也即:
$
&X_f subset union.big_(i in I) X_(g_i)\
<=>& V(f) supset sect.big_(i in I) V(g_i)\
<=>& V(f) supset V(sum_(i in I) (g_i))\
<=>& f in r(sum_(i in I) (g_i)) "(由引理)"\
<=>& exists k in NN^+, f^k in sum_(i in I) (g_i)
$
注意到最后一式中 $f^k$ 一定可以被 $g_i$ 中的有限个元素表示,因此倒推可得 $D(f)$ 有有限子覆盖
== vii)
- 一方面,伪紧集的有限并当然伪紧,因此 $X_f$ 的有限并伪紧
- 另一方面,假设 $S$ 是伪紧开集,注意到 $X_f$ 构成一组拓扑基,可设:
$
S = union.big_(i in I) X_(f_i)
$
这也意味着上式右侧构成一组开覆盖,它将有有限子覆盖 $I' subset I$ 使得:
$
S subset union.big_(i in I') X_(f_i) subset X_(sum_(i in I) f_i) = S
$
因此上式中的不等号都取等,进而 $S$ 是有限个 $X_f$ 的并
= 18
== i)
- 注意到若 ${x}$ 闭,则存在某个理想 $I$,$p_x$ 是唯一包含它的素理想\
而 $I$ 扩充成的极大理想一定是包含 $I$ 的素理想,因此 $p_x$ 就是这个极大理想,也即 $x$ 是极大理想
- 若 $p_x$ 是极大理想,则 $V(p_x) = {x}$ 是闭集
== ii)
显然 $V(p_x)$ 是闭集,只需证明最小性。\
假设 ${x} subset V(a)$,往证 $V(p_x) subset V(a)$
- 事实上:
$
{x} subset V(a) &=> x in V(a)\
&=> a subset p_x\
&=> V(a) supset V(p_x)
$
证毕
== iii)
$
y in overline({x}) &<=> y in V(p_x)\
&<=> p_y supset p_x\
$
== iv)
注意到 $x in overline({y})$ 和 $y in overline({x})$ 不同时成立(否则 $x = y$)\
不妨设 $x in.not overline({y})$,则 $overline({y})$ 是不含 $x$ 的 $y$ 闭邻域,取其补恰为不含 $y$ 的 $x$ 开邻域,证毕
|
|
https://github.com/GYPpro/DS-Course-Report | https://raw.githubusercontent.com/GYPpro/DS-Course-Report/main/Rep/03.typ | typst | #import "@preview/tablex:0.0.6": tablex, hlinex, vlinex, colspanx, rowspanx
#import "@preview/codelst:2.0.1": sourcecode
// Display inline code in a small box
// that retains the correct baseline.
#set text(font:("Times New Roman","Source Han Serif SC"))
#show raw.where(block: false): box.with(
fill: luma(230),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
#show raw: set text(
font: ("consolas", "Source Han Serif SC")
)
#set page(
paper: "a4",
)
#set text(
font:("Times New Roman","Source Han Serif SC"),
style:"normal",
weight: "regular",
size: 13pt,
)
#let nxtIdx(name) = box[ #counter(name).step()#counter(name).display()]
#set math.equation(numbering: "(1)")
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
#set math.equation(numbering: "(1)")
#set page(
paper:"a4",
number-align: right,
margin: (x:2.54cm,y:4cm),
header: [
#set text(
size: 25pt,
font: "KaiTi",
)
#align(
bottom + center,
[ #strong[暨南大学本科实验报告专用纸(附页)] ]
)
#line(start: (0pt,-5pt),end:(453pt,-5pt))
]
)
/*----*/
= 基于块状数组的`dataBlock`
\
#text(
font:"KaiTi",
size: 15pt
)[
课程名称#underline[#text(" 数据结构 ")]成绩评定#underline[#text(" ")]\
实验项目名称#underline[#text(" ") 基于块状数组的`dataBlock` #text(" ")]指导老师#underline[#text(" 干晓聪 ")]\
实验项目编号#underline[#text(" 03 ")]实验项目类型#underline[#text(" 设计性 ")]实验地点#underline[#text(" 数学系机房 ")]\
学生姓名#underline[#text(" 郭彦培 ")]学号#underline[#text(" 2022101149 ")]\
学院#underline[#text(" 信息科学技术学院 ")]系#underline[#text(" 数学系 ")]专业#underline[#text(" 信息管理与信息系统 ")]\
实验时间#underline[#text(" 2024年6月13日上午 ")]#text("~")#underline[#text(" 2024年7月13日中午 ")]\
]
#set heading(
numbering: "1.1."
)
= 实验目的
实现基于`vector`的块状数组,针对插入场景进行特别优化。
= 实验环境
\
#h(1.8em)计算机:PC X64
操作系统:Windows + Ubuntu20.0LTS
编程语言:C++:GCC std20
IDE:Visual Studio Code
= 程序原理
在使用增长数组维护一个索引区域的基础上,使用不再进行移动的倍增数组维护动态扩容的数据。
具体的,每次扩容与`vector`类似,将新申请一个与当前内存相等大小的区域,将其索引插入索引区域,并保持原数组不变。
易得,本结构需要额外$OO(log_2 n)$的索引区域。
其申请与访问操作的复杂度分析大致如下:
`push_back`:$OO (1)$
`get_index`:$log_10 (log_2 (n)) dot n arrow.r OO(log(n))$
由于常数极小,在数据量小于$10^20$时可以认为`get_index`的复杂度为1
特别的,在数据后半段,内存区间连续,依旧能享受到CPU分支优化。
#pagebreak()
= 程序代码
== `dataBlock.hpp`
#sourcecode[
```cpp
// #define _PRIVATE_DEBUG
#ifndef DATA_BLOCK_HPP
#define DATA_BLOCK_HPP
#include <vector>
#include <map>
#define _PRIVATE_DEBUG
#ifdef _PRIVATE_DEBUG
#include <iostream>
#endif
namespace myDS
{
template<typename VALUE_TYPE>
class dataBlock{
protected:
private:
class _iterator
{
private:
VALUE_TYPE *_ptr;
std::pair<std::size_t,std::size_t> loc;
dataBlock<VALUE_TYPE> * _upper_pointer;
public:
enum __iter_dest_type
{
front,
back
};
__iter_dest_type _iter_dest;
_iterator( myDS::dataBlock<VALUE_TYPE> *_upper,std::pair<std::size_t,std::size_t> _loc,__iter_dest_type _d)
{
_upper_pointer = _upper;
loc = _loc;
_ptr = &_upper_pointer->_indexs[loc.first][loc.second];
_iter_dest = _d;
}
VALUE_TYPE & operator*()
{
return (*_ptr);
}
VALUE_TYPE *operator->()
{
return _ptr;
}
myDS::dataBlock<VALUE_TYPE>::_iterator operator++() {
if(_iter_dest == front)
{
loc = _upper_pointer->nextPII(loc);
}
else
{
loc = _upper_pointer->prevPII(loc);
}
_ptr = &_upper_pointer->_indexs[loc.first][loc.second];
return myDS::dataBlock<VALUE_TYPE>::_iterator(_upper_pointer,loc,_iter_dest);
}
myDS::dataBlock<VALUE_TYPE>::_iterator operator++(int) {
myDS::dataBlock<VALUE_TYPE>::_iterator old = *this;
if(_iter_dest == front)
{
loc = _upper_pointer->nextPII(loc);
}
else
{
loc = _upper_pointer->prevPII(loc);
}
_ptr = &_upper_pointer->_indexs[loc.first][loc.second];
return old;
}
bool operator==( myDS::dataBlock<VALUE_TYPE>::_iterator _b) {
return _ptr == _b._ptr;
}
bool operator!=( myDS::dataBlock<VALUE_TYPE>::_iterator _b) {
return _ptr != _b._ptr;
}
};
std::vector<VALUE_TYPE *> _indexs;
std::pair<std::size_t,std::size_t> _cap = {0,0};
std::size_t consMEX = 1;
std::size_t _size = 0;
void _expension()
{
VALUE_TYPE *temp = new VALUE_TYPE[consMEX];
_indexs.push_back(temp);
consMEX *= 2;
_cap.first++;
_cap.second = 0;
}
std::size_t getMEX(std::int32_t p)
{
if(p <= 0) return p+1;
return (1 << (p-1));
}
std::pair<std::size_t,std::size_t> nextPII(std::pair<std::size_t,std::size_t> p)
{
p.second++;
if(p.second >= getMEX(p.first))
{
p.first++;
p.second = 0;
}
return p;
}
std::pair<std::size_t,std::size_t> prevPII(std::pair<std::size_t,std::size_t> p)
{
#ifdef __DETIL_DEBUG_OUTPUT
std::cout << "{" << p.first << "," << p.second << "}'s prev is";
#endif
std::int32_t tmp = p.second;
tmp --;
if(tmp < 0)
{
p.first--;
p.second = getMEX(p.first) - 1;
} else p.second --;
#ifdef __DETIL_DEBUG_OUTPUT
std::cout << "{" << p.first << "," << p.second << "}\n";
#endif
return p;
}
public:
dataBlock(){
VALUE_TYPE *tmp = new VALUE_TYPE[1];
_indexs.push_back(tmp);
}
~dataBlock(){
clear();
delete [] (_indexs[0]);
}
void push_back(VALUE_TYPE t) {
if(_cap.second >= getMEX(_cap.first)) {
_expension();
}
_indexs[_cap.first][_cap.second] = t;
_cap.second++;
_size++;
}
void clear() {
for(auto x:_indexs) delete [] x;
_indexs.clear();
VALUE_TYPE *tmp = new VALUE_TYPE[1];
_indexs.push_back(tmp);
consMEX = 1;
_size = 0;
_cap = {0,0};
}
std::size_t size() {
return _size;
}
myDS::dataBlock<VALUE_TYPE>::_iterator begin() {
return myDS::dataBlock<VALUE_TYPE>::_iterator(this,{0,0}, myDS::dataBlock<VALUE_TYPE>::_iterator::front);
}
myDS::dataBlock<VALUE_TYPE>::_iterator rbegin() {
return myDS::dataBlock<VALUE_TYPE>::_iterator(this,prevPII(_cap), myDS::dataBlock<VALUE_TYPE>::_iterator::back);
}
myDS::dataBlock<VALUE_TYPE>::_iterator end() {
return myDS::dataBlock<VALUE_TYPE>::_iterator(this,nextPII(prevPII(_cap)), myDS::dataBlock<VALUE_TYPE>::_iterator::front);
}
myDS::dataBlock<VALUE_TYPE>::_iterator rend() {
return myDS::dataBlock<VALUE_TYPE>::_iterator(this,prevPII({0,0}), myDS::dataBlock<VALUE_TYPE>::_iterator::back);
}
#ifdef _PRIVATE_DEBUG
void innerPrint() {
std::pair<std::size_t,std::size_t> p = {0,0};
while(p.first <= _cap.first) {
if(p.second == 0) std::cout << "\nBlock : [" << p.first << "] at:" << _indexs[p.first] << "\n";
std::cout << _indexs[p.first][p.second] << " ";
p = nextPII(p);
}
std::cout << "\n";
}
#endif
VALUE_TYPE & operator[](std::size_t p) {
if(p == 0) return _indexs[0][0];
std::int32_t onord = 0;
std::size_t tmp = p;
while(tmp) {
tmp >>= 1;
onord++;
}
#ifdef __DETIL_DEBUG_OUTPUT
std::cout << "onord:" << onord << " p:" << p << " GETMEX :"<< getMEX(onord) << " index:{" << onord << "," << p - getMEX(onord) << "}\n";
#endif
return _indexs[onord][p - getMEX(onord)];
}
};
}
#endif
```]
== `_PRIV_TEST.cpp`
```cpp
#define DS_TOBE_TEST dataBlock
#define _PRIVATE_DEBUG
// #define __DETIL_DEBUG_OUTPUT
#include "Dev\03\dataBlock.hpp"
#include <time.h>
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
using TBT = myDS::dataBlock<int>;
void accuracyTest() {//结构正确性测试
TBT tc = TBT();
for(;;)
{
string op;
cin >> op;
if(op == "clr") { //清空
tc.clear();
} else if(op == "q") //退出测试
{
return;
} else if(op == "pb")//push_back
{
int c;
cin >> c;
tc.push_back(c);
// } else if(op == "pf")//push_frount
// {
// int c;
// cin >> c;
// tc.push_frount(c);
} else if(op == "at")//随机访问
{
int p;
cin >> p;
cout << tc[p] << "\n";
// } else if(op == "delEL")//删除所有等于某值元素
// {
// int p;
// cin >> p;
// cout << tc.erase(p) << "\n";
// } else if(op == "delPS")//删除某位置上的元素
// {
// int p;
// cin >> p;
// cout << tc.erase(tc.get(p)) << "\n";
} else if(op == "iterF") //正序遍历
{
tc.innerPrint();
cout << "Iter with index:\n";
for(int i = 0;i < tc.size();i ++) cout << tc[i] << " ";cout << "\n";
cout << "Iter with begin end\n";
for(auto x = tc.begin();x != tc.end();x ++) cout << (*x) << " ";cout << "\n";
cout << "Iter with AUTO&&\n";
for(auto x:tc) cout << x << " ";cout << "\n";
} else if(op == "iterB") //倒序遍历
{
tc.innerPrint();
cout << "Iter with index:\n";
for(int i = 0;i < tc.size();i ++) cout << tc[tc.size()-1-i] << " ";cout << "\n";
cout << "Iter with begin end\n";
for(auto x = tc.rbegin();x != tc.rend();x ++) cout << (*x) << " ";cout << "\n";
// cout << "Iter with AUTO&&\n";."\n";
} else if(op == "mv")//单点修改
{
int p;
cin >> p;
int tr;
cin >> tr;
tc[p] = tr;
} else if(op == "")
{
} else {
op.clear();
}
}
}
void memLeakTest() {//内存泄漏测试
TBT tc = TBT();
for(;;){
tc.push_back(1);
tc.push_back(1);
tc.push_back(1);
tc.push_back(1);
tc.clear();
}
}
void speedTest()
{
TBT tc = TBT();
int begin = clock();
int N = 1e8;
for(int i = 0;i < N;i ++)
{
tc.push_back(i);
}
cout << "myDS::dataBlock Push_back 10000000 elements cost:" << clock() - begin << "ms\n";
std::vector<int> tmp;
begin = clock();
for(int i = 0;i < N;i ++)
{
tmp.push_back(i);
}
cout << "std::vector push_back 10000000 elements cost:" << clock() - begin << "ms\n";
system("pause");
}
signed main()
{
// accuracyTest();
// memLeakTest();
speedTest();
}
```
= 测试数据与运行结果
运行上述`_PRIV_TEST.cpp`测试代码中的正确性测试模块,得到以下内容:
```
pb 1
pb 2
pb 3
pb 4
iterF
iterB
clr
pb 0
pb 3
pb 1
pb 2
pb 3
pb 4
iterF
iterB
mv 0 3
iterF
pb 1
pb 2
pb 3
pb 4
iterF
Block : [0] at:0x722540
1
Block : [1] at:0x7225c0
2
Block : [2] at:0x722580
3 4
Iter with index:
1 2 3 4
Iter with begin end
1 2 3 4
Iter with AUTO&&
1 2 3 4
iterB
Block : [0] at:0x722540
1
Block : [1] at:0x7225c0
2
Block : [2] at:0x722580
3 4
Iter with index:
4 3 2 1
Iter with begin end
4 3 2 1
clr
pb 0
pb 3
pb 1
pb 2
pb 3
pb 4
iterF
Block : [0] at:0x722540
0
Block : [1] at:0x722580
3
Block : [2] at:0x7225c0
1 2
Block : [3] at:0x722600
3 4 -1163005939 -1163005939
Iter with index:
0 3 1 2 3 4
Iter with begin end
0 3 1 2 3 4
Iter with AUTO&&
0 3 1 2 3 4
iterB
Block : [0] at:0x722540
0
Block : [1] at:0x722580
3
Block : [2] at:0x7225c0
1 2
Block : [3] at:0x722600
3 4 -1163005939 -1163005939
Iter with index:
4 3 2 1 3 0
Iter with begin end
4 3 2 1 3 0
mv 0 3
iterF
Block : [0] at:0x722540
3
Block : [1] at:0x722580
3
Block : [2] at:0x7225c0
1 2
Block : [3] at:0x722600
3 4 -1163005939 -1163005939
Iter with index:
3 3 1 2 3 4
Iter with begin end
3 3 1 2 3 4
Iter with AUTO&&
3 3 1 2 3 4
```
可以看出,代码运行结果与预期相符,可以认为代码正确性无误。
运行`_PRIV_TEST.cpp`中的内存测试模块,在保持CPU高占用率运行一段时间后内存变化符合预期,可以认为代码内存安全性良好。
#image("2.png")
运行`_PRIV_TEST.cpp`中的性能测试模块,得到
```
myDS::dataBlock Push_back 10000000 elements cost:663ms
std::vector push_back 10000000 elements cost:1618ms
```
可以看到`dataBlock`在插入速度上较`STL`中的`vector`快2-3倍左右。 |
|
https://github.com/dadn-dream-home/documents | https://raw.githubusercontent.com/dadn-dream-home/documents/main/contents/01-mo-dau/index.typ | typst | = Mở đầu
Nhà thông minh là một khái niệm ngày càng phổ biến trong thời đại công nghệ
số hiện nay. Nhà thông minh là nhà có khả năng tự động hóa và điều khiển các
thiết bị gia dụng thông qua Internet vạn vật (IOT) và các cảm biến. Nhà thông
minh mang lại nhiều lợi ích cho người sử dụng, như tiết kiệm năng lượng, tăng
cường an ninh, nâng cao sức khỏe và thoải mái sống.
Để tìm hiểu thêm thêm về công nghệ IOT và các cảm biến thông minh, cũng như
ứng dụng kiến thức học được về công nghệ phần mềm, nhóm đã chọn đề tài *Dream
Home*.
Qua dự án, nhóm hy vọng đạt được các mục tiêu sau.
#block(inset: (left: 1cm))[
_Thứ nhất_, nhận và hiển thị dữ liệu từ thiết bị.
_Thứ hai_, kiểm tra dữ liệu nhận được vượt quá ngưỡng cho phép.
_Thứ ba_, điều khiển thiết bị.
_Thứ tư_, ghi nhận hoạt động thiết bị.
_Thứ năm_, sử dụng design pattern trong hiện thực.
] |
|
https://github.com/exusiaiwei/quarto-ilm | https://raw.githubusercontent.com/exusiaiwei/quarto-ilm/main/_extensions/ilm/typst-show.typ | typst | MIT License | #show: quarto-ilm.with(
$if(title)$
title: "$title$",
$endif$
$if(author)$
author: "$author$",
$endif$
$if(date)$
date: "$date$",
$endif$
$if(abstract)$
abstract: [$abstract$],
$endif$
$if(bibliography)$
bibliography-file: "$bibliography$",
$endif$
$if(biblio-style)$
bibliography-style: "$biblio-style$",
$endif$
$if(paper-size)$
paper-size: "$paper-size$",
$endif$
$if(preface)$
preface: [$preface$],
$endif$
$if(table-of-contents)$
table-of-contents: $table-of-contents$,
$endif$
$if(chapter-pagebreak)$
chapter-pagebreak: $chapter-pagebreak$,
$endif$
$if(external-link-circle)$
external-link-circle: $external-link-circle$,
$endif$
$if(figure-index)$
figure-index: $figure-index$,
$endif$
$if(table-index)$
table-index: $table-index$,
$endif$
$if(listing-index)$
listing-index: $listing-index$,
$endif$
) |
https://github.com/jdpieck/oasis-align | https://raw.githubusercontent.com/jdpieck/oasis-align/main/0.1.0/README.md | markdown | # oasis-align
`oasis-align` is a package that automatically sizes your content so that their heights are equal, allowing you to cleanly place content side by side.
To use `oasis-align` in your document, start by importing the package like this:
```typst
#import "@preview/oasis-align:0.1.0": *
```
This will give you access to the two functions found under [configurations](#configuration).
# Examples
## Image with Text
![Animation of image being aligned with text](examples/image-with-text.gif)
## Image with Image
![Animation of image being aligned with another image](examples/image-with-image.gif)
## Text with Text
![Animation of text being aligned with differently sized text](examples/text-with-text.gif)
# Configuration
There are two functions associated with this package. The first is specifically targeted at [aligning images](#oasis-align-images), and the second is targeted at [content in general](#oasis-align-1).
> [!important]
> To change the size of the gutter in both functions, use `#set grid(column-gutter: length)`. This is necessary to allow for fixed rules that aren't possible with user-defined functions.
## `oasis-align-images`
Use this function to align two images.
```typst
#oasis-align-images(
"path/to/image1",
"path/to/image2"
)
```
> [!tip]
> Whenever aligning **only** images, it's best to use this function instead of the default `oasis-align`. _To learn more about why, check out [how it works](#how-it-works)._
## `oasis-align`
Use this function to align content like text with other content like images or figures.
> [!tip]
> The parameters with defined values are the defaults and do not need to be included unless desired.
```typst
#oasis-align(
int-frac: 0.5, // decimal between 0 and 1
tolerance: 0.001pt, // length
max-iterations: 50, // integer greater than 0
int-dir: 1, // 1 or -1
debug: false // boolean
item1, // content
item2, // content
)
```
### `int-frac`
The starting point of the search process. Changing this value may reduce the total number of iterations of the function or find an [alternate solution](#oasis-align-2).
### `tolerance`
The allowable difference in heights between `item1` and `item2`. The function will run until it has reached either this `tolerance` or `max-iterations`. Making `tolerance` larger may reduce the total number of iterations but result in a larger height difference between pieces of content.
> [!note]
> Two pieces of content may not always be able to achieve the desired `tolerance`. In that case, the function sizes the content to the iteration that had the least difference in height. _Check out [how it works](#oasis-align-2) to understand why the function may not be able achieve the desired `tolerance`._
### `max-iterations`
The maximum number of iterations the function is allowed to attempt before terminating. Increasing this number may allow you to achieve a smaller `tolerance`.
### `int-dir`
The initial direction that the dividing fraction is moved. Changing this value will change the initial direction.
> [!note]
> The program is hardcoded to switch directions if a solution is not found in the initial direction. This parameter mainly serves to let you easily choose between [multiple solutions](#oasis-align-2).
### `debug`
A toggle that lets you look inside the function to see what is happening. This is useful if you would like to understand why certain content may be incompatible and which of the parameters above could be changed to resolve the issue.
<!-- # FAQ
## Why won't my image align nicely with my text -->
# How It Works
## `oasis-align-images`
The function begins by determining the width and height of the selected images. These values can then be used to solve a set of linear equations, the first of which states that the sum of the widths of the images (plus the gutter) should be equal to the available horizontal space, and the second which states that their heights should be equal.
If $w_1$ and $h_1$ are the width and height of `image1` and $w_2$ and $h_2$ are the width and height of `image2`, then the final width $w_1'$ of `image1` and the final width $w_2'$ of `image2` are
$$w_1' = \left(\frac{h_1 w_2}{w_1 h_2} + 1 \right)^{-1} \qquad w_2' = \left(\frac{w_1 h_2}{h_1 w_2} + 1 \right)^{-1}$$
## `oasis-align`
Originally designed to allow for an image to be placed side-by-side with text, this function takes an iterative approach to aligning the content. When changing the width of a block of text, the height does not scale linearly, but instead behaves as a step function that follows an exponential trend (the graph below has a simplified visualization of this). This prevents the use of an analytical methodology similar to the one used in `oasis-align-images`, and thus must be solved using an iterative approach.
The function starts by taking the available space and then splitting it using the `int-frac`. The content is then placed in a block with the width as determined using the split from `int-frac` before measuring its height. Based on the `int-dir`, the split will be moved left or right using the bisection method until a solution within the `tolerance` has been found. In the case that a solution within the `tolerance` is not found with the `max-iterations`, the program terminates and uses the container width fraction that had the smallest difference in height.
![Series of graphs visualizing the block width versus height of content](examples/graph-visualization.svg)
### Multiple Solutions (1st Graph)
Depending on the type of content, the function may find multiple solutions. The parameters `int-dir` and `int-frac` will allow you to choose between them by changing the direction in which it iterates and changing the starting container width fraction respectively.
### No Solutions (2nd Graph)
There are cases in which the text size is incompatible with an image. This can be because there is not enough or too much text, and regardless of how the content is resized, their heights do not match.
### Tolerance Not Reached (3rd Graph)
In the case of having texts of different sizes (as seen in [the examples](#text-with-text)), the spacing between lines prevents the function from finding a solution that meets the `tolerance`, and thus the closest solution is used.
<!-- # Nomenclature
"Oasis" as in a fertile spot in a desert, where water is found. -->
# Share With Me!
If you end up using this package, please feel free to share how you used it under "Discussions" on the [GitHub Repository](https://github.com/jdpieck/oasis-align) or on Discord with `@jdpieck`. |
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/def_use/import_ident.typ | typst | Apache License 2.0 | #import "base.typ"
#base
#import "base.typ": x
#base, #x |
https://github.com/chilingg/kaiji | https://raw.githubusercontent.com/chilingg/kaiji/main/part1/front_page.typ | typst | Other | #import "@preview/tablex:0.0.6": tablex, vlinex, hlinex, colspanx, rowspanx
#import "../template/main.typ": base_style, thin_line, normal_line, font_size_list, sans_font_cfg
#show : body => base_style(body)
#set heading(outlined: false)
#align(right + bottom)[
#block(width: 50%)[
#align(left)[
// ■本書の図版に示した書体には,いずれもその著作権者,版権者がある。許可なく,これらを量産商品の材料として利用してはならない。また著作に流用してはならない。
#block(below: 2em)[■本书图片所示字体都有其著作权人、版权人。未经许可,不得将其用作商用素材。不得再挪用作其他创作。]
#set enum(numbering: "1", indent: 1em)
// ■本書は文字のデザイン・シリーズ第6巻にあたる。漢字の上巻は,現行の活字書体の代表的なものを,それぞれ70字示し,特に重要な5書体は210字を4cm角で示した。本書は漢字の下巻で,その設計理論を初歩的な立場からも(基本を),また活字設計専門家の為にも,詳細なデータを以って解説した。
#block(below: 2em)[■本书为文字设计丛书系列第6卷。汉字的上卷分别展示了当前每种常用字体的70个字,特别重要的5个字体以4cm的方形显示了210个字。本书是汉字的下卷,从初级(基础)的角度解释了设计理论,并为字体设计专家提供了详细的数据。]
// - 2巻\~6巻までを総括する設計総論
// - 字体論・書体論,タイポグラフィの効果測定
// - 新書体を設計する全過程の具体例
+ 日本タイポグラフィ(続刊)<sans_font>
- 总结2卷\~6卷的设计总论
- 字形论·字体论,印刷排版的效果效果
- 设计新字体全过程的具体示例。
// - 平仮名の歴史
// - 現代の代表書体
+ ひらがな上(既刊)<sans_font>
- 平假名的历史
- 现代的代表字体
// - 平仮名の設計理論
// - 著者作品
+ ひらがな下(既刊)<sans_font>
- 平假名的设计理论\
- 作者作品
// - 片仮名の歴史
// - 片仮名の設計理論
// - 代表書体の著者作品
+ 力タ力ナ(既刊)<sans_font>
- 片假名的历史
- 片假名的设计理论
- 代表性字体的作者作品
// - 漢字及びその活字書体の歴史
// - 現在使われている漢字の代表書体
+ 漢字上(既刊)<sans_font>
- 汉字及其活字字体的历史
- 目前使用的具有代表性的汉字字体
// - 漢字の設計理論(ことに明朝体について)
// - 〔基準明朝体〕の規格
// - 標準漢字2,000字(2cm角)
+ 漢字下(本巻)<sans_font>
- 汉字设计理论(特别是关于明朝体)
- 〔基准明朝体〕的标准
- 标准汉字2,000字(2cm方形)
]
]
]
#pagebreak()
#v(2cm)
= 序文 <wide_title>
#columns(2)[
== 1 <center>
// ■漢字書体を設計するに当って,最も重要な碁盤はその字体であるが,〔当用漢字字体〕や中国の〔簡化字〕についての字体論は第1巻に讓らぎるをえなくなった。その次に考慮すベきは〔字体を明朝体に結びつける規格〕であるが,日本新聞協会制定の〔基準明朝体〕というものがあって,一般市販の活字もそれに準じていることについては,知る人が少ない。本書では,これを扱っている。委員会から相談を受けた末席のー人として,規格が決まるまでの当時のいきさつを可能な限り再現したつもりである。
// 漢字の設計にっいては初歩の段階から専門にまで及んだ。
■设计汉字字体最重要的基础是字形,关于〔现行汉字字形〕和中国〔简体字〕字形的讨论在第1卷中。其次要考虑的是〔字形结合到明朝体的标准〕,很少有人知道日本新闻协会制定的〔基准明朝体〕,一般市面上的印刷都以此为标准。本书就是要介绍这一点。作为最后被委员会咨询的人之一,我试图尽可能地还原标准决定之前的经过。
汉字的设计从初级到专业阶段都涉及到了。
== 2 <center>
// ■活字・写植書体のデザイナー(ことに本文用標準書体をデザインする専門家)のために,よりどころとなるデータを記載した本は従来皆無であった。研究はされていたかもしれないが,少なくとも発表されたものはない。本書はそれを提供したつもりであるが充分こなれていないきらいがあることは,著者として心苦しい。一般の読者にとっては読みづらいものとなったと思う。
■专为活字、写植字体的设计师(特别是设计正文标准字体的专家)而设。一直以来都没有任何书籍描述过这种难以捉摸的数据。也许有人对其进行过研究,但没有出版过。本书旨在提供这方面的信息,但可能不够全面,作为作者我为此感到遗憾。对于普通读者来说,这些内容并不容易阅读。
// データのとりはじめは14.5年前からであるが,主力をなす部分は1969年10月以後に測定したものである。そのとき現行明朝体についての調査(一般人各層,専門富の意見・好み・可読性テスト)の結果をまとめ,それらの書体から得た数値との相関によって解釈するために,切実な要求であった。
数据的收集始于14.5年前,但主要部分是在1969年10月之后测定的。这是一项迫切的需求,目的是为了总结对现行明朝体的调查结果(公众和专业人士的意见、偏好和可读性测试),并解释这些字体和获得的数据之间的相关性。
// 新書体を具体的に試作する段階となったが,その時こそ本書に書いたようなデータがますま必要であった。書体設計の実作議と,これらの分析研究とは平行におこなわれ,その実効を発揮したのである。
新字体开始制作原型,也正是在这一阶段,需要本书所描述的数据。实际的字体设计讨论和这些数据的分析研究是同时进行的,并且证明其是有效的。
== 3 <center>
// ■個々の漢字にはそれぞれ固有のデッサンがある(下図A), それについての記述は,本書では最小限度にとどめざるを得なかった。個々の漢字は類別してまとめられ,測量された平均値(又は最頻值)の相互関係が求められた。一つの書体の特性はいくつかの数値によってその設計基盤が表現される。本書の内容は大よそこうした帰納的法則化の方向をとった。下図DはAと対蹠的な位置にある。ただしその陰にはAが準備されていることを予想している。本書では3種類の明朝体について,代表的漢字約400字を実例として示してある。
■每个汉字都有其独特的字形(下图A),本书篇幅有限,对这些字形的描述必须尽量减少。将各个汉字分类汇总,取平均值(或众数值)测量它们之间的关系。字体的特征用若干数值来表示,这些数值构成了字体设计的基础。本书的内容基本就是以这种归纳规律为方向的。下图中D是A的对立面。但是,估计A的背后也是受D在影响。本书展示了3种明朝体具有代表性的约400字作为示例。
// 個々の字のデッサン
// 一書体として・の特長
// 明治期以来の活字彫師の方法。感覚のみによる記憶・肉体イヒ。
// グループにまとめ,数量化し,相互関係を顕在化する(グラフ・数式)
#tablex(
columns: (auto, 1fr, auto, 1fr),
auto-vlines: false,
map-cells: cell => {
if cell.x == 0 or cell.y == 0 {
cell.content = [
#set text(size: font_size_list.at(3))
#cell.content
]
} else {
cell.align = center
}
cell
},
(), vlinex(), vlinex(), vlinex(), (),
[],[明治以来活字雕刻师的方法, 仅靠感官进行记忆和肉眼观察。],[],[分组、量化和揭示相互关系(坐标和公式)],
[单个字的字形],[A],[⇆],[C],
[], [⇅], [], [⇅],
[字体的特征],[B],[],[D],
)
#colbreak()
== 4 <center>
// ■ *A→C→D* と帰納されていくにつれ,個々のデータは具体的なディテールをはぎとられ,残るものは平均值とか最頻値とかの一つの数値である。しかし,その数値は必ずしも非実在のものではなく,われわれが一つの書体の特性とし感受する感覚的性格と対応する。性格との対応を専門家は理解しなくてはならない。音符をみて音楽を思いうかベうるように——。
■ *A→C→D* 随着归纳的进行,单个数据的具体细节被剥离,剩下的只是一个数值,如平均值或众数值。但是,这个数值并不一定是实际存在的,而是与我们感知到的字体特征相对应。专家必须理解数值与特征的对应关系,就像看到音符就能想到对应的音乐一样。
== \* <center>
// 数値にすることで,失われるものが多いが,数值にすることによつて,はじめて発見されるルールが多い。それは文中の構成の上に反映された,われわれの精神に内在する調和律でもある。
许多东西在数值形式中丟失了,但只有在数值形式中才能发现更多的规则。规则反映在文中的结构上,这也是我们心中固有的和谐法则。
== \* <center>
// 帰納されたルールや平均値などから,逆にD→C→Aの方向に演绎されるとき,個々の字についてその特性的条件に適応した微妙な調整を加える必要がある。機械的に最小のユニットの組合せとして,文字を造形する方針を考えに入れることも必要ではあるが,仮に光点文字のごとき場合でも,それは単なるユニツトの組合せではない。このとき,前述の平均值はそれ自身をそのまま適用するのではなく,それを手がかりとして,より具体的を調整を加えるために有効な手段としてその存在理由がある。
根据归纳出来的规则和平均值,以反方向D→C→A演绎时,有必要对每个单字进行微小的调整,以适应其字形特性。此外,也有必要考虑作为最小单元的机械组合来构造文字的策略,但即使是光点文字,也不是单纯的单元组合。在这种情况下,上述平均值不能原封不动地使用,而是作为一种有效的手段,以此为线索进行更具体的调整。
== 5 <center>
// ■組まれた文字が高速度で読者の目の前をすすめ流れていくとき,それは原図の静止し,拡大化した文字の姿とはたいへんちがった〔見られ方〕をする。しかもその間に,活字・文字盤·製版·印刷の工程による変形を強いられる。こうした原図と〔読まれる文字〕とのまったく別の2つの世界の間に対応をつけることは,絶対に必要であって,現在はほとんど手がつけられていない(それについては第1卷で少し触れるつもりである)。
■当组合后的文字在读者眼前高速流动时,它的外观与静态的、放大的原始文字截然不同。而且在此期间,因活字、字盘、制版、印刷工艺而产生的变形是不可避免的。绝对有必要在原形和可读文本这两个完全不同的世界之间建立起一种对应关系,现在几乎没有对这方面着手(关于这方面在第1卷中稍微触及)。
\
#align(right)[1976年3月1日 佐藤敬之辅]
]
#pagebreak()
#block(height: 12%)[
= 目录 <wide_title>
#align(bottom)[
== 610 汉字设计理论 <sans_font>
#line(length: 100%)
]
]
#include "../template/contents.typ"
// 角寸法又に仮想ボディ
// 揭載ペーヅ
#block(width: 50%, above: 5em)[
== 字体索引 <sans_font>
#set text(size: 7pt, tracking: 0em)
#tablex(
columns: (1fr, auto, auto, auto),
auto-vlines: false,
map-cells: cell => {
if cell.y == 0 {
cell.align = center
} else if cell.x > 0 {
cell.content = [
#set text(..sans_font_cfg)
#cell.content
]
if cell.x == 2 {
cell.align = right
}
}
cell
},
(), vlinex(), vlinex(stroke: thin_line), vlinex(stroke: thin_line), (),
[字体名],[字身框或假想框],[字数],[页码],
[朝日2.5倍明朝体],
[
1.75cm\
3.0\
4.0
],
[
204\
40\
148
],
[
track_page
],
hlinex(stroke: thin_line),
[写研细明朝体],
[
1.75\
3.0\
4.0
],
[
204\
74\
173
],
[
track_page
],
hlinex(stroke: thin_line),
[モトヤ中明朝体M4],
[
2.0\
4.0
],
[
2000\
210
],
[
track_page
],
hlinex(stroke: thin_line),
[
モリサワ見出明朝体\
正楷書体(岩田母型)\
モトヤ中ゴシツク体G4
],
[
1.75cm\
3.0\
4.0
],
[
204\
40\
148
],
[
track_page
],
)
]
#pagebreak()
#align(center + horizon)[
#block(width: 85%)[
#set align(start)
== 设计项目索引 <sans_font>
#columns(2)[
// ●設計項目の1・2・3は,結局1つの漢字の構成にまとめられるもので,それを異なった3つの側面から取り扱うという意味である。ことに2と3とは入り混っていて,はっきり分離できない。問題はそれらの項目の相互関係にある。
●设计项目中1、2、3,从三个不同的方面来处理,最终可以归纳为汉字的结构。其中2和3耦合性太高,无法明确区分。问题在于要明确这些项目之间的相互关系。
#colbreak()
// 相互関係を二次元でとらえたのが,この表である。実際は,もっと多くの次元が網の目のようにからみあっている関係を,本書から読みほぐしてもらいたい。
该表显示了两个维度间的相互关系。实际的情况更加错综复杂,因为还有更多的维度相互关联,希望大家能在本书中更好的了解到这些关系。
]
#v(2em)
#set text(size: font_size_list.at(3))
// ●表中()は書道楷書,〈〉は活字正楷書体,〔〕はゴシック体,その他は明朝体 ●見開きの場合は,左ページのみ記入
●表中()为书法楷书,〈〉为活字正楷字体,〔〕为黑体,其他为明朝体 ●对开页只注明左页
#tablex(
columns: (..(auto,)*3, ..(1fr,)*6),
auto-lines: false,
map-cells: cell => {
if cell.y == 0 {
cell.align = center
} else if cell.rowspan != 1 {
cell.align = horizon
}
cell
},
// 字づら
(), (), (), ..(vlinex(stroke: thin_line),)*6, (),
hlinex(stroke: normal_line),
colspanx(3)[设计项目], (),[字面],[线数],[最长线],[重心],[居右],[历史],
// 1 組みに関する項目
// 活字サイズ
// 基準ワク
// 引込みワク・ライン
// 字高・字幅
// 字間・行間
hlinex(stroke: normal_line),
colspanx(3)[1 组合相关项目 <sans_font>],(),(),[],[],[],[],[],[],
colspanx(2)[- 活字尺寸],(),[track_page],[track_page],[track_page],[track_page],[track_page],[track_page],[track_page],
colspanx(2)[- 基准框],(),[],[],[],[],[],[],[],
colspanx(2)[- 参考线、框],(),[],[],[],[],[],[],[],
colspanx(2)[- 字高・字宽],(), [],[],[],[],[],[],[],
colspanx(2)[- 字间・行间],(),[],[],[],[],[],[],[],
// 2 一書体としての調整に関する項目
// 字づら
// 大きさ
// 字面率
// 輪郭
// 点画密度
// 点画密度
// 線数
// 線長合計
// ウエイト線幅
// ウエイト段階
// 線率
// エレメント
// ハライ
// 部首
hlinex(stroke: normal_line),
colspanx(3)[2 字体整体调整项目 <sans_font>],(),(),[],[],[],[],[],[],
rowspanx(3)[- 字面],[┌ 大小],[],[],[],[],[],[],[],
(),[┼ 字面率],[],[],[],[],[],[],[],
(),[└ 轮廓],[],[],[],[],[],[],[],
rowspanx(3)[- 笔画密度],[┌ 笔画密度],[],[],[],[],[],[],[],
(),[┼ 线数],[],[],[],[],[],[],[],
(),[└ 线长合计],[],[],[],[],[],[],[],
colspanx(2)[- 线宽权重],(),[],[],[],[],[],[],[],
colspanx(2)[- 加权阶段],(),[],[],[],[],[],[],[],
colspanx(2)[- 线率],(),[],[],[],[],[],[],[],
colspanx(2)[- 部件],(),[],[],[],[],[],[],[],
colspanx(2)[- 撇捺],(),[],[],[],[],[],[],[],
colspanx(2)[- 部首],(),[],[],[],[],[],[],[],
// 3 一字一字の構成に閥する項目
// 格子構造
// 曲線構造
// 斜線構造
// 構造による漢字の分類
// 最長線
// 長さ・幅のリズム
// 長さの順位
// 線間隔・分割のリズム
// 胴幅・胴高
// 重心
// 右勝手
// 周辺のおさえ
// 内部の均一化
// フトコロ
// ボディ
hlinex(stroke: normal_line),
colspanx(3)[3 逐字配置项目 <sans_font>],(),(),[],[],[],[],[],[],
colspanx(2)[- 格子构造],(),[],[],[],[],[],[],[],
colspanx(2)[- 曲线构造],(),[],[],[],[],[],[],[],
colspanx(2)[- 斜线构造],(),[],[],[],[],[],[],[],
colspanx(2)[- 汉字结构分类],(), [],[],[],[],[],[],[],
colspanx(2)[- 最长线],(),[],[],[],[],[],[],[],
colspanx(2)[- 长与宽的规律],(),[],[],[],[],[],[],[],
colspanx(2)[- 长度的顺序],(),[],[],[],[],[],[],[],
colspanx(2)[- 线间隔、分割的规律],(),[],[],[],[],[],[],[],
colspanx(2)[- 字身的宽与高],(),[],[],[],[],[],[],[],
colspanx(2)[- 重心],(),[],[],[],[],[],[],[],
colspanx(2)[- 居右],(),[],[],[],[],[],[],[],
colspanx(2)[- 周边挤压],(),[],[],[],[],[],[],[],
colspanx(2)[- 内部的均一化],(),[],[],[],[],[],[],[],
colspanx(2)[- 字怀],(),[],[],[],[],[],[],[],
colspanx(2)[- 字躯],(),[],[],[],[],[],[],[],
hlinex(stroke: normal_line),
)
]
]
#set heading(
outlined: true,
numbering: (..nums) => "61" + nums
.pos()
.map(str)
.join("-"),
)
|
https://github.com/piepert/logik-tutorium-wise2024-2025 | https://raw.githubusercontent.com/piepert/logik-tutorium-wise2024-2025/main/src/exams/exam01.typ | typst | Creative Commons Zero v1.0 Universal | #import "/src/templates/exams.typ": project, task
#import "/src/packages/inference.typ": *
#show: project.with(no: 1)
#task(lines: 10, points: 3, [Grundbegriffe], [
Erklären Sie, womit sich die Logik beschäftigt. Nennen Sie außerdem die zwei Gütekriterien von Argumenten.
], [], (
(1, [Bestimmung der Logik als Lehre vom gültigen, formalen Schließen.]),
(2, [Benennen der Gütekriterien Gültigkeit und Schlüssigkeit.]),
))
#task(lines: 20, points: 6, [Gütekriterien], [
Beurteilen Sie die folgenden Argumente jeweils in Bezug auf die zwei Gütekriterien! Begründen Sie Ihre Antworten kurz.
], [
1. #inference-raw(```
Wenn ich auf dem Mond laufe, kann ich höher springen als auf der Erde.
Ich kann nicht höher als auf der Erde springen.
----
Ich bin nicht auf dem Mond.
```)
2. #inference-raw(```
Entweder alle Kirschen sind grün oder es regnet Sonnenstrahlen.
Nicht alle Kirschen sind grün.
----
Also regnet es Sonnenstrahlen.
```)
3. #inference-raw(```
Alle Menschen können Fleisch essen.
----
Alle Menschen sollten Fleisch essen.
```)
], (
(2, [
1. Das Argument wurde als schlüssig und gültig charakterisiert, da die Prämissen wahr und die Konklusion logisch aus den Prämissen folgt. Wurde es als unschlüssig beurteilt, so muss eine Begründung erfolgen.
]),
(2, [
2. Das Argument wurde als gültig, aber nicht schlüssig beurteilt, da die Prämissen falsch sind aber die Konklusion logisch aus den Prämissen folgt. Weder sind alle Kirschen grün, noch regnet es Sonnenstrahlen, daher ist die erste Prämisse falsch. Für eine andere Bewertung muss eine angemessene Begründung vorgebracht werden.
]),
(2, [
3. Das Argument ist weder schlüssig noch gültig. Da das Argument nicht gültig ist und auch nicht als gültig gesehen werden kann, kann es ebenfalls nicht schlüssig sein.
]),
))
#task(lines: 10, points: 3, [logische Folgerung], [
Geben Sie zu jedem Argument eine Konklusion an, die logisch aus den Prämissen folgt!
], [
1. #inference-raw(```
Alle Vögel können fliegen.
Ein Pinguin ist ein Vogel.
----
...
```)
2. #inference-raw(```
Pinguine leben am Südpol und Eisbären am Nordpol.
----
...
```)
3. #inference-raw(```
Die Straße ist nass.
----
...
```)
], (
(1, [
Eines der folgenden:
- "Alle Vögel können fliegen."
- "Ein Pinguin ist ein Vogel."
- "Ein Pinguin kann fliegen."
- äquivalente oder allgemeingültige Aussagen
]),
(1, [
Eines der folgenden:
- "Pinguine leben am Südpol und Eisbären am Nordpol."
- "Pinguine leben am Südpol."
- "Eisbären leben am Nordpol."
- äquivalente oder allgemeingültige Aussagen
]),
(1, [
Eines der folgenden:
- "Die Straße ist nass."
- "Es ist nicht der Fall, dass die Straße nicht nass ist."
- äquivalente oder allgemeingültige Aussagen
]),
))
#task(lines: 10, points: 4, extra: true, [Beweis], [
Beweisen Sie die Gültigkeit des folgenden Arguments durch einen indirekten Beweis!
], [
#inference(
[Alle Ärzte sind brilliant.],
[Alle Chirurgen sind Ärzte.],
inference-line,
[Alle Chirurgen sind brilliant.]
)
], (
(1, [Die Konklusion wurde verneint.]),
(1, [Weitere Beweisschritte sind nachvollziehbar.]),
(1, [Der Widerspruch wurde gefunden.]),
(1, [Der Beweis wurde mit "QED" beendet.]),
)) |
https://github.com/danilasar/conspectuses-3sem | https://raw.githubusercontent.com/danilasar/conspectuses-3sem/master/Клубы/Ассемблер/01/01_введение.typ | typst | #set par(
justify: true,
leading: 1.5em,
)
#set text(14pt)
= Введение в ассемблер
Всем привет, думаю, мне нет смысла представляться, так как все здесь присутствующие либо знакомы со мной, либо уже были на лекции по обратной разработки.
С сегодняшнего дня мы начинаем небольшой интенсив по ассемблеру, к концу которого у вас должно появиться чёткое понимание того, что происходит под капотом программы, а также умение писать на языке ассемблера, что находится в одном шаге от свободного владения машинным кодом --- языком, на котором ваш компьютер мыслит.
== Зачем вот это вот всё?
Чем это может быть полезно лично вам? Я думаю, многие из присутствующих пришли просто ради интереса или для общего развития, поэтому давайте обсудим практическое применение тех знаний, за которыми вы сюда пришли. Итак, для чего лично вам нужен этот интенсив? Чем вам поможет владение ассемблером?
Резюмируем. _следить за слайдом_
+ Во-первых, ассемблер --- это билет в системное программирование. Владея им, вы можете писать различные низкоуровневые вещи. В частности, это работа с подключенным оборудованием, а, стало быть, написание и обновление драйверов. Новое оборудование выходит постоянно, старое нужно поддерживать, высокоуровневые языки не дают достаточно возможностей, а это значит, что нужны ассемблеристы. Специалистов такого уровня днём с огнём не сыскать, а потребность имеется (даже в Саратове есть вакансии), поэтому зарплаты здесь что надо, но и попасть непросто.
+ Во-вторых, это может оказаться полезным навыком на CTF --- соревновании по компьютерной безопасности. Если вы хотите заниматься взломом или, наоборот, расследованием и устранением последствий кибератак, то одно из направлений этой индустрии --- обратная разработка, где владение ассемблером пригождается редко, но ценится на вес с золото. _Кирилл не даст соврать, реверс-инженеры --- отдельная каста в мире CTF_
+ В-третьих, это может быть полезно в отладке. Такие ситуации возникают нечасто, но бывает, что вы на 100% уверены в валидности своего кода, а поведение всё равно неадекватное. Отлаживая машинный код, вы можете неожиданно найти баг в используемых вами библиотеках (даже если они не опенсорсные) или вообще в самом компиляторе. Такое бывает редко, но метко, и, думаю, хотя бы раз в жизни с этим столкнётся каждый разработчик.
+ В-четвёртых, самое приземлённое. На втором курсе ПИ и ФИИТ читают ассемблер и было бы неплохо быть готовым сдавать лабы на нём. Антонина Гавриловна, бесспорно, замечательно объясняет свой предмет на лекциях, но вот с практическими занятиями не всё так однозначно и многим нужны дополнительные учебные материалы для выполнения заданий. Так что второкурсники сейчас имеют прекрасную возможность догнать и перегнать учебную программу, а первокурсники --- заранее подготовиться к следующему году. Кроме того, первашам-ИВТшникам и, вроде бы, КБшникам тоже читают ассемблер, а это значит, что и им эти пары не помешают, тем более это вообще по их профилю.
+ Есть и другие, более экзотические причины прикасаться к ассемблеру, но пока мы ограничимся этими тремя пунктами.
== Структура курса
_следить за слайдом_
Курс предельно практический и направлен именно на то, чтобы дать вам возможность уже сейчас научиться писать какие-то базовые вещи на языке ассемблера. Это не значит, что теории не будет. Умение писать на ассемблере требует от вас наличие массы специфических знаний и мы разберёмся с основами работы процессора, операционной системы и самим языком. При этом получаемые знания мы тут же будем подхватывать на практике, что закрепит материал в памяти и поможет лучше его понять.
В рамках этого короткого курса, если у нас хватит сил, мы вместе реализуем целых четыре пет-проекта на ассемблере.
+ Первый из них --- Hello, world! Поскольку ассемблер --- язык далеко не из простых, просто вывод текста на экран, по моему мнению, --- уже не такое маленькое достижение.
+ Следующим будет простой калькулятор, выполняющий четыре базовые арифметические операции. Мы научимся работать с переменными и с числовыми данными, а также познакомимся с консольным вводом.
+ Третий проект будет гораздо интереснее, мы напишем ту самую виселицу из второго семестра инфопроги, у кого она была или будет, но на ассемблере. Программа будет загадывать слово и задача игрока --- побуквенно отгадать его. Здесь мы более тесно поработаем со строками, воспользуемся циклами и функциями.
+ И, наконец, вишенка на торте в виде русской рулетки. Мы напишем полноценную графическую программу. В основном окне мы нарисуем кнопку, по клику на которую откроется другое окошко, сообщающее нам результат рулетки. Для этого мы научимся работать с компоновщиком, таблицей импорта, стандартной библиотекой языка Си и библиотекой GTK.
== Подписываемся на каналы
Секунда нативочки. Я бы прорекламировал здесь свой тг-канал, но делать этого я, конечно же, не стану, вместо этого предлагаю вам достать свои телефоны, отсканировать коды и подписаться на канал Студенческих клубов разработки, где будут делаться объявления в том числе от других клубов, а также публиковаться записи лекций.
А пока кто-то ещё не успел достать свой телефон, я задам вопрос в зал: сколько гендеров вы знаете и можете назвать?
== Ассемблеры
На самом деле, множество гендеров является бесконечным и включает в себя целый список ассемблеров:
/ TASM: ассемблер, который давным-давно был разработан компанией Borland, и имеет 16- и 32-разрядную реализации. Именно он, согласно учебной программе, изучается в начале курса машинно-зависимых языков программирования у Антонины Гавриловны. Его разработка была прекращена много лет назад, да и сама Borland уже сто лет в обед как приказала долго жить. Именно на TASM вы будете писать свои программы под DOS
/ FASM: ассемблер, который отличается особенно простым синтаксисом. В каком-то смысле он чуть более высокоуровневый, чем остальные собраья. Игрушечным его не назовёшь, почти полностью на нём написаны операционные системы Menuet и Kolibri.
/ GAS: мощный ассемблер от GNU, который известен своими возможностями по работе с макросами и директивами. Именно он используется в компиляторе gcc. GAS особенно популярен в Linux-сообществе, но имеет очень специфичный синтаксис.
/ MASM: ассемблер от Microsoft, изначально предназначенный для написания программ под MS-DOS, а затем и Windows. Он поддерживает и другие операционные системы, но ориентирован всё же на майкрософтовскую продукцию. MASM развивается весьма медленно, последняя версия датируется 2017 годом. На этом ассемблере вы будете писать в рамках машинно-зависимых языков программирования ближе ко второй половине семестра.
/ NASM (Netwide Assembler): это свободный ассемблер для архитектуры Intel x86, известный своей простотой и мощью. Он поддерживает 16-, 32- и 64-разрядные программы и предлагает богатый набор макросов. NASM часто используется для написания высокопроизводительных участков кода, драйверов устройств и операционных систем.
Есть и множество других ассемблеров, как универсальных, так и очень специфичных. Некоторые из них суть клоны уже перечисленных. Так, YASM --- это тот же NASM, просто под другой лицензией.
Работать мы будем как раз на NASM под линуксом, потому что я так решил вуахаххаа. У меня уже была лекция, где я рассказал о самых лайтовых приколах винды, и я не хотел бы к этому возвращаться, поэтому мой выбор в пользу линукса кажется очевидным. Можно, конечно, было бы работать и на MASM, и на GAS, но мне не нравится GASовский синтаксис, а, работая под линуксом, было бы непоследовательно брать майкросовтовский ассемблер. Поэтому берём в руки то, что считается здесь лучшей практикой и достойной альтернативой GASу, --- NASM.
== Запускаем компьютеры!
Теперь, разобравшись с организационными вопросами, мы можем приступить непосредственно к занятию и наш план-минимум на сегодня --- реализация Hello, world!
== Исполняемый файл
/ Исполняемый файл: --- это файл, в котором содержатся машинные инструкции, следуя которым, процессор выполняет заданный алгоритм. Кроме них там же лежат самого разного рода данные, необходимые для запуска и поддержания работы процесса.
Структура исполняемых файлов строго стандартизирована и в Linux она соответствует исполняемому и связываемому формату, сокращённо ELF.
Когда мы запускаем исполняемый файл, он попадает в распоряжение загрузчика, который, опираясь на метаданные, подготовит программу к запуску.
== Структура ELF
Исполняемый файл начинается с заголовка ELF, в котором описывается и архитектруа процессора, и метод кодирования данных, и многие другие технические шоколадки.
Далее следует заголовок программы, в котором описываются её сегменты --- комбинации секций --- непересекающиеся блоки с данными, из которых состоит исполняемый файл.
Ну а завершается всё непосредственно секциями и таблицей секций. Как видите, схема очень простая, гораздо проще виндового PE, где скрестили собаку с носорогом (MZ и COFF).
== Секция
Но вернёмсся к секциям. Каждая секция в себе содержит вполне осмысленный набор данных. Это может быть:
- Либо служебная информация для загрузчика
- Либо код программы (то есть машинные инструкции)
- Либо данные программы (переменные, массивы и другие структуры)
_слайд_
Поведение любой секции определяется спецификаторами:
#table(columns: 2, [Спецификатор], [Значение],
[alloc/noalloc], [ выгружать ли секцию в память?],
[exec/noexec], [ разрешено ли выполнение?],
[write/nowrite], [ разрешена ли запись?],
[progbits/nobits], [ хранится ли секция в файле?],
[align], [ параметр выравнивания секции])
_слайд_
Кроме спецификаторов у секции есть имя. Есть также несколько стандартных имён, для которых NASM автоматически устанавливает спецификаторы:
```nasm
section .text progbits alloc exec nowrite align=16; код
section .data progbits alloc noexec write align=4; инициализированные данные
section .bss nobits alloc noexec write align=4; неинициализированные данные
section other progbits alloc noexec nowrite align=1; любая другая секция
```
_слайд_
Спецификаторы можно не прописывать для секций со стандартными именами:
```nasm
section .text ; код
section .data ; инициализированные данные
section .bss ; неинициализированные данные
section other progbits alloc noexec nowrite align=1; любая другая секция
```
== Пишем в память
Инструкция `db` позволяет писать произвольные данные. Воспользуемся этим, чтобы положить строку в секцию данных:
```nasm
section .data ; секция данных
db "Hello, world!",1
```
== Добавляем код
Некоторые вещи (от функций до переменных) мы можем экспортировать, то есть сделать доступными для других программ, с помощью директивы `global`
В частности, с её помощью мы указываем точку входа:
```nasm
global _start ; делаем метку метку _start видимой извне
section .data ; секция данных
db "Hello, world!",1
section .text ; объявление секции кода
_start: ; метка _start - адрес точки входа
```
== Метка `_start`?
Метка --- абстрактное понятие языка ассемблера. Метка олицетворяет адрес следующей за ней инструкции.
```nasm
global _start ; делаем метку метку _start видимой извне
section .data ; секция данных
message: ; указывает на букву H из следующей строки:
db "Hello, world!",1
section .text ; объявление секции кода
_start: ; метка _start - адрес точки входа
```
== Как оперировать данными?
Процессор не стучится по каждому чиху в ОЗУ. Данные, с которыми он работает прямо сейчас, хранятся в его собственной памяти - регистрах.
Регистров много, они имеют разное имя, разное назначение и разный размер (не больше 64 бит)
== Регистры общего назначения
_таблица на слайде_
== Пишем в регистр
Чтобы положить какие-то данные в регистр, существует инструкция `mov`:
```nasm
global _start ; делаем метку метку _start видимой извне
section .data ; секция данных
message: ; указывает на букву H из следующей строки:
db "Hello, world!",1
section .text ; объявление секции кода
_start: ; метка _start - адрес точки входа
mov rax, 60
mov rdi, 0
```
== Системные вызовы
Системный вызов приостанавливает работу нашей программы и передаёт управление ядру ОС, чтобы она сама всё разрулила. Естественно, принимая решения, она будет опираться на те данные, которые мы положили в регистр перед этим вызовом.
Системный вызов делается с помощью инструкции `syscall`
_слайд_
Как правило, в регистре `rax` от нас ожидается номер системного вызова --- что-то вроде имени функции, а в других регистрах --- аргументы.
Так, чтобы завершить работу программы, нужно выполнить вызов 60, а в `rdi` положить код возврата.
_слайд_
Так, чтобы завершить работу программы, нужно выполнить вызов 60, а в `rdi` положить код возврата.
```nasm
global _start ; делаем метку метку _start видимой извне
section .data ; секция данных
message: ; указывает на букву H из следующей строки:
db "Hello, world!",1
section .text ; объявление секции кода
_start: ; метка _start - адрес точки входа
mov rax, 60 ; системный вызов exit
mov rdi, 0 ; код возврата 0
syscall ; делаем системный вызов
```
_слайд_
Все системные вызовы Linux можно найти на этой странице:
![https://filippo.io/linux-syscall-table/](presentations/01/syscalls.svg)
== Консольный вывод
Консольный вывод в Linux --- это поток stdout, он имеет дескриптор 1.
Чтобы оправить данные в поток, существует системный вызов 1, который ожидает:
- В `rdi` дескриптор
- В `rsi` указатель на начало данных
- В `rdx` количество байт
_слайд_
```nasm
global _start ; делаем метку метку _start видимой извне
section .data ; секция данных
message: ; указывает на букву H из следующей строки:
db "Hello, world!",1
section .text ; объявление секции кода
_start: ; метка _start - адрес точки входа
mov rax, 1 ; системный вызов write
mov rdi, 1 ; дескриптор stdout (1)
mov rsi, message ; адрес начала строки
mov rdx, 13 ; количество байт в ней
syscall ; делаем системный вызов
mov rax, 60 ; системный вызов exit
mov rdi, 0 ; код возврата 0
syscall ; делаем системный вызов
```
= Hello, world! |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1720.typ | typst | Apache License 2.0 | #let data = (
("HANUNOO LETTER A", "Lo", 0),
("HANUNOO LETTER I", "Lo", 0),
("HANUNOO LETTER U", "Lo", 0),
("HANUNOO LETTER KA", "Lo", 0),
("HANUNOO LETTER GA", "Lo", 0),
("HANUNOO LETTER NGA", "Lo", 0),
("HANUNOO LETTER TA", "Lo", 0),
("HANUNOO LETTER DA", "Lo", 0),
("HANUNOO LETTER NA", "Lo", 0),
("HANUNOO LETTER PA", "Lo", 0),
("HANUNOO LETTER BA", "Lo", 0),
("HANUNOO LETTER MA", "Lo", 0),
("HANUNOO LETTER YA", "Lo", 0),
("HANUNOO LETTER RA", "Lo", 0),
("HANUNOO LETTER LA", "Lo", 0),
("HANUNOO LETTER WA", "Lo", 0),
("HANUNOO LETTER SA", "Lo", 0),
("HANUNOO LETTER HA", "Lo", 0),
("HANUNOO VOWEL SIGN I", "Mn", 0),
("HANUNOO VOWEL SIGN U", "Mn", 0),
("HANUNOO SIGN PAMUDPOD", "Mc", 9),
("PHILIPPINE SINGLE PUNCTUATION", "Po", 0),
("PHILIPPINE DOUBLE PUNCTUATION", "Po", 0),
)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/linebreak_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// LR groups prevent linbreaking.
#let hrule(x) = box(line(length: x))
#hrule(76pt)$a+b$\
#hrule(74pt)$(a+b)$\
#hrule(74pt)$paren.l a+b paren.r$
|
https://github.com/tingerrr/subpar | https://raw.githubusercontent.com/tingerrr/subpar/main/examples/example.typ | typst | MIT License | #import "/src/lib.typ" as subpar
#set page(height: auto)
#set par(justify: true)
#subpar.grid(
figure(image("/assets/images/andromeda.jpg"), caption: [
An image of the andromeda galaxy.
]), <a>,
figure(image("/assets/images/mountains.jpg"), caption: [
A sunset illuminating the sky above a mountain range.
]), <b>,
columns: (1fr, 1fr),
align: top,
caption: [A figure composed of two sub figures.],
label: <full>,
)
Above in @full, we see a figure which is composed of two other figures, namely @a and @b.
|
https://github.com/liuguangxi/fractusist | https://raw.githubusercontent.com/liuguangxi/fractusist/main/src/lib.typ | typst | MIT License | #import "dragon.typ": dragon-curve
#import "hilbert.typ": hilbert-curve, peano-curve
#import "koch.typ": koch-curve, koch-snowflake
#import "sierpinski.typ": sierpinski-curve, sierpinski-square-curve, sierpinski-arrowhead-curve, sierpinski-triangle
|
https://github.com/qujihan/typst-book-template | https://raw.githubusercontent.com/qujihan/typst-book-template/main/template/parts/figure/tbl.typ | typst | #import "../../params.typ": *
#let tbl-num(_) = {
let chapter-num = counter(heading.where(level: 1)).display()
let type-num = counter(figure-kind-tbl + chapter-num).display()
str(chapter-num) + "-" + str(int(type-num) + 1)
}
#let tblIn(content) = align(center + horizon)[ #content ]
#let tbl(caption, tbl) = {
figure(
tblIn(tbl),
caption: caption,
supplement: [表格],
numbering: tbl-num,
kind: figure-kind-tbl,
)
} |
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/radial/components/gantt-chart.typ | typst | The Unlicense | #import "/packages.typ": timeliney
#import "../colors.typ": *
/// A gantt chart for task management
///
/// Example Usage:
///
/// ```typ
/// #gantt-chart(
/// start: datetime(year: 2024, month: 1, day: 27),
/// end: datetime(year: 2024, month: 2, day: 3),
/// tasks: (
/// ("Build Robot", (0,4)),
/// ("Code Robot", (3,6)),
/// ("Drive Robot", (5,7)),
/// ("Destroy Robot", (7,8)),
/// ),
/// goals: (
/// ("Tournament", 4),
/// )
/// )
/// ```
/// - start (datetime): Start date using datetime object
/// - year: `<integer>`
/// - month: `<integer>`
/// - day: `<integer>`
/// Example usage: ```typ datetime(year: 2024, month: 7, day: 16)```
/// - end (datetime): End date using datetime object
/// - year: `<integer>`
/// - month: `<integer>`
/// - day: `<integer>`
/// Example usage: ```typ datetime(year: 2024, month: 5, day: 2)```
/// - date-interval (integer): The interval between dates, seven would make it weekly
/// - date-format (string): The way the date is formatted using the `<datetime.display()>` method
/// - tasks (array): Specify tasks using an array of arrays that have three fields each
/// + `<string>` or `<content>` The name of the task
/// + `<array>`(`<integer>` or `<float>`, `<integer>` or `<float>`) The start and end point of the task
/// + `<color>` The color of the task line (optional)
/// Example sub-array: ```typ ("Build Catapult", (1,5), red)```
/// - goals (array): Add goal markers using an array of arrays that have three fields each
/// + `<string>` or `<content>` The name of the goal
/// + `<integer>` or `<float>` The position of the goal
/// + `<color>` The color of the goal box (optional)
/// - Default is grey, but put none for no box
/// Example sub-array: ```typ ("Worlds", 6, red)```
/// -> content
#let gantt-chart(
start: datetime,
end: datetime,
date-interval: 1,
date-format: "[month]/[day]",
tasks: (),
goals: none,
) = {
timeliney.timeline(
spacing: 5pt,
show-grid: true,
grid-style: (stroke: (dash: none, thickness: .2pt, paint: black)),
tasks-vline: true,
line-style: (stroke: 0pt),
milestone-overhang: 3pt,
milestone-layout: "in-place",
box-milestones: true,
milestone-line-style: (stroke: (dash: none, thickness: 1pt, paint: black)),
{
import timeliney: *
let difference = end - start
let dates-array = ()
let months-array = ()
let month-len = 0
let last-month = start.month()
let next
for value in range(int((difference.days()) / date-interval) + 1) {
next = start + duration(days: (value * date-interval))
dates-array.push(group(((next).display(date-format), 1)))
if next.month() == last-month {
month-len += 1
last-month = next.month()
} else {
months-array.push(
group((
(
datetime(year: next.year(), month: last-month, day: 1)
).display("[month repr:long]"),
month-len,
)),
)
month-len = 1
last-month = next.month()
}
}
months-array.push(
group((
(
datetime(year: next.year(), month: last-month, day: 1)
).display("[month repr:long]"),
month-len,
)),
)
headerline(..months-array)
headerline(..dates-array)
let goal-color
if goals != none {
for goal in goals {
if goal.len() == 2 {
goal-color = surface-2
} else {
goal-color = goal.at(2)
}
milestone(
[#box(fill: goal-color, outset: 3pt, radius: 1.5pt)[#goal.at(0)]],
at: goal.at(1),
)
}
}
let colors = (red, orange, yellow, green, blue, violet)
let index = 0
let size = difference.days() / date-interval
let pos = ()
taskgroup({
for item in tasks {
pos = (
item.at(1).at(0) + size * 0.007,
item.at(1).at(1) - size * 0.007,
)
if item.len() == 2 {
if index == colors.len() - 1 {
index = 0
}
task(
item.at(0),
pos,
style: (
stroke: (paint: colors.at(index), thickness: 5pt, cap: "round"),
),
)
index += 1
} else {
task(
item.at(0),
pos,
style: (
stroke: (paint: item.at(2), thickness: 5pt, cap: "round"),
),
)
}
}
})
},
)
}
|
https://github.com/sky-y/pandoc-online-20240818 | https://raw.githubusercontent.com/sky-y/pandoc-online-20240818/master/README.md | markdown | # Pandoc ONLINE \#1 - Pandocのトレンド2024:DjotとTypst (藤原 惟)
[Pandoc ONLINE #1 - connpass](https://pandoc-jp.connpass.com/event/323815/)
## Reference
- Typstのテンプレート (template.typなど)
- [GitHub - satshi/typst-jp-template](https://github.com/satshi/typst-jp-template/tree/main)
## License
Create Commons BY 4.0 |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/tgm-hit-thesis/0.1.1/CHANGELOG.md | markdown | Apache License 2.0 | # [v0.1.1](https://github.com/TGM-HIT/typst-diploma-thesis/releases/tags/v0.1.1)
- replaces some custom outline styling with [outrageous](https://typst.app/universe/package/outrageous)
- adds support for highlighting authors of individual pages of the thesis, which is a requirement for the thesis' grading
# [v0.1.0](https://github.com/TGM-HIT/typst-diploma-thesis/releases/tags/v0.1.0)
Initial Release
|