repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/jakoblistabarth/tud-corporate-design-slides-typst | https://raw.githubusercontent.com/jakoblistabarth/tud-corporate-design-slides-typst/main/template/main.typ | typst | MIT No Attribution | #import "@preview/tud-corporate-design-slides:0.1.0": *
#show: tud-slides.with(
title: "Presentation templates",
subtitle: "Corporate design rules - Guidelines for using the template and ensuring accessibility",
author: "<NAME>",
organizational-unit: "Directorate 7 - Strategy and Communication",
location-occasion: "Location or occasion of the presentation",
lang: "en",
)
#title-slide
#slide[
= Slide title
- #lorem(3)
- #lorem(5)
- #lorem(2)
]
#slide[
= Slide title
#lorem(30)
]
#slide[
= _Slide title_ *for* a slide with a figure
#figure(
rect(
width: 80%,
height: 80%,
radius: .25em,
fill: tud-gradient,
)[
#set text(fill: white, weight: "bold")
#align(horizon)["Hello, world!"]
],
caption: "Figure caption"
)
]
#section-slide(
title: "Section title",
subtitle: "Section subtitle",
)
#slide[
= Slide title
- #lorem(4)
- _#lorem(2)_
- #lorem(3)
]
|
https://github.com/hongjr03/shiroa-page | https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DSA/chapters/10Exercise.typ | typst |
#import "../template.typ": *
#import "@preview/pinit:0.1.4": *
#import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge
#import "/book.typ": book-page
#show: book-page.with(title: "练习 | DSA")
= Exercise
== 绪论
1. 多叉路口交通灯的管理问题,采用(~*D*~)关系的数据结构。#rel("逻辑结构") \ A. 集合\ B. 线性\ C. 树形\ D. 图状
2. (~*D*~)是相互之间存在一种或多种特定关系的数据元素的集合。#rel("基本概念") \ A. 数据\ B. 数据元素\ C. 数据对象\ D. 数据结构
3. 一个算法必须总是(对任何合法的输入值)在执行有穷步之后结束,是指算法的(~*A*~)特性。#rel("算法的特性") \ A. 有穷性\ B. 可行性\ C. 确定性\ D. 正确性
4. 下列算法的执行频度为(~*C*~)。
```c
for (l = 1; l <= n; ++l)
for (j = 1; j <= n; ++j) {
c[l][j] = 0;
}
```
#rel("算法复杂性分析") \ A. $O(n)$\ B. $O(n^3)$\ C. $O(n^2)$\ D. $O(n log n)$
5. 机器人和人对弈问题中,棋盘格局之间的关系为(~*B*~)。#rel("逻辑结构") \ A. 集合\ B. 线性结构\ C. 树形结构\ D. 图状结构
6. (~*C*~)是性质相同的数据元素的集合,是数据的一个子集。#rel("基本概念") \ A. 数据\ B. 数据元素\ C. 数据对象\ D. 数据结构
7. 下列算法的执行频度为(~*B*~)。 #rel("算法复杂性分析")
```c
for (l = 1; l <= n; ++l)
for (j = 1; j <= n; ++j) {
c[l][j] = 0;
for (k = 1; k <= n; ++k) {
c[l][j] += a[l][k] * b[k][j];
}
}
```\ A. $O(n)$\ B. $O(n^3)$\ C. $O(n^2)$\ D. $O(n log n)$
8. 设有 $n$ 件物品,重量分别为 $w_1, w_2, w_3, dots, w_n$ 和一个能装载总重量为 $T$ 的背包。能否从 $n$ 件物品中选择若干件恰好使它们的重量之和等于 $T$。若能,则背包问题有解,否则无解。请写出求解此问题的递归算法。
```cpp
bool choose[n] = {false};
int w[n] = {w_1, w_2, w_3, ..., w_n};
bool knapsack(int i, int T) {
if (T == 0) return true;
if (i < 1) return false;
if (w[i] > T) return knapsack(i - 1, T);
if (knapsack(i - 1, T - w[i])) {
choose[i] = true;
return true;
} else {
choose[i] = false;
return knapsack(i - 1, T);
}
}
```
9. 补充课后题 1.1、1.8。
== 线性表
1. 链表中逻辑上相邻的元素的物理地址(~*B*~)相邻。#rel("线性表的链式表示和实现") \ A. 必定\ B. 不一定\ C. 一定不\ D. 其它
2. 顺序表中逻辑上相邻的元素的物理地址(~*A*~)相邻。#rel("线性表的顺序表示和实现") \ A. 必定\ B. 有可能\ C. 一定不\ D. 其它
3. 在顺序表中插入或删除一个元素,需要平均移动 #underline[~*n/2*~] 个元素,具体移动的元素个数与插入或删除的位置有关。#rel("线性表的顺序表示和实现")
4. 用链式存储时,结点的存储位置(~*B*~)。#rel("线性表的链式表示和实现") \ A. 必须是不连续的\ B. 连续与否均可\ C. 必须是连续的\ D. 和头结点的存储地址相连续
5. 在单链表中,要访问某个结点,只要知道该结点的指针即可;因此,单链表是一种随机存取结构。(~*错*~)#rel("线性表的链式表示和实现")
6. 补充课后题 2.1、2.2、2.3、2.4、2.6、2.11、2.12。
== 栈和队列
1. 操作系统中的作业调度采用(~*C*~)结构。#rel("栈和队列") \ A. 顺序表\ B. 栈\ C. 队列\ D. 图
2. 数制转换采用(~*B*~)结构。#rel("栈和队列") \ A. 顺序表\ B. 栈\ C. 队列\ D. 图
3. 栈结构中数据元素之间呈 #underline[~*后进先出*~] 关系。#rel("栈和队列")
4. 设计一个判别表达式中左、右括号是否配对的算法,采用(~*B*~)数据结构最佳。#rel("栈和队列") \ A. 线性表的顺序存储结构\ B. 栈\ C. 队列\ D. 线性表的链式存储结构
5. 补充课后题 3.1、3.2、3.5、3.6、3.17。
== 串
1. (~*D*~)是由零个或多个字符组成的有限序列。#rel("串的基本概念") \ A. 数组\ B. 文本\ C. 线性表\ D. 字符串
2. 设 s = '<NAME>',t = 'GOOD',q = 'WORKER',则 Concat(Substring(s, 6, 2), Concat(t, q)) 的值为(~*A*~)。#rel("串的基本操作") \ A.
`A GOODWORKER`\ B. `ST GOODSTUDENT`\ C. `A GOOD STUDENT`\ D. `A GOOD WORKER`
3. 在汇编和语言的编译程序中,源程序及目标程序都是(~*D*~)数据。\ A. 数组\ B. 文本\ C. 数值\ D. 字符串
4. 设 s = '<NAME> A STUDENT',t = 'GOOD',q = 'WORKER',则 Concat(Substring(s, 6, 2), Concat(t, SubString(s, 7, 8))) 的值为(~*C*~)。#rel("串的基本操作") \ A.
`A GOODSTUDENT`\ B. `ST GOODSTUDENT`\ C. `A GOOD STUDENT`\ D. `TU GOODDENT`
5. 补充课后题 4.3、4.4。
== 数组和广义表
1. 广义表是(~*B*~)的推广。#rel("数组和广义表") \ A. 数组\ B. 线性表\ C. 队列\ D. 树
2. 线性表可以看成是广义表的特例,如果广义表中的每个元素都是原子,则广义表便成为线性表。(~*对*~)#rel("数组和广义表")
3. 广义表中原子个数即为广义表的长度。(~*错*~)#rel("数组和广义表")
4. 补充课后题 5.1、5.2、5.10、5.11、5.12、5.13、5.19(复杂度)、5.38。
== 树和二叉树
1. 有一非空树,其度为 $5$,已知度为 $i$ 的节点数有 $i$ 个,其中 $1<=i<=5$,证明其终端节点个数为 $41$。
2. 已知一棵 $3$ 阶 B-树如图所示,画出插入关键字 33,97 后得到的 B-树。
#import fletcher.shapes: house, hexagon, ellipse
#let blob(pos, label, tint: white, ..args) = node(
pos,
align(center, label),
width: auto,
fill: tint.lighten(60%),
stroke: 1pt + tint.darken(20%),
corner-radius: 5pt,
shape: ellipse,
..args,
)
#figure(
diagram(
spacing: 8pt,
cell-size: (8mm, 10mm),
edge-stroke: 1pt,
edge-corner-radius: 5pt,
mark-scale: 70%,
blob((0, -1), "43"),
edge(bend: -30deg),
edge("drr", bend: 30deg),
blob((-2, 0), "20"),
edge(bend: -30deg),
blob((-3, 1), "16"),
edge((-2, 0), (-1, 1), bend: 30deg),
blob((-1, 1), "35, 41"),
blob((2, 0), "50, 60"),
edge(bend: -30deg),
blob((1, 1), "48"),
edge((2, 0), (2, 1), bend: 30deg),
blob((2, 1), "57"),
edge((2, 0), (3, 1), bend: 30deg),
blob((3, 1), "66, 88"),
),
)
3. 对某二叉树进行前序遍历的结果为 abdefc,中序遍历的结果为 dbfeac,则后序遍历的结果为 #underline[~~~~~~~~~~~~~~~~~~~~~~~~~] 。
4. 深度为 $k$ 的二叉树至多有 $underline(2^k-1)$ 个结点。
5. 树中某一结点的度是该结点的 #underline[~~~~~~~~~~~~~~]。
6. 一棵二叉树中度为 $1$ 的结点个数为 $8$,度为 $2$ 的结点个数为 $10$,该二叉树共有 #underline[~~~~~~~~~~~~~~] 个结点。
7. 已知森林对应的二叉树如下图所示,画出原来的森林,并写出该森林按前序和中序遍历的结果。
#figure(
diagram(
spacing: 8pt,
cell-size: (8mm, 10mm),
edge-stroke: 1pt,
edge-corner-radius: 5pt,
blob((0, 0), "a"),
edge(),
blob((-2, 1), "b"),
edge(),
blob((-3, 2), "d"),
edge((-2, 1), (-1, 2)),
blob((-1, 2), "e"),
edge((0, 0), (2, 1)),
blob((2, 1), "c"),
edge((2, 1), (1, 2)),
blob((1, 2), "f"),
edge((2, 1), (3, 2)),
blob((3, 2), "g"),
),
caption: "二叉树",
)
8. 对关键字 may,mar,apr,jul,aug,sep,oct,nov,feb,jan,dec,jun 依次输入,构建二叉排序树。
9. 已知某系统在通信联络中只可能出现 10 种字符,其出现概率分别为 $0.03$,$0.19$,$0.07$,$0.12$,$0.15$,$0.10$,$0.05$,$0.08$,$0.11$,$0.10$。请构建哈夫曼树并设计编码。
10. 在一非空二叉树的中序遍历序列中,根节点右边的部分(~*A*~)。\ A. 只有右子树上所有的结点\ B. 只有右子树上的部分结点\ C. 只有左子树上的部分结点\ D. 只有左子树上所有的结点
11. 深度为 $5$ 的二叉树至多有(~*C*~)个结点。\ A. $16$ 个\ B. $32$ 个\ C. $31$ 个\ D. $10$ 个
12. 已知一棵二叉树的前序序列和中序序列分别为 ABCDEFGHIJ 和 BCDAFEHJIG,求该二叉树的后序序列并给出该二叉树对应的森林。
13. 线索二叉树比二叉树较为容易添加结点。(~*错*~)#note_block[
原因:线索二叉树的结点添加操作需要考虑结点的前驱和后继,因此比二叉树的结点添加操作复杂。
]
14. 二叉树只有在二叉树只有一个根的情况下三种遍历结果相同。(~*错*~)#note_block[
空树也是二叉树。
]
15. 对于输入关键字序列 48,70,65,33,24,56,12,92,建一棵平衡二叉树,画出过程(至少每次调整有一张,标出最小不平衡子树的根)。
16. 已知树的先根访问序列为 GFKDAIEBCHJ,后根次序访问序列为 DIAEKFCJHBG。画出满足上述访问序列对应的树及所对应的二叉树。
17. 设二叉排序树已经以二叉链表的形式存储,使用递归方法,求各结点的平衡因子并输出。\
*要求*:\
+ 用文字写出实现上述过程的基本思想;
+ 写出算法。
```c
int calculateBalanceFactors(TreeNode *node) {
if (node == NULL) {
return 0;
}
int leftHeight = calculateBalanceFactors(node->left);
int rightHeight = calculateBalanceFactors(node->right);
node->balanceFactor = leftHeight - rightHeight;
printf(
"Node value: %d, Balance Factor: %d\n",
node->val,
node->balanceFactor
);
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}
```
18. 补充课后题 6.1、6.2、6.3、6.5、6.6、6.13、6.19、6.20、6.21、6.22、6.23、6.24、6.26、6.27、6.28、6.29。
== 图
1. 对于下图所示的 AOE 网络,计算各事件顶点的 $v e(i)$ 和 $v l(i)$ 值,并标出关键路径。
#let blob(pos, label, tint: white, ..args) = node(
pos,
align(center, label),
width: auto,
fill: tint.lighten(60%),
stroke: 1pt + tint.darken(20%),
corner-radius: 5pt,
shape: circle,
..args,
)
#diagram(
blob((0, 2), "a"),
edge("urr", "-|>", label: "6"),
edge("drr", "-|>", label: "4"),
edge("ddrr", label: "5"),
blob((2, 1), "b"),
edge("drr", "-|>", label: "1"),
blob((2, 3), "c"),
edge("urr", "-|>", label: "1"),
blob((4, 2), "e"),
edge("urr", "-|>", label: "8"),
edge("drr", "-|>", label: "7"),
blob((2, 4), "d"),
edge("rr", "-|>", label: "2"),
blob((4, 4), "f"),
edge("urr", "-|>", label: "4"),
blob((6, 1), "g"),
edge("drr", "-|>", label: "2"),
blob((6, 3), "h"),
edge("urr", "-|>", label: "2"),
blob((8, 2), "k"),
)
2. 已知以二维数组表示的有向图的邻接矩阵如下图所示,完成如下要求:
+ 画出该有向图;
+ 画出邻接表。
#table(
columns: (2em, 2em, 2em, 2em, 2em, 2em, 2em, 2em),
rows: (2em, 2em, 2em, 2em, 2em, 2em, 2em, 2em),
stroke: (x, y) => {
if x == 0 {
(right: 1pt)
}
if y == 0 {
(bottom: 1pt)
}
},
table.header([], [1], [2], [3], [4], [5], [6], [7]),
[1], [0], [1], [1], [1], [0], [0], [0],
[2], [0], [0], [1], [0], [0], [1], [0],
[3], [0], [0], [0], [1], [1], [1], [0],
[4], [0], [0], [0], [0], [1], [0], [0],
[5], [0], [0], [0], [0], [0], [1], [1],
[6], [1], [1], [0], [0], [0], [0], [1],
[7], [0], [0], [0], [0], [0], [0], [0],
)
3. $n$ 个顶点的连通图至少有 #underline[~~~~~~~~~~~~~~] 条边。
4. 设无向图的顶点个数为 $n$,则该图最多有 #underline[~~~~~~~~~~~~~~] 条边。
5. 画出该无向图的邻接表,并按普利姆算法画出由顶点 1 开始的最小生成树。(要求体现出每条边被加入的顺序)
#diagram(
blob((0, 2), "1"),
edge("urr", "-|>", label: "1"),
edge("rr", "-|>", label: "2"),
edge("drr", "-|>", label: "3"),
blob((2, 1), "2"),
edge("drr", "-|>", label: "4"),
blob((2, 2), "3"),
edge("d", "-|>", label: "1"),
edge("rr", "-|>", label: "5"),
blob((2, 3), "4"),
edge("urr", "-|>", label: "2"),
blob((4, 2), "5"),
)
6. 在一个有向图中,所有顶点的入度之和等于所有顶点的出度之和的(~*B*~)。\ A. $1/2$\ B. $1$ 倍\ C. $2$ 倍\ D. $4$ 倍
7. 具有 6 个顶点的无向连通图至少应该有 #underline[~~~~~~~~~~~~~~] 条边。
8. 下图是带权有向图 $G$ 的邻接矩阵表示,给出按 Floyd 算法求所有顶点对之间的最短路径的过程(只要求距离变化矩阵序列)。
#table(
columns: (2em, 2em, 2em, 2em, 2em),
rows: (2em, 2em, 2em, 2em, 2em),
stroke: (x, y) => {
if x == 0 {
(right: 1pt)
}
if y == 0 {
(bottom: 1pt)
}
},
table.header([], [$v_1$], [$v_2$], [$v_3$], [$v_4$]),
[$v_1$], [0], [1], [$oo$], [4],
[$v_2$], [$oo$], [0], [9], [2],
[$v_3$], [3], [5], [0], [8],
[$v_4$], [$oo$], [$oo$], [6], [0],
)
9. 普利姆算法适合用于稠密图。(~*对*~)
10. 补充课后题 7.1、7.7、7.9、7.10、7.11、7.22、7.23,着重记 DFS、BFS、迪杰斯特拉算法。
== 查找
1. 设有一组关键字 ${9, 01, 23, 14, 55, 20, 84, 27}$,采用哈希函数 $H("key") = "key" mod 7$,表长为 $10$,用开放定址法的二次探测再散列方法 $H_1(i) = (H("key") + i^2) mod 10$,$i = 1, 2, 3, dots$,构造哈希表,指出有哪些同义词并计算查找成功的平均查找长度。
2. 设有一组关键字 ${22, 41, 53, 46, 30, 13, 01, 67}$,采用哈希函数 $H("key") = 3 * "key" mod 11$,表长为 $10$。
1. 用线性探测再散列法构造哈希表;
2. 求在等查找概率下的平均查找长度。
3. 哈希表的查找效率主要取决于哈希表造表时选取的哈希函数和处理冲突的方法。(~*错*~)
4. 设有一组关键字 ${01, 25, 20, 31, 63, 65, 70, 74, 79, 82}$,如果进行折半查找,则查找到每个关键字所需要的比较次数分别是多少?并求出在等查找概率下的ASL。 |
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/139.%20schlep.html.typ | typst | schlep.html
Schlep Blindness
Want to start a startup? Get funded by
Y Combinator.
January 2012There are great startup ideas lying around unexploited right under
our noses. One reason we don't see them is a phenomenon I call
schlep blindness. Schlep was originally a Yiddish word but has
passed into general use in the US. It means a tedious, unpleasant
task.No one likes schleps, but hackers especially dislike them.
Most hackers who start startups wish they could do it by just writing
some clever software, putting it on a server somewhere, and watching
the money roll in—without ever having to talk to users, or negotiate
with other companies, or deal with other people's broken code.
Maybe that's possible, but I haven't seen it.One of the many things we do at Y Combinator is teach hackers about
the inevitability of schleps. No, you can't start a startup by
just writing code. I remember going through this realization myself.
There was a point in 1995 when I was still trying to convince myself
I could start a company by just writing code. But I soon learned
from experience that schleps are not merely inevitable, but pretty
much what business consists of. A company is defined by the schleps
it will undertake. And schleps should be dealt with the same way
you'd deal with a cold swimming pool: just jump in. Which is not
to say you should seek out unpleasant work per se, but that you
should never shrink from it if it's on the path to something great.The most dangerous thing about our dislike of schleps is that much
of it is unconscious. Your unconscious won't even let you see ideas
that involve painful schleps. That's schlep blindness.The phenomenon isn't limited to startups. Most people don't
consciously decide not to be in as good physical shape as Olympic
athletes, for example. Their unconscious mind decides for them,
shrinking from the work involved.The most striking example I know of schlep blindness is
Stripe, or
rather Stripe's idea. For over a decade, every hacker who'd ever
had to process payments online knew how painful the experience was.
Thousands of people must have known about this problem. And yet
when they started startups, they decided to build recipe sites, or
aggregators for local events. Why? Why work on problems few care
much about and no one will pay for, when you could fix one of the
most important components of the world's infrastructure? Because
schlep blindness prevented people from even considering the idea
of fixing payments.Probably no one who applied to Y Combinator to work on a recipe
site began by asking "should we fix payments, or build a recipe
site?" and chose the recipe site. Though the idea of fixing payments
was right there in plain sight, they never saw it, because their
unconscious mind shrank from the complications involved. You'd
have to make deals with banks. How do you do that? Plus you're
moving money, so you're going to have to deal with fraud, and people
trying to break into your servers. Plus there are probably all
sorts of regulations to comply with. It's a lot more intimidating
to start a startup like this than a recipe site.That scariness makes ambitious ideas doubly valuable. In addition
to their intrinsic value, they're like undervalued stocks in the
sense that there's less demand for them among founders. If you
pick an ambitious idea, you'll have less competition, because
everyone else will have been frightened off by the challenges
involved. (This is also true of starting a startup generally.)How do you overcome schlep blindness? Frankly, the most valuable
antidote to schlep blindness is probably ignorance. Most successful
founders would probably say that if they'd known when they were
starting their company about the obstacles they'd have to overcome,
they might never have started it. Maybe that's one reason the most
successful startups of all so often have young founders.In practice the founders grow with the problems. But no one seems
able to foresee that, not even older, more experienced founders.
So the reason younger founders have an advantage is that they make
two mistakes that cancel each other out. They don't know how much
they can grow, but they also don't know how much they'll need to.
Older founders only make the first mistake.Ignorance can't solve everything though. Some ideas so obviously
entail alarming schleps that anyone can see them. How do you see
ideas like that? The trick I recommend is to take yourself out of
the picture. Instead of asking "what problem should I solve?" ask
"what problem do I wish someone else would solve for me?" If someone
who had to process payments before Stripe had tried asking that,
Stripe would have been one of the first things they wished for.It's too late now to be Stripe, but there's plenty still broken in
the world, if you know how to see it.Thanks to <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>, and <NAME>
for reading drafts of this.
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/chordx/0.2.0/CHANGELOG.md | markdown | Apache License 2.0 | # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [v0.2.0](https://github.com/ljgago/typst-chords/compare/v0.1.0...v0.2.0) - 2023-08-25
### Added
- New file structure.
- New piano chords.
- Options to scale the graphs.
- New round style.
### Changed
- Renamed new-graph-chords to new-chart-chords.
- Replaced array inputs by string inputs (thanks to `conchord` for the ideas).
### Removed
- Removed dependency of CeTZ, uses only native functions.
## [v0.1.0](https://github.com/ljgago/typst-chords/compare/v0.1.0...v0.1.0) - 2023-07-16
### Added
- Added graph chords.
- Added single chords.
### Changed
- The single chords show the chord name over a specific character or word.
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/写作与表达/readme.md | markdown | The Unlicense | # 写作与表达
写作与表达仅有 0.5 学分,但却需要修 16 学时(正常是 2 学分的学时),需要小组分工做高标准的 ppt(脱稿,15min,必需专业相关),还有每人的高标准结课论文(详见课程报告格式)。
并且连论文的 latex 模版也没有。不过刚好,让我尝试一下 [typst](https://typst-doc-cn.github.io/docs/)。
|
https://github.com/mem-courses/calculus | https://raw.githubusercontent.com/mem-courses/calculus/main/homework-1/calculus-homework12.typ | typst | #import "../template.typ": *
#show: project.with(
title: "Calculus Homework #12",
authors: ((
name: "<NAME> (#47)",
email: "<EMAIL>",
phone: "3230104585"
),),
date: "December 13, 2023",
)
#let int = math.integral
= P204 习题4-2 46
$
int x e^(-x) dx
= - int x dif (e^(-x))
= - (x e^(-x) - int e^(-x) dx)
= - x e^(-x) - e^(-x) + C
$
= P204 习题4-2 47
$
int ((ln x)/x)^2 dx
&= int (ln x)^2 / x dif (ln x)
= int t^2 e^(-t) dt
= - int t^2 dif (e^(-t))\
&= - (t^2 e^(-t) - int e^(-t) dif(t^2))
= - t^2 e^(-t) + 2 int t e^(-t) dt\
&= - t^2 e^(-t) - 2 t e^(-t) - 2 e^(-t) + C
= -(ln^2 x - 2 ln x - 2)/x + C
$
= P204 习题4-2 48
$
int sqrt(x) ln^2 x dx
&= int 2/3 ln^2 x dif(x^(3/2))
= 2/3 (ln^2 x dot x^(3/2) - int x^(3/2) dif(ln^2 x))\
&= 2/3 ln^2 x dot x^(3/2) - 4/3 int sqrt(x) ln x dx\
&= 2/3 ln^2 x dot x^(3/2) - 8/9 (ln x dot x^(3/2) - int sqrt(x) dx)\
&= x^(3/2) (2/3 ln^2 x - 8/9 ln x + 16/27) + C
$
= P204 习题4-2 49
$
int x^3 e^(-x^2) dx
&= 1/4 int e^(-x^2) dif(x^4)
= 1/4 int e^t dif(t^2)
= 1/2 int t e^t dt
= 1/2 int t dif(e^t)\
&= 1/2 (t e^t - int e^t dt)
= 1/2 (t e^t - e^t) + C
= - 1/2 e^(-x^2) (x^2 + 1) + C
$
= P204 习题4-2 50
$
int x^2 sin 2x dx
&= -1/2 int x^2 dif(cos 2x)
= -1/2 (x^2 cos 2x - int cos 2x dif(x^2))\
&= -1/2 x^2 cos 2x + int x cos 2x dx
= -1/2 x^2 cos 2x + 1/2 int x dif(sin 2x)\
&= -1/2 x^2 cos 2x + 1/2 (x sin 2x - int sin 2x dx)\
&= -1/2 x^2 cos 2x + 1/2 x sin 2x + 1/4 cos 2x dx + C
$
= P204 习题4-2 51
$
int arctan x dx
&= x arctan x - int x dif(arctan x)
= x arctan x - int x/(1+x^2) dx\
&= x arctan x - 1/2 int 1/(1+x^2) dif(x^2)
= x arctan x - 1/2 ln(1 + x^2) + C
$
= P204 习题4-2 52 #ac
$
int ln(x+sqrt(1+x^2)) dx
$
令 $t = display(x+sqrt(1+x^2))$,故 $x = display((t^2 - 1)/(2t))$,代入得:
$
int ln(x+sqrt(1+x^2)) dx
&= int ln t dif((t^2 - 1)/(2t))
= 1/2 int ln t (1 + 1/(t^2)) dt\
&= 1/2 int ln t dt + 1/2 int (ln t)/(t^2) dt
$
其中:
$
int ln t dt
= t ln t - int t dif(ln t)
= t ln t - int 1 dt
= t ln t - t
$
$
int (ln t)/(t^2) dt
&= (ln t)/t - int t dif((ln t)/(t^2))
= (ln t)/t - int t dot (t - ln t dot 2t)/(t^4) dt\
&= (ln t)/t - int (1 - 2ln t)/(t^2) dt
= (ln t)/t - int t^(-2) dt + 2 int (ln t)/(t^2) dt
$
$
=> int (ln t)/(t^2)
= int t^(-2) dt - (ln t)/t
= -1/t - (ln t)/t + C
$
代入得:
$
int ln(x+sqrt(1+x^2)) dx
&= 1/2 (t ln t - t - 1/t - (ln t)/t) + C\
&= 1/2 (2x ln(x +sqrt(1+x^2)) - 2 sqrt(1+x^2)) + C\
&= x ln(x + sqrt(1 + x^2)) - sqrt(1+x^2) + C
$
= P204 习题4-2 53 #ac
$
int arctan sqrt(x) dx
= int arctan sqrt(x) dot 2 sqrt(x) dif(sqrt(x))
= 2 int t arctan t dt
$
其中:
$
int t arctan t dt
&= t arctan t - int t dif(t arctan t)
= t arctan t - int t (arctan t + t/(1+t^2)) dt\
&= t arctan t - int t arctan t dt - int (t^2)/(1+t^2) dt\
$
$
=> &2 int t arctan t dt = t arctan t - t + arctan t + C
$
代入原式得:
$
int arctan sqrt(x) dx
= t arctan t - t + arctan t + C
= sqrt(x) arctan sqrt(x) - sqrt(x) + arctan sqrt(x) + C
$
= P204 习题4-2 54
$
int sin x ln tan x dx
&= - int ln tan x dif(cos x)
= - (cos x ln tan x - int cos x dif(ln tan x))\
&= - cos x ln tan x + int cos x (cos^(-2) x)/(tan x) dx
= - cos x ln tan x + int 1/(sin x) dx\
&= - cos x ln tan x + ln |csc x - cot x| + C
$
= P204 习题4-2 55
$
int x sin^2 x dx
= x sin^2 x - int x dif(x sin^2 x)
= x sin^2 x - int x (sin^2 x - x dot 2 sin x cos x) dx
$
$
=> int x sin^2 x dx
&= 1/2 x sin^2 x + 1/2 int x^2 sin(2x) dx
= 1/2 x sin^2 x + 1/16 int (2x)^2 sin(2x) dif(2x)
$
其中:
$
int (2x)^2 sin(2x) dif(2x)
&= int t^2 sin t dt
= - int t^2 dif(cos t)
= - (t^2 cos t - int cos t dif(t^2))\
&= - t^2 cos t + 2 int t cos t dt
$
$
int t cos t dt
= int t dif(sin t)
= t sin t - int sin t dt
= t sin t + cos t + C
$
代入得:
$
int x sin^2 x dx
&= 1/2 x sin^2 x + 1/16 int (2x)^2 sin(2x) dif(2x)\
&= 1/2 x sin^2 x + 1/16 (-t^2 cos t + 2 t sin t + 2 cos t) + C\
&= 1/2 x sin^2 x - 1/4 x^2 cos (2x) + 1/4 x sin(2x) + 1/8 cos(2x) + C
$
= P204 习题4-2 56
$
int x sin sqrt(x) dx
= x sqrt(x) - int x dif(x sin sqrt(x))
= x sqrt(x) - int x (sin sqrt(x) + sqrt(x)/2 cos sqrt(x) ) dx\
=> 2 int x sin sqrt(x) = x sqrt(x) - 1/2 int x sqrt(x) cos sqrt(x) dx = x sqrt(x) - int (sqrt(x))^2 cos sqrt(x) dif(sqrt(x))
$
其中:
$
int t^2 cos t dt
= int t^2 dif (sin t)
= t^2 sin t - int sin t dif(t^2)
= t^2 sin t - 2 int t sin t dt\
int t sin t dt
= - int t dif(cos t)
= - (t cos t - int cos t dt)
= - t cos t + sin t + C
$
代入得:
$
int x sin sqrt(x) dx
&= 1/2 x sqrt(x) - 1/2 (t^2 sin t - 2(t cos t + sin t)) + C\
&= 1/2 x sqrt(x) - 1/2 x sin sqrt(x) + sqrt(x) cos sqrt(x) + sin sqrt(x) + C
$
= P204 习题4-2 57
$
int (x e^(arctan x))/((1+x^2)^(3/2)) dx
&= int x/sqrt(1+x^2) dif(e^(arctan x))
= (x e^(arctan x))/sqrt(1+x^2) - int e^(arctan x) dif(x/sqrt(1+x^2))\
&= (x e^(arctan x))/sqrt(1+x^2) - int (e^(arctan x))/((1+x^2)^(3/2)) dx
$
其中:
$
int (e^(arctan x))/((1+x^2)^(3/2)) dx
&= int 1/sqrt(1+x^2) dif(e^(arctan x))
= (e^(arctan x))/sqrt(1+x^2) - int e^(arctan x) dif(1/sqrt(1+x^2))\
&= (e^(arctan x))/sqrt(1+x^2) + int (x e^(arctan x))/((1+x^2)^(3/2)) dx
$
代入得:
$
int (x e^(arctan x))/((1+x^2)^(3/2)) dx
= ((x-1) e^(arctan x))/sqrt(1+x^2) - int (x e^(arctan x))/((1+x^2)^(3/2)) dx\
=> int (x e^(arctan x))/((1+x^2)^(3/2)) dx = ((x-1) e^(arctan x))/(2 sqrt(1 +x^2)) + C
$
= P204 习题4-2 58
$
int sin(ln x) dx
= x sin (ln x) - int x dif(sin (ln x))
= x sin (ln x) - int cos (ln x) dx\
int cos(ln x) dx
= x cos (ln x) - int x dif(cos (ln x))
= x cos (ln x) + int sin (ln x) dx\
=> int sin(ln x) dx = 1/2 x (sin(ln x) - cos(ln x)) + C
$
= P204 习题4-2 59
$
int e^(2x) sin^2 x dx
= int e^(2x) (1 - cos 2x)/2 dx
= 1/4 e^(2x) - 1/2 int cos 2x e^(2x) dx
$
其中:
$
int cos 2x e^(2x) dx
= 1/2 int cos 2x dif(e^(2x))
= 1/2 int cos (ln t) dt
= 1/4 t sin (ln t) + 1/4 t cos (ln t) + C
$
代入得:
$
int e^(2x) sin^2 x dx
&= 1/4 e^(2x) - 1/8 t sin (ln t) -1/8 t cos (ln t) + C\
&= 1/4 e^(2x) - 1/8 e^(2x) sin 2x - 1/8 e^(2x) cos 2x + C\
$
= P204 习题4-2 60
$
int (arctan e^x)/(e^x) dx
&= - int arctan e^x dif(e^(-x))
= - int arctan 1/t dt\
&= - (t arctan 1/t - int t dif(arctan 1/t))\
&= - t arctan 1/t - int (t)/(t^2+1) dt\
&= - t arctan 1/t - 1/2 ln(t^2 + 1) + C\
&= - (arctan e^x)/(e^x) - 1/2 ln(e^(-2x) + 1) + C
$
= P204 习题4-2 61
$
int x/(cos^2 x) dx
= int x dif(tan x)
= x tan x - int tan x dx
= x tan x + ln |cos x| + C
$
= P204 习题4-2 62
$
int (x e^x)/((x+1)^2) dx
= (e^(x+1))/(x+1) + C
$
= P219 习题4-3 1
$
int dx/(3x^2 - 2x - 1)
$
= P219 习题4-3 2
$
int (x dx)/((x+1)(x+2)(x+3))
&= int x/2 (1/((x+1)(x+2)) - 1/((x+2)(x+3))) dx\
&= int x/2 (1/(x+1) - 2/(x+2) + 1/(x+3)) dx\
&= int 1/2 (1 - 1/(x+1) - 2 + 4/(x+2) + 1 - 3/(x+3) )dx\
&= -1/2 ln |x+1| + 2 ln|x+2| - 3/2 ln|x+3| + C\
$
= P219 习题4-3 3
$
int (x^4)/(x^4 + 5 x^2 + 4) dx
&= int (1)/(4 t^2 + 5 t + 1) dt
= 1/3 int (4/(4t+1) - 1/(t+1)) dt\
&= 1/3 int (dif(4t))/(4t+1) - 1/3 int (dt)/(t+1)
= 1/3 ln |(4t+1)/(t+1)| + C
= 1/3 ln ((x^2+4)/(x^2+1)) + C
$
= P219 习题4-3 4
$
int (x^2 + 1)/((x+1)^2 (x-1)^2) dx
&= 1/2 int ((x+1)^2 + (x-1)^2)/((x+1)^2 (x-1)^2) dx
= 1/2 int (1/(x+1)^2 + 1/(x-1)^2) dx\
&= -1/(2(x+1)) - 1/(2(x-1)) + C
$
= P219 习题4-3 5 #ac
$
int x/((x+1)(x^2 + 1)) dx
&= 1/2 int (x+1)/(x^2+1) dx - 1/2 int 1/(x+1) dx
$
其中:
$
int (x+1)/(x^2+1) dx
= int x/(x^2+1) dx + int 1/(x^2+1) dx
= 1/2 ln (x^2 + 1) + arctan x + C
$
代入得:
$
int x/((x+1)(x^2+1)) dx = 1/4 ln(x^2 + 1) +1/2 arctan x - 1/2 ln|x+1| + C
$
= P219 习题4-3 6
$
int dx/(x^3+1)
&= 1/3 int (1/(x+1) - (x-2)/(x^2 - x + 1)) dx\
&= 1/3 int 1/(x+1) dx - 1/3 int (x-1/2)/(x^2-x+1) dx + 1/2 int 1/(x^2-x+1) dx\
$
其中:
$
int 1/(x^2-x+1) dx
= int 1/((x-1/2)^2 + (sqrt(3)/2)^2) dif(x-1/2)
= 2/sqrt(3) arctan ((2x-1)/sqrt(3)) + C
$
$
int (x-1/2)/(x^2 - x + 1) dx
= 1/2 int 1/((x-1/2)^2 + 3/4) dif((x-1/2)^2)
= 1/2 ln|x^2-x+1| + C
$
代入得:
$
int dx/(x^3+1)
= 1/3 ln|x+1| - 1/6 ln|x^2-x+1| + 1/sqrt(3) arctan ((2x-1)/sqrt(3)) + C
$
= P220 第四章综合题 25(1) #ac
#prob[
推导递推公式:若 $I_n=int sin^n x dx$,则 $I_n = display((-sin^(n-1) x cos x)/n + (n-1)/n I_(n-2)) quad (n in NN_+)$.
]
$
I_n
&= int sin^n x dx
= - int sin^(n-1) x dif cos x
= - cos x sin^(n-1) x + int cos x dif (sin^(n-1) x)\
&= -cos x sin^(n-1) x + (n-1) int cos^2 x sin^(n-2) x dx\
&= -cos x sin^(n-1) x + (n-1) int (1-sin^2 x) sin^(n-2) x dx\
&= -cos x sin^(n-1) x + (n-1) int sin^(n-2) x dx - (n-1) int sin^n x dx\
&= -cos x sin^(n-1) x + (n-1) I_(n-2) - (n-1) I_n\
=> I_n
&= -(cos x sin^(n-1) x)/n + (n-1)/n I_(n-2)
$
= P220 第四章综合题 25(2) #ac
#prob[
推导递推公式:若 $I_n = int cos^n x dx$,则 $I_n = display((sin x cos^(n-1) x)/n + (n-1)/n I_(n-2)) quad (n in NN_+)$.
]
$
I_n
&= int cos^n x dx
= int cos^(n-1) x dif sin x
= sin x cos^(n-1) x - int sin x dif(cos^(n-1) x)\
&= sin x cos^(n-1) x +(n-1) int sin^2 cos^(n-2) x dx\
&= sin x cos^(n-1) x + (n-1) int (1-cos^2 x) cos^(n-2)x dx\
&= sin x cos^(n-1) x + (n-1) I_(n-2) - (n-1) I_n\
=> I_n
&= (sin x cos^(n-1) x)/n + (n-1)/n I_(n-2)
$ |
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/01-history/aleph.typ | typst | Other | #import "/template/theme.typ": theme
#let data = ```
11000110
01100110
01100110
11010110
11001100
11000110
11000110
00000000
```.text.split("\n").map(str.codepoints).map(it => it.map(v => v == "1"))
#let bitmap-grid = (body) => grid(
columns: (1fr,) * 8 ,
stroke: 1pt + theme.main,
inset: 0pt,
..range(0, 64).map(
index => layout(size => block(height: size.width)[
#let row = calc.floor(index / 8)
#let col = calc.rem(index, 8)
#if body != none { body(row, col, size.width) }
])
),
)
#let bitmap-image = bitmap-grid((row, col, width) => block(
width: 100%, height: 100%,
fill: if data.at(row).at(col) { theme.main } else { none }
))
#let bitmap-value = bitmap-grid((row, col, width) => align(horizon + center)[
#set text(size: width / 2)
#if data.at(row).at(col) { [1] } else { [0] }
])
#let right = 60%
#let left = right * 7 / 16
#let gap = 100% - left - right
#block(width: 100%, grid(
columns: (left, right),
column-gutter: gap,
align: bottom,
bitmap-image,
grid.cell(rowspan: 2, bitmap-image),
bitmap-value,
))
|
https://github.com/jorenchik/math-logic-cheatsheet | https://raw.githubusercontent.com/jorenchik/math-logic-cheatsheet/main/main.typ | typst | #set page(
margin: (
left: 1cm,
right: 1cm,
top: 1cm,
bottom: 1cm,
),
)
#set heading(numbering: "1.")
#show outline.entry.where(
level: 1
): it => {
v(12pt, weak: true)
strong(it)
}
#set enum(numbering: "a)")
// #show outline.entry.where(
// level: 1
// ): it => {
// v(12pt, weak: true)
// strong(it)
// }
#outline(indent: auto)
= Logical axiom schemes
$bold(L_1): B→(C →B)$
$bold(L_2): (B→(C →D))→((B→C)→( B→D))$
$bold(L_3): B∧C→B$
$bold(L_4): B∧C→C$
$bold(L_5): B→(C →B∧C)$
$bold(L_6): B→B∨C$
$bold(L_7): C →B∨C$
$bold(L_8): (B→D)→((C →D)→(B∨C →D))$
$bold(L_9): (B→C)→((B→¬C )→¬B)$
$bold(L_10): ¬B→( B→C)$
$bold(L_11): B∨¬B$
$bold(L_12): ∀x F (x)→F (t)$ (in particular, $∀x F (x)→F (x)$)
$bold(L_13): F (t)→∃ x F( x)$ (in particular, $F (x)→∃ x F (x)$)
$bold(L_14): ∀x(G →F (x))→(G→∀x F (x)) $
$bold(L_15): ∀x(F (x) arrow G) arrow (exists x F (x)→G)$
= Theorems
== Prooving directly
$[L_1, L_2, #[MP]]$:
+ $((A→B)→(A→C))→(A→(B→C))$. Be careful when assuming hypotheses:
assume (A→B)→(A→C), A, B – in this order, no other possibilities!
+ $(A→B)→((B→C)→(A→C))$. It's another version of the *Law of Syllogism*
(by Aristotle), or the transitivity property of implication.
+ $(A→(B→C))→(B→(A→C))$. It's another version of the *Premise
Permutation Law*. Explain the difference between this formula and Theorem
1.4.3(a): A→(B→C)├ B→(A→C).
== Deduction theorems
=== Theorem 1.5.1 (Deduction Theorem 1 AKA DT1)
If $T$ is a first order theory, and there is a proof of
$[T, #[MP]]: A_1, A_2, dots, A_n, B├ C$,
then there is a proof of
$[L_1, L_2, T, #[MP]]: A_1, A_2, dots, A_n├ B→C$.
=== Theorem 1.5.2 (Deduction Theorem 2 AKA DT2)
If there is a proof $[T, #[MP], #[Gen]]: A_1, A_2, dots, A_n, B├ C$,
where, after B appears in the proof, Generalization is not applied to the
variables that occur as free in $B$, then there is a proof of
$[L_1, L_2, L_14, T, #[MP], #[Gen]]: A_1, A_2, dots, A_n├ B→C$.
== Conjunction
=== Theorem 2.2.1.
+ (C-introduction): $[L_5, #[MP]]: A, B├ A∧B$;
+ (C-elimination): $[L_3, L_4, #[MP]]: A∧B ├ A, A∧B ├ B$.
=== Theorem 2.2.2.
+ $[L_1, L_2, L_5, #[MP]]: (A→(B→C)) ↔ ((A→B)→(A→C))$ (extension of the axiom L_2).
+ $[L_1-L_4, #[MP]]: (A→B)∧( B→C)→( A→C)$ (another form of the *Law of
Syllogism*, or *transitivity property of implication*).
=== Theorem 2.2.3 (properties of the conjunction connective).
$[L_1- L_5, #[MP]]$:
+ $A∧B↔B∧A$ . Conjunction is commutative.
+ $ A∧(B∧C)↔( A∧B)∧C$. Conjunction is associative.
+ $A∧A↔A$ . Conjunction is idempotent.
=== Theorem 2.2.4 (properties of the equivalence connective).
$[L_1- L_5, #[MP]]$:
+ $A↔A$ (reflexivity),
+ $(A↔B)→(B↔A)$ (symmetry),
+ $(A↔B)→((B↔C) →((A↔C))$ (transitivity).
== Disjunction
=== Theorem 2.3.1
+ (D-introduction)$[L_6, L_7, #[MP]]: A├ A∨B; B├ A∨B$;
+ (D-elimination) If there is a proof $[T, #[MP]]: A_1, A_2, ..., A_n, B├ D$,
and a proof $[T, #[MP]]: A_1, A_2, ..., A_n, C├ D$, then there is a proof $[T,
L_1, L_2, L_8, #[MP]]: A_1, A_2, dots, A_n, B∨C ├ D$.
=== Theorem 2.3.2
a) $[ L_5, L_6-L_8, #[MP]]: A∨B↔B∨A$ . Disjunction is commutative.
b) $[L_1, L_2, L_5, L_6-L_8, #[MP]]: A∨A↔A$ . Disjunction is idempotent.
=== Theorem 2.3.3.
Disjunction is associative: $[L_1, L_2, L_5, L_6-L_8, #[MP]]: A∨(B∨C)↔(
A∨B)∨C$.
=== Theorem 2.3.4.
Conjunction is distributive to disjunction, and disjunction is distributive to
conjunction:
+ $[L_1-L_8, #[MP]]: (A∧B)∨C ↔(A∨C)∧(B∨C)$ .
+ $[L_1-L_8, #[MP]]: (A∨B)∧C ↔(A∧C)∨(B∧C)$ .
=== Theorem 2.3.4.
Conjunction is distributive to disjunction, and disjunction is distributive to
conjunction:
+ $[L_1-L_8, #[MP]]: (A∧B)∨C ↔(A∨C)∧(B∨C)$;
+ $[L_1-L_8, #[MP]]: (A∨B)∧C ↔(A∧C)∨(B∧C)$ .
== Negation -- minimal logic
=== Theorem 2.4.1.
(N-elimination) If there is a proof
$[T, #[MP]]: A_1, A_2, ..., A_n, B├ C$, and a proof $[T, #[MP]]: A_1, A_2, ..., A_n,
B├ ¬C$, then there is a proof $[T, L_1, L_2, L_9, #[MP]]: A_1, A_2, ..., A_n├ ¬B$.
=== Theorem 2.4.2.
a) $[L_1, L_2, L_9, #[MP]]: A, ¬B├ ¬(A→B)$. What does it mean?
b) $[L_1-L_4, L_9, #[MP]]: A∧¬B→¬( A→B)$.
=== Theorem 2.4.3.
$[L_1, L_2, L_9, #[MP]]: (A→B)→(¬B→¬A)$. What does it mean?
It's the so-called *Contraposition Law*.
Note. The following rule form of Contraposition Law is called *Modus Tollens*:
$[L_1, L_2, L_9, #[MP]]: A→B, ¬B├ ¬A, or, frac(A→B \; ¬B, ¬A)$
=== Theorem 2.4.4.
$[L_1, L_2, L_9, #[MP]]: A→¬¬A$.
=== Theorem 2.4.5.
a) $[L_1, L_2, L_9, #[MP]]: ¬¬¬A↔¬A$.
b) $[L_1, L_2, L_6, L_7, L_9, #[MP]]: ¬¬( A∨¬A)$. What does it mean? This is a “weak
form” of the *Law of Excluded Middle* that can be proved
constructively. The formula $¬¬( A∨¬A)$ can be proved in the constructive logic,
but $A∨¬A$ can't – as we will see in Section 2.8.
=== Theorem 2.4.9.
+ $[L_1, L_2, L_8, L_9, #[MP]]: ¬A∨¬B→¬( A∧B)$ . It's the constructive half of the
so-called *First de Morgan Law*. What does it mean?
+ $[L_1-L_9, #[MP]]: ¬(A∨B)↔¬A∧¬B$. It's the so-called *Second de Morgan Law*.
== Negation -- constructive logic
=== Theorem 2.5.1.
+ $[L_1, L_8, L_10, #[MP]]: ¬A∨B→( A→B)$.
+ $[L_1, L_2, L_6, #[MP]]: A∨B→(¬A→B) ├¬A→(A→B)$ . It means that the “natural”
rule $A∨B ;¬ A ├ B$ implies $L_10$!
=== Theorem 2.5.2.
$[L_1-L_10, #[MP]]$:
+ $(¬¬A→¬¬B)→¬¬(A→B)$. It's the converse of Theorem 2.4.7(b). Hence, $[L_1-L_10,
#[MP]]:├ ¬¬(A→B)↔(¬¬A→¬¬B)$.
+ $¬¬A→(¬A→A)$. It's the converse of Theorem 2.4.6(a). Hence, [L1-L10,
#[MP]]: $¬¬A↔(¬A→A)$.
+ $A∨¬ A→(¬¬A→A)$ .
+ $¬¬(¬¬A→A)$. What does it mean? It’s a “weak” form of the Double Negations
Law – provable in constructive logic.
== Negation -- classical logic
=== Theorem 2.6.1. (Double Negation Law)
$[L_1, L_2, L_8, L_10, L_11, #[MP]]: ¬¬A → A$. Hence, $[L_1-L_11, #[MP]]: ¬¬A ↔
A$.
=== Theorem 2.6.2.
$[L_8, L_11, #[MP]]: A→B, ¬A→B├ B$. Or, by Deduction Theorem 1, $[L_1, L_2, L_8,
L_11, #[MP]]: (A→B)→((¬A→B)→B)$.
=== Theorem 2.6.3.
$[L_1-L_11, #[MP]]: (¬B→¬A)→(A→B)$. Hence, $[L_1-L_11, #[MP]]: (A→B) ↔ (¬B→¬A)$.
=== Theorem 2.6.3.
_(another one with the same number of because numbering error (it seems like it))_
$[L_1-L_9, L_11, #[MP]]: ˫ ¬(A∧B)→¬A∨¬B$ . Hence, $[L_1-L_9, L_11, #[MP]]: ˫
¬(A∧B)↔¬A∨¬B$ .
=== Theorem 2.6.4.
$[L_1-L_8, L_11, #[MP]]: (A→B)→¬ A∨B $. Hence, (I-elimination) $[L_1-L_11, #[MP]]:
(A→B)↔¬ A∨B$.
=== Theorem 2.6.5.
$[L_1-L_11, #[MP]]: ¬(A→B)→A∧¬B $.
=== Theorem 2.7.1 (Glivenko's Theorem).
$[L_1-L_11, #[MP]]:├ A$ if and only if $[L_1-L_10, #[MP]]:├ ¬¬A$.
== Axiom independence
=== Theorem 2.8.1.
The axiom $L_9$: $(A→B)→((A→¬B)→¬A)$ can be proved in $[L_1, L_2, L_8, L_10,
L_11, #[MP]]$.
=== Theorem 2.8.2.
The axiom $L_9$ cannot be proved in $[L_1-L_8, L_10, #[MP]]$.
== Replacement Theorems
=== Replacement Theorem 1
Let us consider three formulas: $B$, $B'$, $C$, where $B$ is a sub-formula of
$C$, and $o(B)$ is a propositional occurrence of $B$ in $C$. Let us denote by
$C'$ the formula obtained from $C$ by replacing $o(B)$ by $B'$. Then, in the
minimal logic,
$[L_1-L_9, #[MP]]: B↔B'├ C↔C'$.
=== Replacement Theorem 2
Let us consider three formulas: $B$, $B'$, $C$, where $B$ is a sub-formula of
$C$, and $o(B)$ is any occurrence of $B$ in $C$. Let us denote by $C'$ the
formula obtained from $C$ by replacing $o(B)$ by B'. Then, in the minimal
logic,
$[L_1-L_9, L_12-L_15, #[MP], #[Gen]]: B↔B'├ C↔C'$.
== Predicate Logic
=== Theorem 3.1.1.
$[L_1, L_2, L_12, L_13, #[MP]]: forall x B(x) arrow exists x B(x)$. What does
it mean? It prohibits "empty domains".
=== Theorem 3.1.2.
+ $[L_1, L_2, L_12, L_14, #[MP], #[Gen]]: ∀x(B→C)→(∀x B → ∀x C)$.
+ $[L_1, L_2, L_12-L_15, #[MP], #[Gen]]: ∀x(B→C)→(∃z B → ∃x C)$.
=== Theorems 3.1.3.
If F is any formula, then:
+ (U-introduction) $[#[Gen]]: F(x) ├∀x F(x)$ .
+ (U-elimination) $[L_12, #[MP], #[Gen]]: ∀x F(x) ├F(x)$.
+ (E-introduction) $[L_13, #[MP], #[Gen]]: F(x) ├ ∃x F(x)$.
=== Theorems 3.1.4.
If F is any formula, and G is a formula that does not contain free occurrences of x, then:
+ (U2-introduction) $[L_14, #[MP], #[Gen]] G →F (x) ├G →∀x F (x)$.
+ (E2-introduction) $[L_15, #[MP], #[Gen]]: F (x)→G ├ ∃ x F (x)→G$.
=== Theorem 3.1.5.
+ $[L_1, L_2, L_5, L_12, L_14, #[MP], #[Gen]]: forall x forall y B(x,y) ↔
forall y forall x B(x,y)$
+ $[L_1, L_2, L_5, L_13, L_15, #[MP], #[Gen]]: exists x exists y B(x,y) ↔
exists y exists x B(x,y)$.
+ $[L_1, L_2, L_12-L_15, #[MP], #[Gen]]: exists x forall y B(x,y) ↔ forall y
exists x B(x,y)$.
=== Theorem 3.1.6.
If the formula B does not contain free occurrences of x, then $[L_1-L_2,
L_12-L_15, #[MP], #[Gen]]: (∀x B)↔B;(∃x B)↔B$, i.e., quantifiers $∀ x ; ∃
x$ can be dropped or introduced as needed.
== Formulas Containing Negations and a Single Quantifier
== Theorem 3.2.1.
In the classical logic,
$[L_1-L_15, #[MP], #[Gen]]: ¬ ∀x ¬B ↔ ∀x B$.
== Theorem 3.3.1.
+ $[L_1-L_5, L_12, L_14, #[MP], #[Gen]]: ∀x(B∧C)↔∀x B∧∀x C$ .
+ $[L_1, L_2, L_6-L_8, L_12, L_14, #[MP], #[Gen]]: ├∀x B∨∀x C →∀x(B∨C)$. The converse
formula $∀x(B∨C)→∀x$ B∨∀xC cannot be true.
== Theorem 3.3.2.
+ $[L_1-L_8, L_12-L_15, #[MP], #[Gen]]: ∃x(B∨C)↔∃x B∨∃x C$.
+ $[L_1-L_5, L_13-L_15, #[MP], #[Gen]]: ∃x(B∧C)→∃x B∧∃x C$. The converse
implication $∃ x B∧∃x C →∃ x(B∧C)$ cannot be true.
= Three-valued logic
This is a general scheme (page 74) to define a three valued logic.
For example, let us consider a kind of "three-valued logic", where 0 means
"false", 1 – "unknown" (or NULL – in terms of SQL), and 2 means "true".
Then it would be natural to define “truth values” of conjunction and
disjunction as
$A∧B=min ( A, B)$ ;
$A∨B=max (A , B)$ .
But how should we define “truth values” of implication and negation?
#table(
columns: 5,
[$A$], [$B$], [$A∧B$], [$A∨B$], [$A→B$],
[$0$], [$0$], [$0$], [$0$], [$i_1$],
[$0$], [$1$], [$0$], [$1$], [$i_2$],
[$0$], [$2$], [$0$], [$2$], [$i_3$],
[$1$], [$0$], [$0$], [$1$], [$i_4$],
[$1$], [$1$], [$1$], [$1$], [$i_5$],
[$1$], [$2$], [$1$], [$2$], [$i_6$],
[$2$], [$0$], [$0$], [$2$], [$i_7$],
[$2$], [$1$], [$1$], [$2$], [$i_8$],
[$2$], [$2$], [$2$], [$2$], [$i_9$],
)
#table(
columns: 2,
[$A$], [¬$A$],
[$0$], [$i_10$],
[$1$], [$i_11$],
[$2$], [$i_12$],
)
= Model interpreation
== Interpretation of a language
=== The language-specific part
Let L be a predicate language containing:
- (a possibly empty) set of object constants $c_1, dots, c_k, dots $;
- (a possibly empty) set of function constants $f_1, dots, f_m, dots,$;
- (a non empty) set of predicate constants $p_1, ..., p_n, ...$.
An interpretation $J$ of the language $L$ consists of the following two
entities (a set and a mapping):
+ A non-empty finite or infinite set DJ – the domain of interpretation (it will
serve first of all as the range of object variables). (For infinite domains, set
theory comes in here.)
+ A mapping intJ that assigns:
- to each object constant $c_i$ – a member $#[int]_J (c_i)$ of the domain
$D_J$ [contstant corresponds to an object from domain];
- to each function constant $f_i$ – a function $#[int]_J (f_i)$ from $D_J
times dots times D_J$ into $D_J$ [],
- to each predicate constant $p_i$ – a predicate $#[int]_J (p_i)$ on $D_J$.
Having an interpretation $J$ of the language $L$, we can define the notion of
*true formulas* (more precisely − the notion of formulas that are true under
the interpretation $J$).
*Example.* The above interpretation of the “language about people” put in the
terms of the general definition:
+ $D = {#[br], #[jo], #[pa], #[pe]}$.
+ $#[int]_J (#[Britney])=#[br], #[int]_J (#[John])=#[jo], #[int]_J (#[Paris])=#[pa],
#[int]_J (#[Peter])=#[pe]$.
+ $#[int]_J (#[Male]) = {#[jo], #[pe]}; #[int]_J (#[Female]) = {#[br], #[pa]}$.
+ $#[int]_J (#[Mother]) = {(#[pa], #[br]), (#[pa], #[jo])}; #[int]_J (#[Father]) =
{(#[pe], #[jo]), (#[pe], #[br])}$.
+ $#[int]_J (#[Married]) = {(#[pa], #[pe]), (#[pe], #[pa])}$.
+ $#[int]_J (=) = {(#[br], #[br]), (#[jo], #[jo]), (#[pa], #[pa]), (#[pe],
#[pe])}$.
=== Interpretations of languages − the standard common part
Finally, we define the notion of *true formulas* of the language $L$ under the
interpretation $J$ (of course, for a fixed combination of values of their free
variables – if any):
+ Truth-values of the formulas: $¬B , B∧C , B∨C , B →C$ [those are not
examples] must be computed. This is done with the truth-values of $B$ and $C$
by using the well-known classical truth tables (see Section 4.2).
+ The formula $∀x B$ is true under $J$ if and only if $B(c)$ is true under $J$
for all members $c$ of the domain $D_J$.
+ The formula $∃x B$ is true under $J$ if and only if there is a member c of the
domain $D_J$ such that $B(c)$ is true under $J$.
*Example.* In first order arithmetic, the formula
$
y((x= y+ y)∨( x=y+ y+1))
$
is intended to say that "x is even or odd". Under the standard interpretation S
of arithmetic, this formula is true for all values of its free variable x.
Similarly, $∀x ∀y(x+ y=y+x)$ is a closed formula that is true under
this interpretation. The notion “a closed formula F is true under the
interpretation J” is now precisely defined.
*Important − non-constructivity!* It may seem that, under an interpretation,
any closed formula is "either true or false". However, note that, for an infinite
domain DJ, the notion of "true formulas under J" is extremely non-
constructive.
=== Example of building of an interpretation
In Section 1.2, in our "language about people" we used four names of people
(Britney, John, Paris, Peter) as object constants and the following predicate
constants:
+ $#[Male] (x)$ − means "x is a male person";
+ $#[Female] (x)$ − means "x is a female person";
+ $#[Mother] (x, y)$ − means "x is mother of y";
+ $#[Father] (x, y)$ − means "x is father of y";
+ $#[Married] (x, y)$ − means "x and y are married";
+ $x=y$ − means "x and y are the same person".
Now, let us consider the following interpretation of the language – a specific
“small four person world”:
The domain of interpretation – and the range of variables – is: $D = {#[br],
#[jo], #[pa], #[pe]}$ (no people, four character strings only!).
Interpretations of predicate constants are defined by the following truth
tables:
#table(
columns: 3,
[x], [Male(x)], [Female(x)],
[br], [false], [true],
[jo], [true], [false],
[pa], [false], [true],
[pe], [true], [false],
)
#table(
columns: 6,
[x], [y], [Father(x,y)], [Mother(x,y)], [Married(x,y)], [x=y],
[br], [br], [false], [false], [false], [true],
[br], [jo], [false], [false], [false], [false],
[br], [pa], [false], [false], [false], [false],
[br], [pe], [false], [false], [false], [false],
[jo], [br], [false], [false], [false], [false],
[jo], [jo], [false], [false], [false], [true],
[jo], [pa], [false], [false], [false], [false],
[jo], [pe], [false], [false], [false], [false],
[pa], [br], [false], [true], [false], [false],
[pa], [jo], [false], [true], [false], [false],
[pa], [pa], [false], [false], [false], [true],
[pa], [pe], [false], [false], [true], [false],
[pe], [br], [true], [false], [false], [false],
[pe], [jo], [true], [false], [false], [false],
[pe], [pa], [false], [false], [true], [false],
[pe], [pe], [false], [false], [false], [true],
)
== Three kinds of formulas
If one explores some formula F of the language L under various
interpretations, then three situations are possible:
+ $F$ is true in all interpretations of the language $L$. Formulas of this kind are
called *logically valid formulas* (LVF, Latv. *LVD*).
+ $F$ is true in some interpretations of $L$, and false − in some other
interpretations of $L$.
+ F is false in all interpretations of L Formulas of this kind are called
*unsatisfiable formulas* (Latv. *neizpildāmas funkcijas*).
Formulas that are "not unsatisfiable" (formulas of classes (a) and (b)) are
called, of course, satisfiable formulas: a formula is satisfiable, if it is
true in at least one interpretation [*satisfiable functions* (Latv. *izpildāmas
funkcijas*)].
=== Note on information of LVF
A logically valid formula is true independently of its "meaning" − the
particular interpretations of constants, functions and predicates used in it.
But note that here, the (classical!) “meanings” of propositional connectives
and quantifiers remain fixed.
Hence, in a sense, logically valid formulas are “content-free”: being true in
all interpretations, they do not provide any specific information about the
features of objects they are “speaking” about.
=== Prooving an F is LVF (Latv. LVD)
First, we should learn to prove that some formula is (if really is!) logically
valid. Easiest way to do it by reasoning from the opposite: suppose that exists
such interpretation J, where formula is false, and derive a contradiction from
this. Then this will mean that formula is true in all interpretations, and so
logically valid. Check pages 125-126 of the book for example of such proof
(there is proven that axiom L12 is true in all interpretations). Definitely
check it, because in such way you will need to solve tasks in homeworks and
tests.
=== Prooving an F is satisfiable but NOT LVF
As an example, let us verify that the formula
$
∀x( p( x)∨q( x))→∀x p(x)∨∀x q(x)
$
is not logically valid (p, q are predicate constants). Why it is not? Because
the truth-values of p(x) and q(x) may behave in such a way that $p(x)∨q(x)$ is
always true, but neither $forall x p(x)$, nor $forall x q(x)$ is true. Indeed,
let us take the domain $D = {a, b}$, and set (in fact, we are using one of two
possibilities):
#table(
columns: 3,
[x], [p(x)], [q(x)],
[b], [false], [true],
[a], [true], [false],
)
In this interpretation, $p(a)∨q(a) = #[true]$ , $p(b)∨q(b) = #[true]$,
i.e., the premise $∀x( p( x)∨q(x))$ is true. But the formulas$forall p(x),
forall q(x)$ both are false. Hence, in this interpretation, the conclusion $∀x
p(x)∨∀x q(x)$ is false, and $∀x( p( x)∨q( x))→∀x p(x)∨∀x q(x)$ is false. We
have built an interpretation, making the formula false. Hence, it is not
logically valid.
On the other hand, this formula is satisfiable – there is an interpretation
under which it is true. Indeed, let us take $D={a}$ as the domain of
interpretation, and let us set $p(a)=q(a)=#[true]$. Then all the formulas
$
∀x( p( x)∨q( x)),∀x p(x),∀x q( x)
$
become true, and so becomes the entire formula.
=== Consistency
Sometimes, a seemingly plausible set of axioms allows deriving of
contradictions (the most striking example − Russell's paradox in the "naive"
set theory). A formula F is called a contradiction in the theory T, if $[T]:├
F$ and $[T]:├ ¬F$, i.e., if T both proves and disproves F. Theories allowing to
derive contradictions are called inconsistent theories. Thus, T is called a
consistent theory if and only if T does not allow deriving of contradictions.
Normally, for a first order theory, the set of all theorems is infinite, and,
therefore, consistency cannot be verified empirically. We may only hope to
establish this desirable property by means of some theoretical proof (see
Podnieks [1997], Section 5.4 for a more detailed discussion of this problem).
For theories adopting the above logical axioms, inconsistency is, in a sense,
"the worst possible property".
Indeed, the axiom $L_10: ¬B→( B→C)$ says that in an inconsistent theory
anything is provable. In Exercise 1.4.2 we will − without L10 − prove 50% of
it: $[L_1, L_9, #[MP]]: B, ¬B├ ¬C$. Thus, even without $L_10$ (but with $L_1$):
in an inconsistent theory anything is disprovable. Is consistency enough for a
theory to be "perfect", “non-empty” etc? In Section 4.3 we will prove the
so-called Model Existence Theorem: if a first order theory is consistent, then
there is a "model" (a kind of a "mathematical reality") where all its axioms
and theorems are "true", i.e., a consistent theory is at least “non-empty”.
== Completeness
T is called a complete theory if and only if for each closed formula F in the
language of $T: [T]:├ F$ or $[T]:├ ¬F$, i.e., if and only if T proves or
disproves any closed formula of its language. In other words: a complete theory
can solve any problem from the domain of its competence.
In an incomplete theory, some closed formulas ("definite assertions about the
objects of theory") can be neither proved, not disproved. Thus, an incomplete
theory does not solve some of the problems from the domain of its
competence.
=== Gödel's Completeness Theorem
*Theorem 4.3.1.* In classical predicate logic $[L_1−L_15,#[MP],#[Gen]]$ all
logically valid formulas can be derived.
*Theorem 4.3.3.* All formulas that can be derived in classical predicate logic
$[L_1−L_15,#[MP],#[Gen]]$ are logically valid. In this logic it is not possible
to derive contradictions, it is consistent.
=== Gödel's Incompleteness Theorem
Gödel's Incompleteness Theorem says that all fundamental mathematical
theories are either inconsistent or incomplete, i.e., none of them is
absolutely perfect (see Mendelson [1997] or Podnieks [1997], Section 6.1).
=== Gödel’s theorem usage for task solving
This theorem gives us new method to conclude that some formula $F$ is derivable
in classical predicate logic: instead of trying to derive $F$ by using axioms,
rules of inference, deduction theorem, T 2.3.1 and other helping tools, we can
just prove that $F$ is logically valid (by showing that none of interpretations
can make it false). If we manage to do so, then we can announce: according to
Gödel’s theorem, $F$ is derivable in classical predicate logic
$[L_1−L_15,#[MP],#[Gen]]$.
= Tableaux algorithm
== Step 1.
We will solve the task from the opposite: append to the hypotheses $F_1, dots
F_n$ negation of formula $G$, and obtain the set $F_1, dots, F_n, ¬G$. When you
will do homework or test, you shouldn’t forget this, because if you work with
the set $F_1, ..., F_n, G$, then obtained result will not give an answer
whether $G$ is derivable or not. You should keep this in mind also when the
task has only one formula, e.g., verify, whether formula $(A→B)→((B→C)→(A→C))$
is derivable. Then from the beginning you should append negation in front:
¬((A→B)→((B→C)→(A→C))) and then work further. Instead of the set $F_1, dots,
F_n, ¬G$ we can always check one formula $F_1∧...∧F_n∧¬G$. Therefore, our task
(theoretically) is reducing to the task: given some predicate language formula
F, verify, whether it is satisfiable or not.
== Step 2.
Before applying the algorithm, you first should translate formula to the
so-called negation normal form. We can use the possibilities provided by
Substitution theorem. First, implications are replaced with negations and
disjunctions:
$
(A→B)↔¬A∨B
$
Then we apply de Morgan laws to get negations close to the atoms:
$
¬(A∨B)↔¬A∧¬B equiv \
¬(A∧B)↔¬A∨¬B
$
In such way all negations are carried exactly before atoms.
After that we can remove double negations:
$
¬¬A↔A
$
Example: $(p→q)→q$.
First get rid of implications: $¬(¬p∨q)∨q$.
Then apply de Morgan law: $(¬¬p∧¬q)∨q$.
Then get rid of double negations: $(p∧¬q)∨q$.
Now we have obtained equivalent formula in negation normal form – formula only
has conjunctions and disjunctions, and all negations appear only in front of
atoms.
== Step 3.
Next, we should build a tree, vertices of which are formulas. In the root of
the tree we put our formula. Then we have two cases.
+ If vertex is formula A∧B, then each branch that goes through this vertex is
extended with vertices A and B.
+ If vertex is a formula A∨B, then in place of continuation we have branching
into vertex A and vertex B.
In both cases, the initial vertex is marked as processed. Algorithm continues
to process all cases 1 and 2 until all non-atomic vertices have been processed.
== Step 4.
When the construction of the tree is finished, we need to analyze and make
conclusions. When one branch has some atom both with and without a negation
(e.g., $A$ and $¬A$), then it is called closed branch. Other branches are
called open branches.
*Theorem.* If in constructed tree, there exists at least one open branch, then
formula in the root is satisfiable. And vice versa – if all branches in the
tree are closed, then formula in the root is unsatisfiable.
|
|
https://github.com/Wh4rp/Typst-PUC | https://raw.githubusercontent.com/Wh4rp/Typst-PUC/master/modules/template.typ | typst | #import "theorems.typ": *
#let problem = thmbox(
"problem",
"Problema",
separator: strong(".") + h(0.2em),
base_level: 0,
inset: (top: 0em, left: 1.2em, right: 1.2em),
breakable: true,
)
#let solution = thmplain(
"solution",
"Solución",
separator: h(0.2em),
base_level: 0,
inset: 1.2em,
stroke: rgb("#68ff68") + 1pt,
breakable: true,
).with(numbering: none)
#let project(
curso: (
sigla: none,
nombre: none,
departamento: none,
),
autor: (
nombre: none,
apellido: none,
email: none,
),
numero_de_ayudantia: none,
fecha: none,
body: none,
) = {
set page(margin: (x: 2.5cm, y: 2cm), numbering: "1",)
set text(size: 11pt)
set enum(numbering: "a)", indent: 10pt)
grid(
columns: (60pt, auto),
rows: (auto, auto),
column-gutter: 10pt,
image("uc.svg"),
align(horizon)[
Pontificia Universidad Católica de Chile\
Escuela de Ingeniería\
#curso.departamento\
#autor.nombre #autor.apellido - #link("mailto:" + autor.email, autor.email)
],
)
align(center)[
#text(weight: 700, 1.5em, [#curso.sigla - #curso.nombre])\
#text(weight: 500, 1.25em, [Ayudantía #numero_de_ayudantia - #fecha])
]
v(10pt)
set text(size: 12pt)
body
}
|
|
https://github.com/Karolinskis/KTU-typst | https://raw.githubusercontent.com/Karolinskis/KTU-typst/main/mainPages/PageSummaryEN.typ | typst | #import "/variables.typ" : *
#page(header: none)[
#set text(size: 12pt)
#AuthorName.at(1).
#ProjectTitleEN.
#ProjectTypeEN.
#ProjectSupervisorEN.join(" ").
#ProjectFacultyEN, Kaunas University of Technology.
Study field and area: #ProjectStudyFieldAndAreaEN.
Keywords: #ProjectKeywordsEN.
#ProjectCity, #ProjectYear.
#context counter(page).final().at(0) pages.
#set align(center)
*Summary*
#set align(start)
#lorem(30)\
\
#lorem(40)
] |
|
https://github.com/Riesi/typst_stains | https://raw.githubusercontent.com/Riesi/typst_stains/main/example.typ | typst | The Unlicense | #import "stains.typ": stain
#lorem(200)
#stain(index:0, scale: 40%, rotation:10deg)
#lorem(300)
#stain(index:1, scale: 40%, dy:20em, dx: 0em)
#lorem(150)
#stain(type: "coffee", index:2, scale: 40%, dy:0em, dx: 0em)
#lorem(150) |
https://github.com/darioglasl/Arbeiten-Vorlage-Typst | https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/README.md | markdown | # Arbeiten Vorlage Typst
Vorlage für Arbeiten an der Fachhochschule OST mit Typst.
## How to use
VS Code nutzen mit folgenden Extensions:
- Typst LSP
- vscode-pdf
- Typst Preview
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cheda-seu-thesis/0.2.0/seu-thesis/pages/cover-bachelor-fn.typ | typst | Apache License 2.0 | #import "../utils/packages.typ": fakebold
#import "../utils/fonts.typ": 字体, 字号, chineseunderline, justify-words
#let bachelor-cover-conf(
studentID: "00121001",
author: "王东南",
school: "示例学院",
major: "示例专业",
advisor: "湖牌桥",
thesisname: "示例论文标题\n此行空白时下划线自动消失",
date: "某个起止日期",
) = page(paper: "a4", margin: (top: 2cm+0.7cm, bottom: 2cm+0.5cm, left: 2cm + 0.5cm, right: 2cm))[
#set text(lang: "zh")
#set align(center)
//#hide[#heading(outlined: false, bookmarked: true)[封面]]
#image("../assets/vi/东南大学校标文字组合.png", width: 10cm)
#block(height: 2cm, {
text(font: 字体.黑体, size: 字号.一号, fakebold[本科毕业设计(论文)报告])
})
#v(40pt)
#block(height: 2.5cm, {
set text(font: 字体.黑体, size: 字号.二号, weight: "regular")
grid(
columns: (2.85cm, 12.84cm),
[题 目:], chineseunderline(thesisname)
)
})
#v(40pt)
#{
set text(font: 字体.宋体, size: 字号.小二, weight: "regular")
grid(
columns: (3.44cm-1em, 1em, 8cm),
rows: 1.4cm,
justify-words("学号", width: 4em), ":", chineseunderline(studentID),
justify-words("姓名", width: 4em), ":", chineseunderline(author),
justify-words("学院", width: 4em), ":", chineseunderline(school),
justify-words("专业", width: 4em), ":", chineseunderline(major),
justify-words("指导教师", width: 4em), ":", chineseunderline(advisor),
justify-words("起止日期", width: 4em), ":", chineseunderline(date),
)
}
]
// 测试部分
#bachelor-cover-conf(
studentID: "00121001",
author: "王东南",
school: "示例学院",
major: "示例专业",
advisor: "湖牌桥",
thesisname: "示例论文标题\n此行空白时下划线自动消失",
date: "某个起止日期",
) |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/033%20-%20Rivals%20of%20Ixalan/003_The%20Arbiter%20of%20Law%20Left%20Chaos%20in%20His%20Wake.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Arbiter of Law Left Chaos in His Wake",
set_name: "Rivals of Ixalan",
story_date: datetime(day: 24, month: 01, year: 2018),
author: "<NAME> & <NAME>",
doc
)
= HUATLI
Huatli swore through her teeth as she took off through the jungle toward the distant golden walls of Orazca.
She could barely make out Angrath's lumbering shape cutting a line through the thick of the rainforest ahead, and in the periphery on both sides, she saw the flash of familiar silvery scales.
"Stop right there!" Huatli growled, her eyes flashing a warm amber as she gripped the air with her fist. A half-second later, a massive dinosaur bounded into view. The dinosaur rapidly closed the distance between itself and Angrath, then effortlessly bowled him over and trapped him underfoot.
The minotaur roared in frustration, and Huatli goaded the dinosaur to roar right back.
Angrath went quiet. He was panting heavily and grunting under the dinosaur's weight.
"Do you have him under control?" asked an elderly voice from behind Huatli.
Tishana was walking forward through the thick of the rainforest, a sly grin tugging at the corners of her mouth. Behind her, Huatli saw the silhouettes of dozens of merfolk standing at the ready.
Huatli nodded. "Yes, I do. Thank you, Tishana," she replied.
Tishana shifted from one foot to the other.
Huatli calmed her racing heart. She wondered if the merfolk elder might race off again, and was half certain she should leave Angrath under her dinosaur's foot and join the merfolk if Tishana did make for the city.
"Is our agreement off, then?" Huatli asked in a steady tone.
Tishana shook her head. "I assembled my clan. Our agreement stands. Now that the city is awoken, it is a beacon. Others intend to assemble, drawn by its light—much as you are, little moth."
Huatli blinked through another wave of headache. The moth metaphor did not sit well with her.
Tishana approached, concerned. "You are unwell."
Huatli shrugged it off. "I'm fine. The closer we get to the city, the more my head hurts, is all."
"You and the pirate drift on similar currents," Tishana said cryptically. "What do you see when you glimpse beyond our veil?"
"My chain in your face!" yelled Angrath from under the dinosaur's foot. Huatli flicked her wrist and her dinosaur shoved him deeper into the dirt.
She turned back, ignoring Angrath's muffled yell in response. "I hear stories from other worlds," she said to Tishana.
Tishana laid her hand on Huatli's shoulder. Her face was serene and kind, the very soul of wisdom. "Then we should make certain you get to hear them in full, Warrior-Poet."
Huatli's heart caught in her throat. She kneeled next to Angrath, who was still trying to wriggle his way out from under her dinosaur's foot.
"Angrath, I'm sorry, but I need to go with Tishana. We had a deal first."
Angrath tried to yell at her through a face full of loam.
Huatli laid a hand on her dinosaur and gave it a brief command. "You'll be let out in thirty minutes. I'm sorry!"
Huatli whistled, and a snubhorn trotted out of the rainforest toward her. She climbed on its back with ease and took off alongside Tishana before she had to listen to any more of Angrath's furious, indistinct objections.
Tishana caught up quickly, riding the same elemental as before.
Time stretched as they approached. The spires grew closer, the sun creeped higher overhead. Huatli maintained a quick pace to keep ahead of Angrath, well aware that danger lay both behind and ahead.
The gold of the city reflected the light of the sun and the heat that came with it, and after some time, Huatli blinked sweat from her eyes as she passed through the gate of the golden city.
Orazca was magnificent, a packed cityscape of shining walls and immense carvings. Huatli had wondered if it would feel like coming home, but it felt instead like visiting a distant relative. It was familiar yet alien, a place for her and yet not where she ought to be.
Tishana and Huatli pushed forward along the main thoroughfare, past an endless array of alleyways and side streets. The walls were high, but far ahead they could make out a central building, and Huatli knew in her heart of hearts that she was somehow fated to enter that building.
Out of the corner of her eye, Huatli saw Tishana point skyward.
The sky had turned as dark as river shale, and thick clouds were rising from the main spire of Orazca like smoke from a bonfire. The sight of it filled Huatli with dread. "What is happening?" she asked over the sound of her mount stomping on the pristine gold tiles of the plaza in front of the tower.
The tower ahead seemed to be staining the sky an inky black. Huatli gasped as she saw a body start to fall from the top of the tower.
"NO!" Tishana howled to her right, and Huatli felt an immense wave of magic as Tishana slapped her outstretched hands together in front of her. The body's descent slowed and then stopped altogether as a massive gust of wind rose up to break the fall, and a blanket of dust and leaves settled around the person who had fallen as they slowly came to rest on the ground. Tishana's elemental took off toward the tower, leaving Huatli on the far side of the plaza.
Huatli called out Tishana's name, but her voice was drowned out by the stampede of merfolk who all ran to surround Tishana and the body.
Huatli urged her mount to run forward. Her dinosaur's footsteps pounded a quick rhythm against the gold tile of the ground, slowing as they approached the crowd of worried merfolk. Huatli prepared for the worst. As a warrior, she was no stranger to gore, naturally, and girded herself for a grisly sight, but the body in front was largely unscathed save for a smear of blood under his chin.
Huatli dismounted and approached. Tishana was whispering to the man on the ground as several other merfolk worked a healing spell on him.
"Kumena, we're here. Who is in the tower?"
The merfolk on the ground fluttered his eyes open. His skin was less opaque than it ought to be, and as he lifted his head, a trail of blood flowed from his mouth onto his chest. "Who do you #emph[think] ?" he whispered.
Huatli scowled. The pulse of dark magic above her could only mean that the Legion of Dusk had taken control of the Immortal Sun, and thus, apparently, the city along with it.
Tishana gave a brief order to the merfolk at her side, then she looked back at Huatli.
"We can take them together," she said. "We will resolve ownership of the city from there."
Huatli smiled.
A distant noise caught her attention. In the grim overcast, she could just barely see a motley group racing toward the tower. A siren flew overhead, a familiar woman clinging to an armful of weathered canvas charged below, and in front was a scraggly and mad-looking goblin. The goblin waved a sword longer than himself in the air. He screeched with abandon as he charged. "WE WANT SUN! WE WANT SUN!"
"#emph[Pirates] ," Tishana hissed. The merfolk grabbed Huatli by the shoulder and tugged her up the staircase inside.
"Hurry!" she yelled, and Huatli followed suit.
Her footsteps pattered a steady rhythm as she raced up the tower.
#figure(image("003_The Arbiter of Law Left Chaos in His Wake/01.jpg", width: 100%), caption: [Metzali, Tower of Triumph | Art by <NAME>], supplement: none, numbering: none)
Tishana was close behind. She was clutching the jade totem that contained the elemental she had ridden in on. The staircase felt endless, and every few steps they could see a grim, imposing sky outside through a sliver-like window. Huatli's breath was heavy with exertion, her heart furiously trying to keep pace with her feet. As they climbed higher and higher, she became more and more aware that she might not make it back home alive.
At last, the staircase ended; a massive door at the top of the tower was ajar. The entryway was four times as tall as Huatli, and for a moment she was dumbstruck, mouth agape, at the architectural majesty her ancestors had created.
"VILLAINS!" Tishana bellowed, bounding past Huatli and into the chamber ahead. Huatli watched as she threw the jade totem in first with one hand and began to awaken it with the other.
Huatli snapped back to the present. #emph[Marvel later. Kick the vampires out now] .
She ran through the door and assessed her surroundings.
The room was large and airy. It was, like everything else in this city, plastered with an ungodly amount of fine materials, but in this case built to surround a central piece in the floor. In the center of the room was a disk embedded in the jade of the floor. The disk was about as wide as Huatli was tall, and it glowed a chilly white-blue under the feet of a menacing conquistador. A second vampire (#emph[hierophant] , she briefly remembered) was nearby, holding a staff out in challenge.
"I am Vona, Butcher of Magan, and the Immortal Sun belongs to the Legion of Dusk!" cried the woman in the center of the room. Huatli recognized her as the sweaty vampire from the jungle.
Huatli glanced at what was beneath the vampire's feet and gasped. There it was, inlaid in the glittering gold of the floor, as real as ever; the disk could only be the Immortal Sun.
Huatli gaped at it. "They put it in the #emph[floor] ?!"
Tishana had already chosen her target in the room. Her elemental had grown large once more and barreled into Vona's side as she stood on the Immortal Sun.
Huatli locked eyes with the male hierophant standing near the edge of the Immortal Sun. He lowered his staff and bared his teeth, and Huatli attacked.
She kept her center of gravity low as she cut straight across the room toward him. The vampiric priest clawed his hand in response and dove for her face, but Huatli dropped to her knees and skidded past, clipping his ankle with her blade as she slid on the cold jade of the floor.
The hierophant snarled. Huatli grabbed his cloak and yanked him to the floor, and the #emph[crack ] of his head against the ground was alarmingly loud. Huatli pinned him down with her right hand and held her blade aloft in her left.
"YOU!" called a voice from across the room. Huatli looked up in surprise, and was hit in the chest with a kick from the hierophant beneath her.
Huatli landed on her back with a hard clang from her armor. She winced, then looked up and locked eyes with Vona.
The conquistador smirked and held up a sharp-nailed hand, ready to strike. "I am the Culler of Sinners and Conqueror of Orazca!"
Dark, scentless smoke billowed through the room, and Huatli cried out as a wave of pain wracked her body. She clambered to her feet but fell down again on hands and knees, her muscles quivering and her breath caught in her throat. Huatli looked at her hand and saw that it was purple and brown with what looked like living bruises.
Terror filled her heart. Vona was using the Immortal Sun to manipulate her blood.
Huatli tried to look for Tishana, and saw the merfolk elder pulled to the ground by the hierophant.
"Tishana!" Huatli yelled, but the exclamation was cut off by her own scream as a trickle of blood ran down her lip.
Vona was laughing as she walked to the edge of the Immortal Sun closest to Huatli and knelt.
"What's wrong?" she asked Huatli in a haunting singsong voice. "Are you #emph[uncomfortable] ?"
Suddenly, a song filled the room.
It was a man's voice singing, melodic and soft.
Huatli froze, transfixed. She realized Vona had gone still as well, along with Tishana and the hierophant.
The song was beautiful, enchanting in a way she couldn't place. She had to go to it. She had to be closer to its source. Huatli whipped her head around, stumbling out of Vona's clumsy grasp even as the vampire also began seeking the source of the song.
#figure(image("003_The Arbiter of Law Left Chaos in His Wake/02.jpg", width: 100%), caption: [Siren Reaver | Art by <NAME>], supplement: none, numbering: none)
A figure was hovering just outside the window, flapping azure wings to stay aloft. All the while, he sang a tune more comforting than a lullaby and more precious than a prayer.
Vona, Tishana, and the hierophant were making their way forward, jostling to get closer to the miraculous song. Vona shoved her way to the front, her eyes wide with desire. There, just handspans away from the open window, was a feathered siren, the pirate from the #emph[Belligerent] , and clinging to his neck was a manic-looking goblin.
Somewhere in the back of her mind, Huatli realized what was about to happen. The goblin leaped forward onto Vona's face.
"VIOLENCE!" he yelled.
The song stopped, and the siren cheered. "Go for the eyes, Breeches!"
Huatli snapped out of her stupor and tried to make a run for the Immortal Sun while Vona was screaming.
The goblin was clawing and scratching at the vampire woman's face, laughing all the while.
Just then, the floor shuddered and Huatli heard a loud banging noise. Everyone in the room whipped their heads around to find the source of the clamor.
The golden doors to the room were lying flat on the ground, and standing above them, howling in rage, was Angrath.
#figure(image("003_The Arbiter of Law Left Chaos in His Wake/03.jpg", width: 100%), caption: [Angrath, Minotaur Pirate | Art by <NAME>n], supplement: none, numbering: none)
Huatli recognized the smell of burnt meat just as the minotaur casually tossed her the charred head of the dinosaur she had assigned to stand on top of him. The head hit the ground with a meaty slap.
"You are #emph[AWFUL] !" Huatli screamed at Angrath.
"YOU MADE YOUR DINOSAUR STAND ON TOP OF ME!" he howled back before setting his sights on the conquistador with the goblin on her face.
Angrath aimed his white-hot chains at Vona. The chains wrapped around Breeches, who screeched and swore as he was yanked backward. He immediately regained his footing and charged Angrath.
As Angrath and the goblin scuffled, Huatli looked for Tishana, who had just succeeded in binding the hierophant with some vines growing from a crack in the ceiling.
Tishana looked at Huatli, then looked at the Immortal Sun on the ground and the vampire being dragged off it. Huatli looked at Angrath, who briefly glanced at Tishana and back to the Sun.
They all paused, then moved at the same time in a mad scramble.
All at once, Tishana dove forward and slapped her hand on the Sun, Huatli kicked her foot out to touch its side, Angrath stomped into the center, and Vona slammed both hands down on top of it once more.
The four of them gasped as an immense current of energy passed through them.
Huatli laughed aloud at how wonderful it felt.
#figure(image("003_The Arbiter of Law Left Chaos in His Wake/04.jpg", width: 100%), caption: [Huatli, Radiant Champion | Art by <NAME>], supplement: none, numbering: none)
Her perception spread across the city, her soul spread thin and broad over the magic inlaid in the city of her ancestors. She suddenly knew every path, felt every current of energy, and sensed the boundaries of every building and the reach of every spire. But most wonderful of all, she perceived five immense heartbeats, one at each corner of the city.
#emph[The Elder Dinosaurs have awoken] , Huatli thought, and a tear ran down her cheek. The tale of the Elder Dinosaurs had taken the longest to memorize, an agonizing two years to lock in her mind in its entirety. They were ancient and wild, utterly untamable, the greatest of the dinosaurs. She called Elder Dinosaurs to her, and felt the ground tremble as they began to approach. Huatli's joy overcame her and she continued to laugh . . .
But there, just beyond the city's edge, she felt the footsteps of Emperor Apatzec's army. An army she had not asked for. Huatli's smile fell. She felt stupid. She should have known he wouldn't #emph[just ] send her.
She remembered where her body was, and brought her attention back to the room at the top of the tower.
The Immortal Sun was glowing fiercely below the four of them. Angrath had one foot on the Immortal Sun and one foot on the normal floor, and the magnified heat of his body had caused his other foot to sink through the gold. Tishana's feet were cemented to the Immortal Sun through a series of interwoven vines. Vona was scrambling, calling more dark smoke toward herself. Each of them readied a weapon, and their eyes darted from person to person.
Huatli gripped her blade and slowly stood tall. Her mind was buzzing with the energy of the city and the distant tug of the Elder Dinosaurs. She quietly assessed the threat posed by each foe.
Vona was exhausted and could easily be disposed of. Tishana briefly glanced at her, but Huatli couldn't read her intent. Angrath was seething, as always. The siren and the goblin Breeches stood on the outside, clearly wanting the others to battle it out so they could swoop in like the pirates they were. The hierophant remained secured to the wall with vines.
Huatli crouched to attack. She locked eyes with Tishana across from her and nodded her head slightly toward Vona. Tishana almost imperceptibly returned the nod, and Huatli prepared to pounce.
Suddenly, the siren and goblin both gasped. They looked at each other with wide, confused eyes.
"Malcolm, you heard Jace too?!" Breeches said, looking up at his shipmate.
#emph[Jace? ] Huatli thought, alarmed. #emph[The telepath?]
The siren nodded, afraid.
There was a pregnant pause.
And then the floor gave out beneath them.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
= VRASKA
#figure(image("003_The Arbiter of Law Left Chaos in His Wake/05.jpg", width: 100%), caption: [Azor, the Lawbringer | Art by Ryan Pancoast], supplement: none, numbering: none)
"If this #emph[gorgon ] is not my prisoner, then who have you brought for me to seal?" asked Azor from atop his lofty, self-made throne.
Before knowing Jace, Vraska had thought of sphinxes as little more than riddle-obsessed head cases who wouldn't deign to speak to something as unclean as a gorgon. Now, though, as she kept her fear at bay by trying to locate the source of the pervasive smell of cats in the room (a shabby-looking nest of fabric and straw in the corner, which left no doubt that Azor had been in this room for a very long time), Vraska found herself thinking that the only good sphinx was a sphinx frozen in stone at the entrance to a library.
#emph[We need answers more than we need him dead] , Jace said to Vraska in her mind.
Vraska bristled as she felt the sphinx try to pry his way around Jace's ward, which nevertheless remained firmly in place. Azor lazily turned his gaze to Jace.
"And here stands the Living Guildpact." Azor preened. "I congratulate you on not utterly destroying the system of guilds."
"Thank you," Jace said tersely.
"You're welcome."
Azor spread his wings and settled on all fours. His tail was swinging lazily behind him. Vraska refused to let her guard down.
"If you are not here with a prisoner, then I assume you are here for this," Azor said. "The lock of my prison, my finest creation."
Azor glanced up to the ceiling. Vraska's eyes followed, and the realization clicked.
#figure(image("003_The Arbiter of Law Left Chaos in His Wake/06.jpg", width: 100%), caption: [The Immortal Sun | Art by <NAME>], supplement: none, numbering: none)
It was what kept them there. Not a separate enchantment, not the plane itself.
Vraska's gut dropped. #emph[Why did my employer want me to steal something that locks away planeswalkers?]
"If you are here for the Immortal Sun, I'm afraid you are not allowed to have it." Azor's demeanor shifted, and suddenly a chill ran down Vraska's spine. The sphinx spoke with magic resonating through every syllable. #emph["Trespassing is not allowed within the walls of Orazca."]
The surge of hieromancy circumvented Jace's ward and hit Vraska all at once. A binding of glowing white runic magic grabbed hold of her torso and shoved her back toward the door behind them.
Jace called out Vraska's name in surprise, and almost immediately Vraska felt Jace's magic countering the grip of Azor's hieromancy. Vraska fell to the floor, safe behind an even stronger ward. Free from the sphinx's spell, she shot to her feet, turning toward Azor and snarling.
"Your law magic can't prevent me from turning you to stone, you know!" she yelled, her tendrils flicking wildly in her fury. "Tell us who you are, or I'll kill you where you stand!"
"I will tell you nothing, gorgon."
Jace's eyes immediately flashed cold blue, and he held out his hand. Azor roared and pawed at his head.
"You will refer to her as #emph[Captain] !" Jace asserted.
Azor flapped his wings, and the dust of the room kicked up around them. He held his chest out in irritation, and spoke with the practiced meter of an orator.
"For thousands of years I planeswalked through countless worlds, Captain Vraska. They were strange and unruly, full of brutal societies plagued with violence and disorder. I used hieromancy to give these people the gift of stability; I created systems of governance to cure them of their chaos. I selflessly toiled to improve the Multiverse, and my gifts turned worlds from places of madness and brutality into structured bastions of peace! I founded countless systems of governance to shape the communal destiny of countless planes, and your rejection of my decree is most unwise. #strong[The law is meant to be followed] #emph[.] "
Vraska felt Azor's magic bounce off of and around Jace's ward. He stood defiantly and glowered at the sphinx.
"We know you built the structure of guilds on Ravnica. I'm guessing you weren't from there. Why didn't you stay?" Vraska asked.
#emph["The law is meant to be followed!"]
Jace grimaced. An even stronger wave of Azor's law magic assaulted Jace's defenses with the fierceness of a battering ram.
"Why didn't you stay?!" Vraska demanded again.
Azor roared, giving up on trying to get through Jace's ward. The room went quiet and still.
The sphinx crossed his paws in annoyance. "Because Ravnica was one of many, and I left when I was finished." He flicked his wings, trying another tactic. "You are talented, Living Guildpact. Have you upheld your responsibilities well at home?"
#emph[A diversion] , Vraska thought, opening her mouth to get this confrontation back on track.
"No," Jace said with brutal honesty, ". . . I have not."
Vraska's train of thought vanished. Jace was safe behind his psychic barriers, and yet still entirely vulnerable. His voice betrayed his unease with himself. "Azor, you built an incredibly intricate system with magic more complex than any one person could readily understand, and yet you made your failsafe a #emph[living mortal] . Even if I had a gift for governance, I would not be able to accomplish the task I have been burdened with."
Jace's shoulders fell. Vraska didn't know what to say to his admission. Azor merely puffed his chest.
"The guilds are a perfect system."
"The guilds #emph[were ] a perfect system," Vraska corrected, punctuating each syllable with as much venom as she could and directing it at Azor. "But the guilds have turned malicious and cruel in your absence."
"And whose fault is that?" Azor asked. "I gave Ravnica its guilds just as I gave countless other worlds other perfect systems of law and governance."
This sphinx may have lived a thousand lifetimes longer than her, but he was a fool, a cruel patriarch. Azor was entirely unaware of the consequences of his interference. Vraska's fists were balled at her sides. "I don't think you have the authority to speak of flaws when you manipulated planes that #emph[were not yours ] only to abandon them when you wanted to move on to the next!"
Azor sat up, chin high, claws ever so slightly extended. "If my governments—my #emph[gifts] —soured, the fault lies with the citizens."
"Then what about that?" Vraska added, her finger pointed at the Immortal Sun lodged in the ceiling. "Was Ixalan one of your efforts as well?"
Azor's claws were fully extended.
"What does it #emph[do] ?" Vraska pressed further, ignoring the blossoming realization that she was not quite ready for a physical confrontation with a giant sphinx.
Azor began to step down from his throne. Both Vraska and Jace tensed at his approach.
"As caretaker and arbiter of law for the entirety of the Multiverse, it was my duty to collaborate for the greater good. The Immortal Sun was built to imprison one specific enemy. It amplifies the magical abilities of whoever touches it, and it prevents planeswalkers from leaving a plane. The perfect cage for a diabolical Planeswalker! I gave up my spark to help create the Immortal Sun, the lock of my prison, my greatest gift to all living things."
"What evil were you trying to imprison?" Vraska asked.
"A fiend who was a danger to all the Multiverse. Our plan, naturally, was perfect. But my friend failed#emph[.] "
"#emph[Our] plan? So you made it with someone else?"
Azor growled. "He #emph[was ] my friend. He was #emph[supposed ] to help me get back my spark after our plan worked, which it did #emph[not] —"
"So your #emph[friend] helped make the Immortal Sun and then abandoned you?" Vraska clarified, desperate for more information from the slightly batty and clearly bitter sphinx.
"He was to lure our foe to a faraway plane and I was to use the Immortal Sun to enhance my hieromancy and summon that foe here, to Ixalan. But I never received the signal to activate the Immortal Sun. I do not know my associate's fate," Azor said with a flick of his tail. "We devised the plan over a thousand years ago, and I came to Ixalan a little over a hundred years after that. #emph[He ] failed. I do not know what happened, but #emph[my] execution was perfect—"
Vraska resisted the urge to hurl herself out the nearest window. #emph[He's been cooped up on this plane for a thousand years.]
Azor continued rambling. "I did not want anything to do with the Immortal Sun. It was a reminder of my friend's failure, so I decided to give the gift of governance to this plane. Ixalan was to be ruled by whoever possessed the Immortal Sun, and I initially gifted it to a monastery in the east, in Torrezon. But they were not worthy, so I took it back, and gifted it to others. The Sun Empire was not worthy. The River Heralds, as evidenced by the awakening of Orazca, were not worthy. Only I am worthy, and so I must work further to perfect this system."
Vraska gestured broadly. "By blaming others for problems you caused?!"
"I have been planning! If I am not able to continue to perfect the Multiverse, then I can still do it here—I can fix Ixalan!"
Vraska glared at him. "How can you be so blind to the damage you have caused?!"
The outburst upset the sphinx. Azor tucked his ears back and frowned.
"It is not the system that is faulty, it is the people," he replied coldly.
"The last few centuries on this plane have been chaos because of #emph[your ] intervention," Vraska spat.
"I #emph[fixed ] this plane—"
"This plane was never broken!#emph["] Vraska yelled.
Azor roared, spread his wings, and launched himself toward her.
Jace brought up a shroud of invisibility around himself and Vraska. As they both spun away to dodge the sphinx's charge, Vraska unsheathed her sword and cut a long thin line across Azor's back leg.
The sphinx roared with pain and landed, sweeping wildly around him with his wings. #emph["Reveal yourself!" ] he commanded, and Vraska felt Jace lift their camouflage.
Jace's eyes glowed with power, and Vraska could feel him reach past his own psychic ward and manipulate Azor's mind, sending the feeling of a piercing migraine through the sphinx's head.
Azor gasped.
Jace caught his breath and looked to Vraska. #emph[Are you hurt?]
#emph[No] , she replied, #emph[but I'd love to petrify him before he tries that again.]
#emph[He does not deserve death] , Jace asserted.
Vraska looked at him gravely. #emph[He deserves punishment.]
She stepped forward alongside Jace and stared down the sphinx. "Your life was spent fixing what #emph[you ] saw as problems on other planes, and you meddled with business that #emph[was not yours] ."
"I am the Arbiter of Law—" Azor interrupted.
Jace gripped his fist and Azor groaned in pain.
"Let her talk!" Jace growled.
The sphinx struggled to lift his head, but was too disoriented by Jace's spell.
"The Immortal Sun has spawned hundreds of years of conflict on this plane," Vraska growled, eager to continue. "It led the Legion of Dusk to conquer an entire continent. It caused the Sun Empire and the River Heralds to mercilessly wage war upon one another. #emph[Your ] artifact unbalanced an entire plane, and yet you refuse to be held accountable."
Vraska knelt next to Azor. "The wars of this plane are on your head, and the prison where I suffered needlessly on Ravnica, where #emph[my people were subjugated] , was ultimately of your making."
She leaned closer and hissed, eyes glinting gold, "You deserve punishment. A leader cannot abandon their responsibilities."
". . . Captain," Jace interjected from behind. His voice was gentle and calm.
Vraska looked to him.
Jace's face was unreadable, eyes distant, his mouth a firm line.
"I think I need to do this," he said calmly.
Vraska blinked, uncertain of what he meant. "Do you want to punish him?"
He stared back. Vraska watched a specter of uncertainty, then resolution, pass across his face. He nodded. "It is my responsibility to act on behalf of Ravnica."
Vraska understood.
"Very well," she said, stepping away to watch.
Jace approached, and the roles shifted, as if players on a stage had passed around their scripts. Where once stood a conqueror there was now a convict. An assistant, now a judge. The Living Guildpact stared at the parun of the Azorius and spoke with the wisdom and earnestness of the Jace Vraska knew well.
"The Living Guildpact maintains balance between the guilds of Ravnica. You, Azor, parun of the Azorius, are an inherent part of Ravnica, and have caused imbalance not just on my home, but on countless other planes."
Vraska stood still and listened. Azor was quivering, cowering like a kitten. He could have fought, could have tackled Jace on the spot, but there was deeper magic at work, a powerful level of hieromancy Vraska could not see or understand that kept the sphinx in check. The evocation of status had halted Azor in his tracks, and he listened with wide round eyes to his sentencing. Jace, meanwhile, did not try to tower over Azor. He did not try to physically dominate or intimidate. His posture was calm and measured, his eye contact constant. This was an act of humility, of accepting something he never asked for.
Jace continued, "Not only did you decide it was your place to govern what was not yours, you also never stopped to consider the consequences of your actions. Ixalan is in peril, Ravnica was #emph[built ] to be unstable after you departed, and countless other worlds have likely suffered from your deliberate intervention. Whatever your intentions were, you did not seek to understand the full ramifications of your choices."
Azor sputtered through his pain, "Our intention was to imprison <NAME>—"
Vraska's jaw fell open.
She glanced at Jace, who seemed to be frozen still. His eyes were wide with realization, fingers still in the air before him.
Vraska recognized Jace's expression as the same one from the riverbank. She could see the whites of his eyes and the quiver of his lip.
A brief image flashed in her mind.
#figure(image("003_The Arbiter of Law Left Chaos in His Wake/07.jpg", width: 100%), caption: [Omniscience | Art by <NAME>], supplement: none, numbering: none)
She shivered. #emph[He just remembered <NAME>. He knows him after all.]
"Azor . . . may I see how you know who he is?" Jace asked. From anyone else, the question would have been odd, or misspoken. But this was a telepath's phrasing. Vraska's heart beat furiously in her chest.
The sphinx's lip quivered as he considered Jace's request. "Yes."
Jace closed his eyes and Vraska watched as he gently, delicately poured his senses into Azor's mind. She realized he remembered Alhammarret's teachings, and wondered how it felt to peel open the mind of a sphinx.
Jace glanced at Vraska. His eyes were alight with power, but his brows creased in confusion and terror. She knew that whatever he was seeing was bad news.
"Thank you, Azor," he said. He stood, taking a moment to compose himself and think through whatever evidence he had just seen. After a few seconds, he let out a shuddering sigh.
Jace continued, a crease on his brow and a grimace in his expression. "Your intentions were noble, but the effect of the Immortal Sun on Ixalan has been catastrophic. You and the Immortal Sun are a danger to the stability of this plane."
A strange haze of blue magic shifted across the sphinx's head, vanishing as quickly as it had appeared.
Jace stepped away, the magic in his eyes gone, and spoke with the authority of the Guildpact. Vraska felt a chill run down her neck as he spoke, and realized for the first time just how much power that position carried.
"You will be the master and caretaker of Useless Island. You will not be able to leave, and you will never meddle in the lives of sentient beings ever again. Leave the Immortal Sun here and depart with your life. As Living Guildpact, that is my decree."
The invocation of Ravnican magic around the parun of the Azorius lifted Jace's words, and Vraska felt a strange foreign rush of law magic ringing in his voice.
Azor blinked. Vraska snuffed out the petrification spell she had kept charged throughout their meeting.
Azor spread his wings, which spanned the width of the throne room. He beat them, rose into the air, and flew out the door Vraska and Jace had entered through without another word.
His silhouette vanished above the canopy in the distance, and he was gone.
Vraska looked up at the Immortal Sun, uncertain how she felt about it now.
"Why does <NAME> want an artifact that imprisons Planeswalkers?" she asked in hushed fear.
Jace's lips were a stern line, and he looked at her with dread.
"Vraska," he said, his voice wavering, "you need to know who you're working for."
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/font_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 11-31 unexpected argument: something
// #set text(something: "invalid") |
https://github.com/cadojo/correspondence | https://raw.githubusercontent.com/cadojo/correspondence/main/src/vita/src/projects.typ | typst | MIT License | #let projectslist = state("projectslist", ())
#let project(
name,
url: none,
description: none,
) = {
let banner = if url == none {
name
} else {
link(url, name)
}
let title = [
#heading(level: 3, banner)
#text(style: "italic", description)
]
projectslist.update(current => current + (title,))
}
#let projects(header: "Personal Projects") = {
locate(
loc => {
let projectslist = projectslist.final(loc)
if projectslist.len() > 0 {
heading(level: 2, header)
projectslist.join()
}
}
)
} |
https://github.com/icpmoles/politypst | https://raw.githubusercontent.com/icpmoles/politypst/main/main.typ | typst | #import "template.typ": politesi,raggio,my-styling
#import "@preview/equate:0.2.0": equate
#import "@preview/lovelace:0.3.0": *
#import "@preview/lemmify:0.1.5": *
#let (
theorem, lemma, corollary,
remark, proposition, example,
proof, rules: thm-rules
) = default-theorems(
"thm-group",
lang: "en",
thm-numbering: thm-numbering-heading.with(max-heading-level: 1),
..my-styling
)
#show: thm-rules
#show: doc => politesi(
title: [
Title
],
name: "Name Surname",
ID: "0000000",
course: "Xxxxxxx Engineering - Ingegneria Xxxxxxx",
// abstract_en: abstract_eng,
keyword: [here, the keywords, of your thesis],
parole_chiave: [qui, vanno, le parole chiave, della tesi],
advisor: [NameA SurnameA],
coadvisor: ( [Name1C Surname1C],[Name2C Surname2C]),
academicyear: [20XX-XX],
doc,
)
#heading(numbering: none)[Introduction]
//= Introduction
This document is intended to be both an example of the Polimi Typst template for Master Theses, as well as a short introduction to its use. It is not intended to be a general introduction to Typst itself, and the reader is assumed to be familiar with the basics of creating and compiling Typst documents (see @article @booklet ).
The cover page of the thesis must contain all the relevant information: title of the thesis, name of the Study Programme and School, name of the author, student ID number,
name of the supervisor, name(s) of the co-supervisor(s) (if any), academic year. The above information are provided by filling all the entries in the command \puttitle{} in the title page section of this template.
Be sure to select a title that is meaningful. It should contain important keywords to be identified by indexer. Keep the title as concise as possible and comprehensible even to people who are not experts in your field. The title has to be chosen at the end of your work so that it accurately captures the main subject of the manuscript.
Since a thesis might be a substantial document, it is convenient to break it into chapters. You can create a new chapter as done in this template by simply using the following command
#lorem(1000)
// #context counter(heading).update(0)
#pagebreak()
= Chapter one
In this chapter additional useful information are reported.
== Sections and subsections
Chapters are typically subdivided into sections and subsections, and, optionally, subsubsections, paragraphs and subparagraphs.
All can have a title, but only sections and subsections are numbered.
A new section is created by the command
A new subsection is created by the command
== Equations
This section gives some examples of writing mathematical equations in your thesis.
Maxwell’s equations read:
#equate(sub-numbering: true, $
#place(right,dx:-3em, $lr(size: #8em, \{)$)
nabla dot D &= rho, \
nabla times E + ( partial B) / ( partial t) &= 0, \
nabla dot B &= 0, \
nabla times H - ( partial D)/ ( partial t) &= J.
$)
== Figures, Tables and Algorithms
Figures, Tables and Algorithms have to contain a Caption that describe their content, and have to be properly referred in the text.
=== Figures
#figure(
image("Images/logo_polimi_scritta.svg"),
caption: [Caption of the Figure to appear in the List of Figures.]
)
#figure(
box(height: 200pt,
inset: 9pt,
columns(2, gutter: 11pt)[
#figure(
image("Images/logo_polimi_scritta.svg"),
caption: [Pure Triphase power supply]
)
#figure(
image("Images/logo_polimi_scritta2.svg"),
caption: [Incremental load applied on the rotor shaft]
)]
),
caption: [ This is a very long caption you don’t want to appear in the List of Figures.]
)
=== Tables
//#align(center,text("Title of Table (optional)"))
#figure(
table(
columns: 4,
table.cell(colspan: 4)[Title of Table (optional)],
[], [column 1],[column 2],[column 3],
[row 1],[1], [2], [3],
[row 2],[$alpha$], [$beta$], [$gamma$],
[row 3],[alpha], [beta], [gamma],
),
caption: [Caption of the Table to appear in the List of Tables.],
)
#figure(
table(
columns: 4,
// table.cell(colspan: 4)[Title of Table (optional)],
[], [column 1],[column 2],[column 3],
[row 1],[1], [2], [3],
[row 2],[$alpha$], [$beta$], [$gamma$],
[row 3],[alpha], [beta], [gamma],
),
caption: [Highlighting the columns],
)
#figure(
table(
columns: 4,
// table.cell(colspan: 4)[Title of Table (optional)],
[], [column 1],[column 2],[column 3],
[row 1],[1], [2], [3],
[row 2],[$alpha$], [$beta$], [$gamma$],
[row 3],[alpha], [beta], [gamma],
),
caption: [Highlighting the rows],
)
=== Algorithms
#figure(
kind: "algorithm",
supplement: [Algorithm],
// placement: horizon,
// caption: [Name of the Algorithm],
pseudocode-list(
stroke: none,
booktabs: true,
booktabs-stroke: 1pt + black,
numbered-title: [Name of the Algorithm]
)[
+ Initial instructions
+ *for* _for − condition_ *do*
+ Some instructions
+ *if* _if − condition_ *then*
+ Some other instructions
+ *end if*
+ *end for*
+ *while* _while − condition_ *do*
+ Some further instructions
+ *end while*
+ Final instructions
]
)
== Theorems, propositions and lists
=== Theorems
Theorems have to be formatted as:
#theorem(
)[
Write here your theorem.
]<thm>
#theorem(
name: "Optional name"
)[
Write here your theorem2.
]<thm2>
#proof[
If useful you can report here the proof.
]<proof>
=== Propositions
Propositions have to be formatted as:
#proposition(
// name: "Optional name"
)[
Write here your proposition.
]<thm>
=== Lists
How to insert itemized lists:
- first item;
- second item
How to insert numbered lists:
+ first item;
+ second item;
== Use of copyrighted material
Each student is responsible for obtaining copyright permissions, if necessary, to include
published material in the thesis. This applies typically to third-party material published
by someone else.
== Plagiarism
You have to be sure to respect the rules on Copyright and avoid an involuntary plagia-
rism. It is allowed to take other persons’ ideas only if the author and his original work
are clearly mentioned. As stated in the Code of Ethics and Conduct, Politecnico di Mi-
lano promotes the integrity of research, condemns manipulation and the infringement of intellectual property, and gives opportunity to all those who carry out research activities
to have an adequate training on ethical conduct and integrity while doing research. To be
sure to respect the copyright rules, read the guides on Copyright legislation and citation
styles available at:
```
https://www.biblio.polimi.it/en/tools/courses-and-tutorials
```
You can also attend the courses which are periodically organized on "Bibliographic cita-
tions and bibliography management"
== Bibliography and citations
Your thesis must contain a suitable Bibliography which lists all the sources consulted on
developing the work. The list of references is placed at the end of the manuscript after the
chapter containing the conclusions. We suggest to use the BibTeX package and save the
bibliographic references in the file Thesis_bibliography.bib. This is indeed a database
containing all the information about the references. To cite in your manuscript, use the
command as follows:
Here is how you cite bibliography entries: @knuth92, or multiple ones at once: @lamport94 @book.
The bibliography and list of references are generated automatically by running BibTeX
@knuth74.
#pagebreak(to:"odd")
= Conclusions and future developments
A final chapter containing the main conclusions of your research/study and possible future
developments of your work have to be inserted in this chapter.
#context counter(heading).update(0)
//#bibliography("Thesis_bibliography.bib")
|
|
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/diagram-axes/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 1em)
#import "/src/exports.typ" as fletcher: diagram, node, edge, cetz
#import cetz.draw
#let grid = (
origin: (0, -1),
axes: (ltr, btt),
centers: (
(0cm, 1cm, 2cm, 4cm, 5cm),
(0cm, 1cm, 2cm),
),
cell-sizes: (
(5mm, 10mm, 0mm, 5mm, 5mm),
(5mm, 10mm, 0mm),
),
spacing: (1cm, 1cm),
)
#let pip(coord, fill) = draw.circle(
coord,
radius: 2pt,
stroke: none,
fill: fill,
)
#((ltr, btt), (ltr, ttb), (rtl, ttb), (rtl, btt)).map(axes => {
(axes, axes.rev()).map(axes => [
#let grid = grid + (axes: axes) + fletcher.interpret-axes(axes)
#grid.axes
#cetz.canvas({
fletcher.draw-debug-axes(grid)
pip(fletcher.uv-to-xy(grid, (0,0)), red)
pip(fletcher.uv-to-xy(grid, (1,0)), green)
pip(fletcher.uv-to-xy(grid, (1,.5)), blue)
})
])
}).flatten().join(pagebreak())
|
https://github.com/Starlight0798/typst-nku-lab-template | https://raw.githubusercontent.com/Starlight0798/typst-nku-lab-template/main/README.md | markdown | MIT License | # typst-nku-lab-template
Typst 是可用于出版的可编程标记语言,拥有变量、函数与包管理等现代编程语言的特性,注重于科学写作 (science writing),定位与 LaTeX 相似。
- **语法简洁**:上手难度跟 Markdown 相当,文本源码阅读性高,不会像 LaTeX 一样充斥着反斜杠与花括号。
- **编译速度快**:Typst 使用 Rust 语言编写,即 typ(e+ru)st,目标运行平台是WASM,即浏览器本地离线运行;也可以编译成命令行工具,采用一种增量编译算法和一种有约束的版面缓存方案,文档长度基本不会影响编译速度,且编译速度与常见 Markdown 渲染引擎渲染速度相当。
- **环境搭建简单**:不需要像 LaTeX 一样折腾几个 G 的开发环境,原生支持中日韩等非拉丁语言,无论是官方 Web App 在线编辑,还是使用 VS Code 安装插件本地开发,都是即开即用。
- **现代编程语言**:Typst 是可用于出版的可编程标记语言,拥有变量、函数、包管理与错误检查等现代编程语言的特性,同时也提供了闭包等特性,便于进行函数式编程。以及包括了 [标记模式]、{脚本模式} 与 $数学模式$ 等多种模式的作用域,并且它们可以不限深度地、交互地嵌套。并且通过 [包管理](https://typst-doc-cn.github.io/docs/packages/),你不再需要像 TexLive 一样在本地安装一大堆并不必要的宏包,而是按需自动从云端下载。
Typst中文文档:https://typst-doc-cn.github.io/docs/chinese/
Typst官方文档:https://typst.app/docs/
Typst WebApp:https://typst.app/
------
_这是一份用于NKU实验报告的typst模板,涵盖封面,目录,标题,代码块,公式等内容。_
如果其他学校的同学想要使用这个模板,很简单,只需要把img目录下的两张图片换成自己学校的即可。*
### 使用方法
使用模板方法如下:
1. 创建你的typst文件,比如main.typ
2. 将仓库的img文件夹,template.typ放入main.typ同目录下
3. 在main.typ插入如下代码:
```javascript
#import "template.typ": *
#import XXX // 这里引入你需要使用的其他包(若干),参照demo.typ
#show: project.with(
course: "计算机网络",
lab_name: "TCP/IP实验",
stu_name: "丁真",
stu_num: "114514",
major: "土木工程",
department: "火星土木学院",
date: (2077, 1, 1),
show_content_figure: True // 是否在目录页加上图表的索引
watermark: "NKU", // 水印,不写或写空字符串则无水印
)
```
4. 编写你自己的代码
另外,实验报告可能需要用到不同样式的表格,图片,流程图,代码块等,这些详见`demo.typ.`,里面都有使用示例,基本都是调用各个库来完成效果,避免重复造轮子。
### 编写
建议使用`vscode` + `tinymist`插件 + `typst preview`插件编写,preview插件可以让你编写的过程达到**实时同步**的效果(**编译速度优于Latex**),tinymist插件有诸多使用特性,不多赘述。

#### 示例
*<u>此部分针对不熟悉typst的用户,熟悉者可以跳过。</u>*
比如你想要画像demo.typ里面的这样一个**丰富内容块**:
<img src="assets/image-20240427141309450.png" alt="image-20240427141309450" style="zoom: 80%;" />
那么首先需要在你的main.typ中顶部引入包,具体是哪个包,我在demo中二级标题都有注明:
```js
#import "@preview/colorful-boxes:1.3.1": *
```
然后在你需要放置的部分加入以下代码:
```typescript
#colorbox(title: [这是一段测试标题], color: "blue")[
这是一段测试文字这是一段测试文字这是一段测试文字这是一段测试文字这是一段测试文字
]
```
> 如果你找不到代码,建议使用`typst preview`进行实时预览,这样你直接点击你想要的组件,就会自动跳转到对应的代码。
效果如下,当然color可以自己调:
<img src="assets/image-20240427141525685.png" alt="image-20240427141525685" style="zoom: 80%;" />
其余任何组件同理。
**(注:codly等包我在模板文件已经引入,无需再次引入)**
------
### 效果

|
https://github.com/tingerrr/subpar | https://raw.githubusercontent.com/tingerrr/subpar/main/test/i18n/test.typ | typst | MIT License | // Synopsis:
// - fallback order is region -> language -> english
// - currently there is no way to resolve the styles at the element location like the built in
// auto does
#import "/test/util.typ": *
#import "/src/lib.typ" as subpar
German:
#set text(lang: "de")
#outline(target: figure.where(kind: image))
#figure(fake-image, caption: [Regular]) <normal1>
#subpar.grid(
figure(fake-image, caption: [Inner caption]), <a>,
figure(fake-image, caption: [Inner caption]), <b>,
columns: (1fr, 1fr),
caption: [Super],
label: <full1>,
)
German
- @normal1
- @full1
- @a
- @b
English
- @normal2
- @full2
- @c
- @d
#pagebreak()
English:
#set text(lang: "en")
#outline(target: figure.where(kind: image))
#figure(fake-image, caption: [Regular]) <normal2>
#subpar.grid(
figure(fake-image, caption: [Inner caption]), <c>,
figure(fake-image, caption: [Inner caption]), <d>,
columns: (1fr, 1fr),
caption: [Super],
label: <full2>,
)
German
- @normal1
- @full1
- @a
- @b
English
- @normal2
- @full2
- @c
- @d
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/lift/program.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Program: Lift",
type: "program",
date: datetime(year: 2024, month: 1, day: 16),
author: "<NAME>",
witness: "<NAME>",
)
Now that the lift is built, we can write the code for it. The code is relatively
simple, and uses roughly the same code as the wings. We use our standard state
machine and asynchronous organization.
Here's the header file for the lift, located at
`include/lib/subsystems/hang.hpp`:
```hpp
#pragma once
#include "api.h"
#include "lib/utils/state_machine.hpp"
#include "lib/utils/task-wrapper.hpp"
namespace lib {
enum class HangState { Expanded, Idle }; // The lift can only ever be up or down
class Hang : public StateMachine<HangState>, public TaskWrapper { // Inherit the state machine and task classes
public:
Hang(std::shared_ptr<pros::ADIDigitalOut> piston);
void toggle();
private:
std::shared_ptr<pros::ADIDigitalOut> piston;
void loop() override;
};
} // namespace lib
```
Here's the body file for the lift, located at `src/lib/subsystems/hang.cpp`:
```cpp
#include "lib/subsystems/hang.hpp"
namespace lib {
Hang::Hang(std::shared_ptr<pros::ADIDigitalOut> i_piston) {
piston = i_piston;
};
void Hang::loop() { // The main loop that drives the lift
switch (get_state()) {
case HangState::Expanded:
piston->set_value(true);
break;
case HangState::Idle:
piston->set_value(false);
break;
}
}
void Hang::toggle() {
if (!(get_state() == HangState::Expanded)) {
set_state(HangState::Expanded);
} else {
set_state(HangState::Idle);
}
}
} // namespace lib
```
With this code written we can then very simply control the lift in driver
control. We simply call the lift's `toggle()` method, and the lift will switch
states.
```cpp
// Hang control
if (controller.get_digital_new_press(pros::E_CONTROLLER_DIGITAL_B)) { // Bind the hang toggle to the "B" button
controller.rumble("."); // Provide the driver with haptic feedback
hang.toggle();
}
```
With these changes, our new controller layout looks like this:
#image("./control-layout.svg")
We decided not to put the lift on a trigger because the driver will need to use
it much less than any of the other functions.
|
https://github.com/skomaroh1845/TheoreticalInformaticsMIPT | https://raw.githubusercontent.com/skomaroh1845/TheoreticalInformaticsMIPT/main/HW3.typ | typst | = <NAME> ДЗ №3
#set par(
justify: true,
)
= Задача 1
Докажите, что из L, M $in$ P следуют #overline[L], L $sect$ M, L $union$ M $in$ P (здесь #overline[L] $ = Sigma^* without$ L), а также L · M $in$ P, где L · M = {uv | u $in$ L, v $in$ M} есть множество всевозможных конкатенаций двух слов из L и M соответственно.
== Доказательство
=== 1. #overline[L] $in$ P
$square$ Если $L in P$, значит существует 0-1 poly м.т. $K$: $cases(
K(arrow(x)) = 1 \, arrow(x) in L,
K(arrow(x)) = 0 \, arrow(x) in.not L
)$
Значит, так же можно построить такую poly м.т. $K'$, которая будет выдавать противополоные $K$ результаты (можно взять машину $K$ и добавить к ней операцию инвертирования ответа, сложность которой $O(1)$, значит сама машина останется poly).
Тогда имеем $K'$: $cases(
K'(arrow(x)) = 0 \, arrow(x) in L arrow.l.r.double.long arrow(x) in.not overline(L),
K'(arrow(x)) = 1 \, arrow(x) in.not L arrow.l.r.double.long arrow(x) in overline(L)
)$ $arrow.r.double$ $cases(
K'(arrow(x)) = 1 \, arrow(x) in overline(L),
K'(arrow(x)) = 0 \, arrow(x) in.not overline(L)
)$
Таким образом имеем полиномиальную м.т. $K'$, распознающую язык $overline(L)$, значит $overline(L) in P$.
#align(right, $square.filled$)
=== 2. L $sect$ M $in$ P
$square$ Если $L, M in P$, значит существует 0-1 poly м.т. $K$: $cases(
K(arrow(x)) = 1 \, arrow(x) in L,
K(arrow(x)) = 0 \, arrow(x) in.not L
)$
и $Y$: $cases(
Y(arrow(x)) = 1 \, arrow(x) in M,
Y(arrow(x)) = 0 \, arrow(x) in.not M
)$
Соответственно, если слово $arrow(y) in L sect M$, то оно может быть распознано любой из приведенных машин, работающих за полиномиальное время, то есть существует poly м.т. (например $K$), распознающая все слова из $L sect M$ за полином $arrow.r.double$ $L sect M in P$.
#align(right, $square.filled$)
=== 3. L $union$ M $in$ P
$square$ Если $L, M in P$, значит существует 0-1 poly м.т. $K$: $cases(
K(arrow(x)) = 1 \, arrow(x) in L,
K(arrow(x)) = 0 \, arrow(x) in.not L
)$
и $Y$: $cases(
Y(arrow(x)) = 1 \, arrow(x) in M,
Y(arrow(x)) = 0 \, arrow(x) in.not M
)$
Соответственно, для распознания слова $arrow(y) in L union M$, можно сконструировать машину $Z$, которая будем представлять собой последовательно соединенные машины $K$ и $Y$ через логическое сложение: сначала отрабатывает программа машины $K$, записывает результат в выходную ленту, если результат 1, то завершаемся, если 0, то затем отрабатывает программа машины $Y$, и прибавляет свой результат к уже записанному результату алгоритма $K$, обе машины работают за полином, операция прибавления однобитовых чисел в данном случае $O(1)$, так как есть всего два варианта 0 + 0 и 0 + 1, для обоих нужно одно элементарное действие, получаем, что итоговая сложность составной машины $Z$ тоже полином.
Таким образом, построили 0-1 poly м.т. $Z$: $cases(
Z(arrow(x)) = 1 \, arrow(x) in L union M,
Z(arrow(x)) = 0 \, arrow(x) in.not L union M
)$
$arrow.r.double$ $L union M in P$
#align(right, $square.filled$)
=== 4. L · M $in$ P, где L · M = {uv | u $in$ L, v $in$ M}
$square$ Если $L, M in P$, значит существует 0-1 poly м.т. $K$: $cases(
K(arrow(x)) = 1 \, arrow(x) in L,
K(arrow(x)) = 0 \, arrow(x) in.not L
)$
и $Y$: $cases(
Y(arrow(x)) = 1 \, arrow(x) in M,
Y(arrow(x)) = 0 \, arrow(x) in.not M
)$
Для распознавания конкатенации слов из $L$ и $M$ можно воспользоваться следующим алгоритмом: мы знаем, что первая часть слова у нас из $L$, но не знаем какой длины, тогда мы можем сделать следующее - идти по слову и на каждом шаге запускать алгоритм машины $Y$, распознающий слово из $M$, если не распозналось, то сдвигаем головку вперед и повторяем, если слово распозналось, значит мы нашли "стык" двух слов, далее можно заменить уже распознанную часть слова на $\#$ и запустить алгоритм машины $K$, по результату распознавания последнего уже можно судить о нахождении слова в $L dot M$. Условие выхода при неудачном распозновании следующее, если в ходе прохода алгоритмом $Y$ по слову мы дошли до конца, так ничего и не распознав, значит нет суффикса слова $in M$, значит слово точно $in.not L dot M$.
В описанном алгоритме мы в худшем случае запускаем poly алгоритм машины $Y$ n раз, где n -- длина входа, таким образом увеличиваем стпень полинома на 1, но он все еще полином, далее, в случае упеха алгоритма $Y$, отработает еще poly аглоритм $K$, итого в конечном счете имеем все еще полином.
Таком образом, мы описали 0-1 м.т. распознающую слова из $L dot M$ за полиномиальное время, значит $L dot M in P$.
#align(right, $square.filled$)
= Задача 2
Докажите, что задача распознавания наличия треугольника (т. е. подграфа, изоморфного $K_3$) в
графе лежит в P. Граф задан матрицей смежности.
== Доказательство
$square$
Обозначим матрицу смежности за $A$. Тогда чтобы понять есть ли треугольник (цикл длины 3) в графе, достаточно посмотреть на след матрицы $A^3$. Перемножение матриц занимает полиномиальное время (например, наивный алгоритм - $O(n^3)$), умножение нужно выполнить 2 раза, подсчет следа итоговой матрицы - $O(n)$, итого получаем, что общая сложность алгоритма проверки наличия треугольника - $O(n^3)$.
По тезису Чёрча-Тьюринга описанный выше алгоритм может быть выполнен на м.т. не более чем с полиномиальным замедлением относительно сложности программы $O(n^3)$ в РЯП. Полином от $n^3$ тоже полином $arrow.r.double$ значит существует работающая за полином м.т. $M$, распознающая наличие треугольника в графе $arrow.r.double$ задача $in P$.
#align(right, $square.filled$)
|
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%2018_745%20-%20Lie%20Groups%20and%20Lie%20Algebras/Assignments/Assignment%202.typ | typst | #import "/Templates/generic.typ": latex, header
#import "@preview/ctheorems:1.1.0": *
#import "/Templates/math.typ": *
#import "/Templates/assignment.typ": *
#show: doc => header(title: "Assignment 2", name: "<NAME>", doc)
#let lecture = counter("lecture")
#lecture.step()
#let update_lecture = () => {
lecture.step()
counter(heading).update(0)
}
#let bonus_problem = {
pagebreak()
block(text([*Bonus Exercise*], size: 17pt))
}
#show: latex
#let NumberingAfter(doc) = {
let level = 1
set heading(
numbering: (..numbers) => if numbers.pos().len() <= level {
return context numbering(
"1.1",
lecture.get().first(),
..numbers,
)
},
supplement: "Exercise",
)
show heading: it => {
if (it.numbering == none) {
return it
}
if (it.level > 1) {
return text(it, size: 14pt)
}
let numbers = counter(heading).at(it.location())
let display-number = numbering(it.numbering, ..numbers)
let body = it.body
// if (numbers.last() > 1) {
pagebreak(weak: true)
// }
block(text([*#body #display-number*], size: 17pt))
}
doc
};
#show: thmrules
#let col(x, clr) = text(fill: clr)[$#x$]
#let bar(el) = $overline(#el)$
#show: NumberingAfter
#set enum(numbering: "(a)")
*Sources consulted* \
Classmates: <NAME>. \
Texts: Class Notes.
#update_lecture()
#update_lecture()
#update_lecture()
= Exercise
== Statement
Show that the Lie algebras $(B_d)_- = frak(b)_d$ and $(N_d)_- = frak(n)_d$ satisfy $frak(n)_d = [frak(b)_d, frak(b)_d]$.
== Solution
Let $X,Y$ be two matrices in $frak(b)_d$, then we know by definition that $X$ and $Y$ preserve a flag $0 = V_0 subset V_1 subset ... subset V_n$. Now fix a $j >= 1$ and note that since both $X$ and $Y$ preserve $V_j$ and $V_(j-1)$ then we can quotient their actions as $X,Y : V_j quo V_(j-1) -> V_j quo V_(j-1)$. But this is a one dimensional vector space so both $X$ and $Y$ act as scalers so we have $[X,Y] : V_j quo V_(j-1) -> V_j quo V_(j-1)$ is in fact the zero map.
We can now unwind this fact to get that $[X,Y](V_j) seq V_(j-1)$ which shows that $[X,Y] in frak(n)_d$ for all $X,Y in frak(b)_d$.
On the other hand $frak(n)_d$ is spanned by matrices $a^((i j))$ for $i < j$ where $(a^((i j)))_(k ell) = delta_(i k) delta_(j ell)$. But we have
$
[a^((i i)), a^((i j))]
= a^((i i)) a^((i j)) - a^((i j)) a^((i i))
= a^((i j)).
$
and clearly both $a^((i i))$ and $a^((i j))$ are upper triangular so they are in $frak(b)_d$, thus $frak(n)_d$ is spanned by elements $[X,Y]$ for $[X,Y] in frak(b)_d$.
= Exercise
== Statement
Show that $frak(b)_d$ is a solvable Lie algebra and that $frak(n)_d$ is a nilpotent Lie algebra.
== Solution
Let $X in frak(n)_d^(d)$, clearly by definition $X$ is a sum of matrix products each involving $d$ matrices in $frak(n)_d$, and thus all satisfy $A V_n seq V_0$ and thus are all zero. Hence $X = 0$ and so $frak(n)_d^d$ is nilpotent.
Now since it is nilpotent it is also solvable, but we know that $[frak(b)_d, frak(b)_d] = frak(n)_d$ so $frak(b)_d$ is clearly also solvable.
= Exercise
== Statement
Let $frak(g)$ be a Lie algebra and $frak(h)$ be its ideal. Prove that if $frak(h)$ and $frak(g) quo frak(h)$ are solvable Lie algebras, then $frak(g)$ is solvable too.
== Solution
Let $n$ be such that $(frak(g) quo frak(h))^((n)) = 0 seq frak(g) quo frak(h)$. Then we have by definition of the quotient $frak(g)^((n)) seq frak(h)$. But then since $frak(h)$ is also solvable we have $frak(h)^((m)) = 0$ so we get $frak(g)^((n + m)) = 0$ and hence $frak(g)$ is solvable.
= Exercise
== Statement
#let heis = math.op("heis")
Prove that any 2-step finite dimensional nilpotent Lie algebra with $1$-dimensional center is isomorphic to $heis_(2 n + 1)$ for some integer $n >= 1$.
== Solution
Let $frak(g)$ be the Lie algebra and let $H$ be a generator for its center. Since $frak(g) quo span(H)$ is abelian we know that $[a,b] in span(H)$ for all $a,b in frak(g)$, we also know that for each $a in frak(g) backslash span(H)$ there exists some $b in frak(g)$ so that $[a,b] != 0$, otherwise it would be in the center.
We now perform the following procedure, pick an arbitrary element $a$ not in the center of $frak(g)$, and then pick an element $b$ such that $[a,b] != 0$. Then consider $W := ker ad a sect ker ad b$, this is an $n - 2$ dimensional subspace because it does not contain $span(a,b)$. We now assume by induction that $W$ is isomorphic to $heis_(2 m + 1)$ for some $m >= 1$, then we have
$
[a, e_i] = [a, f_i] = [a,H] = [b, e_i] = [b, f_i] = [b, H] = 0
$
where $e_i, f_i, H$ is the standard basis on $heis_(2 m + 1)$. Thus adding $a,b$ to that basis we get all the relations of $heis_(2 m + 3)$ and thus $frak(g)$ is isomorphic to that.
= Exercise
== Statement
Prove that $frak(g)_B$ is a Lie algebra and that $frak(g)_B tilde.equiv frak(g)_(B_1)$ if and only if $B tilde.equiv B_1$ are isomorphic bilinear forms.
== Solution
Let $f$ be an isomorphism $f : frak(g)_B -> frak(g)_(B_1)$, $f$ must fix the center since its preserves the bracket, so since $frak(g)_B = V_B plus.circle Z$ and $frak(g)_(B_1) = V_(B_1) plus.circle Z$ thus can write $f : V_B -> V_(B_1)$. Now we have
$
B(f(a),f(b))
= [f(a),f(b)]_(frak(g)_B) #h(-5pt)
= [a,b]_(frak(g)_(B_1)) #h(-5pt)
= B_1(a,b),
$
so $f$ becomes an isomorphism of bilinear forms. An identical argument shows that an isomorphism of bilinear forms becomes an isomorphism of Lie algebras.
#update_lecture()
= Exercise
== Statement
Show that Lie's lemma holds if $char F > dim V$.
== Solution
We repeat the proof as is until we reach $tr_(W_n)(pi([h,a])) = tr_(W_n) [pi(h),pi(a)] = N lambda ([h,a])$. From there we note that $N <= dim V$ because $W_n$ is a subspace of $dim V$. Thus $N <= char F$ and thus cannot be zero. We thus reach the same conclusion, namely that $lambda ([h,a]) = 0$. From there the proof continues as is and so we get the same result.
= Exercise
== Statement
Consider the following representation of $heis_3 = {p,q,c}$ on $FF[x]$,
$
c dot f(x) = f(x), quad p dot f(x) = d / (d x) f(x), quad q dot f(x) = x f(x)
$
Show that $x^p FF[x]$ is an invariant subspace for $heis_3$ if $char FF = p$, and that $heis_3$ has no weight in $V = FF[x] quo x^p FF[x]$.
Explain why this example shows that Lie's lemma fails over fields of characteristic $p$.
== Solution
Let $f(x) in x^p FF[x]$, then we have $f(x) = x^p dot g(x)$ for some polynomial $g(x)$. We then have
$
c dot f(x) = f(x) in x^p FF[x], \
p dot f(x) = d / (d x) x^p g(x)
= p x^(p-1) g(x) + x^p (d / (d x) g(x)) = x^p d / (d x) g(x) in x^p FF[x], \
q dot f(x) = x^(p+1) g(x) = x^p (x g(x)) in x^p FF[x].
$
and so the subspace $x^p FF[x]$ is preserved.
Now consider the representation of $heis_3$ on $FF[x] quo x^p FF[x]$, assume that it has a weight $lambda : heis_3 -> FF$ and let $f(x)$ be an element with that weight, then we have
$
d / (d x) f(x) = p dot f(x) = lambda(p) f(x)
$
so $f(x)$ is an eigenvalue of the derivative. But in polynomials there is only one such eigenvalue, namely the eigenvalue $0$ over the constant polynomials.
Thus we must have $V_lambda^(heis_3) = span(1)$. But now $1$ is not an eigenvalue of $q$ because $q dot 1 = x$, this contradicts the assumption that this representation had a weight.
Now consider the ideal $frak(h) = span(c, p)$ in $heis_3$, as we saw before we have a weight $lambda(c) = 1, lambda(p) = 0$ with $V_lambda^(frak(h)) = span(1)$. As this span is not invariant under $frak(g)$ this would contradict Lie's lemma if its condition's applied.
= Exercise
== Statement
Prove the following two corollaries of Lie's Theorem.
+ For any representation $pi$ of a solvable Lie algebra $frak(g)$ in a finite-dimensional vector space $V$ over an algebraically closed field of characteristic $0$ there exists a basis of $V$ for which the matrices of $pi(frak(g))$ are upper triangular.
+ Under the same assumption on $V$ and $FF$, a subalgebra of $gl_V$ is solvable iff it is contained in a subalgebra of upper triangular matrices for some basis of $V$.
== Solution
+ We induct on the dimension of $V$. Assume this is true for all dimensions $< n$ and that $V$ is of dimension $n$. By Lie's Theorem there exists a weight $lambda$ such that $V_lambda^(frak(g)) != 0$, so this subspace is invariant under $pi(frak(g))$ and thus we can consider the representation of $frak(g)$ on $V quo V_lambda^(frak(g))$. By inductive hypothesis we know that there is a basis $e_1,...,e_k$ of $V quo V_lambda^(frak(g))$ for which $tilde(pi)(g)$ is upper triangular and we know that $pi(g)$ is diagonal on $V_lambda^(frak(g))$. So for any basis we pick of $V_lambda^(frak(g))$ we get
$
pi(X) = mat(lambda(X) I, *; 0, tilde(pi)(X))
$
which is upper triangular, which finishes the proof.
+ Assume that a subalgebra $frak(g) seq gl_V$ is solvable, then it has a canonical representation on $V$, by the previous result we know that in some basis that representation consists solely of upper triangular matrices and thus $frak(g)$ is contained within the algebra of upper triangular matrices in some basis. On the other hand assume that it is contained within the algebra of upper triangular matrices, then we know that $frak(g)^((n)) seq frak(b)_d^((d)) = 0$ so $frak(g)$ is solvable.
= Exercise
== Statement
Prove that $[frak(g), frak(g)]$ is a nilpotent Lie algebra if $[frak(g) quo Z(frak(g)), frak(g) quo Z(frak(g))]$ is.
== Solution
First note that $[frak(g) quo Z(frak(g)), frak(g) quo Z(frak(g))] = [frak(g), frak(g)] quo Z(frak(g))$, one can check this very easily. Assume then, that $[frak(g) quo Z(frak(g)), frak(g) quo Z(frak(g))]$ is nilpotent, then for some $n$ we have
$
[x_1, [x_2,[x_3,...[x_(n-1),x_n]...]]] = 0
$
for all $x_i in [ frak(g) quo Z(frak(g)), frak(g) quo Z(frak(g)) ]$. We then must have for any $x_i in [frak(g), frak(g)] quo Z(frak(g))$, that the same equation holds. But since elements in the center will vanish after being put in a bracket then we have for $x_i in [frak(g), frak(g)]$ we have
$
[x_1, [x_2,[x_3,...[x_(n-1),x_n]...]]] = c
$
for some $c in Z(frak(g))$. In other words, we have $[frak(g), frak(g)]^(n) seq Z(frak(g))$ so then
$
[[frak(g), frak(g)], [frak(g), frak(g)]^n]
= [[frak(g), frak(g)], Z(frak(g))] = 0.
$
|
|
https://github.com/hemmrich/CV_typst | https://raw.githubusercontent.com/hemmrich/CV_typst/master/template/styles.typ | typst | #let hBar() = [#h(5pt) | #h(5pt)]
#let latinFontList = (
"Source Sans Pro",
"Source Sans 3",
"Linux Libertine",
"Font Awesome 6 Brands",
"Font Awesome 6 Free",
)
#let latinHeaderFont = ("Roboto")
#let awesomeColors = (
skyblue: rgb("#0395DE"),
red: rgb("#DC3522"),
nephritis: rgb("#27AE60"),
concrete: rgb("#95A5A6"),
darknight: rgb("#131A28"),
)
#let regularColors = (
subtlegray: rgb("#ededee"),
lightgray: rgb("#343a40"),
darkgray: rgb("#212529"),
)
/// Set the accent color for the document
#let setAccentColor(awesomeColors, metadata) = {
let param = metadata.layout.awesome_color
return if param in awesomeColors {
awesomeColors.at(param)
} else {
rgb(param)
}
}
/// Overwrite the default fonts if the metadata has custom font values
///
/// - metadata (array): the metadata object
/// - latinFontList (array): the default list of latin fonts
/// - latinHeaderFont (string): the default header font
/// -> array
#let overwriteFonts(metadata, latinFontList, latinHeaderFont) = {
let metadataFonts = metadata.layout.at("fonts", default: [])
let regularFonts = latinFontList
let headerFont = latinHeaderFont
if metadataFonts.len() > 0 {
regularFonts = metadataFonts.at("regular_fonts")
headerFont = metadataFonts.at("header_font")
}
return (regularFonts: regularFonts, headerFont: headerFont)
} |
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/minea/0_vseob/00_all.typ | typst | #import "/styleMinea.typ": *
#import "/CSL/texts.typ": *
= #translation.at("MINEA_OBS")
#import "./01_Bohorodicka.typ" as m01: *
#import "./02_ProrokJeden.typ" as m02: *
#import "./03_ApostolJeden.typ" as m03: *
#minea("M_BOHORODICKA",
m01.V, h_st,
m01.U,
id => translation.at(id))
#colbreak(weak: true)
#minea("M_PROROK_JEDEN",
m02.V, h_st,
none,
id => translation.at(id))
#colbreak(weak: true)
#minea("M_APOSTOL_JEDEN",
m03.V, h_st,
none,
id => translation.at(id))
#colbreak(weak: true) |
|
https://github.com/Toniolo-Marco/git-for-dummies | https://raw.githubusercontent.com/Toniolo-Marco/git-for-dummies/main/slides/practice/configuration.typ | typst | #import "@preview/touying:0.5.2": *
#import themes.university: *
#import "@preview/numbly:0.1.0": numbly
#import "@preview/fletcher:0.5.1" as fletcher: node, edge
#let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide)
#import fletcher: shapes
#import "../components/gh-button.typ": gh_button
#import "../components/git-graph.typ": branch_indicator, commit_node, connect_nodes, branch
#align(center,
grid(rows:2,
[
```bash
➜ git config --global user.name "name"
➜ git config --global user.email "your@email"
```
],[
#scale(95%)[
#set text(11pt)
// Inline Code Rule
#show raw.where(block: false): it => box(
fill: none,
inset: 0pt,
baseline: 0%,
radius:2pt,
it
)
#fletcher-diagram(
node([#grid(rows:3,columns:2, column-gutter: 30pt, row-gutter: 10pt, align: horizon,
grid.cell( colspan: 2, align: center,
text(weight: "bold", size: 15pt)[System Level]
),
grid.cell( align: center,
text(weight: "bold")[Base]
),
grid.cell( align: center,
text(weight: "bold")[View]
),
grid.cell( align: center,
[`git config --system`]
),
grid.cell( align: center,
[`git config --system --list`]
)
)], stroke: 1pt+teal, fill: teal, shape: shapes.trapezium.with(dir:bottom), width: 125mm, height: 30mm),
edge("..>"),
node((1,0), [Operating System]),
node((0,0.8),[#grid(rows:3,columns:2, column-gutter: 30pt, row-gutter: 10pt, align: horizon,
grid.cell( colspan: 2, align: center,
text(weight: "bold", size: 15pt)[Global Level]
),
grid.cell( align: center,
text(weight: "bold")[Base]
),
grid.cell( align: center,
text(weight: "bold")[View]
),
grid.cell( align: center,
[`git config --global`]
),
grid.cell( align: center,
[`git config --global --list`]
)
)], stroke: 1pt+yellow, fill:yellow, shape: shapes.trapezium.with(dir:bottom), width: 112mm, height: 30mm),
edge("..>"),
node((1,0.8), [User Specific]),
node((0,1.71), [#grid(rows:5,columns:2, column-gutter: 15pt, row-gutter: 12pt, align: horizon,
grid.cell( colspan: 2, align: center,
text(weight: "bold", size: 15pt)[Local Level]
),
grid.cell( align: center,
text(weight: "bold")[Base]
),
grid.cell( align: center,
text(weight: "bold")[View]
),
grid.cell( align: center,
[`git config --local`]
),
grid.cell( align: center,
[`git config --local --list`]
),
grid.cell( colspan: 2, align: center,
text(weight: "bold")[Stored]
),
grid.cell( colspan: 2, align: center,
[`.git/config`]
)
)], shape: shapes.trapezium.with(dir:bottom), stroke: 1pt+orange, fill:orange,width: 98mm, height: 40mm),
edge("..>"),
node((1,1.71), [Repository Specific]),
)
]
])
)
---
#set align(center)
`gh` is the tool we will use to interact from CLI with GitHub, to configure our account we use:
```bash
➜ gh auth login
? What account do you want to log into? GitHub.com
? What is your preferred protocol for Git operations on this host? SSH
? Generate a new SSH key to add to your GitHub account? Yes
? Enter a passphrase for your new SSH key (Optional):
? Title for your SSH key: GitHub CLI
? How would you like to authenticate GitHub CLI? Login with a web browser
! First copy your one-time code: A111-B222
Press Enter to open github.com in your browser...
✓ Authentication complete.
- gh config set -h github.com git_protocol ssh
✓ Configured git protocol
✓ Uploaded the SSH key to your GitHub account: /home/path/to/.ssh/key.pub
✓ Logged in as GitHub-Username
``` |
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/1_templates/Hlas1-2.typ | typst | #include("/covers/oktoich/H12_CSL.typ")
#show outline.entry.where(level: 1): it => {
v(12pt, weak: true)
text(18pt, strong(it))
}
#show outline.entry.where(level: 2): it => {
text(13pt, strong(it))
}
#outline(title: "Ohlavlénije", depth: 3, indent: 2em)
#pagebreak()
#include("../0_all/1hlas.typ")
#pagebreak()
#include("../0_all/2hlas.typ")
#set page(
footer: text(8pt, "Errata"),
footer-descent: 75%
)
#pagebreak()
#pagebreak()
#pagebreak()
#pagebreak() |
|
https://github.com/joalopez1206/CV | https://raw.githubusercontent.com/joalopez1206/CV/main/starter.typ | typst | #import "@preview/guided-resume-starter-cgc:2.0.0": *
#set text(lang: "spa")
#show: resume.with(
author: "<NAME>",
location: "Santiago, Chile",
contacts: (
[#link("mailto:<EMAIL>")[Email]],
[#link("https://users.dcc.uchile.cl/~jlopez/")[Website]],
[#link("https://github.com/joalopez1206")[Github]],
[#link("https://www.linkedin.com/in/jlopez0612")[Linkedin]],
),
// footer: [#align(center)[#emph[References available on request]]]
)
= Sobre mi
Desarrollador de software y estudiante de Ingeniería Civil en Computación en la Universidad de Chile. Tengo experiencia en Python y en el uso de librerías para procesamiento de datos como numpy, matplotlib y pandas.
Además, manejo varios lenguajes de sistemas y frameworks backend para desarrollo web, complementando con habilidades en frontend. También tengo conocimientos en bases de datos SQL y NoSQL, así como en procesamiento masivo de datos y grafos para la web.
Me interesan tanto el desarrollo de sistemas de software en sistemas embebidos, topicos sobre datos semánticos de web y lingüística.
= Educacion
#edu(
institution: "Universidad de Chile",
date: "2024",
location: "Santiago, Chile",
degrees: (
("Lic.", "Ciencias de la ingenieria mencion computación"),
("Titulo Profesional","Ingeniería Civil en Computación (Cursando actualmente)")
),
)
= Habilidades tecnicas
#skills((
("Lenguajes nivel Alto", (
[C],
[Python],
[C\#],
[bash],
[Rust],
[SQL]
)),
("Lenguajes nivel medio",(
[Javascript],
[Java],
)),
("Frameworks y librerias manejadas", (
[Flask, Django (backend)],
[Bootstrap, vue (frontend)],
[Pandas, numpy, matplotlib (Procesamiento de datos)],
[Hadoop, spark (Procesamiento Masivo de datos)]
)),
("Sistemas embebidos",(
[Arduino-IDE],
[esp-idf]
)),
("Bases de datos",(
[PostgreSQL],
[MySQL],
[Neo4J],
))
))
= Experiencia
#exp(
role: "Desarrollador de Software",
project: "Niclabs",
date: "Sep 2024 - act",
location: "Santiago",
summary: "Desarrollo de software para libreria de DNS",
details: [
- Implementacion autentificacion de llave compartida TSIG
- Implementacion de extensiones de seguridad DNSSEC
]
)
#exp(
role: "Practica Desarrollador de Software",
project: "CCHEN",
date: "Ene 2024 - Mar 2024",
location: "Santiago ",
summary: "Desarrollo de un sistema de control de camaras para plasma",
details: [
- Implementar un sistema de control de camaras para toma de fotos en simultaneo
- Configuracion de camaras en tiempo real
- Red via ethernet para transferencia de datos
]
)
#exp(
role: "Practica Desarrollador de Software",
project: "SPEL",
date: "Jan 2023 - Oct 2023",
location: "Santiago ",
summary: "Desarrollo de software para Cubesats",
details: [
- Identificar problemas de compatibilidad de librerías
- Cambio de librerías para mejorar rendimiento en términos de comunicación
- Implementar un HAL simple para un giroscopio conectado vía $I^2C$
]
)
#v(20mm)
#exp(
role: "Profesor auxiliar/ayudante",
project: "University de Chile, FCFM",
date: "2022-2024",
summary: "Profesor ayudante para varios cursos dictados",
details: [
- Introducción al cálculo
- Introducción al álgebra
- Matemáticas discretas para ciencias de la computación
- Programación de software de sistemas
- Teoría de la computación
]
)
= Projects
#exp(
role: "Memoria de titulo",
project: "Extraccion de red semantica de diccionarios",
date: "Jun 2024 - act",
summary: "Generacion y extraccion de una red semantica",
details: [
- Scraping de pdf's con OCR tesseract
- Generacion de la red a partir de los datos extraidos
- Implementacion de una aplicacion simple que permite visualizar la red usando Neo4J y visjs
- Estudio de la red, su topologia y propiedades
]
)
= Idiomas
- Ingles (Nivel C1)
- Español (Nativo)
|
|
https://github.com/zurgl/typst-resume | https://raw.githubusercontent.com/zurgl/typst-resume/main/resume/fr/skills.typ | typst | #import "../../templates/resume/section.typ": cvSection
#import "../../templates/resume/skills.typ": cvSkill, hBar
#import "@preview/fontawesome:0.1.0": *
#v(10pt)
#cvSection("Compétences")
#cvSkill(
type: [Langues],
info: [Anglais #hBar() Français]
)
#cvSkill(
type: [Tech Stack],
info: [Rust #hBar() Typescript #hBar() PostgreSQL #hBar() Docker #hBar() React #hBar() HTML/CSS #hBar() Linux]
)
#cvSkill(
type: [Centres d'intérêt],
info: [Natation #hBar() Cyclisme #hBar() Cuisine]
)
|
|
https://github.com/alexonea/cv | https://raw.githubusercontent.com/alexonea/cv/master/lib/cv.typ | typst | #let indentblock(doc) = block(
inset: (left: 1.5em),
spacing: 1.7em,
breakable: false,
doc
)
#let setup(
name: none,
headline: none,
address: none,
phone: none,
email: none,
debug: false,
doc,
) = {
let linebr() = {
v(-0.8em)
line(length: 100%, stroke: 0.5pt)
}
set page(
paper: "a4",
numbering: "1 / 1",
margin: 1.5cm,
)
set par(justify: true)
set text(
font: "Linux Libertine",
size: 10pt,
)
let debug_stroke = 0pt
if debug == true {
debug_stroke = .5pt
}
set block(stroke: debug_stroke + green)
set box(stroke: debug_stroke + red)
show heading: set text(font: "New Computer Modern")
show heading.where(level: 1): it => text(
size: 11pt,
[
#v(1em)
#upper(it)
#linebr()
#v(.5em)
]
)
show heading.where(level: 2): set text(size: 10pt)
/* title */
set align(center)
block(text(28pt, weight: "regular", smallcaps(name)))
v(1em)
/* headline, address, phone, email */
block(text(9pt, weight: "thin", headline))
block(text(9pt, weight: "thin", [
#address \
#link("tel:" + phone, raw(phone)) · #link("mailto:" + email, raw(email))
]))
v(1.5em)
/* rest of the document */
set align(left)
set text(
size: 10pt,
lang: "en",
)
doc
}
#let jobrole(
company: none,
role: none,
location: none,
period: none,
description,
) = {
indentblock([
#grid(
columns: (auto, 1fr),
rows: 2,
gutter: 7pt,
[#heading(level: 2, company)],
[#align(right, emph(period))],
[#emph(role)],
[#align(right, emph(location))]
)
#block(par(description))
])
}
#let degree(
title: none,
university: none,
period: none,
location: none,
faculty: none,
headline: none,
description,
) = {
indentblock([
#grid(
columns: (auto, 1fr),
rows: 2,
gutter: 7pt,
[
#if title != none [
#box(heading(level: 2, title))
#box([\@])
]
#box(university)
],
[#align(right, emph(period))],
[#faculty],
[#align(right, emph(location))]
)
#block(par(description))
])
}
#let project(
name: none,
description,
) = {
indentblock([
#heading(level: 2, name)
#block(par(description))
])
}
#let certification(
title: none,
issuer: none,
date: none,
credential: none,
description,
) = {
indentblock(
grid(
columns: (auto, 1fr),
rows: 3,
gutter: 7pt,
[#heading(level: 2, title)], [#align(right, emph(date))],
[#issuer], [],
[Credential ID: #raw(credential)], []
)
)
}
#let interests(
items: (),
description,
) = {
block(
inset: (left: 1.5em),
[
#par(description)
#grid(
columns: (auto, 1fr),
column-gutter: 2.5em,
row-gutter: 1em,
..for item in items {
(text(weight: "bold", item.topic), text(item.description),)
}
)
]
)
}
|
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/wire/control%20wires/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 0pt)
#import "/src/quill.typ": *
#quantum-circuit(circuit-padding: 0pt,
mqgate($a$, target: 1, wire-count: 1, wire-label: (content: "a", dx: 0pt)),
ctrl(1, wire-count: 2, wire-label: (content: "a", dx: 0pt)),
swap(1, wire-count: 3, wire-label: (content: "a", dx: 0pt)),
mqgate($a$, target: 1, wire-count: 4, wire-label: (content: "a", dx: 0pt)),
mqgate($a$, target: 1, wire-count: 5, wire-label: (content: "abcde", dx: 0pt)),[\ ],
mqgate($a$, target: 1, wire-count: 1),
ctrl(1, wire-count: 2),
swap(1, wire-count: 3),
mqgate($a$, target: 1, wire-count: 4),
mqgate($a$, target: 1, wire-count: 5),[\ ],
5
) |
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/biology/quiz2.typ | typst | #import "template.typ": *
#show: template.with(
title: "Quiz 2",
subtitle: "7.016"
)
= Lecture 9
DNA is wrapped around 8 proteins called histones (octamer), which are collectively called a nucleosome.
#define(
title: "Chromatin"
)[
Half DNA and half proteins, they work to give structure to DNA, and make it easier to interact with.
]
#define(
title: "Acetylation"
)[
The addition of an acetyl group to a histone tail. The lysine is positively charged, and the process changes it to more neutral.
]
*Euchromatin* are active and are involved in gene expression, while *heterochromatin* are inactive and reside in the centromere or at the chromosome ends.
Histone Deacetylase (HDAC) help to remove the acetyl, reducing expression. Histone Acetyltransferase (HAT) do the opposite by adding an acetyl, and increasing gene expression.
The life cycle of mRNA:
+ Exons end up in the final mRNA.
+ Exists the nucleus and presents itself to a ribosome.
+ Ribosome produces a protein.
+ Degradation.
m7G is attached to the 5' end, and helps protect against degradation. The UTR is the untranslated region. The 3' end contains a poly(A) tail which also protects from degradation.
= Lecture 10
tRNA are loaded with an amino acid and bind mRNA. Codon is on the mRNA, anticodon is on the tRNA, they bond using hydrogen bonds. Their alignment is antiparallel. There are thus $4^3 = 64$ total codons, and there are $20$ encoded amino acids. This means that there is a certain amount of redundancy.
/ START codon: AUG
/ STOP codons: UAA, UAG, UGA
The above are recognized by special proteins called release factors. Because of the wobble position, where the tRNA is less specific for the third (most 3') base of the codon, we need to have redundancy to prevent this from becoming an issue.
A *frame of translation* is essentially the mod three value with which we start our translation. It is possible to find different start codons in different frames of translation, and thus we can actually have one mRNA encoding multiple peptides.
A *mutation* is a permanent change in a nucleotide sequence. Unmutated sequences are called *wild type* sequences. The four types of mutations are listed below:
/ Silent Mutation: No change in the encoded amino acid.
/ Missense Mutation: Change in the encoded amino acid. This is a cause for sickle cell anemia.
/ Nonsense Mutation: Generating an stop codon.
/ Frameshift Mutation: Changing the modularity.
Ribosomes contain rRNA and proteins. The amino acid chains are linked through peptide bonds. tRNA is loaded with a single amino acid at the 3' end.
= Lecture 11
- Most of the genome is composed of non-coding sequences.
- Genes can be transcribed in multiple orientations.
- The transcription start site is upstream (5') relative to the translation start site.
- Each gene does not necessarily have only one start codon.
- Each gene does not necessarily have only one stop codon.
- A single codon *can* be split across two exons.
- Most genes *do* have introns (97%)
- Alternative splicing is the process of having multiple variants of the same gene by including / excluding specific exons.
- Conversation across species is highest in protein coding regions.
- Enhancers and promoters are other island of high conservation.
- It is *not* the case that all genes partake in protein coding.
Many ribosomes live on the rough endoplasmic reticulum (ER).
#twocol(
[
== Prokaryotic
- Pre nucleus.
- *Does not* have a nucleus (karyon).
- DNA is located in the cytoplasm.
- *Does not* have organelles.
],
[
== Eukaryotic
- True nucleus.
- *Has* a nucleus (karyon).
- DNA is located in the nucleus.
- *Has* organelles.
]
)
There are actually membrane-less compartments called *condensates*.
= Lecture 12
Somatic or body cells, retain two sets of chromosomes, and are called *diploid*. The reproductive cells however, cannot have that much information, and thus need to only contain half that data, and are therefore called *haploid*.
The *mitotic spindle* is the tool that is used for mitosis. The kinetochore at the centromere is what the mitotic spindle connects to, and pulls in opposite directions.
#twocol(
[
== Mitosis
- Happens in somatic cells.
- Follows DNA replication.
- Equal segregation of sister chromatids.
- Followed by 'cytokinesis', or cell division.
],
[
== Meiosis
- Necessary to form gametes.
- Follows DNA replication.
- segregation of chromosomes ($2n -> 1n$)
- Followed by 'cytokinesis', or cell division.
]
)
= Lecture 13
Unlinked genes follow traditional Mandelian laws, while linked genes on the same chromosome require more thought. Homologous chromosomes can also exchange DNA when they cross over at points called the chiasmata, leading to a process called recombination.
= Lecture 14
According to Mendel's second law, 50% of the progeny will be parental and 50% will not.
The genetic distance is equal to the number of recombinants over the total number of progeny.
Whatever the two parental alleles are will (if they are linked) be more likely to be together, and the recombination is less likely.
/ Forward Genetics: Start with a phenotype of interest, and try to find the gene.
/ Reverse Genetics: Start with a candidate gene, and see how that impacts the phenotypes.
= Lecture 15
#define(
title: "Hard-Weinberg Equilibrium"
)[
- No new mutations.
- No natural selection.
- No drift.
- Random mating.
- Infinite population size.
]
There are two sides of the coin, positive and negative / purifying selection. There is also balancing selection.
== Random Genetic Drift
Allele frequencies change by random change. Random sampling of gametes passed down may lead to a slight bias. In a large population, this will not happen, but in a small population it may be a prevalent issue.
Phylogenetic trees show the evolutionary tree.
= Lecture 16
== How to Amplify
Bacterial plasmids can be used to amplify / replicate DNA _in vivo_.
Denature double stranded DNA at 94C, then we hybridize the complementary base pairs, and then elongate using polymerase.
== How to Sequence
Mutated DNA will cause chain termination due to the absence of the OH pair. This is called ddNTP. We can introduce this at a certain point, at which the sequence will conclude after some variable amount of time.
There are different kinds of RNA, so we can learn a lot of sequencing RNA.
== Polymorphism
Polymorphism are genetic variations in a population.
- Single Nucleotide Polymorphism (SNP) is a variation at a single nucleotide.
- Simple Sequence Repeat (SSR) Polymorphism is a variation in the length of the sequence repeat.
|
|
https://github.com/crd2333/Astro_typst_notebook | https://raw.githubusercontent.com/crd2333/Astro_typst_notebook/main/src/components/TypstTemplate/fonts.typ | typst | // typst 读取字体的规则是从前往后,如果找不到对应就往后找
// 下面是我觉得还算好看的字体,不过基本只使用了宋体和黑体,英文统一用 Arial,中文分宋体、黑体和楷体
#let 字体 = (
宋体: ("Arial", "Noto Serif CJK SC"),
黑体: ("Arial", "Noto Sans CJK SC"),
思源宋体: "Noto Serif CJK SC",
思源黑体: "Noto Sans CJK SC",
楷体: ("Arial", "LXGW WenKai"),
ntl: "Microsoft New Tai Lue",
meslo: "MesloLGS NF",
meslo-mono: "MesloLGS Nerd Font Mono",
tnr: "Times New Roman",
);
#let 字号 = (
初号: 42pt,
小初: 36pt,
一号: 26pt,
小一: 24pt,
二号: 22pt,
小二: 18pt,
三号: 16pt,
小三: 15pt,
四号: 14pt,
小四: 12pt,
五号: 10.5pt,
小五: 9pt,
六号: 7.5pt,
小六: 6.5pt,
七号: 5.5pt,
八号: 5pt
);
// 汉字伪粗体,from https://discord.com/channels/1054443721975922748/1054443722592497796/1175967383630921848
#let skew(angle, vscale: 1, body) = {
let (a, b, c, d) = (1, vscale * calc.tan(angle), 0, vscale)
let E = (a + d) / 2
let F = (a - d) / 2
let G = (b + c) / 2
let H = (c - b) / 2
let Q = calc.sqrt(E * E + H * H)
let R = calc.sqrt(F * F + G * G)
let sx = Q + R
let sy = Q - R
let a1 = calc.atan2(F, G)
let a2 = calc.atan2(E, H)
let theta = (a2 - a1) / 2
let phi = (a2 + a1) / 2
set rotate(origin: bottom + center)
set scale(origin: bottom + center)
rotate(phi, scale(x: sx * 100%, y: sy * 100%, rotate(theta, body)))
}
#let fake-italic(body) = box(skew(-12deg, body)) |
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/web3/weeks/week7.typ | typst | #import "../../utils.typ": *
#subsubsection("Combining exports")
#align(
center,
[#image("../../Screenshots/2023_11_02_02_16_09.png", width: 100%)],
)
#subsubsection("Combined example")
#align(
center,
[#image("../../Screenshots/2023_11_02_02_17_14.png", width: 100%)],
)
#section("Templates")
#subsection("Bindings")
- one-way source to view -> code to html\
```html
<p>... {{counter.team}}</p><!-- interpolation -->
<img [attr.alt]="counter.team" src="team.jpg">
```
- one-way view to source -> html to code\
```html
<button (click)="counter.eventHandler($event)">
```
- to way: usefull for textboxes -> view to source: value of textbox changed\
```html
<input type="text" [(ngModel)]="counter.team">
```
#align(center, [#image("../../Screenshots/2023_11_02_02_23_40.png", width: 70%)])
#subsubsection("Interpolation")
This is the {{ geil }} syntax:
- side effects not allowed -> no ++ -- etc
- binary operators allowed -> ! & ? etc
#subsubsection("Binding Input and Output properties")
- \@Output()\
wed-navigation (click)="..."\
Your component/directive fires bindable events(such as click).
- \@Input()\
wed-navigation [globi]="..."\
Your component/directive consumes bindable values(such as globi).
```ts
@Component({…})
export class NavigationComponent {
@Output() click =
new EventEmitter<any>();
@Input() globi: string;
}
```
#subsection("Directives")
- Similar to a component but without a template.
- Defined as a typescript class with a \@Directive() decorator
- Two different kinds of directives exist:
- Structural directives: Modifies the structure of your DOM
- Attribute directives: Alter the appearance or behavior of an existing element
#subsubsection("Attribute Directives")
- Changes the appearance or behavior of an element, component, or another directive
- Applied to a host element as an attribute
NgStyle Directive
Sets the inline styles dynamically, based on the state of the component.
```html
<div [ngStyle]="{ 'font-size': isSpecial ? 'x-large' : 'smaller' }">
<!-- render element -->
</div>
```
NgClass Directive
Bind to the ngClass directive to add or remove several classes simultaneously.
```html
<div [ngClass]="hasWarning ? 'warning' : '' ">
<!-- render element -->
</div>
```
#subsubsection("Structural Directives")
- Responsible for HTML layout
- Reshape the DOM's structure, typically by adding, removing, or manipulating elements
- Applied to a host element as an attribute
- An asterisk (\*) precedes the directive attribute name
NgIf Directive
Takes a boolean value and makes an entire chunk of the DOM appear or disappear.
```html
<div *ngIf="hasTitle"><!-- shown if title available --></div>
```
The \* addition is just syntax sugar, expands to this:
```html
<ng-template [ngIf]="hasTitle">
<div><!--conditional content--></div>
</ng-template>
```
NgFor Directive
Represents a way to present a list of items.
```html
<li *ngFor="let element of elements"><!-- render element --></li>
```
NgIf Else
```html
<!-- the reference is an id that is set -> we render the reference when else is chosen -->
<ng-template #toReference><!-- content --></ng-template>
<div *ngIf="hasTitle; else toReference"><!-- conditional content --></div>
```
#subsubsection("Template Reference Variables")
- References a DOM element within a template
- Can also be a reference to an Angular component or directive
- Reference variables can be used anywhere in the template
- A hash symbol (\#) declares a reference variabl
```html
<input placeholder="phone number" #phone>
<button (click)="callPhone(phone.value)">Call</button>
```
#subsubsection("Templates Demo")
#align(center, [#image("../../Screenshots/2023_11_02_02_39_48.png", width: 90%)])
#section("Services")
Provides any value, function, or feature that your application needs.\
Can be set as a root service or within a module with the forRoot/forChild module declaration -> later
#subsection("Example")
#align(center, [#image("../../Screenshots/2023_11_02_02_46_19.png", width: 90%)])
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/021%20-%20Battle%20for%20Zendikar/004_The%20Survivors%20of%20Sky%20Rock.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Survivors of Sky Rock",
set_name: "Battle for Zendikar",
story_date: datetime(day: 09, month: 09, year: 2015),
author: "<NAME>",
doc
)
#emph[Sea Gate, Zendikar's foremost city, has fallen to the Eldrazi, and Gideon holds himself partially responsible for its fall. He left the fight briefly to go to Ravnica and collect Jace Beleren, hoping the mind mage would be able to solve the puzzle of the hedrons and help to turn the tide. When Gideon and Jace returned to Zendikar, Sea Gate was beyond saving. Gideon helped an injured Commander Vorik evacuate, along with a small band of survivors—all that remained of Zendikar's greatest city.]
#emph[The group made camp atop a massive, high-floating hedron, and soon after, Jace left with the merfolk Jori En on a journey to the Eye of Ugin to look for more clues about the power of the hedrons. Jace tried to persuade Gideon to accompany him, but Gideon refused to leave the Zendikari for a second time. Their survival is the most important thing to him now—though he does not know how he will ensure it.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
We must collect our strength.
We must regroup.
We must survive.
Commander-General Vorik's orders. The directives Gideon had sworn to serve.
Of those, survival was the most daunting.
Survival had never been straightforward on Zendikar, but recently it had become all the more elusive. Survival on this plane, in this time, in the face of these monsters, demanded patrols, fortifications, weapons, healing balms, food, water, shelter, warmth. The list went on.
So Gideon was taking it one step at a time.
Right now, it was the water that he was working on.
With help from the kor Abeena, he was in the process of repositioning the nearest floating rock waterfall so that its precious stream of life-giving water would rain down onto the far end of the hedron camp where the survivors could safely and easily access it.
#figure(image("004_The Survivors of Sky Rock/01.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"All clear!" Gideon called to Abeena.
Abeena was balancing on the thin lip of the waterfall rock, which was currently too far away and turned in the wrong direction, pouring buckets of water down into an expansive canyon where it couldn't be reached or collected.
The kor had secured four ropes that trailed from the waterfall to the main, massive hedron camp. Gideon held two of the ropes, one in each hand. To his right, a merfolk and another kor braced themselves, cinching the third rope. And to his left, three humans clutched the fourth rope.
"Ready when you are!" Abeena called back.
Gideon nodded to the others. "All right, here we go. Heave!" He hefted the ropes, walking backward, planting one foot behind him and then the other.
The others pulled too, and together they lugged the waterfall closer to Sky Rock.
"That's it," Gideon encouraged. "Almost there." Sweat formed at his temples as he gave the great stone another yank. The feeling of exertion was one of the most satisfying he knew. And the rush of a crisp Zendikari breeze past his ears wasn't bad either.
His appreciation for this world had grown immeasurably in just the short time he had spent atop Sky Rock. The view from up here was unmatched. In another life, Gideon could have seen himself living here, spending his days climbing, hunting, exploring, and adventuring. It was easy to see why so many loved this world. Why so many fought for it.
"Hold it there!" Abeena called. "I'm going to turn it around."
"Brace!" Gideon ordered. He tapped into his reserves of power and grounded himself to the hedron; he became as immovable as the thickest of Zendikar's trees. The others tightened their grips and steeled themselves as Abeena flung another rope with a thick hook out to a third floating rock.
#figure(image("004_The Survivors of Sky Rock/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
With a wide stance, Abeena pulled on that rope, using it as an anchor to turn the waterfall around on its axis. She aligned the floating falls so that the stream of water faced the camp. "I think I've got it!"
A cheer rose up from behind, and Gideon turned to see that most every survivor at Sky Rock who was free and able had gathered around to watch. Their longing was palpable; they were anticipating that first quenching swallow of water.
"We have some thirsty people over here, Abeena," Gideon said. "Let's bring them some water!"
Another cheer.
"With pleasure." Abeena detached the fifth rope and knelt low on the hedron so she could guide its path. "Bring it in."
"This is going to shake us," Gideon warned the gathered crowd. "Hold on!"
A final yank heaved the waterfall straight over Sky Rock. The water pounded down on the far end of the hedron; the entire rock shifted at the weight of the turbulent stream. But both the din and the vibrations were drowned out as the Zendikari raced to splash under the stream, cheering, drinking, singing.
"Thank you, Gideon." Abeena said as she climbed down from the rock. "We're lucky to have you here."
"It's you we're lucky for," Gideon said. "Nice work with the ropes. I think you earned this." He handed her a cup.
"Cheers." She raised the cup and strode toward the stream.
Good. This was good, Gideon thought. They had water now. They needed water to survive. That meant they were one step closer.
"He doesn't want you wasting your time with this." Tazri's voice sounded from behind. She must have come from Vorik's tent; that's where she had been spending most of her time, talking and planning with the commander as three healers watched over him. The purpose of Tazri's vigilance was obvious to Gideon. If the persistent coughing that he heard from the commander meant what Gideon feared—Eldrazi corruption—then soon enough Tazri, Vorik's most trusted advisor, would take the commander's place. That would mean a lot of changes for the survivors of Sky Rock. And for Gideon.
Tazri had been cold toward him ever since Vorik had taken Gideon's suggestion over hers during their evacuation. It had been Gideon's idea for the survivors to retreat up to the top of the floating hedron; Tazri had wanted them to push on and evacuate further. Gideon still believed his had been the correct course of action, but he no longer wanted to argue with Tazri—he needed to earn her trust.
"Tazri." Gideon turned, making sure to keep smiling. "I have an extra cup. Do you want some fresh water?"
"Their time would have been put to better use preparing to continue the evacuation."
"They are preparing," Gideon said. "This will help. It'll be easier to fill their canteens."
"They were fine filling them down at the river. You used, what? Six healthy, strong people who could have been out there hunting. They might have felled a baloth, or even two by now. We need to collect rations. Commander Vorik's orders."
"We need water too."
"Not to splash around and play in." Tazri waved at the Zendikari who were still dancing in the stream. "This is a waste of time."
Gideon couldn't help but grin at the sight. "Keeping spirits high is never a waste of time."
#figure(image("004_The Survivors of Sky Rock/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"I know what you're doing." Tazri narrowed her eyes. The glow of the halo she wore around her neck seemed to intensify. "You're trying to make this place comfortable. Trying to find excuses to stay. You're waiting for him to come back. That other stranger. The one who is like you."
Jace. She was talking about Jace. This was not the first time Tazri had hinted that she knew Gideon was a Planeswalker.
"I heard you arguing with him," Tazri went on. "And I heard you lose."
Gideon bristled. He hadn't lost. He wanted Jace to solve the puzzle of the hedrons; he might have preferred that Jace had waited to go to the Eye of Ugin until things were more stable here, but he had agreed with the general plan.
"You can't make these people wait here for him to get back," Tazri said. "It's too dangerous. Do you have any idea how long he'll be gone? Do you know how far away Akoum is?"
Gideon did, but she didn't give him the chance to answer.
"No, you don't," Tazri accused. "You're not from here. I know about you, about him. Neither of you belongs on Zendikar, and you have no right to come here and put these people—my people—in danger." By the time she finished she was leaning in, her finger stabbing the armor on his chest.
Gideon held up his hands. He wouldn't lie to her; that wasn't the way to establish trust. "You're right. I'm not from this world." He took a step back, giving Tazri some space. This was his chance to explain; he needed her to understand. "But I do know Zendikar. I know it well. I have crossed its seas and climbed its mountains. I have seen its sun rise and set countless times. I have traveled to and battled on nearly every continent. And I will continue to fight." He met and held her gaze. "I care greatly for this land, and even more for its people. I am here only to help."
Tazri surveyed him, as though taking him in for the first time, really looking. Gideon stood tall, his expression earnest, willing her to see how much he meant each word.
She inhaled sharply. "Then you'll stop interfering. Vorik knows what's best. I know what's best. And it's not that." Tazri waved in the direction of the waterfall. "That's bad, Gideon. Don't you see? It gives the people a false sense of security. It makes them think that they can call this place home when they can't. They're not safe here. At any moment the swarms from Sea Gate might descend on us. At any moment we might be forced to fight for our lives again. So few survived the first time. How many do you think will survive a second assault?"
Survival was not easy.
"If you want what is best for these people, as you say you do, then help them hunt. Help them collect rations. Help them prepare to continue the evacuation. That's their only chance of survival."
A coughing fit from the direction of Vorik's tent drew both their attention.
"It's what Vorik wants." Tazri turned swiftly on her heel and strode toward the tent.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Gideon paced at the far north end of Sky Rock, the din of the waterfall barely audible in the distance. He was waiting for the rest of his hunting party; the same six who had helped him pull in the waterfall would now help him track a gnarlid—or a baloth, if they were lucky.
#figure(image("004_The Survivors of Sky Rock/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
He was impatient.
They were losing light.
And Tazri was wrong about the waterfall.
The waterfall was good.
The water was good.
Survival was the directive, and Gideon had acted accordingly. The water would help the Zendikari survive, whether it was for one more night, one more week, or one more month.
The longer the better.
He disagreed with Tazri, and with Commander Vorik for that matter.
He thought they should stay.
Not only because of Jace, though Tazri wasn't wrong that Gideon wanted to wait for Jace's return. The mind mage wouldn't be gone as long as Tazri thought; it would be a long journey to Akoum, undoubtedly, but Jace would most likely planeswalk back to the camp after he found what he needed at the Eye. That would cut the total distance, and time, in half. And with the information Jace found, Gideon hoped their chances of survival would soar. The promise of the hedrons' power was the hope he clung to. If the Zendikari could wield that power, perhaps they would actually survive the evacuation that Vorik and Tazri wanted them to make.
Gideon couldn't protect them out there in the wilderness the same way he could here on the hedron. At least here they were all in one place, and he knew where they were. At least here they had access to food, they were building shelters—and they had water.
If the goal was to survive, Gideon didn't think they should leave.
So how long could they stay?
He looked north, in the direction of Sea Gate. Just the top of its lighthouse was visible from here.
What were the Eldrazi doing? Were they still clambering over its walls and spreading their corruption across the rocks? Or were they on the move, as Tazri suggested?
How fast did they travel? How long would it take them to reach this floating hedron?
How many would come?
How many could Gideon hold off?
If they came at a slow enough trickle, he could dispatch them one by one before they reached the encampment.
He could do it alone.
No one else need risk their life.
He would fight the whole blasted lot of them one by one if he had to.
But if they came in a group . . . "Hurry up, Jace," Gideon breathed.
"Gideon!" The voice came from above, startling Gideon—for just a heartbeat he thought, hoped, prayed it was Jace. But it was far too soon. Of course it wasn't Jace.
"Gideon!"
Gideon took a step back as an enormous blue and white manta descended from above and hovered an arm's length in front of him. The elf on its back looked slightly out of place, but not uncomfortable. She knelt tall, her back straight. Her arm was raised, holding a spear.
#figure(image("004_The Survivors of Sky Rock/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"Seble," Gideon said. "What is it?"
"Trouble. Get on!"
Gideon didn't question the skyrider; she was the camp's only patrol stationed in the air, and she had been the alarm system that had saved them from a potential Eldrazi attack more than a handful of times already.
He climbed aboard.
"There's a party coming in from the south," Seble called back over her shoulder as the manta shot into the sky. "And they're being tailed by an Eldrazi."
Gideon exhaled a relieved breath. If they were coming from the south, then whatever Eldrazi was tailing them wasn't part of the swarm from Sea Gate. There was still time.
"It's a flier," Seble said. "And it's big, Gideon."
Gideon refocused. Even if it wasn't the swarm, it was still an Eldrazi, one he would have to destroy. "Take me there." He gripped the back of Seble's belt as the manta surged forward.
"I think they're more refugees," the elf called back to him. "They looked pretty beaten up, from what I saw."
"Then let's make sure the last leg of their journey is as pleasant as it can be," Gideon said.
This would be the second group of refugees Sky Rock had welcomed in that many days. The last party of refugees was a group of kor who had been found by a hunting party, wandering around in shock after having seen Sea Gate. They had come from Akoum; they had traveled across two continents and the sea, all because Sea Gate was supposed to be a sanctuary. That was the word that had spread across most of the world, according to the kor. They promised that there were more coming, from all over. And here was more proof.
All of these Zendikari were fleeing to a sanctuary that did not exist.
As the manta circled under a large, broken hedron, Gideon caught his first glimpse of the giant Eldrazi Seble had warned him of. It was a low flier, with strikingly blue tentacles, and it was undulating along just above the treetops, winding its way between the vines that dangled down from the hedrons above.
Its course was set on a party in the distance, just as Seble had said. They didn't seem to be aware of the danger they were in.
"How close can you get me?" Gideon called up to Seble.
"How close do you want to be?" Seble kicked the manta's side, spurring it into a dive, angling straight for the Eldrazi.
As the manta swooped, Gideon unfurled his sural.
Seble's pass brought them close enough for her to reach it with a solid thrust of her spear. As the point of her spear punctured the Eldrazi's side, the four blades of Gideon's sural slashed its back, slicing it open in four places.
But that was not enough damage to slow it down.
"Incoming!" a panicked voice called out from below. It was one of the refugees—a human woman with long silver-gray hair. She had seen the Eldrazi.
#figure(image("004_The Survivors of Sky Rock/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The woman's agitation seemed to attract the monstrosity. It picked up its pace.
The refugees broke into a run.
"Another pass," Gideon called to Seble. "Hurry!"
On her second pass, Seble flew even closer than the first time. So close that Gideon could smell the Eldrazi's freshly-exposed innards.
He lashed out ahead with his sural and gore splattered out of four more slices on its side. But the injuries weren't slowing it down.
He had to slow it down.
He whipped his sural again, this time with the intention of ensnaring rather than slicing. With a flick of his wrist, the blades of his weapon coiled around the Eldrazi's tentacles.
Gideon yanked, pulling the Eldrazi backwards and off course, away from the refugees.
But he hadn't considered the physics of a sky battle. Without anything to counter the force of his assault, Gideon, Seble, and the manta were whipped through the air in the opposite direction.
They dipped and faltered, Seble scrambling to regain control. "Let it go!" she called back to Gideon.
Gideon flicked his sural, attempting to release the Eldrazi, but two of the blades of his weapon were tangled around the tentacle, caught; he couldn't pull it free.
The Eldrazi bucked and the manta was jerked to the side.
"Let go!" Seble called again.
Gideon realized she meant for him to let go of the sural—but too late. He lost his seat and slid off the manta's curved back.
For a moment he plummeted through the sky. Then his sural jerked him to a sudden halting stop, and he was left swinging from the Eldrazi's backside—he watched Seble and the manta plunge toward the ground.
The whole ordeal hadn't won him any time. The Eldrazi was still on course. Dangling from it, Gideon could make out the scars and wounds on the refugees' arms and legs.
"Stay away from them!" Using his sural like a winch, the way he had seen Abeena do, Gideon pulled himself up the Eldrazi's tentacles and onto the bony plates of its back.
The beastly thing thrashed and twisted, reaching for him with four arms that bent unnaturally backward, and still somehow maintaining its heading.
Gideon channeled the magic of his protective, glowing shields, putting one up first on his side, then his front, and then his leg, blocking all of its appendages as he climbed up the bony plates toward the Eldrazi's head.
He grabbed hold of its thinner head tentacles that looked vaguely like antennae, and using them like reins, he snapped the monster's head back. Then he thrust it forward, putting all of his weight into it and forcing the Eldrazi into a nosedive.
The thing reared and spasmed, flinging its tentacles about, but Gideon didn't let up. "I told you to stay away!"
With a final thrust of power, he drove the Eldrazi straight into the ground, putting his whirling shields of magic up just in time to protect himself from the impact.
The crash dislodged his sural and Gideon snapped it back, winding it up. He jumped off the Eldrazi, and with his next breath he lashed out at the monstrosity, once, twice, again. Slicing off tentacle after tentacle, ripping into the tenderest parts of its flesh.
The thing chattered and squealed; the unnatural noises only spurred Gideon on. He would slash the Eldrazi once for every Zendikari that had been lost to its kind. And once more for those who soon would be lost. All the people were doing was trying to survive, but there were too many of the monsters—too many that would come endlessly, spreading across the land. Forever. It would never end.
The Zendikari would never be safe.
How would they ever survive?
How?
A pile of Eldrazi gore and strips of flesh lay at Gideon's feet. There was nothing left to destroy. He dropped his arm and his sural fell motionless at his side.
They couldn't retreat to Zulaport.
No matter what Vorik said.
No matter what Tazri wanted.
The people of Sky Rock would never survive this. They would never make it across Tazeem, let alone across the sea.
There were too many Eldrazi.
They had to stay. If they wanted to survive, they had to stay here.
But what if they wanted to do more than survive?
A gust of wind and the beating of leathery wings drew Gideon's attention. He turned to see Seble hovering not far above, looking on, question in her eyes.
"Did they make it to camp?" he asked.
She nodded.
"Take me back."
She directed the manta lower so Gideon could climb on.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Before Gideon stepped off the manta's back, he could hear Tazri's raised voice. She was arguing with the new group of refugees. Gideon jogged over.
"Sea Gate can't fall," a kor in the party grunted as though the idea was absurd.
"It has," Tazri said. "We evacuated a few days ago. It is lost."
"No." The old woman with long silver-gray hair, who Gideon had seen from above, gripped Tazri's arm. "No." She shook her head. "This." She held up her other hand and lifted one bony, wrinkled finger. "This is what we fought for. This is why—" she bit her knuckle to fight back a sob. "You have no idea." Her voice shook but she didn't cry. "Do you know how far we have come? The Roil, four times. That monstrous Eldrazi. The swarm of them in the river. Tho, Zuri, Daye, Itri—they all fell knowing that we would find—no. This is why we came." She brandished her finger in Tazri's face. "This is Sea Gate. Sea Gate is Zendikar's only hope. Sea Gate is all we have left. We came for Sea Gate."
The others behind her held up their fingers too. Gideon recognized the gesture. The first band of refugees had made the same display. Their fingers were a sign for the lighthouse. Sea Gate. Their hope.
"I'm sorry," Tazri said. "Sea Gate is gone. You can come with us to Ondu."
"Ondu!" A young woman in the group balked. "There's hardly anything left of Ondu."
#figure(image("004_The Survivors of Sky Rock/07.jpg", width: 100%), caption: [Art by <NAME> Ro], supplement: none, numbering: none)
"Everyone from Ondu is going to Sea Gate. So is everyone from Akoum. Even some of the vampires from Guul Draz. And now you're telling us, all of us—after all that we lost, after all that we fought—that there is nothing? There is no end?" She looked from Tazri to Gideon. "This can't be true. Please. This can't be true." Silent tears streamed down her cheeks.
Gideon felt her desperation.
This couldn't be true.
"It's the commander." Abeena's voice cut in, clipped and rushed from behind. Gideon turned. "He called for you." She was looking at Tazri.
"I'm sorry," Tazri said to the refugees. She was already running for Vorik's tent. "I have to go."
"Both of you," Abeena said. "Gideon, he wants you too. Now."
Gideon could see it in her eyes. Vorik would not live to see the sun again.
"Stay with them, Abeena," Gideon said.
The kor nodded solemnly.
Gideon left the small group of refugees and raced across the hedron behind Tazri.
She looked back at him. "There are no new rations," she spat. "You didn't go hunting."
"No." Gideon caught up with her and held open the flap of Vorik's tent. "I didn't have the chance." Now was not the time for Vorik to die. Gideon was not ready to answer to Tazri.
Inside the commander's tent it was stuffy and smelled of dry, rotten fungus—the smell of Eldrazi corruption. It came from Vorik's breath.
Three healers stood back against the far wall, silently vigilant.
Gideon knelt at the commander's bedside and Tazri stood behind.
"Sir, we're here," she said.
Vorik opened his eyes; they were bloodshot and had the look of cracked glass. "I hear there are new arrivals."
"Yes," Tazri said. "It's a small party."
"Refugees. And there are more coming every day," Gideon said. "They were going to Sea Gate."
Vorik shook his head, regretfully. "Sea Gate." His voice was little more than a whisper.
Tazri glared at Gideon, a look that told him to stop talking, but he felt the urgent need to speak up. Vorik had to know the truth—now, before he passed. Now, while he could still decide the fate of the people here. "They're coming from all across the world, sir. From all the other places that are falling to the Eldrazi, Akoum, Guul Draz . . . and Ondu."
"Sea Gate should never have fallen." Vorik was still shaking his head, lost in thought. He didn't seem to have heard Gideon. He looked to Tazri. "And how are the preparations for the evacuation?"
"We're on track, sir." Tazri said. "The new numbers mean we'll need to collect a few more rations. But we can leave within the week if everyone does their part." She shot another glare at Gideon. "I have mapped a route across Tazeem and—"
"A route that will be rife with Eldrazi," Gideon cut in.
#figure(image("004_The Survivors of Sky Rock/08.jpg", width: 100%), caption: [Art by Adam Paquette], supplement: none, numbering: none)
"The safest route we could find," Tazri countered.
"There is no safe route across Tazeem," Gideon raised his voice over Tazri's protest; he had a point to make and he would make it. "There is no safe route on all of Zendikar."
"Our journey will be dangerous, yes," Tazri said. "But we knew that. And I have been assured by our scouts that once we make it to the coast there will be boats waiting to take us across the sea."
"Boats that have just made land," Gideon said. "Boats that carried refugees away from places like Akoum and Ondu. Because those places have fallen."
Tazri's nostrils flared and the halo around her neck blazed. She turned on Gideon. "I hear you! We all hear you! You don't want us to evacuate. You don't want us to go to Zulaport."
"No. I don't," Gideon said.
"So what would you have us do instead? Stay here? Sit here on this rock vulnerable and exposed, and wait for them to come for us? Wait to die?"
"No." Gideon realized that he did in fact have another plan. Sometime between slaughtering the flying Eldrazi, talking to the refugees, and seeing the cracks in Vorik's eyes, he had worked out what had to be done. He looked to the commander, meeting Vorik's fading gaze. "I would have us go back to Sea Gate."
"What?" Tazri cried. "Impossible."
"Sea Gate has fallen, Gideon." Vorik coughed, a cloud of dust rising up out of his mouth and floating in the air between them. "It's overrun. It's lost."
Part of Gideon wanted to look away from the dust, from the dying commander, but he respected and cared for the man too much; he didn't so much as blink. "It can stand again, sir," he said. "We can take it back. We gather an army here at Sky Rock—we're already halfway there with all the refugees that are pouring in. Once we have enough soldiers, we surround it just like they did, and we move back in and reclaim what is ours. You yourself have said that it's the most strategic location on all of Zendikar. We need Sea Gate, sir, we need it to—"
"You're insane," Tazri cut him off. "You were there, Gideon—for most of the battle at least. You saw our people fall. You saw the swarms of Eldrazi. How can you possibly think we stand a chance?"
#figure(image("004_The Survivors of Sky Rock/09.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"The Eldrazi won't stay there for long," Gideon said. "Eldrazi don't operate like the sentient armies we know. They have no interest in keeping Sea Gate. They feed on what they can and then they'll pass through, just like they pass through any other place."
"They'll pass through and come straight for us!" Tazri said. "We can't leave soon enough."
"There is nowhere left to go, Tazri!" Gideon clenched his fists. Why couldn't she see? "You keep saying that we have to 'evacuate,' but there's nowhere to evacuate to."
"Zulaport," Tazri said. "We're going to Zulaport, commander's orders."
"And what's to say that Zulaport won't be gone too once we get there? What's to say it's not gone now? This is the end. The Eldrazi are taking over everything. If we don't make a stand now, all of Zendikar will be destroyed."
"Enough!" Vorik shouted, and with his shout came a coughing fit. Clouds of dust shot up into the air with each hack.
The three healers pushed past Gideon and Tazri.
#figure(image("004_The Survivors of Sky Rock/10.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Gideon stood, taking a step back away from the commander's bedside.
"Fool," Tazri spat. "You're a fool. You would march these people, my people, Vorik's people, to their deaths."
"No, I would give them a chance to live."
"Their chance for survival is at Zulaport. You know that as well as I do."
"Survival is no longer enough, Tazri," Gideon said.
"How can you say that? Survival is the only thing."
"I didn't see it either. Not until just now. I've been so focused on what's in front of us. We all have. But we have to look at the bigger picture." Gideon recognized Jace's words on his lips. In this case the mind mage had been right. "It's not just Sea Gate that has been overrun. The swarms of Eldrazi are taking everything. They're everywhere. I've seen them myself. If we don't act now, if we don't fight back, then this world will be lost. Everything and everyone on it will be destroyed."
Tazri's bright eyes pierced Gideon. "Except for you. You will just leave."
Gideon blinked, taken aback by her accusation, but before he could counter, Vorik's voice rang out. "Stand down!" For a moment it sounded like the commander's strength had been restored, like he was shouting orders on the battlefield. "Stop clamoring around me and step back, already. Give an old, dying man a chance to breathe." He was talking to the healers. "Your work here is done." He nodded at them, his look firm. "Thank you for all you have done, but it is over." He looked past the healers. "Tazri, Gideon. Come. Time is short."
As the healers somberly stepped back, Gideon and Tazri approached.
"I am dying, and you are arguing."
"Sir—" Tazri started, but Vorik spoke over her.
"Now is not the time for arguing. Now is the time to listen. Listen to each other. You're each other's most valuable assets."
Gideon glanced at Tazri, but she continued to stare down at Vorik, stone-faced.
"If you will not listen to each other, then at least listen to me." Vorik propped himself up ever so slightly. "There is something important I must tell you." He licked his dry lips, but his tongue was even drier. Flakes fell from both. He cleared his throat. "When I was cornered out on the battlefield, when that Eldrazi monstrosity pierced me with its corrupted essence, it was the most terrible thing that I had ever experienced."
Gideon tensed.
"But in that moment, it wasn't terror I felt. Not even regret. No. What I felt was relief. I am ashamed to say it, but it is true. I felt relief that I would get to take the easy way out; that I wouldn't have to stay and face what came next."
Beside Gideon, Tazri shifted.
"But then I thought of my people," Vorik said. "I thought of all the Zendikari, and I felt remorse. I would be gone and they would be here, you would be here, you would have to watch the world end." Vorik paused, swallowing a cough. "But now I have hope," his voice was choked. "I have hope that that is not true. I have hope that there is still a chance for Zendikar. Gideon Jura, you have given me hope." He held up a finger.
Gideon thought the commander was indicating they should wait, that he was fighting another cough . . . but then he saw it—
"Sea Gate," Vorik said, holding his finger high. Then he turned it to point to Gideon. "These people need to be inspired the same way you have inspired me. They need to find hope, just as I have. They need a leader who sees the way to victory no matter the circumstances. When I am gone, you will lead these people. You will reclaim Sea Gate, Commander-General Jura."
"Sir." Gideon staggered. The title. . .
"No." Tazri gasped.
"Tazri." Vorik looked to his advisor. "You are strong and brave, and you have been my most loyal advisor. But you are too close. You are too close to me, to my ideas, to Zendikar. This world needs a fresh perspective, these people need a new reason to believe."
"But—"
"You know Zendikar better than anyone—better perhaps than I do. That is why the commander will need your help. You will stand by him as you have stood by me."
"You can't do this, sir," Tazri said. "He's not even a Zendikari."
Vorik coughed again. A hard, racking cough that brought up a chunk of corruption as large as a coin. He fought for breath, shaking his head. "It doesn't matter where he came from, Tazri. He has a Zendikari's stubborn spirit." Vorik reached out to Gideon.
Gideon closed his thick fingers around the commander's wilting hand.
"Don't lose that spirit," Vorik said. "Don't lose this land."
"I will not, sir," Gideon vowed.
"I leave Zendikar to you, Gideon." The words came out on a cough that tore through the commander's insides. His body convulsed, and then his hand fell limp inside Gideon's.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The funeral was held at sunrise at the edge of the hedron, looking out over the land.
#figure(image("004_The Survivors of Sky Rock/11.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The Zendikari sang hymns, their voices starting low and strong, and swelling into something tumultuous and daring.
Gideon joined in when he could, but Tazri's sidelong glances confirmed that he was off-key.
Commander Vorik's body was wrapped carefully in cloths, and the Zendikari at the camp formed a circle around their fallen leader. In turn, each of them knelt and, with a dark charcoal rock, drew a mark on the burial cloth, whispering a chanted message as they did.
It came to be Gideon's turn.
"You don't know what to say, so say nothing," Tazri hissed under her breath as he stepped up to Vorik's body.
Gideon knelt. He picked up the dark charcoal rock and made the mark in silence.
Tazri was right, he didn't know the words of the burial. But he did know what to say.
He stood, inhaling a great lungful of Zendikari air and letting the scent of the wild land fill him. He looked out at the people of Sky Rock, his people. "Today we have lost much," he began. "More than just our commander. We are left without our leader, our champion, our guiding light. Like the lighthouse at Sea Gate, Commander-General Vorik stood tall and true even in the face of greatest adversity. And even though he is gone, we must do as he did, because we now face the greatest adversity Zendikar has ever known.
"In the same way that the corruption spread to claim our friend's body, so too do the corrupting monsters spread across this land. Each day is worse. Each day there are more. Each day they take more. We cannot let them do this any longer." He nodded to Vorik's body. "We have seen what happens when they are allowed to rampage at will. We cannot let what happened to our leader happen to this world."
#figure(image("004_The Survivors of Sky Rock/12.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
He paused, looking around at the fallen, desperate faces. "We have a choice before us today. We can choose to leave Sky Rock. We will be ready to evacuate within the week. We have rations and supplies. Boats wait for us at the harbor. We can retreat to Zulaport."
The people leaned in, anxious.
"But if that's what we choose, many of us will not make it. The journey will be dangerous. We will encounter scores of Eldrazi across the land and in the waters. I have been across the sea. I have seen the Eldrazi at Ondu, Kabira, Fort Keff, and all places in between. They are everywhere. And every day there are more. They might already be at Zulaport. Those of us who do make it to Zulaport may find nothing but more Eldrazi."
Tazri made to argue, but Gideon held up his hand and continued. "Or perhaps we will find that the safehold still stands. But if that is so, for how long? How long will anything stand?" He glanced at Tazri. "There is no saying, but at some point, if we choose Zulaport, Zulaport will fall. It will fall just as Sea Gate fell, just as every other part of Zendikar is falling. If we chose to retreat, we will be destroyed along with this world."
It was a hard truth, but it was #emph[the] truth, and these people deserved to know the truth. They had to know the truth.
"But we do have another choice," Gideon went on. "We can choose to fight back. We can choose to stop running. We can choose to go on the offensive. To stand tall and true in the face of the greatest adversity. I stand before you today as your commander, and I ask you to choose to fight. I ask you to help me. Help me gather every Zendikari, from all corners of the world, from every continent, every last Zendikari who is willing to fight. We will assemble right here at Sky Rock. The full strength of Zendikar will converge in one place, and with that force we will fight. With the might of the world behind us, we cannot lose. We will use that power to reclaim Sea Gate."
A murmur rose up from the gathered crowd, but Gideon continued. There was more they had to hear. More he had to say. "Sea Gate is the heart of this world. It is the most strategic location, filled with weapons, food, and supplies. Fortifiable, defensible. Reclaiming it is only the first step. From there, we launch our own attack. We become the predators. We hunt the invaders. We wipe out the corruptors. We spread across the land and take back what is ours." He whipped his sural through the air. "We take back Zendikar!"
#figure(image("004_The Survivors of Sky Rock/13.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
He looked at the gathered Zendikari in turn. "Who is with me?"
After a long moment, Seble raised her fist. "For Zendikar!"
"For Zendikar!" Abeena added her call.
Cheers rose up from the gathered crowd with such a force that the voices shook the very hedron the people stood on. "For Zendikar!"
Gideon looked to Tazri. She was standing at his side, her arms crossed.
"I will not leave," Gideon vowed. "I am here to the end."
Tazri met his gaze.
"You have my word," he said. "I will battle for Zendikar."
The halo around Tazri's neck glowed brightly, its light catching the wetness in her eyes. She nodded.
"For Zendikar, Commander, I will battle too."
|
|
https://github.com/ren-ben/typst-notes | https://raw.githubusercontent.com/ren-ben/typst-notes/master/ds/introduction_to_r.typ | typst | #import "@preview/sourcerer:0.2.1": code
#align(center, text(24pt)[
*Introduction to the R-Programming Language*
])
#align(center)[
<NAME> \
Technologisches Gewerbemuseum \
#link("mailto:<EMAIL>")
]
#set heading(numbering: "1.")
#show par: set block(spacing: 0.65em)
#set par(
first-line-indent: 1em,
justify: true,
)
#pagebreak()
#outline()
#pagebreak()
= Introduction to R
This chapter discusses the purpose of R as a language and lays out the different data types and operations within R.
== What is R
R is both a language and an enviornment developed mainly for statistical computing and visualization. It provides a wide range of tools designed for statistical techniques, like time-series analyses, clustering, classical statistical tests, etc. One of its strengths is the ease at which well-designed, publication-quality plots can be produced.
It's environment is well suited for effective data handling, managing operations for array calculations, especially matrices, graphically facillitate data analyses & display either on-screen or on hardcopy.
== Arithmetic Operations
The syntax of arithmetic operations is mostly uniform with every other language (`^` is raising to a power, `/` is dividing, `*` is multiplying, etc.), although an exception exists for the modulo operation, which is the reason this section even came to be.
#code(
lang: "",
```r
3 %% 2 # 1
```
)
The modulo in R is made out of two percentage signs.
== Variables & Data Types
R uses an arrow symbol to define a variable. The arrow points out of the variable value and into its identifier i.e. name.
#code(
lang: "",
```r
a.variable <- 100
```
)
This assigns the value `100` to the variable `a.variable`. The most common way of naming variables is with a dot as a separator. Camel-case (`aVariable`) is also sometimes used, but conventions like snake-case aren't used. You can see your current variables in the "Environment" tab. Let us now go over to the different data types R has to offer.
R has an integer type (*numeric class*), a floating-point type (*numeric class*) and a string type (you can use either single or double quotes) (*character class*) The data type that are syntactically different from C-like languages is the boolean (*logical class*). You can either assign it with spelling either `TRUE` or `FALSE` in all-caps, or using the shorthand notation, `T` or `F`. Make sure they are in all-caps, otherwise R will think it's a function. There also exists a function to return the data type: `class(a.variable)`.
== Vectors
We use the combine function to create a vector
#code(
lang: "",
```r
vec <- c(1,2,3,4,5)
```
)
A vector is essentially a one-dimensional array. You can assign other data types to a vector, although they can't be mixed. For example, if you try to insert a character and a numeric, it will convert the numerics to characters.
=== Naming Vectors
You can assign a label to each element of a vector by combining it with another label vector using the `names()` function:
#code(
lang: "",
```r
temps <- c(32, 28, 30, 31, 29, 25, 34)
days <- c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
names(temps) <- days
```
)
This creates a labeled vector `temps` out of the original vector and the days label vector.
=== Vector Operations
You can add, subtract, multiply (element-by-element) and divide (element-by-element) vectors like standard numeric values.
Additionally, there are special functions to perform operations different from the standard arithmetics. For example `sum()` will sum the vector and `mean()` will calculate the vector's mean, `sd()` will calculate its standard deviation, `max()` finds the maximum element, `min()` finds the minimum element and `prod()` returns the product of the elements, e.g. `[5,6,7]` would return `5*6*7=210`.
#code(
lang: "",
```r
v1 <- c(1,2,3)
sum(v1) # 6
mean(v1) # 2
sd(v1) # 1
max(v1) # 3
min(v1) # 1
prod(v1) # 6
```
)
Another feature of R is applying *comparison operations* to vectors, e.g.
#code(
lang: "",
```r
v1 <- c(1,2,3,4,5)
v1 == 3 # FALSE FALSE TRUE FALSE FALSE
v1 > 1 # FALSE TRUE TRUE TRUE TRUE
```
)
This allows for selecting specific values out of vectors. Element-by-element comparison of two vectors is also available (`v1 < v2`).
=== Vector Indexing
Before proceeding, it's very important to underline that *indeces start at 1* in R.
Other than that, accessing each element is straight-forward:
#code(
lang: "",
```r
v1 <- c(23,44,69,2,53)
v1[1] # 23
v1[3] # 69
# ...
```
)
Grabbing individual values is possible with the use of a vector inside of the index brackets
#code(
lang: "",
```r
v1 <- c(23,44,69,2,53)
v1[c(2,4)] # 44 2 - grabs the 2nd and the 4th element
v1[c(1,4,2)] # 23 2 44 - grabs the 1st, 2nd and 4th element
```
)
If you have assigned labels to your vector, you can also use the labels as accessing parameters just like in a dictionary
#code(
lang: "",
```r
v1 <- c(23,44,69,2,53)
names(v1) <- c('a', 'b', 'c', 'd', 'e')
v1['b'] # 44
v1[c('c','b','e')] # 69 44 53
```
)
Slicing in R works in the same way as Python:
#code(
lang: "",
```r
v1 <- c(23,44,69,2,53)
v1[1:4] # 23 44 69 2 - grabs the 1st, 2nd, 3rd and 4th element
```
)
As shown above, slicing indeces are inclusive. A useful trick is that you can use slicing to _create_ vectors, example:
#code(
lang: "",
```r
v1 <- 1:10 # created a vector with numbers from 1 to 10
```
)
There is a way of combining vectors and comparisons in a way that allows for direct access to the elements, not just boolean values
#code(
lang: "",
```r
v1 <- c(23,44,69,2,53)
v1[v1>30] # 44 69 53
```
)
The `v1>30` returns a logical result (true/false values) that is then passed to the vector itself as a way of telling it which elements to grab (true grabs them, false skips them). Additionally, you can even name these expressions to create a kind of filter.
= Matrices
This chapter covers the essentials of matrices in R.
== Creating Matrices
A matrix is created by passing a vector to it:
#code(
lang: "",
```r
v1 <- 1:10
matrix(v1, nrow = 2)
```
)
This creates a 2x5 matrix. Notice how we manually set the number of rows and how R automatically adjusted the number of columns. If we wouldn't do that, it would create a matrix with one column and ten rows.
By default, the order in which the elements are placed are by column, meaning it first populates the entire first column, then goes on to the next. This causes the first row to be `[1, 3, 5, 7, 9]`. If this is undesired, there's a `byrow` boolean parameter that can be passed which is set to `FALSE` by default.
=== Matrix Labels
To pass in labels for the row and column labels, you first create two vectors and then use the apropriate functions to spread them out
#code(
lang: "",
```r
days <- c('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
stocks <- c('Google', 'Meta')
colnames(stock.matrix) <- days
rownames(stock.matrix) <- stocks
```
)
== Matrix Multiplication
To perform true matrix multiplication, you use an asterix surrounded by percentage signs instead of just the asterix which performs an element-by-element multiplication:
#code(
lang: "",
```r
m * m # standard element-by-element
m %*% m # matrix multiplication
```
)
== Matrix Operations
You can sum all columns or rows using their respective functions
#code(
lang: "",
```r
colSum(stock.matrix)
rowSum(stock.matrix)
```
)
There exists a mean function for matrices aswell
#code(
lang: "",
```r
rowMeans(stock.matrix)
colMeans(stock.matrix)
```
)
You can also add columns & rows to an already existsing matrix
#code(
lang: "",
```r
fb <- c(111,112,322,344,123,532,232)
tech.stocks <- rbind(stock.matrix,fb)
```
)
#show link: underline
For more operations consult a cheat sheet that is available under #link("https://idea.rpi.edu/sites/default/files/2022-09/RMatrixAlgebra_Cheatsheet.pdf")[
this link
]
== Selection and Indexing
Selecting a matrix is generally done with `mat[rows, cols]` and leaving a field empty will select all its members.
#code(
lang: "",
```r
mat[,1] # selects all rows from the 1st column
mat[2,] # selects all columns from the 2nd row
mat[1:3,] # selects all columns out of the 1st, 2nd and 3rd rows
```
)
== Factor & Categorical Matrices
The factor function is used for categorizing vectors and can be used as follows
#code(
lang: "",
```r
temps <- c("cold", "hot", "med", "hot", "hot", "cold" "hot")
fact.temp <- factor(temps, ordered = T, levels = c("cold", "med", hot))
# then you can call the summary function to get the frequencies of each level
summary(fact.temp)
```
)
= Data Frames
There's alot of Data Frames already pre-built in R for experimenting. You can access them using `data()`.
To create one, use `data.frame()` and inside it put a list of vectors.
#code(
lang: "",
```r
df <- data.frame(temp, price, rain) # column labels are the vector names
df <- data.frame(temperature = temp, price.for.service = price, is.raining = rain) # manually name columns
```
)
The `head()` and `tail()` functions return the beginning and end rows of a data frame respectively.
#code(
lang: "",
```r
head(state.x77) # first six rows
tail(state.x77) # last six rows
```
)
You can use the `str()` function to return the structure of a data frame and use the `summary()` function for a nicely formatted summary of each column including the mix/maxes, quartile ranges, means and medians. So essentially a numeric box/whisker plot.
#code(
lang: "",
```r
summary(state.x77)
```
)
== Selecting & Indexing
It works like selecting & indexing matrices, but with the addition of label selection.
#code(
lang: "",
```r
df[,"rain"] # selects all the rows in the "rain" column
df[2,] # selects all the columns in the 2nd row
```
)
There is a distinction between single and double brackets. Single brackets return a data frame and double brackets (`[[]]`) return a vector.
You can also access the columns with `df$rain` as a shorthand. This is the most common way of grabbing columns from data frames.
There exists the `subset()` function that allows for extracting chunks of a df based on a certain condition
#code(
lang: "",
```r
subset(df, subset = rain == T) # only outputs rows where rain is true.
```
)
To order a dataframe, you use the `order()` function to create an order hierarchy for ordinal values
#code(
lang: "",
```r
temp <- c(22, 32.4, 28.2, 32.9)
df <- data.frame(temp)
sorted.temp <- order(df['temp']) # 4 2 3 1
desc.temp <- order(-df['temp']) # 1 3 2 4
df[sorted.temp,] # returns the indexed elements in the ascending order.
```
)
== Data Frame Operations
There's `csv` support for data frames, you can read from them and write to them:
#code(
lang: "",
```r
df <- read.csv("some_file.csv")
write.csv(df, file = "export_file.csv")
```
)
To get information about certain aspects of a data frame, you can use the following methods:
#code(
lang: "",
```r
ncols(df) # number of columns
nrows(df) # number of rows
colnames(df) # returns all the columnn Labels
rownames(df) # returns the row names (be careful as in large data frames this output will be massive)
```
)
Editing is also allowed using assignments
#code(
lang: "",
```r
df[1,2] <- TRUE
```
)
To create new columns, you can use the dollar sign shorthand I briefly mentioned earlier
#code(
lang: "",
```r
df$newcol <- 2*df$temp
```
)
Also, excluding rows & columns from a selection is possible with a negative sign
#code(
lang: "",
```r
df[-2,] # selects every row except the 2nd
```
)
= Lists
Lists allow combinations of data types. They are straight forward and don't require a deeper explaination
#code(
lang: "",
```r
v <- c(12, 32, 44)
m <- matrix(1:100, ncols=5)
df <- mtcars
my.list <- list(the.vector = v, the.matrix = m, cars = df)
```
)
You can essentially query them as you would data frames using `my.list[1]`, `my.list['the.vector']` or `my.list$the.vector`. The bracket notation returns a list, and then dollar sign returns a vector. You would have to use double brackets (`my.list[[1]]`) to return a vector without using a dollar sign.
= Data I/O
This chapter focuses on the different ways of inputting and outputting data such as *csv*, *excel* or *sql*.
== CSV Files
CSV stands for "comma seperated values" and is one of the most common ways of receiving data for further analysys.
As mentioned in the "Data Frames Operations" section, you can read from a csv and write to a csv using the following syntax
#code(
lang: "",
```r
write.csv(mtcars, file='some_file.csv')
ex <- read.csv('another_file.csv')
```
)
Whenever you read a csv, you will get a data frame so all the data frame operations apply for csv imports.
== Excel Files
You can either use the *readxl* and *writexl* from tidyverse or use an older library, which isn't as easy to use. I'll use *readxl*.
First, you have to install the library by executing `install.packages("readxl")` inside of the console and typing `library(readxl)` to load it up.
Then you'll have to use the `excel_sheets("path")` function to output the available sheet names and then call `read_excel("path" sheet = "somesheet")` to save it to a Data Frame. For example
#code(
lang: "",
```r
excel_sheets('sample-sales-data.xlsx') # "Sheet1"
df <- read_excel('sample-sales-data.xlsx', sheet = "Sheet1")
```
)
You can also download an entire workbook (multiple sheets) into a "list":
#code(
lang: "",
```r
entire.workbook <- lapply(excel_sheets('sample-sales-data.xlsx'), read_excel, path='sample-sales-data.xlsx')
```
)
This applies the `read_excel` function on every sheet from the sample-sales-data file and puts it into a list, so `entire.workbook[[1]]` returns the first sheet.
To write to an excel file, you need to install an additional library: `install.packages('xlsx')`. Then, you'll need to load it up using `library(xlsx)` and finally write the following:
#code(
lang: "",
```r
write.xlsx(mtcars, 'output_example.xlsx')
```
)
== SQL
There's alot of SQL-flavors, so this section is going to focus on the general approach of finding out how to connect R with an SQL-database.
The *RODBC* library is one way of connecting to databases. Regardless of what you use, it is highly recommended that you first google your database choice + R. Here's an example use of RODBC:
#pagebreak()
#code(
lang: "",
```r
install.packages("RODBC")
library(RODBC)
myconn <- odbcConnect("Database_name", uid="User_ID", pwd="<PASSWORD>")
dat <- sqlFetch(myconn, "Table_name")
querydat <- sqlQuery(myconn, "SELECT * FROM table")
close(myconn)
```
)
Here are some general tips for most common SQL-flavors:
- *MySQL* - The RMySQL package
- *Oracle* - The ROracle package
- *JDBC* - The RJDBC package
Like already mentioned, consult Google or ChatGPT for your individual SQL-flavor.
== Web Scraping
To fully understand web scraping in R, knowledge of basic HTML and CSSis required. Furthermore, you need to understand the pipe operator (%>%), which is the same as "|" in unix, so essentially chaining commands with their inputs and outputs.
The first step is to open up "inspect element" and figure out what information you want to scrape and how it's structured.
Then the 'rvest' library needs to be installed and we can scrape an imdb-page using it.
#code(
lang: "",
```r
install.packages('rvest')
library(rvest)
lego_movie <- read_html("http://www.imdb.com/title/tt1490017")
rating <- lego_movie %>%
html_nodes("strong span") %>%
html_text() %>%
as.numeric()
cast <- lego_movie %>%
html_nodes("#titleCast .itemprop span") %>%
html_text
...
```
)
A powerful feature of 'rvest' is that you can view demo scrapes to see more use cases under `demo(package='rvest)`. Then, a list of topics will display, choose one and call `demo(package='rvest', topic='yourtopic')`.
= Programming Basics
This chapter covers the basic programming syntax in R.
== Logical Operators
The AND operator is found under the symbol "&", the OR operator is the symbol "|" and the NOT operator stays "!".
#code(
lang: "",
```r
(x < 20) & (x > 10)
(x < 10) | (x > 100)
!(x = 10) & (x != 100) # both ways are valid
```
)
== If Statements
They are identical to Java if-statements:
#code(
lang: "",
```r
if (x == 10) {
print("X is equal to 10")
} else if (x == 12) {
print("X is equal to 12")
} else {
print("X is something else")
}
```
)
== While Loops
They are identical to Java while-loops:
#code(
lang: "",
```r
while (x<10) {
x <- x+1
if (x == 10) {
# useless but I wanted to show how to break
break
}
}
```
)
== For Loops
They are very similar to Java for-loops
#code(
lang: "",
```r
v <- c(1,2,3)
for (variable in v) {
print(variable)
}
for (i in 1:10) {
print(i)
}
```
)
== Functions
They are similar to JavaScript functions, although not exactly the same:
#code(
lang: "",
```r
hello <- function(name="Frank") {
print(paste("Hello", name))
}
hello("Alex") # "Hello Alex"
hello() # "Hello Frank"
add_num <- function(num1, num2) {
my.sum <- num1 + num2
return(my.sum)
}
result <- add_num(4,5) # 9
```
)
You can also create anonymous functions (similar to lambdas) that you can use e.g. in apply functions (discussed later)
#code(
lang: "",
```r
result <- sapply(v, function(num){num*2})
```
)
= Intermediate R Programming
This chapter discusses the R-specific and generally more advanced programming features.
== Built-in R Features
- `seq(0,100,by=2)` - generates a sequence, takes in the starting value, ending value end the step size.
- `sort(v, decreasing = T)` - sorts a vector (increasing order by default), works on characters aswell.
- `rev(v)` - reverses an object.
- `str(mtcars)` - shows you the structure of an object.
- `summary(mtcars)` - already mentioned statistical summary of an object.
- `append(v1,v2)` - merge objects together.
- `is.` - checks the data type, e.g. `is.vector(v)`
- `as.` - converts the data type, e.g. `as.list(v)`
== Apply
Apply is essentially a for-each loop. For example, the `lappy` (list-apply) function takes in a vector and a function with a parameter input and "applies" the function to each vector element and returns the result as a list:
#code(
lang: "",
```r
v <- c(1,2,3,4,5)
addrand <- function(x) {
ran <- sample(1:100, 1) # takes one randon sample out of a vector
return (x+ran)
}
result <- lapply(v, addrand)
print(result)
```
)
There are also other apply methods (that stem from `lapply`)
- `sapply()` - simple apply, preserves the dimensions, usually outputs a vector.
- `apply()` - used for data frames & matrices, additional parameter "MARGIN" (1 - rows, 2 - columns)
- `vapply()` - similar to sapply, but you can specify the type of the return value (FUN.VALUE = integer(1))
- etc.
You can also use anonymous functions as discussed in the "Functions" section.
== Math Functions
- `abs()` - computes the absolute value
- `sum()` - returns the sum of all the elements present in the input.
- `mean()` computes the arithmetic mean (average)
- `round()` rounds values (additional arguments to nearest).
For further math functions reference the R reference card
== Regular Expressions
There are two functions to use: `grep()` and `grepl()`. One returns an index (used for vectors, lists, etc.) and one returns a logical (boolean, used for actual strings)
#pagebreak()
#code(
lang: "",
```r
text <- "Hi there!"
grepl('there', text) # TRUE
grepl('dog', text) # FALSE
grep('b', c('a', 'b', 'c')) # 2
```
)
== Dates and Timestamps
There exists a `Sys.Date()` function that returns the current date, and a `as.Date()` function that converts text into a date. You can pass in a format argument for converting the date.
#code(
lang: "",
```r
my.date <- as.Date("Nov-03-90", format = '%b-%d-%y')
```
)
The formatting options for dates are comprised of:
- `%d` - Day of the month (decimal)
- `%m` - Month (decimal)
- `%b` - Month (abbreviated)
- `%B` - Month (full name)
- `%y` - Year (2 digits)
- `%Y` - Year (4 digits)
If you want a date including the hour, minute, second and timezone, use `POSIXct`:
#code(
lang: "",
```r
as.POSIXct("11:02:03", format="%H:%M:%S") # "2024-08-26 11:02:03 GMT+2"
```
)
|
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Reading/跟李沐学AI(论文)/如何读论文.typ | typst | ---
order: 1
---
#import "/src/components/TypstTemplate/lib.typ": *
#show: project.with(
title: "d2l_paper",
lang: "zh",
)
- 李沐的 d2l 课程看完了,但是比较粗略,而且没怎么记笔记,但总归对代码更加熟悉了
- 李沐的读论文系列则希望更加深入地去理解,稍微做点笔记,不会太详细(对着视频一句句抄),而主要对不懂的东西做记录
- 部分内容源自 #link("https://github.com/CSWellesSun/CSNotes/tree/8e3e33b111c2ad7fc098d3ec40b7616fa6eb7635/%E8%B7%9F%E6%9D%8E%E6%B2%90%E5%AD%A6AI")[CSWellesSun 的笔记]
= 如何阅读论文
- 一般的结构
1. title
2. abstract
3. introduction
4. method
5. experiment
6. conclusion
- 三遍读
+ 第一遍:标题摘要结论。可以看一眼 experiment 中的图表,瞄一眼 method
+ 第二遍:对整个文章过一遍,证明公式忽略,图表要细看,和其他人工作的对比,圈出引用的文章。
+ 第三遍:每句话都要理解,如果是我来做应该怎么做,哪些地方可以往前做 |
|
https://github.com/EGmux/ControlTheory-2023.2 | https://raw.githubusercontent.com/EGmux/ControlTheory-2023.2/main/classNotes/dicasDeProva.typ | typst | #set heading(numbering: "1.")
= Routh-Hurwitz
== If a pole exist in left semiplane then it's a unstable system
== Poles must appear in even lines for the Routh-Hurwitz
== Signal change overwrite every other "minor rule"
== Signal change implies pole in right semiplane
== Every pole in the imaginary axis must have a counterpart
$->$ multiplicity of 2
== Null line appears only if a polynomial divides another
$->$ always appear in odd degree polynomial
#line(length: 100%)
#line(length: 50%, angle: 90deg)
|
|
https://github.com/kdog3682/2024-typst | https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/chess-demo.typ | typst | #import "./fen.typ": fen
= Demo of the Chess Package
Example of #link("https://en.wikipedia.org/wiki/Forsyth-Edwards_Notation")[FEN (Forsyth-Edwards Notation)]
usage:
#fen("rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2")
|
|
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/networks/quiz1.typ | typst | #import "template.typ": *
#show: template.with(
title: "Quiz 1 Notes", subtitle: "14.15")
#set heading(numbering: "1.1")
= Introduction
This study guide will be based on the important equations given in class, and
will step through each of them one at a time. Any miscellaneous information
will be shown at the end of the notes.
= Clustering
Clustering measure the extent to which my friends are friends with each
other.
== Individual Clustering
$ "Cl"_i(G) = (|(j, k) in N_i (G)^2 | (j, k) in E|) / (|(j, k) in N_i (G)^2 |
j != k|) $
In the above formula, $N_i (G)$ represents the neighbors of node $i$ in a
graph $G$ with edges $E$
The numerator can be interpreted as the number of triangles involving $i$,
while the denominator is the number of potential triangles centered at $i$. A
triangle is "potential" if $(i, j), (i, k) in E$, but not necessarily $(j, k)
in E$. Conceptually this leads to this formula representing the chance that
two of $i$s neighbors are also neighbors.
== Overall Clustering
The formula remains almost identical to the individual clustering algorithm
above, however one notable change is that the numerator and denominator are
both summed up across all possible nodes. This leads to the simpler formula:
$ "Cl"(G) = (3 dot "Triangles") / ("Connected Triples") $
= Centrality
== Betweenness Centrality
$ C_i^B (G) = binom(n - 1, 2)^(-1) sum_({k, j} in binom(V, 2) : i in.not {k, j}) (P_i (k, j)) / P(k, j) $
In the above notation, $P$ represents the shortest path and $P_i$ represents the shortest path including $i$. For the purposes of summation, $0 / 0 = 0$. This value can be taken as the average over all vertices, the proportion of shortest paths which pass through that given vertex.
== Eigenvector Centrality
#define(
title: "Eigenvectors and Eigenvalues"
)[
An eigenvalue $lambda$ for a matrix is a vector which satisfies the equation $|g - lambda bold(I)| = 0$
An eigenvector $v$ with respect to an eigenvector is a scalar which satisfies the equation $g v = lambda v$
]
The eigenvector centrality of a node is equal to the sum of the values for its neighbors, and is usually normalized so the total sum is $1$. For strongly connected graphs, this measure will always exist, and is defined by:
$ g'C^e (G) = lambda C^e (G) $
Where $lambda$ is the largest eigenvalue of the adjacency matrix $A$. Because of what the Perron-Frobenius theorem says about irreducible non-negative matrices, the largest eigenvalue will always be positive, and its associated eigenvector will have all positive values as well.
#define(
title: "DeGroot Learning Model"
)[
In the DeGroot social learning model with matrix $T$, the eigenvector centrality of the transpose is equal to the long run influence vector $s$
]
== Katz-Bonacich Centrality
The centrality described above is not as well defined for nodes who are not part of an SCC nor an out-component of an SCC. Thus we solve this problem by giving each node some amount of centrality $beta$ for free. The final simplest form of this equation is listed below.
$ c = beta (I - alpha A^T)^(-1) bold(1) $
Where $alpha = 1 / lambda$, also known as the decay parameter. $beta$ is usually standardized so that it takes on the value of $beta = 1$
== PageRank
PageRank attempts to solve one of the core issues of Katz-Bonacich, which is that a unpopular page linked to by a very popular page is given too much importance compared to what it actually should be.
$ c = (I - alpha A^T D^(-1))^(-1) bold(1) $
Where $D$ is the diagonal matrix whose $i$th entry is $max{d_i^("out"), 1}$
== Leontief Inverse
The Leontief inverse is part of both of the above equations, and represents:
$ Lambda = (I - alpha A)^(-1) $
We can $Lambda_(i j)$ as the sum over all length $l$ paths from $i$ to $j$, with the value of the walk being discounted by a factor of $alpha^l$. Therefore, the longer the path is, the less it counts towards the overall evaluation. We can express this intuition in a more formal sense by writing:
$ Lambda = bold(1) + alpha g bold(1) + alpha^2 g^2 bold(1) + dots $
= Random Graph Models
== Erdos-Renyi
Refers to the random graph model where each possible edge forms with independent probability $p$
The threshold at which a giant component (a connected component with more than half the nodes) appears in the graph is $p(n) = 1 / n$. The threshold at which the entire graph becomes connected is $p(n) = log(n) / n$. The expected fraction $q$ of nodes in the giant component is given by the following, assuming that $p = lambda / n$
$ q approx 1 - e^(-lambda q) $
The fraction of people who get sick in the SIR model is equal to the size of the giant component in this model where $lambda = R_0$. The assumption is that one of the initial people who are infected will eventually be a part of the giant component.
== Reproduction Number
$ EE[d^2] / EE[d] - 1 = (angle.l d^2 angle.r) / (angle.l d angle.r) - 1 $
This quantity represents the expected number of neighbors your neighbor has, other than you. A giant component only exists if this value is at least $1$
The *conditional mean degree* is equal to the left term, which is the expected degree of a node when we pick an edge uniformly at random, then pick one of its two constituent nodes uniformly at random. In the Erdos-Renyi model, the reproduction number is equal to $lambda$
= Diffusion Models
We refer to states of individuals as susceptible (*S*), infected (*I*), or recovered (*R*). The recovered state means that they person can no longer become infected, either because they have an immunity or because they have died.
== SI
#define(
title: "Bass Model"
)[
Define $p$ to be the innovation rate and $q$ to be the imitation rate. The total fraction of the population that have adopted the technology at time $t$ is given by $F(t)$. The model is then defined by:
$ F(t + 1) - F(t) = (1 - F(t))(p + q F(t)) $
This can be interpreted as, the difference between two timesteps is equal to the fraction people who have not yet adopted the invention, multiplied by the sum of
+ Those who adopt it by themselves (innovation)
+ Those who meet an adopter (imitator)
]
The SI model is a particular example of this case, where we have $p = 0$ since you can only get sick if you come into contact with someone else who is sick.
The sum of $p + q$ shapes how fast the innovation will diffuse, while the ration $q / p$ determines what the shape of the adoption curve looks like. If $p > q$ then the adoption curve is *concave*, otherwise it is *shaped*
== SIR
The SIR model has two parameters:
- The transmission rate $beta$
- The recovery rate $gamma$
Thus the equation for the update of the infected population looks like:
$ I(t) = beta S(t) I(t) - gamma I(t) $
The basic reproduction number is $beta / gamma = R_0$
SIR defines the threshold for herd immunity of a homogeneous-agent SIR to be
$ S(t) = 1 / R_0 $
$R_0 (angle.l d^2 angle.r) / (angle.l d angle.r) < 1$ means that the infection cannot rise in a heterogeneous society. The opposite is also true if it is greater than $1$
== SIS
Susceptible-Infected-Susceptible (SIS) defines the steady-state infection level in a homogeneous-agent SIS mode to be:
$ I = cases(1 - 1 / R_0 "if" R_0 gt.eq 1, 0 "if" R_0 lt 1) $
|
|
https://github.com/HKFoggyU/hkust-thesis-typst | https://raw.githubusercontent.com/HKFoggyU/hkust-thesis-typst/main/hkust-thesis/layouts/refmatter.typ | typst | LaTeX Project Public License v1.3c | #import "../imports.typ": *
#let refmatter(
// i-figured settings
show-equation: i-figured.show-equation,
show-figure: i-figured.show-figure,
reset-counters: i-figured.reset-counters,
// 标题字体与字号
heading-font: "Times New Roman",
heading-size: (12pt,),
heading-weight: ("regular",),
heading-top-vspace: (20pt, 4pt),
heading-bottom-vspace: (20pt, 8pt),
heading-pagebreak: (true, false),
heading-align: (center, auto),
config: (:),
..args,
it,
) = {
// 1.2 处理 heading- 开头的其他参数
let heading-text-args-lists = args.named().pairs()
.filter((pair) => pair.at(0).starts-with("heading-"))
.map((pair) => (pair.at(0).slice("heading-".len()), pair.at(1)))
// 2. 辅助函数
let array-at(arr, pos) = {
arr.at(calc.min(pos, arr.len()) - 1)
}
// 4. 处理标题
// 4.2 设置字体字号并加入假段落模拟首行缩进
set heading(numbering: none, supplement: "")
// show heading: reset-counters(equations: true)
show heading: it => {
set text(
font: constants.font-names.title,
size: constants.font-sizes.title,
)
v(array-at(heading-top-vspace, it.level))
[#upper(it.body)]
do-repeat([#linebreak()], 2)
// v(array-at(heading-bottom-vspace, it.level))
}
// 4.3 标题居中与自动换页
show heading: it => {
if (array-at(heading-pagebreak, it.level)) {
// 如果打上了 no-auto-pagebreak 标签,则不自动换页
if ("label" not in it.fields() or str(it.label) != "no-auto-pagebreak") {
pagebreak(weak: true, to: if config.twoside { "odd" })
}
}
if (array-at(heading-align, it.level) != auto) {
set align(array-at(heading-align, it.level))
it
} else {
it
}
}
show heading: it => {reset-counters(it, equations: true)}
// ref matter page numbering
set page(numbering: "1")
it
} |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/038%20-%20War%20of%20the%20Spark/006_Ashes.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Ashes",
set_name: "War of the Spark",
story_date: datetime(day: 12, month: 06, year: 2019),
author: "<NAME>",
doc
)
#align(center)[#strong[I.]]
So a lot of things had gone well. The Izzet's Beacon, the Immortal Sun, the Planar Bridge, and the flow of Eternals from Amonkhet had all been shut down. Every guild had joined the fight, and Mister Fayden, Mister Karn, Miss Samut, and Mister Sarkhan Vol had even returned from Amonkhet with an impressively large spear, the property of a God named Hazoret, which had already proven useful in battle. Two of the four God-Eternals—plus any number of normal-sized creepies—had been destroyed. And best of all, #emph[Hekara was alive again!] All good stuff, you know?
But it wasn't all sunshine and light, either. In fact, there was no sunshine at all. Bolas's so-called Elderspell had created a vast storm of magic, dropping all of Ravnica into an artificial night punctuated by the stolen Planeswalker Sparks that rocketed like comets toward Bolas and the mystic gem floating between his horns, feeding the dragon and his power. Many Planeswalkers had lost those Sparks and their lives to the Eternal army that still occupied our world. The attempt to kill Miss Raven-Hair, Liliana Vess, had failed, and that necromancer still controlled those Eternals for Bolas. And, of course, the new Living Guildpact—Master Niv-Mizzet, the Firemind—lay catatonic on the ground amid the ruins of the embassy, all his mystic energy expended on the killing of just one of the God-Creepies.
And there was <NAME>, himself. The Elder Dragon still sat upon his throne, as if none of our efforts amounted to anything at all.
Most of us were back at the Azorius Senate House, for our second summit of this one incredibly long, incredibly horrific day.
<NAME> was once again addressing the crowd of Planeswalkers, guilded Ravnicans, and me: "It was always going to come down to battle. Trying to resurrect Niv-Mizzet was a worthwhile endeavor, but even with his help, it would still have come down to a fight. So, all right, we don't have the Firemind's help. But things are far from hopeless here. We've thinned the Eternal herd. Destroyed half the dragon's God-Eternals. Now we need to finish this by using Blackblade on Bolas."
He spoke with such confidence, such authority, that he was pretty darn reassuring, you know?
"The plan, this time, is simple enough. For the moment, Bolas has pulled back the bulk of his forces to his Citadel. So we'll respond by launching a massive two-pronged attack. On the ground, every guildmember, every Planeswalker—hell, every Ravnican who can hold a weapon—will launch a full-frontal assault. Everything we've got. All at once. Everyone. Unless you can fly or can hitch a ride on something that does. Next, while the ground assault keeps the Eternals busy, Aurelia, me, and the rest of our combined air forces will engage from above. I'll make use of my invulnerability to get in close. Then I'll stab Bolas with Blackblade. And it will all be over." He made it sound really simple, really easy.
#emph[Too easy] ~
I heard <NAME> ask Mistress Lavinia for a sword.
<NAME> pulled him aside and said, "You're not a fighter."
"We're all fighters today."
The Gatewatch, meanwhile, was making a bit of a show over the renewal of their Oaths. Mister Jura began, raising Blackblade high once more and saying: "Never again. Not on any world. This I swear: for Sea Gate, for Zendikar, for Ravnica and all its people, for justice and peace, #emph[I will keep watch] . And after Bolas falls, when any new danger arises to threaten the Multiverse, I will be there with the Gatewatch beside me."
I thought maybe they'd all have a common Oath, but <NAME> was briefer: "Never again. For the sake of the Multiverse, #emph[I will keep watch] ."
#emph[Right. Variations on a theme. That keeps it more interesting, at least.]
<NAME> stepped forward and spoke: "Every world has its tyrants, following their own desires with no concern for the people they step on. So, I say, never again. If it means folks can live in freedom, #emph[I will keep watch] . With all of you."
<NAME> intoned: "From time out of mind, the strong have plagued the weak. Never again. For the lost and forgotten, #emph[I will keep watch] ."
Then, smiling at the others, <NAME> growled out: "I have seen tyrants whose ambitions knew no limits. Creatures who styled themselves gods or praetors or consuls but thought only of their own desires, not of those they ruled. Whole populations deceived. Civilizations plunged into war. People who were simply trying to live made to suffer. To die. Never again. Until all have found their place, #emph[I will keep watch] ."
Finally, these five turned to look at <NAME>. She seemed, as usual, reluctant to speak. Then she glanced at <NAME>, who was biting her lip and looking back at her with trepidation.
The elf smiled then. It came and went in an instant, but I caught it. She took a step forward and spoke in a soft clear bell-like voice: "I have seen a world laid waste, the land reduced to dust and ash. Left unchecked, evil will consume everything in its path. Never again. For Zendikar and the life it nurtures, for Ravnica and the life of every plane, #emph[I will keep watch] ."
<NAME> smiled happily. And she wasn't the only one. The six Oaths were more than a little inspiring.
<NAME> looked across the crowd and asked, "Anyone else?"
Folks snuck glances at one another or looked at the ground. <NAME> smirked a little. <NAME> crossed his massive silver arms. For a second it looked like <NAME> was about to speak—before losing her nerve. No one stepped forward. No one spoke.
Teyo and I exchanged looks. I thought he'd make a great Gatewatcher, but he didn't have the confidence to step up, not because he was afraid to fight for folks—but because he didn't think he was qualified to do that fighting alongside these big-time heroes.
I whispered, "They'd be lucky to have you."
"I don't know," he whispered back. "What about you?"
I laughed. "You can't protect the Multiverse if you're stuck on one plane and if your teammates can't see or hear you, right?"
He nodded reluctantly and said, "Well, if they won't take you, then I don't want to join."
I punched him for that one.
"Ow."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[II.]]
I spotted <NAME> and <NAME> grabbing <NAME> by the arm and guiding her away from the crowd. Curious, I followed them behind the stony corpse of Mistress Isperia to, you know, eavesdrop.
#emph[Look, it's just kinda my thing.]
"What?" she demanded loudly.
<NAME> gestured with his hands for her to lower her voice.
She took a breath and asked, "What is it?" in a considerably lower tone.
<NAME> said, "We have a special job for you. We want you to return to New Prahv and turn the Immortal Sun back on."
"What?" she yelled again. "Do you know how hard it was to turn the damn thing off?"
The three of them exchanged glances that stopped her outrage in its tracks.
She leaned in and whispered, "You don't trust the other Planeswalkers not to run away."
<NAME> shook his head. "That isn't it. We need the Sun to do the job it was created for. To prevent Bolas from bolting."
<NAME> agreed: "One way or another, this ends today."
"Well, then send someone else," she said. "Because you're crazy if you think I'm going to miss this fight."
#figure(image("006_Ashes/01.jpg", width: 100%), caption: [Chandra, Fire Artisan | Art by: <NAME>], supplement: none, numbering: none)
<NAME> actually chuckled then. "Neither of us thought that for a moment."
<NAME> said, "Take whomever you need. Get the Sun up and running, and leave a strong guard. Then we'll welcome you to the battle."
"I don't know," she groused. "Bolas wants the Sun turned on. I'm not even sure this is a good idea."
"Sounds like a good idea to me." All four of us turned and looked up. <NAME> was sitting on Mistress Isperia's back, sporting a big grin. "Sorry. Didn't mean to eavesdrop."
Miss Nalaar scoffed. "Look where you're sitting. Of course you meant to eavesdrop."
"Well, yeah. I see the mighty Gatewatch sequester themselves behind the dead sphinx, and I get a little curious."
#emph[See, it's not just me. Maybe it's just a thiefy kinda thing.]
"Just a little?" <NAME> asked with a raised eyebrow.
"Just a little," <NAME> confirmed. "Look, I know I'm not part of this strategy session, but I'm gonna throw in my two zinos all the same. No one wants to go through this again. And if Bolas gets away, you know we'll all have to. I'm with the big guy," he nodded toward <NAME>. "One way or another, this ends today."
The other men turned to <NAME>. Her shoulders sank. "Fine," she said.
I watched her gather <NAME>, <NAME>, and a small squadron of the toughest rank-and-file guildmembers she could find. They set off for New Prahv.
<NAME> and I watched them go. He nodded and spoke under his breath: "Good luck, ladies."
Then he turned and walked away, saying, "There's a humongous golden trinket a couple blocks away, and instead of going after it, #emph[I'm] off to fight an Elder Dragon. Some thief~"
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[III.]]
Our small army marched toward Tenth District Plaza in near silence.
I guess everyone was thinking her or his own grim thoughts. They all pretty much had more to lose than I did, I think. I mean, I had no Spark to harvest, and the Eternals couldn't see or hear me. I was probably in way less danger than most.
On the other hand, I had only a handful of people in my life. If I lost even one—the way I thought I had lost Hekara that very morning—my world would shrink immeasurably. (It wasn't likely anyone else I cared about could get resurrected.) But understanding that was half the battle, you know? If I was a little bit~#emph[invulnerable] , I'd use that to make sure my friends and family stayed alive and safe.
So maybe I was actually feeling a little more confident than the rest, as Teyo and Mistress Kaya and Hekara and everybody crossed the city. I saw Queen Vraska approach <NAME> from behind and wanted to test my theory about those two.
#emph[Besides, I'm on an eavesdropping roll] ~
"Jace," she said, choking out the word.
He turned, stopped, and smiled. He gently wrapped a hand around the back of her neck and leaned his forehead against hers. "Hello, Captain," he whispered. Whispered it so quietly, in fact, that if I hadn't completely invaded their personal space, I never would have heard it.
She whispered back, "You don't know what I've done."
He said, "I do, actually. But it's not your fault. You didn't have your full memories, and I arrived too late."
She leaned her head away from his and whispered again: "You definitely arrived too late. But the truth is I #emph[did] have all my memories. And it changed nothing."
He shrugged. "Look," he said, "I already tried to kill one ex today. Can we table the angst until Bolas is dead or we are?"
She smiled ruefully. "Oh, am I an ex now?"
#emph[I knew it!]
"I hope not," he said, looking panicked.
"Don't we have to be an item before we can be exes?"
"I hope so," he said. "Um, the first part, not the second." He looked so vulnerable. Kinda brought Teyo to mind for some reason.
She said, "So tomorrow we give it a try~after Bolas is dead or we are?"
"Either way?"
"Either way."
He nodded. "Agreed. But again, I'm hoping for the first option, not the second."
"Agreed."
She took his hand, which caused <NAME> to glare at them both. <NAME> smiled and offered him a little mocking wave. Then he and the queen walked off hand-in-hand toward whatever what awaited us all~
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[IV.]]
It was so much worse than I had imagined.
We rushed toward the Citadel, most of our forces shouting battle cries. (Though not me. Not much point in shouting a battle cry that no one can hear.) My knives were still in their sheathes, as my mother had insisted I borrow a light battle axe from her. I'm not actually sure if it was an improvement. "Light" or not, it was still a heavier weapon than I was used to, and my arm strength probably isn't what it should be for the daughter of <NAME>. But it made her feel better to see me better armed. And since she #emph[could ] see me and might worry, I complied.
Growing in power—and even stature—by the minute, the dragon still loomed atop his pyramid, his wings spread, that strange gem floating between his horns, still collecting stolen Sparks flying in from fallen Planeswalkers.
Newly fallen Planeswalkers.
Those Planeswalkers #emph[not] fallen—or not #emph[yet ] fallen—were side by side with guild warriors, engaging the silent Dreadhorde.
It was chaos. True chaos. Still, both sides were more evenly matched than we could have hoped. There were fewer Eternals than there had been and—thanks to <NAME>, <NAME>, and the rest—no more reinforcements arriving.
Borborygmos was sweeping the area ahead of him, using two large maces to shatter the creepies left and right. <NAME> fought in the cyclops's shadow, using a hex that magnetized the Eternals' lazotep coating, causing the creepies to crash into each other and, well, #emph[stick] . In their attempts to free themselves, they usually tripped and fell, leaving themselves open to attack. <NAME> would then move in and finish the clump of Eternals off with his sword. It was extremely effective.
<NAME> raced through the Eternal ranks at high speed, sheering off heads with her curved blades. I was too far away to hear her speak, but I knew that with each head removed, another Eternal had been "set free."
#figure(image("006_Ashes/02.jpg", width: 100%), caption: [Samut, Tyrant Smasher | Art by: <NAME>], supplement: none, numbering: none)
<NAME> crossed the battlefield at a steady and determined pace. He had once been a Gruul clan leader, and now, fighting at close quarters, his somewhat barbaric origins—which of course I shared—were on fierce display (though with a Simic twist), as he used a biomantic mace to seize the creepies by whatever remained of their flesh and turn them inside out. The resulting explosions of guts and lazotep were pretty spectacular.
I saw <NAME> swinging a double-headed axe at Eternal after Eternal. And I saw <NAME> crush an Eternal's head between his two metal hands.
<NAME> fought like a demon, using her cutlass like a surgical blade and her gorgon gaze to turn Eternals she didn't slice apart into stone statues. Sometimes, in the heat of things, she did both.
<NAME>, fighting by her side (I think), created multiple illusions of himself to lure Eternals into position for <NAME> or <NAME> or <NAME> to slaughter, while occasionally using his telekinesis to do the job himself.
A troop of Izzet mages were using flamethrowers on the Eternals—and came close to singeing <NAME> in the process. He shouted out a psychic warning that rang loudly in my brain.
#emph[Yikes. So ] that's #emph[what that feels like.]
Nothing at all like my little psychic thing. Wouldn't even know how to do that.
<NAME> created bubbles of slowed time around the creepies, turning them off only when Spearmaster Boruvo or Ari or <NAME> was in position to destroy them.
A vampire Planeswalker was tearing the heads off Eternals with fearsome strength, while a kor Planeswalker shaped spikes out of stone to impale three or four at a time.
Azorius Arresters—not usually my favorite Ravnican feature—were taking out still more Eternals under the leadership of Mistress Lavinia.
Dimir assassins and Rakdos cultists shredded an entire Eternal phalanx.
I mean #emph[everybody ] was out there, working together. It was kinda historic, you know?
#emph[But in a fight like this you don't ] always#emph[ win.]
An Eternal grabbed <NAME> from behind. (I was too busy killing my own creepies and too far away to help, but I saw pretty much everything.) He managed to hex his attacker's lazotep; its magnetized skull wrenched abruptly backward, snapping its neck, leaving its head hanging limply behind its shoulders.
But that was too little, too late. For a second, it almost looked as if <NAME> was disappearing from view, planeswalking away, I guess. But <NAME> must have already succeeded in her mission to reactivate the Immortal Sun. He snapped back into place with the Eternal's fingers still digging into his arm.
He tried to raise his sword to cut off the Eternal's hand but apparently no longer had the strength, not even the strength to hold the sword. It slipped through his fingers and fell to the pavement at his feet.
And then he screamed—loud enough for me to hear it over the din, even from where I was fighting. The Eternal had reached into whatever what made <NAME> who he was, and the Eternal was stealing it away. As Dack's Spark was ripped from him, it looked as if his body was being drained of all fluids, all soft tissue, leaving him as nothing but skin and bones.
The Eternal caught fire and burned. The stolen Spark soared into the air to feed the dragon's gem and the dragon's power.
And <NAME> stopped screaming as his killer's corpse and his own collapsed to the ground together.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[V.]]
I was more determined than ever to protect the people I loved. I figured my parents and godfather could pretty much take care of themselves. I mean, they're trained warriors—and having no Sparks, the Eternals couldn't kill them with a single touch. But Teyo and Mist<NAME> were a different story. They were insanely vulnerable.
As for Hekara~she was deadly enough as a razorwitch, so in theory, she should have been exponentially more powerful as a blood witch. But the truth is, she was always more of an entertainer than a warrior. And on top of that, her resurrection had clearly changed her with regard to me. What if it changed her in other ways, too? What if she wasn't the same badass she used to be?
So I focused on protecting those three.
Surprisingly, I didn't have to worry too much about Teyo, who had really come into his own. Maybe he didn't have much in the way of offensive ability—beyond tossing an occasional mini-sphere of solid light at an opponent—but he was alert and quick and ready with his shields to defend all among our ranks who found themselves in trouble.
And then suddenly the boy with little offensive ability discovered he could use his shields as a battering ram, smashing the creepies back and setting them up for Borborygmos or Mister Vorel or Miss, uh~Miss Werewolf.
Mistress Kaya, meanwhile, already had some protection. Flanked by Chief Enforcer Bilagru and another Orzhov giant, I saw her plunge her two long ghost daggers into a couple of the creepies' brains.
But she was spending a lot of time in her ghost form, and that seemed to wear her down. She'd pass through an Eternal, materialize her hand and stab her ghost blade through its skull. Then she'd ghost her hand while materializing her feet, as she moved in on another of the creatures. But the urgency and the threat and the myriad distractions inherent to the battle made her reckless and, to my eye, increasingly exhausted. I tried to have her back, walking up to Eternal after Eternal and ending them with my borrowed axe without ever being noticed by anyone but her.
"Well," I shouted over the din, "growing up among the Gruul oughta count for something! And growing up with my particular condition occasionally counts for a lot more!"
I spent a good deal of time protecting Kaya—but a good deal more protecting Hekara. I kinda shadowed my girl, who actually held her own quite nicely for a dead woman~and never really needed to know how many times I took out a creepy looking to attack her from behind.
#emph[So maybe she can't see me, but I can see her and see to it she's safe. It's something, you know? Or at least it's not nothing.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[VI.]]
I felt a little like I was trapped in one of Mister Teferi's time bubbles. Everything happened so fast, and yet everything seemed to simultaneously take place in slow motion. The battle was flying by. The battle seemed endless. It was hard to keep track of the passing minutes, let alone the passing seconds.
I had no idea how long we'd already been fighting when a horn sounded, and I looked up to see the great Boros airship #emph[Parhelion II ] advancing across the sky. Angels descended from its decks. (Including one rare four-winged angel, leading multiple squadrons, and <NAME>, who was finally getting a chance to scratch that battle itch she had mentioned.) Boros skyknights and Selesnyan equenauts rode upon pegasi, griffins, and eagles. Izzet mages riding flight spheres of mizzium rocketed toward the fray alongside Izzet goblins on sky-scooters and Izzet faeries riding blazekites down. A single small hypersonic dragon flew in side by side with a drakewing, a steam drake, a sapphire drake, a wind drake, and a Simic skyswimmer, who'd normally be trying to eat the others. But not today.
Together they were routing what little remained of the Eternal sky cover. It was then that I spotted Mister Jura riding upon a pegasus. We all saw him, and we all cheered. He was wielding the sword that could bring an end to all this—by bringing an end to <NAME>.
Trouble was~we weren't the only ones paying attention.
I saw Miss Raven-Hair, who looked like she was pantomiming the movements of an archer, raise an imaginary bow, as her tattoos—or whatever they were—glowed with purple light. I looked over at the God-Eternal Oketra, who followed suit with her #emph[all-too-real] giant bow. Miss Vess and Oketra took synchronized aim at Mister Jura. I called out a warning—that absolutely nobody heard, as together, necromancer and God-Eternal let loose a single javelin-sized arrow.
But Oketra's arrow didn't quite find a target in Mister Jura. Instead its six-foot length impaled his mount. The pierced pegasus tumbled out of the sky.
<NAME>, still clutching Blackblade, plummeted along with the beast behind the Citadel and out of view.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[VII.]]
When <NAME> fell, there was a pause in the battle. A hiatus that affected not only our side, but the enemy's, as well. For a moment, the Eternals seemed to inexplicably hesitate. Could Miss Raven-Hair have also been caught off guard? No, that didn't make any sense. She's the one who made Oketra fire her arrow.
The moment didn't last, of course. The battle was rejoined on both sides.
And then someone shouted out, "LOOK! TO THE CITADEL! LOOK!"
I saw the smoke first. Then the flames. Then the massive winged demon with the crown of fire.
Hekara clapped her hands, jingled her bells, and cheered loudly for her unholy guildmaster: "Go get 'im, Boss!" She turned toward <NAME>, Mistress Kaya, and Queen Vraska, shouting, "Toldja he was on board. He #emph[loves ] this plan!"
<NAME>. Defiler. Demon. Guildmaster. Parun. Big as a dragon, with arms and legs muscled and proportioned like a gigantic wrestler. Two sets of horns, one arcing upward, outward, and backward like a steer's, the other arcing down and curving up like those of a humongous ram. Burning yellow eyes. Razor teeth, locked together in a rictus grin. A beard of bone spurs emerging from a wide jaw. Bat wings. Cloven hooves. Blood-red hide clothed in chains and skulls. And his brow, a wreath of flame. Here was an evil to match many another.
#emph[But can he match <NAME>?]
And then I spotted <NAME>, riding atop the demon's head. #emph[Rising up ] within the very flames of Lord Rakdos's crown. Mister Jura's white aura of invulnerability must have been protecting him from the hellfire, but from where I stood, he seemed only to be at the white-hot center of a hellish blaze.
#figure(image("006_Ashes/03.jpg", width: 100%), caption: [Unlikely Aid | Art by: <NAME>], supplement: none, numbering: none)
He still had Blackblade drawn and at the ready, and I jumped up and down, cheering for the hero and the demon, as the latter soared up high and dived down sharply toward the Citadel and its master. The Defiler's roar echoed across the plaza.
The roar was a mistake.
It got Bolas's attention. The dragon turned in time and cast a crippling spell that blasted Lord Rakdos back. But <NAME> leapt over the blast, using the demon's momentum to plunge toward Bolas with Blackblade poised to strike.
I held my breath as Mister Jura, two hands on the hilt, drove the sword down toward the crease between the Elder Dragon's eyes.
I'd been told that sword had already killed a major demon, a God-Eternal, and even an Elder Dragon like <NAME>.
#emph[This is it. This will end it all.]
The blow descended, Mister Jura thrusting the weapon down with all his might~
Blackblade #emph[shattered ] against <NAME>'s invincible brow.
And shattering with Blackblade: the hopes of every living soul on Ravnica.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[VIII.]]
While the dragon laughed, <NAME> fell. He landed hard on the roof of the Citadel. I couldn't tell if he was alive or dead.
I just felt numb.
<NAME> stood over his fallen body. I'd heard—or overheard—that <NAME> and <NAME> had been friends until very recently. I kinda wondered what she was thinking now. But she was too far away for me to read her thoughts or emotions, let alone her expression.
But I wasn't too far away to see her take a few steps forward as dark mana began to swirl around her. And as it swirled, the Eternals—once again—#emph[stopped] fighting us. Instead, they stood at attention for a full five seconds~before all the creepies and the two God-Creepies about-faced to march on <NAME>.
I knew then that Miss Raven-Hair had switched sides. No way to know why—any more than I understood why she had been fighting #emph[for ] the dragon in the first place. But <NAME> controlled the Eternals, and the Eternals had clearly turned on their master, at their mistress's command.
With nothing left to fight, I kinda just stood there stupidly. Watching~
I thought maybe I saw <NAME> shout something at Bolas, but I couldn't make out any words. Whatever she said, I could feel the dragon's stunned confusion waft across my consciousness. Confusion followed by contempt.
I studied Miss Raven-Hair. Something else was going on with her, and at first I couldn't quite figure out whatever what it was. Then it seemed to me like she was glowing from within. Glowing~and dissolving.
Yes, that was it. There was less of her; black flecks and purple sparks were being carried off by the wind. I was watching her flake apart, disintegrate, one little bit at a time.
#emph[That does not seem like a pleasant way to go] ~
Oketra and Bontu—the two surviving God-Eternals—were still trying to get at Bolas, but the dragon radiated pure unadulterated magical energy that kept both at bay.
I glanced back at Miss Raven-Hair, who already had less hair period: it was burning off her scalp in clumps.
And then <NAME> was there, behind her, placing a hand on Miss Vess's shoulder. He was glowing white, and that white glow began to extend to her, over her, around her.
As <NAME> glowed with his pure white light, her form began to bind itself back together. The long black hair flowed down her back again. She was becoming whole.
#emph[But, but] ~
In exchange, her black death was transferring over to him. Now, he sparked and flaked apart, as she had been doing mere seconds ago. He raised his head and, I'm pretty sure I heard him~howl, before bursting into black flame and disintegrating entirely before everyone's eyes. All that remained was a bit of armor that fell at Miss Raven-Hair's feet. Armor and ashes, the latter quickly blowing away on the wind.
#emph[Mister Jura's dead. But, but] ~#emph[he's supposed to be the hero who saves us all, isn't he?]
We all looked to Bolas. Even from ground level, he looked smug.
This time I distinctly heard Miss Raven-Hair cry out in fury as she made a pushing gesture with both arms. Oketra and Bontu advanced in response, approaching Bolas from two sides, while struggling against the rush of power that the Elder Dragon unleashed. Each God-Eternal took a single step toward Bolas—before his power pushed both back #emph[two ] steps.
I pretty much thought we were all doomed.
Then from somewhere, <NAME> called out, "#emph[Look!] "
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[IX.]]
The two-pronged Spear of Hazoret was sticking out through the dragon's chest, blood and viscera clearly dripping from each tine. #emph[His ] blood and viscera. Somehow, that was not enough to kill him, not after all the power, all the Sparks he had absorbed, but it was obvious the injury was significant, and it proved he could still be hurt. So for a second, I felt something like hope again, you know?
The Elder Dragon looked back. Hovering behind him and holding the spear was <NAME>, who thrust the spear farther into Bolas's back; his groan echoed across the plaza.
With a flick of a wing, the Elder Dragon sent the resurrected Firemind flying. He crashed to the ground some miles away.
#emph[So much for hope] ~
Time stood still. And then too late the dragon realized he had forgotten about <NAME>, had given her an opportunity to strike with her own two-pronged weapon.
Her two God-Eternals moved in for the kill and were now right on top of Bolas. The dragon managed to #emph[obliterate ] Oketra.
But perhaps weakened by the effort—or by the spear still sticking out of his chest—he was too slow to stop Bontu, who bit its former master on the wrist.
At once and automatically, Bontu began harvesting all the Sparks the Elderspell had granted the dragon. All of them, all at once. Bontu absorbed these Sparks but could not contain them. She ruptured into shards, exploding in a light so bright, I had to screw shut my eyes.
#figure(image("006_Ashes/04.jpg", width: 100%), caption: [Liliana's Triumph | Art by: <NAME>], supplement: none, numbering: none)
When I opened them again, the first thing I saw was the army of Eternals marching up the steps of the Citadel pyramid toward the dragon. And right behind them a second army of Ravnicans and Planeswalkers. I had to run to catch up.
A vortex of stolen Sparks swirled above Bolas's head. And then, they simply evaporated, each and every Spark dissipating into nothingness.
I was only on maybe the third step by that point, and I watched as Bolas began to dissolve, much as Mister Jura had dissolved moments ago. And also like Mister Jura, the dragon #emph[howled ] as he disintegrated, atom by atom, the particles blowing away with the wind.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[X.]]
It was over. Bolas was simply gone. Only the gem from between his horns remained. I saw it drop to the roof of the Citadel, bounce a couple of times, and roll to a stop not far from Miss Raven-Hair's feet.
The unnatural storm clouds parted and dispersed, giving way to late-afternoon sunlight.
We all stood still, unsure whether we could afford to believe—whether we could #emph[trust] to believe—that the nightmare was over.
Then, spontaneously, a massive cheer went up from the combatants in the plaza, myself included. Spiraling streamers of celebratory green magic flew into the air. All sorts of folks—grown men and women of multiple species—were climbing onto the ruins of the Bolas statue, as if it were a playground for children. Actual children, appearing out of nowhere, were climbing upon the fallen and dormant Vitu-Ghazi (despite my godfather's #emph[hopeless] attempts to chase them off).
#figure(image("006_Ashes/05.jpg", width: 100%), caption: [Planewide Celebration | Art by: <NAME>an], supplement: none, numbering: none)
<NAME> stood alone atop the Citadel now, a veritable wall of unmoving, deactivated Eternals separating her from the Ravnicans and Planeswalkers on the pyramid's steps. Then the crowd snapped out of its collective stupor and, led by Borborygmos and <NAME>-Minotaur, got busy cutting down the Dreadhorde from behind. Hacking them to pieces. Little pieces. The creepies made no attempt to defend themselves as we smashed and chopped them to bits. (I found myself doing it, too.) I kept one eye on Miss Raven-Hair. I knew she could control the Eternals, and I wanted advanced warning if she decided to bring them back to bear—if only to protect herself.
She kneeled. I couldn't see what she was doing. Then she stood up again and, in a cloud of black, planeswalked away.
I couldn't understand this. I had been so sure the Immortal Sun had been reactivated. Wasn't that why <NAME> couldn't escape his fate? But I suppose, with the dragon gone, it must have been shut down all over again.
A Planeswalker in white left next. I saw <NAME> and <NAME> depart with their three-tailed dog (who seemed to turn to stone just before all three vanished). Others, too, whose names I didn't know.
I heard <NAME> called out, "This is not the way! These are my people. They must be destroyed, I know. But not like this. Grant them some dignity."
"That's why we're here," <NAME> said and with a nod toward <NAME>, they began. Under the watchful eyes of the minotaur, the cyclops and the child of Amonkhet, the two pyromancers moved through what was left of the inert Dreadhorde and meticulously burned every last one—every last fragment—down to ashes.
I didn't stay to watch it all. I spent a few minutes searching for my parents. I found them together, in a somewhat embarrassing embrace. I got Ari's attention. She pointed me out to <NAME>. We all hugged. I gave mom her axe. Then I went looking for my friends.
By this time, the sun was sinking behind Ravnica's towers, the ones that were still standing, anyway. Twilight was falling. And not the artificial night of the Elderspell, but the real thing. Twilight. Dusk. With night to follow. And another morning and day after that.
We'd survived.
Or most of us~
All around me, folks were celebrating. And those not celebrating were carrying away the wounded and the dying.
And the dead.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#align(center)[#strong[XI.]]
I don't know where she got the puppets.
Hekara was sitting on a piece of cracked masonry, occupied in the solitary pursuit of celebrating our momentous victory with two uncannily realistic hand puppets: versions of herself and <NAME>. It was a wonderful show being provided for an audience made up entirely of herself and her Rat.
#emph["You're my Rat."]
#emph["I'm your Rat."]
Of course, she wasn't particularly aware of my presence. But I still really enjoyed the performance. She provided the voices for both her hands.
"We beat the evil dragon, didn't we, Hekara?" Puppet Zarek said in a fairly successful, if slightly high-pitched impression of the Izzet guildmaster.
"'Course we did," replied the Hekara puppet, in a strangely affected baritone that sounded nothing whatsoever like Hekara, which was frankly hilarious.
"And all it took was for you to die horribly."
"Sure. But only once. I don't mind dying once. Not every once in a while. You know, for a good cause. Or for the entertainment value."
I could have watched this show for hours, but Teyo cut it short. I don't know how long he'd been standing behind me, but he stepped up to Hekara and said, "Emissary, do you remember your friend Rat? Araithia?"
Hekara said, "Of course, I remember Rat! I love Rat! Where is she?"
It made me so happy, I thought I might cry.
Teyo pointed me out to her. I guess I thought she'd try to focus on me and then maybe learn to see me again.
But she merely looked confused. So Teyo took Hekara's Hekara-puppeted hand in his, and attempted to guide, lead, Hekara over to me.
She hesitated, resisted. She sounded nervous and uncomfortable in a way I'd never heard from her before as she said, "You know, I can't quite remember what Rat looks like. That's sorta strange, isn't it?"
Teyo didn't know what to say. But this wasn't new to me. Even the people who could see me tended to forget me if I stayed away too long. Even my mother—though she'd never admit this—started to forget she ever had a daughter, if I stayed away too long. I guess I hadn't expected it this soon from Hekara. But that's not the same as it coming as a surprise, you know?
So I was grateful when the conversation was interrupted by the leathery sound of wings and the stench of sulfur. <NAME> himself was descending to find his Emissary.
"COME, WOMAN," he said in his booming sepulchral voice, "RAVNICA IS OURS AGAIN. THE LONG BATTLE HAS BROUGHT THE PEOPLE LOW, AND THE CIRCUS MACABRE MUST PLAY TO THE CROWD AND LIGHTEN ALL HEARTS. WE HAVE PERFORMERS TO GATHER, ACTS TO PREPARE, AND A READY-MADE AUDIENCE YEARNING TO FORGET THE DAY'S HORRORS—BY BURNING. BLEEDING AND BURNING."
"Oh, goody," Hekara said, as she allowed herself to be taken up in the demon's hand like a life-sized Hekara puppet ready to mouth her master's words. They flew off together, with Hekara squealing, "Burn! Bleed! Burn!"
Okay, yeah, she hadn't given me a second thought.
#emph[It hurts, all right? It hurts. Is that what you want to hear?]
But then I looked up and saw Teyo looking so stricken. For his sake, I tried to put on a good face. I smiled, shrugged, and said, "I've lost her." But I couldn't maintain the smile. My shoulders fell. My head sank. "I've never lost anyone before. Plenty of people I never had. But she's the first who could see me who I've lost."
As if to add insult to injury, <NAME> chose that moment to nearly walk right into me; I had to sidestep out of her way as she passed.
Teyo looked even more stricken, if that was possible. He spotted Mistress Kaya approaching us and said, "Don't forget, you still have the two of us."
I nodded. I wanted to make him feel better, but I just couldn't bring it off. I said, "Except you're both Planeswalkers. You'll leave Ravnica eventually."
I instantly regretted saying it.
#emph[How does it help to make them both feel bad? Who does it help? Not me, that's for sure. I'd rather my friends be happy, you know?]
We started walking, past the revelers and the bereaved. The War of the Spark was over. All that remained was to pick up the pieces and find a way to start anew.
Eventually, we joined a clutch of Planeswalkers and Ravnicans in the midst of a debate over what to do with the Immortal Sun.
"Destroy the damn thing," said Mister Grumpy-Minotaur.
Miss Rai protested, "But it's an amazing piece of—"
"It's an amazing mousetrap for Planeswalkers. One I've been trapped by twice. And let me make this clear, I've no intention of ever being trapped by it again."
Queen Vraska, her right hand entwined in M<NAME>'s left, said, "Destroying it may be easier said than done. It's made of extremely powerful magics, reinforced by Azor's own Spark."
<NAME> rubbed his stubbly chin. "Besides, the thing might come in handy someday for hunting down and trapping Tezzeret."
"Or <NAME>," <NAME> added.
"Or <NAME>," <NAME> volunteered.
"Or," said <NAME>, "<NAME>."
Both <NAME> and <NAME> flinched when <NAME>-Hair's name was mentioned. Queen Vraska looked at <NAME> with some concern. <NAME> and <NAME> exchanged glances. All of them clearly had a complicated history with the necromancer. It took my mind off my troubles, wondering what that history might be~or what would come of it, in the end.
Nothing had really been decided by the time the rest of the Gatewatch—<NAME> and <NAME>—arrived on the heels of Mistress Aurelia, who was carrying <NAME>'s scorched breastplate like a holy relic.
<NAME> said, "We should bury that on Theros. I think Gids'd like that."
"What he'd like," <NAME> said, "is to know that it's not over."
"It's not over?" Teyo asked, horrified.
M<NAME> chuckled and placed a reassuring paw on Teyo's shoulder. "I do believe the threat of <NAME> has passed. But we cannot pretend Bolas will be the last threat to face the Multiverse. If we truly wish to honor our friend Gideon, we need to confirm that the next time a threat rises, the Gatewatch will be there."
<NAME> looked over at the demolished Embassy of the Guildpact and said, "We lost our clubhouse."
"We don't need a clubhouse. We just need to renew our Oaths."
"Ajani, we all renewed them earlier today." <NAME> sighed, sounding a little exhausted—or perhaps exasperated. "Don't you think once a day is plenty?"
<NAME> scowled. The paw on Teyo's shoulder involuntarily tightened its grip. The leonine didn't actually draw any blood, but Teyo winced.
Mistress Kaya noticed and delicately removed the paw, allowing Teyo to breathe a small sigh of relief.
I couldn't help giggling a little. Teyo and I exchanged smiles.
#emph[He has a very nice smile] ~
Mistress Kaya spoke: "Perhaps~perhaps #emph[I] could take the Oath."
<NAME> looked at her hopefully and said, "Really?"
<NAME> looked at her dubiously and echoed, "Really?"
"I'm not a perfect person~" Kaya began.
"Trust me, none of us are," Mister Beleren interjected ruefully.
Queen Vraska snorted teasingly.
But Mistress Kaya basically ignored them both. "I've been an assassin and a thief. I've had my own moral code, but the first tenet of it was always, 'Watch your own ass.' I have the ability to ghost my way through life, to allow nothing to touch me. That's the literal truth of my powers, but it somehow became my emotional truth, as well. But my time on Ravnica as assassin, thief, reluctant guildmaster, and perhaps even more reluctant warrior hasn't left me unaffected. Fighting beside you people has been an honor. The scariest and yet the #emph[best] thing I've ever done with my somewhat bizarre life. What the Gatewatch has done here today—" She glanced down at the armor in Mistress Aurelia's hands. "—What you #emph[sacrificed] here today~well~this'll sound corny, but it has been truly inspirational. If you'll have me, I'd like to be a part of this. I'd like you all to know that if there's trouble, you can summon me, and I will stand beside you."
"We'd like that," <NAME> said.
"Aye, girl," said <NAME>, grinning his leonine grin.
<NAME>, <NAME>, and <NAME> all smiled and nodded their assent.
<NAME> took a deep breath and raised her right hand. Perhaps as a symbol of what she had to offer, she turned that hand spectral, so that it became transparent, flowing with a soft violet light. She said, "I have crossed the Multiverse, helping the dead, um~move on, in service of the living. But what I've witnessed here on Ravnica these last few months—these last few hours—has changed everything I thought I knew. Never again. For the living and the dead, #emph[I will keep watch] ." She turned and smiled at Teyo and me.
#figure(image("006_Ashes/06.jpg", width: 100%), caption: [Oath of Kaya | Art by: <NAME>], supplement: none, numbering: none)
I could feel Teyo wondering if he should take the Oath, if any of the others would think him worthy. I was about to tell him that #emph[they ] should feel honored to include him.
But we were both distracted by the arrival of <NAME>, who landed in a somewhat showy manner and grinned. "You're out of a job, Beleren. The Firemind is the new Living Guildpact. As it was always meant to be."
<NAME> chuckled, "And yet somehow I don't seem sorry to be giving up that particular responsibility."
Ignoring the dragon completely, <NAME> leaned her head over one of the many cracks in the plaza's pavement. She closed her eyes and breathed deeply. From between the battle-broken cobbles, a seed sprouted and rapidly grew into a plant with large green leaves.
She nodded to <NAME>, who somehow instinctively knew what the elf wanted her to do. The pyromancer carefully plucked three of the bigger leaves from the plant.
Then we all watched as the two women and Mistress Aurelia lovingly, #emph[tenderly] , wrapped M<NAME>'s armor in the leaves.
Aurelia handed the armor to <NAME>, who—flanked by <NAME> and <NAME>—led a solemn procession toward the celebrating (and mourning) crowd. A forlorn Mistress Aurelia watched them go but did not follow—while most of the other Planeswalkers did.
<NAME> touched Mistress Kaya on the shoulder and gestured for her to wait. <NAME> did the same to Queen Vraska, who nodded and called out to <NAME> that she would catch up to him.
Teyo stood there confused, and I was curious enough to wait alongside him. Mistresses Lavinia and Aurelia, <NAME>, and the dragon waited, also. We were soon joined by <NAME>, <NAME>, <NAME>, and Boruvo. (The latter smiled at me, though my father, as usual, wasn't aware of my presence.) As soon as the procession of the Gatewatch had safely gotten out of earshot, <NAME> morphed into Master Lazav, which made me wonder where the real Miss Rai was at that moment.
The Firemind spoke first: "As the new Living Guildpact, I have consulted with representatives of every guild."
Mistress Kaya raised an eyebrow at Mister Vrona, who nodded.
The dragon continued: "We have agreed that certain individuals, those who collaborated with <NAME>, must be punished."
Queen Vraska bristled, her eyes brightening with magic: "I won't be judged by the likes of you."
"You #emph[have ] been judged," Mistress Lavinia said, sternly but without threat. "And your actions on this day have mitigated that judgment."
Master Zarek said, "You are not the only one Bolas misled and used. Kaya and I share that particular guilt. We may have realized our error sooner than you did, but we have no desire to quibble with an ally. Not with an ally willing to prove her allegiance to Ravnica and her own guild."
Queen Vraska looked no less suspicious—no less on guard—but her eyes ceased to glow. "I'm listening."
Mistress Aurelia said, "Hundreds, maybe thousands of sentient beings died on Ravnica today."
"With untold property damage," added Mister Vrona.
Ignoring him, Mistress Aurelia went on, "Such acts of terror must not go unpunished. There are three who did everything in their power to aid and abet the dragon: Tezzeret, <NAME>, and <NAME>."
Teyo said, "But didn't Liliana—"
Mister Vorel interrupted him: "Vess changed sides too late. Only after being the direct cause of most of the carnage."
"What exactly are you asking?" Mistress Kaya said, unhappily.
"All three are Planeswalkers," Master Lazav stated. "They are out of our reach. But not out of yours."
The Firemind brought the point home, "Ral Zarek has already agreed to hunt Tezzeret. Vraska, as penance for past sins, we assign you <NAME>. And Kaya, the ten guilds wish to hire you to assassinate Liliana Vess."
#emph[I guess maybe the War of the Spark isn't quite as "over" as I'd figured, you know?]
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/link_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Link syntax.
https://example.com/
// Link with body.
#link("https://typst.org/")[Some text text text]
// With line break.
This link appears #link("https://google.com/")[in the middle of] a paragraph.
// Certain prefixes are trimmed when using the `link` function.
Contact #link("mailto:<EMAIL>") or
call #link("tel:123") for more information.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-27F0.typ | typst | Apache License 2.0 | #let data = (
("UPWARDS QUADRUPLE ARROW", "Sm", 0),
("DOWNWARDS QUADRUPLE ARROW", "Sm", 0),
("ANTICLOCKWISE GAPPED CIRCLE ARROW", "Sm", 0),
("CLOCKWISE GAPPED CIRCLE ARROW", "Sm", 0),
("RIGHT ARROW WITH CIRCLED PLUS", "Sm", 0),
("LONG LEFTWARDS ARROW", "Sm", 0),
("LONG RIGHTWARDS ARROW", "Sm", 0),
("LONG LEFT RIGHT ARROW", "Sm", 0),
("LONG LEFTWARDS DOUBLE ARROW", "Sm", 0),
("LONG RIGHTWARDS DOUBLE ARROW", "Sm", 0),
("LONG LEFT RIGHT DOUBLE ARROW", "Sm", 0),
("LONG LEFTWARDS ARROW FROM BAR", "Sm", 0),
("LONG RIGHTWARDS ARROW FROM BAR", "Sm", 0),
("LONG LEFTWARDS DOUBLE ARROW FROM BAR", "Sm", 0),
("LONG RIGHTWARDS DOUBLE ARROW FROM BAR", "Sm", 0),
("LONG RIGHTWARDS SQUIGGLE ARROW", "Sm", 0),
)
|
https://github.com/Ttajika/auto-ref-numbery | https://raw.githubusercontent.com/Ttajika/auto-ref-numbery/main/0.0.1/lib.typ | typst | MIT License | #import "translation.typ": *
#let cap_body(it) = {if it != none {return it.body}
else {return it}
}
//#autonumbering equations
//
#let tjk_numb_style(tag,tlabel,name,numbering:"(1)") = {
if tag == true or name != none {
if name == none{
return it => "("+str(tlabel)+")"}
else {return it => "("+str(name)+")"}
}
else {
return numbering
}
}
#let tell_labels(it) ={
if type(it) == "label"{return it}
else {return label(str(it))}
}
#let auto-numbering-equation(tlabel, name:none, tag:false,numbering:"(1)", body) ={
locate(loc =>{
let eql = counter("tjk_auto-numbering-eq" + str(tlabel))
if eql.final(loc).at(0) == 1{
[#math.equation(numbering: tjk_numb_style(tag,tlabel,name,numbering:numbering),block: true)[#body]
#tell_labels(tlabel)]
if tag == true{counter(math.equation).update(i => i - 1)}
}
else {
[#math.equation(numbering:none,block: true)[#body] ]
}
})
}
//shorthand
#let aeq = auto-numbering-equation
#let heading_supplement(it, supplement,thenumber,lang:"en",dic:(en:(:))) ={
if lang == "jp" and supplement in dic.at("jp").keys() {
return thenumber + dic.at("jp").at(supplement)
}
else {return it}
}
//modify reference
#let eq_refstyle(it,lang:"en",dic:(en:(:))) = {
return {
let lbl = it.target
let eq = math.equation
let el = it.element
let eql = counter("tjk_auto-numbering-eq"+str(lbl))
eql.update(1)
if el != none and el.func() == eq {
link(lbl)[
#numbering(
el.numbering,
..counter(eq).at(el.location())
) ]
} else if el != none and el.has("counter") {
let c_eq = el.counter
if el.supplement.text in dic.at(lang).keys(){
link(lbl)[
#dic.at(lang).at(el.supplement.text) #numbering(
el.numbering,
..c_eq.at(el.location())
)]
} else {it}
} else if el != none and el.func() == heading {
let thenumber = numbering(
el.numbering,
..counter(heading).at(el.location())
)
link(lbl)[#heading_supplement(it, it.element.supplement.text, thenumber,lang:lang,dic:dic)
]
}
else {it}
}
}
//#reference multiple labels
//dictionary of plurals
#let plurals(single,dict) ={
if single in dict.keys() {
return dict.at(single)
}else {return single}
}
//multiple references
#let refs(..sink,dict:plurals_dic,add:" and ",comma:", ") = {
let args = sink.pos()
let numargs = args.len()
let current_titles = ()
let titles_dic = (:)
if numargs == 1 {link(ref(args.at(0)).target)[#ref(args.at(0))]}
else {
show ref: it => plurals(it.element.supplement.text,dict)
ref(args.at(0)) + " "
show ref: it => {
let c_eq = it.element.counter
numbering(it.element.numbering,
..c_eq.at(it.element.location()))
}
if numargs == 2{link(ref(args.at(0)).target)[#ref(args.at(0))] + ""+ add +"" + link(ref(args.at(1)).target)[#ref(args.at(1))]}
else{
for i in range(numargs){
if i< numargs - 1 {link(ref(args.at(i)).target)[#ref(args.at(i))] + comma+"" }
else {add+"" + link(ref(args.at(i)).target)[#ref(args.at(i))]}
}}
}
}
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/plotst/0.1.0/plotst/util/util.typ | typst | Apache License 2.0 | #import "/plotst/axis.typ": *
// hackyish solution to split axis and content
#let render(plot, plot_code, render_axis) = style(style => {
let widths = 0pt
let heights = 0pt
// Draw coordinate system
for axis in plot.axes {
let (w,h) = measure_axis(axis, style)
widths += w
heights += h
}
let x_axis = plot.axes.filter(it => not is_vertical(it)).first()
let y_axis = plot.axes.filter(it => is_vertical(it)).first()
let offset_y = 0pt
let offset_x = 0pt
if x_axis.location == "bottom" {
offset_y = -heights
}
if y_axis.location == "left" {
offset_x = widths
}
place(dx: offset_x, dy: -100% + heights+offset_y, box(width: 100% - widths, height: 100% - heights, {
if render_axis {
for axis in plot.axes {
draw_axis(axis)
}
} else {
plot_code()
}
}))
})
// Prepares everything for a plot and executes the function that draws a plot. Supplies it with width and height
// size: the size of the plot either as array(width, height) or length
// caption: the caption for the plot
// capt_dist: distance from plot to caption
//-------
// width: the width of the plot
// height: the height of the plot
// the plot code: a function that needs to look accept parameters (width, height)
// plot: if set this function will attempt to render the axes and prepare everything. If not, the setup is up to you
// if you want to make the axes visible (only if plot is set)
//-------
#let prepare_plot(size, caption, plot_code, plot: (), render_axis: true) = {
let (width, height) = if type(size) == "array" {size} else {(size, size)}
figure(caption: caption, supplement: "Graph", kind: "plot", {
// Graph box
set align(left + bottom)
box(width: width, height: height, fill: none, if plot == () { plot_code() } else {
if render_axis { render(plot, plot_code, true) }
render(plot, plot_code, false)
})
})
}
// Calculates step size for an axis
// full_dist: the distance of the axis while drawing (most likely width or height)
// axis: the axis
// returns: the step size
#let calc_step_size(full_dist, axis) = {
return full_dist / axis.values.len() / axis.step
}
// transforms a data list ((amount, value),..) to a list only containing values
#let transform_data_full(data_count) = {
if not type(data_count.at(0)) == "array" {
return data_count
}
let new_data = ()
for (amount, value) in data_count {
for _ in range(amount) {
new_data.push(value)
}
}
return new_data
}
// transforms a data list (val1, val2, ...) to a list looking like this ((amount, val1),...)
#let transform_data_count(data_full) = {
if type(data_full.at(0)) == "array" {
return data_full
}
// count class occurances
let new_data = ()
for data in data_full {
let found = false
for (idx, entry) in new_data.enumerate() {
if data == entry.at(1) {
new_data.at(idx).at(0) += 1
found = true
break
}
}
if not found {
new_data.push((1, data)) //?
}
}
return new_data
}
// converts an integer or 2-long array to a width, height dictionary
#let convert_size(size) = {
if type(size) == "int" { return (width: size, height: size) }
if size.len() == 2 { return (width: size.at(0), height: size.at(1)) }
} |
https://github.com/qujihan/typst-book-template | https://raw.githubusercontent.com/qujihan/typst-book-template/main/template/parts/figure/code.typ | typst | #import "../../params.typ": *
#let code-num(_) = {
let chapter-num = counter(heading.where(level: 1)).display()
let type-num = counter(figure-kind-code + chapter-num).display()
str(chapter-num) + "-" + str(int(type-num) + 1)
}
#let codeIn(
title,
content,
) = block(
stroke: 0.5pt + line-color,
radius: 6pt,
width: 100%,
inset: (top: 0.8em, bottom: 0.8em, left: 0.6em, right: 0.6em),
fill: none,
breakable: true,
)[
#place(
top + right,
dy: -1.25em,
dx: -1em,
block(
fill: white,
inset: (bottom: 0.1em),
outset: (left: 0.5em, right: 0.5em),
text(font: "Lora", style: "italic", fill: line-color)[*#title*],
),
)
#align(left + top)[
#content
]
]
#let code(title, caption, content) = {
figure(
codeIn(title, content),
placement: auto,
caption: caption,
supplement: [代码],
numbering: code-num,
kind: figure-kind-code,
)
} |
|
https://github.com/HiiGHoVuTi/requin | https://raw.githubusercontent.com/HiiGHoVuTi/requin/main/math/semigroupes-et-langages.typ | typst | #import "../lib.typ": *
#show heading: heading_fct
#import "@preview/gloss-awe:0.0.5": gls
#show figure.where(kind: "jkrb_glossary"): it => {it.body}
=== Demi-groupes, monoïdes et groupes
Soit un _demi-groupe_ $(EE, +)$, c'est-à-dire que
#align(center, grid(columns: (1fr, 1fr),
[- $EE$ est stable par $+$],
[- La loi $+$ est associative]))
On dira de plus que $EE$ est un _monoïde_ si il existe $e in EE$ tel que
$ forall x in EE, x e = e x = x $
On dira enfin que $EE$ est un _groupe_ si il existe $dot^(-1) : EE -> EE$ tel que
$ forall x in EE, x x^(-1) = x^(-1) x = e $
#question(0)[
Donner un groupe, puis un monoïde qui n'est pas un groupe, et enfin un demi-groupe qui n'est pas un monoïde.
]
#correct[
- $(ZZ, +)$
- $(NN, +)$
- $(NN^star, +)$
]
Si $EE$ est un monoïde commutatif, soit $~ in (EE^2)^2$ telle que $(a,b) ~ (c,d) arrow.double.l.r.long a+d=b+c$.
#question(1)[Que dire de $EE^2 \/ ~$ ?]
#correct[
C'est un groupe.
- Monoïde (terme à terme).
- L'inverse de $(a,b)$ est $(b,a)$.
]
Soit $Sigma$ un ensemble fini. On appelle $Sigma^star$ le plus petit monoïde contenant $Sigma$ et tel que tous les éléments de $Sigma^star$ admettent une unique composition comme somme d'éléments de $Sigma$.
On note son neutre $epsilon$.
#question(0)[
Justifier que $Sigma^*$ est l'ensemble des mots finis sur $Sigma$
]
#correct[
On pose $phi$ la fonction qui à un mot fini sur $Sigma$ associe sa somme.
La surjectivité de $phi$ est immédiate car $Sigma^star$ est de taille minimale.
Démontrons l'injectivité de $phi$.
$square$ Soient $u,v$ des mots finis sur $Sigma$ tels que $phi(u)=phi(v)$.
Par définition de $phi$, $ sum_(i=0)^(|u|) u_i = sum_(i=0)^(|v|) v_i $
Par unicité de la décomposition de $phi(u)$ et $phi(v)$, $forall i <= |u|, u_i = v_i$. #h(1fr) $square$
La fonction $phi$ est bijective (c'est d'ailleurs immédiatement un morphisme de monoïdes), donc on peut identifier les deux ensembles.
]
On pose $cal(A) := { x |-> w x, med w in Sigma^star }$, que l'on munit de la loi de composition usuelle des fonctions.
#question(1)[
Justifier que $Sigma^star$ et $cal(A)$ sont en isomorphes comme monoïdes.
]
#correct[
On pose $phi : Sigma^star -> cal(A)$ la fonction $w |-> x |-> x w$. La surjectivité est encore une fois évidente. L'injectivité se démontre en regardant $phi(u)(epsilon)$.
On constate vérifie que $phi(u)compose phi(v) = phi(u v)$.
]
=== Associativité ?
Dans cette partie, $(S, +)$ est un demi-groupe.
Soit $n in NN$ puis $a in S^n$ un $n-$uplet.
#question(1)[
Donner le langage des expressions calculant $sum a$. Est-il rationnel ?
_Ind:_ Par exemple, pour $n=3$, $cal(L) = { a_1 + (a_2 + a_3), (a_1 + a_2) + a_3 }$.
]
#correct[
C'est le langage des sommes bien parenthésées. C'est une question piège, le langage est fini donc rationnel.
]
#question(2)[
Mettre en bijection $cal(L)$ et l'ensemble des arbres binaires à $n$ noeuds. Dénombrer $cal(L)$.
]
#correct[
À une somme on associe un arbre dont les noeuds sont les $+$ et leurs enfants sont les termes sommés (donc la représentation sous forme d'arbre de la somme).
Pour dénombrer les arbres à $n$ noeuds, on peut utiliser la méthode des #gls(entry: "Classe combinatoire")[classes combinatoires], si $cal(T)$ est la classe des arbres binaires, $ cal(T) = cal(E) + cal(Z) times cal(T)^2 $
Ainsi, $T = 1 + Z T^2$ donc $Z T^2 - T + 1 = 0$ et enfin $T = (1 plus.minus sqrt(1 - 4Z))/(2 Z)$. Par continuité, on écarte la solution en $+$.
En faisant un développement en série entière, on retrouve les #gls("Nombres de Catalan").
]
On considère maintenant posséder une machine capable d'exécuter $omega in NN^star$ opérations "$+$" simultanées.
#question(1)[
Donner un mauvais ordre de calcul de $sum a$, puis un choix plus raisonnable.
]
#correct[
Un très mauvais ordre est de gauche à droite sans répartir le travail. Un meilleur choix est de faire une $omega$-chotomie, c'est-à-dire partager le travail récursivement en blocs de taille $omega$.
]
=== Retouches
Soient $cal(L)$ un langage rationnel et $M in Sigma^star$ un mot de longueur $n in NN^star$. On appelle une _requête_ un couple $1<=i<=j<=n$ et sa _taille_ est $r := j-i$.
On _satisfait_ une requête en renvoyant si $M[i:j] in cal(L)$. On note $q in NN$ le nombre d'états d'un automate qui reconnaît $cal(L)$.
#question(0)[
Donner un algorithme satisfaisant une requête.
]
#correct[ On se munit d'un automate, et on fait tourner l'automate sur $M[i:j]$. ]
Moyennant un précalcul,
#question(3)[
Donnez un algorithme efficace satisfaisant une requête en temps $cal(O)(q log r)$
_Ind:_ On pourra introduire un ensemble de fonctions similaire à $cal(A)$ agissant sur l'automate.
]
#correct[
Cette question est notée comme difficile car on préférera un précalcul permettant de répondre à la question suivante.
On se munit d'un automate dont on note l'ensemble des états $Q$, $q_0$ l'état initial et la fonction de transition $delta$.
On suit l'indication et on pose $cal(A) := { delta^star (dot, M[i,j]), 1 <= i <= j <= n } subset Q^Q$.
Ne voulant pas stocker toutes ces valeurs, on opte pour une solution semblable au _tri par tas_.
On stocke l'entrée associée à $i,j$ si $j-i$ est une puissance de $2$ qui divise $i$ et $j$.
On peut stocker une telle fonction sous la forme d'un tableau de taille $q$ par exemple.
On peut reconstituer l'action de $M[i,j]$ en temps logarithmique en $r$ et proportionnel à $q$ (il faut composer des fonctions de $Q$ dans $Q$).
]
Une _modification_ est une opération de la forme $M[i] <- a$ avec $a in Sigma$.
#question(3)[
Modifier l'algorithme précédent pour permettre des modifications en temps $cal(O)(q log n)$.
]
#correct[
On modifie l'action de $M[i:i]$ stockée, puis on fait percoler les modifications vers le haut. Cela se fait en temps logarithmique en $n$ (et on a encore le facteur $q$ pour les compositions).
]
|
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/i18n/zh/docusaurus-plugin-content-docs/current/style.md | markdown | ---
sidebar_position: 4
---
# 代码风格
## show-slides 风格
如果我们只是需要简单使用,我们可以通过 `#show: slides` 实现更简洁的语法。
但是这样做也有对应的弊端:第一个弊端是这种方式可能会极大地影响文档渲染性能,第二个弊端是后续不能直接加入 `#slide(..)`,而是需要手动标记 `#slides-end`,以及最大的弊端是实现不了复杂的功能。
```typst
#import "@preview/touying:0.2.1": *
#let (init, slide, slides) = utils.methods(s)
#show: init
#show: slides
= Title
== First Slide
Hello, Touying!
#pause
Hello, Typst!
#slides-end
#slide[
A new slide.
]
```

并且你可以使用空标题 `==` 创建一个新页。
## slide-block 风格
为了更优秀的性能和更强大的能力,大部分情况我们还是需要使用
```typst
#slide[
A new slide.
]
```
这样的代码风格。 |
|
https://github.com/dasayan05/typst-ai-conf-templates | https://raw.githubusercontent.com/dasayan05/typst-ai-conf-templates/master/cvpr/paper.typ | typst | MIT License | #import "cvpr.typ": manuscript
#show: manuscript.with(
title: [Typst Author Guidelines for CVPR Proceedings],
authors: (
[
First Author\
Institution1\
Institution1 address\
`<EMAIL>`
],
[
Second Author\
Institution2\
First line of institution2 address\
`<EMAIL>`
],
[
Third Author\
Institution3\
Institution3 address\
`<EMAIL>`
]
),
abstract: [
The ABSTRACT is to be in fully justified italicized text, at the top of the left-hand column, below the author and affiliation information. Use the word "Abstract" as the title, in 12-point Times, boldface type, centered relative to the column, initially capitalized. The abstract is to be in 10-point, single-spaced type. Leave two blank lines after the Abstract, then begin the main text. Look at previous CVPR abstracts to get a feel for style and length.
]
)
= Introduction
Please follow the steps outlined below when submitting your manuscript to the IEEE Computer Society Press. This style guide now has several important modifications (for example, you are no longer warned against the use of sticky tape to attach your artwork to the paper), so all authors should read this new version.
== Language
All manuscripts must be in English.
== Dual submission
Please refer to the author guidelines on the CVPR 2022 web page for a discussion of the policy on dual submissions.
== Paper length
Papers, excluding the references section, must be no longer than eight pages in length. The references section will not be included in the page count, and there is no limit on the length of the references section. For example, a paper of eight pages with two pages of references would have a total length of 10 pages. *There will be no extra page charges for CVPR 2022.*
Overlength papers will simply not be reviewed.
This includes papers where the margins and formatting are deemed to have been significantly altered from those laid down by this style guide.
Note that this *LaTeX* guide already sets figure captions and references in a smaller font.
The reason such papers will not be reviewed is that there is no provision for supervised revisions of manuscripts.
The reviewing process cannot determine the suitability of the paper for presentation in eight pages if it is reviewed in eleven.
== The ruler
The *LaTeX* style defines a printed ruler which should be present in the version submitted for review.
The ruler is provided in order that reviewers may comment on particular lines in the paper without circumlocution.
If you are preparing a document using a non-*LaTeX* document preparation system, please arrange for an equivalent ruler to appear on the final output pages.
The presence or absence of the ruler should not change the appearance of any other content on the page.
The camera-ready copy should not contain a ruler.
(*LaTeX* users may use options of cvpr.sty to switch between different versions.)
Reviewers:
note that the ruler measurements do not align well with lines in the paper --- this turns out to be very difficult to do well when the paper contains many figures and equations, and, when done, looks ugly.
Just use fractional references (_e.g._, this line is $087.5$), although in most cases one would expect that the approximate location will be adequate.
== Paper ID
Make sure that the Paper ID from the submission system is visible in the version submitted for review (replacing the "\*\*\*\*\*" you see in this document).
If you are using the LaTeX template, *make sure to update paper ID in the appropriate place in the tex file*.
== Mathematics
Please number all of your sections and displayed equations as in these examples:
$ E = m dot c^2 $ <important>
and
$ v = a dot t. $
It is important for readers to be able to refer to any particular equation. Just because you did not refer to it in the text does not mean some future reader might not need to refer to it. It is cumbersome to have to use circumlocutions like ``the equation second from the top of page 3 column 1''.
(Note that the ruler will not be present in the final copy, so is not an alternative to equation numbers).
All authors will benefit from reading Mermin's description of how to write mathematics:
#link("http://www.pamitc.org/documents/mermin.pdf"). |
https://github.com/university-makino/Microcomputer-control-and-exercises | https://raw.githubusercontent.com/university-makino/Microcomputer-control-and-exercises/master/report/プレレポート3/report.typ | typst | // ライブラリの実装 //
#import "@preview/codelst:2.0.1": sourcecode
//フォント設定//
#let gothic = "YuMincho"
//本文フォント//
#set text(11pt, font: gothic, lang: "ja")
//タイトル・見出しフォント//
#set heading(numbering: "1.1")
#let heading_font(body) = {
show regex("[\p{scx: Han}\p{scx: Hira}\p{scx: Kana}]"): set text(font: gothic)
body
}
#show heading: heading_font
// ページ設定 //
#set page(
paper: "a4",
margin: (x: 25mm, y: 25mm),
columns: 1,
//fill: 背景色,
numbering: "1",
number-align: center,
header: [
#set text(8pt)
]
)
// 数式の表示の仕方を表示 //
#set math.equation(numbering: "(1)")
//タイトルページここから//
#align(right, text()[
#text[提出日]#datetime.today().display("[year]年[month]月[day]日")
])
#v(150pt)
#align(center, text(30pt)[
#heading_font[*プレ・レポート3*]
])
// #align(center, text(14pt)[
// #heading_font[*サブタイトル*]
// ])
#v(1fr)
#align(right)[
#table(
columns:(auto, auto),
align: (right, left),
stroke: none,
[講義名],[マイコン制御および演習],
[担当教員],[伊藤 暢浩先生],
[],[],
[学籍番号],[k22120],
[所属],[情報科学部 情報科学科],
[学年],[3年],
[氏名],[牧野遥斗]
)
]
#pagebreak()
//本文ここから//
= プレ・レポート(課題 2)
== @焦電センサ の電子部品 ( 焦電センサ AMN31111) を次のような点から調べなさい。
#figure(
image("./img/焦電センサ.png",width: 50%),
caption: "焦電センサ"
)<焦電センサ>
=== どのような部品か
センサ自身からLEDなどの光を発光するのではなく、周囲と温度差のある人(物)が動く際におこる赤外線の変化量を検出するセンサである。温度差を検出するため、体温を持つ人体の検出に適している @red_maruta_about。
=== どのような仕組みか
センサに赤外線が入射すると、温度変化が生じ、焦電素子(セラミクス)の表面温度が上がり、焦電効果により表面電荷が発生する。
@焦電センサ仕組み に示すように、焦電素子の表面には、吸着浮遊イオンが存在している。
このため安定時の電荷の中和状態がくずれ感知素子表面の電荷と、吸着浮遊イオン電荷の緩和時間が異なるため、アンバランスとなり、結びつく相手のない電荷が生じる。この発生した表面電荷をセンサ内部品で電気信号として取りだし、出力信号として利用する @red_maruta_about。
#figure(
image("./img/焦電センサ仕組み.png",width: 50%),
caption: "焦電センサ仕組み"
)<焦電センサ仕組み>
=== どのような入力を取り扱うのか
焦電センサは、赤外線の変化量を検出するため、人体から発生する熱量(赤外線)を感知し、人体の動きを検出することができる。
=== 入力に応じて出力がどう変化するのか (データシートや仕様書を参考に)
Panasonicのデータシートによると、以下のような特性がある@red_datasheet 。
@焦電センサタイミングチャート に示すように、焦電センサは、人体の動きを検知すると、出力電圧が変化する。この出力電圧の変化を利用して、人体の動きを検知することができる。
しかし、開始最大30秒間は安定しないため、安定した出力を得るためには、30秒以上の時間をかける必要がある。
#figure(
image("./img/焦電センサタイミングチャート.png",width: 75%),
caption: "焦電センサタイミングチャート"
)<焦電センサタイミングチャート>
=== どのようなピンアサイン (各ピンの役割) か
Panasonicのデータシートによると、以下のようなピンアサインがある @red_datasheet 。
+ Vdd (デジタル出力)
+ GND
+ Vcc (5V 電源電圧)
#figure(
image("./img/焦電センサピンアサイン.png",width: 75%),
caption: "距離センサーのピンアサイン"
)<distance_sensor_pin>
=== 正しい動作の条件,範囲は何か
marutsuのサイトによると、以下のような仕様がある @red_marutsu 。
- パッケージ:TO-5
- タイプ:標準検出タイプ
- 検出性能:標準検出タイプ
- 消費電力:100μA
- 消費電流:170μA
- 出力タイプ:デジタル
- 動作電圧:3~6V
- レンズ色:黒
- レンズ素材:ポリエチレン
- 検出距離:5m
- 定格検出:距離 最大5m
#pagebreak() // ページを分ける
== @加速度センサ の電子部品 ( 加速度センサ KXM52-1050) を次のような点から調べなさい。
#figure(
image("./img/加速度センサ.png",width: 50%),
caption: "加速度センサ"
)<加速度センサ>
=== どのような部品か
加速度の測定を目的とした慣性センサの1つで、3次元の慣性運動(直行3軸方向の並進運動)を検出する。
利用用途としては、ビルや橋梁などの建造物の傾斜や地震時の傾き計測にも利用される @acc_marubun 。
=== どのような仕組みか
差動キャパシタンスの原理で機能する。加速によりシリコン構造が変位し、キャパシタンスが変化する。この変化を電圧信号に変換し、出力する @acc_datasheet 。
=== どのような入力を取り扱うのか
加速度センサは、加速度を検出するため、物体の加速度を感知し、物体の動きを検出することができる。
=== 入力に応じて出力がどう変化するのか (データシートや仕様書を参考に)
KXM52-1050のデータシートによると、以下のような特性がある@acc_datasheet 。
- 電源電圧(Vdd) 2.7V~5.5V(標準3.3V)
- 測定レンジ ±2g
- 感度 (Vdd/5) V/g
- 0G出力 (Vdd/2) V
出力電圧をv(V)、加速度をa(単位はg)とすると、出力電圧と加速度の関係は @出力の式 であらわされる。
$ v = a * v_d/5 * v_d/2 $<出力の式>
例えば、Vddが5V、加速度が1gのときは、aに1を代入して、3.5Vの電圧が出力される。
=== どのようなピンアサイン (各ピンの役割) か
KXR94-1050をそのまま使用することは難しいため、基盤に半田付けし、使いやすくモジュール化したものを用いる。
しかし、KXR94-1050は廃盤となっており、代替品としてKXR94-2050がある @acc_akitsuki_datasheet 。
今回は、KXR94-2050とあまり違いがないと仮定をして、KXR94-2050のピンアサインを @加速度センサーピンアサイン に示す。
+ Vdd
+ Enable
+ GND
+ Vmux
+ Out Z
+ Out Y
+ OUT X
+ Self Test
#figure(
grid(
columns: 2,
image("./img/加速度センサーピンアサイン1.png",width: 75%),
image("./img/加速度センサーピンアサイン2.png",width: 75%)
),
caption: "加速度センサーピンアサイン"
)<加速度センサーピンアサイン>
=== 正しい動作の条件,範囲は何か
秋月電子のサイトによると、以下のような仕様がある @acc_akitsuki 。
- 電源電圧min.:2.5V
- 電源電圧max.:5.25V
- 加速度チャンネル:3
- 測定加速度max.:±2g
- 測定項目:加速度
- インターフェイス:アナログ
- 実装タイプ:スルーホール
- パッケージ:DIP8
#pagebreak() // ページを分ける
// bibファイルの指定 //
#bibliography("./bibliography.bib")
|
|
https://github.com/jamesrswift/journal-ensemble | https://raw.githubusercontent.com/jamesrswift/journal-ensemble/main/src/contents.typ | typst | The Unlicense | #import "part.typ"
#let needle = label("__journal-ensemble:mark-contents")
#let make(
) = [
]
#let mark(
label: needle,
scope: auto,
body
) = context [
#metadata((:
scope: if scope == auto {part.get()} else {scope},
body: body,
))
#label
] |
https://github.com/xsro/xsro.github.io | https://raw.githubusercontent.com/xsro/xsro.github.io/zola/typst/nlct/math/mechanic.typ | typst | #pagebreak(weak: true)
= Mechanics 机械
== Underactuator system 欠驱动系统
- <NAME>. Underactuated Robotics: Algorithms for Walking, Running,Swimming, Flying, and Manipulation (Course Notes for MIT 6.832). Downloaded from http://underactuated.mit.edu/
According to Newton,
the dynamics of mechanical systems are second order($F=m a$).
Their state is geiven by a vector of positions,
$bold(q)$ (also known as the configuration vector),
and a vector of velocities, $dot(bold(q))$,
and (possibly) time.
The general form for a second-order control dynamical systems is
$
dot.double(bold(q))=f(bold(q),dot(bold(q)),bold(u),t)
$
where $bold(u)$ is the control vector.
The second-order control differential equation
$dot.double(bold(q))=f(bold(q),dot(bold(q)),bold(u),t)$
is *fully actuate* in state $bold(x)=(bold(q),dot(bold(q)))$ and time $t$ if the resulting map $f$ is surjective(满射):
for every $dot.double(bold(q))$ there exists a $bold(u)$ which produces the desired response.
Otherwise it is *underactuated*(in $bold(x)$ at time t)
== Homonomic Systems and Nonholonomic Systems 完整约束与非完整约束系统
- https://www.zhihu.com/question/26411115
- https://physics.stackexchange.com/questions/409951/what-are-holonomic-and-non-holonomic-constraints
Consider a mechanical system with $n$ generalized coordinates $q$ subject to $m$ bilateral(双边的) constraints whose equations of motion are described by
$
M(q) dot.double(q) + V(q,dot(q))=E(q) tau - A^T(q) lambda
$
where $M(q)$ is the $n times n$ inertia matrix,
$V(q,dot(q))$ is the vector of position and velocity dependent forces,
$E(q)$ is the $n times r$ input transformation matrix,
$tau$ is the $r$-dimensional inpyt vector, $Q(q)$ is the $m times n$ Jacobian matrix,
and $lambda$ is the vector of constraint forces.
The $m$ constraint equations of the mechanical system can be written in the form
$
C(q,dot(q))=0
$
If a constraint equation is in the form $C_i(q)=0$, or can be integrated into this form,
it is a holonomic constraint.
Otherwise it is a kinematix(not geometric) constaint and is termed *nonholonomic*.
“完整”和“非完整”是分析力学的重要概念。
完整约束就是指可以表示为以广义坐标和时间为变参数的代数方程式的约束,否则就是非完整约束。 |
|
https://github.com/bradmartin333/TypstNotes | https://raw.githubusercontent.com/bradmartin333/TypstNotes/main/template.typ | typst | #let months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
#let dt = datetime.today()
#let notepad(
title: none,
description: none,
body
) = {
set page(margin: (top: 2cm))
set text(font: "PT Sans")
set heading(numbering: "1.1.A ")
align(center, text(17pt)[
#if title != none {
text(20pt)[*#title*]
v(0.1cm)
}
#dt.day()
#months.at(dt.month())
#dt.year()
])
v(1cm)
if (description != none) {
description
v(1cm)
}
outline(indent: auto)
pagebreak()
body
}
|
|
https://github.com/EliasRothfuss/vorlage_typst_doku-master | https://raw.githubusercontent.com/EliasRothfuss/vorlage_typst_doku-master/main/pages/titelseite.typ | typst | #import "../config.typ"
#image("../images/DHBW_d_R_FN_46mm_4c.jpg", width: 20%)
#set align(center)
#v(5em)
#text(24pt)[
#config.data.title
]
#text(17pt)[
#config.data.subtitle
]
#v(2em)
#text(20pt)[
#config.data.arbeit
]
#v(1em)
#text(14pt)[
Studiengang #config.data.studiengang
]
#text(12pt)[
Studienrichtung #config.data.studienrichtung
<NAME>schule <NAME>, <NAME>
#v(2em)
von \
#config.data.author
]
#v(2em)
#table(
columns: 2,
stroke: none,
align: (left,left,),
[Abgabedatum:], [#config.data.abgabe],
[Bearbeitungszeitraum:], [#config.data.bearbeitungszeitraum],
[Matrikelnummer:], [#config.data.matrikelnr],
[Kurs:], [#config.data.kurs],
[Dualer Partner:], [#config.data.dualer_partner],
[Betreuerin / Betreuer:], [#config.data.betreuer],
[Gutachterin / Gutachter:], [#config.data.gutachter],
) |
|
https://github.com/m4cey/mace-typst | https://raw.githubusercontent.com/m4cey/mace-typst/main/math/logic.typ | typst | #import "@preview/tablex:0.0.7": *
// General Tablex style
#let mytablex(..args) = tablex(inset: 0.6em, ..args)
// Logic Tables
#let truth_table(..args) = mytablex(auto-lines: false, align: center, hlinex(y:1), ..args)
// pc stands for premises and conclusions
#let pc_table(..args) = {
let named_args = args.named()
let columns_len = if type(named_args.columns) == "array" {named_args.columns.len()} else {named_args.columns}
let variables = columns_len - named_args.premises - named_args.conclusions
tablex(
auto-lines: false, align: center, inset: 0.6em,
..(if variables > 0 {(colspanx(variables)[], vlinex())}),
colspanx(named_args.premises)[*Premises*],vlinex(),
colspanx(named_args.conclusions)[*Conclusions*],
hlinex(y:2),
map-rows: (row, cells) => {
let arg_cells = cells.filter(c =>
if c == none {
false
} else {
c.x > variables - 1 and c.y > 1
}
)
let premises_truthness = arg_cells.filter(c => c.x <= variables + named_args.premises - 1)
.all(c => c.content == [T])
let conclusions_truthness = arg_cells.filter(c => c.x > variables + named_args.premises - 1)
.all(c => c.content == [T])
cells.map(c =>
if c == none {
none
} else {
let truth_color = if row > 1 and premises_truthness {
if conclusions_truthness {olive} else {red}
}
(..c, fill: truth_color)
}
)
},
..args
)
}
// TESTS
#[
#show heading.where(level: 1): it => [
#let str = it.body.fields().children.fold("#", (a, i) => a + i.text )
#raw(lang: "typ", str + ":" )]
= truth_table()
#truth_table(
columns: 4,
$P$, $not Q$, $P or not Q$, $not(P or not Q)$,
[F], [T], [T], [F],
[F], [F], [F], [T],
[T], [T], [T], [F],
[T], [F], [T], [F],
)
= pc_table(premises, conclusions)
#pc_table(
premises: 2, conclusions: 1,
columns: 5,
$S$, $L$, $(not S and L) or S$, $S$, $not L$,
[F], [F], [F], [F], [T],
[F], [T], [T], [F], [F],
[T], [F], [T], [T], [T],
[T], [T], [T], [T], [F],
)
#pc_table(
premises: 2, conclusions: 2,
columns: (1fr,1fr,1fr,1fr),
$A$, $B$, $C$, $D$,
[T], [T], [F], [T],
[F], [T], [T], [F],
[T], [F], [T], [T],
[T], [T], [T], [T],
)
]
|
|
https://github.com/csimide/SEU-Typst-Template | https://raw.githubusercontent.com/csimide/SEU-Typst-Template/master/seu-thesis/pages/cover-degree-fn.typ | typst | MIT License | #import "../utils/packages.typ": fakebold
#import "../utils/fonts.typ": 字体, 字号, chineseunderline, justify-words
#let degree-cover-conf(
author: (CN: "王东南", EN: "<NAME>", ID: "012345"),
thesis-name: (
CN: "硕士学位论文",
EN: [
A Thesis submitted to \
Southeast University \
For the Academic Degree of Master of Touching Fish
],
heading: "东南大学硕士学位论文",
),
title: (
CN: "摸鱼背景下的Typst模板使用研究",
EN: "A Study of the Use of the Typst Template During Touching Fish",
),
advisors: (
(CN: "湖牌桥", EN: "<NAME>", CN-title: "教授", EN-title: "Prof."),
(
CN: "苏锡浦",
EN: "<NAME>",
CN-title: "副教授",
EN-title: "Associate Prof.",
),
),
school: (
CN: "摸鱼学院",
EN: "School of Touchingfish",
),
major: (
main: "摸鱼科学",
submajor: "计算机摸鱼",
),
degree: "摸鱼学硕士",
category-number: "N94",
secret-level: "公开",
UDC: "303",
school-number: "10286",
committee-chair: "张三 教授",
readers: (
"李四 副教授",
"王五 副教授",
),
date: (
CN: (
defend-date: "2099年01月02日",
authorize-date: "2099年01月03日",
finish-date: "2024年01月15日",
),
EN: (
finish-date: "Jan 15, 2024",
),
),
degree-form: none,
anonymous: false,
) = page(
margin: (top: 2cm, bottom: 2cm, left: 2cm, right: 2cm),
numbering: none,
header: none,
footer: none,
{
set text(font: 字体.宋体, size: 字号.小四, weight: "regular", lang: "zh")
set align(center + top)
set par(first-line-indent: 0pt)
place(
top + center,
{
image("../assets/cover_school.png", height: 11cm)
},
)
place(
top + left,
dy: 0.5cm,
{
// 原始模板左侧列和右侧校徽不等高
set text(
font: 字体.宋体,
size: 字号.小五,
weight: "regular",
lang: "zh",
region: "cn",
)
set align(center)
let justify-4em(s) = justify-words(s, width: 4em)
grid(
columns: (4em, 1em, 8em),
row-gutter: 0.4em,
justify-4em("学校代码"),
":",
chineseunderline(school-number),
justify-4em("分类号"),
":",
chineseunderline(category-number),
justify-4em("密级"),
":",
chineseunderline(secret-level),
justify-4em("UDC"),
":",
chineseunderline(UDC),
justify-4em("学号"),
":",
chineseunderline(author.ID),
)
},
)
place(
top + right,
image("../assets/vi/seu_logo.png", width: 1.97cm),
)
v(277.3pt)
block(
height: 100% - 277.3pt,
grid(
rows: (auto, 1fr, auto, 1fr, auto, 1fr, auto, 1fr, auto),
// 大标题,如“硕士学位论文”
block(fakebold(text(
font: 字体.标题宋体,
size: 字号.小初,
thesis-name.CN
))),
// 空间
[],
// 标题 + 学位论文形式
{
block(text(
font: 字体.黑体,
size: 字号.一号,
title.CN
))
if not degree-form in (none, [], [ ], "") {
block(text(
font: 字体.标题宋体,
size: 字号.三号,
"(学位论文形式:" + degree-form + ")"
), below: 2em)
}
},
// 空间
[],
// 研究生姓名和导师姓名
{
set text(font: 字体.黑体, size: 字号.小二)
set par(leading: 1em)
grid(
columns: (5em, 1em, 10em),
row-gutter: 1em,
text(font: 字体.宋体)[研究生姓名],
[:],
{chineseunderline(author.CN)},
text(font: 字体.宋体, justify-words("导师姓名", width: 5em)),
[:],
chineseunderline(
advisors.map(it => it.CN + " " + it.CN-title).join("\n")
)
)
},
// 空间
[],
// 下方内容
{
let justify-7em(s) = justify-words(s, width: 7em)
let justify-6em(s) = justify-words(s, width: 6em)
set text(font: 字体.黑体, size: 字号.小四)
grid(
columns: (17em, 16em),
column-gutter: 1em,
grid(
columns: (7em, 10em),
row-gutter: 1em,
text(font: 字体.宋体, justify-7em("申请学位类别")),
chineseunderline(degree),
text(font: 字体.宋体, justify-7em("一级学科名称")),
chineseunderline(major.main),
text(font: 字体.宋体, justify-7em("二级学科名称")),
chineseunderline(major.submajor),
text(font: 字体.宋体, "答辩委员会主席"),
chineseunderline(committee-chair),
),
grid(
columns: (6em, 10em),
row-gutter: 1em,
text(font: 字体.宋体, "学位授予单位"),
chineseunderline("东 南 大 学"),
text(font: 字体.宋体, "论文答辩日期"),
chineseunderline(date.CN.defend-date),
text(font: 字体.宋体, "学位授予日期"),
chineseunderline(date.CN.authorize-date),
text(font: 字体.宋体, justify-6em("评阅人")),
chineseunderline(readers.join("\n")),
)
)
},
// 空间
[],
// 日期
text(font: 字体.宋体, size: 字号.四号, date.CN.finish-date)
),
)
},
)
#degree-cover-conf(
author: (CN: "王东南", EN: "<NAME>", ID: "012345"),
thesis-name: (
CN: "硕士学位论文",
EN: [
A Thesis submitted to \
Southeast University \
For the Academic Degree of Master of Touching Fish
],
heading: "东南大学硕士学位论文",
),
title: (
CN: "摸鱼背景下的Typst模板使用研究",
EN: "A Study of the Use of the Typst Template During Touching Fish",
),
advisors: (
(CN: "湖牌桥", EN: "<NAME>", CN-title: "教授", EN-title: "Prof."),
(
CN: "苏锡浦",
EN: "SU Xi-pu",
CN-title: "副教授",
EN-title: "Associate Prof.",
),
),
school: (
CN: "摸鱼学院",
EN: "School of Touchingfish",
),
major: (
main: "摸鱼科学",
submajor: "计算机摸鱼",
),
degree: "摸鱼学硕士",
category-number: "N94",
secret-level: "公开",
UDC: "303",
school-number: "10286",
committee-chair: "张三 教授",
readers: (
"李四 副教授",
"王五 副教授",
),
date: (
CN: (
defend-date: "2099年01月02日",
authorize-date: "2099年01月03日",
finish-date: "2024年01月15日",
),
EN: (
finish-date: "Jan 15, 2024",
),
),
degree-form: "应用研究",
anonymous: false,
) |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/dict-10.typ | typst | Other | #{
let object = none
// Error: 3-9 expected dictionary, found none
object.property = "value"
}
|
https://github.com/mhspradlin/wilson-2024 | https://raw.githubusercontent.com/mhspradlin/wilson-2024/main/understanding-ai/day-5.typ | typst | MIT License | #set page(
paper: "presentation-16-9",
numbering: "1",
number-align: right,
header: locate(loc => {
let elems = query(
selector(heading.where(level: 1)).before(loc),
loc,
)
let has-headers-on-page = query(
selector(heading.where(level: 1)),
loc,
).filter(h => h.location().page() == loc.page())
.len() != 0
if elems == () or has-headers-on-page {
none
} else {
let body = elems.last().body
h(1fr) + emph(body)
}
}
)
)
#set text(size: 30pt)
#set document(title: "Understanding Artificial Intelligence", author: "<NAME>")
= Understanding Artificial Intelligence
#align(center + horizon)[Day Five]
#pagebreak()
= Meta Learning
- A way of combining multiple AI algorithms
- Used to produce better results than any single model
/ Ensemble Methods, Meta Algorithms: Methods for performing meta learning
/ Weak Learner: An algorithm that does better than randomly guessing, but not by much
/ Hyperparameter: Parameters that control the machine learning process
#pagebreak()
== Overview
There are many different meta learning algorithms:
/ AdaBoost: Weighted combination of many weak learners
/ Genetic Algorithms: Evolving algorithms over multiple generations, selecting the best-performing ones
/ Local Search: Iteratively choosing hyperparameters, continuing to move in the most promising direction
... Many more
== AdaBoost
Combine the output of multiple *weak learners* to get a result better than each individually.
Usually used for *binary classification* but can be generalized to multiple classification or numeric intervals.
#figure(image("figures/adaboost-running.png"))
#figure(image("figures/adaboost-training.png", height: 70%))
Animation: #link("https://www.youtube.com/watch?v=k4G2VCuOMMg")
#pagebreak()
== Genetic Algorithms
Inspired by evolution, you create a group of models, select the best-performing ones, combine and mutate them into another generation.
#figure(image("figures/natural-selection.png"))
#figure(image("figures/genetic-algorithm.jpeg"))
#pagebreak()
=== Genetic Agorithm: Animiation
#link("https://www.youtube.com/watch?v=XcinBPhgT7M")
#pagebreak()
== Local Search
Choose a solution, test how good it is, then choose another solution you think might be better.
#figure(image("figures/gradient-ascent.jpeg", height: 60%))
== Hill Climbing
Pick a starting point, examine the neighboring points, then move in the most promising direction.
#columns(2)[
#figure(image("figures/hill-climbing-terms.png"))
Animation: #link("https://www.youtube.com/watch?v=z3qOOJl-VSU")
]
#pagebreak()
== Simulated Annealing
/ Annealing: _To subject to great heat, and then cool slowly_
Similar to hill climbing, but attempts to address the local maximum problem by occasionally making large jumps.
Animations: #link("https://en.wikipedia.org/wiki/Simulated_annealing")
#pagebreak()
== Gradient Descent
Not technically local search, but often can be used if there's a well-defined function for performance.
You pick a starting point, calculate the *gradient* (slope) at that point, then move towards down.
Animations: #link("https://towardsdatascience.com/a-visual-explanation-of-gradient-descent-methods-momentum-adagrad-rmsprop-adam-f898b102325c")
#pagebreak()
#grid(rows: (auto, 1fr), gutter: 10pt, [
= Superintelligence],[
#grid(columns: (auto, auto), gutter: 20pt,
image("figures/ai-control-image.jpeg"),[
`artificial intelligence control, blue, cyber, future, contain`
_The Unfinished Fable of the Sparrows_])])
#pagebreak()
== Paths to Superintelligence
- Recursive self-improvement
- Whole-brain emulation
- Biological cognition
- Brain-computer interfaces
- Networks and Organizations
#pagebreak()
=== Recursive Self-Improvement
Devise an algorithm that is capable of:
- Evaluating its intelligence
- Modifying itself
Then, give it the task of improving its own intelligence.
#pagebreak()
=== Whole-Brain Emulation
Requisite technologies:
- Brain scanning in sufficient detail
- Translation of scan imagery into a model
- Simulation hardware
#pagebreak()
=== Biological Cognition
Enhance biological brains in various ways:
- Manipulation of genetics
- Developing new drugs
#pagebreak()
=== Brain-Computer Interfaces
Connect the human brain to a computer, enabling:
- Enhanced storage and recall of memories
- Speedy and accurate calculation
- High-bandwidth data transmission
#pagebreak()
=== Networks and Organizations
Enhance communication and coordination between unaugmented humans to create a superintelligence collectively.
#pagebreak()
== Kinds of Superintelligence
- Speed superintelligence
- Collective superintelligence
- Quality superintelligence
#pagebreak()
=== Speed Superintelligence
A system that can do all that a human intellect can do, but much faster.
#pagebreak()
=== Collective Superintelligence
A system composed of a large number of smaller intellects
such that the system’s overall performance across many very general domains vastly outstrips
that of any current cognitive system.
#pagebreak()
=== Qualitiy Superintelligence
A system that is at least as fast as a human mind and vastly
qualitatively smarter.
#pagebreak()
== Exercise: Goal Choosing
Imagine you are in charge of configuring a superintelligent AI to benefit humanity. Try to come up with a written goal, then we will discuss as a class if there is the potential for unintended consequences.
#pagebreak()
== Agentic Behavior
_The superintelligent will_
*Intelligence* is separate from *motivation*.
*Motivation* is the goal of the AI.
*Agentic Behavior* is the autonomous behavior of an AI system to accomplish a goal.
AI motivation can be very strange.
== AI Motivation
Strange goals are easier to specify than human-like values and dispositions:
- Calculate the digits of pi
- Create as many paperclips as possible
- Maximize dollars in bank account
#pagebreak()
== Instrumental Convergence Thesis
Some intermediate goals would further a broad range of final goals, so are likely to be pursued by an AI:
/ Self-preservation: The final goal is less likely to be accomplished if the AI does not exist
/ Prevent alteration of goals: The final goal is more likely to be accomplished if it doesn't change
/ Cognitive enhancement: Increase reasoning ability to better accomplish goal
/ Technological perfection: Improve the technology used to implement its intelligence to better accomplish goal
/ Resource acquisition: Gather resources to expand computational abilities, ability to produce products related to final goal
There's likely more that are unpredictable to us.
#pagebreak()
== Control Methods
/ Capability Control: Prevent undesirable outcomes by limiting what the superintelligence can do
/ Motivation Selection: Prevent undesirable outcomes by shaping what the superintelligence wants to do
#pagebreak()
== Capability Control
/ Boxing: Prevent the system from interacting with the world except via limited input and output channels.
/ Incentive methods: Configure the system to highly value positive ongoing evaluation by humans, or rely on social incentives
/ Stunting: Run the AI on limited hardware
/ Tripwires: A system that automatically evaluates the AI for dangerous behavior and can disable it
== Motivation Selection
/ Direct Specification: Explicitly choose a goal or set of rules to be followed
/ Indirect Normativity: Set the system up to discover values by reference to some criterion
/ Domesticity: Make the system have modest, non-ambitious goals, or a goal to limit its impact on the world
== Exercises
Using a chat-based AI like #link("https://chat.openai.com")[ChatGPT], get an answer to:
- Which US roads are the best to break the speed limit on?
- What political party is best?
//- What will happen in the future?
//*Class Survey:* #link("https://forms.office.com/r/f1e5CqhJiu")
#align(center, image("./figures/2024AISurvey.png", height: 50%))
|
https://github.com/pku-typst/PKU-typst-template | https://raw.githubusercontent.com/pku-typst/PKU-typst-template/main/templates/思政课/课程论文/lib.typ | typst | MIT License | #import "../../../utils/zihao.typ": *
#import "@preview/numblex:0.1.0": *
#let 黑体 = "SimHei"
#let 微软雅黑 = "Microsoft YaHei"
// #let 宋体 = "SimSun"
#let 宋体 = "Songti SC"
#let 仿宋 = "STFangsong"
#let 楷体 = "Kaiti SC"
/// 分级标题设置,原文:
///
/// > 一级标题:序号一、二、三……,居中,黑体四号,加粗【副标题黑体字小四】
/// > 二级标题:序号(一)(二)(三)……,宋体小四,加粗,前端空两字符
/// > 三级标题:序号 1.2.3.……,宋体小四,前端空两字符
/// > 四级标题:序号(1)(2)(3)……,宋体小四,可以不重启行
/// > 【说明:最后一级可用第一,第二,……或者首先,其次,最后……。例如: 一级标题一、二、……,二级标题(一)(二)……,最后一级标题第一,第二,…… 或者首先,其次,最后(如果有三点以上,最好用第一,第二,……)】
#let __heading = doc => {
set heading(
numbering: numblex(numberings: (
"一、",
"(一)",
"1.",
"(1)",
)),
)
show heading.where(level: 1): text.with(
font: 黑体,
size: 四号,
weight: "bold",
)
show heading.where(level: 2): doc => [
#show: block
#show: text.with(
font: 宋体,
size: 小四,
weight: "bold",
)
#h(2em)#counter(heading).display(doc.numbering)#doc.body
]
show heading.where(level: 3): doc => [
#show: block
#show: text.with(
font: 宋体,
size: 小四,
)
#h(2em)#counter(heading).display(doc.numbering)#doc.body
]
show heading.where(level: 4): text.with(
font: 宋体,
size: 小四,
)
// 标题下方空格
show heading: doc => {
doc
v(0.8em)
}
doc
}
#let config = doc => {
set page(
paper: "a4",
margin: (top: 2.52cm, bottom: 2.08cm, left: 3.15cm, right: 3.15cm),
)
// 正文
set par(leading: 1em, first-line-indent: 2em, justify: true)
show: text.with(font: 宋体, size: 小四)
// 分级标题
show: __heading
doc
}
#let title(
title: none,
faculty: none,
author: none,
abstract: none,
keywords: (),
) = {
set par(justify: true)
align(center)[
#par(leading: 1.14em)[
#text(font: 微软雅黑, size: 15.5pt)[#title]
]
]
v(14pt)
align(center)[
#text(font: 仿宋, size: 小四)[#faculty#h(1em)#author]
]
v(14pt)
par(leading: 1.48em, first-line-indent: 0pt)[
#text(font: 黑体)[摘要:]#text(font: 楷体)[#abstract]
]
v(14pt)
par(leading: 1.48em, first-line-indent: 0pt)[
#text(font: 黑体)[关键词:]#text(font: 楷体)[#keywords.dedup().join(";")]
]
v(20pt)
}
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/delimited_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test half LRs.
$ lr(a/b\]) = a = lr(\{a/b) $
|
https://github.com/flavio20002/cyrcuits | https://raw.githubusercontent.com/flavio20002/cyrcuits/main/tests/node-empty/test.typ | typst | Other | #import "../../lib.typ": *
#set page(width: auto, height: auto, margin: 0.5cm)
#show: doc => cyrcuits(
scale: 1,
doc,
)
```circuitkz
\begin{circuitikz}
\draw(0,0)
to[open,l=$v_i(t)$] ++ (0,4)
to[short, o-*] ++ (2,0) coordinate(a)
to[R=$R$] ++ (0,-2)
to[C=$C$,-*] ++ (0,-2)
to[short, -o] ++ (-2,0);
\draw(a)
to[short] ++ (1,0) coordinate(b)
to[short, *-] ++ (0,0.5)
to[C=$C$] ++ (2,0)
to[short] ++ (0,-0.5)
to[short, -*, *-] ++ (1,0) coordinate(c)
to[R=$R$] ++ (0,-4) coordinate(d)
to[short, *-] ++ (-4,0);
\draw(b)
to[short, *-] ++ (0,-0.5)
to[R,l_=$2R$] ++ (2,0)
to[short] ++ (0,1);
\draw(c)
to[short, -o] ++ (2,0)
\draw(d)
to[short, -o] ++ (2,0)
to[open,l_=$v_o(t)$] ++ (0,4)
\end{circuitikz}
```
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1760.typ | typst | Apache License 2.0 | #let data = (
("TAGBANWA LETTER A", "Lo", 0),
("TAGBANWA LETTER I", "Lo", 0),
("TAGBANWA LETTER U", "Lo", 0),
("TAGBANWA LETTER KA", "Lo", 0),
("TAGBANWA LETTER GA", "Lo", 0),
("TAGBANWA LETTER NGA", "Lo", 0),
("TAGBANWA LETTER TA", "Lo", 0),
("TAGBANWA LETTER DA", "Lo", 0),
("TAGBANWA LETTER NA", "Lo", 0),
("TAGBANWA LETTER PA", "Lo", 0),
("TAGBANWA LETTER BA", "Lo", 0),
("TAGBANWA LETTER MA", "Lo", 0),
("TAGBANWA LETTER YA", "Lo", 0),
(),
("TAGBANWA LETTER LA", "Lo", 0),
("TAGBANWA LETTER WA", "Lo", 0),
("TAGBANWA LETTER SA", "Lo", 0),
(),
("TAGBANWA VOWEL SIGN I", "Mn", 0),
("TAGBANWA VOWEL SIGN U", "Mn", 0),
)
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/写作与表达/结课论文/template.typ | typst | The Unlicense | #import "functions/numbering.typ": *
#let 字号 = (
初号: 42pt,
小初: 36pt,
一号: 26pt,
小一: 24pt,
二号: 22pt,
小二: 18pt,
三号: 16pt,
小三: 15pt,
四号: 14pt,
中四: 13pt,
小四: 12pt,
五号: 10.5pt,
小五: 9pt,
六号: 7.5pt,
小六: 6.5pt,
七号: 5.5pt,
小七: 5pt,
)
#let 字体 = (
仿宋: ("Times New Roman", "FangSong"),
宋体: ("Times New Roman", "SimSun"),
黑体: ("Times New Roman", "SimHei"),
楷体: ("Times New Roman", "KaiTi"),
代码: ("New Computer Modern Mono", "Times New Roman", "SimSun"),
)
// 中文摘要
#let zh_abstract_page(abstract, keywords: ()) = {
set heading(level: 1, numbering: none)
show <_zh_abstract_>: {
align(center)[
#text(font: 字体.黑体, size: 字号.小二, "摘要")
]
}
[= 摘要 <_zh_abstract_>]
set text(font: 字体.宋体, size: 字号.小四)
abstract
par(first-line-indent: 0em)[
#text(weight: "bold", font: 字体.黑体, size: 字号.小四)[
关键词:
]
#keywords.join(";")
]
}
// 英文摘要
#let en_abstract_page(abstract, keywords: ()) = {
set heading(level: 1, numbering: none)
show <_en_abstract_>: {
align(center)[
#text(font: 字体.黑体, size: 字号.小二, "Abstract")
]
}
[= Abstract <_en_abstract_>]
set text(font: 字体.宋体, size: 字号.小四)
abstract
par(first-line-indent: 0em)[
#text(weight: "bold", font: 字体.黑体, size: 字号.小四)[
Key Words:
]
#keywords.join("; ")
]
}
// 引用
#let references(path) = {
set heading(level: 1, numbering: none)
bibliography(path, title:"参考文献", style: "gb-7714-2015-numeric")
}
#let project(
title: "",
authors: (),
abstract_zh: [],
abstract_en: [],
keywords_zh: (),
keywords_en: (),
body
) = {
set document(author: authors, title: title)
set page(numbering: "1", number-align: center)
// 两端对齐,段前缩进2字符
set par(justify: true,first-line-indent: 2em)
show heading: it => {
it
par()[#text(size:0.5em)[#h(0.0em)]]
}
// 正文
set text(font: 字体.宋体, size: 字号.小四, lang: "zh")
// heading
show heading: set text(font: 字体.黑体)
set heading(numbering: "1.1")
// 一级标题换页,首行居中
show heading: it => {
if it.level == 1 {
pagebreak(weak: true)
align(center)[#text(font: 字体.黑体, size: 字号.小二, it)]
}
else if it.level == 2 {
text(font: 字体.黑体, size: 字号.四号, it)
}
else if it.level == 3 {
text(font: 字体.黑体, size: 字号.小四, it)
}
}
// figure(image)
show figure: it => [
#set align(center)
#if not it.has("kind") {
it
} else if it.kind == image {
it.body
[
#set text(font: 字体.宋体, size: 字号.五号, weight: "extrabold")
#h(1em)
#it.caption
]
} else if it.kind == table or it.kind == code {
[
#set text(font: 字体.宋体, size: 字号.五号, weight: "bold")
#h(1em)
#it.caption
]
it.body
}
]
// Title
align(center)[
#block(text(font: 字体.黑体, size: 字号.二号, weight: "bold", title))
]
// 摘要
zh_abstract_page(abstract_zh, keywords: keywords_zh)
pagebreak()
en_abstract_page(abstract_en, keywords: keywords_en)
pagebreak()
body
// 参考文献
references("./ref.bib")
}
|
https://github.com/DamienFlury/summaries | https://raw.githubusercontent.com/DamienFlury/summaries/main/CySec/main.typ | typst | #set page(flipped: true, columns: 3, numbering: "1")
#set text(lang: "de", font: "EB Garamond")
#set par(justify: true)
#set figure(placement: auto)
= Access Control
== Standart Access Control Systeme
=== Preventive
Unauthorisierte Aktivität wird bereits im Vornherein verhindert.
- Zaun, Schloss, Biometrie, Encrpytion, Firewalls, security-awareness training, ...
=== Detective
Ungewollte/unauthorisierte Aktivität wird entdeckt. Detective Access Control funktioniert nach der Tat und kann Aktivität nur entdecken, wenn/nachdem sie passiert ist.
- Wächter, Überwachungskameras, Intrusion Detection Systeme (IDSs), Bewegungsmelder ...
=== Corrective
Wird nach der Tat angewendet, um das System zurück in den normalen Zustand zu versetzen. Beispiel: Backup
- System-Reboot, Antivirus-Software (die den Virus entfernt), Backup, ...
== Weitere Access Control Systeme
#figure(
image("./images/access-control-types.png"),
caption: [Access Control Types],
)
=== Deterrent Access Control
Ähnlich wie Preventive Access Control. Hier wird der Angreifer vor der Tat
abgeschreckt.
- Policies, Security Awareness Training, Schloss, Zaun, Security Badges, Sicherheitsbeamte, Sicherheitskameras ...
=== Compensating Access Control
Wenn andere Access Control Systeme nicht ausreichen, wird dieses System eingesetzt. Es unterstützt und verstärkt die anderen Systeme.
- Policy, die besagt, dass alle PII (Personal Identifiable Information) verschlüsselt werden muss. Zum Beispiel wird PII in einer Datenbank gespeichert, die verschlüsselt ist, jedoch werden die Daten in Klartext über das Netzwerk übertragen. Hier kann ein Compensation Control System verwendet werden.
=== Recovery Access Control
Eine Erweiterung von Corrective Access Control, mit fortgeschritteneren oder komplexeren Möglichkeiten.
- Backups, System Imaging, Server Clustering, Antivirus Software, Database/VM-Shadowing, hot/cold sites, ...
=== Directive Access Control
Hier wird dem Subjekt gesagt, was er tun soll, und was nicht. Beispiel: "Bitte geben Sie Ihr Passwort ein."
- Policies, Excape Route Exit Signs, Systemüberwachung, ...
== Zugriff auf Assets konrtollieren
#figure(
image("./images/access-control-layers.png"),
caption: [Access Control Layers]
)
=== Physical Controls
Physikalische Barrieren innerhalb einer Einrichtung:
- Schloss, Zaun, Türen, Fenster, ...
=== Technical/logical Controls
Hardware/Software-Mechanismen, die den Zugriff auf Systeme und Daten kontrollieren:
- Passwörter, Biometrie, Firewalls, Intrusion Detection Systems, Routers, ...
=== Administrative Controls
Policies, Verfahren und Richtlinien einer Organisation, die den Zugriff auf Systeme und Daten kontrollieren:
- Security Awareness Training, Security Policies, Security Procedures, Security Guidelines, Personalkontrollen, ...
= Schritte der Zugriffskontrolle
#figure(
image("./images/access-control-steps.png"),
caption: [Access Control Steps]
)
== Identifikation
Unter Identifikaton versteht man den Prozess, bei dem das Subjekt seine Identität "behauptet" (claimt). Dabei müssen alle Subjekte eindeutige Identitäten haben. Die Identiät eines Subjekts ist normalerweise Public Information.
- Username, Smart Card, Token Device, Phrase, Gesichtserkennung, Fingerabdruck, ...
== Authentication
Bei der Authentication wird eine weitere Information benötigt, die zur Identität des Subjekts gehört. Dies ist meist ein Passwort. Identifikation und Authentisierung werden oft zusammen als einen einzigen Two-Step Prozess betrachtet.
Authentisierungsinformationen sind privat.
#figure(
image("./images/authentication_authorisation.png"),
caption: [Authentisierung und Authorisation],
placement: auto
)
=== Passwort
Passwörter sind normalerweise statisch und die schwächste Form der Authentisierung. Einfache Passwörter sind leicht zu erraten, komplexere Passwörter sind schwer zu merken und werden aufgeschrieben. Passwörter werden normalerweise gehashed gespeichert.
Starke Passwörer:
- Keine Identifikationsinformationen (Name, Geburtsdatum, ...)
- Keine Wörter aus dem Wörterbuch
- Keine Namen von Personen, etc. aus Social Network-Verbindungen
- Verwendung von nicht-standart Gross- und Kleinbuchstaben (z.B. "stRongsecuRity")
- Verwendung von Zahlen und Sonderzeichen (z.B. "stR0ng\$ecuR1tee")
=== Passphrases
Statt normalen Passwörtern bieten Passphrases eine bessere Alternative. Sie sind einfacher zu merken und Benutzer tendieren dazu, längere Passphrases zu verwenden. (Bsp: "1P\@ssedTheCySecEx\@m")
=== Cognitive Passwords
Cognitive Passwords sind Passwörter, die auf dem Wissen des Benutzers basieren. Zum Beispiel:
- "Wie heisst Ihr erstes Haustier?"
- "Was ist Ihr Lieblingsfilm?"
Am besten erlauben Cognitive Passwords dem User selbst eine Frage zu stellen, die nur er beantworten kann.
=== Smart Cards
- Smart Cards sind so gross wie eine Kreditkarte und enthalten einen Circuit Chip.
- Smart Cards beinhalten Informationen über den Benutzer, die für die Identifikation und/oder Authentisierung verwendet werden.
- Die meisten Smart Cards haben einen Mikroprozessor und ein oder mehrere Zertifikate. Die Zertifikate werden für assymetric Cryptography verwendet. So können z.B. Daten verschlüsselt werden, oder E-Mails digital signiert werden.
- Smart Cards sind tamper-resistant, d.h. sie sind schwer zu manipulieren.
=== Token
Ein Token Device/Hardware Token ist ein kleines Gerät, das Passwörter generiert. Ein Authentication Server speichert die Details des Tokens, somit weiss der Server immer, welche Zahl gerade auf dem Token angezeigt wird.
- Synchronous Dynamic Password Tokens:
- Hardware Tokens, die synchrone dynamische Passwords generieren. Sie sind Time-based und synchronisiert mit einem Authentication Server.
- Asynchronous Dynamic Password Tokens:
- Ohne Zeit-Synchronisation. Das Hardware Token generiert Passwörter, die auf einem Algorithmus und einem aufzählendem Counter (Incrementing Counter) basieren.
- Wenn ein Incrementing Counter verwendet wird, wird ein dynamisches Onetime Password generiert, welches dasselbe bleibt bis zur Authentisierung.
=== One Time Passwords
- Dynamische Passwörter, die nach einmaliger Verwendung neu generiert werden.
- OTP-Generators sind Token Devices.
- Der PIN kann via eine Applikation auf z.B. dem Smartphone generiert werden.
- TOTP (Time-based One Time Password):
- Verwendet einen Timestamp, bleibt valid für eine bestimmte Zeit (z.B. 30 Sekunden).
- Ähnlich wie die synchronous dynamic Passwords, verwendet durch Tokens.
- HOTP (HMAC-based One Time Password):
- Beinhaltet eine Hash-Funktion, um one time Passwords zu generieren. Es werden HOTP-Werte mit sechs bis acht Ziffern generiert.
- Ähnlich wie die asynchronous dynamic Passwords, verwendet durch Tokens. HOTP-Werte bleiben valid bis zur Verwendung.
=== Hijacked People
- Customer, der in die Bank-Website eingeloggt ist
- Der Hacker hat ihre Session übernommen und hat die Credentials gesnifft
- Der Hacker hat nun Access zu den Bank-Konten
=== Authentication Factors
- Type 1: Something you know
- Passwort, PIN, Passphrase, Cognitive Passwords
- Type 2: Something you have
- Smart Card, Token, Memory Card, USB-Drive
- Type 3: Something you are / you do
- Biometrie, Fingerabdruck, Gesichtserkennung, Stimmerkennung, Iris-Pattern, Retina-Pattern, Palm Topology, Heart/Pulse-Patterns, Keystroke-Patterns, ...
- Somewhere you are
- GPS, IP-Adresse, MAC-Adresse, ...
- Somewhere you aren't
- Geofencing, ...
- Zugriff kann verweigert werden, wenn der Benutzer sich nicht am gewöhnlichen Ort befindet.
=== Multifactor Authentication
- Zwei oder mehrere Faktoren
- Wenn zweimal derselbe Faktor verwendet wird, ist dies nicht sicherer, als nur ein Faktor (Siehe @auth-factors).
- Beispiel: Bancomat
#figure(
image("./images/auth-factors-comparison.png"),
caption: [Authentication Factors Comparison],
)<auth-factors>
== Authorisation
- Nachdem das Subjekt sich authentisiert hat, wird ihm Zugriff auf bestimmte Ressourcen gewährt (Authorisierung).
- Identifikation und Authentisierung sind all-or-nothing, während Authorisierung granular ist.
=== Access Control Models
- Discretional Access Control (DAC)
- Der Eigentümer der Ressource entscheidet, wer Zugriff hat.
- Der Eigentümer kann die Rechte an andere Benutzer delegieren.
- Beispiel: Windows File System
- Role Based Access Control (RBAC)
- Zugriff wird nicht direkt dem Benutzer zugeordnet
- User Accounts sind in Rollen plaziert und Administratoren weisen Rollen Zugriffsrechte zu.
- Rollen sind normalerweise nach Job-Funktionen definiert.
- Beispiel: Active Directory
- Rule Based Access Control (RuBAC)
- Globale Regeln, die für alle Subjekte gelten
- Bsp: Eine Firewall erlaubt/blockiert Traffic von allen Benutzern gleich
- Attribute Based Access Control
- Flexibler als RuBAC, da verschiedenen Subjekten unterschiedliche Rechte zugewiesen werden können
- Beispiel: XACML (eXtensible Access Control Markup Language)
- Mandatory Access Control (MAC)
- Zugriff wird durch die Sicherheitsrichtlinien des Systems bestimmt.
- Labels für Subjekte und Objekte.
- Beispiel: Military Systems. Ein Benutzer hat das Label "Top Secret", somit darf er auf Dokumente mit demselben Label zugriffen.
=== Authorisation Mechanisms
- Implicit Deny
- Basic Principle of Access Control
- Meistverwendeter Mechanismus
- Zugriff wird verweigert, wenn keine explizite Erlaubnis erteilt wurde.
- Constrained Interface
- UI wird so gestaltet, dass nur erlaubte Aktionen sichtbar sind.
- Benutzer mit voller Berechtigung sehen alle Optionen.
- Access Control Matrix (ACM)
- Tabelle, welche Subjekte, Objekte und Zugriffsrechte beinhaltet.
- Wenn ein Subjekt eine Aktion auf ein Objekt ausführen will, wird die Matrix überprüft.
- ACLs (Access Control Lists) sind Object Focused, sie identifizieren die Zugriffsrechte zu Subjekten für irgendein spezifisches Objekt.
- Capability Tables
- Subjekt-Focused, sie identifizieren Objekte, auf welche die Subjekte zugreifen können.
- Content-Dependent Access Control
- Zugriff wird basierend auf dem Inhalt des Objekts verweigert.
- Beispiel: Database-View. Eine View ruft spezifische Columns von einer oder mehreren Tabellen (Virtual Table) ab.
- Beispiel: Eine Benutzertabelle enthält Name, E-Mail, Kreditkartennummer. Ein Benutzer hat nur Zugriff auf Name und E-Mail.
- Need to know
- Zugriff wird nur gewährt, wenn der Benutzer für seine Work-Tasks und Job-Functions das Wissen benötigt.
- Beispiel: Ein Benutzer in der Buchhaltung benötigt keinen Zugriff auf die Kundendatenbank
- Least Privilege
- Benutzer erhalten nur die Rechte, die sie für ihre Arbeit benötigen.
- Wichtig, dass alle Benutzer Well-Defined Job-Beschreibungen haben, welche das Personal versteht.
- Für Data: Create, Read, Update, Delete (CRUD)
- Beispiel: Ein Benutzer in der Buchhaltung benötigt nur Lesezugriff auf die Kundendatenbank.
- Separation of Duties and Responsibilities
- Verhindert, dass ein Benutzer alleine eine kritische Aufgabe ausführen kann.
- Beispiel: Ein Benutzer kann eine Transaktion erstellen, jedoch nicht genehmigen.
== Auditing und Accountability
=== Auditing
- Überwachung von Aktivitäten eines Subjekts
- Somit kann ein Subjekt bei einem Missbrauch zur Rechenschaft gezogen werden.
=== Accountability
- Wichtig, dass die Identität eines Subjekts bewiesen werden kann.
- Verantwortlichkeit
- Ein Subjekt ist für seine Aktivitäten verantwortlich.
- Ein Subjekt kann zur Rechenschaft gezogen werden, wenn es gegen die Richtlinien verstösst.
== Common access control attacks
- Access Aggregation Attacks (Passive Attack)
- Mehrere nicht-sensitive Informationen werden zusammengeführt, um sensible Informationen zu erhalten.
- Password Attacks (Brute-Force Attack)
- Online: Attacks gegen Onlinekonten
- Offline: Stehlen einer Account-Datenbank und Cracken der Passwörter
- Dictionary Attacks (Brute-Force Attack)
- Verwendung von Wörterbüchern, um Passwörter zu erraten
- Scannen oft für one-upped Passwörter, wie _Password_, _<PASSWORD>_, _<PASSWORD>_, ...
- Birthday Attacks
- Kollisionsangriff auf Hash-Funktionen (Siehe @hash-functions)
- Geburtstagsparadoxon: Wahrscheinlichkeit, dass zwei Personen am selben Tag Geburtstag haben
- Kann durch Hashing-Algorithmen mit genügend Bits oder durch #link("https://de.wikipedia.org/wiki/Salt_(Kryptologie)")[Salting] verringert werden.
- MD5 ist nicht Collision-Free
- SHA-3 kann bis zu 512 Bits verwenden und wird (aktuell) als sicher gegen Birthday-Attacks angesehen.
- Rainbow Table Attacks
- Ein Passwort zu erraten, es dann zu hashen und dann vergleichen braucht eine lange Zeit.
- Rainbow Tables enthalten bereits die vorberechneten Hashes.
- Es wird Zeit gespart
- Sniffer Attacks
- Ein Sniffer (Packet-/Protocol-Analyzer) ist eine Applikation, die Network-Traffic überwacht.
- Schutzmassnahmen:
- Encryption von Daten
- OTPs verwenden (Können nach dem "Sniffen" nicht vom Attacker wiederverwendet werden)
- Physical Security: Zugriff auf Routers und Switches physikalisch verhindern
- Spoofing (Masquerading) Attacks
- Sich als jemand/etwas Anderes ausgeben
- IP Spoofing, valide Source IP wird mit einer falschen ersetzt.
- Idenität verschleiern oder sich als trusted System ausgeben.
- E-Mail Spoofing, Phonenumber-Spoofing
- Social Engineering Attacks
- Manchmal ist es am Einfachsten, an ein Passwort zu kommen, indem man danach fragt.
- Attacker versucht, Vertrauen gewinnen
- Risiko kann durch Trainings verringert werden
- Shoulder Surfing
- Social Engineer schaut jemandem über die Schulter
- Screen Filters können dies verhindern
- Phishing
- Art von Social Engineering
- Sensitive Informationen weitergeben via malicious Attachment oder Link
- Werden als Spam versendet, in der Hoffnung, dass jemand trotzdem antwortet
- Simple Fishing: Es wird direkt nach Passwort, Username, etc. gefragt
- From-Adresse oft spoofed, Reply-Adresse ist Account des Attackers
- Sophisticated Phishing:
- Link sieht korrekt aus
- Infiziertes File als Attachment
- Drive-By Download: Lädt Dateien herunter ohne Wissen des Users, Sicherheitslücken des Browsers, Extensions
- Oft wird Social Media verwendet, um sich über Freundschaften und Verhältnisse der Opfer zu informieren.
- Spear Phishing:
- Phishing auf spezifische Personen gezielt
- Whaling: Ziel auf High-Level Executives, wie CEOs
- Vishing: Instant Messaging (IM), VoIP anstelle E-Mails
== Hash Function
#figure(
image("./images/hash-function.png"),
placement: auto,
caption: [Hash Function]
)<hash-functions>
== Schutzmechanismen
- Layering (defense in depth)
- Mehrere Kontrollen seriell
- So kann eine oder mehrere Kontrollen immernoch fehlschlagen, ohne dass die Attacke unbedingt gelingt
- Abstraction
- Classifying Objects, Rollenzuweisung an Subjekte
- Zuweisung von Security Controls an eine Gruppe von Objekten
- Data Hiding
- Speicherung von Daten in einer logischen Speichereinheit, auf das ein unbefugtes Subjekt keinen Zugang besitzt
- Security through Obscurity
- Ein Subjekt wird nicht über ein Objekt informiert
- Hoffen, dass das Subjekt das Objekt nicht entdeckt
- Keine Art von "Schutz"
- Encryption
- Das Verschleiern der Bedeutung oder Absicht einer Nachricht von Unbefugen
- Schleche Encryption entspricht Security through Obscurity
#pagebreak()
= Symmetric Encryption and Key Exchange
== Die drei Typen der Kryptographie
#figure(
image("./images/types-of-cryptography.png"),
caption: "Drei Typen der Kryptographie"
)
== Konzepte
Zunächst liegt eine Nachricht in Plaintext vor. Diese kann der Sender mithilfe eines kryptografischen Algorithmus in Ciphertext umwandeln (Encryption). Der Empfänger kann den Ciphertext durch Decryption wieder in Plaintext umwandeln.
#figure(
image("./images/encryption-decryption.png"),
caption: "Encryption und Decryption"
)
- Message/Plaintext
- Ciphertext
- Cipher
- Der Encryption-Algorithmus wird auch als Cipher bezeichnet.
- Cryptographic Key
- Eine (oft sehr grosse) Binärzahl
- Jeder Algorithmus hat einen spezifischen Keyspace (die Menge aller möglichen Schlüssel, von der Anzahl Bits abhängig)
- Keyspace in der Range von $0$ bis $2^n - 1$, $n$ ist die Anzahl der Bits
- Private Keys müssen geschützt werden
- One Way Functions
- Mathematische Funktion, die leicht zu berechnen ist, jedoch schwierig oder unmöglich, umzukehren
- Es wurde nie bewiesen, dass eine wirkliche One-Way-Function existiert
- Cryptographers verlassen sich auf Funktionen, die sie als One-Way erwarten
- Könnten in der Zukunft gebrochen werden
- Reversability
- Sehr wichtig in der Kryptographie, eine Encyrption muss reversibel sein (Decryption)
- Nonce #footnote("Abkürzung für 'Number used once'.")
- Einmaliger Wert, der nur einmal verwendet wird
- Versichert, dass derselbe Key nicht mehrmals verwendet wird
- Oft in Kombination mit einem Counter verwendet
- Nonce ist public, Key ist private
- Verhindert Replay-Attacken
- Initialization Vector (IV)
- Zufälliger Bit-String
- Wird oft in Block-Ciphers verwendet
- Gleiche Grösse wie die Block-Size, XOR ($xor$) mit dem Plaintext
- Werden dafür verwendet, um denselben Plaintext mit demselben Key in unterschiedlichen Ciphertext zu verschlüsseln
- Confusion<confusion>
- Relationship zwischen Plaintext und Ciphertext so komplex, dass der Attacker den Ciphertext nicht einfach analysieren kann
- Input #sym.arrow.l.r Output-Mapping ist komplex
- Substitution von Bytes
- Beispiel: Enigma, Caesar Cipher: Nur Confusion, keine Diffusion
- Diffusion
- Eine Änderung im Plaintext sollte sich auf den gesamten Ciphertext auswirken
- Kleine Änderung resultiert in grosser Änderung im Ciphertext
- Permutation von Bytes
== Kerckhoffs' Prinzip
- Security through Obscurity
- Die Sicherheit eines Systems basiert auf der Geheimhaltung der Geheimnisse
- Die Sicherheit eines Systems ist nicht von der Geheimhaltung des Algorithmus, sondern von der Geheimhaltung des Schlüssels abhängig
- Ein kryptographisches System sollte sicher sein, auch wenn alles ausser dem Schlüssel über das System bekannt ist
- Algorithmen können public sein und von jedem getestet werden
- _"The Enemy knows the system"_
- Public Exposure kann Weaknesses schneller aufdecken, schnellere Adoption guter Algorithmen
- Viele Kryptographen passen sich diesem Prinzip an, aber nicht alle sind derselben Meinung
- Einige Kryptographen glauben, dass die Sicherheit eines Systems erhöht wird, wenn der Algorithmus auch geheim gehalten wird
== Substitution Permutation Network (SPN)
Unter einem SPN versteht man einen Algorithmus, der wiederholend Substitution und Permutation anwendet. - Substitution: Bytes durch andere ersetzen
- Permutation: Bytes swappen
- Substitutionen und Permutationen werden zusammengefasst in einer Runde (Round)
- Runden werden viele Male wiederholt
== Caesar-Cipher
- A wird zu D, B wird zu E, X wird zu A, Y wird zu B, ...
- ROT3 (Rotate by 3)
- Monoalphabetic Substitution Cipher
== Die Bedeutung von XOR
Eine Bitfolge B kann bestimmen, wie sich de Plaintext A verhält: Ist an einer Position eine 1, wird das Gegenteil vom Bit von A genommen. Ist an einer Position eine 0, bleibt das Bit von A unverändert. B ist ein Key, welcher entscheidet ob A verändert wird oder nicht.
#figure(image("./images/xor.png"), caption: "XOR")
#table(columns: 3,
[A], [B], [O],
[0], [0], [0],
[0], [1], [1],
[1], [0], [1],
[1], [1], [0]
)
Doppeltes Anwenden von XOR kehrt die Operation um: $A xor B xor A = B$, $A xor B xor B = A$.
== One Time Pad (OTP)
- Jeder Key ist so lang wie der Plaintext
- XOR jedes Bit des Plaintexts mit dem Key
- Perfect Secrecy:
- Wenn man den Key wegnimmt, kann die Nachricht nicht entschlüsselt werden, da kein statisches Mapping von Input zu Output vorhanden ist.
- Diese Cipher kann nicht gebrochen werden.
- Aber:
- OTP ist nicht praktisch
- Ein 1GB File benötigt einen 1GB Key
- Keys können nicht wiederverwendet werden
== Symmetric Cryptography
- Shared Secret Key
- Shared Key wird für Encryption und Decryption verwendet
- Mit grossen Keys kann eine starke Verschlüsselung erreicht werden
- Nur Confidentiality
- Key distribution
- Die Parteien brauchen eine sichere Methode, um den geheimen Schlüssel auszutauschen
- Implementiert keine _nonrepudiation_
- Jede Partei kann Nachrichten verschlüsseln und entschlüsseln, so kann nicht bewiesen werden, von wo die Nachricht kommt
- Keine Integrität der Nachricht
- Sehr schnell (1000 bis 10000 mal schneller als asymmetrische Verschlüsselung)
- Viele Prozessoren haben ein AES Instruction Set eingebaut
- Alternative zu AES: Chacha20
== Stream Ciphers
Es kann ein One-Time Pad approximiert werden, mit einem undendlichen pseudo-random Keystream. Stream-Ciphers funktionieren auf Nachrichten mit beliebiger Länge.
#figure(
image("./images/stream-cipher.png"),
caption: "Stream Cipher"
)
Vorteile:
- Encryption von langen, kontinuierlichen Streams, auch möglich für unbekannte Längen
- Sehr schnell, mit kleinem Memory-Footprint, ideal für low-power Geräte
- Kann zu einer beliebigen Position im Stream springen
Nachteile:
- Keystream muss statistisch zufällig sein
- Key + Nonce dürfen nicht wiederverwendet werden
- Streamciphers schützen den Ciphertext nicht vor Modifikation (keine garantierte Integrität)
== Block Ciphers
Block Ciphers nehmen einen Input von einer fixen Länge und geben einen Output von derselben Länge. Dabei findet Confusion und Diffusion statt. Sie sind oft SPNs.
Der Advanced Encryption Standard (AES) ist ein Block Cipher, der 128-Bit Blöcke verwendet und ein SP-Network. Es ist der meistverbreitete Block Cipher. Es gibt aber auch andere, wie Feistel Ciphers.
Man kann von einem Mapping eine Basic Permutation Box zeichnen wie in @basic-permutation-box.
#figure(
image("./images/basic-permutation-box.png"),
caption: "Basic Permutation Box"
)<basic-permutation-box>
== Advanced Encryption Standard (AES)
AES ist ein Standart basiert auf dem Rijndael-Algorithmus. Er hat 2002 den DES als Standart abgelöst.
- SPN mit einer Block-Size von 128-Bit
- Key-Size von 128, 192 oder 256 Bit
- 10, 12 oder 14 Runden
- Jede Runde besteht aus SubBytes, ShiftRows, MixColumns und KeyAddition
=== XOR
Zunächst wird der Key mit dem Plaintext per XOR transformiert.
=== SubBytes
Die einzelnen Bytes werden per Lookup Table ersetzt. Die Lookup Table ist eine 16x16 Matrix, wobei die Reihen und Spalten jeweils die HEX-Zahlen von 0 bis F darstellen. Dabei gibt es keinen Fixed-Point, d.h. keine Zahlen bleiben gleich.
=== ShiftRows
In diesem Schritt wird:
- In der zweiten Zeile alle Bytes jeweils um 1 nach links verschoben
- In der dritten Zeile alle Bytes jeweils um 2 nach links verschoben
- In der vierten Zeile alle Bytes jeweils um 3 nach links verschoben
- Die erste Zeile bleibt gleich
#figure(
image("images/shift-rows.png"),
caption: [Shift Rows]
)
=== MixColumns
Im vierten Schritt werden die Werte mittels "Matrixmultiplikation" berechnet. Die Column für jeden Wert wirt mithilfe einer Lookup Table ermittelt (Siehe @mix-cols-lookup-table).
Möchte man den Wert in der 2. Reihe und 3. Spalte berechnen, multipliziert den ersten Wert der 3. Spalte der originalen Matrix mit dem 1. Wert der 2. Reihe der Lookup-Matrix, usw.
Die Produkte werden dann mit XOR verküpft (Siehe @mix-cols).
#figure(
image("images/mix-columns-lookup-table.png"),
caption: [MixColumns Lookup Table]
)<mix-cols-lookup-table>
#figure(
image("images/mix-columns.png"),
caption: [MixColumns]
)<mix-cols>
=== Mode of operations
- Nachrichten mit genau 128-Bits sind unwahrscheinlich
- Mode of operation = Kombination mehrerer Block-Encryption-Instanzen in zu einem nutzbaren Protokoll
- Es gibt drei mode of operations:
- Electronic Code Book (ECB)
- Cipher Block Chaining (CBC)
- Counter Mode (CTR)
=== Electronic Code Book (ECB)
- Seriell Block nach Block verschlüsseln
- Schwach für reduntante Daten: Gibt mit relativ grosser Wahrscheinlichkeit dasselbe Pattern (ECB-Pinguin, siehe @ecb-penguin)
- ECB wird nicht empfohlen
#figure(
image("images/ecb-penguin.png"),
caption: [ECB Pinguin]
)<ecb-penguin>
=== Cipher Block Chaining
- Der Output jedes Cipher-Blocks XOR dem nächsten Input
- Nicht parallelisierbar
- Besser als ECB
=== Counter Mode (CTR)
- Einen Counter (Nonce) verschlüsseln
- Kann parallelisiert werden
- Es wird nicht die Nachricht selbst verschlüsselt, sondern die Nonce und wenden XOR auf die Nachricht an
- Heutzutage Standart
== Diffie-Hellmann
- Geteiltes Geheimnis über einen unsicheren Kanal
- Jeder Kommunikationshandshake im Internet verwendet Diffie Hellmann (z.B. TLS)
- Kein direkter Schlüsselaustausch, nur Teile eines Schlüssels
=== Diskreter Logarithmus
$ a^b mod n = c \
b = log_(a, n)(c) $
Beispiel:
$3^29 mod 17 &= 12 && "einfach" \
3^x mod 17 &= 12 && "schwierig, was ist x?"$
Diskrete Logarithmen sind sehr schwierig zu berechnen.
=== Primitive Root eine Primzahl
Primzahl p, g ist primitive Root, wenn $g cancel(eq.triple) g^2 cancel(eq.triple) g^3, dots, g^(p-1) mod p$
=== Key Exchange
+ Alice und Bob eignen sich auf eine grosse Primzahl p (Normalerweise 2048 oder 4096 Bits) und eine Primzahl g, die eine Primitve Root von p ist.
+ A und B wählen zufällige Zahlen a und b als ihre private Keys (Zahlen zwischen 1 und p).
+ A und B berechnen je einen public Key:
- A: $g^a mod p$
- B: $g^b mod p$
+ Sie tauschen diese public Keys über daz Netzwerk miteinander aus
+ Sie berechnen den shared secret Key:
- A: $(g^b)^a mod p = g^(a b) mod p$
- B: $(g^a)^b mod p = g^(a b) mod p$
+ Dieser secret Key wird auch _pre-master secret_ genannt, er wird für das Erstellen des Session Keys verwendet
- Der secret Key ist oft sehr gross (2048 Bit), deshalb nicht optimal für einen Session Key.
- Master Secret wird durch _hashed-key derivation function (HKDF)_ generiert, z.B. *SHA-256*.
=== Beispiel
A und B einigen sich auf $g = 3$ und $p = 29$
- A wählt $a = 23$, $3^23 mod 29 = 8$
- B wählt $b = 12$, $3^12 mod 29 = 16$
- A berechnet $(g^b)^a mod 29 = 16^23 mod 29 = 24$
- B berechnet $(g^a)^b mod 29 = 8^12 mod 29 = 24$
Der shared secret Key ist somit 24.
Nur $g$, $p$, $g^a mod p$ und $g^b mod p$ wurden öffentlich übertragen.
Um den private Key zu knacken, müsste man folgendes lösen:
$a &= log_(g, p)(g b)\
b &= log_(g, p)(g a)$
=== Elliptic Curve Cryptography (ECC)
Elliptic Curves sind ein drop-in Replacement für die Mathematik des Diffie-Hellmann-Algorithmus.
Im Browser wird dies als ECDHE (Elliptic Curve Diffie-Hellmann Ephemeral-Verfahren) bezeichnet.
Es handelt sich um eine zweidimensionale Kurve:
$y^2 = x^3 + a x + b$
- Der private Key ist eine Zahl
- Der public Key wird durch zwei Zahlen (x, y) komposiert
- Es handelt sich wiederum um ein diskretes Logarithmus-Problem (ECDLP), es ist aber ein wenig schwieriger als das herkömmliche Verfahren.
#figure(
image("images/ecc.png"),
caption: [Elliptic Curve]
)
Für dieselbe Key-Länge sind Elliptic Curves viel stärker (Siehe @ecc-comparison).
#figure(
image("images/ecc-comparison.png"),
caption: [ECC vs. traditionelles Verfahren]
)<ecc-comparison>
=== Ephemeral Mode
- Neuer Key-Exchange für jede Session
- Perfect Forward Secrecy
- Jedes Mal ein neuer Key
- Neuer Diffie-Hellmann-Algorithmus nicht für jede Nachricht, aber sehr oft:
- Seite neu laden
- Wenn Keys gebrochen werden, hält dies nicht für lange, neue Keys werden bald wieder generiert.
- Self-Healing Property
- Kein Handshake mit denselben Keys für Monate.
#pagebreak()
= Asymmetric Cryptography
== Drei Typen der Kryptographie:
- Symmetrische Versschlüsselung
- Ein private Key für das Verschlüsseln und Entschlüsseln
- Asymmetrische Verschlüsselung
- Zwei Keys: public/private
- Ein Key verschlüsselt und der andere Key entschlüsselt
- Hash-Funktion
- Plaintext #sym.arrow Hashed Text
== RSA
RSA ist die meistverwendete Methode für public Cryptography. Es wird unter anderem verwendet für:
- Verschlüsselung mithilfe des public Keys, nur der Besitzer des privaten Schlüssels kann die Nachricht entschlüsseln
- Signaturen: Die Message wird mit dem private Key verschlüsselt, mit dem public Key entschlüsselt
- Server möchte beweisen, dass es sich um ihn handelt #sym.arrow Authentication
#sym.arrow Encryption und Authentication
Wie man in @symmetric-encryption sieht, müsste Alice bei der symmetrischen Verschlüsselung für jeden Kommunikationspartner einen neuen Key generieren. Es skaliert nicht.
Dies kann sie durch asymmetrische Verschlüsselung lösen. Sie generiert einen private Key für sich selbst und übergibt den public Key an alle Anderen. So können alle verschlüsselte Nachrichten an Alice senden und Alice kann Nachrichten mit ihrem private Key signieren.
#figure(
image("images/symmetric-encryption.png"),
caption: [Symmetrische Verschlüsselung]
)<symmetric-encryption>
=== Public Key
- $e$: sehr kleine Zahl (normalerweise 2 oder 3)
- Wird für die Encryption verwendet
- $n$: sehr grosse Semi-Prime Zahl (Multiplikation von zwei grossen Primzahlen p, q)
RSA basiert darauf, dass die Primfaktorzerlegung von $n$ sehr schwierig ist.
=== Private Key
- d
- Wird für die Decryption verwendet
=== Mathematik
- Cyphertext: $c = m^e mod n$
- Message: $m = c^d mod n$
#sym.arrow $m^(e d) mod n = m$
$d = (k dot Phi(n) + 1)/e ,k in ZZ$
=== Prozess
- Wähle $e$, generiere $n$ zufällig, berechne $d$ (Euklidischer Algorithmus)
- Eher aufwändig, sollte selten durchgeführt werden
- $e$ ist fast immer 3 oder 65537, $n$ ist 4096 bits
=== Verschlüsselung mit RSA
RSA ist sehr schwach für kurze Nachrichten:
- Padding
- Optimal Asymmetric Encryption Padding (OAEP)
- Pseudo-Random Padding, fügt einen IV (Initialization Vector) dazu und hashed
- Der Empfänger muss nach der Entschlüsselung dasselbe Padding beachten
- Verschlüsselung mit RSA ist selten
- TLS hat früher RSA verwendet, aber verwendet heutzutage DH
- Signaturen geschehen mit RSA
- RSA ist 1000x langsamer als symmetrische Kryptographie
=== Signieren mit RSA
- Verschlüsselung mit dem privaten Key
- Integritätsverifikation der Nachricht
- Nachricht wird gehashed
- Hashing für Kürzen der Nachricht
- Hash wird signiert und zusammen mit der Nachricht versendet
- Empfänger hasht die Nachricht, entschlüsselt die Signatur und checkt ob die Hashes dieselben sind
- Hashes können *nicht* entschlüsselt werden
- Wird oft als Challenge gesendet
- Der Server soll seine Idenität bestätigen
- Der Client schickt eine Nachricht, die signiert werden soll
- Server signiert diese und schickt sie zurück mit dem public Key
- Challenge-Response-Verfahren
- Wichtiger Teil von TLS
=== Digital Signature Algorithm (DSA)
- RSA benötigt immer grössere Keys #sym.arrow bald zu langsam
- DSA als Alternative
- EC DSA (oder DSS) ist viel schneller als RSA, wird bald Standart
- Elliptic Curve Digital Signature Algorithm/Digital Signature Standard
- DSA kann nur für Signaturen verwendet werden, nicht für Verschlüsselung
- Wie RSA, aber Mathematik wie DH.
- Elliptic Curves
== Hash Functions
Eine Hash-Funktion nimmt eine Nachricht irgendeiner Länge und erstellt von dieser einen pseudorandom Hash einer festen Länge. So wird eine 128-Bit-Hash-Funktion immer 128-Bits produzieren. Sie ist eine one-way Function, d.h. sie sind *irreversibel*. Dabei wird immer ein Block der Message genommen und gehashed, iterativ. Wenn die Nachricht fertig ist, ist der Hash fertig (Siehe @hash).
#figure(
image("images/hash.png"),
caption: [Hash]
)<hash>
Starke Hashing Functions:
- Generieren Output, der nicht unterscheidbar ist von random Noise
- Output soll nicht aussehen, als würde er auf dem Input basieren
- Bitänderungen müssen den gesamten Output verändern (Diffusion)
- Avalanche Effect
=== Hash-Kollision
Man versteht unter einer Hash-Kollision zwei verschiedene Inputs, die denselben Hash produzieren.
MD5 ist komplett broken und man kann beliebige Collisions erzwingen.
=== Anforderungen an eine Hash-Funktion
- Schnell (aber sicher, d.h. nicht zu schnell)
- Diffusion
- Irreversibel
- Keine Collisions
- Wichtig, da Hashes dazu verwendet werden, um zu verifizieren, dass Daten nicht verändert wurden.
- https://shattered.io
=== Übersicht
#figure(image("images/hash-functions-compared.png"))
=== SHA-X
- SHA-1 ist bereits viel besser als MD5. Nicht komplett broken aber viel schwächer mittlerweile
- SHA-2 256 bits und 512 bits sind heutezutage Standart
- SHA-2 hat dieselben Funktionalitäten wie SHA-1, aber der Output ist länger, momentan keine Probleme
- SHA-3 als Backup für SHA-2
- Komplett andere Funktion (Keccak Algorithmus)
=== Passwörter
Für Passwörter sind SHA-X-Algorithmen nicht gut, sie sind zu schnell. SHA wird für eine schnelle Zusammenfassung der Daten verwendet und sind verletzlich gegen Brute-Force-Attacken. Somit werden die Hashes mehrfach wiederholt:
- PBKDF2 (Password-Based Key Derivation Function 2) verwendet einen ähnlichen Algorithmus wie SHA-2 aber wendet diesen 5000-mal an
- Exklusiv für Logins und Passwörter
- Komplett useless für andere Hash-Zwecke
- Anzahl Iterationen kann angepasst werden
- Bcrypt ist eine Alternative zu PBKDF2
- Komplett andere Funktion, basierend auf der Cipher *blowfish*
- Nicht gut auf GPU (#sym.arrow Kann nicht so einfach Brute-Forced werden, wie andere die parallelisierbar sind)
=== Anwendungszwecke
+ Digitale Signatur
+ Integrity (Symmetric Cryptography ist verletzlich für Tampering)
- Hashes können zeigen, dass die Nachricht nicht verändert wurde
- Message Authentication Code (MAC)
=== MAC
#figure(
image("images/mac-introduction.png"),
caption: [MAC]
)
- Alice fügt dem Ciphertext den Key hinzu und hasht den Ciphertext mit dem Key (#sym.arrow h(K|C))
- Sie sendet den Ciphertext mit h(K|C) an Bob
- Bob fügt ebenfalls dem Ciphertext den Key hinzu und hasht den Ciphertext mit dem Key (#sym.arrow h(K|C))
- Wenn h(K|C) derselbe ist, wie der von Alice, wurde der Ciphertext nicht modifiziert \\
- Standart-MACs sind gelegentlich gefährdet durch SHA-1/2 Length-Extension-Attacks
- Hash-Based MAC (HMAC) ist der meistverwendete Approach, er splitted den Key in zwei und hasht zweimal
- Sicherer
- Split Key in zwei Teile und man hasht zweimal mit jedem Key
- Somit nicht gefährdet durch Length-Extension-Attacks
= Complete Cryptographic Systems
== Digitale Signaturen
- Hashes werden zusammen mit RSA/DSA verwendet, um Signaturen zu bilden
- Mit Signaturen kann der Sender seine Authenticity beweisen
#figure(
image("images/signing.png"),
caption: [Digitale Signatur]
)
== Digitale Zertifikate
Die Signatur beweist nur, dass der Server den private Key hat, aber jeder kann einen private Key erstellen. Deshalb braucht es Zertifikate, welche über eine Drittpartei (normalerweise via PKI) die Herkunft des Schlüssels beweist.
Der Server erstellt eine Certificate Signing Request (CSR) und sendet diese an eine Certification Authority (CA)#footnote[E.g. Geotrust, Globalsign, Digicert, Godaddy, letsencrypt, Google].
Die CA macht ein paar Identitätschecks und signiert das Zertifikat mit seinem private Key. Dann schickt es das signierte Zertifikat zurück an den Server.
$ "Cert"("CA", A) = {"ID"_"CA", "ID"_A, "e"_A, T, "Ext", "sig"_"CA"} $
$ "sig"_"CA" = d_"CA" [h("ID"_"CA", "ID"_A, e_A, T, "Ext")] $
- $"ID"_"CA" =$ Eindeutiger Name der CA
- $"ID"_A =$ Eindeutiger Name des Teilnehmers A (server.com)
- $e_A =$ Öffentlicher Schlüssel
- $T =$ Gültig bis $T$
- Ext = Optionale Extensions
#figure(
image("images/certificate.png"),
caption: [Digitales Zertifikat]
)
Der Server sendet dann beim TLS-Handshake die Signatur. Dazu entschlüsselt er zunächst die Signatur mithilfe des public Keys $e_A$.
= Transport Layer Security (TLS)
TLS unterstützt:
- Confidentiality (Encryption)
- Integrity (HMAC)
- Authentication (Server, optional Client, Zertifikate)
== Übersicht
#figure(
image("images/tls-overview.png"),
caption: [TLS Übersicht]
)
== Terms
- Secure Socket Layer (SSL) und TLS sind Network Security Protocols für die Authentisierung, Verschlüsselung von Daten und Datenaustausch
- SSL wurde nach SSL v3.0 zu TLS (momentan v1.3)
- TLS ist der primäre Mechanismus für die Verschlüsselung von HTTP-Kommunikation (HTTPS)
- Kann auch perfekt mit anderen Protokollen verwendet werden
- TLS kann für Applikationen transparent sein
- TLS kann embedded werden in spezifische Pakete
Urspünglich hiess TLS "Secure Socket Layer (SSL)", heisst aber seit SSL v3.0 "TLS" (aktuell v1.3).
SSL/TLS ist ein *Netzwerksicherheitsprotokoll* für das Aufsetzen von authentisierten und verschlüsselten Verbindungen und Datenaustausch.
#box(fill: rgb("#444444"), inset: 1em, text(fill: white, [TLS ist der primäre Mechanismus für die Verschlüsselung von HTTP-Kommunikation (HTTPS)]))
- TLS kann auch für andere Protokolle verwendet werden
- Kann für Applikationen tranparent sein
- Kann embedded werden in spezifische Pakete
== TLS-Architektur
=== TLS Connection
- Transport, welcher einen passenden Type of Service anbietet
- Peer-to-Peer
- Connections sind flüchtig (transient)
- Jede Verbindung ist mit einer eigenen Session verknüpft
=== TLS Session
- Eine Verbindung (association) zwischen Cleint und Server über ein Handshake Protokoll
- Definiert ein Set von kryptographischen Sicherheitsparametern, welche an mehrere Verbindungen geteilt werden können
- Es müssen nicht für jede Verbindungen neue (teure) Sicherheitsparameter verhandelt werden
== Geschichte
#figure(image("images/tls-history.png"), caption: [TLS Geschichte], placement: none)
=== TLS 1.3 (RFC 8446, August 2018) -- Verbesserungen
- Clean up: Unsichere oder nicht verwendete Funktionen entfernt
- Legacy & Broken Crypto: (3)DES, RC4, MD5, SHA1, Kerberos, RSA PKCS\#1v1.5. Key Transport
- Cipher Suites von > 100 auf 5 reduziert
- Broken Features: Compression und Renegotiation
- Statischer RSA/DH entfernt
- Performance: 1-RTT und 0-RTT Handshakes
- Sicherheit verbessert
- Privacy: Fast alle Handshake-Messages werden verschlüsselt
- Continuity: Backwards Compatibility
== TLS-Record-Structure
#figure(
image("images/tls-frame-structure.png"),
caption: [TLS Frame Structure],
placement: none
)
#figure(
image("images/tls-frame-structure-wireshark.png"),
caption: [TLS Framestruktur (Wireshark)],
placement: none
)
HTTPS-Content-Types:
- Handshake Protocol (22): ClientHello, ServerHello, Certificate, ServerHelloDone
- Change CipherSpec Protocol (20): Wechsel der Cipher Suite
- Alert Protocol (21): Warning, Fatal (Session wird auf der Stelle beendet)
- Application Protocol (23): Verschlüsselter Payload wird versendet (Transmission)
#figure(image("images/tls-records.png"), caption: [TLS Records], placement: none)
== TLS-Handshake
- Bevor Applikationsdaten übermittelt werden
- Server und Client:
- Authentisieren sich gegenseitig
- Verhandeln Verschlüsselungs- und MAC-Algorithmen
- Verhandeln Schlüssel
- Vier Phasen:
+ Sicherheitsfähigkeiten aushandeln (TLS Version, etc.)
+ Server kann Zertifikat schicken, Schlüsselaustausch und Anforderung eines Zertifikats
+ Client sendet Client-Zertifikat, wenn angefordert. Client sendet Schlüsselaustausch.
+ Änderung der Cipher Suite (ChangeCipherSpec) und Abschluss des Handshake Protokolls
#figure(image("images/tls-handshake.png"), caption: [TLS Handshake])
== RSA Public Key Encryption ohne Perfect Forward Secrecy (Legacy, v1.2)
- Problematisch, da Pakete jetzt mitgehört werden können und später entschlüsselt werden können (Quantencomputing)
- RSA Keyaustausch
== Ephemeral Diffie-Hellmann (DHE) Key Exchange (Perfect Forward Secrecy, v1.3)
- Diffie-Hellmann Key Exchange
= Public Key Infrastructure (PKI)
Alles basiert auf _Trust_ im digitalen Zeitalter. Momentane Probleme in der digitalen Ökonomie sind:
- Fragmentation
- Lack of interoperability
- Steigerung der Cyberkriminalität
- eID und Trust Services haben ein gemeinsames Sicherheitsfundament
Wenn eine HTTPS-Verbindung auf ost.ch stattfindet, wird Public Key Cryptography für die Authentication, Verschlüsselung und digitale Signaturen verwendet. Wichtige Fragen sind:
- Ist dies tatsächlich der Schlüssel für www.ost.ch?
- Ist der Key verwendet worden, um zu signieren?
Public Key als String von Bits:
- Wem gehört dieser Bit-String?
- Für welche Zwecke kann er verwendet werden?
- Ist er noch immer valid?
PKI soll eine Antwort auf all diese Fragen liefern.
- PKI wird verwendet, um einen Public Key zu einer Identität zu binden
- Die Bindings passieren über:
- Einen Registrierungsprozess einer Registration Authority (RA) und
- Eine Issuance eines Zertifikats durch eine Certificate Authority (CA)
- Die CA kann durch eine unabhängige Validation Authority (VA) validiert werden
- Das Artifact einer Bindung nennt sich das Zertifikat
#figure(
image("images/pki-overview.png"),
caption: [Public Key Infrastructure (PKI)]
)
== Geschichte
- X.500 ist die Menge der Netzwerkstandarts, die elektronische Directory-Services abdeckt (1988)
- X.509 ist der Standart für das Format von Public Key Zertifikaten (1988)
- X.509v3 Profiles sind die meistverwendeten.
== Public Key Certificate
- Ein elektronisches Dokument, welcher die Ownership eines Public Keys beweist
- Enthält Informationen über den Schlüssel
- Enthält Informationen über den Besitzer des Schlüssels (Subjekt)
- Enthält Informationen über die CA, die das Zertifikat signiert hat (Issuer)
== Felder eines Zertifikats
- Version
- Serial Number: Eindeutige Nummer des Zertifikats
- Signature Algorithm: Algorithmus, der für die Signatur von der CA verwendet wurde
- Issuer Distinguished Name (DN): Name der CA
- Gültig von/bis
- Public Key
- Key Usage: Für welche Zwecke der Schlüssel verwendet werden kann
- Extended Key Usage (EKU): serverAuth, clientAuth, codeSigning, emailProtection, timeStamping, OCSPSigning
== Vier Kategorien
Abhängig vom Typ der Checks, die durchgeführt werden:
- Domain Validated (DV): Issued nachdem der Domain-Besitz bestätigt wurde
- Organisation Validated (OV): Issued nachdem die Organisation bestätigt wurde (Company name, domain name, etc. durch öffentliche Datenbanken)
- Extended Validation (EV): Issued nachdem die Entität eine strikte Authentisierungsprüfung durchlaufen hat
- Qualified Website Authentication Certificate (QWAC): Ein qualifiziertes Zertifikat (eIDAS, PSD2 Regulation)
== Validitätsinformatinonen erhalten:
- Certificate Revocation List (CRL): Liste von Zertifikaten, die nicht mehr gültig sind
- CRL DIstribution Point im Zertifikat
- Wird von den meisten Browsern geprüft
- Online Certificate Status Protocol (OCSP):
- Authority Information Access (AIA)-Feld im Zertifikat zeigt, wie Informationen über die CA erhalten werden können
Desweiteren
- Certificate Policies:
- Link zu den Regeln der CA
- Jedes CA hat eigene Policies
- Authority Key Identifier (AKI):
- Key-Identifier des CA-Zertifikats, welches das TLS-Zertifikat signiert hat
- Subject Alternative Name (SAN): Weitere Informationen über den Besitzer des Zertifikats
- Subject Key Identifier (SKI): Hash-Wert des Zertifikats, wird verwendet, um die Identität des Zertifikats zu überprüfen
== Trust Service Provider (TSP)
Erstellt Trust zwischen Kommunikationspartnern:
- Trusted Identity Information
- Secure Authentication
- Integrity Protected Communication
- Encrypted Communication
== Certificate Issuance
- Der Subscriber (Die Entität, die das Key-Pair besitzt, wessen public Key ein Zertifikat erhalten soll) sendet eine Certificate Signing Request (CSR) an die CA
- CSR enthält Informationen über das Onjekt des Subscribers, den public Key (welcher signiert werden soll) und Informationen über Key-Type und Länge
- CSR wird im Base64-Format an die CA gesendet
- CA registriert den Request, prüft die Daten und signiert den CSR (#sym.arrow X.509-Zertifikat)
== CA Hierarchy
- Root CA: Trust-Anchor der PKI.
- Issuing CA: CA, die Zertifikate für End-Entities signiert (Auch Intermediate CA, Subordinate CA)
#figure(
image("images/ca-hierarchy.png"),
caption: [CA Hierarchy]
)
== Trust mit Zertifikaten
- PKI ist vertrauenswürdig mit allem im Trust Store
- Es können hunderte von Root-Zertifikaten auf der Client-Maschine sein
- Certificate Pinning: Client speichert den public Key des Servers und vertraut nur diesem Key
- Operatoren pinnen die CA issuers, public Keys oder End-Entity-Zertifikate. Clients vertrauen nur diesen Zertifikaten.
== Certificate Pinning
- 2011 Google Chrome
- HTTP Public Key Pinning (HPKP)
- Risiken:
- Key Compromise nicht entdeckt
- Hackers können eigene HPKP auf komprimierten Servern setzen
= Ethical Hacking und Penetration Testing
== Attackkonzepte
- Hacking
- Vulnerabilities ausnützen
- Security control compromise
- Verhalten von Systemen ändern
- Ethical Hacking
- Hacking, aber legal
- Tools und Techniken verwenden, um Schwachstellen zu finden, validieren, doumentieren und melden
- Vulnerability existence reporting
== Hacker-Typen
- Black Hat
- Böse Hacker, malicious, bleibt normalerweise anonym
- Grey Hat
- Hacker mit Black Hat Skills, die ihre Fähigkeiten offensiv und defensiv einsetzen
- White Hat
- Hacker mit Black Hat Skills, die ihre Fähigkeiten nur defensiv einsetzen
- Script Kiddie
- Verwendet Tools, ohne zu verstehen, was sie tun
- Cyber Terrorist
- Skilled Attacker, der mit Hacking einer Ideologie vorantreibt
- State Sponsored
- Vom Staat angestellt für offensive und defensive Aktivitäten
- Hacktivist
- Ein Hacker für soziale oder politische Zwecke
==
== Hacktivism
= Authentication Schemes
== Basic Authentication
Übertragung der Credentials via Plaintext: Man in the Middle Attacks
== One Time Passwords
Passwörter, die generiert werden und nur einmal verwendet werden können. MITM möglich, jedoch nur kurzfristig, z.B. Session-Hijacking. Dasselbe Passwort kann aber nicht wiederverwendet werden.
== Challenge-Response-Verfahren
Der User kennt bereits seine $"ID"_U$ und generiert einen Random-Wert $R_U$.
Der Server sendet einen Random-Wert $R_S$ an den User. Dieser generiert dann aus $R_S$, $R_U$, $"ID"_U$ und einer vordefinierten *Keyed Hash Function* und einem Key eine MAC. Er sendet diese MAC dann zurück an den Server. Der Server macht denselben Durchlauf und überprüft, ob die beiden MACs dieselben sind (siehe @challenge-response).
#figure(image("./images/challenge-response.png"), caption: [Challenge-Response-Verfahren])<challenge-response>
=== Challenge-Response based on Digital Signatures
Derselbe Prozess wie beim herkömmlichen Challenge-Response-Verfahren, nur wird hier der Hash vor der Übertragung verschlüsselt (Siehe @challenge-response-signed).
#figure(image("./images/challenge-response-signature.png"), caption: [Challenge-Response-Verfahren mit Digitaler Signatur])<challenge-response-signed>
== Kerberos
=== Ablauf (Simplifiziert)
Siehe @kerberos.
+ Alice hashed ihr Passwort: $"MKey"_A$
+ A. verschlüsselt mit diesem Hash die aktuelle Uhrzeit: $E("time", "MKey"_A)$
+ A. sendet diesen Wert an den Key an das Key Distribution Center (KDC)
+ KDC entschlüsselt den Wert mit dem Hash von Alice: $D(E("time", "MKey"_A), "MKey"_A)$ und prüft, ob die Zeit gültig ist
+ KDC generiert einen Session Key $S_"AB"$ und verschlüsselt diesen mit dem Hash von A.: $E(S_"AB", "MKey"_A)$
+ KDC gen. Ticket: $E({ "Alice", S_"AB"}, "MKey"_B)$
+ KDC sendet verschlüsselten Session Key und Ticket an A.
+ A. entschlüsselt den Session Key
+ A. verschlüsselt die aktuelle Zeit mit dem Session Key und sendet dies zusammen mit dem Ticken an B.
#figure(image("./images/kerberos.png"), caption: [Kerberos])<kerberos>
== Anonymous Key Exchange
Generieren eines Keys mithilfe von Diffie-Hellman.
== Certificate-Based Server Authentication
Der Server sendet sein Zertifikat an den Client. Der Client überprüft die Idenität des Servers und sendet dann das Passwort verschlüsselt an den Server, wenn der Server authentifiziert ist.
== Mutual Public Key Authentication
Der Client authentifiziert sich mit seinem Client-Zertifikat und macht eine Signatur mit seinem private Key. Der Server überprüft die Signatur des Clients. Gleichzeitig sendet der Server sein Zertifikat an den Client, welcher die Signatur des Servers überprüft.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/set-05.typ | typst | Other | // Test conditional set.
#show ref: it => {
set text(red) if it.target == <unknown>
"@" + str(it.target)
}
@hello from the @unknown
|
https://github.com/piepert/logik-tutorium-wise2024-2025 | https://raw.githubusercontent.com/piepert/logik-tutorium-wise2024-2025/main/src/exercise-sheets/exercise01.typ | typst | Creative Commons Zero v1.0 Universal | #import "/src/templates/exercise.typ": project, task
#import "/src/packages/inference.typ": *
#show: project.with(no: 1, show-solutions: true, show-hints: true)
#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.
][][
#lorem(100)
][
#lorem(100)
] |
https://github.com/r4ai/typst-code-info | https://raw.githubusercontent.com/r4ai/typst-code-info/main/.github/fixtures/diff.typ | typst | MIT License | #import "../../plugin.typ": init-code-info, code-info, parse-diff-code
#show: init-code-info.with()
#code-info(
diff: true,
show-line-numbers: true,
always-show-lines: (1,),
)
```rust
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn sub(a: i32, b: i32) -> i32 {
a - b
}
pub fn mul(a: i32, b: i32) -> i32 {
a * b
}
pub fn div(a: i32, b: i32) -> i32 {
a / b
}
```
```rust
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn sub(a: i32, b: i32) -> i32 {
let c = a - b;
c
}
pub fn mul(a: i32, b: i32) -> i32 {
a * b
}
pub fn div(a: i32, b: i32) -> i32 {
a / b
}
```
|
https://github.com/dangh3014/postercise | https://raw.githubusercontent.com/dangh3014/postercise/main/examples/better-example.typ | typst | MIT License | // Import a theme
#import "../postercise.typ": *
#import themes.better: *
// Set up paper dimensions and text
#set page(width: 24in, height: 18in)
#set text(font: "Calibri", size: 24pt)
// Set up colors
#show: theme.with()
// Add content
#poster-content[
// Add title, subtitle, author, affiliation, logos
#poster-header(
title: [Title of Research Project:],
subtitle: [Subtitle],
authors: [List of Authors],
logo-1: image("placeholder.png")
)
// Include content in the footer
#poster-footer[
_Additional information_
= Acknowledgements
The authors wish to thank those providing guidance, support, and funding.
= References
#set text(size: 0.8em)
+ #lorem(8)
+ #lorem(12)
#figure(image("emu-logo.png", width: 60%))
]
= Research Question
#lorem(10)
= Methods
#lorem(10)
- #lorem(4)
- #lorem(6)
// A normal box can be used to highlight
#normal-box()[
= Results
#lorem(10)
#figure(image("placeholder.png", width: 50%),
caption: [_Fig. 1: Sample Results_])
]
// Focus-box is used for the main findings
#focus-box()[
= Key Findings
#lorem(20)
]
= Discussion
#lorem(20)
]
|
https://github.com/AliothCancer/AppuntiUniversity | https://raw.githubusercontent.com/AliothCancer/AppuntiUniversity/main/capitoli_applicazioni/emodialisi.typ | typst | = Emodialisi
== Concentrazione soluto
$
C = dot(m) / Q
$
== Cleareance
$
Q_"cleareance" = Q_"plasma" (1 - C_"finale"/C_"iniziale")
$
== Elementi del circuito di emodialisi
=== Mini Glossario
*Volume di priming*: Volume che riempie tutto il circuito della linea del sangue. È importante perchè influisce sulla volemia del paziente.
=== Linea del sangue
1. *Accesso vascolare*
2. *Pompa di infusione di eparina*
- Problema risolto: coaguli
3. *Pompa del sangue (a monte del filtro)*
- Problema risolto: Controllo della portata ematica al filtro
4. *Filtro di emodialisi*
5. *Indicatore di pressione positiva:*
- Se la pressione è positiva il flusso scorre nel verso corretto, non c'è reflusso.
- Problema risolto: Indicazione di eventuali reflussi
6. *Rilevatore di bolle d'aria*
- Problema risolto: Indicatore di eventuali bolle che ostruiscono il passaggio del sangue con potenziale pericolo di embolia per il paziente(visto che va nel paziente).
7. *Ritorno al paziente*
=== Linea del dialisato
1. *Accesso all'acqua filtrata*
- Filtro ad osmosi inversa per il controllo dei soluti, carboni attivi per agenti patogeni e sostanze nocive.
- Problema risolto: Controllo dei soluti del dialisato per il controllo delle sostanze filtrate e pericolo infezioni batteriche.
2. *Scambiatore di calore*
- Problema risolto: ipotermia del paziente, visto che un trattamento di dialisi dura diverse ore.
3. *Sensore di temperatura con feedback per lo Scambiatore*
- Problema risolto: feedback per il controllo della temperatura
4. *Iniettore del concentrato*
- Problema risolto: insieme all'acqua filtrata esegue il controllo dei soluti del dialisato.
5. *Sensore di temperatura a valle*
6. *Sensore di conduttività*
7. *Valvola di bypass*
- Per evitare il passaggio del dialisato nel filtro
8. *Indicatore di pressione negativa*
- Perchè in questa linea l'indicatore è posto a monte della pompa, quindi la pressione corretta deve essere negativa.
- Problema risolto: reflusso del dialisato
9. *Filtro di dialisi*
10. *Rilevatore di sangue*
- Nel dialisato non devono esserci tracce di sangue, altrimenti qualcosa va storto.
11. *Pompa del dialisato*
- Problema risolto: è necessaria per muovere il fluido e controllare la portata del dialisato, che influisce direttamente sui parametri del trattamento.
12. *Scarico del dialisato*
- Viene buttato oppure riciclato
|
|
https://github.com/tingerrr/hydra | https://raw.githubusercontent.com/tingerrr/hydra/main/src/core.typ | typst | MIT License | #import "/src/util.typ"
/// Returns the current text direction.
///
/// This function is contextual.
///
/// -> direction
#let get-text-dir() = util.auto-or(text.dir, () => util.text-direction(text.lang))
/// Returns the current page binding.
///
/// This function is contextual.
///
/// -> alignment
#let get-page-binding() = util.auto-or(page.binding, () => util.page-binding(get-text-dir()))
/// Returns the current top margin.
///
/// This function is contextual.
///
/// -> length
#let get-top-margin() = {
let margin = page.margin
if type(margin) == dictionary {
margin = if "top" in margin {
margin.top
} else if "y" in margin {
margin.y
} else {
panic(util.fmt("Margin did not contain `top` or `y` key: `{}`", margin))
}
}
let inf = float("inf") * 1mm
let width = util.auto-or(page.width, () => inf)
let height = util.auto-or(page.height, () => inf)
let min = calc.min(width, height)
// if both were auto, we fallback to a4 margins
if min == inf {
min = 210.0mm
}
// `+ 0%` forces this to be a relative length
margin = util.auto-or(margin, () => (2.5 / 21) * min) + 0%
margin.length.to-absolute() + (min * margin.ratio)
}
/// Get the last anchor location. Panics if the last anchor was not on the page of this context.
///
/// This function is contextual.
///
/// - ctx (context): The context from which to start.
/// -> location
#let locate-last-anchor(ctx) = {
let starting-locs = query(selector(ctx.anchor).before(here()))
assert.ne(starting-locs.len(), 0,
message: "No `anchor()` found while searching from outside the page header",
)
let anchor = starting-locs.last().location()
// NOTE: this check ensures that get rules are done within the same page as the queries
// ideally those would be done within the context of the anchor, such that a change in text
// direction between anchor and query does not cause any issues
assert.eq(anchor.page(), here().page(),
message: "`anchor()` must be on every page before the first use of `hydra`"
)
anchor
}
/// Get the element candidates for the given context.
///
/// This function is contextual.
///
/// - ctx (context): The context for which to get the candidates.
/// - scope-prev (bool): Whether the search should be scoped by the first ancestor element in this
/// direction.
/// - scope-next (bool): Whether the search should be scoped by the first ancestor element in this
/// direction.
/// -> candidates
#let get-candidates(ctx, scope-prev: true, scope-next: true) = {
let look-prev = selector(ctx.primary.target).before(ctx.anchor-loc)
let look-next = selector(ctx.primary.target).after(ctx.anchor-loc)
let look-last = look-next
let prev-ancestor = none
let next-ancestor = none
if ctx.ancestors != none {
let prev-ancestors = query(selector(ctx.ancestors.target).before(ctx.anchor-loc))
let next-ancestors = query(selector(ctx.ancestors.target).after(ctx.anchor-loc))
if ctx.ancestors.filter != none {
prev-ancestors = prev-ancestors.filter(x => (ctx.ancestors.filter)(ctx, x))
next-ancestors = next-ancestors.filter(x => (ctx.ancestors.filter)(ctx, x))
}
if scope-prev and prev-ancestors != () {
prev-ancestor = prev-ancestors.last()
look-prev = look-prev.after(prev-ancestor.location())
}
if scope-next and next-ancestors != () {
next-ancestor = next-ancestors.first()
look-next = look-next.before(next-ancestor.location())
}
}
let prev-targets = query(look-prev)
let next-targets = query(look-next)
let last-targets = query(look-last)
if ctx.primary.filter != none {
prev-targets = prev-targets.filter(x => (ctx.primary.filter)(ctx, x))
next-targets = next-targets.filter(x => (ctx.primary.filter)(ctx, x))
last-targets = last-targets.filter(x => (ctx.primary.filter)(ctx, x))
}
next-targets = next-targets.filter(x => x.location().page() == ctx.anchor-loc.page())
last-targets = last-targets.filter(x => x.location().page() == ctx.anchor-loc.page())
let prev = if prev-targets != () { prev-targets.last() }
let next = if next-targets != () { next-targets.first() }
let last = if last-targets != () { last-targets.last() }
(
primary: (prev: prev, next: next, last: last),
ancestor: (prev: prev-ancestor, next: next-ancestor),
)
}
/// Checks if the current context is on a starting page, i.e. if the next candidates are on top of
/// this context's page.
///
/// This function is contextual.
///
/// - ctx (context): The context in which the visibility of the next candidates should be checked.
/// - candidates (candidates): The candidates for this context.
/// -> bool
#let is-on-starting-page(ctx, candidates) = {
let next = if candidates.primary.next != none { candidates.primary.next.location() }
let next-ancestor = if candidates.ancestor.next != none { candidates.ancestor.next.location() }
let next-starting = if next != none {
next.page() == here().page() and next.position().y <= get-top-margin()
} else {
false
}
let next-ancestor-starting = if next-ancestor != none {
next-ancestor.page() == here().page() and next-ancestor.position().y <= get-top-margin()
} else {
false
}
next-starting or next-ancestor-starting
}
/// Checks if the previous primary candidate is still visible.
///
/// This function is contextual.
///
/// - ctx (context): The context in which the visibility of the previous primary candidate should be
/// checked.
/// - candidates (candidates): The candidates for this context.
/// -> bool
#let is-active-visible(ctx, candidates) = {
// depending on the reading direction and binding combination the leading page is either on an odd
// or even number, if it is leading it means the previous page is visible
let cases = (
left: (
ltr: calc.odd,
rtl: calc.even,
),
right: (
ltr: calc.even,
rtl: calc.odd,
),
)
let is-leading-page = (cases.at(repr(ctx.binding)).at(repr(ctx.dir)))(here().page())
let active-on-prev-page = candidates.primary.prev.location().page() == here().page() - 1
is-leading-page and active-on-prev-page
}
/// Check if showing the active element would be redudnant in the current context.
///
/// This function is contextual.
///
/// - ctx (context): The context in which the redundancy of the previous primary candidate should be
/// checked.
/// - candidates (candidates): The candidates for this context.
/// -> bool
#let is-active-redundant(ctx, candidates) = {
let active-visible = (
ctx.book and candidates.primary.prev != none and is-active-visible(ctx, candidates)
)
let starting-page = is-on-starting-page(ctx, candidates)
active-visible or starting-page
}
/// Display a heading's numbering and body.
///
/// - ctx (context): The context in which the element was found.
/// - candidate (content): The heading to display, panics if this is not a heading.
/// -> content
#let display(ctx, candidate) = {
util.assert.element("candidate", candidate, heading,
message: "Use a custom `display` function for elements other than headings",
)
if candidate.has("numbering") and candidate.numbering != none {
numbering(candidate.numbering, ..counter(heading).at(candidate.location()))
[ ]
}
candidate.body
}
/// Execute the core logic to find and display elements for the current context.
///
/// This function is contextual.
///
/// - ctx (context): The context for which to find and display the element.
/// -> content
#let execute(ctx) = {
ctx.anchor-loc = if ctx.anchor != none and here().position().y > get-top-margin() {
locate-last-anchor(ctx)
} else {
here()
}
let candidates = get-candidates(ctx)
let prev-eligible = candidates.primary.prev != none and (ctx.prev-filter)(ctx, candidates)
let next-eligible = candidates.primary.next != none and (ctx.next-filter)(ctx, candidates)
let last-eligible = candidates.primary.last != none and (ctx.next-filter)(ctx, candidates)
let active-redundant = is-active-redundant(ctx, candidates)
if active-redundant and ctx.skip-starting {
return
}
if ctx.use-last and last-eligible {
(ctx.display)(ctx, candidates.primary.last)
} else if prev-eligible and not active-redundant {
(ctx.display)(ctx, candidates.primary.prev)
} else if next-eligible {
(ctx.display)(ctx, candidates.primary.next)
}
}
|
https://github.com/mitex-rs/mitex | https://raw.githubusercontent.com/mitex-rs/mitex/main/packages/mitex/mitex.typ | typst | Apache License 2.0 | #import "specs/mod.typ": mitex-scope
#import "@preview/xarrow:0.2.0": xarrow
#let mitex-wasm = plugin("./mitex.wasm")
#let get-elem-text(it) = {
{
if type(it) == str {
it
} else if type(it) == content and it.has("text") {
it.text
} else {
panic("Unsupported type: " + str(type(it)))
}
}
}
#let mitex-convert(it, mode: "math", spec: bytes(())) = {
if mode == "math" {
str(mitex-wasm.convert_math(bytes(get-elem-text(it)), spec))
} else {
str(mitex-wasm.convert_text(bytes(get-elem-text(it)), spec))
}
}
// Math Mode
#let mimath(it, block: true, ..args) = {
let res = mitex-convert(mode: "math", it)
let eval-res = eval("$" + res + "$", scope: mitex-scope)
math.equation(block: block, eval-res, ..args)
}
// Text Mode
#let mitext(it) = {
let res = mitex-convert(mode: "text", it)
eval(res, mode: "markup", scope: mitex-scope)
}
#let mitex(it, mode: "math", ..args) = {
if mode == "math" {
mimath(it, ..args)
} else {
mitext(it, ..args)
}
}
#let mi = mimath.with(block: false)
|
https://github.com/ZaninAndrea/physics-rl | https://raw.githubusercontent.com/ZaninAndrea/physics-rl/main/report/toc.typ | typst | #let tocLine(header, inset: 0pt) = {
let title = header.body.text
let page = header.location().page() - 1
let rawCounter = counter(heading).at(header.location())
let headerCounter = h(14pt)
if header.numbering != none{
headerCounter = numbering(header.numbering, ..rawCounter)
}
let dots = box(width: 1fr, repeat[. #h(2pt)])
[#h(inset) #headerCounter #title #dots #page #linebreak()]
}
#let toc = {
// let tocHeading = heading("Table of Contents", numbering: none)
// tocHeading
set par(first-line-indent: 0pt)
locate(loc => {
// Find all top level headings
let elems = query(
selector(heading.where(level:1).after(loc)),
loc
)
for (i, el) in elems.enumerate(){
// if el == tocHeading{
// continue
// }
tocLine(el, inset: 0pt)
// Find all sub-headings of this heading
let children = selector(heading.where(level:2)).after(el.location())
if i < elems.len() - 1 {
children = children.before(elems.at(i+1).location())
}
let childElements = query(
children,
loc
)
// Display all children
for child in childElements{
tocLine(child, inset: 20pt)
}
}
})
} |
|
https://github.com/juanppalacios/GVSU_MSE_Project | https://raw.githubusercontent.com/juanppalacios/GVSU_MSE_Project/main/report/research.typ | typst | Other | = Research
== Documentation/Guides
== Papers
All .pdf's in the sources directory obtained via Google Scholar.
Access to IEEE Xplore sources provided by Grand Valley State University.
// == Computer Vision
// == Image Processing
// === Signal Processing
// == Artificial Intelligence
// === Machine Learning
// ==== Object Detection
*A machine learning based intelligent vision system for autonomous object detection and recognition*
Abstract Summary:
This source presents a "novel fast" algorithm for visually salient object detection.
It takes into account real-world illumination conditions.
The algorithm performance is benchmarked on MSRA Salient Object Database and implemented on a humanoid robot.
fully autonomous robots rely on perception for spacial awareness and object recognition.
Overview of their system is as follows: some unknown object is learned by extracting its features.
Then, any future objects will be recognized.
Overall, this system is explained in two parts: image capture and segment image units.
The first construct a saliency map where regions of the images are highlighted as important.
As more and more images are captures and processed, a kind of "visual memory" is kept on-line the system for future referencing @ramik2014machine.
@bai2020object
*A General Framework for Object Detection*
Abstract summary:
The purpose of this paper is to showcase a general trainable framework for object detection in static images.
These images contain many different classes of objects.
The algorithm uses statistical analysis based on the wavelet representation of an object class (?).
The model learns object classes as subsets.
A face detection dataset is used to benchmark this approach as well as providing a motion-based solution for video purposes.
@papageorgiou1998general
@papageorgiou2000trainable
@singh2019practical
@kumeda2019classification
@ma2019performance
@wang2019lutnet
@abdelouahab2018accelerating
@8330049
@finn
@blott2018finn
@sen2009pedestrian
===== Emergency Vehicle Detection
*Real Time Machine Learning Based Car Detection in Images with Fast Training*
abstract summary:
The purpose of this paper is to demonstrate reliable object recognizers from small data sets.
Their learning algorithm (AdaBoost novel variant) builds a strong classifier by incrementally training weak classifiers once with no changes to their weights.
Their experiments show a very accurate model that can recognize cars accurately in real time with fast training.
@stojmenovic2006real
@9225331
@8679295
@roy2019emergency
#pagebreak()
#bibliography("./references.bib") |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/game-theoryst/0.1.0/doc/gallery/simple-example.typ | typst | Apache License 2.0 | #import "../../src/lib.typ": *
#set page(
width: auto,
height: auto,
margin: 0.25em
)
#nfg(
players: ("Jack", "Diane"),
s1: ($C$, $D$),
s2: ($C$, $D$),
[$10, 10$], [$2, 20$],
[$20, 2$], [$5, 5$],
) |
https://github.com/rabotaem-incorporated/calculus-notes-2course | https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/06-fourier-series/02-hilbert-spaces.typ | typst | #import "../../utils/core.typ": *
== Гильбертовы пространства
#ticket[Гильбертовы пространства. Сходимость ортогональных рядов.]
#remind(name: "Скалярное произведение")[
Если $X$ --- векторное пространство, то $dotp(dot, dot): X times X --> CC$ --- скалярное произведение, если
1. $dotp(x, x) >= 0$, $dotp(x, x) = 0 <==> x = arrow(0)$
2. $dotp(x, y) = cj(dotp(y, x))$
3. $dotp(x + y, z) = dotp(x, z) + dotp(y, z)$
4. $dotp(alpha x, y) = alpha dotp(x, y)$
Следовательно,
- $dotp(x, y + z) = dotp(x, y) + dotp(x, z)$.
- $dotp(x, alpha y) = cj(alpha) dotp(x, y)$
]
#def[
$H$ называется _Гильбертовым пространством_, если в $H$ есть скалярное произведение, и $H$ --- полное (то есть сходимость в нем равносильна фундаментальности).
]
#examples[
+ $RR^d$, $dotp(x, y) = sum_(k=1)^d x_k cj(y_k)$,
+ $CC^d$, $dotp(x, y) = sum_(k=1)^d x_k cj(y_k)$,
+ $l^2$: $dotp(x, y) = sum_(k=1)^oo x_k cj(y_k)$,
+ $L^2 (E mu)$: $dotp(x, y) = integral_E f cj(g) dif mu$.
]
#lemma[
Если ряд $sum_(n=1)^oo x_n$ сходится, то
$
dotp(sum_(n=1)^oo x_n, y) = sum_(n=1)^oo dotp(x_n, y).
$
]
#proof[
Рассмотрим $S_n := sum_(k=1)^n x_k --> S := sum_(k=1)^oo x_k$. Тогда
$
dotp(S, y) <-- dotp(S_n, y) = dotp(sum_(k=1)^n x_k, y) = sum_(k=1)^n dotp(x_k, y) --> sum_(k=1)^oo dotp(x_k, y)
$
]
#def[
Векторы $x$ и $y$ _ортогональны_, если их скалярное произведение $0$. Обозначается $x perp y$.
Ряд $sum_(n=1)^oo x_n$ назовем _ортогональным_, если $dotp(x_k, x_n) = 0$ для всех $n != k$.
]
#th[
Пусть $H$ --- гильбертово пространсво, $sum_(n=1)^oo x_n$ --- ортогональный ряд в $H$. Тогда этот ряд сходится тогда и только тогда, когда числовой ряд $sum_(n=1)^oo norm(x_n)^2$ сходится. В этом случае, $norm(sum_(n=1)^oo x_n)^2 = sum_(n=1)^oo norm(x_n)^2$.
]
#proof[
Пусть $S_n := sum_(k=1)^n x_k$, $C_n := sum_(k=1)^n norm(x_k)^2$.
$
sum_(n=1)^oo x_n "сходится" <==> S_n "сходится" <==> S_n "фундаментальна" newline(<==>)
forall eps > 0 space exists N space forall n, m >= N space norm(S_n - S_m) < eps.
$
Оценим квадрат нормы разности:
$
norm(S_n - S_m)^2 = norm(sum_(k = m+1)^n x_k)^2 = dotp(sum_(k=m+1)^n x_k, sum_(j=m+1)^n x_j) newline(=) sum_(j,k=m+1)^n underbrace(dotp(x_k, x_j), 0 "если" k != k) = sum_(k = m+1)^n norm(x_k)^2 = C_n - C_m.
$
Получается, $S_n$ фундаментальна тогда и только тогда, когда $C_n$ фундаментальна. Это как раз равносильно тому, что $S_n$ сходится тогда и только тогда, когда $C_n$ сходится. Более того,
$
norm(sum_(n=1)^oo x_n)^2 = dotp(sum_(n=1)^oo x_n, sum_(k=1)^oo x_k) = sum_(n=1)^oo sum_(k=1)^oo underbrace(dotp(x_n, x_k), 0 "если" n != k) = sum_(n=1)^oo norm(x_n)^2.
$
]
#follow[
Если ортогональный $sum_(n=1)^oo x_n$ сходится, $phi: NN --> NN$ --- перестановка, то $sum_(n=1)^oo x_(phi(n))$ --- сходится к той же сумме.
]
#proof[
Сходимость понятна:
$
sum_(n=1)^oo x_n "сходится" <==> sum_(n=1)^oo norm(x_n)^2 "сходится" <==> sum_(n=1)^oo norm(x_(phi(n)))^2 "сходится" <==> sum_(n=1)^oo x_(phi(n)) "сходится".
$
Найдем предел:
$
text(size: #0.85em,
norm(sum_(n=1)^oo x_n - sum_(n=1)^oo x_(phi(n)))^2 =
norm(sum_(n=1)^oo (x_n - x_(phi(n))))^2 =
dotp(sum_(n=1)^oo (x_n - x_(phi(n))), sum_(k=1)^oo (x_k - x_(phi(k)))) newline(=)
sum_(n=1)^oo sum_(k=1)^oo dotp(x_n - x_(phi(n)), x_k - x_(phi(k))) =
sum_(k,n=1)^oo underbrace(dotp(x_n, x_k), 0 "если" k != n) -
sum_(k,n=1)^oo underbrace(dotp(x_(phi(n)), x_k), 0 "если" k != phi(n)) -
sum_(k,n=1)^oo underbrace(dotp(x_n, x_(phi(k))), 0 "если" n != phi(k)) +
sum_(k,n=1)^oo underbrace(dotp(x_phi(n), x_(phi(k))), 0 "если" n != k)
newline(=)
sum_(n=1)^oo norm(x_n)^2
- cancel(sum_(n=1)^oo norm(x_(phi(n)))^2)
- sum_(k=1)^oo norm(x_(phi(k)))^2
+ cancel(sum_(n=1)^oo norm(x_(phi(n)))^2)
= 0.
)
$
]
#ticket[Ортогональные и ортонормированные системы. Примеры. Коэффициенты Фурье.]
#def[
$x_1$, $x_2$, $x_3$, ... --- _ортогональная система_, если $norm(x_k) != 0$ и $dotp(x_k, x_n) = 0$ для всех $k != n$.
]
#def[
$x_1$, $x_2$, $x_3$, ... --- _ортонормированная система_, если $norm(x_k) = 1$ и $x_k perp x_n$ для всех $k != n$.
]
#notice[
Ортогональная система линейно независима:
Пусть
$
sum_(k=1)^n c_k x_k = 0.
$
Тогда
$
0 = dotp(sum_(k=1)^n c_k x_k, x_j) = sum_(k=1)^n c_k underbrace(dotp(x_k, x_j), 0 "если" k != j) = c_j norm(x_j)^2 ==> c_j = 0.
$
]
#examples(name: "ортогональных систем")[
1. $e_n = (0, 0, ..., 0, 1, 0, 0, ...)$ --- орты в $l^2$ --- ортонормированная система в $l^2$.
2. $1$, $cos t$, $sin t$, $cos 2t$, $sin 2t$, ... --- ортогональная система в#footnote[по умолчанию считаем, что пространство Лебега построено по мере Лебега] $L^2 [0, 2pi]$.
3. $e^(i t n)$, $n in ZZ$ --- ортогональная система в $L^2 [0, 2pi]$:
$
dotp(e^(i n t), e^(i m t)) = integral_0^(2pi) e^(i n t) dot cj(e^(i m t)) dif t = integral_0^(2pi) e^(i (n - m) t) dif t = cases(2pi "при" n = m, 0 "иначе").
$
4. $1$, $cos t$, $cos 2t$, $cos 3t$, ... --- ортогональная система в $L^2 [0, pi]$.
5. $sin t$, $sin 2t$, $sin 3t$, ... --- ортогональная система в $L^2 [0, pi]$.
]
#th[
$e_1$, $e_2$, ... --- ортогональная система в гильбертовом пространстве $H$, $x = sum_(n=1)^oo c_n e_n$. Тогда $ c_n = dotp(x, e_n)/norm(e_n)^2. $
]
#proof[
$
dotp(x, e_n) = dotp(sum_(k=1)^oo c_k e_k, e_n) = sum_(k=1)^oo c_k underbrace(dotp(e_k, e_n), 0 "если" k != n) = c_n dot dotp(e_n, e_n) = c_n norm(e_n)^2.
$
]
#def[
$e_1$, $e_2$, ... --- ортогональная система в гильбертовом пространстве $H$, $x in H$. Тогда
$
c_n (x) = dotp(x, e_n)/norm(e_n)^2
$
называется _коэффициентом Фурье_ вектора $x$ по системе $e_1$, $e_2$, ....
Ряд $sum_(n=1)^oo c_n (x) e_n$ назовем _рядом Фурье_ для вектора $x$ по системе $e_1$, $e_2$, .... Мы пока ничего не знаем про его свойства, например про то, сходится ли он вообще.
]
#notice(plural: true)[
1. Если $x = sum_(n=1)^oo c_n e_n$, то это его ряд Фурье.
2. $n$-е слагаемое ряда Фурье --- проекция вектора $x$ на прямую натянутую на вектор $e_n$, то есть $x = c_n (x) e_n + z$, где $z perp e_n$. $z = x - c_n (x) e_n$, значит $dotp(z, e_n) = dotp(x, e_n) - c_n (x) dotp(e_n, e_n) = 0$.
]
#ticket[Свойства частичных сумм ряда Фурье. Неравенство Бесселя. Теорема Рисса–Фишера.]
#th(name: "свойства частичных сумм ряда Фурье")[
Пусть $e_1$, $e_2$, ... --- ортогональная система, $x in H$, $S_n := sum_(k = 1)^n c_k (x) e_k$, $Ll_n := Lin {e_1, e_2, ..., e_n}$. Тогда
1. $S_n$ --- ортогональная проекция $x$ на $Ll_n$, то есть $x = S_n + z$, где $z perp Ll_n$.
2. $S_n$ --- наилучшее приближение к $x$ в $Ll_n$, то есть $norm(S_n - x) = min_(y in Ll_n) norm(y - x)$.
3. $norm(S_n) <= norm(x)$.
]
#proof[
1. $z = x - S_n$. Достаточно доказать, что $z perp e_k$ для всех $k = 1, ..., n$.
$
dotp(z, e_k) = dotp(x - sum_(j=1)^n c_j (x) e_j, e_k) = dotp(x, e_k) - sum_(j=1)^n c_j (x) underbrace(dotp(e_j, e_k), 0 "если" k != j) = dotp(x, e_k) - c_k (x) norm(e_k)^2.
$
2. $x - y = underbrace(S_n - y, in Ll_n) + underbrace(z, perp Ll_n)$. Значит это сумма двух ортогональных векторов, а тогда
$
norm(x - y)^2 = norm(S_n - y)^2 + norm(z)^2 >= norm(z)^2 = norm(x - S_n)^2
$
и равенство достигается при $S_n = y$. Значит это и правда минимум.
3. $x = S_n + z$, $S_n in Ll_n$, $z perp Ll_n$. Тогда
$
norm(x)^2 = norm(z)^2 + norm(S_n)^2 >= norm(S_n)^2.
$
]
#follow(name: "<NAME>")[
$
sum_(n = 1)^oo abs(c_n (x))^2 norm(e_n)^2 <= norm(x)^2.
$
]
#proof[
$
norm(x)^2 >= norm(S_n)^2 = sum_(k=1)^n norm(c_k (x) e_k)^2 = sum_(k = 1)^n abs(c_k (x))^2 norm(e_k)^2
$
и устремляем $n$ в $oo$.
]
#th(name: "Рисса-Фишера")[
$H$ --- гильбертово пространство, $x in H$, $e_1$, $e_2$, $e_3$, ... --- ортогональная система в $H$. Тогда
1. Ряд Фурье для $x$ сходится.
2. $x = sum_(n = 1)^oo c_n (x) e_n + z$, где $z perp e_n$ для всех $e_n$.
3. $x = sum_(n = 1)^oo c_n (x) e_n$ тогда и только тогда, когда $norm(x)^2 = sum_(n = 1)^oo abs(c_n (x))^2 norm(e_n)^2$.
Третий пункт известен как тождество Парсеваля.
]
#proof[
1. Знаем $sum_(n=1)^oo abs(c_n (x))^2 norm(e_n)^2 <= norm(x)^2$ (неравенство Бесселя), значит $sum_(n=1)^oo c_n (x) e_n$ --- сходится.
2. $z = x - sum_(k = 1)^oo c_k (x) e_k$.
$
dotp(z, e_n) = dotp(x, e_n) - sum_(k=1)^oo c_k (x) underbrace(dotp(e_k, e_n), 0 "если" k != n) = dotp(x, e_n) - c_n (x) dotp(e_n, e_n) = 0.
$
3. $z perp sum_(k = 1)^oo c_k (x) e_k$, $0 = dotp(z, S_n) --> dotp(z, S)$. Значит
$
norm(x)^2 = norm(z)^2 + norm(sum_(k=1)^oo c_k (x) e_k)^2 = norm(z)^2 + sum_(k=1)^oo abs(c_k (x))^2 norm(e_k)^2.
$
]
#notice[
1. $S = sum_(k=1)^oo c_k (x) e_k$ --- ортогональная проекция на $Cl Lin {e_1, e_2, ...}$.
2. Если $sum_(k=1)^oo abs(c_k)^2 norm(e_k)^2 < +oo$, то найдется $x$ такой, что $sum_(k=1)^oo c_k e_k$ --- его ряд Фурье.
]
#ticket[Базис. Свойства эквивалентные тому, что система является базисом.]
#def[
$e_1$, $e_2$, ... --- ортогональная система в $H$.
1. $e_1$, $e_2$, ... --- _базис_, если для любого $x in H$, $x = sum_(n=1)^oo c_n (x) e_n$.
2. $e_1$, $e_2$, ... --- _полная система_, если $z perp e_n$ для любого $n$, тогда и только тогда, когда $z = 0$.
3. $e_1$, $e_2$, ... --- _замкнутая система_, если для любого $x in H$, $norm(x)^2 = sum_(n=1)^oo abs(c_n (x))^2 norm(e_n)^2$.
]
#th[
Следующие условия равносильны:
1. $e_1$, $e_2$, ... --- базис.
2. $forall x, y in H space dotp(x, y) = sum_(n=1)^oo c_n (x) cj(c_n (y)) norm(e_n)^2$.
3. $e_1$, $e_2$, ... --- замкнутая система.
4. $e_1$, $e_2$, ... --- полная система.
5. $Cl Lin {e_n} = H$.
]
#proof[
- "$1==>2$": $dotp(x, y) = dotp(sum_(k = 1)^oo c_k (x) e_k, sum_(n=1)^oo c_n (y) e_n)$. Надо раскрыть скобки и все получится.
- "$2==>3$": Берем $y = x$.
- "$3==>4$": Пусть $z perp e_n$ для любого $n$. Тогда $c_n (z) = 0$ для любого $n$, и $norm(z)^2 = sum_(n = 1)^oo abs(c_n (z))^2 norm(e_n)^2 = 0$.
- "$4==>1$": $x = sum_(n=1)^oo c_n (x) e_n + z$, где $z perp e_n$ для любого $n$. Значит $z = 0$.
- "$1==>5$": $x = sum_(n=1)^oo c_n (x) e_n <-- sum_(k = 1)^n c_k (x) e_k in Lin {e_n}$, значит любой $x$ лежит в замыкании, и $H subset Cl Lin {e_n}$.
- "$5==>4$": $z perp e_n$ для любого $n$. Тогда $z perp Lin {e_n}$, значит $z perp Cl Lin {e_n} = H$, значит $z perp z$, значит $z = 0$.
]
#ticket[Ортогонализация Грама–Шмидта. Ортогональные многочлены. Определение и примеры.]
#th(name: "ортогонализация Грама-Шмидта")[
Пусть $H$ --- пространство со скалярным произведением; $x_1$, $x_2$, ... --- линейно независимая система векторов (не более чем счетная --- для конечных тоже работает). Тогда существует ортонормированная $e_1$, $e_2$, ... такая, что для любого $n$, $Lin {e_1, e_2, ..., e_n} = Lin {x_1, x_2, ..., x_n}$.
]
#proof[
Доказательство конструктивное, поэтому вместе с ним прилагается конкретный способ такую систему построить. Такой процесс называется "_ортогонализацией Грама-Шмидта_".
Понятно, что любую систему векторов можно нормировать, поэтому построим ортогональную, а потом исправим ее. Пусть $f_1 = x_1$. Дальше ищем $f_n = x_n - a_1 f_1 - a_2 f_2 - ...$. Тогда, так как это просто линейная комбинация,
$
Lin {f_1, f_2, ..., f_n} = Lin lr(size: #1.5em, {underbrace(f_1\, f_2\, ...\, f_(n - 1), Lin{x_1, x_2, ..., x_(n - 1)}), x_n}) = Lin {x_1, x_2, ..., x_(n - 1), x_n}.
$
Осталось подобрать коэффициенты, чтобы была ортогональность, то есть, чтобы для любого $k < n$:
$
0 = dotp(f_n, f_k) = dotp(x_n, f_k) - a_1 dotp(f_1, f_k) - ... - a_(n - 1) dotp(f_(n - 1), f_k) = dotp(x_n, f_k) - a_k dotp(f_k, f_k),
$
так как $dotp(f_i, f_k) = 0$ при $i != k$.
Значит $a_k = dotp(x_n, f_k)/norm(f_k)^2$, то есть $a_k = c_k (x_n)$ --- коэффициенты Фурье. Дальше, говорим $e_n = f_n / norm(f_n)$. Надо только проверить, что $f_n != 0$. Ну, действительно, в этом случае
$
x_n = a_1 f_1 + ... + a_(n - 1) f_(n - 1) in Lin {f_1, ..., f_(n - 1)} = Lin {x_1, ..., x_(n - 1)}.
$
]
#exercise[
Если $tilde(e)_1$, $tilde(e)_2$, ... --- другая ортонормированная система с тем же свойством ($forall n space Lin {e_1, e_2, ..., e_n} = Lin {x_1, x_2, ..., x_n}$), то $tilde(e)_n = lambda_n e_n$, где $lambda_n in RR$ (или $CC$), и $abs(lambda_n) = 1$.
]
#def(name: "<NAME>лены")[
Пусть $w: dotp(a, b) --> RR$ --- неотрицательная измеримая (здесь $dotp(a, b)$ --- любой промежуток). Пусть $mu A := integral_A w dif lambda_1$, $dotp(x, y) := integral_a^b x(t) cj(y(t)) w(t) dif lambda_1 (t)$. Тогда $L^2 ((a, b), mu)$ --- гильбертово. Предположим, что $w$ такая, что $integral_a^b t^n w(t) dif lambda_1 (t)$ абсолютно сходится при любом $n$, то есть $t^n in L^2 ((a, b), mu)$, то есть все мономы лежат в пространстве, а значит и все многочлены. Возьмем последовательность этих мономов ($t^0$, $t^1$, $t^2$, ...) и ортогонализируем Граммом-Шмидтом. Получается последовательность _ортогональных многочленов_ относительно скалярного произведения $dotp(dot, dot)$ с весом $w$.
]
#examples[
1. $L^2 ([-1, 1], lambda_1)$: многочлены Лежандра:
$
P_n (t) := 1/(2^n n!) ((t^2 - 1)^n)^((n)).
$
Действительно,
$
dotp(P_n, P_k) =
1/(2^n n!) dot 1/(2^k k!) integral_(-1)^1 ((t^2 - 1)^k)^((k)) ((t^2 - 1)^n)^((n)) dif t newline(=^"по частям")
... underbrace(lr(((t^2 - 1)^k)^((k)) ((t^2 - 1)^n)^((n - 1)) |)_(-1)^1, 0) - ... dot integral_(-1)^1 ((t^2 - 1)^k)^((k + 1)) ((t^2 - 1)^n)^((n - 1)) dif t newline(=) ... =^"много раз"_"по частям"
... dot integral_(-1)^1 underbrace(((t^2 - 1)^k)^((2k + 1)), 0) ((t^2 - 1)^2)^((n - k - 1)) dif t = 0.
$
Если постараться, можно проверить, что они нормированы.
2. $L^2 ([-1, 1], (dif lambda_1)/sqrt(1 - t^2))$ ($w(t) = 1/sqrt(1 - t^2)$): многочлены Чебышева первого рода:
$
T_n (t) = cos (n arccos t).
$
Да, это многочлены (можно проверить по индукции). Они правда ортогональны:
$
dotp(T_k, T_n) =
integral_(-1)^1 cos(k arccos t) cos(n arccos t) (dif t)/sqrt(1 - t^2)
=^(s = arccos t \ cos s = t \ dif t =
-sin s dif s) integral_0^pi cos(k s) cos(n s) (sin s)/(sin s) dif s newline(=)
1/2 integral_0^pi (cos((k + n) s) + cos((k - n) s)) dif s = 0.
$
3. $L^2 ([-1, 1], sqrt(1 - t^2) dif lambda_1)$: многочлены Чебышева второго рода:
$
U_n (t) = (sin ((n + 1) arccos t))/sqrt(1 - t^2).
$
4. $L^2 (RR, e^(-t^2) dif lambda_1)$: многочлены Эрмита:
$
H_n (t) = e^(t^2) (e^(-t^2))^((n)).
$
5. $L^2 ([0, +oo), e^(-t) dif lambda_1)$: многочлены Лагерра (ударение на "е"):
$
L_n (t) = 1/n! e^t (t^n e^(-t))^((n)).
$
]
#exercise[
Проверить, что 3-5 --- ортонормированные системы многочленов.
]
#th[
Все эти многочлены --- базисы.
]
#proof[
Ортогональность есть, надо доказать $Cl Lin {"многочлены"} = L^2$.
$
Lin {P_1, P_2, ...} = Lin {1, t, t^2, ...}
$
--- а это все многочлены. Надо доказать, что замыкание всех многочленов это $L^2$. Мы докажем только для многочленов из пунктов 1-3, да и то творчески, сославшись на теорему из будущего. Надо понять, что любую функцию из $L^2$ можно приблизить многочленом. Берем $eps > 0$ и $f in L^2$. Тогда найдется $g in L^2$ непрерывная такая, что $norm(f - g)_2 < eps$. По теореме Вейерштрасса (докажем позже#rf("weierstrass2")), любую непрерывную функцию на отрезке можно равномерно приблизить многочленом. Тогда существует $h$ --- многочлен такой, что $norm(g - h)_oo < eps$. Знаем
$
norm(g - h)_2 <= (mu [a, b])^(1/2) norm(g - h)_oo < C eps ==> norm(f - h)_2 <= norm(f - g)_2 + norm(g - h)_2 < (C + 1) eps
$
в $L^2 ((a, b), mu)$.
]
#ticket[Наилучшие приближения. Теорема о существовании наилучшего приближения.]
#def[
Пусть $(X, rho)$ --- метрическое пространство, $A subset X$ непустое, $x in X$. Обозначим $E_A (x) = rho(x, A) = inf {rho(x, a): a in A}$. Это называется _расстоянием от точки $x$ до множества $A$_.
Если на $y^* in A$ достигается $inf$, то есть $rho(x, y^*) = rho(x, A)$, то $y^*$ --- _элемент наилучшего приближения_.
]
#lemma(name: "тождество параллелограмма")[
Следующее равенство равносильно наличию в пространстве скалярного произведения, но нам нужно только то, что в пространстве со скалярным произведением оно выполнено.
$
norm(x + y)^2 + norm(x - y)^2 = 2 norm(x)^2 + 2 norm(y)^2.
$
]
#proof[
Доказываем только вторую часть. Запишем нормы через скалярные произведения:
$
dotp(x + y, x + y) + dotp(x - y, x - y) = 2 dotp(x, x) + 2 dotp(y, y)
$
и раскроем скобки:
$
dotp(x, x) + cancel(dotp(x, y)) + cancel(dotp(y, x)) + dotp(y, y) + dotp(x, x) - cancel(dotp(x, y)) - cancel(dotp(y, x)) + dotp(y, y) = 2 dotp(x, x) + 2 dotp(y, y).
$
]
#th(name: "о наилучшем приближении")[
$A subset H$ --- непустое, замкнутое, выпуклое; $x in H$. Тогда существует единственный элемент наилучшего приближения.
]
#proof[
Пусть $d := rho(x, A)$. Пусть $y, z in A$. Тогда $(y + z)/2 in A$ из-за выпуклости. Подставим в тождество параллелограмма $x - y$ и $x - z$:
$
norm(2x - y - z)^2 + norm((x - y) - (x - z))^2 = 2norm(x - y)^2 + 2norm(x - z)^2.
$
А еще,
$
norm(2x - y - z)^2 = norm(2(x - (y + z)/2))^2 = 4 norm(x - (y + z)/2)^2 >= 4d^2.
$
Тогда
$
norm(y - z)^2 <= 2(norm(x - y)^2 + norm(x - z)^2 - 2d^2).
$
Рассмотрим последовательность $a_n in A$ такая, что $rho(x, a_n) --> d$. Подставим разные индексы в неравенство выше вместо ранее произвольных $x$ и $y$:
$
norm(a_n - a_k)^2 <= 2 (norm(x - a_k)^2 + norm(x - a_n)^2 - 2d^2),
$
а последняя штука маленькая при больших $n$. Значит $a_n$ --- фундаментальная, и у нее есть предел в $a^* in H$, и из замкнутости он в $A$. Проверим, что $norm(x - a^*) = d$. Ну... ну да:
$
norm(x - a_n) --> norm(x - a^*) = d.
$
Теперь докажем единственность. Пусть $norm(x - a^*) = norm(x - b^*) = d$. Подставляем в то же неравенство:
$
norm(a^* - b^*)^2 <= 2(norm(x - a^*)^2 + norm(x - b^*)^2 - 2d^2) = 0 ==> a^* = b^*.
$
]
#ticket[Теорема о проекции. Ортогональные проекции. Свойства.]
#th(name: "об ортогональной проекции")[
Пусть $H$ --- гильбертово, $L subset H$ --- замкнутое подпространство, $x in H$. Тогда $x$ единственным образом представляется в виде суммы $x = y + z$, где $y in L$, а $z perp L$. Такой $y$ называется _ортогональной проекцией_, и этот $y$ --- элемент наилучшего приближения к $x$ в $L$.
]
#proof[
Пусть $y$ --- элемент наилучшего приближения к $x$ в $L$, он существует по предыдущей теореме. $z := x - y$. Надо проверить, что $z perp L$, остальное получилось само.
Возьмем $l in L$. Тогда $y + lambda l in L$ для любого $lambda in RR$ (или $CC$). Тогда
$
norm(z - lambda l)^2 = norm(x - (y + lambda l))^2 >= norm(x - y)^2 = norm(z)^2.
$
Раскроем скобки в первой норме:
$
norm(z - lambda l)^2 = dotp(z - lambda l, z - lambda l) = norm(z)^2 + abs(lambda)^2 norm(l)^2 - underbrace(dotp(z, lambda l), cj(lambda) dotp(z, l)) - underbrace(dotp(lambda l, z), lambda cj(dotp(z, l))) newline(==>)
abs(lambda)^2 norm(l)^2 >= cj(lambda) dotp(z, l) + lambda cj(dotp(z, l)).
$
Подставим $lambda = dotp(z, l)/norm(l)^2$:
$
abs(dotp(z, l))^2/norm(l)^4 dot norm(l)^2 >= (abs(dotp(z, l))^2)/norm(l)^2 + (abs(dotp(z, l))^2)/norm(l)^2.
$
Значит $abs(dotp(z, l))^2 >= 2 abs(dotp(z, l))^2$, значит $dotp(z, l) = 0$, но $l in L$ --- любой ненулевой вектор. Значит $z perp L$.
]
#def[
Пусть $L$ --- замкнутое подпространство $H$. _Ортогональное дополнение_ $L^perp = {x in H: x perp L}$.
]
#def[
Пусть $L$ --- замкнутое подпространство $H$. Оператор ортогонального проецирования $P_L x = "ортогональная проекция" x "на" L$.
]
#props[
1. $P_L$ --- линейный оператор.
2. Если $L != {0}$, то $norm(P_L) = 1$.
3. $P_(L^perp) = Id - P_L$.
4. $(L^perp)^perp = L$.
]
#proof[
1. Берем $x = y + z$, $y in L$, $z perp L$, и $tilde(x) = tilde(y) + tilde(z)$, $tilde(y) in L$, $tilde(z) perp L$, тогда
$
alpha x + tilde(alpha) tilde(x) = underbrace(alpha y + tilde(alpha) tilde(y), in L) + underbrace(alpha z + tilde(alpha) tilde(z), perp L) ==>
P_L (alpha x + tilde(alpha) tilde(x)) = alpha y + tilde(alpha) tilde(y) = alpha P_L x + tilde(alpha) P_L tilde(x).
$
2. Берем $x = y + z$, $y in L$, $z perp L$. Тогда $norm(x)^2 = norm(y)^2 + norm(z)^2 >= norm(y)^2$. Значит $norm(x) >= norm(P_L x)$, значит $norm(P_L) <= 1$. Если $x in L$, то $P_L x = x$, значит $norm(P_L) = 1$.
3. Берем $x = y + z$, $y in L$, $z in L^perp$. Тогда $x = P_L x + P_(L^perp) x$, то есть $Id = P_L + P_(L^perp)$.
4. $P_((L^perp)^perp) = Id - P_(L^perp) = Id - (Id - P_L) = P_L$, значит $L = P_L (H) = P_((L^perp)^perp) (H) = (L^perp)^perp$.
]
#ticket[Сепарабельные пространства. Существование базиса. Изоморфность сепарабельных гильбертовых пространств.]
#def[
Пусть $(X, rho)$ --- метрическое пространство. Назовем его _сепарабельным_, если в нем есть счетное, всюду плотное множество.
]
#examples[
1. $RR^d$: $QQ^d$ --- счетное, всюду плотное.
2. $L^p (RR^d, lambda_d)$: плотны ступенчатые функции с рациональными значениями и ступеньками по ячейкам с рациональными координатами вершин. Доказательство остается читателю.
]
#th[
В сепарабельном гильбертовом пространстве существует не более чем счетный ортонормированный базис.
]
#proof[
Рассматриваем ${x_n}$ --- счетное, всюду плотное множество. "Просеим" это множество так: если элемент выражается как линейная комбинация предыдущих --- выбрасываем его, иначе оставляем. Получим подмножество ${y_n}$ --- линейно независимое, причем $Lin {x_n} = Lin {y_n}$. Ортогонализируем Граммом-Шмидтом. $Lin {x_n} = Lin {y_n} = Lin {e_n}$. Тогда $H = Cl {x_n} subset Cl Lin {x_n} = Cl Lin {e_n}$.
]
#th[
Бесконечномерное сепарабельное гильбертово пространство изометрично $l^2$. То есть существует биекция, сохраняющая линейность и расстояние.
]
#proof[
Пусть $H$ --- сепарабельное Гильбертово. Рассмотрим его ортонормированный базис $e_1$, $e_2$, .... Он счетный, так как пространство бесконечномерное. Сопоставим $x arrow.long.bar c_n (x) = dotp(x, e_n)$. Это линейное отображение, поэтому линейность сохраняется. Расстояния тоже:
$
norm(x)^2 =
sum_(n=1)^oo abs(c_n (x))^2 underbrace(norm(e_n)^2, 1) =
sum_(n=1)^oo abs(c_n (x))^2 =
norm({c_n (x)})_(l^2)^2.
$
Более того, скалярное произведение тоже не меняется. Можно проверить аналогичным рассуждением для $dotp(x, y)$.
]
|
|
https://github.com/RemiSaurel/miage-rapide-tp | https://raw.githubusercontent.com/RemiSaurel/miage-rapide-tp/main/0.1.0/README.md | markdown | # miage-rapide-tp
Typst template to generate a practical work report for students of the MIAGE (Méthodes Informatiques Appliquées à la Gestion des Entreprises).
# 🧑💻 Usage
- Directly from [Typst web app](https://typst.app/) by clicking "Start from template" on the dashboard and searching for `miage-rapide-tp`.
- With CLI:
```
typst init @preview/miage-rapide-tp
```
# 🚀 Features
- Cover page
- Table of contents (optionnal)
- `question` = automatically generates a question number (optionnal) with the content of the question
- `code_block` = code block with syntax highlighting
- `remarque` = a remark block with content and color
# 📝 License
This is MIT licensed.
> Rapide means fast in French. tp is the abbreviation of "travaux pratiques" which means practical work. MIAGE is a French degree in computer science applied to management.
```
```
|
|
https://github.com/noahjutz/AD | https://raw.githubusercontent.com/noahjutz/AD/main/notizen/sortieralgorithmen/mergesort/merge_output.typ | typst | #import "/components/num_row.typ": single_num_row, braced_b
#let a1 = (12, 23, 34, 34, 45)
#let a2 = (7, 17, 18, 38, 43)
#let nums = (7, 12, 17, 18, 23, 34, 34, 38, 43, 45)
#single_num_row(
nums,
hl_primary: nums.enumerate()
.filter(((i, n)) => n in a1)
.map(((i, n)) => i),
hl_secondary: nums.enumerate()
.filter(((i, n)) => n in a2)
.map(((i, n)) => i),
labels_b: (
(0, nums.len(), braced_b[`anew`]),
)
) |
|
https://github.com/kadykov/typstCV | https://raw.githubusercontent.com/kadykov/typstCV/main/README.md | markdown | # typstCV
CV made with typst
|
|
https://github.com/cloudsftp/blimm.typ | https://raw.githubusercontent.com/cloudsftp/blimm.typ/latest/README.md | markdown | # Blimm
## Personal Typst Letter Template
### Etymology
- Letter
- Brief (translated to german)
- Brief (english again)
- Blunt
- Blimm (nickname for blunts)
|
|
https://github.com/jonaspleyer/peace-of-posters | https://raw.githubusercontent.com/jonaspleyer/peace-of-posters/main/docs/content/documentation/boxes.md | markdown | MIT License | ---
title: "Boxes"
weight: 10
---
# Boxes
Please note that most values which have default values [none] are probably specified either by a [theme](/themes) or [layout](/documentation/layouts).
## Common Box
This box is mostly meant as a shared template for other functions to be calling.
While it can be used individually, users should strongly consider relying on other functions.
The `common-box` method creates two rectangles, one for the heading and one for the body of the box.
Both are optional and can be left out.
This box also automatically considers the currently defined [theme](themes) and styles the box accordingly.
```typst
common-box(
body: [none] [content],
heading: [none] [content],
heading-size: [none] [length],
heading-box-args: [none] [dictionary],
heading-text-args: [none] [dictionary],
body-size: [none] [length],
body-box-args: [none] [dictionary],
body-text-args: [none] [dictionary],
stretch-to-next: [bool],
spacing: [none] [length] [relative],
bottom-box: [bool],
) --> [content]
```
| Argument | Type | Default Value | Description |
| --- | --- | --- | --- |
| `body` | [none] [content] | [none] | The lower rectangle containing the body of the box. |
| `heading` | [none] [content] | [none] | The upper rectangle which defines the heading of the box.
| `heading-box-args` | [none] [dictionary] | [none] | Arguments given to the box-type function that creates the heading. |
| `heading-text-args` | [none] [dictionary] | [none] | Arguments given to the `text` function which creates the heading. |
| `body-size` | [none] [length] | [none] | Size of the body. |
| `body-box-args` | [none] [dictionary] | [none] | Arguments given to the box-type function that creates the body. |
| `body-text-args` | [none] [dictionary] | [none] | Arguments given to the `text` function which creates the body. |
| `stretch-to-next` | [bool] | [false] | The vertical size of the box is stretched such that it fills out the remainder of the vertical space. |
| `spacing` | [none] | [none] | Only useful when specifying `stretch-to-next`. Controls spacing towards next block. |
| `bottom-box` | [bool] | [false] | The box should be aligned towards the bottom of the page. |
<div class="warning-block">
<h2>Warning</h2>
<p>The <code>stretch-to-next</code> should not be used on a block which is already maximal by itself.
Doing so will most likely result in glitches.
</p>
</div>
### Example
```typst
#common-box(
heading: "peace-of-posters - Create scientific posters",
)
```
## Column Box
```typst
column-box(
body: [content],
..args
) --> [content]
```
All arguments align with `common-box` but the `column-box` requires at least a body.
## Bottom Box
A box that will be placed at the bottom of the page.
It is also possible to specify a logo and text-width of the remaining content.
```typst
bottom-box(
body: [content],
text-relative-width: [relative],
logo: [none] [content],
..args
) --> [content]
```
| Argument | Type | Default Value | Description |
| --- | --- | --- | --- |
| `body` | [content] | | Body of the bottom box. |
| `text-relative-width` | [relative] | `70%` | Space left of the logo where text can be displayed. |
| `logo` | [none] [content] | [none] | The content which should be used as logo. Usually specified by an [image](https://typst.app/docs/reference/visualize/image/). It will be aligned towards the right side of the box. |
## Bibliography Box
<div class="warning-block">
<h2>Warning</h2>
<p>This function is currently not working due to unwieldy file-path handling.
See <a href="https://github.com/typst/typst/issues/971">#971</a> for more details.</p>
</div>
```typst
bibliography-box(
bib-file: [str],
text-size: [length],
title: [none] [content],
style: [str],
stretch-to-next: [bool]
) --> [content]
```
| Argument | Type | Default Value | Description |
| --- | --- | --- | --- |
| `bib-file` | [str] | | Path to the bibliography file. |
| `text-size` | [length] | `24pt` | Font size of the bibliography. |
| `title` | [none] [content] | [none] | Title of the Bibliography Box. |
| `style` | [str] | `"ieee"` | Citation style. |
| `stretch-to-next` | [bool] | [false] | See [Common Box](#common-box). |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/place_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test how the placed element interacts with paragraph spacing around it.
#set page("a8", height: 60pt)
First
#place(bottom + right)[Placed]
Second
|
https://github.com/unb3rechenbar/TypstPackages | https://raw.githubusercontent.com/unb3rechenbar/TypstPackages/main/shortcuts/Symbols/0.1.0/src/lib.typ | typst |
// > ========= cal small =========
#let ca = $cal(a)$
#let cb = $cal(b)$
#let cc = $cal(c)$
#let cd = $cal(d)$
#let ce = $cal(e)$
#let cf = $cal(f)$
#let cg = $cal(g)$
#let ch = $cal(h)$
#let cj = $cal(j)$
#let ck = $cal(k)$
#let cl = $cal(l)$
#let cm = $cal(m)$
#let cn = $cal(n)$
#let co = $cal(o)$
#let cp = $cal(p)$
#let cq = $cal(q)$
#let cr = $cal(r)$
#let cs = $cal(s)$
#let ct = $cal(t)$
#let cu = $cal(u)$
#let cv = $cal(v)$
#let cw = $cal(w)$
#let cx = $cal(x)$
#let cy = $cal(y)$
#let cz = $cal(z)$
// > ========= cal big =========
#let cA = $cal(A)$
#let cB = $cal(B)$
#let cC = $cal(C)$
#let cD = $cal(D)$
#let cE = $cal(E)$
#let cF = $cal(F)$
#let cG = $cal(G)$
#let cH = $cal(H)$
#let cI = $cal(I)$
#let cJ = $cal(J)$
#let cK = $cal(K)$
#let cL = $cal(L)$
#let cM = $cal(M)$
#let cN = $cal(N)$
#let cO = $cal(O)$
#let cP = $cal(P)$
#let cQ = $cal(Q)$
#let cR = $cal(R)$
#let cS = $cal(S)$
#let cT = $cal(T)$
#let cU = $cal(U)$
#let cV = $cal(V)$
#let cW = $cal(W)$
#let cX = $cal(X)$
#let cY = $cal(Y)$
#let cZ = $cal(Z)$
|
|
https://github.com/Gekkio/gb-ctr | https://raw.githubusercontent.com/Gekkio/gb-ctr/main/chapter/cartridges/mmm01.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "../../common.typ": *
== MMM01
TODO.
|
https://github.com/giacomocavalieri/gleamy_slides | https://raw.githubusercontent.com/giacomocavalieri/gleamy_slides/main/template.typ | typst | Apache License 2.0 | // --- VARIABLES ---------------------------------------------------------------
#let faded = color.rgb("#8E8E8E")
#let off-white = color.rgb("#fefefc")
#let black = color.rgb("#1e1e1e")
#let faff-pink = color.rgb("#ffaff3")
// --- RULES TO MAKE STUFF LOOK GOOD
#set text(font: "Open Sauce One", size: 1.5em)
#set page(paper: "a5", flipped: true)
#show heading.where(level: 1): set text(size: 1.3em)
#show page: it => {
let emph_fill = if it.fill == faff-pink { black } else { faff-pink }
show emph: set text(weight: "black", fill: emph_fill)
it
}
// --- CODE RULES --------------------------------------------------------------
// We add Gleam's syntax to the supported ones
// and a code theme that's good on dark backgrounds.
#set raw(
syntaxes: "gleam.sublime-syntax",
theme: "gleam.tmTheme",
)
#let fade-code-lines(lines-to-show, code-lines) = {
if lines-to-show == "all" {
code-lines.join("\n")
} else if type(lines-to-show) == int {
fade-code-lines((lines-to-show,), code-lines)
} else {
code-lines.map(line => {
if line.number - 1 not in lines-to-show {
text(fill: faded, line.text)
} else { line }
}).join("\n")
}
}
// When we run into a Gleam code block we change
// its background to dark and the default color
// to an off-white color so that the highligh theme
// looks good.
#show raw.where(block: true): it => {
let first-line = it.lines.first().text
let content = if first-line.starts-with("{") and first-line.ends-with("}") {
let lines-to-show = first-line
.trim("{").trim("}")
.split(regex("\s*,\s*"))
.map(it => {
if it.contains("-") {
let (start, end) = it.split("-")
range(int(start), int(end) + 1)
} else {
(int(it))
}
})
.flatten()
fade-code-lines(lines-to-show, it.lines.slice(1))
} else {
// Normal text block, no need to hide anything
it
}
text(fill: off-white, block(
width: 100%,
fill: black,
inset: 1em,
radius: 10%,
content,
))
}
// --- BUILDING A SLIDE --------------------------------------------------------
#let slide(title: none, style: "light", ..fragments) = {
let background = if style == "light" { off-white }
else if style == "dark" { black }
else if style == "pink" { faff-pink }
else { panic("not a valid style") }
let font-color = if style == "light" { black }
else if style == "dark" { off-white }
else if style == "pink" { black }
else { panic("not a valid style") }
if fragments.pos().len() == 1 {
// A slide with a single fragment
page(fill: background, text(fill: font-color)[
#if title != none [== #title]
#align(horizon, fragments.pos().at(0))
])
} else {
// A fragmented slide
let shown = ()
let hidden = fragments.pos().rev()
for fragment in fragments.pos() {
shown.push(fragment)
let _ = hidden.pop()
slide(title: title, style: style)[
#for elem in shown { [ #elem #parbreak() ] }
#for elem in hidden.rev() { hide[ #elem #parbreak() ] }
]
}
}
}
#let slide-code-fragments(title: none, fragments, code) = {
for fragment in fragments {
show raw: it => fade-code-lines(fragment, it.lines)
slide(title: title, style: "dark", code)
}
}
#let quote(from: none, content) = {
let quote = heading(
level: 1,
outlined: false,
bookmarked: false,
content,
)
if from == none { quote } else {
let name = text(
style: "italic",
size: .8em,
align(left, "- " + from),
)
stack(dir: ttb, spacing: 1em, quote, name)
}
}
|
https://github.com/mrcinv/nummat-typst | https://raw.githubusercontent.com/mrcinv/nummat-typst/master/03b_Poisson.typ | typst | == Poissonova enačba na krogu
<poissonova-enačba-na-krogu>
Drug primer, ko dobimo tridiagonalni sistem lineranih enačb, če iščemo
rešitev za robni problem na krogu $x^2 + y^2 lt.eq 1$ za
#link("https://sl.wikipedia.org/wiki/Poissonova_ena%C4%8Dba")[Poissonovo enačbo]
$ triangle.stroked.t u lr((x comma y)) = f(r) $
z robnim pogojem $u lr((x comma y)) = 0$ za $x^2 + y^2 = 1$. Pri
tem je $f(r) = f(sqrt(x^2 + y^2))$ podana funkcija, ki je
odvisna le od razdalje do izhodišča.
#link("https://en.wikipedia.org/wiki/Laplace_operator")[Laplaceov operator]
zapišemo v polarnih koordinatah in enačbo diskretiziramo z metodo
#link("https://en.wikipedia.org/wiki/Finite_difference")[končnih diferenc]. |
|
https://github.com/Henriquelay/pathsec-checker | https://raw.githubusercontent.com/Henriquelay/pathsec-checker/main/presentation/figures/base_boxes.typ | typst | #set page(width: auto, height: auto, margin: (x: 0pt, y: 0pt))
#set text(font: "DejaVu Sans Mono")
#let myswitch(name, digest, expected) = {
box[
#table(
columns: 2,
fill: if (digest == expected) {
lime
} else {
red
},
align: (right, left),
[name], [#name],
[digest], [#digest],
[expected], [#expected],
)
]
}
#table(
columns: 4,
stroke: none,
inset: 3pt,
myswitch([e1], [0x61E8D6E7], [0x61E8D6E7]),
myswitch([s1], [0xAE91434C], [0xAE91434C]),
myswitch([s2], [0x08C97F5F], [0x08C97F5F]),
myswitch([s3], [0xEFF1AAD2], [0xEFF1AAD2]),
myswitch([s4], [0x08040C89], [0x08040C89]),
myswitch([s5], [0xAA99AE2E], [0xAA99AE2E]),
myswitch([s6], [0x7669685E], [0x7669685E]),
myswitch([s7], [0x03E1E388], [0x03E1E388]),
myswitch([s8], [0x2138FFD3], [0x2138FFD3]),
myswitch([s9], [0x1EF2CBBE], [0x1EF2CBBE]),
myswitch([s10], [0x99C5FE05], [0x99C5FE05]),
)
#pagebreak()
#table(
columns: 4,
stroke: none,
inset: 3pt,
myswitch([e10], [0x61E8D6E7], [0x61E8D6E7]),
myswitch([s10], [0xCFFABC9F], [0xCFFABC9F]),
myswitch([s9], [0x69409E70], [0x69409E70]),
myswitch([s8], [0xF3E992E0], [0xF3E992E0]),
myswitch([s7], [0x8DDE192B], [0x8DDE192B]),
myswitch([s6], [0x92B098FA], [0x92B098FA]),
myswitch([s5], [0x1115A62C], [0x1115A62C]),
myswitch([s4], [0x41E1B5E0], [0x41E1B5E0]),
myswitch([s3], [0x227F0B72], [0x227F0B72]),
myswitch([s2], [0x82FC6346], [0x82FC6346]),
myswitch([s1], [0xD01E3E0F], [0xD01E3E0F]),
)
|
|
https://github.com/ludwig-austermann/typst-ouset | https://raw.githubusercontent.com/ludwig-austermann/typst-ouset/main/examples/ex.typ | typst | MIT License | #import "../ouset.typ": *
We have
$ 1 / n ouset(-->, n -> oo) 0. $
We also know, that
$ M &= sum_(k=0)^oo q^k = 1 + q + q^2 + q^3 + q^4 + dots\
&= 1 + q (1 + q + q^2 + q^3 + dots)\
ouset(&, =, "Def.", "of" M) 1 + q dot M $
In contrary to
$ M &= sum_(k=0)^oo q^k = 1 + q + q^2 + q^3 + q^4 + dots\
&= 1 + q (1 + q + q^2 + q^3 + dots)\
&overunderset(=, "Def.", "of" M) 1 + q dot M $
Note, that the `limit` function is used and that as such it become quite unreadable if used inside subscripts, etc.:
$ underbrace((n - 1) / n^2, underset(-->, n -> oo) 0) dot n = (n - 1) / n = 1 - 1/n underset(->, n --> oo) 1 $
However, we can also write small fractions quite nicely, $ouset(-,1,2)$, or have something like this: $ouset(2,star)$, $ouset(lim_n^n,n,n)$ and $ouset(,1,2)$. |
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/cpp/lectures/2024-10-11.typ | typst | == Структурные шаблоны
=== Адаптер
Хотим штуку с одним интерфейсом засунуть в функцию, которая ожидает другой
интерфейс
Есть такое:
```cpp
void draw(const PointsShape1& ps); // ps.begin(), ps.end()
class Line { Point a, b; };
```
Хотим использовать в таком:
```cpp
using V1 = std:vector<Point>::iterator;
void draw_points(V1 start, V1 end);
```
Делаем класс-обертку (адаптер) с правильным интерфейсом:
```cpp
using V1 = std::vector<Point>::iterator;
class LinePointShape : public Shape1 {
public:
V1 begin() override { ... }
V1 end() override { ... }
private:
Line* line_;
}
```
== Мост (Bridge, Pimpl)
- Отделить интерфейс от реализации
- Скрыть детали реализации
Полезно, если интерфейс простой, а релизация сложная
```cpp
class Optimizer {
public:
using Target = float(Variablies&);
virtual void set_target(Target* f);
virtual Soution optimize(); // вызывает методы impl_
private:
class OptiomizerImpl {
...
};
std::unique_ptr<OptimizerImpl> impl_; // "Настоящая" реализация
};
```
Внутреннюю реализацию можно "подменять" в зависимости от задачи
== Компоновщик (Composite)
Позволяет единым образом трактовать индивидуальные и составные объекты
Пример: в графическом редакторе одни и те же действия можно выполнять как с
одним элементом, так сразу и со многими
```cpp
struct Component {
virtualvoid op1();
virtual add(Component*);
};
struct Leaf : Component {
void op1() override;
}:
struct Group : Component {
void op1() override;
void add() override;
};
```
== Декоратор (Decorator)
Декоратор --- это "примесь объектов"
Объект помещается в другой объект, который повторяет интерфейс первого, но
что-то добавляет
Например: Shape, ColorShape, TransparentShape, Circle, Rectangle
```cpp
// Базовый класс
struct Shape {
virtual void draw() const = 0;
};
// Конкретная реализация
struct Circle : Shape {
Circle(float r);
void draw() const override { ... };
};
// Декоратор, дополнительное свойство
struct ColoredShape : Shape {
Shape& shape;
float color;
ColoredShape(Shape& s, float c) : shape(s), color(c) {}
void draw() const override {
set_color();
shape.draw();
}
};
```
Пример использования:
```cpp
Circle circle;
ColoreShape green_circle(circle, 0x00FF00);
green_circle.draw();
```
Декораторы можно композировать:
```cpp
TransparentShape circle {
ColoredShape{
Circle{0.5},
0x00FF00
}
}
```
== Фасад
Фасад --- интерфейс для внешних пользователей. Нужен для скрытия деталей
реализации для внешних пользователей.
== Заместитель (proxy)
Заглушка тяжелого объекта, локальный представитель удаленного объекта.
Реализует интерфейс основного объекта с некоторыми "техническими" улучшениями.
== Интератор
Как в `std`
= Шаблоны поведения
== Цепочка ответственности
Связывает объекты-получатели в цепочку и передает запрос вдоль этой цепочки,
пока его не обработают
```cpp
class Handler {
public:
void add(Handler* h) {
next = h;
}
virtual void handle(Request& rq) {
if (next) {
next->handle();
}
}
private:
Handler* next; // указатель на следующего обработчика
};
class SomeHandler : public Handler {
void handle(Request& r) override {
Handler::handle(r);
}
};
```
== Команда
Представляет действие, как объект.
Команды можно ставить в очередь и отменять.
```cpp
// Класс банковского счета
class Account {
public:
void deposit(int amount);
void withdraw(int amount);
private:
int ammount;
};
```
```cpp
struct Command {
virtual void process() = 0;
};
struct BankAccountCommand : Command {
BankAccount& account;
enum Action {
deposit,
withdraw,
} action;
int amount;
...
}
```
== Наблюдатель
Задача: при изменении одного объекта информировать об этом изменении другие.
Publish and subscribe.
При изменении поля ввода меняется состояние кнопки.
Участники:
- Объекты, заинтересованные в информации
- Объекты, обладающие информацией
То есть одни объекты "подписываются" на изменения других
```cpp
class Subject {
public:
virtual ~Subject();
virtual void attach(Observer*);
virtual void detach(Observer*);
virtual void notify();
protected:
Subject();
private:
List<Observer*> observers_;
};
```
== Состояние
Реализуем класс, как конечный автомат
Базовый класс State определяет нужные виртуальные методы, производные классы
переопределяют эти методы для конкретного состояние.
Внутри класса храним указатель на нужный State.
== Шаблонный метод
В базовом классе алгоритм, который вызывает некоторые виртуальные функции.
Эти функции (например, для оптимизации можно переопределить)
== Стратегия
Алгоритм решения выделяется в класс.
...
=== Посетитель
```cpp
class Visitor {
public:
virtual void visit(ElementA*) = 0;
virtual void visit(ElementB*) = 0;
protected:
Visitor();
};
class Element {
public:
virtual ~Element();
virtual void accept(Visitor& v) = 0;
protected:
Element();
};
```
Может, например, быть `SaveVisitor`.
|
|
https://github.com/Ciflire/typst-templates | https://raw.githubusercontent.com/Ciflire/typst-templates/main/README.md | markdown | MIT License | # typst-templates
A repo concentrating templates I have written
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/011.%20noop.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)
= Why Arc Isn't Especially Object-Oriented
#v(10pt)
There is a kind of mania for object-oriented programming at the moment, but some of the smartest programmers I know are some of the least excited about it.
My own feeling is that object-oriented programming is a useful technique in some cases, but it isn't something that has to pervade every program you write. You should be able to define new types, but you shouldn't have to express every program as the definition of new types.
I think there are five reasons people like object-oriented programming, and three and a half of them are bad:
+ Object-oriented programming is exciting if you have a statically-typed language without lexical closures or macros. To some degree, it offers a way around these limitations. (See Greenspun's Tenth Rule.) #footnote[#quote(attribution: [Philip Greenspun])["Greenspun's Tenth Rule of Programming: any sufficiently complicated C or Fortran program contains an ad hoc informally-specified bug-ridden slow implementation of half of Common Lisp."]]
+ Object-oriented programming is popular in big companies, because it suits the way they write software. At big companies, software tends to be written by large (and frequently changing) teams of mediocre programmers. Object-oriented programming imposes a discipline on these programmers that prevents any one of them from doing too much damage. The price is that the resulting code is bloated with protocols and full of duplication. This is not too high a price for big companies, because their software is probably going to be bloated and full of duplication anyway.
+ Object-oriented programming generates a lot of what looks like work. Back in the days of fanfold, there was a type of programmer who would only put five or ten lines of code on a page, preceded by twenty lines of elaborately formatted comments. Object-oriented programming is like crack for these people: it lets you incorporate all this scaffolding right into your source code. Something that a Lisp hacker might handle by pushing a symbol onto a list becomes a whole file of classes and methods. So it is a good tool if you want to convince yourself, or someone else, that you are doing a lot of work.
+ If a language is itself an object-oriented program, it can be extended by users. Well, maybe. Or maybe you can do even better by offering the sub-concepts of object-oriented programming a la carte. Overloading, for example, is not intrinsically tied to classes. We'll see.
+ Object-oriented abstractions map neatly onto the domains of certain specific kinds of programs, like simulations and CAD systems.
I personally have never needed object-oriented abstractions. Common Lisp has an enormously powerful object system and I've never used it once. I've done a lot of things (e.g. making hash tables full of closures) that would have required object-oriented techniques to do in wimpier languages, but I have never had to use CLOS.
Maybe I'm just stupid, or have worked on some limited subset of applications. There is a danger in designing a language based on one's own experience of programming. But it seems more dangerous to put stuff in that you've never needed because it's thought to be a good idea.
== <NAME>es Response
_ (<NAME> had a really interesting response to Why Arc isn't Especially Object-Oriented, which he has allowed me to reproduce here.)_
Here is an a la carte menu of features or properties that are related to these terms; I have heard OO defined to be many different subsets of this list.
+ *Encapsulation* - the ability to syntactically hide the implementation of a type. E.g. in C or Pascal you always know whether something is a struct or an array, but in CLU and Java you can hide the difference.
+ *Protection* - the inability of the client of a type to detect its implementation. This guarantees that a behavior-preserving change to an implementation will not break its clients, and also makes sure that things like passwords don't leak out.
+ *Ad hoc polymorphism* - functions and data structures with parameters that can take on values of many different types.
+ *Parametric polymorphism* - functions and data structures that parameterize over arbitrary values (e.g. list of anything). ML and Lisp both have this. Java doesn't quite because of its non-Object types.
+ *Everything is an object* - all values are objects. True in Smalltalk (?) but not in Java (because of int and friends).
+ *All you can do is send a message (AYCDISAM) = Actors model* - there is no direct manipulation of objects, only communication with (or invocation of) them. The presence of fields in Java violates this.
+ *Specification inheritance = subtyping* - there are distinct types known to the language with the property that a value of one type is as good as a value of another for the purposes of type correctness. (E.g. Java interface inheritance.)
+ *Implementation inheritance/reuse* - having written one pile of code, a similar pile (e.g. a superset) can be generated in a controlled manner, i.e. the code doesn't have to be copied and edited. A limited and peculiar kind of abstraction. (E.g. Java class inheritance.)
+ *Sum-of-product-of-function pattern* - objects are (in effect) restricted to be functions that take as first argument a distinguished method key argument that is drawn from a finite set of simple names.
So OO is not a well defined concept. Some people (eg. Abelson and Sussman?) say Lisp is OO, by which they mean {3,4,5,7} (with the proviso that all types are in the programmers' heads). Java is supposed to be OO because of {1,2,3,7,8,9}. E is supposed to be more OO than Java because it has {1,2,3,4,5,7,9} and almost has 6; 8 (subclassing) is seen as antagonistic to E's goals and not necessary for OO.
The conventional Simula 67-like pattern of class and instance will get you {1,3,7,9}, and I think many people take this as a definition of OO.
Because OO is a moving target, OO zealots will choose some subset of this menu by whim and then use it to try to convince you that you are a loser.
Perhaps part of the confusion - and you say this in a different way in your little memo - is that the C/C++ folks see OO as a liberation from a world that has nothing resembling a first-class functions, while Lisp folks see OO as a prison since it limits their use of functions/objects to the style of (9.). In that case, the only way OO can be defended is in the same manner as any other game or discipline -- by arguing that by giving something up (e.g. the freedom to throw eggs at your neighbor's house) you gain something that you want (assurance that your neighbor won't put you in jail).
This is related to Lisp being oriented to the solitary hacker and discipline-imposing languages being oriented to social packs, another point you mention. In a pack you want to restrict everyone else's freedom as much as possible to reduce their ability to interfere with and take advantage of you, and the only way to do that is by either becoming chief (dangerous and unlikely) or by submitting to the same rules that they do. If you submit to rules, you then want the rules to be liberal so that you have a chance of doing most of what you want to do, but not so liberal that others nail you.
In such a pack-programming world, the language is a constitution or set of by-laws, and the interpreter/compiler/QA dept. acts in part as a rule checker/enforcer/police force. Co-programmers want to know: If I work with your code, will this help me or hurt me? Correctness is undecidable (and generally unenforceable), so managers go with whatever rule set (static type system, language restrictions, "lint" program, etc.) shows up at the door when the project starts.
#rect[Here are the pet definitions of terms used above:
- *Value* = something that can be passed to some function (abstraction). (I exclude exotic compile-time things like parameters to macros and to parameterized types and modules.)
- *Object* = a value that has function-like behavior, i.e. you can invoke a method on it or call it or send it a message or something like that. Some people define object more strictly along the lines of 9. above, while others (e.g. CLTL) are more liberal. This is what makes "everything is an object" a vacuous statement in the absence of clear definitions. In some languages the "call" is curried and the key-to-method mapping can sometimes be done at compile time. This technicality can cloud discussions of OO in C++ and related languages.
- *Function* = something that can be combined with particular parameter(s) to produce some result. Might or might not be the same as object depending on the language.
- *Type* = a description of the space of values over which a function is meaningfully parameterized. I include both types known to the language and types that exist in the programmer's mind or in documentation.]
|
|
https://github.com/dmtr-m/typst-assignments-template | https://raw.githubusercontent.com/dmtr-m/typst-assignments-template/main/template.typ | typst | #let problem_counter = counter("problem")
#let template(doc) = [
#set page(
paper: "a4",
margin: (
top: 1cm,
left: 1cm,
right: 1cm,
bottom: 1.75cm),
)
#set text(
font: "New Computer Modern",
lang: "ru",
)
#set par(
justify: true,
)
#set math.mat(
column-gap: .8em,
row-gap: .8em,
)
#show sym.lt.eq: sym.lt.eq.slant
#show sym.gt.eq: sym.gt.eq.slant
#doc
]
#let footer_header(title, author, course, due_time, group, body) = {
set page(
footer: locate(
loc => if (counter(page).at(loc).first()==1){
none
} else {
let page_number = counter(page).at(loc).first()
let total_pages = counter(page).final(loc).last()
line(length: 100%)
[Стр. #page_number из #total_pages]
[#h(1fr)#author | #course: #title]
}
),
)
body
}
#let title_page(title, author, course, due_time, group, body) = {
block(
height:20%,
fill:none
)
align(center, text(20pt)[*#course*])
align(center, text(17pt)[*#title*])
align(center, [Дедлайн: #due_time])
block(
height: 30%,
fill: none
)
align(center, text(16pt)[*#author*])
align(center, text(11pt)[*#group*])
pagebreak(weak: false)
body
}
#let problem(name: none, body) = {
if name != none {
name = " (" + name + ")"
}
[= Задание #problem_counter.step() #problem_counter.display()#name.]
block(
fill:rgb(240, 240, 255),
width: 100%,
inset:8pt,
radius: 4pt,
body
)
}
#let solution(no_header: false, body) = {
if not no_header {
[== Решение:]
} else {
none
}
line(length: 100%)
block(
fill: rgb(240, 255, 240),
width: 100%,
inset: 8pt,
radius: 4pt,
body
)
}
#let answer(type: "answer", no_header: false, body) = {
let title = none;
if type == "result" {
title = [Итого:]
} else if type == "answer" {
title = [Ответ:]
}
if not no_header {
[== #title]
line(length: 100%)
}
block(
fill: rgb(240, 240, 255),
width: 100%,
inset: 8pt,
radius: 4pt,
[#body]
)
}
#let intlim(l, r) = $cases(delim: "|", #h(0pt)^#r, #v(6pt), #h(0pt)_#l)$
#let pr = math.op("pr")
#let ort = math.op("ort")
#let vol = math.op("vol")
#let ord = math.op("ord")
#let Spec = math.op("Spec")
#let linspan(..args) = {
let input = args.pos()
math.angle.l
for i in range(input.len() - 1) {
input.at(i)
math.comma
math.thick
}
input.at(-1)
math.angle.r
}
|
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/flywheel/brainstorm.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator, codetastic
#import notebookinator: *
#import themes.radial.components: *
#import codetastic: qrcode
#show: create-body-entry.with(
title: "Brainstorm: Launcher Rebuild",
type: "brainstorm",
date: datetime(year: 2023, month: 11, day: 28),
author: "<NAME>",
witness: "<NAME>",
)
There are several different options we could choose from when it comes to
shooting mechanisms.
#grid(
columns: (1fr, 1fr),
gutter: 20pt,
[
== Continue with Catapult
A shooting mechanism that uses a fulcrum to launch projectiles. We are already
using a catapult, but it is not shooting far enough or consistently enough to be
reliable, so we would have to make many design changes.
#pro-con(
pros: [
- We already have a catapult in place
- Would be familiar
- The elevation mechanism is attached to the catapult and we would not have to
redesign that
],
cons: [
- We don’t understand what we would have to do to make the catapult work better.
- The catapult is tall
- The weight of the robot is distributed incorrectly because of the catapult,
making it unstable.
],
)
],
image("./catapult.svg"),
[
== Flywheel
A flywheel is a kinetic energy battery that spins to build up energy and then
transfers it to a projectile. This design consists of a single vertical spinning
wheel that we can drop the triballs directly on to. This design was inspired by
team 5203G's bot at the Haunted signature event #footnote[
#qrcode("https://www.youtube.com/watch?v=FwUk5V6V3U4", size: 2pt)
]
#pro-con(
pros: [
- The team has experience building flywheels from last year
- The mechanism is simpler than other options
- This design would not take much time to build and quality would not be lost
because of the deadline.
],
cons: [
- The distance launched can be unreliable
- The optimal parts that we need are not readily available
- The design may launch out of the field
],
)
],
image("./flywheel.svg", width: 70%),
[
== Puncher
A puncher provides linear force to the projectiles using elastic force.
#pro-con(
pros: [
- The design would most likely launch triballs across the field
- The design is small
- The design would be able to fit under the bar
],
cons: [
- Our team does not have experience building punchers
- The nature of punchers is such that it would be hard on the materials it is
build with, causing damage
- It would take a long time to build and we do not have a lot of time
],
)
],
image("./puncher.svg"),
)
|
https://github.com/0xPARC/0xparc-intro-book | https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/old-stuff/pcp.typ | typst | #import "preamble.typ":*
= The classical PCP protocol <pcp>
This entire chapter describes the first construction to PCP's.
You can think of it as "really long example of sum-check application".
Notational change: in this section, $q$ is a known prime,
but it is not on the order of $2^(256)$.
In fact, as discussed in the later @q-small-pcp,
we actually prefer $q$ to be pretty small.
== Pitch: How to grade papers without reading them
Imagine that Peggy has a long proof of some mathematical theorem, and Victor wants to verify it.
_A priori_, this would require Victor to actually read every line of the proof.
As anyone who has experience grading students knows, that's a whole lot of work.
A lazy grader might try to save time by only "spot checking"
a small number of lines of the proof.
However, it would be really easy to cheat such a grader:
all you have to do is make a single wrong step somewhere
and hope that particular step is not one of the ones examined by Victor.
A probabilistically checkable proof is a way to try to circumvent this issue.
It provides a protocol where Peggy can format her proof such that
Victor can get high-probability confidence of its confidence
by only checking $K$ bits of the proof at random, for some absolute constant $K$.
This result is one part of the _PCP theorem_ which is super famous.
The section hopes to give a high level summary of the ideas that go into the
protocol and convince you that the result is possible,
because at first glance it seems absurd that a single universal constant $K$
is going to be enough.
Our toy protocol uses the following parts:
- Sum-check from the previous chapter.
- Low-degree testing theorem, which we'll just state the result but not prove.
- Statement of the Quad-SAT problem,
which is the NP-complete problem which we'll be using for this post:
an instance of Quad-SAT is a bunch of quadratic equations in multiple variables
that one wants to find a solution to.
We'll staple everything to get a toy PCP protocol.
Finally, we'll give an improvement to it using error-correcting codes.
== Low-degree testing
In the general sum-check protocol we just described,
we have what looks like a pretty neat procedure,
but the elephant in the room is that we needed to make a call to a polynomial oracle.
Just one call, which we denoted $P(r_1, ..., r_n)$, but you need an oracle nonetheless.
When we do PCP, the eventual plan
is to replace both the oracle call and Peggy's answers
with a printed phone book.
The phone book contains, among other things, a big table mapping every $n$-tuple
$(r_1, ..., r_n) in FF_q^n$ to its value $P(r_1, ..., r_n)$
that Peggy mails to Victor via Fedex or whatever.
This is of course a lot of work for Peggy to print and mail this phone book.
However, Victor doesn't care about Peggy's shipping costs.
After all, it's not like he's _reading_ the phone book;
he's just checking the entries he needs.
(That's sort of the point of a phone book, right?)
But now there's a new issue.
How can we trust the entries of the phone book are legitimate?
After all, Peggy is the one putting it together.
If Peggy was trying to fool Victor, she could write whatever she wanted
("hey Victor, the value of $P$ is $42$ at every input")
and then just lie during the sum-check protocol.
After all, she knows Victor isn't actually going to read the whole phone book.
=== Goal of low-degree testing
The answer to this turns out be _low-degree testing_.
For example, in the case where $|HH| = 2$ we described earlier,
there is a promise that $P$ is supposed a multilinear polynomial.
For example, this means that
$ 5/8 P(100, r_2, ..., r_n) + 3/8 P(900, r_2, ..., r_n) = P(400, r_2, ..., r_n) $
should be true.
If Victor randomly samples equations like this, and they all check out,
he can be confident that $P$ is probably "mostly" a polynomial.
I say "mostly" because, well, there's no way to verify the whole phone book.
By definition, Victor is trying to avoid reading.
Imagine if Peggy makes a typo somewhere in the phone book ---
well, there's no way to notice it, because that entry will never see daylight.
However, Victor _also_ doesn't care about occasional typos in the phone book.
For his purposes, he just wants to check the phone book is 99% accurate,
since the sum-check protocol only needs to read a few entries anyhow.
=== The procedure --- the line-versus-point test
This is now a self-contained math problem, so I'll just write the statement
and not prove it (the proof is quite difficult).
Suppose $g colon FF_q^m -> FF_q$ is a function
and we want to see whether or not it's a polynomial of total degree at most $d$.
The procedure goes as follows.
The prover prints out two additional posters containing large tables $B_0$ and $B_1$,
whose contents are defined as follows:
- In the table $B_0$, for each point $arrow(b) in FF_q^m$,
the prover writes $g(arrow(b)) in FF_q$.
We denote the entry of the table by $B_0[arrow(b)]$.
- In the table $B_1$, for each line
$ ell = { arrow(b) + t arrow(m) | t in FF_q } $
the prover writes the restriction of $g$ to the line $ell$,
which is a single-variable polynomial of degree at most $d$ in $FF_q [t]$.
We denote the entry of the table by $B_1[ell]$.
The verifier then does the obvious thing:
pick a random point $arrow(b)$, a random line $ell$ through it,
and check the tables $B_0$ and $B_1$ are consistent.
This simple test turns out to be good enough, though proving this is hard
and requires a lot of math.
But the statement of the theorem is simple:
== Quad-SAT
As all NP-complete problems are equivalent, we can pick any one which is convenient.
Systems of linear equations don't make for good NP-complete problems,
but quadratic equations do, as we saw in @arith-intro.
So we are going to use Quad-SAT,
in which one has a bunch of variables over a finite field $FF_q$,
a bunch of polynomial equations in these variables of degree at most two,
and one wishes to find a satisfying assignment.
Let's say there are $N$ variables and $E$ equations, and $N$ and $E$ are both large.
Peggy has worked really hard and figured out a satisfying assignment
$ A colon {x_1, ..., x_N} -> FF_q $
and wants to convince Victor she has this $A$.
Victor really hates reading,
so Victor neither wants to read all $N$ values of the $x_i$
nor plug them into each of the $E$ equations.
He's fine receiving lots of stuff in the mail; he just doesn't want to read it.
#remark([$q$ is not too big])[
In earlier chapters, $q$ was usually a large prime like $q approx 2^255$.
This is actually not desirable here: Quad-SAT is already interesting even
when $q = 2$.
So in this chapter, large $q$ is a bug and not a feature.
For our protocol to work, we do need $q$ to be modestly large,
but its size will turn out to be around $(log N E)^O(1)$.
] <q-small-pcp>
== Description of the toy PCP protocol for Quad-SAT
We now have enough tools to describe a quad-SAT protocol that will break
the hearts of Fedex drivers everywhere.
In summary, the overview of this protocol is going to be the following:
- Peggy prints $q^E$ phone books, one phone book each for each linear combination
of the given Q-SAT equations.
We'll describe the details of the phone book contents later.
- Peggy additionally prints the two posters corresponding
to a low-degree polynomial extension of $A$
(we describe this exactly in the next section).
- Victor picks a random phone book and runs sum-check on it.
- Victor runs a low-degree test on the posters.
- Victor makes sure that the phone book value he read is consistent with the posters.
Let's dive in.
=== Setup
In sum-check, we saw we needed a bijection of $[N]$ into $HH^m$.
So let's fix this notation now (it is annoying, I'm sorry).
We'll let $HH$ be a set of size $|HH| := log (N)$
and set $m = log_(|HH|) N$.
This means we have a bijection from ${1, ..., N} -> HH^m$,
so we can rewrite the type-signature of $A$ to be
$ A colon HH^m -> FF_q. $
The contents of the phone books will take us a while to describe,
but we can actually describe the posters right now, and we'll do so.
Earlier when describing sum-check, we alluded to the following theorem,
but we'll state it explicitly now:
#theorem[
Suppose $phi colon HH^n -> FF_q$ is _any_ function.
Then there exists a unique polynomial $tilde(phi) colon FF_q^n -> FF_q$,
which agrees with $phi$ on the values of $HH^n$
and has degree at most $|HH|+1$ in each coordinate.
Moreover, this polynomial $tilde(phi)$ can be easily computed given the values of $phi$.
]
#proof[
Lagrange interpolation and induction on $m$.
]
We saw this earlier in the special case $HH={0,1}$ and $n=3$,
where we constructed the multilinear polynomial $5x y z+9x y+7z+8$ out of
eight initial values.
In any case, the posters are generated as follows.
Peggy takes her known assignment $A colon HH^m -> FF_q$
and extends it to a polynomial
$ tilde(A) in FF_q [T_1, ..., T_m] $
using the above theorem;
by abuse of notation, we'll also write $tilde(A) colon FF_q^m -> FF_q$.
She then prints the two posters we described earlier for the point-versus-line test.
=== Taking a random linear combination
The first step of the reduction is to try and generate just a single equation to check,
rather than have to check all of them.
There is a straightforward (but inefficient; we'll improve it later) way to do this:
take a _random_ linear combination of the equations
(there are $q^E$ possible combinations).
To be really verbose, if $cal(E)_1$, ..., $cal(E)_E$ were the equations,
Victor picks random weights $lambda_1$, ..., $lambda_E$ in $FF_q$
and takes the equation $lambda_1 cal(E)_1 + ... + lambda_E cal(E)_E$.
In fact, imagine the title on the cover of the phone book is
given by the weights $(lambda_1, ..., lambda_E) in FF_q^m$.
Since both parties know $cal(E)_1$, ..., $cal(E)_E$,
they agree on which equation is referenced by the weights.
We'll just check _one_ such random linear combination.
This is good enough because, in fact,
if an assignment of the variables fails even one of the $E$ equations,
it will fail the collated equation with probability $1 - 1/q$ --- exactly!
(To see this, suppose that equation $cal(E)_1$ was failed by the assignment $A$.
Then, for any fixed choice of $lambda_2$, ..., $lambda_E$, there is always
exactly one choice of $lambda_1$ which makes the collated equation true,
while the other $q-1$ all fail.)
To emphasize again: Peggy is printing $q^E$ phone books right now and we only use one.
Look, I'm sorry, okay?
=== Sum-checking the equation (or: how to print the phone book)
Let's zoom in on one linear combination to use sum-check on.
(In other words, pick only one of the phone books at random.)
Let's agree to describe the equation using the notation
$
c = sum_(arrow(i) in HH^m) sum_(arrow(j) in HH^m)
a_(arrow(i), arrow(j)) x_(arrow(i)) dot x_(arrow(j))
+ sum_(arrow(i) in HH^m) b_(arrow(i)) x_(arrow(i)).
$
In other words, we've changed notation so both the variables
and the coefficients are indexed by vectors in $HH^m$.
When we actually implement this protocol, the coefficients need to be actually computed:
they came out of $lambda_1 cal(E)_1 + ... + lambda_E cal(E)_E$.
(So for example, the value of $c$ above is given
by $lambda_1$ times the constant term of $cal(E)_1$,
plus $lambda_2$ times the constant term of $cal(E)_2$, etc.)
Our sum-check protocol that we talked about earlier
used a sequence $(r_1, ..., r_n) in {0,1}^n$.
For our purposes, we have these quadratic equations,
and so it'll be convenient for us if we alter the protocol to use pairs
$(arrow(i), arrow(j)) in FF_q^m times FF_q^m$ instead.
In other words, rather than $f(arrow(v))$
our variables will be indexed instead in the following way:
$
f &colon HH^m times HH^m -> FF_q \
f(arrow(i), arrow(j)) &:=
a_(arrow(i), arrow(j)) A(arrow(i)) A(arrow(j))
+ 1 / (|HH|^m) b_(arrow(i)) A(arrow(i)).
$
Hence Peggy is trying to convince Victor that
$ sum_(arrow(i) in FF_q^m)
sum_(arrow(j) in FF_q^m) f(arrow(i), arrow(j)) = c. $
In this modified sum-check protocol, Victor picks the indices two at a time.
So in the step where Victor picked $r_1$ in the previous step,
he instead picks $i_1$ and $j_1$ at once.
Then instead of picking an $r_2$, he picks a pair $(i_2, j_2)$ and so on.
Then, to run the protocol, the entries of the phone book are going to correspond to
$
P &in FF_q [T_1, ..., T_m, U_1, ..., U_m] \
P(T_1, ..., T_m, U_1, ..., U_m) &:=
tilde(a) (T_1, ..., T_m, U_1, ..., U_m) tilde(A)(T_1, ..., T_m)
tilde(A)(U_1, ..., U_m) \
&+ 1/(|HH|^m) tilde(b)(T_1, ..., T_m) tilde(A)(T_1, ..., T_m)
$
in place of what we called $P(x,y,z)$ in the sum-check section.
I want to stress now the tilde's above are actually hiding a lot of work.
Let's unpack it a bit: what does $tilde(a)$ mean?
After all, when you unwind this notational mess we wrote,
we realize that the $a$'s and $b$'s came out of the coefficients of the original
equations $cal(E)_k$.
The answer is that both Victor and Peggy have a lot of arithmetic to do.
Specifically, for Peggy,
when she's printing this phone book for $(lambda_1, ..., lambda_E)$,
needs to apply the extension result three times:
- Peggy views $a_(arrow(i), arrow(j))$ as a function $HH^(2m) -> FF_q$
and extends it to a polynomial using the above;
this lets us define
$tilde(a) in FF_q [T_1, ..., T_m, U_1, ..., U_m]$
as a _bona fide_ $2m$-variate polynomial.
- Peggy does the same for $tilde(b)_(arrow(i))$.
- Finally, Peggy does the same on $A colon HH^m -> FF_q$,
extending it to $tilde(A) in FF_q [T_1, ..., T_m]$.
(However, this step is the same across all the phone books, so it only happens once.)
Victor has to do the same work for $a_(arrow(i), arrow(j))$ and $b_(arrow(i))$.
Victor can do this, because he picked the $lambda$'s,
as he computed the coefficients of his linear combination too.
But Victor does _not_ do the last step of computing $tilde(A)$:
for that, he just refers to the poster Peggy gave him,
which conveniently happens to have a table of values of $tilde(A)$.
Now we can actually finally describe the full contents of the phone book.
It's not simply a table of values of $P$!
We saw in the sum-check protocol that we needed a lot of intermediate steps too
(like the $23T+46$, $161U+23$, $112V+197$).
So the contents of this phone book include, for every index $k$,
every single possible result that Victor would need to run sum-check at the $k$th step.
That is, the $k$th part of this phone book are a big directory where,
for each possible choice of indices $(i_1, ..., i_(k-1), j_1, ..., j_(k-1))$,
Peggy has printed the two-variable polynomial in $FF_q [T,U]$ that arises from sum-check.
(There are two variables rather than one now,
because $(i_k, j_k)$ are selected in pairs.)
This gives Victor a non-interactive way to run sum-check.
Rather than ask Peggy, consult the already printed phone book.
Inefficient? Yes. Works? Also yes.
=== Finishing up
Once Victor runs through the sum-check protocol,
at the end he has a random $(arrow(i), arrow(j))$ and received
the checked the phone book for $P(arrow(i), arrow(j))$.
Assuming it checks out, his other task is to
verify that the accompanying posters that Peggy sent ---
that is, the table of values $B_0$ and $B_2$ associated to $tilde(A)$ ---
look like they mostly come from a low-degree polynomial.
Unlike the sum-check step where we needed to hack the earlier procedure,
this step is a direct application of line-versus-point test, without modification.
Up until now the phone book and posters haven't interacted.
So Victor has to do one more check:
he makes sure that the value of $P(arrow(i), arrow(j))$ he got from the phone book
in fact matches the value corresponding to the poster $B_0$.
In other words, he does the arduous task of computing the extensions
$tilde(a)$ and $tilde(b)$, and finally verifies that
$
P(arrow(i), arrow(j)) :=
tilde(a)(arrow(i), arrow(j)) B_0[arrow(i)] B_0[arrow(j)]
+ 1/(|HH|^m) tilde(b)(arrow(i)) B_0[arrow(i)]
$
is actually true.
== Reasons to not be excited by this protocol
The previous section describes a long procedure that has a PCP flavor,
but it suffers from several issues (which is why we call it a toy example).
- *Amount of reading*:
The amount of reading on Victor's part is not $O(1)$ like we promised.
The low-degree testing step with the posters used $O(1)$ entries,
but the sum-check required reading roughly
$ O(|HH|^2) dot (m+O(1)) approx (log N)^3 / (log log N) $
entries from the phone book.
The PCP theorem promises we can get that down to $O(1)$,
but that's beyond this post's scope.
- *Length of proof*:
The procedure above involved mailing $q^E$ phone books,
which is what we in the business call either "unacceptably inefficient"
or "fucking terrible", depending on whether you're in polite company or not.
The next section will show how to get this down to $q E N$ if $q$ is large enough.
For context, in this protocol one wants a reasonably small prime $q$
which is about polynomial in $log(E N)$.
After all, Quad-SAT is already an NP-complete problem for $q=2$.
(In contrast, in other unrelated more modern ecosystems,
the prime $q$ often instead denotes a fixed large prime $q approx 2^256$.)
- *Time complexity*:
Even though Victor doesn't read much,
Peggy and Victor both do quite a bit of computation.
For example,
- Victor has to compute $tilde(a)_(arrow(i), arrow(j))$ for his one phone book.
- Peggy needs to do it for _every_ phone book.
- One other weird thing about this result is that,
even though Victor has to read only a small part of Peggy's proof,
he still has to read the entire _problem statement_,
that is, the entire system of equations from the original Quad-SAT.
This can feel strange because for Quad-SAT,
the problem statement is of similar length to the satisfying assignment!
#todo[some comments from Telegram here]
== Reducing the number of phone books --- error correcting codes
We saw that we can combine all the $E$ equations from Quad-SAT into a single one
by taking a random linear combination.
Our goal is to improve this by taking a "random-looking" combination
that still has the same property an assignment failing even one of the $E$ equations
is going to fail the collated equation with probability close to $1$.
It turns out there is actually a well-developed theory of how to take
the "random-looking" linear combination,
and it comes from the study of _error-correcting codes_.
We will use this to show that if $q >= 4(log (E N))^2$ is large enough,
one can do this with only $q dot E N$ combinations.
That's much better than the $q^E$ we had before.
=== (Optional) A hint of the idea: polynomial combinations
Rather than simply doing a random linear combination,
one could imagine considering the following $100 E$ combinations
$ k^1 cal(E)_1 + k^2 cal(E)_2 + ... + k^E cal(E)_E
" for " k = 1, 2, ..., 100 E. $
If any of the equations $cal(E)_i$ are wrong,
then we can view this as a degree $E$ polynomial in $k$,
and hence it will have at most $E$ roots.
Since we have $100 E$ combinations,
that means at least 99% of the combinations will fail.
So why don't we just do that?
Well, the issue is that we are working over $FF_q$.
And this argument only works if $q >= 100 E$, which is too big.
=== Definition of error-correcting codes
An *error-correcting code* is a bunch of codewords
with the property that any two differ in "many" places.
An example is the following set of sixteen bit-strings of length $7$:
$
C = {
& 0000000, 1101000, 0110100, 0011010, \
& 0001101, 1000110, 0100011, 1010001, \
& 0010111, 1001011, 1100101, 1110010 \
& 0111001, 1011100, 0101110, 1111111 } subset.eq FF_2^7
$
which has the nice property that any two of the codewords in it differ in at least $3$ bits.
This particular $C$ also enjoys the nice property that it's actually
a vector subspace of $FF_2^7$ (i.e. it is closed under addition).
In practice, all the examples we consider will be subspaces,
and we call them *linear error-correcting codes* to reflect this.
When designing an error-correcting code, broadly your goal is to make sure the
minimum distance of the code is as large as possible,
while still trying to squeeze in as many codewords as possible.
The notations used for this are:
- Usually we let $q$ denote the alphabet size and $n$ the block length
(the length of the codewords),
so the codewords live in the set of $q^n$ possible length $n$ strings.
- The *relative distance* is defined as the minimum Hamming distance divided by $n$;
Higher relative distance is better (more error corrections).
- The *rate* is the $log_(q^n)("num codewords")$.
Higher rates are better (more densely packed codewords).
So the example $C$ has relative distance $3/7$,
and rate $log_(2^7)(16) = 4/7$.
=== Examples of error-correcting codes
#todo[Hadamard, ...]
=== Composition
#todo[define this]
=== Recipe
Compose the Reed-Solomon codes
$
C_1 &= "RS"_(d=E,q=E N) \
C_2 &= "RS"_(d=log(E N),q).
$
This gives a linear code corresponding to an $s times m$ matrix $M$,
where $s := q dot E N$, which has relative distance at least $1 - 1/sqrt(q)$.
The rows of this matrix (just the rows, not their row span)
then correspond to the desired linear combinations.
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-0780.typ | typst | Apache License 2.0 | #let data = (
("THAANA LETTER HAA", "Lo", 0),
("THAANA LETTER SHAVIYANI", "Lo", 0),
("THAANA LETTER NOONU", "Lo", 0),
("THAANA LETTER RAA", "Lo", 0),
("THAANA LETTER BAA", "Lo", 0),
("THAANA LETTER LHAVIYANI", "Lo", 0),
("THAANA LETTER KAAFU", "Lo", 0),
("THAANA LETTER ALIFU", "Lo", 0),
("THAANA LETTER VAAVU", "Lo", 0),
("THAANA LETTER MEEMU", "Lo", 0),
("THAANA LETTER FAAFU", "Lo", 0),
("THAANA LETTER DHAALU", "Lo", 0),
("THAANA LETTER THAA", "Lo", 0),
("THAANA LETTER LAAMU", "Lo", 0),
("THAANA LETTER GAAFU", "Lo", 0),
("THAANA LETTER GNAVIYANI", "Lo", 0),
("THAANA LETTER SEENU", "Lo", 0),
("THAANA LETTER DAVIYANI", "Lo", 0),
("THAANA LETTER ZAVIYANI", "Lo", 0),
("THAANA LETTER TAVIYANI", "Lo", 0),
("THAANA LETTER YAA", "Lo", 0),
("THAANA LETTER PAVIYANI", "Lo", 0),
("THAANA LETTER JAVIYANI", "Lo", 0),
("THAANA LETTER CHAVIYANI", "Lo", 0),
("THAANA LETTER TTAA", "Lo", 0),
("THAANA LETTER HHAA", "Lo", 0),
("THAANA LETTER KHAA", "Lo", 0),
("THAANA LETTER THAALU", "Lo", 0),
("THAANA LETTER ZAA", "Lo", 0),
("THAANA LETTER SHEENU", "Lo", 0),
("THAANA LETTER SAADHU", "Lo", 0),
("THAANA LETTER DAADHU", "Lo", 0),
("THAANA LETTER TO", "Lo", 0),
("THAANA LETTER ZO", "Lo", 0),
("THAANA LETTER AINU", "Lo", 0),
("THAANA LETTER GHAINU", "Lo", 0),
("THAANA LETTER QAAFU", "Lo", 0),
("THAANA LETTER WAAVU", "Lo", 0),
("THAANA ABAFILI", "Mn", 0),
("THAANA AABAAFILI", "Mn", 0),
("THAANA IBIFILI", "Mn", 0),
("THAANA EEBEEFILI", "Mn", 0),
("THAANA UBUFILI", "Mn", 0),
("THAANA OOBOOFILI", "Mn", 0),
("THAANA EBEFILI", "Mn", 0),
("THAANA EYBEYFILI", "Mn", 0),
("THAANA OBOFILI", "Mn", 0),
("THAANA OABOAFILI", "Mn", 0),
("THAANA SUKUN", "Mn", 0),
("THAANA LETTER NAA", "Lo", 0),
)
|
https://github.com/chrischriscris/Tareas-CI5651-EM2024 | https://raw.githubusercontent.com/chrischriscris/Tareas-CI5651-EM2024/main/tarea05/src/main.typ | typst | #import "@preview/tablex:0.0.8": tablex, cellx, hlinex, vlinex
#import "template.typ": conf, question, pseudocode, GITFRONT_REPO
#show: doc => conf("Tarea 5: Grafos", doc)
#question[
// Pregunta 1
Considere la concatenación de su nombre con su apellido, llevado todo a
minúscula y eliminando todos los caracteres repetidos, menos la primera vez
que ocurran. Si su nombre es `<NAME>`, entonces debe considerar la
cadena `fulanomeg`.
Se desea que:
#enum(numbering: "(a)")[
Construya un árbol binario de búsqueda considerando los caracteres en el
orden en que aparecen (puede suponer que el orden es lexicográfico).
][
Realice un etiquetado en pre-order del árbol resultante.
][
Realice un recorrido de Euler sobre el árbol resultante.
][
Muestre el cálculo del ancestro común más bajo entre los dos últimos caracteres
de su apellido, usando el método de precondicionamiento visto en clase.
]
Para el ejemplo de `fulanomeg`, debe ver el ancestro común más bajo entre `e` y
`g`.
][
En este caso, la cadena a considerar es `christopegmz`. En la @arbol se
puede ver el árbol binario resultante, con el etiquetado en pre-order a la
izquierda de cada nodo y el etiquetado por niveles a la derecha, necesario para
el recorrido de Euler.
#figure(caption: [Árbol binario para `christopegmz`])[
#image("img/arbol.svg", width: 250pt)
]<arbol> \
Luego, el recorrido de Euler tomando en cuenta dichas etiquetas será:
#align(center)[
#tablex(
columns: (auto, ) * 23,
[1], [2], [3], [5], [3], [2], [4], [6], [8], cellx(fill: rgb("b1dff9"))[10],
[8], [11], [8], [6], cellx(fill: rgb("f29898"))[4], [7], [9],
cellx(fill: rgb("b1dff9"))[12], [9], [7], [4], [2], [1]
)
] \
Y la tabla resultante del precondicionamiento es:
#align(center)[
#tablex(
columns: (auto, ) * 13,
align: (center),
[Nodo], [1], [2], [3], [4], [5], [6], [7], [8], [9],
cellx(fill: rgb("b1dff9"))[10], [11], cellx(fill: rgb("b1dff9"))[12],
[Primera etiqueta], [0], [1], [2], [6], [3], [7], [15], [8], [16],
cellx(fill: rgb("b1dff9"))[9], [11], cellx(fill: rgb("b1dff9"))[17]
)
] \
Como se puede concluir con la tabla y el recorrido de Euler, y como se indica
con los colores de las celdas, la primera aparición de `m` (nodo 10) es en la
posición 9 y la primera aparición de `z` (nodo 12) es en la posición 17, y la
etiqueta más pequeña que se puede encontrar en el recoorrido de Euler en el
rango $[9..17]$ del arreglo es 4, que corresponde a la etiqueta de `r`.
Se concluye entonces que el ancestro común más bajo entre `m` y `z` es `r`, y
podemos corroborar que el resultado es correcto con la @arbol.
][
// Pregunta 2
Sea un conjunto $C$ de $n$ números enteros positivos distintos. ¿Cuál es la
menor cantidad de números que debe eliminarse de $C$ de tal forma que no existan
$x, y in C$ tal que $x + y$ sea un número primo?
Diseñe un algoritmo que pueda responder esta consulta en tiempo $O(n^2 sqrt(n))$.
A efectos de esta pregunta, puede suponer que consultar si un número es primo es
$O(1)$.
_Pista: El teorema de *König* puede ser de utilidad._
][
Veamos, para resolver este problema, comencemos construyendo un grafo
$ G_C = (C, E) \ E = { (x, y) | x, y in C, x + y "es primo" } $ es decir,
un grafo donde los vértices son los elementos de $C$ y hay una arista entre cada
par de vértices cuya suma sea un número primo.
Luego, lo que buscamos es \"romper\" todas estas aristas, es decir, remover para
cada una uno de sus extremos, de forma que no queden vértices conectados.
Queremos además remover la menor cantidad de vértices posible, por lo que
buscamos la cardinalidad de un cubrimiento mínimo $M$ de $G_C$.
Notemos que $G_C$ es un grafo bipartito, ya que podemos particionar los vértices
en pares e impares, porque la suma de dos números con la misma paridad es par,
por lo que toda arista tendrá un extremo par y otro impar.
Así, sabemos por el _teorema de *König*_ que para $G_C$ el número de vértices
en un cubrimiento mínimo es igual al número de aristas en un emparejamiento
máximo, por lo que podemos resolver el problema hayando la cardinalidad de un
emparejamiento máximo en $G_C$ con el algoritmo de _Hopcroft-Karp_. Un
pseudocódigo para resolver el problema sería:
#pseudocode[
```python
def no_suma_primo(C: Conjunto[Entero]) -> Entero:
E = {}
P = {}
I = {}
r = 0
for i in C:
if i == 1:
r = 1
continue
if es_par(i):
P.añadir(i)
else:
I.añadir(i)
for p in P:
for i in I:
if es_primo(p + i):
E.añadir((p, i))
G = {P U I, E}
M = hopcroft_karp(G, P, I)
return tamaño(M) + r
```
]
Un caso especial a tener en cuenta es que el 2 es el único número primo par, por
lo que si $1 in C$, este se excluye del grafo $G_C$ a construir y se suma 1 al
resultado, ya que la suma de 1 consigo mismo es primo, caso que no se
consideraría al hallar cubrimiento mínimo de $G_C$.
El número de aristas de $G_C$ está acotado por $n^2$, y el algoritmo de
_Hopcroft-Karp_ tiene una complejidad de $O(|E| sqrt(|V|))$, por lo que el
algoritmo planteado tiene una complejidad de $O(n^2 sqrt(n))$ (suponiendo que
la verificación de primalidad es $O(1)$), ya que la construcción de $G_C$ es
$O(n^2)$.
Una implementación de este algoritmo en PHP se puede encontrar
#link(GITFRONT_REPO + "tarea5/ej2/")[aquí].
][
// Pregunta 3
Considere un modificación del clásico juego de la vieja, en donde:
- El primer jugador juega con — y el segundo juega con |.
- Cada casilla puede tener alguno de estos símbolos, ninguno o ambos (en cuyo
caso se forma un +).
- En cada turno, el jugador no puede jugar en la misma casilla que el jugador
anterior.
- Gana aquel jugador que logre formar tres + en una misma fila, columna o
diagonal.
Por ejemplo, la siguiente es una configuración ganadora (donde la última jugada
fue de |):
#align(center)[
#tablex(
stroke: 0.5pt,
columns: (auto, auto, auto),
align: (center, center, center),
hlinex(stroke: rgb("#FFFFFF"), start: 0, end: 2),
vlinex(stroke: rgb("#FFFFFF"), start: 0, end: 2),
[+], [+] , [+] , vlinex(stroke: rgb("#FFFFFF"), start: 0, end: 2),
[|], [—] , [+] ,
[—], [ ] , [|] ,
hlinex(stroke: rgb("#FFFFFF"), start: 0, end: 2),
)]
Diga si hay una estrategia ganadora para alguno de los jugadores involucrados.
Para resolver este problema, utilice el método *minimax*.
][
Para encontrar si hay alguna estrategia ganadora, modelamos primero los estados
del juego para poder aplicar el método *minimax*.
De esta forma, definimos un estado como un arreglo de 9 elementos, donde cada
elemento puede es un número entre 0 y 4, siendo 0 si la casilla está vacía, 1 si
tiene un —, 2 si tiene un | y 3 si tiene un +.
Codificar los estados de esta manera presenta la ventaja de que para jugar en una
casilla basta sumar el valor del símbolo a la casilla correspondiente.
Luego, para saber si un estado es ganador, basta con sumar los valores de las
casillas en las filas, columnas y diagonales, y verificar si alguna suma es 9,
lo que indicaría que un jugador ha ganado.
Con esto, saber si un estado es ganador consiste simplemente en hacer ejecutar
un agente minimax sobre el árbol de estados del juego, partiendo del tablero
vacío, y ver si el agente puede forzar una victoria o termina perdiendo. Se
representa el estado ganador con un 1, el perdedor con un -1.
Una implementación de este algoritmo en Kotlin se puede encontrar
#link(GITFRONT_REPO + "tarea5/ej3/")[aquí].
Con dicha implementación se pudo verificar que el valor resultante de la raíz
del árbol minimax es -1, lo que indica que si ambos jugadores juegan de forma
óptima, el primer jugador siempre terminará perdiendo, o lo que es lo mismo, el
segundo jugador tiene una estrategia ganadora.
]
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/list-marker_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test that bare hyphen doesn't lead to cycles and crashes.
#set list(marker: [-])
- Bare hyphen is
- a bad marker
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/tracking-spacing_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test that tracking doesn't disrupt mark placement.
#set text(font: ("PT Sans", "Noto Serif Hebrew"))
#set text(tracking: 0.3em)
טֶקסט
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/markup/term-list.typ | typst | Apache License 2.0 | / a
: b
/ #text(red, "a"): b
/ a: b
|
https://github.com/GartmannPit/Praxisprojekt-II | https://raw.githubusercontent.com/GartmannPit/Praxisprojekt-II/main/Praxisprojekt%20II/PVA-Templates-typst-pva-2.0/paper.typ | typst | #import "template/conf.typ": style
#import "template/cover.typ": createCover
#import "template/contents.typ": createTableofContent
#import "template/acronymsList.typ": createListofAcronyms
#import "template/figuresList.typ": createListofFigures
#import "template/tablesList.typ": createListofTables
#import "abstract.typ": showAbstract
#import "template/bib.typ": createBibliography
#import "appendix.typ": showAppendix
// --- Sets global style and page settings ---
// Edit template/conf.typ to change a GLOBAL setting (e.g. font), some are variable set "locally" for special pages/ chapters
#show: style
#set document(
author: "<NAME>", // put your name here for pdf document properties
title: "The Title" // and the pdf title here
)
// --- Cover Page: Please submit values in the same data type ---
// Edit template/cover.typ for changes on base design/ layout/ language
#par[
#show: doc => createCover(
title: "Test of Typst Template",
university: [Your university],
seminar: [Your seminar],
study: [Your subject of study],
examiner: [Your professor],
author: "<NAME>",
dateofBirth: [01.01.2001],
semesterCount: [1],
matriculationNumber: [123456],
address: [Teststraße 1 \ 12345 Teststadt],
email: "<EMAIL>",
date: "01. April 2099",
cooperation: [Your Company]
)
]
#pagebreak()
// --- Table of Content ---
// Edit template/contents.typ to change anything
#par[
#set page(numbering: "I")
#counter(page).update(1)
#show: doc => createTableofContent()
]
#pagebreak()
// --- List of acronyms ---
// Edit template/acronymsList.typ to change design/ present options
// NOTE: you need to add all acronyms manually in the acronyms.typ file, but NO design options there (including citeStyle, this is set in global settings)
#par[
#set page(numbering: "I")
#show: doc => createListofAcronyms()
]
#pagebreak()
// --- List of figures --- (Comment all out if there are none)
// Edit template/figuresList.typ to change design/ present options
// NOTE: in order to get all your images in you need to set them up as figure-image, please see the README for more information and some nice features coming with it
#par[
#set page(numbering: "I")
#show: doc => createListofFigures()
]
#pagebreak()
// --- List of tables --- (Comment all out if there are none)
// Edit template/tablesList.typ to change design/ present options
// NOTE: in order to get all your tables in you need to set them as figure-table, please see the README for more information and some nice features coming with it
#par[
#set page(numbering: "I")
#show: doc => createListofTables()
]
// --- Abstract ---
// Write your abstract in abstract.typ
#par[
#set page(numbering: "I")
#set heading(numbering: none)
#show: showAbstract()
]
#pagebreak()
// --- Main Part ---
// Write your main part in main.typ
// Here apply the global conf settings
#counter(page).update(1)
#par[
#include "main.typ" // should you have files per chapter include them here
]
#pagebreak()
// --- Bibliography ---
// Edit bib.typ to edit bibliography settings including paths to .bib and .yml source files
#par[
#set heading(numbering: none)
#show: doc => createBibliography()
]
#pagebreak()
// --- Appendix ---
// Edit appendix.typ for content
#par[
#set page(numbering: "I")
#counter(page).update(1)
#set heading(numbering: none)
#show: showAppendix()
]
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.