repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/mem-courses/discrete-mathmatics | https://raw.githubusercontent.com/mem-courses/discrete-mathmatics/main/homework/week11.typ | typst | MIT License | #import "../template.typ": *
#import "../functions.typ": *
#show: project.with(
course: "Discrete Mathmatics",
course_fullname: "Discrete Mathematics and Application",
course_code: "211B0010",
title: "Homework #11: Equivalence Relations",
authors: (
(
name: "<NAME>",
email: "<EMAIL>",
id: "A10",
),
),
semester: "Spring-Summer 2024",
date: "May 13, 2024",
)
= 9.5 Equivalence Relations
#hw("3")[
Which of these relations on the set of all functions from $ZZ$ to $ZZ$ are equivalence relations? Determine the properties of an equivalence relation that the others lack.
#parts(
a: [${(f, g) | f(1) = g(1)}$],
b: [${(f, g) | f(0) = g(0) or f(1) = g(1)}$],
c: [${(f, g) | f(x) − g(x) = 1 "for all" x ∈ Z}$],
d: [${(f, g) | "for some" C ∈ Z, "for all" x ∈ Z, f(x) − g(x) = C}$],
e: [${(f, g) | f(0) = g(1) and f(1) = g(0)}$],
)
][#parts(
a: [Equivalent.],
b: [
Not equivalent.
- Suppose that $f(0) = g(0), f(1) = h(1)$ but $g(0) != h(0)$ and $g(1) != h(1)$. Then $(g,f) in R$ and $(f,h) in R$ but $(g,h) in.not R$. This implies that the transitive property is not satisfied.
],
c: [
Not equivalent.
- Suppose that $f$ is a function from $ZZ$ to $ZZ$ with $(f,f) in R$. Then $f(x)-f(x) = 1$ should hold according to the definition of $R$. However, there is clearly a contradiction since $f(x) -f(x)$ is always zero. Therefore, the reflexive property is not satisfied.
- Suppose that $(f,g) in R$, then $(g,f) in R$ holds according to the reflexive property of an equivalence relation. This implies that $f(x) - g(x) = 1 and g(x) - f(x) = 1$. But this is clearly a contradiction, as $f(x) - g(x)$ should be equal to $-(g(x) - f(x))$. Therefore, the symmetric property is not satisfied.
- Suppose that $(f,g) in R$ and $(g,h) in R$. Then we have $f(x)-g(x)=1$ and $g(x)-h(x)=1$. This implies that $f(x)-h(x)=2$, which means $(f,h) in.not R$. Therefore, the transitive property is not satisfied.
],
d: [
Not equivalent.
- Suppose $(f,g) in R$ holds for a non-zero $C$. Then, similiar to the proof in (c), we can argue that $R$ does not satisfy the symmetric property nor the transitive property.
#correction[
Equivalent.
Note that this is "for some" $C$ (similar to existence), not for a specific $C$.
]
],
e: [
Not equivalent.
- Suppose $(f,g) in R$ and $(f,h) in R$. Then we have $f(0)=g(1)=h(1) and f(1) = g(0) = h(0)$. If $f(0) != f(1)$ (in general), then $g(0) != h(1) and g(1) != h(0)$. That is $(g,h) in.not R$. Therefore, the transitive property is not satisfied.
],
)]
#hw("10")[
Suppose that $A$ is a nonempty set and $R$ is an equivalence relation on $A$. Show that there is a function $f$ with $A$ as its domain such that $(x, y) in R$ if and only if $f(x) = f(y)$.
][
Construct the function $f$ in this way: divied the set $A$ into several equivalence classes. Assign an unique value $y$ for each equivalence class, for each element $x$ in this equivalence class, let $f(x)=y$. This implies that for every element $x$ in each equivalence class, $f(x)=f(y)$ if and only if element $y$ is in the same equivalence class. Therefore, the function $f$ we constructed satisfies the requirements of the problem.
]
#hw("16")[
Let $R$ be the relation on the set of ordered pairs of positive integers such that $((a, b), (c, d)) in R$ if and only if $a d = b c$. Show that $R$ is an equivalence relation
][
- Reflexive: For any ordered pair $(a,b) in A$, we have $a b = b a$, which implies that $((a,b),(a,b)) in R$.
- Symmetric: For any ordered pair $((a,b),(c,d)) in R$, we have $a d = b c$. This implies that $c b = d a$, so $((c,d),(a,b)) in R$.
- transitive: For any ordered pair $((a,b),(c,d)) in R$ and $((c,d),(e,f)) in R$, we have $a d = b c$ and $c f = d e$. So $(a d)(c f) = (b c)(d e)$. As all integers are positive, we have $a f = b e$. That is $((a,b),(e,f)) in R$.
]
#hw("36(b)")[
What is the congruence class $[4]_m$ when $m$ is 3?
][
The answer is $S = {x | x equiv 4 space (mod space 3)} = {3k+1 | k in ZZ} = {dots.c,-5,-2,1,4,7,dots.c}$.
]
#hw("39")[
(_Exercise 15_: Let $R$ be the relation on the set of ordered pairs of positive integers such that $((a, b), (c, d)) in R$ if and only if $a + d = b + c$. Show that $R$ is an equivalence relation.)
#parts(
a: [What is the equivalence class of (1, 2) with respect to the equivalence relation in _Exercise 15_?],
b: [
Give an interpretation of the equivalence classes for the equivalence relation $R$ in Exercise 15.
_Hint_: Look at the difference $a − b$ corresponding to $(a, b)$.
],
)
][#parts(
a: [
$a+d = b + c <==> a - b = c - d$. So the equivalence class of $(1,2)$ is $[(1,2)]_R = {(k,k+1) | k in ZZ^+}$.
],
b: [
According to the conclusion obtained earlier, for an equivalence class, the value of $a-b$ should keep the same.
],
)]
#hw("41")[
Which of these collections of subsets are partitions of {1, 2, 3, 4, 5, 6}?
#parts(
columns: 2,
a: [${1, 2}, {2, 3, 4}, {4, 5, 6}$],
b: [${1}, {2, 3, 6}, {4}, {5}$],
c: [${2, 4, 6}, {1, 3, 5}$],
d: [${1, 4, 5}, {2, 6}$],
)
][
#parts(
columns: 2,
a: [False. As 2 and 4 appears in two subsets.],
b: [True.],
c: [True.],
d: [False. As the union of all subsets is not the original set.],
)
] |
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/经济学原理/hw/hw10.typ | typst | #import "../../template.typ": *
#show: note.with(
title: "作业8",
author: "YHTQ ",
date: none,
logo: none,
withOutlined: false,
withTitle: true
)
=
==
令 $Q_1 = Q_2$,得:
$
1000 - 5 P = 4 P - 80 => P = 120, Q = 400
$
总支出为:
$
P Q = 48000
$
生产者剩余为:
$
integral_(Q = 0)^400 (120 - P_1 (Q)) d Q = integral_(P = 20)^120 4 (120 - P) d P = 20000
$
消费者剩余为:
$
integral_(Q = 0)^400 (P_2 (Q) - 120) d Q = integral_(P = 120)^200 5(P - 120) d P = 16000
$
==
新的成交价格为:
$
300 = 1000 - 5P' => P' = 140
$
此时生产者剩余与消费者剩余的和为:
$
integral_(Q = 0)^300 (140 - P_1 (Q)) d Q + integral_(Q = 0)^300 (P_2 (Q) - 140) d Q = integral_(Q = 0)^300 (P_2 (Q) - P_1 (Q)) d Q = integral_(Q = 0)^300 (200 - 1/5 Q - (20 + 1/4 Q)) d Q = 33750
$
损失为:
$
36000 - 33750 = 2250
$
==
新的均衡价格满足:
$
1270 - 5 P = 4 P - 80 => P = 150, Q = 520
$
生产者剩余为:
$
integral_(Q = 0)^520 (150 - P_1 (Q)) d Q = integral_(P = 20)^150 4 (150 - P) d P = 33800
$
消费者剩余为:
$
integral_(Q = 0)^520 (P_2' (Q) - 150) d Q = integral_(P = 150)^254 5(P - 150) d P = 27040
$
==
最高价格 $P_m = 120$,市场成交数量 $Q = 400$
生产者剩余变为:
$
integral_(Q = 0)^400 (120 - P_1 (Q)) d Q = 20000
$
消费者剩余变为:
$
integral_(Q = 0)^400 (P_2' (Q) - 120) d Q = integral_(P = 174)^254 5(P - 120) d P = 37600
$
无谓损失为:
$
33800 + 27040 - 20000 - 37600 = 3240
$
=
==
当市场价格为 $P$ 时。为了满足边际成本等于边际收益,每个生产者的生产量 $q$ 将满足
$
P = q + 10 => q = P - 10
$
市场供给为:
$
q = cases(
100P - 1000 space P >= 10,
0 space P < 10
)
$
==
均衡价格满足:
$
100 P - 1000 = 1100 - 50 P => 150 P = 2100 => P = 14
$
成交量为 $Q = 400$\
生产者剩余为:
$
integral_(Q = 0)^400 (14 - P_1 (Q)) d Q = integral_(P = 10)^14 100 (14 - P) d P = 800
$
==
设新的均衡价格为 $P$,则应有:
$
100 (P - 3) - 1000 = 1100 - 50 P => P = 16
$
均衡数量为 $Q = 300$\
==
总计税收为 $300 * 3 = 900$,其中生产者承担 $(14-13)/3 = 1/3$,消费者承担 $2/3$
==
新的生产者剩余为:
$
integral_(Q = 0)^300 (13 - P_1 (Q)) d Q = integral_(P = 10)^13 100 (13 - P) d P = 450
$
总计损失为 $800 - 450 = 350$ |
|
https://github.com/Zeng-WCh/SYSU-Typst-Internship-report-template | https://raw.githubusercontent.com/Zeng-WCh/SYSU-Typst-Internship-report-template/main/usage.typ | typst | MIT License | #import "template.typ": *
#show: report.with(
title: "本科生实习报告书",
banner: "banner.png",
school: "摸鱼学院摸鱼专业",
grade: "xxxx 级 x 班",
name: "张三",
stu_id: "22223333",
company: "某某公司",
start_time: "2077 年 7 月 1 日",
end_time: "2077 年 8 月 31 日",
teacher: "李四",
year: "2077",
month: "12",
day: "25",
)
// Add your content here
1. `C++` 中 Hello World 的 114514 种写法
1.1 C With Class 风格
```cpp
#include <stdio.h>
int main() {
printf("Hello World!\n");
return 0;
}
```
1.2 C++ 风格
```cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!\n";
return 0;
}
```
1.3 面向对象风格
```cpp
#include <iostream>
using namespace std;
class HelloWorld {
private:
const char *str = "Hello World!";
public:
HelloWorld() {
cout << str << endl;
}
};
int main() {
HelloWorld hw;
return 0;
}
```
1.5 操作符重载风格
```cpp
#include <iostream>
#include <ostream>
using namespace std;
class HelloWorld {
private:
const char *str = "Hello World!";
public:
friend ostream &operator<<(ostream &os, const HelloWorld &hw);
};
ostream &operator<<(ostream &os, const HelloWorld &hw) {
os << hw.str;
return os;
}
int main() {
cout << HelloWorld() << endl;
}
```
1.6 操作符重载 (2)
```cpp
#include <iostream>
using namespace std;
class HelloWorld {
private:
const char *str = "Hello World!";
public:
operator int() {
cout << str << '\n';
return 0;
}
};
int main() {
return HelloWorld();
}
```
1.7 抽风风格
```cpp
#include <iostream>
using namespace std;
class HelloWorld {
private:
const char *str = "Hello World!";
public:
~HelloWorld() {
cout << str << endl;
}
};
HelloWorld hw;
int main() {
return 0;
}
```
1.8 仿 lambda 风格
```cpp
#include <iostream>
using namespace std;
class HelloWorld {
private:
const char *str = "Hello World!";
public:
int operator()() {
cout << str << endl;
return 0;
}
};
HelloWorld hw;
int a = hw();
int main() {
return a;
}
```
1.9 lambda 风格
```cpp
#include <iostream>
using namespace std;
auto f = []() -> int {
cout << "Hello World\n";
return 0;
};
int main() {
return f();
}
```
...
#lorem(2500)
|
https://github.com/MaxAtoms/T-705-ASDS | https://raw.githubusercontent.com/MaxAtoms/T-705-ASDS/main/content/week9.typ | typst | #import "../template.typ": example, exercise
#import "../boxes.typ": colorbox, definition
#import "../tags.typ": week, barron
#line(length: 100%)
#week("9")
== Confidence interval for the ratio of two population variances
#barron("9.5.5")
$ [ (s_X^2) / (s_Y^2 dot.op F_(alpha / 2) (n-1, m-1)), (s_X^2) / (s_Y^2 dot.op F_(1-alpha / 2) (n-1, m-1))] $
== F-test to compare two variances
#barron("9.5.6")
The null hypothesis about the ratio of two variances is
$H_0: sigma_X^2 = sigma_Y^2$ or $H_0: sigma_X^2 / sigma_Y^2 = 1$
The test statistic is:
$
F=(s_X^2\/s_Y^2)/(Theta_text("obs")) = s_X^2/s_Y^2
$
Under $H_0$ it equals:
$ F =(s_X^2\/sigma_X^2)/(s_Y^2\/sigma_Y^2) ~ F(n-m, m-1) $
The alternative hyp.
+ Right side: $ H_A: sigma_X^2/sigma_Y^2 > 1$: reject if $F_alpha < F_text("obs")$
+ Left side: $ H_A: sigma_X^2/sigma_Y^2 < 1$: reject if $F_(1-alpha) > F_text("obs")$
+ two-side: $ H_A: sigma_X^2/sigma_Y^2 eq.not 1$: reject if $F_(alpha/2) < F_text("obs")$ or $F_(1-alpha/2) > F_text("obs")$
#example(number: "9.44 & 9.49")[
Conversative investment:
2 funds, one is 10% higher volatility.\
Is one fund more risky than the other?
We are asked to test the hypothesis $H_0: sigma_x = sigma_y$ vs $H_A: sigma_x > sigma_y$.
Given the data collected over 30 days we measure $s_X / s_Y = 1.1$.
We can do an F-test:
$F_text("obs") = S_X^2 / S_Y^2 = (S_X/S_Y)^2 = 1.21$
Find the p-value of this right sided test
From table: $alpha=0.25$, $p=1.28$
We accept $H_0$. There is no evidence to support the claim that the fund is more risky.
]
Every statistical test has its assumptions. Our conclusions are only valid if the assumptions hold.
For F-tests:
1. Data are normally distributed $->$ not necessarily
2. Independent and identically distributed (iid) within each sample
3. Independence of the two samples
F-test is a robust test (i.e. mild departure from assumptions will not affect outcome).
#exercise("9.23")[
Anthony and Eric
$accent(A, macron)=85$
$S_A^2=162.8$
$n=m=6$
$accent(E, macron) = 80$
$S_E^2=10.4$
$alpha=0.05$
#enum(numbering: "a)",
enum.item[
1. $H_0: mu_A = mu_E$ vs $H_A: mu_A > mu_E$
To test this, we need to check if the population variances are equal.
#colorbox(title: "Side Step")[
1. $H_0: sigma_A^2 = sigma_E^2 text("vs") H_A: sigma_A^2 eq.not sigma_E^2 <=> H_0 = sigma_A^2 / sigma_E^2 = 1 text("vs") H_0 = sigma_A^2 / sigma_E^2 eq.not 1$
2. Find test stat.:
$F_text("obs") = S_A^2 / S_E^2 = 162.8 / 10.4 = 15.65$
3. From the table we get: p-Value is $p<0.005$
For $alpha/2 = 0.01$
$F_0.01 = 11$
$F_0.05 = 14.9$
$F_0.001 = 298$
We reject $H_0$, the variances are not equal.
]
2. Find the test stat.
$ t = (accent(A, macron) - accent(E, macron) - 0) / (sqrt(s_A^2 / n + s_E^2 / m)) = 0.931 $
3. Find p-Value
But first we need the d.f.
We use the satterthwait approximation (Eq. 9.12)
$ nu = (s_A^2 / n + s_E^2 / m)^2 / (s_A^4 / (n^2 (n-1)) + s_E^4 / (m^2 (m-1))) = 6 $
We use the t-dist with 6 d.f.
The critical value is $t_(alpha/2) = 2.447 > t$.
We accept $H_0$, A ist not a better student than E.
],
enum.item[
#enum(numbering: "i)",
enum.item[$ H_0: sigma_E^2 = sigma_A^2 text("vs") H_A: sigma_E^2 < sigma_A^2
<=> H_0: sigma_A^2 / sigma_E^2 = 1 text("vs") H_A: sigma_A^2 / sigma_E^2 > 1$],
enum.item[
$ F_text("obs") = s_A^2 / s_E^2 = 162.8 / 10.4 = 15.65 $],
enum.item[The p-Value is $0.001 < p < 0.005$]
)
We do reject, Eric is better than Anthony.
])
]
#pagebreak()
== Testing a family of distributions
#barron("10.1.2")
We can do a $chi^2$ goodness of fit test #underline("also") when we do not know the values of the parameters.
Given a sample of observations $X_1,dots,X_n~F$ where $F in frak(F)$, a family of distributions.
We test: $H_0: F in frak(F)$ vs $H_A: F in.not frak(F)$
Here $Theta$ is not given. We need to estimate it via the Method of Maximum Likelihood.
#definition[*Goodness of fit procedure*
1. Find ML estimator $accent(theta, hat)$ and consider the distribution $F(accent(Theta,hat))$
2. Partition the support of $F(accent(Theta, hat))$ into N bins.
$B_1,B_2,dots,B_N$ where $N in [5,8]$
3. Compute probability $p_k = P(X in B_k), k=1,dots,N$
4. Compute $text("obs")(k)$ for data, $text("exp")(k) = n dot.op p_k$
5. Calculate $chi^2$-test statistic and p-value
$text("d.f.") = N - 1 = d$ where d is the number of parameters
]
|
|
https://github.com/monaqa/typst-easytable | https://raw.githubusercontent.com/monaqa/typst-easytable/master/manual.typ | typst | MIT License | #import "@preview/tidy:0.2.0"
#import "src/lib.typ": easytable, elem
#import elem: *
#let example_result(body) = block(stroke: 0.5pt + luma(80%), inset: 10pt, breakable: false, body)
#let example(code, result) = grid(columns: 2, column-gutter: 5pt, {
set block(breakable: false)
code
}, example_result(result))
#set par(justify: true)
// #set text(font: "Noto Serif CJK JP")
#show heading: set text(font: "Noto Sans CJK JP")
#show heading: set pad(bottom: 2em)
#set heading(numbering: "1.")
#show raw.where(block: false): box.with(
fill: black.lighten(95%),
inset: (x: 2pt, y: 0pt),
outset: (x: 0pt, y: 2pt),
radius: 1.5pt,
)
#show raw.where(block: true, lang: "typst"): block.with(
width: 100%,
fill: black.lighten(95%),
inset: (x: 8pt, y: 6pt),
radius: (top-left: 6pt, bottom-right: 6pt, rest: 0pt),
)
#align(center)[
#text(size: 2em, [Typst-Easytable Package])
version: 0.1.0
#datetime.today().display()
]
#outline(title: "Outline", indent: 1em, depth: 3)
= Overview
`typst-easytable` is a simple package for writing tables in Typst.
== Goal of `typst-easytable`
- Concise, highly visible markup
- Some degree of flexibility, versatility
== Non-Goal of `typst-easytable`
- Features that are not needed for most applications
= Usage
```typst
#import "@preview/easytable:0.1.0": easytable, elem
```
== A Simple Table
Simple tables can be described simply.
#example[
```typst
#easytable({
elem.tr[How ][I ][want ]
elem.tr[a ][drink, ][alcoholic ]
elem.tr[of ][course,][after ]
elem.tr[the ][heavy ][lectures ]
elem.tr[involving][quantum][mechanics.]
})
```
][
#easytable({
elem.tr[How ][I ][want ]
elem.tr[a ][drink, ][alcoholic]
elem.tr[of ][course,][after ]
elem.tr[the ][heavy ][lectures ]
elem.tr[involving][quantum][mechanics.]
})
]
`elem.tr` is a function representing data element in the `elem` module.
To add a table header, use the `elem.th` function. It represents header element.
#example[
```typst
#easytable({
elem.th[Header 1 ][Header 2][Header 3 ]
elem.tr[How ][I ][want ]
elem.tr[a ][drink, ][alcoholic ]
elem.tr[of ][course, ][after ]
elem.tr[the ][heavy ][lectures ]
elem.tr[involving][quantum ][mechanics.]
})
```
][
#easytable({
elem.th[Header 1 ][Header 2][Header 3 ]
elem.tr[How ][I ][want ]
elem.tr[a ][drink, ][alcoholic ]
elem.tr[of ][course, ][after ]
elem.tr[the ][heavy ][lectures ]
elem.tr[involving][quantum ][mechanics.]
})
]
If you feel tedious to write `elem.*`, you can omit it by writing as follows:
```typst
// If you don't care having functions such as `th` and `tr` in global namespace,
// it is easiest to write the import statement here!
#import elem: *
#easytable({
// If you care, please state the following for each table.
// import elem: *
tr[How ][I ][want ]
tr[a ][drink, ][alcoholic ]
tr[of ][course,][after ]
tr[the ][heavy ][lectures ]
tr[involving][quantum][mechanics.]
})
```
We will omit `import elem: *` in examples hereafter.
The argument of `elem.tr` is variadic, i.e., you can easily create tables with any number of columns.
#example[
#set text(size: 0.9em)
```typst
#easytable({
vline(x: 1, stroke: 0.5pt)
cstyle(..(center,) * 7)
th[$*$][$e$][$r$][$r^2$][$s$][$r s$][$r^2s$]
tr[$e$][$e$][$r$][$r^2$][$s$][$r s$][$r^2s$]
tr[$r$][$r$][$r^2$][$e$][$r s$][$r^2s$][$s$]
tr[$r^2$][$r^2$][$e$][$r$][$r^2s$][$s$][$r s$]
tr[$s$][$s$][$r^2s$][$r s$][$e$][$r^2$][$r$]
tr[$r s$][$r s$][$s$][$r^2s$][$r$][$e$][$r^2$]
tr[$r^2s$][$r^2s$][$r s$][$s$][$r^2$][$r$][$e$]
})
```
][
#easytable({
vline(x: 1, stroke: 0.5pt)
cstyle(..(center,) * 7)
th[$*$][$e$][$r$][$r^2$][$s$][$r s$][$r^2s$]
tr[$e$][$e$][$r$][$r^2$][$s$][$r s$][$r^2s$]
tr[$r$][$r$][$r^2$][$e$][$r s$][$r^2s$][$s$]
tr[$r^2$][$r^2$][$e$][$r$][$r^2s$][$s$][$r s$]
tr[$s$][$s$][$r^2s$][$r s$][$e$][$r^2$][$r$]
tr[$r s$][$r s$][$s$][$r^2s$][$r$][$e$][$r^2$]
tr[$r^2s$][$r^2s$][$r s$][$s$][$r^2$][$r$][$e$]
})
]
Please be careful, the number of arguments to `th` and `tr` (and `cstyle` and `cwidth`, described below) elements must be consistent within a table. If not, the Typst processor throws an error.
Conversely, there is no need to worry about forgetting to put a cell and not noticing that the layout is broken.
== Changing Alignment and Width of Columns
To change the alignment for each column, use `cstyle`:
#example[
```typst
#easytable({
cstyle(left, center, right)
th[Header 1 ][Header 2][Header 3 ]
tr[How ][I ][want ]
tr[a ][drink, ][alcoholic ]
tr[of ][course, ][after ]
tr[the ][heavy ][lectures ]
tr[involving][quantum ][mechanics.]
})
```
][
#easytable({
cstyle(left, center, right)
th[Header 1 ][Header 2][Header 3 ]
tr[How ][I ][want ]
tr[a ][drink, ][alcoholic ]
tr[of ][course, ][after ]
tr[the ][heavy ][lectures ]
tr[involving][quantum ][mechanics.]
})
]
What if I want to change the length of each column? Use `cwidth`:
```typst
#easytable({
cwidth(100pt, 1fr, 20%)
th[Header 1 ][Header 2][Header 3 ]
tr[How ][I ][want ]
tr[a ][drink, ][alcoholic ]
tr[of ][course, ][after ]
tr[the ][heavy ][lectures ]
tr[involving][quantum ][mechanics.]
})
```
#example_result[
#easytable({
cwidth(100pt, 1fr, 20%)
th[Header 1 ][Header 2][Header 3 ]
tr[How ][I ][want ]
tr[a ][drink, ][alcoholic ]
tr[of ][course, ][after ]
tr[the ][heavy ][lectures ]
tr[involving][quantum ][mechanics.]
})
]
It is of course possible to use `cstyle` and `cwidth` in combination.
```typst
#easytable({
cwidth(100pt, 1fr, 20%)
cstyle(left, center, right)
th[Header 1 ][Header 2][Header 3 ]
tr[How ][I ][want ]
tr[a ][drink, ][alcoholic ]
tr[of ][course, ][after ]
tr[the ][heavy ][lectures ]
tr[involving][quantum ][mechanics.]
})
```
#example_result[
#easytable({
cwidth(100pt, 1fr, 20%)
cstyle(left, center, right)
th[Header 1 ][Header 2][Header 3 ]
tr[How ][I ][want ]
tr[a ][drink, ][alcoholic ]
tr[of ][course, ][after ]
tr[the ][heavy ][lectures ]
tr[involving][quantum ][mechanics.]
})
]
It is also possible to write long content that spans multiple lines.
```typst
#easytable({
cwidth(auto, 50%)
cstyle(right, left)
th[Term][Long Description]
tr[*LaTeX*][A great typesetting system. May be difficult to learn.]
tr([*Typst*], [
A great typesetting system! Specifically, it offers the following advantages:
- Very easy to install
- Very easy to learn
We encourage everyone to use it.
])
})
```
#example_result[
#easytable(
{
cwidth(auto, 50%)
cstyle(right, left)
th[Term][Long Description]
tr[*LaTeX*][A great typesetting system. May be difficult to learn.]
tr(
[*Typst*],
[
A great typesetting system! Specifically, it offers the following advantages:
- Very easy to install
- very easy to learn
We encourage everyone to use it.
],
)
},
)
]
== Customizing Element
Element `tr` has an keyword argument `trans`, which can be used to customize the layout of a particular line.
#example[
```typst
#easytable({
let tr2 = tr.with(trans: emph)
let tr3 = tr.with(
trans: (c) => box(fill: blue, inset: 3pt, text(size: 0.8em, fill: white, c)),
)
th[Header 1][Header 2][Header 3]
tr[How][I][want]
tr2[a][drink,][alcoholic]
tr[of][course,][after]
tr3[the][heavy][lectures]
tr[involving][quantum][mechanics.]
})
```
][
#easytable(
{
let tr2 = tr.with(trans: emph)
let tr3 = tr.with(
trans: (c) => box(fill: blue, inset: 3pt, text(size: 0.8em, fill: white, c)),
)
th[Header 1][Header 2][Header 3]
tr[How][I][want]
tr2[a][drink,][alcoholic]
tr[of][course,][after]
tr3[the][heavy][lectures]
tr[involving][quantum][mechanics.]
},
)
]
If you want to assign a common layout to all rows, you can override the definition of `tr` itself locally.
#example[
```typst
#easytable(
{
let tr = tr.with(trans: pad.with(x: 3pt))
th[Header 1][Header 2][Header 3]
tr[How][I][want]
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
},
)
```
][
#easytable({
let tr = tr.with(trans: pad.with(y: 3pt))
th[Header 1 ][Header 2][Header 3 ]
tr[How ][I ][want ]
tr[a ][drink, ][alcoholic ]
tr[of ][course, ][after ]
tr[the ][heavy ][lectures ]
tr[involving][quantum ][mechanics.]
})
]
Use the `cell_style` argument to change the background color.
#example[
```typst
#easytable({
let th = th.with(trans: emph)
let tr = tr.with(
cell_style: (x: none, y: none)
=> (fill: if calc.even(y) {
luma(95%)
} else {
none
})
)
th[Header 1][Header 2][Header 3]
tr[How][I][want]
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
})
```
][
#easytable({
let th = th.with(trans: emph)
let tr = tr.with(cell_style: (x: none, y: none)
=> (fill: if calc.even(y) {
luma(95%)
} else {
none
}))
th[Header 1][Header 2][Header 3]
tr[How][I][want]
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
})
]
With `hline` you can draw a horizontal line at any position. The same goes for `vline`.
#example[
```typst
#easytable({
th[Header 1][Header 2][Header 3]
tr[How][I][want]
hline(stroke: red)
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
// Specifying the insertion point directly
hline(stroke: 2pt + green, y: 4)
vline(
stroke: (paint: blue, thickness: 1pt, dash: "dashed"),
x: 2,
start: 1,
end: 5,
)
})
```
][
#easytable({
th[Header 1][Header 2][Header 3]
tr[How][I][want]
hline(stroke: red)
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
// Specifying the insertion point directly
hline(stroke: 2pt + green, y: 4)
vline(
stroke: (paint: blue, thickness: 1pt, dash: "dashed"),
x: 2,
start: 1,
end: 5,
)
})
]
== Customizing Column Style
Use `cstyle`.
The `cstyle` function accepts a function as well as an alignment as its argument.
#example[
```typst
#easytable({
let show_tag(c) = box(
fill: red.darken(60%),
inset: (x: 2pt),
outset: (y: 2pt),
text(fill: white, size: 0.8em, c),
)
cstyle(left, center, left)
th[Header 1][Header 2][Header 3]
// Change style from the middle of the table
cstyle(left, center, show_tag)
tr[How][I][want]
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
})
```
][
#easytable({
let show_tag(c) = box(
fill: red.darken(60%),
inset: (x: 2pt),
outset: (y: 2pt),
text(fill: white, size: 0.8em, c),
)
cstyle(left, center, left)
th[Header 1][Header 2][Header 3]
// Change style from the middle of the table
cstyle(left, center, show_tag)
tr[How][I][want]
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
})
]
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-16.typ | typst | Other | // Test the `slice` method.
#test((1, 2, 3, 4).slice(2), (3, 4))
#test(range(10).slice(2, 6), (2, 3, 4, 5))
#test(range(10).slice(4, count: 3), (4, 5, 6))
#test(range(10).slice(-5, count: 2), (5, 6))
#test((1, 2, 3).slice(2, -2), ())
#test((1, 2, 3).slice(-2, 2), (2,))
#test((1, 2, 3).slice(-3, 2), (1, 2))
#test("ABCD".split("").slice(1, -1).join("-"), "A-B-C-D")
|
https://github.com/StefanieJaeger/sa-docu | https://raw.githubusercontent.com/StefanieJaeger/sa-docu/main/glossary.typ | typst | #import "@preview/glossarium:0.4.1": make-glossary, print-glossary, gls, glspl
#show: make-glossary
// https://typst.app/universe/package/glossarium/
#print-glossary(
show-all: true,
(
// School
(key: "module", short: "Modul", desc: "foo"),
(key: "category", short: "Kategorie", desc: "foo"),
(key: "focus", short: "Spezialisierung", desc: "foo, auch Vertiefung genannt"),
(key: "std", short: "Studienordnungen", desc: "foo"),
(key: "ects", short: "Credit", plural: "Credits", desc: "foo"),
// Tech
(key: "spa", short: "SPA", long: "Single Page Application", desc:""),
(key: "fontawesome", short: "Fontawesome", desc: ""),
(key: "tailwind", short: "Tailwind CSS", desc: ""),
(key: "vite", short: "Vite", desc: "")
// UX
)
)
|
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/markup/content-raw.typ | typst | Apache License 2.0 | #align(center, table(
[
```
underbrace(x + y, |A|)
```
],
))
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-20.typ | typst | Other | // Error: 3-10 cannot repeat this string -1 times
#(-1 * "")
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/match_def/param.typ | typst | Apache License 2.0 | #let f(a /* ident */) = a; |
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/build-intake-upgrade/entry.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Build: Intake Upgrade",
type: "build",
date: datetime(year: 2023, month: 9, day: 30),
author: "<NAME>",
witness: "Violet Ridge",
)
#grid(
columns: (1fr, 1fr),
gutter: 20pt,
[
After finishing the catapult we realized that the second intake roller
interfered with the catapult arm. We decided to remove one of rollers to let the
catapult fire uninhibited.
1. We unscrewed the bracing from the top of the intake.
2. We unscrewed the rear 2 pillow bearings.
3. We took the rear roller off of the drivetrain.
4. We build stops our of standoffs to stop the intake from traveling out too far.
#admonition(
type: "warning",
)[
With the removal of the cross bracing the two pieces of half cut can move
independently. The only thing keeping them in line are the stops. This design is
undesirable, and can lead to excess friction.
]
],
figure(image("./top.jpg"), caption: "Finished intake"),
)
|
https://github.com/yonatanmgr/summaries-template | https://raw.githubusercontent.com/yonatanmgr/summaries-template/main/template/template.typ | typst | #import "/template/ilm-custom.typ": *
#import "/template/thm-custom.typ": *
#import "/template/utils.typ": *
#import "/template/functions.typ": *
// Config file.
#let cmeta = yaml("/config.yaml")
// Environment definitions.
#let question = newenv("global", "שאלה", olive, addon: "תשובה").with([])
#let ex = newenv("exercise", "תרגיל", teal, addon: "פתרון", numbering: 0).with([])
#let exqed = newenv("exercise", "תרגיל", qed: true, teal, addon: "פתרון", numbering: 0).with([])
#let example = newenv("example", "דוגמה", green, numbering: 0).with([])
#let namedex = newenv("exercise", "תרגיל", teal, addon: "פתרון", numbering: 0)
#let def = newenv("global", "הגדרה", blue)
#let prop = newenv("global", "טענה", purple, addon: "הוכחה", qed: true)
#let conclusion = newenv("global", "מסקנה", color.hsl(50deg,200,60))
#let conclusionqed = newenv("global", "מסקנה", qed: true, addon: "הוכחה", color.hsl(50deg,200,60))
#let the = newenv("global", "משפט", red, addon: "הוכחה", qed: true)
#let lem = newenv("global", "למה", orange, addon: "הוכחה", qed: true)
#let note = newenv("global", "הערה", black, alt: true, centered: true).with([])
#let thebr = newenv("global", "משפט", red, addon: "הוכחה", qed: true, breakable: true)
#let lembr = newenv("global", "למה", orange, addon: "הוכחה", qed: true, breakable: true)
#let propbr = newenv("global", "טענה", purple, addon: "הוכחה", qed: true, breakable: true) |
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/物联网技术及应用/大论文/main.typ | typst | The Unlicense | #import "template.typ": *
// 需要 typst 0.10.0
#show: project.with(
title: "基于软件定义网络技术的物联网应用研究",
authors: ("absolutex",),
abstract_zh: [
本文首先定义了物联网(IoT)的概念,并阐述了其关键特点,包括设备间的互联互通、数据的自动采集与处理等。随后,文章探讨了物联网在不同领域的应用,如智慧物流、健康医疗、智能环境等,并指出了物联网在数据安全、隐私保护、网络流量管理等方面面临的挑战。文章进一步介绍了软件定义网络(SDN)技术的发展历程、优势以及在物联网中的应用潜力。通过分析SDN的分层架构和关键技术,本文揭示了SDN如何提升物联网的网络管理效率、安全性和资源优化。最后,文章总结了SDN在物联网中的实际应用场景,并对未来的研究方向提出了展望。
],
abstract_en: [
This article begins by defining the concept of the Internet of Things (IoT) and outlining its key characteristics, including the interconnectivity of devices and the automatic collection and processing of data. It then explores the application of IoT in various fields, such as smart logistics, healthcare, and intelligent environments, and highlights the challenges faced by IoT in terms of data security, privacy protection, and network traffic management. The article further introduces the development history, advantages, and application potential of Software-Defined Networking (SDN) technology in IoT. By analyzing the layered architecture and key technologies of SDN, this paper reveals how SDN can enhance the efficiency, security, and resource optimization of IoT network management. Finally, the article summarizes the practical application scenarios of SDN in IoT and provides prospects for future research directions.
],
keywords_zh: ("物联网", "SDN"),
keywords_en: ("IoT", "SDN"),
)
= 引言
随着物联网(IoT)技术的快速发展,越来越多的设备被连接到互联网,形成了一个庞大且复杂的网络。物联网的广泛应用,如智能家居、智慧城市、工业自动化、远程医疗、智能交通、智能农业等,对网络管理提出了新的挑战。传统的网络架构难以满足物联网的需求,如灵活性差、扩展性有限、管理复杂等问题。软件定义网络(SDN)技术的出现,为解决这些问题提供了新的思路。SDN通过将控制平面与数据平面分离,实现了网络的集中式管理和动态配置,极大地提高了网络的灵活性和可编程性。本文旨在综述基于软件定义网络技术的物联网应用研究,探讨SDN技术在物联网中的应用现状、面临的挑战以及未来的发展方向。
= 物联网应用背景
当谈到物联网(IoT)时,我们进入了一个充满潜力的数字化时代。物联网通过连接大量智能设备和传感器,将它们互相关联并收集、分析和共享数据,实现了物理世界的数字化。本节简要地探讨了一下物联网的定义、特点、应用领域以及当前的发展现状和挑战。
== 物联网的定义与特点
物联网技术是一种计算设备、机械、数字机器相互关系的系统@Brown2016,也是基于互联网的信息社会基础设施,它连接了大量具备通信功能的物品,如汽车、家用电器、智能手表等。通过物联网技术,这些具备通用唯一识别码的设备能够实现互相通信、自动协调和智能化控制,也被称为“万物互联”。
物联网的核心是将各种物理对象连接到互联网,使它们能够相互通信和交换数据。这种通过网络传输数据的能力,使海量物联网设备无需人与人或人与设备的交互。物联网还能通过自动采集、共享和处理数据,实现对环境的自动控制和管理,从而缩短决策时间和成本。
== 物联网的应用领域
物联网的应用领域非常广泛,目前已逐步深入运输和物流、工业制造、健康医疗、智能环境(家庭、办公、工厂)、能源系统以及个人和社会领域,具有广阔的前景。@区块链轻量化技术
例如,智慧物流中应用物联网技术,能够实现对物品的实时跟踪和监控,提高物流运作的透明度和效率。同时,借助云计算、大数据、数据孪生、边缘计算、人工智能等智能化技术,智慧物流能够实现对复杂数据的分析和处理,为决策者提供更加准确和及时的信息,从而更好地满足市场需求和客户需求。@物联网技术在智慧物流中的应用研究
== 物联网的发展现状与挑战
尽管物联网在许多领域都取得了显著的进展,但仍然面临一些挑战。
在数据安全和隐私方面,物联网设备通常需要收集和传输大量的用户数据,包括个人信息、使用习惯等。这就增加了数据被盗用或滥用的风险。例如,黑客可能会利用设备的安全漏洞,窃取用户的个人信息。此外,一些设备可能会在未经用户同意的情况下收集和使用数据,这也侵犯了用户的隐私权。
随着物联网设备数量的增加,网络流量也会相应增加。这可能会导致网络速度变慢,甚至服务中断。例如,如果一个家庭中有大量的智能设备同时在线,可能会导致家庭的网络速度下降。在更大的范围内,如果一个城市的物联网设备过多,可能会对整个城市的网络造成压力。
近年来,物联网设备数量剧烈增长,我国移动物联网用户规模快速扩大。截至2022年底,连接数达18.45亿户,比2021年底净增4.47亿户,占全球总数的70%。@peoplesDaily2023 而每一个物联网设备都需要进行配置、更新和维护。这对于IT部门来说是一个巨大的负担。例如,设备的软件需要定期更新,以修复安全漏洞和添加新功能。此外,设备可能会出现故障,需要进行维修或更换。这些都需要投入大量的人力和物力。
最后,大量的物联网设备需要消耗大量的电力。这不仅会增加用户的电费,还会对环境和能源供应造成压力。例如,如果一个城市的物联网设备过多,可能会导致电网的负荷过大,甚至出现停电的情况。此外,电力的生产通常会产生大量的二氧化碳,这对环境也是一种压力。
= 软件定义网络技术
软件定义网络(SDN)技术是一种网络架构和设计理念,它将网络的控制平面与数据平面分离,实现了网络的集中式管理和动态配置。SDN技术通过将网络设备的管理功能从硬件中分离出来,实现了网络的灵活性和可编程性。
== 软件定义网络技术的发展历程
SDN起源于2006年斯坦福大学的Clean Slate研究课题。@stanford2006 2009年,Mckeown教授正式提出了SDN概念。@mckeown2009software 2012年,谷歌宣布已在数据中心内部骨干网络上成功使用SDN技术,标志着SDN进入到商用化阶段。之后,SDN被MIT列为“改变世界的十大创新技术之一”。2013年,SIGCOMM会议收录了多篇相关文章,甚至将SDN列为专题来研讨,带动了SDN相关研究的蓬勃发展。
在早期,SDN技术主要应用于数据中心网络。数据中心是托管大量服务器、存储设备和网络设备的地方,用于处理云计算、大数据、应用程序等工作负载。数据中心网络中的设备数量相对较少,因此集中式的控制平面可以有效地管理网络。这意味着网络管理员可以通过一个中央控制器来配置、监控和优化整个网络,而不需要逐个管理每个交换机或路由器。
随着物联网技术的发展,SDN技术开始应用于物联网网络。物联网连接了各种设备,例如传感器、智能家居设备、工业自动化设备等。SDN可以帮助物联网网络实现更灵活的配置、更好的资源利用和更高的安全性。例如,通过SDN,可以根据不同设备的需求自动分配网络带宽,从而优化整个物联网网络。
后期,随着5G网络和边缘计算技术的发展,SDN技术开始应用于这些领域。在5G网络中,SDN可以帮助实现网络切片,以满足不同应用的不同需求。边缘计算中的SDN可以优化数据在边缘设备和云之间的传输,提高响应速度和效率。
=== 软件定义网络技术解决问题的能力
SDN的灵活性显著提升了网络管理的效率和响应速度。在传统网络架构中,网络设备的配置和管理通常是静态和分散的,难以适应快速变化的网络需求。而SDN通过集中式控制平面,允许管理员对整个网络进行动态配置。这种集中控制使得网络可以根据实际需求进行快速调整,灵活应对物联网中设备数量的激增和应用场景的不断变化。例如,当新的物联网设备加入网络时,SDN控制器可以自动检测并配置相应的流量规则,确保新设备能够迅速并入现有网络结构中,从而维持网络的高效运行。
SDN技术的可编程性使得网络数据平面能够根据具体应用需求进行定制。传统网络设备通常依赖于厂商预设的功能,难以满足多样化的物联网应用需求。通过SDN,网络管理员可以编写特定的程序来控制数据流的处理方式,灵活适应不同设备和应用的通信需求。例如,在一个智能家居系统中,SDN可以定制化处理不同家电设备的数据流量,优化带宽分配,确保高优先级的任务(如安全监控)始终得到优先处理。这种高度可编程的特性,使得物联网网络能够更加精确地满足各种应用场景的需求。
SDN技术在提升物联网安全性方面也发挥了重要作用。通过集中控制,SDN能够实现更精细的网络隔离和访问控制,增强整体网络的安全防护能力。传统网络架构中的安全策略往往难以精细化实施,而SDN可以根据设备类型、用户身份、数据流特征等多种因素,对网络流量进行分类和管理,制定细粒度的安全策略。例如,对于同一网络中的传感器和执行器设备,可以设置不同的访问控制规则,限制敏感数据的传输路径,从而降低安全风险。此外,SDN还支持动态检测和响应网络威胁,及时隔离受攻击的网络部分,保护其他设备的正常运行。
== 软件定义网络技术的分层架构
SDN 系统架构可分为三个层次:控制平面,数据平面和应用层。
#figure(
image("static/SDN模型架构.jpg", width: 50%),
caption: [SDN分层架构],
)
控制平面是SDN系统的核心,负责管理网络流量、路由和策略。在物联网中,控制层 (也称为网络操作系统(NOS)) 主要负责处理数据转发面资源的抽象信息, 可支持网络拓扑、状态信息的汇总和维护, 并基于应用的控制来调用不同的转发面资源。
数据平面(数据转发层)是物联网设备之间的通信通道。它可以是物理交换机、虚拟交换机或其他网络设备。在SDN物联网中,数据平面负责基于业务的流表的数据处理、转发和状态收集, 原有网络中转发面功能在分离的网络设备中实现, 而支持SDN的网络中这些功能可以在同样的网络设备中通过融合实现, 支持不同的通信协议和数据格式,由控制层的可编程接口进行调用。
应用层 (AL)是SDN物联网的最终用户接口,它可以是一个Web界面、移动应用程序或其他形式的用户界面。应用层包括各种不同的业务和应用, 可以管理和控制网络对应用转发/处理的策略, 也支持对网络属性的配置实现提升网络利用率、保障特定应用的安全和服务质量,提供用户友好的操作和管理功能。@SDN标准化和应用场景探讨
== 软件定义网络技术的关键
SDN的核心思想是控制和转发分离。在传统的网络中,控制和转发是紧密耦合在一起的,每个转发节点都需要独立处理控制命令。而在SDN中,控制功能被集中到一个或多个控制器上,这些控制器通过开放的API接口与下层转发节点通信,从而实现全局的网络控制。这种分离使得网络管理员可以通过软件编程的方式,集中管理和控制整个网络,大大简化了网络管理的复杂性。@深入浅出SDN
SDN的工作原理可以归结为“集中控制、分散转发”。通过将控制功能从转发节点中剥离出来,SDN控制器可以全局地了解网络的拓扑结构和状态,从而做出更智能、更快速的网络决策。而转发节点则只负责根据控制器的指令进行数据包的转发,大大简化了节点的功能和工作负载。@深入浅出SDN
利用分层的思想,SDN将数据与控制相分离。在控制层,包括具有逻辑中心化和可编程的控制器,可掌握全局网络信息,方便运营商和科研人员管理配置网络和部署新协议等。在数据层,包括哑的(dumb)交换机(与传统的二层交换机不同,专指用于转发数据的设备)。交换机仅提供简单的数据转发功能,可以快速处理匹配的数据包,适应流量日益增长的需求。两层之间采用开放的统一接口(如OpenFlow等)进行交互。控制器通过标准接口向交换机下发统一标准规则,交换机仅需按照这些规则执行相应的动作即可。因此,SDN技术能够有效降低设备负载,协助网络运营商更好地控制基础设施,降低整体运营成本,成为最具前途的网络技术之一。@软件定义网络SDN研究进展
== 软件定义网络的实际应用场景
=== OSPF 动态网络
OSPF(Open Shortest Path First)路由协议是一种应用于企业网络的内部网关路由协议(IGP),其管理配置灵活,并根据网络的实际链路状态进行路由选择,所以其运行效率优于传统的距离矢量路由协议.OSPF路由协议只在一个自治系统(AS)内运行,按照链路状态的通告范围,OSPF协议可以分为单区域的OSPF协议和多区域的OSPF协议.单区域的OSPF协议应用最为广泛,在单区域的OSPF网络中,所有网络设备都位于同一个OSPF区域,只要区域中一个网络发生了改变,OSPF协议会把LSA( Link-State Advertisement)报文泛洪广播到本区域内所有的网络设备,这不但耗费了大量的网络带宽,而且还加重了网络设备的转发负担,降低了网络的运行效率.多区域OSPF协议能减少网络中的LSA,但是维护多区域的OSPF的代价较高,需要耗费大量资源。@基于决策树的SDN网络入侵分类检测模型
结合SDN和多区域OSPF网络的优点,刘路等人提出一种基于SDN的多区域OSPF动态网络模型,此模型通过SDN对多区域的OSPF网络进行配置,对区域进行动态划分,其有效的降低了路由器LSDB数据规模,同时也提升了网络的管理效率.多区域OSPF协议将大多数LSA报文限制在较小的OSPF区域内,通过SDN进行网络配置,减轻了网络设备的负荷,提升了网络的运行效率和用户的使用感知,所以此种网络模型可以用于单区域OSPF网络的调整和升级。@基于动态连接的RDMA可靠传输协议设计 SDN控制器为结构的控制层,比如BGP协议、组播协议和L2TP协议的部署和运算都集中在了控制器,控制器把指令发给其余的网络设备,网络设备对数据进行转发。@具有私钥可恢复能力的云存储完整性检测方案 @一种基于SDN和多区域OSPF路由协议的动态网络
=== 防火墙
基于SDN和NFV的下一代防火墙的出现,不仅提供了更高效的网络管理和安全性,同时,也为未来网络的发展奠定了坚实基础。SDN作为这一架构的关键组成部分,为防火墙引入了灵活性和可编程性。传统防火墙往往依赖于静态的规则集,无法应对网络拓扑结构的频繁变化。@SDN与NFV技术在数据中心建设中的应用及发展探析 SDN通过将控制平面和数据平面分离,使网络管理员能够通过集中的控制器动态地调整防火墙规则。这种动态性使得防火墙能够更好地适应不断变化的网络环境,提高了网络的可管理性和灵活性。SDN还为防火墙提供了更精细的流量控制和QoS管理能力。通过集中的控制器,管理员可以根据网络流量的实时情况对防火墙规则进行调整,优化网络性能。这种精细的流量控制不仅提高了网络的效率,还为网络安全提供了更为细致的保护。SDN的这些特性使得下一代防火墙能够更好地适应云计算和大数据环境下的复杂网络架构。@基于SDN和NFV的下一代防火墙研究与应用
基于SDN和NFV的下一代防火墙架构设计的关键组件包括控制器、网络函数虚拟化平台和安全策略。通过将这些组件结合起来,可以实现更高灵活性、可扩展性和安全性的网络防火墙系统。控制器是整个架构的核心,它负责管理和控制网络中的所有设备和功能。控制器通过与网络设备进行通信,获取网络拓扑信息,并根据安全策略对流量进行过滤和转发。控制器还负责监测网络中的异常行为,并及时采取相应的措施来保护网络安全。网络函数虚拟化平台是实现SDN和NFV的关键组件之一,将传统的硬件设备虚拟化为软件功能,使其能够灵活地部署和管理。在防火墙架构中,网络函数虚拟化平台可以提供各种安全功能,如入侵检测和防御、应用层网关等。通过将安全功能虚拟化,可以实现更高的灵活性和可扩展性。@面向云网融合的SDN控制器与组网技术研究
== 软件定义网络与物联网结合
SDN技术可以应用于车联网,通过实时监控和管理车辆间的通信,提高车联网的安全性和可靠性@软件定义网络中基于队列管理的优化流量自适应调度算法。在5G网络中,SDN技术可以帮助网络自动化管理和配置,提高网络性能和可靠性,实现高效的网络资源管理。在物联网中,SDN技术可以应用于物联网的边缘网络管理和优化,提高物联网的可靠性和安全性。除了数据中心网络、车联网、5G和物联网,SDN网络管理与优化技术还可以应用于其他各种类型的网络,如广域网、城域网和局域网等。在广域网中,SDN技术可以实现多种服务质量(QoS)需求的动态配置@软件定义网络中基于队列管理的优化流量自适应调度算法,从而提高网络的吞吐量和稳定性。在城域网中,SDN技术可以实现智能路由、负载均衡和服务级别协议(SLA)管理,提高城域网的可靠性和性能。在局域网中,SDN技术可以实现实时流量监控和管理,提高局域网的安全性和稳定性@软件定义网络流量管理方法研究。此外,SDN技术还可以应用于电信、金融、医疗等各行业的网络中,帮助这些行业提高网络的可靠性和安全性,提高业务的效率和用户体验。
= 总结
=== SDN 应用场景
在物联网中,SDN技术已经被广泛应用于各个领域。例如,在智慧城市交通管理领域:考虑一个智慧城市中的交通管理系统。这个系统需要实时监测交通流量、优化信号灯控制、减少拥堵等。通过SDN,可以实现动态路由优化和信号灯控制。
对于动态路由优化,SDN控制器可以根据实时交通数据调整路由,避免拥堵。
对于信号灯控制,SDN可以根据交通流量和优先级调整信号灯的时间间隔,提高交通效率。
=== SDN 设备
思科向市场推出了SDN变体–思科以应用为中心的基础设施 (ACI)。瞻博网络在其Contrail产品中采用了SDN,而Arista Networks将SDN原理集成到其可扩展操作系统中,试图将新的软件定义云网络推向市场。@techtarget_sdn
随着网络变得多样化以及新工作负载移至边缘,SDN理所当然地在这些新的复杂环境中找到一席之地。即使在消费者世界中,SDN元素也已进入相关产品。例如,消费者在家庭服务器中常运行着基于控制器的网络系统。@techtarget_sdn
== 局限性与挑战
=== 设备异构性
物联网设备类型繁多,包括各种传感器、执行器、智能家电和其他嵌入式设备。这些设备在硬件架构、通信协议和功能需求方面存在显著差异,给SDN技术的统一管理带来了巨大困难。目前,SDN技术在支持不同设备类型的集成方面还不够完善。例如,不同设备可能使用不同的通信标准(如Zigbee、Z-Wave、LoRa、Wi-Fi等),这要求SDN系统具有高度的兼容性和灵活性,能够适应多种通信协议和数据格式。未来的研究需要致力于开发更加通用的SDN控制平台和接口协议,以便更好地支持和管理异构设备,提升网络的整体兼容性和操作简便性。
=== 大规模设备管理
随着物联网设备数量的不断增加,SDN物联网的网络规模也在迅速扩大。大规模网络中的数据流量管理、设备协调和资源分配都变得更加复杂和困难。例如,在一个大规模的物联网系统中,成千上万的设备同时连接和通信,如何有效地管理这些设备的连接状态、路由选择和流量优化,成为一个亟需解决的问题。此外,网络规模的扩大还可能导致控制平面的瓶颈和性能下降。为了应对这些挑战,研究需要探索分布式SDN控制架构和智能化管理算法,以实现对大规模网络的高效管理和优化。采用分布式控制器可以减轻单点故障的风险,并提高系统的可靠性和扩展性。
=== 安全性
内部攻击成为了安全最大的风险。在大数据、物联网技术、人工智能应用的推动下,边缘计算的应用场景越来越多,在靠近数据源或用户的地方提供计算、存储等基础设施,并为边缘应用提供云服务和IT环境服务。随着5G和工业互联网的快速发展,新兴业务对边缘计算的需求十分迫切。相比于集中部署的云计算服务,边缘计算解决了时延过高、汇聚流量过大等问题,为实时性和带宽密集型业务提供了更好的支持,但也为边缘计算的安全问题带来了更大的挑战。@基于SDN的智能安全接入平台研究
=== 2. 未来研究的方向
未来研究的方向涵盖了多个关键领域,旨在增强SDN(软件定义网络)与物联网(IoT)的集成与应用效果。
自适应性是一个亟需深入研究的领域。随着物联网设备和应用的多样化和动态性,如何使SDN物联网系统更加自适应显得尤为重要。这不仅包括对不断变化的环境和需求的响应能力,还涉及自动化和智能化调整网络流量控制策略。研究可以探讨自动调整流表规则和优化路由算法等方面,通过机器学习和人工智能技术,提高网络的自适应性和响应速度,从而确保网络的高效、稳定运行。
边缘计算也是物联网发展的重要趋势之一。边缘计算通过在靠近数据源的地方进行数据处理,可以显著减少延迟并提高带宽利用效率。因此,研究如何将SDN技术与边缘计算相结合,是提升物联网应用性能和效率的关键。具体研究方向可以包括:在边缘节点部署SDN控制器,优化数据处理和传输路径,以及实现边缘设备的智能化管理。这些研究不仅能改善数据处理效率,还能增强系统的可靠性和安全性。
最后,跨领域合作对于SDN物联网的进一步发展具有重要意义。SDN物联网涉及计算机科学、通信工程、电子工程等多个学科领域,未来的研究需要促进这些领域之间的深度合作和交流。通过跨学科的协同研究,可以实现资源共享、技术互补和创新突破。例如,通信工程的先进技术可以提升SDN的传输效率,而电子工程的最新成果可以为物联网设备提供更高性能的硬件支持。整合这些不同领域的研究成果,可以推动SDN物联网技术的全面发展,创造出更加高效、智能的网络系统。
这些方向不仅能解决当前面临的技术挑战,还能为物联网的发展开辟新的路径,为实现智能化、自动化和高效化的物联网系统奠定坚实基础。
== 结论
通过本文的综述,我们深入探讨了基于软件定义网络技术的物联网应用。SDN在物联网中具有广泛的应用前景,但仍然面临一些挑战。我们希望未来的研究能够进一步推动SDN物联网的发展,为智能、高效的物联网系统提供更好的解决方案。
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/raw_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Multiline block splits paragraphs.
Text
```rust
fn code() {}
```
Text
|
https://github.com/MatheSchool/typst-g-exam | https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/test/questions/test-003-only-subquestion.typ | typst | MIT License | #import "../../src/lib.typ": *
#show: g-exam.with()
#g-subquestion(points: 1)[Sub question 1]
#g-subquestion(points: 1)[Sub question 2]
#g-subquestion(points: 1.5)[Sub question 3] |
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/foundations/std.typ | typst | // Test 'std', a module with the standard library
--- std-basic-access ---
#test(std.grid, grid)
#test(std.calc, calc)
--- std-import ---
#import std: grid as banana
#test(grid, banana)
--- std-of-shadowed ---
#let my-grid = grid[a][b]
#let grid = "oh no!"
#test(my-grid.func(), std.grid)
--- std-shadowing ---
#let std = 5
// Error: 6-10 cannot access fields on type integer
#std.grid
--- std-mutation ---
// Error: 3-6 cannot mutate a constant: std
#(std = 10)
--- std-shadowed-mutation ---
#let std = 10
#(std = 7)
#test(std, 7)
--- std-math ---
$ std.rect(x + y = 5) $
|
|
https://github.com/jrihon/multi-bibs | https://raw.githubusercontent.com/jrihon/multi-bibs/main/chapters/02_chapter/mod.typ | typst | MIT License | #import "../../lib/multi-bib.typ": *
#import "bib_02_chapter.typ": biblio
#pagebreak() // pagebreak previous bibliography
= Chapter 2
#include "introduction.typ"
#include "methods.typ"
#include "results.typ"
#include "discussion.typ"
#mbibliography(biblio, "ieee")
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/004%20-%20Dragon's%20Maze/002_Teysa%20Karlov.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"<NAME>",
set_name: "Dragon's Maze",
story_date: datetime(day: 10, month: 04, year: 2013),
author: "<NAME>",
doc
)
#emph[They've ruled for far too long.]
Teysa sat in her favorite chair, made from Utvaran ebony, and let the blasphemous thought dwell in her mind for a while. She savored the feeling that it generated within her—a thrilling blend of sacrilege and freedom.
#figure(image("002_Teysa Karlov/01.jpg", width: 100%), caption: [Art by Karla Ortiz], supplement: none, numbering: none)
Certainly, there was danger ahead of her. The Obzedat had given her the title of grand envoy, but Teysa knew it was so they could keep closer tabs on her—constantly testing her loyalty and keeping her busy with endless "official business." Teysa was no stranger to the game and she knew she could only gain so much influence on the side of the living before feeling the phantom strings of the Obzedat pulling her into their domain. And Teysa had been steadily increasing in power. She had felt their strings pulling for quite some time.
She'd had enough of these dead, old men.
#emph[The Generational Manifesto for the Orzhov's Future] sat on her desk. The ancient tome had not gathered a mote of dust since her days as a young advokist. Teysa had read it from cover to cover several times, but this last time she did so from a different context. The words took on a whole new meaning. Teysa's eyes were opened; no longer was she that ambitious, young advokist who entered a ruthless world of power and lies. Lately, Teysa began to see herself as a stand-in for something new within the Orzhov that had instilled her mind with deep conviction and ideas. She wanted to gut the Orzhov guild and reshape it into a new kind of power that Ravnica had never seen.
She picked up the heavy book and opened it to the most recent quote that rung in her head.
Simple but audacious words that eventually led to "Anonymous" being hunted down and put to death. No one outside the Orzhov elite knew the full story, but those within the Orzhov families knew Anonymous was an aristocrat named <NAME>. Jarik was known within the Orzhov elite for speaking out against the Obzedat. At first, it was considered an eccentricity of Jarik's Orzhovan blood, and her family name kept her safe until she began publishing essays critical of the ghost council. Those essays and her refusal to desist led to her arrest, trial, and public disintegration in the Forum of Orzhova.
Teysa had spent a small fortune in coin and favors to a trusted Dimir contact to secretly procure the rare and incendiary writings of Jarik. They were in Teysa's collection but hidden far away, under lock and key and several high-powered, magical wards. To possess Jarik's words was to be guilty of the same crimes Jarik was put to death for. But Teysa had stopped giving a damn about what the Obzedat could do to her and had started to focus her formidable mind on what she could do to them.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The maze.
A few days earlier, the Obzedat had used a Deathpact to deliver the message. A terrified scribe blurted out the message to Teysa within the confines of a verity circle. Teysa listened with the intensity of a cat watching a mouse hole. The maze started off as a passing interest for the Orzhov, another strange Izzet obsession to be monitored but not taken too seriously. Teysa could feel this new information shifting the game. The maze had become vastly more important and that was something the Obzedat had no plan for. And she knew it.
#figure(image("002_Teysa Karlov/02.jpg", width: 100%), caption: [Maze’s End | Art by Cliff Childs], supplement: none, numbering: none)
The Obzedat's greatest weakness was that it was composed of spirits playing a corporeal game—they needed someone on the other side of the veil they could trust with matters of great importance. Up until then, Teysa had been their reluctant answer. She could feel their frustration of having to divulge their urgency to Teysa with this task of running the maze and finding out its ancient secret. Would it be unbridled power? Would it be a vast fortune? Would it grant rulership over Ravnica? Teysa knew the Obzedat was truly worried about what could happen; the maze was out of its control and the clock was ticking. Teysa was its best bet at solving the maze. Now she had the upper hand—she had something the council wanted.
As she looked out from her balcony, she couldn't contain the smirk from the sheer delight of it all.
"Slubnik," Teysa called.
Her thrull wheezed over and bowed before Teysa.
"Send a messenger and bring <NAME> of the Boros to my study."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Tajic sat in Teysa's study. The sound of Teysa's cane on the tile floor heralded her arrival. As she walked in, the Boros knight stood and smiled, his white teeth seemed somehow feral against his olive skin and black goatee. He offered his arm and aided Teysa to her chair. His arm felt like coiled steel.
Teysa could tell his eyes took in every detail of his surroundings. She could sense Tajic's intellect but she could also sense how he radiated danger. Even though Teysa was anything but a warrior, she supposed Tajic could tear apart the guards that stood outside her door and everyone else within her mansion if he chose.
Teysa motioned for Tajic to sit. "I'll get right to the point. I know you to be a man of your word, Tajic, and unquestionable integrity is something that I value above all things—coin, land, or even power. We both know that integrity is power and that which has no integrity has no power."
Tajic's eyes sparkled. He liked this Orzhov aristocrat; she was a fighter and a visionary. "You have always been a friend to the Boros, <NAME>, even when our guildmasters have not seen eye to eye." His accent was thick and he spoke it with an assurance which, no doubt, had irked his elocutionist in the Boros Academy. "Your efforts in curing the Kuga Mot, restoring the Utvara, defeating Zomaj Hauc, creating a new #emph[Guildpact] —all these actions speak to your character. I know Ravnica is not just a commodity to you."
#figure(image("002_Teysa Karlov/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"I am glad you see me without the usual cynicism." Teysa sipped her tea. "Most do not afford me the simple capacity of what it is to be human, let alone consider that I actually care about the wellbeing of our city without thought of profit." Teysa looked over the rim of her cup.
Tajic leaned forward in his chair. "I knew that you appreciated the law and what it means for Ravnica. That is why I accepted your invitation to talk today." He leaned back. "I have to be honest with you, <NAME>, I have always admired your courage from afar but now that I am in your presence, I can sense what makes you a great leader." Tajic said the words with no hint of subterfuge or guile; Teysa felt a slight blush come to her cheeks.
"You do me honor, Sir." She took a self-conscious sip of tea.
"I know what inspires people," Tajic said matter-of-factly.
There was a long pause. The two sat in silence, sipping tea, Tajic with a sphinx-like expression that betrayed no emotion and Teysa feeling this was the oddest Boros commander she had ever encountered. He was perfect for the task. This was the man who would help her achieve her goal.
Teysa took a breath, the kind of breath one takes before opening a door from which there is no return.
"I would like to form an alliance with you. A special kind of alliance that requires absolute commitment and dedication."
Tajic smiled as if expecting Teysa's request all along. "You want me to help you run the maze and steal the prize from the insatiable claws of Niv-Mizzet? My pleasure."
"No," Teysa said. "I want you to help me destroy the Obzedat."
#figure(image("002_Teysa Karlov/04.jpg", height: 40%), caption: [], supplement: none, numbering: none)
|
|
https://github.com/jijinbei/typst_template | https://raw.githubusercontent.com/jijinbei/typst_template/main/report/README.md | markdown | # レポートのテンプレート
Typstのレポート用のテンプレート
## インストール方法
> git clone https://github.com/jijinbei/typst_template.git (dirname)
でクローンする。
dirnameを好きなファイル名に
## 使い方
`date`や`titlepage`でテンプレートの設定を変える
## 注意
デフォルトのフォントはLatin Modern Roman, Harano Aji Mincho、数式のフォントはLatin Modern Mathを用いているので、これらをインストールしてください。
|
|
https://github.com/Quaternijkon/Typst_USTC_CS | https://raw.githubusercontent.com/Quaternijkon/Typst_USTC_CS/main/README.md | markdown | **www.中国科学技术大学.com**
# 省流版
为了降低新手上路的代码分析成本以及降低项目的耦合性,特将项目拆分成多个typ文件,请按以下步骤了解:
`main.typ`是渲染的入口,新手上路直接从这里开始。//第一步
`main.typ`中导入了`config.typ`,这是配置文件,封面的标题,副标题,作者等信息在这里修改,其他你无须烦恼。//第二步
`config.typ`中导入了`theme.typ`和`lib.typ`,新手上路可以暂时跳过。
- `theme.typ`相当于`CSS`,控制着模板长什么样,如果你对模板的样式不满意,包括字体,图片素材,跳转功能,或者改成其他学校的主题,在这里修改成你希望的样子。学习曲线较陡峭,初学者无需关心,
- `lib.typ`中是第三方包和自定义函数,当模板中的包不能满足你的需求,或者想自定义一些常用函数,请把它们放在这里以保持项目的结构性和低耦合。
`content.typ`这是你放实际内容的地方,一级标题是大纲,二级标题是当页的标题,之后的n级标题都在页内作为内容显示,无特殊地位。//第三步
# 文件说明
- `assets`: 模板资源文件
- `img`: 模板图片文件
- `template`: 可复用组件
- []
- `config.typ` : 配置文件,包括封面的信息在这里。
- `content.typ` : 只需在此处添加内容
- `lib.typ` : 库文件,导入第三方库请在这导入
- `main.typ` : 编译入口,导入第三方库时有可能需要把`#show`放在此处
- `theme.typ` : 主题文件,可自行修改样式
# 使用方法
1. vscode下载插件`Typst LSP`,`Tinymist Typst`,`Typst Sync`。
2. 打开本项目,在`main.typ`中点击`preview`。若在`content.typ`中点击`preview`,则预览类似`markdown`的文档排版。
# 注意事项
1. 在使用时,`config.typ` 应作为顶层文件被其他文件导入,避免交叉导入。
# 自定义模板
1.
# 组件说明 (见doc中的文档)
# 其他说明
有空再写代码注释 |
|
https://github.com/AnsgarLichter/hka-thesis-template | https://raw.githubusercontent.com/AnsgarLichter/hka-thesis-template/main/supplementary/abstract.typ | typst | #import "../common/todo.typ": *
#heading(outlined: false, numbering: none, "Abstract")
#todo("Abstract") |
|
https://github.com/loicreynier/sandbox | https://raw.githubusercontent.com/loicreynier/sandbox/main/typst-demo/README.md | markdown | The Unlicense | # `typst-demo`
Sandbox article written using [Typst](https://typst.app) to test its features.
## About
Article body has been generated using ChatGPT with the following prompt:
> Write a scientific article on isotropic turbulence
> caused by a dragon's fire breath,
> employing different formulas for the wyvern's fire energy spectra
> and the dragon's fire energy spectra.
> The article should be composed in a world where dragons exist.
> Formulas for the energy spectra must be provided.
|
https://github.com/alberto-lazari/cns-report | https://raw.githubusercontent.com/alberto-lazari/cns-report/main/conclusions.typ | typst | = Conclusions <conclusions>
In our work, we showed how the process of fuzz testing mobile application using QR codes described in @carboni2023if can be improved. Our contribution is about the complete virtualization of the testing process, making it significantly more scalable and efficient.
Previously, fuzz testing mobile applications with QR codes has been performed by relying on physical devices, which pose several challenges such as difficult setup process, camera overheating issues, and scalability issues. By virtualizing the testing environment, we effectively eliminated these critical aspects.
Overall, our approach to virtualizing the fuzz testing process not only addressed the critical issues associated with physical devices but also significantly enhanced the scalability, efficiency, and effectiveness of QR fuzz testing enabling researchers and developers to conduct tests at scale. |
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/packages/physics.md | markdown | MIT License | # Physics
## `physica`
> Physica (Latin for _natural sciences_) provides utilities that simplify
> otherwise complex and repetitive mathematical expressions in natural sciences.
> Its [manual](https://github.com/Leedehai/typst-physics/blob/master/physica-manual.pdf)
> provides a full set of demonstrations of how the package could be helpful.
### Mathematical physics
The [packages/math.md](./math.md#common-notations) page has more examples on its
math capabilities. Below is a preview that may be of particular interest in the
domain of physics:
* Calculus: differential, ordinary and partial derivatives
* Optional function name,
* Optional order number or array of order numbers,
* Customizable "d" symbol and product joiner (say, exterior product),
* Overridable total order calculation,
* Vectors and vector fields: div, grad, curl,
* Taylor expansion,
* Dirac braket notations,
* Tensors with abstract index notations,
* Matrix transpose and dagger (conjugate transpose).
* Special matrices: determinant, (anti-)diagonal, identity, zero, Jacobian,
Hessian, etc. <!-- TODO Add rotation and gram matrices in physica:0.9.2 -->
A partial glimpse:
```typ
#import "@preview/physica:0.9.1": *
#show: super-T-as-transpose // put in a #[...] to limit its scope...
#show: super-plus-as-dagger // ...or use scripts() to manually override
$ dd(x,y,2) quad dv(f,x,d:Delta) quad pdv(,x,y,[2i+1,2+i]) quad
vb(a) va(a) vu(a_i) quad mat(laplacian, div; grad, curl) quad
tensor(T,+a,-b,+c) quad ket(phi) quad A^+ e^scripts(+) A^T integral^T $
```
### Isotopes
```typ
#import "@preview/physica:0.9.1": isotope
// a: mass number A
// z: the atomic number Z
$
isotope(I, a:127), quad isotope("Fe", z:26), quad
isotope("Tl",a:207,z:81) --> isotope("Pb",a:207,z:82) + isotope(e,a:0,z:-1)
$
```
### Reduced Planck constant (hbar)
In the default font, the Typst built-in symbol `planck.reduce` looks a bit off:
on letter "h" there is a slash instead of a horizontal bar, contrary to the
symbol's colloquial name "h-bar". This package offers `hbar` to render the
symbol in the familiar form. Contrast:
```typ
#import "@preview/physica:0.9.1": hbar
$ E = planck.reduce omega => E = hbar omega, wide
frac(planck.reduce^2, 2m) => frac(hbar^2, 2m), wide
(pi G^2) / (planck.reduce c^4) => (pi G^2) / (hbar c^4), wide
e^(frac(i(p x - E t), planck.reduce)) => e^(frac(i(p x - E t), hbar)) $
```
## `quill`: quantum diagrams
> See [documentation](https://github.com/Mc-Zen/quill/tree/main).
```typ
#import "@preview/quill:0.2.0": *
#quantum-circuit(
lstick($|0〉$), gate($H$), ctrl(1), rstick($(|00〉+|11〉)/√2$, n: 2), [\ ],
lstick($|0〉$), 1, targ(), 1
)
```
```typ
#import "@preview/quill:0.2.0": *
#let ancillas = (setwire(0), 5, lstick($|0〉$), setwire(1), targ(), 2, [\ ],
setwire(0), 5, lstick($|0〉$), setwire(1), 1, targ(), 1)
#quantum-circuit(
scale-factor: 80%,
lstick($|ψ〉$), 1, 10pt, ctrl(3), ctrl(6), $H$, 1, 15pt,
ctrl(1), ctrl(2), 1, [\ ],
..ancillas, [\ ],
lstick($|0〉$), 1, targ(), 1, $H$, 1, ctrl(1), ctrl(2),
1, [\ ],
..ancillas, [\ ],
lstick($|0〉$), 2, targ(), $H$, 1, ctrl(1), ctrl(2),
1, [\ ],
..ancillas
)
```
```typ
#import "@preview/quill:0.2.0": *
#quantum-circuit(
lstick($|psi〉$), ctrl(1), gate($H$), 1, ctrl(2), meter(), [\ ],
lstick($|beta_00〉$, n: 2), targ(), 1, ctrl(1), 1, meter(), [\ ],
3, gate($X$), gate($Z$), midstick($|psi〉$)
)
``` |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/gallery/test6.typ | typst | Apache License 2.0 | #import "@preview/cetz:0.2.2": draw, vector
#import "../src/lib.typ": *
#set page(width: auto, height: auto, margin: .5cm)
#circuit({
element.multiplexer(
x: 10, y: 0, w: 1, h: 6, id: "ResMux",
entries: ("000", "001", "010", "011", "101"),
h-ratio: 90%,
fill: util.colors.blue
)
element.extender(
x: (rel: -3, to: "ResMux.west"),
y: (from: "ResMux-port-in4", to: "out"),
w: 2, h: 1, id: "Ext",
name: "Zero Ext",
name-anchor: "south",
fill: util.colors.green
)
gates.gate-or(
x: (rel: -2, to: "ResMux.west"),
y: (from: "ResMux-port-in3", to: "out"),
w: 1, h: 1, id: "Or"
)
gates.gate-and(
x: (rel: -2, to: "ResMux.west"),
y: (from: "ResMux-port-in2", to: "out"),
w: 1, h: 1, id: "And"
)
element.alu(
x: (rel: -2.5, to: "Ext.west"),
y: (from: "ResMux-port-in0", to: "out"),
w: 1.5, h: 3, id: "Add",
name: text("+", size: 1.5em),
name-anchor: "name",
fill: util.colors.pink
)
element.multiplexer(
x: (rel: -1.5, to: "Add.west"),
y: (from: "Add-port-in1", to: "out"),
w: 0.5, h: 1.5, id: "NotMux",
h-ratio: 80%,
fill: util.colors.blue
)
gates.gate-not(
x: (rel: -2, to: "NotMux.west"),
y: (from: "NotMux-port-in1", to: "out"),
w: 1, h: 1, id: "Not"
)
draw.hide(
draw.line(name: "l1",
"Not-port-in0",
(rel: (-2, 0), to: ()),
(horizontal: (), vertical: "NotMux-port-in0")
)
)
let b = "l1.end"
draw.hide(
draw.line(name: "l2",
b,
(horizontal: (), vertical: "Add-port-in2")
)
)
let a = "l2.end"
wire.wire("wB0", (b, "NotMux-port-in0"), bus: true)
wire.wire(
"wB1", (b, "Not-port-in0"),
style: "zigzag",
zigzag-ratio: 1.5,
bus: true
)
wire.wire(
"wB2", (b, "And-port-in0"),
style: "zigzag",
zigzag-ratio: 1,
bus: true
)
wire.wire(
"wB3", (b, "Or-port-in0"),
style: "zigzag",
zigzag-ratio: 1,
bus: true
)
wire.intersection("wB1.zig")
wire.intersection("wB2.zig")
wire.intersection("wB2.zag")
wire.wire("wNot", ("Not-port-out", "NotMux-port-in1"), bus: true)
wire.wire("wAddA", ("NotMux-port-out", "Add-port-in1"), bus: true)
wire.wire("wA0", (a, "Add-port-in2"), bus: true)
wire.wire(
"wA1", (a, "And-port-in1"),
style: "zigzag",
zigzag-ratio: 0.5,
bus: true
)
wire.wire(
"wA2", (a, "Or-port-in1"),
style: "zigzag",
zigzag-ratio: 0.5,
bus: true
)
wire.intersection("wA1.zig")
wire.intersection("wA1.zag")
wire.wire("wMux0", ("Add-port-out", "ResMux-port-in0"), bus: true)
wire.wire(
"wMux1", ("Add-port-out", "ResMux-port-in1"),
style: "zigzag",
zigzag-ratio: 2,
bus: true
)
wire.wire("wMux2", ("And-port-out", "ResMux-port-in2"), bus: true)
wire.wire("wMux3", ("Or-port-out", "ResMux-port-in3"), bus: true)
wire.wire("wMux4", ("Ext-port-out", "ResMux-port-in4"), bus: true)
wire.wire(
"wAdd", ("Add-port-out", "Ext-port-in"),
style: "zigzag",
zigzag-ratio: 0.5,
bus: true
)
wire.intersection("wMux1.zig")
wire.intersection("wAdd.zig")
let c = (rel: (0, 2), to: "ResMux.north")
wire.wire("wResCtrl", (c, "ResMux.north"), bus: true)
wire.wire(
"wAddCtrl", (c, "Add.north"),
style: "zigzag",
zigzag-dir: "horizontal"
)
let d = (rel: (1, 0), to: "ResMux-port-out")
wire.wire("wRes", ("ResMux-port-out", d), bus: true)
draw.content(
"wAddCtrl.zag",
[ALUControl#sub("[1]")],
anchor: "south-west",
padding: 3pt
)
wire.wire(
"wCout", ("Add.south", (horizontal: (), vertical: "Ext.north-east"))
)
draw.content(
"wCout.end",
[C#sub("out")],
angle: 90deg,
anchor: "east",
padding: 3pt
)
draw.content(
a,
[A],
angle: 90deg,
anchor: "south",
padding: 3pt
)
draw.content(
b,
[B],
angle: 90deg,
anchor: "south",
padding: 3pt
)
draw.content(
c,
[ALUControl#sub("[2:0]")],
angle: 90deg,
anchor: "west",
padding: 3pt
)
draw.content(
d,
[Result],
angle: 90deg,
anchor: "north",
padding: 3pt
)
draw.content(
("wAdd.zig", 0.2, "wAdd.zag"),
text("[N-1]", size: 0.8em),
angle: 90deg,
anchor: "north-east",
padding: 3pt
)
}) |
https://github.com/kaarmu/splash | https://raw.githubusercontent.com/kaarmu/splash/main/src/palettes/typst-highlighting.typ | typst | MIT License | /* Typst Syntax Highlighting Colors
*
* Source: https://github.com/typst/typst, file: library/src/text/raw.rs
* Accessed: 2023-03-31, 9414d56f97c5be71d9c37abb0fd1632a76bde995
*/
// FIXME: These names are a bit weird
#let typst-highlighting = (
comment : rgb("#8a8a8a"),
escape-character : rgb("#1d6c76"),
markup : rgb("#818181"),
math-punctuation : rgb("#298e0d"),
math-operator : rgb("#1d6c76"),
list-punctuation : rgb("#8b41b1"),
label : rgb("#1d6c76"),
reference : rgb("#1d6c76"),
keyword : rgb("#d73a49"),
language-constant : rgb("#d73a49"),
language-variable : rgb("#d73a49"),
storage-modifier : rgb("#d73a49"),
storage-type : rgb("#d73a49"),
constant : rgb("#b60157"),
string : rgb("#298e0d"),
function-variable : rgb("#4b69c6"),
support : rgb("#4b69c6"),
entity : rgb("#4b69c6"),
macro-support : rgb("#16718d"),
meta-annotation : rgb("#301414"),
other-entity : rgb("#8b41b1"),
meta-interpolation : rgb("#8b41b1"),
)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/numbering-02.typ | typst | Other | #set text(lang: "he")
#for i in range(9, 21, step: 2) {
numbering("א.", i)
[ עבור #i \ ]
}
|
https://github.com/paugarcia32/CV | https://raw.githubusercontent.com/paugarcia32/CV/main/modules/certificates.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Certificates")
#cvHonor(
date: [2022],
title: [Google Cybersecurity Professional Certificate],
issuer: [Coursera],
) |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-28.typ | typst | Other | // Error: 3-7 cannot mutate a constant: rect
#(rect = "hi")
|
https://github.com/ShapeLayer/ucpc-solutions__typst | https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/examples/2024-gist-algorithm-masters-solutions.typ | typst | Other | #import "@preview/ucpc-solutions:0.1.0" as ucpc
#import ucpc.presets: difficulties as lv
// Definitions
#let primary_color = rgb("#2c2e35")
#let secondary-color = rgb("#de3624")
#let gist_color = rgb("#ff3e29")
#let name(_name, _super) = {
_name + " " + super(_super)
}
#let KMG = name("<NAME>", "@JNU " + `jjkmk1013`)
#let PJH = name("<NAME>", "@JNU " + `belline0124`)
#let SHG = name("<NAME>", "@GIST " + `invrtd_h`)
#let LYS = name("<NAME>", "@JNU " + `lys9546`)
#show: ucpc.ucpc.with(
title: "2024 GIST Algorithm Masters",
authors: ("2024 GIST Algorithm Masters TF"),
hero: ucpc.utils.make-hero(
title: [#text(fill: secondary-color)[G]IST \ ALGORITHM \ MASTERS],
subtitle: [\
#text(fill: rgb("#ffffff"), size: 20pt)[2024 Contest\
Official Solutions Editorial]],
bgcolor: primary_color,
height: 70%,
authors: ("2024 GIST Algorithm Masters TF"),
)
)
#ucpc.utils.make-prob-overview(
[A], [Printing GIST], lv.easy, SHG,
[B], [Matching Couple Ring], lv.easy, PJH,
[C], [FOCUS], lv.normal, SHG,
[D], [Binary Grid], lv.normal, SHG,
[E], [Making ChatGPT], lv.hard, SHG,
[F], [Infinitely Popping Bubbles in a Bottle], lv.hard, [#SHG\
#LYS],
[G], [Copying Money], lv.hard, [#SHG\
#KMG],
[H], [Elementary Wizardry], lv.challenging, SHG,
[I], [Operating DevNight], lv.challenging, SHG
)
#pagebreak()
#text(size: 20pt)[
= #text(size: 1.35em, fill: primary_color)[Note]
#align(horizon)[
#list(marker: [»])[We excluded cheating participants from the first solver statistics.]
#list(marker: [»])[This document was originally written in Korean. This document was machine translated from the Korean document and then reviewed by a non-English speaker.]
]
]
#pagebreak()
#ucpc.utils.problem(
id: "A",
title: "Printing GIST",
tags: ("implementation", "string", ),
difficulty: lv.easy,
authors: (SHG, ),
stat-open: (
submit-count: 115,
ac-count: 103,
ac-ratio: 90.435,
first-solver: `riroan`,
first-solve-time: 1,
),
stat-onsite: (
submit-count: 128,
ac-count: 51,
ac-ratio: 39.844,
first-solver: name("<NAME>", "@JNU"),
first-solve-time: 2,
),
pallete: (
primary: primary_color,
secondary-color: white,
),
[
- Implement the formula presented in the problem as is.
- Most programming languages use 0-based index, but you should keep in mind that matrices use 1-based index.
- Implement the following equation:
$ Y = (y_(i j)), y_(i j) = x_(floor(i/K)floor(j/K)) $
- Another way is to add 1 space of padding in the data, implement it as a 1-based index, and then cut the padding when output.
]
)
#ucpc.utils.problem(
id: "B",
title: "Matching Couple Ring",
tags: ("implementation", "hash-map", ),
difficulty: lv.easy,
authors: (PJH, ),
stat-open: (
submit-count: 111,
ac-count: 77,
ac-ratio: 70.270,
first-solver: `riroan`,
first-solve-time: 2,
),
stat-onsite: (
submit-count: 165,
ac-count: 41,
ac-ratio: 24.848,
first-solver: name("<NAME>", "@JNU"),
first-solve-time: 7,
),
pallete: (
primary: primary_color,
secondary-color: white,
),
[
- For each ring feature given as input, the goal is to find the ring feature that appears exactly twice.
- The correct solution is to create and utilize key-value pairs with the ring feature as the key and the set of the number of appearances of the ring feature and the name of the person wearing the ring as the values.
- Because the concept of key-value pairs and how to deal with them are less difficult, solving this problem without dealing with key-value pairs is more difficult. Therefore, we did not specifically block the processing of simple loop statements without using key-value pairs.
]
)
#ucpc.utils.problem(
id: "C",
title: "FOCUS",
tags: ("implementation", "bitmasking", ),
difficulty: lv.normal,
authors: (SHG, ),
stat-open: (
submit-count: 75,
ac-count: 51,
ac-ratio: 69.333,
first-solver: `edwardblue`,
first-solve-time: 5,
),
stat-onsite: (
submit-count: 113,
ac-count: 36,
ac-ratio: 31.858,
first-solver: name("<NAME>", "@GIST"),
first-solve-time: 16,
),
pallete: (
primary: primary_color,
secondary-color: white,
),
[
- *Subtask 1*: Count the number of 3, and if there is an odd number, key $0$ is in $P_1$, key $1$ is in $P_0$, and all remaining keys remain in place. If there is an even number, all the keys are in place.
- *Subtask 2 & 3*: There are two solutions.
- *Bitmasking solution*: Use the bit operation x & (1 << i) to store all information about which bit is turned on, and then swap only when the number of bits turned on is 2.
- *Preprocessing solution*: After declaring an array $"arr"$ of length 256, find the value of $2^i + 2^j$ for all $0 <= i < j <= 7$ and use $"arr"[ 2^i + 2^j] = (i, j)$.
]
)
#ucpc.utils.problem(
id: "D",
title: "Binary Grid",
tags: ("dp", ),
difficulty: lv.normal,
authors: (SHG, ),
stat-open: (
submit-count: 84,
ac-count: 34,
ac-ratio: 40.476,
first-solver: `hyperbolic`,
first-solve-time: 9,
),
stat-onsite: (
submit-count: 81,
ac-count: 20,
ac-ratio: 24.691,
first-solver: name("<NAME>", "@JNU"),
first-solve-time: 26,
),
pallete: (
primary: primary_color,
secondary-color: white,
),
[
- *Subtask 1*: Complete search. Unfortunately, it is not much easier than solving *Subtask 3*.
- *Subtask 2*: Collect numbers by following the diagonal line.
- *Subtask 3*: If you store the maximum binary number $M = M[i][j]$ that can be obtained when reaching every cell, the following ignition equation is established. So DP can solve your problem.
$M[i][j] = 2 times max(M[i - 1][j], M[i][j - 1]) + D[i][j]$
($D[i][j]$ is the number written in the row $i$ and column $j$ (0-based index))
]
)
#ucpc.utils.problem(
id: "E",
title: "Making ChatGPT",
tags: ("implementation", "graph_theory", ),
difficulty: lv.hard,
authors: (SHG, ),
stat-open: (
submit-count: 128,
ac-count: 18,
ac-ratio: 17.969,
first-solver: `iktk`,
first-solve-time: 25,
),
stat-onsite: (
submit-count: 199,
ac-count: 7,
ac-ratio: 3.518,
first-solver: name("<NAME>", "@JNU"),
first-solve-time: 70,
),
pallete: (
primary: primary_color,
secondary-color: white,
),
[
- *Subtask 1*: You can implement the fingerprint almost as is.
- The fingerprint states that whenever a letter $c$ is given, all letters $c$ within the training corpus are searched. However, since there are only 29 characters, the search results for all 29 characters are preprocessed. It is recommended to leave it there.
- After preprocessing, each time a character comes in, the next character can be predicted in $O(1)$. Implementing this frees up subtask 1. Time complexity is $O(S+K)$. ($S$ is the size of the training corpus)
#pagebreak()
- *Subtask 2*: If the index exceeds a certain value, you need to determine that there is periodicity in the string.
- Let's assume that the length of the generated sentence $s$ is 30 or more. 29 characters that can appear, so at least 2 of the 30 characters must be the same.
- Let's find this and say $s[i] = s[j]$. Then $s[i + 1] = s[j + 1]$, $s[i + 2] = s[j + 2]$, $...$, etc. all hold true. Therefore, the string has periodicity, and the length of the string is infinite.
- If the length of the string is infinite, the $K$th character can be found in $O(1)$ through modulo operation.
- If the length of the string is finite, then by the above argument its length is less than or equal to 29. Therefore, if the input $K$ is more than 30, print a dot (`.`).
- It should be noted that there may not be any special periodicity at the beginning of the string.
- For example, given a training corpus {[gisss]} containing 1 sentence, the generated string is [gissssssss...
- Time complexity is $O(S)$.
]
)
#ucpc.utils.problem(
id: "F",
title: "Infinitely Popping Bubbles in a Bottle",
tags: ("simulation", "ad-hoc", "(hashmap)", ),
difficulty: lv.hard,
authors: (SHG, LYS, ),
stat-open: (
submit-count: 25,
ac-count: 11,
ac-ratio: 48.000,
first-solver: `hyperbolic`,
first-solve-time: 14,
),
stat-onsite: (
submit-count: 24,
ac-count: 0,
ac-ratio: 0.000,
first-solver: "-"
),
pallete: (
primary: primary_color,
secondary-color: white,
),
[
- *Subtask 1*: Proceed with the simulation by scanning the entire array every second. Time complexity is $O(N T)$.
- *Subtask 2*: If you think about how high the bubbles created in the 1st zone can go, it doesn't go up that. Even if 100,000 bubbles are created in the first zone, the number of bubbles decreases to $1$/$5$ every time you go up one zone, so if you repeat this, the number of bubbles quickly becomes 0. \
\
Therefore, we find the area that the bubbles generated in the first area cannot reach, then exclude that area and run the simulation. At this time, since the number of non-excluded regions is about $O(log M)$, the time complexity is $O(T log M)$.
#pagebreak()
- *Subtask 3*: This task requires generalizing the solution of Subtask 2.
- Let us assume that bubble generation occurs only once at location $y=Y$ at time $T=0$.
- List the (time, location) pairs affected by this bubble generation. Then:
- $(0, Y)$ \\ $(1, Y-1), (1, Y), (1, Y+1)$ \\ $(2, Y-2), (2, Y-1 ), (2, Y), (2, Y+1), (2, Y+2)$ \\ ...
- Likewise, since the number of bubbles decreases exponentially, there is a limit to the number of (time, position) pairs that can be affected. Its size is approximately $O(log^2 M)$.
- In areas not affected by bubble generation, the number of bubbles is always $0$.
- Therefore, you only need to manage $O(T log^2 M)$ cells affected by $T$ number of bubbles.
- You can think of a way to use HashMap, etc. to manage only cells with a positive number of bubbles, excluding cells with 0 bubbles.
- There is also a solution that does not use HashMap, but it runs much faster than the fixed solution.
- Time complexity is $O(T log^2 M)$.
]
)
#ucpc.utils.problem(
id: "G",
title: "Copying Money",
tags: ("bellman-ford", "parametric-search", ),
difficulty: lv.hard,
authors: (KMG, SHG, ),
stat-open: (
submit-count: 27,
ac-count: 5,
ac-ratio: 18.519,
first-solver: `aeren`,
first-solve-time: 58,
),
stat-onsite: (
submit-count: 0,
ac-count: 0,
ac-ratio: 0.000,
first-solver: "-"
),
pallete: (
primary: primary_color,
secondary-color: white,
),
[
- Transactions can be modeled as graphs.
- If a customer changes item A to item B and loses $c$ in the process, let's give an edge with weight $c$ from A to B.
- On the contrary, if the customer gains $c$, let's give an edge with weight $-c$ from A to B.
- In the case of information transactions 1 and 2 where only one item is involved in the transaction process, let's fill in the empty space with item 0.
#pagebreak()
- Now, this problem is replaced with the problem of finding negative cycles.
- We can use the Bellman-Ford algorithm, which is an algorithm for finding negative cycles.
- However, if the customer does not have enough money, there are cases where a specific edge cannot be used, so to be exact, we will use an algorithm that slightly modifies Bellman-Ford. In the modified algorithm, edge propagation does not occur if the customer does not have enough money.
- Using the modified algorithm, we can determine whether the customer can reach a negative cycle with the initial funds of $c$. The validity of the algorithm can be proven by modifying the proof that the standard Bellman-Ford algorithm can legitimately determine the existence of negative cycles.
#pagebreak()
- Finally, the minimum amount of money needed to reach a negative cycle can be implemented using binary search. If you can reach a negative cycle with an initial fund of $c$, you can do it with $c+1$, and if you cannot reach a negative cycle with an initial fund of $d$, you cannot do it with $d-1$.
- The time complexity is (Bellman-Ford time complexity) $times$ (Binary search time complexity) = $O(M N log C)$.
#pagebreak()
*Appendix*: Let's prove the validity.
- *Argument*. The problem situation can be modeled as DP.
- Let $"dp"[i][j]$ be the largest amount of money that can be held when reaching the item $i$ using at most $j$ exchanges. - Base case is defined as $"dp"[0][0] = c, "dp"[i][0] = -infinity (i >= 1)$. $c$ is the initial capital.
- In this case, the following formula holds: \
$"dp"[i][j] = max("dp"[i][j - 1], max_(v in S) ("dp"[v][j - 1] + "cost"[v][i]))$
- In this case, the set $S$ is the set of all $v$s that have an edge from $v$ to $i$ and that make $"dp"[v][j - 1] + "cost"[v][i]$ greater than or equal to $0$.
#pagebreak()
- *Claim*. If the DP table is updated after the algorithm has been performed for $n+1$ rounds, then there is a positive cycle in this graph and the cycle is accessible from vertex $0$. - The reason why we use $n+1$ here is because the number of vertices in the graph is $n+1$.
- *Proof*. The update of the value of vertex $v$ means that one of the vertices with an edge to vertex $v$ was updated in the previous round. If we repeat this backtracking, we will eventually form a path starting from vertex $0$, which is the only vertex with a non-$-infinity$ value in the $0$th round, and going to vertex $v$, which is updated in the $n+1$th round. By the pigeonhole principle, this path must have a cycle. Since an update always increases a value, the value assigned to the vertex must increase after one round of this cycle. Therefore, this cycle is a positive cycle.
#pagebreak()
- *Argument*. If the DP table is not updated when the algorithm is performed for $k$ rounds, the DP table will not be updated even when the algorithm is performed for $k+1$ rounds.
- *Proof*. If no update occurs in round $k$, then $"dp"[i][k] = "dp"[i][k - 1] >= max_(v in S) "dp"[v][k - 1] + "cost"[v][i]$ and vice versa. Now
$"dp"[i][k + 1] = max("dp"[i][k], max_(v in S) ("dp"[v][k] + "cost"[v][i])) \
= max("dp"[i][k - 1], max_(v in S) ("dp"[v][k - 1] + "cost"[v][i])) \
= "dp"[i][k - 1] = "dp"[i][k]$
We get
- *Assertion*. When the DP table is not updated after the algorithm has been performed for $n+1$ rounds, money duplication is impossible. Since the DP table will never be updated in the future according to the above claim, the maximum amount of money that can be earned at each vertex is determined.
]
)
#ucpc.utils.problem(
id: "H",
title: "Elementary Wizardry",
tags: ("sorting", "greedy", ),
difficulty: lv.challenging,
authors: (SHG, ),
stat-open: (
submit-count: 9,
ac-count: 6,
ac-ratio: 66.667,
first-solver: `chmpro`,
first-solve-time: 70,
),
stat-onsite: (
submit-count: 0,
ac-count: 0,
ac-ratio: 0.000,
first-solver: "-"
),
pallete: (
primary: primary_color,
secondary-color: white,
),
[
- *Subtask 1*: Use brute force. It looks like there are 100 million possible $x$-coordinates and 100 million possible $y$-coordinates for the top right point of the magic circle, but in reality, we only need to look at $N^2$ cases where the $x$-coordinate matches the $x$-coordinate of some magic circle and the $y$-coordinate matches the $y$-coordinate of some magic circle. Therefore, we can solve the problem with a time complexity of $O(N^3)$.
- *Subtask 2*: Since the $y$-coordinates of the points are all the same, we sort the points by $x$-coordinate and continue to increase the $x$-coordinates until the magic circle includes all the colored magic circles. The time complexity is the time complexity of sorting, $O(N log N)$.
#pagebreak()
- *Subtask 3*: Let's extend the logic of *Subtask 2*. Let's say the magic circle is a part surrounded by four lines $x = 0, x = X, y = 0, y = Y$. When the value of $Y$ is fixed, maximizing the power of the magic circle can be done using the same logic of *Subtask 2*. We keep increasing the value of $X$, and when we can no longer increase it, we try to decrease the value of $Y$.
- The reason why this algorithm is possible is that when the value of $Y$ is fixed, the maximum value of $X$, $X_max (Y)$, is a non-decreasing function.
- Each time we decrease the value of $Y$, we need to decide which point will be removed from the magic circle. Since the $y$ coordinates of the magic circle are removed in order of increasing value, we can create a PQ that manages all the points in the magic circle and can pass with the time complexity $O(N log N)$.
]
)
#ucpc.utils.problem(
id: "I",
title: "Operating DevNight",
tags: ("dijkstra", ),
difficulty: lv.challenging,
authors: (SHG, ),
stat-open: (
submit-count: 20,
ac-count: 5,
ac-ratio: 25.000,
first-solver: `chmpro`,
first-solve-time: 97,
),
stat-onsite: (
submit-count: 0,
ac-count: 0,
ac-ratio: 0.000,
first-solver: "-"
),
pallete: (
primary: primary_color,
secondary-color: white,
),
[
- *Subtask 1*: If you run Dijkstra's algorithm once for a starting vertex, you can find out the length of the shortest path to all other vertices. Therefore, you can run Dijkstra's algorithm once for each of the $K$ communication rooms as a starting point.
- When Dijkstra's algorithm is implemented in $O(M log M)$, the time complexity is $O(K M log M)$. Subtask 1 is sufficient because $K$ is small.
- *Subtask 2*: After creating a path, sweep along the path and manage up to 2 communication rooms on both sides of each vertex. The second closest communication room is one of the 4, 2 on the left and 2 on the right of each conference room.
#pagebreak()
- *Subtask 3*: In addition to the solution explained in the editorial, there is one more solution for the reviewer. The reviewer's solution is probably easier. - Some prior knowledge of Dijkstra's algorithm is required.
- *Multisource Dijkstra*: Let's assume that there are multiple starting vertices and that you can start from any of them. Even in this situation, you can find the length of the shortest path to the destination vertex.
- *Proof*: You can prove this by replacing Multisource Dijkstra with the equivalent Standard Dijkstra problem. Let's randomly add a vertex and connect that vertex and all starting vertices with a unidirectional edge of length 0. Then, let's make the added vertex the new starting vertex.
#pagebreak()
- The problem requires the shortest path from each conference room to one of the communication rooms, but from the perspective of Multisource Dijkstra, it is more efficient to think of the shortest path from one of the communication rooms to each conference room. Therefore, from now on, we will call the communication room the starting vertex.
#pagebreak()
- *Shortest Path Tree*: A tree consisting of the shortest paths starting from the root node to each vertex.
- The Shortest Path Tree always exists and can be obtained during the process of running Dijkstra's algorithm. In each round of the algorithm, the vertex with the smallest assigned value among the vertices whose shortest path length is not yet determined is determined.
- At this time, the newly determined vertex may have been influenced by one of the vertices whose shortest path length has already been determined. If so, connect the influenced vertex and the influenced vertex.
- The shortest Path Tree is not unique. However, in this problem, people prefer communication rooms with smaller vertex numbers when the shortest path length is the same, so the Shortest Path Tree is unique.
#pagebreak()
- Multisource Dijkstra also has something similar to Shortest Path Tree. However, this time, it exists as a Forest (with multiple Trees) instead of a Tree. If you remove the vertex added in the proof above, you can obtain a Forest.
- At this time, *each forest has only one of several starting vertices (communication rooms) as its root node.*
- You can group the vertices based on which forest they belong to.
#pagebreak()
- Now, let's think about a set of vertices $V_k$ that have the $k$th communication room as their root node.
- We need to find the closest communication room among the communication rooms that are *not* the $k$th communication room for all vertices in $V_k$.
- You can do this by running Dijkstra again with the vertices adjacent to $V_k$ as the starting point. When you push the adjacent vertices to pq, you also include the length of the shortest path.
- For example, let's say that the vertices adjacent to $V_k$ are vertices 10 and 11, and the distance from vertex 10 to the closest communication room is 100, and the distance from vertex 11 to the closest communication room is 110. Then, we first put (10, 100) and (11, 110) in PQ.
#pagebreak()
- We can prove that this algorithm works in the same way as the standard Dijkstra by creating a new vertex and connecting the starting vertices to that vertex, just like the proof of multisource Dijkstra. The distance of the newly created edges is the distance to the nearest communication room.
- We just need to run Dijkstra for all $V_k$.
- If we run dijkstra $K$ times like this, the time complexity will be $O(K M log M)$. However, if we think about it carefully, we do not need information about the entire graph when we run Dijkstra once. We only need information about $V_k$, its adjacent vertices, and the edges between the vertices.
- In this regard, if we do a good job of optimizing the size of the graph, we can reduce the time complexity to $O(M log M)$.
]
)
|
https://github.com/rpitasky/typst-braid | https://raw.githubusercontent.com/rpitasky/typst-braid/main/README.md | markdown | The Unlicense | # typst-braid
Braid Group Visualization in Typst.
I wrote this in about an hour for a presentation; the output is not nearly as pretty as comparable tools using tikz, but the output is certainly workable. There are a number of configuration parameters available, their default values and concise explanations are given below.
```
strands: 0 // number of strands in the group
unit_width: 18pt // width separating each strand
unit_height: 40pt // height of an individual crossing
stroke: 2pt // weight of each line for under-crossings
bold_stroke: 4pt // weight of each line for over-crossings
curvature: 0.25 // allowed values between 0 and 1, higher values are more curvy
```
Example:
```typ
#braid(strands: 3)[$sigma_1 sigma_2^(-1) sigma_1 sigma_2^(-1)$]
#braid(strands: 2)[$sigma_1 sigma_1^(-1)$]
``` |
https://github.com/Functional-Bus-Description-Language/Specification | https://raw.githubusercontent.com/Functional-Bus-Description-Language/Specification/master/src/functionalities/param.typ | typst | == Param
The param functionality is an inner functionality of the proc and stream functionalities.
It represents a data fed to a procedure or streamed by a downstream.
The param functionality has following properties:
*`range`*` range | [range] (None) {definitive}`
#pad(left: 1em)[
The range property defines the range of valid values.
The range property on param behaves exactly the same as the range property on config.
]
*`width`*` integer (bus width) {definitive}`
#pad(left: 1em)[
The width property defines the bit width of the param.
]
#block(breakable: false)[
The following example presents the definition of a downstream with three parameters.
#pad(left: 1em)[
```fbd
Sum_Reduce stream
type param_t param; width = 16
a param_t
b param_t
c param_t
```
]
]
|
|
https://github.com/WinstonMDP/knowledge | https://raw.githubusercontent.com/WinstonMDP/knowledge/master/residue_field.typ | typst | #import "cfg.typ": cfg
#show: cfg
= Поля вычетов
Класс эквивалентности сравнимости по модулю $n$, содержащий целое число a, называется
вычетом числа $a$ по модулю $n$ и обозначается $[a]_n$.
Фактормножество множества $ZZ$ по отношению сравнимости по модулю $n$ обозначается через
$ZZ_n$.
$ZZ_n = {[0]_n, [1]_n, ..., [n - 1]_n}$
$ZZ_n$ - коммутативное ассоциативное кольцо с единицей. Оно назывется кольцом вычетов по
модулю $n$.
$ZZ_n$ - поле $<-> n$ - простое
$[k]_n$ обратим в $ZZ_n <-> (n, k) = 1$
В полях вычетов встречается новое явление, не имевшее место в числовых полях (подполях
комплексных чисел): в поле $ZZ_n$ выполняется $underbrace(1 + 1 + ... + 1, n) = 0$.
Наименьшее $n$, для которого это выполняется, называется характеристикой поля и
обозначается $"char" F$. Если такого $n$ не существует, то $"char" F = 0 $. Таким образом
характеристика числовых полей нулевая.
$underbrace(x + x + ... + x, "char" F) = (underbrace(1 + 1 + ... + 1, "char F"))x = 0$
$(a + b)^("char" F) = a^("char" F) + b^("char" F)$
Малая теорема Ферма: в $ZZ_p$ $x^p = x$.
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/visualize/gradient-sharp.typ | typst | Apache License 2.0 | // Test sharp gradients.
---
#square(
size: 100pt,
fill: gradient.linear(..color.map.rainbow, space: color.hsl).sharp(10),
)
#square(
size: 100pt,
fill: gradient.radial(..color.map.rainbow, space: color.hsl).sharp(10),
)
#square(
size: 100pt,
fill: gradient.conic(..color.map.rainbow, space: color.hsl).sharp(10),
)
---
#square(
size: 100pt,
fill: gradient.linear(..color.map.rainbow, space: color.hsl).sharp(10, smoothness: 40%),
)
#square(
size: 100pt,
fill: gradient.radial(..color.map.rainbow, space: color.hsl).sharp(10, smoothness: 40%),
)
#square(
size: 100pt,
fill: gradient.conic(..color.map.rainbow, space: color.hsl).sharp(10, smoothness: 40%),
)
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/3-methodology/study-2/mod.typ | typst | MIT License | #import "../../../lib/mod.typ": *
== #study.H-2.full.n <s.m.study-2>
This section covers the methodology for #study.H-2.prefix. The concept of internal and external iteration scheduling is described in @s.iteration-schedules. An experiment to test the effect of the introduced concept is presented and discussed in @s.r.study-2. These two complete research objectives #boxed(color: theme.green, [*O-2.1.1*]), while the corresponding results in @s.r.study-2 and the following discussion provides closure for #boxed(color: theme.green, [*O-2.2.1*]). Hereafter, different ideas for internally representing the graph are deliberated as an argument to objectives #boxed(color: theme.green, [*O-2.3.1*]) and #boxed(color: theme.green, [*O-2.3.2*]).
// The general approach for integrating global planning with the original approach by@gbpplanner is described in @s.m.global-planning. The results of the carried out method from this section are presented in @s.r.study-3.
#include "iteration-schedules.typ"
#include "graph-representation.typ"
|
https://github.com/jassielof/typst-templates | https://raw.githubusercontent.com/jassielof/typst-templates/main/apa7/README.md | markdown | MIT License | # APA 7th Edition Template for Typst
|
https://github.com/ToguyC/typst-packages | https://raw.githubusercontent.com/ToguyC/typst-packages/main/unige-simple-report/1.0.0/lib.typ | typst | #let config(
title: none,
authors: (),
abstract: [],
class: (),
doc,
) = {
set page(
header: context {
if counter(page).get().first() > 1 {
authors.first().name
h(1fr)
title
linebreak()
v(-9pt)
line(length: 100%, stroke: 0.5pt)
}
},
footer: context {
if counter(page).get().first() > 1 {
h(1fr)
"Page " + counter(page).display()
}
},
)
set heading(numbering: "1.a")
set align(center)
v(10pt)
text(18pt, smallcaps("Université de Genève"))
v(15pt)
text(14pt, smallcaps(class.name))
linebreak()
text(14pt, class.id)
v(15pt)
line(length: 100%, stroke: 2pt)
text(size: 18pt, weight: "bold")[#title]
line(length: 100%, stroke: 2pt)
v(15pt)
let count = authors.len()
let ncols = calc.min(count, 3)
grid(
columns: (1fr,) * ncols,
row-gutter: 24pt,
..authors.map(author => [
#author.name \
#author.affiliation \
#link("mailto:" + author.email)
])
)
v(4fr)
let date = datetime.today()
date.display("[month repr:long] [year]")
v(1fr)
image("images/unige_csd.png", width: 50%)
v(0.3fr)
pagebreak()
counter(page).update(2)
set align(left)
doc
}
|
|
https://github.com/xhalo32/constructive-logic-course | https://raw.githubusercontent.com/xhalo32/constructive-logic-course/master/slides/math-camp.typ | typst | #import "@preview/touying:0.4.2": *
#import "slidetheme.typ"
#let palette = (
rgb("#7287fd"), // lavender
rgb("#209fb5"), // sapphire
rgb("#40a02b"), // green
rgb("#df8e1d"), // yellow
rgb("#fe640b"), // peach
rgb("#e64553"), // maroon
)
#let math-palette = palette.map(c => c.darken(20%))
#show raw: slidetheme.colorize-code(palette)
#show math.equation: it => slidetheme.colorize-math(math-palette, it)
#set raw(syntaxes: "Lean4.sublime-syntax", theme: "Catppuccin Latte.tmTheme")
#set text(font: "Fira Sans", weight: "light", size: 20pt)
#show raw: it => block(
fill: rgb("#eff1f5"),
inset: 8pt,
radius: 12pt,
text(fill: rgb("#4c4f69"), it)
)
#let s = slidetheme.register(aspect-ratio: "16-9")
#let s = (s.methods.info)(
self: s,
title: [Matematiikkaa tietokoneavusteisesti],
subtitle: [Lean ja formaali todistaminen],
author: [<NAME> & <NAME>],
date: datetime.today(),
institution: [Aalto Math Camp 2024],
)
#let (init, slides, touying-outline, alert, speaker-note) = utils.methods(s)
#show: init
#show strong: alert
#let (slide, empty-slide, title-slide, new-section-slide, focus-slide) = utils.slides(s)
#show: slides
== Mikä on todistus?
- Mikä riittää matemaattisen ongelman ratkaisuksi?
- Milloin ollan perusteltu riittäväsi?
- Voiko perustelu olla *täydellinen*?
== Todistus?
Väite: Kaikkien kahden luonnollisen luvun $a, b$ summa on suurempaa, kuin kumpikaan luvuista.
Todistus: Tehdään induktiotodistus. Aloitetaan kantatapauksesta 1:
$a + 1 > a "ja" a + 1 > 1$, tämä on ilmiselvästi totta.
Seuraavaksi induktiivinen tapaus, jossa saadaan olettaa, että $a + b > a "ja" a + b > b$:
$a + b + 1 > a "ja" a + b + 1 > b + 1$ vasen puoli on selvästi totta, todistetaan oikea puoli:
$a + b + 1 > b + 1$, vähennetään molemmilta puolilta $1$ ja saadaan:
$a+b > b$, mikä saadaan suoraan induktio-oletuksista.
== Formalisointi
- Formaali kieli esitetään merkkijonona, eli tekstinä, jonka käsittelylle on tarkat säännöt.
- Koodi on tekstiä ja koodin suorittamiselle on tarkat säännöt
$->$ Funktionaalinen ohjelmointi on formaalia.
- Matematiikkaa voidaan formalisoida ohjelmointikielillä, mikä mahdollistaa matematiikan tekemistä ja todistamista *tietokoneavusteisesti*.
== Todistusassistentit
- Tietokoneohjelma, joka ymmärtää formaalia matematiikkaa ja pystyy tarkistamaan sen korrektiutta.
- Seuraavat ovat yleisiä todistusassistentteja: *Lean*, Coq, Isabelle, Agda
== Lean
- Funktionaalinen, dependentisti tyypitetty ohjelmointikieli ja todistusassistentti.
#image("nng-demo.png") |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/page_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Set width and height.
// Should result in one high and one wide page.
#set page(width: 80pt, height: 80pt)
#[#set page(width: 40pt);High]
#[#set page(height: 40pt);Wide]
// Flipped predefined paper.
#[#set page(paper: "a11", flipped: true);Flipped A11]
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/055%20-%20Murders%20at%20Karlov%20Manor/004_Episode%204%3A%20Justice%20Before%20Mercy.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 4: Justice Before Mercy",
set_name: "Murders at Karlov Manor",
story_date: datetime(day: 10, month: 01, year: 2024),
author: "<NAME>",
doc
)
Teysa's body had yet to cool. When Kaya found the strength to move—when her frozen legs began responding to her commands, although her feet refused to quite solidify, bits of broken statue on the floor passed through them as she approached the desk—she crossed the office to her fallen friend, brushing her fingertips across Teysa's cheek. She was no stranger to death, hadn't been even before her time in Ravnica, and she knew what had to happen now. She also knew these might be the only moments she had to study the scene undisturbed before the rest of the household came rushing in.
Kaya circled the desk to Teysa's side, not letting herself touch the body again. Her claims of innocence would be easier to believe if she didn't have blood on her hands.
Teysa's expression was pained, which was to be expected but oddly peaceful, as if she had seen this coming on some level and been prepared to face it.
"Is this what you wanted to talk about?" Kaya asked. "Gods and monsters, Teysa, you could have called me sooner. You could have—we could have—whatever happened, it didn't have to. Whatever you did, we could have …" She stopped. Debating with the dead was only productive when the dead could answer back.
Most people who were going to return as ghosts didn't do so immediately upon their deaths. Loss of the physical body caused disorientation, and adapting to an insubstantial, spectral existence caused even more. Still, the more powerful the magic and will of the deceased, the more quickly they were likely to adapt. Grappling with the idea of a Ravnica that didn't contain Teysa troubled Kaya.
She wasn't a spirit medium, not really—her magic followed other channels—but she had been an Orzhov oligarch, and their dead recognized her authority, at least to the degree of being willing to speak with her. She straightened, reluctantly pulling herself away from the shell of her friend.
"<NAME>, I would speak with you," she said, forcing her voice not to tremble.
Teysa's ghost did not do her the courtesy of appearing.
Instead, a thinly sketched female figure drifted through one of the walls dressed in the simple attire of an Orzhov servant, clearly having been permitted passage by the house wards. She moved toward Kaya, hands folded demurely in front of herself.
"<NAME> is not entertaining guests at this time," she said, voice as much sigh as sound.
Kaya bit the inside of her cheek for a moment before saying, "I was invited. Is she going to be that rude?"
The ghost woman glanced up, briefly alarmed. "<NAME> is not entertaining guests at this time," she repeated.
"But you know where she is?"
The woman didn't reply. Kaya scowled.
"You #emph[do] know where she is?" If Teysa had been killed by a sufficiently powerful rival, her spirit could be imprisoned somewhere, ready to be exploited by her enemies.
The ghost woman looked down again. "<NAME> is not entertaining guests at this time."
This was getting old, fast. Kaya sighed. "Where is everyone, anyway? No one came to greet me or shake me down for bribes when I came in, and that's not right."
"Master Teysa gave the living servants the day off, in anticipation of your arrival."
"So you can say other things. That's good. Did you see what happened?"
"No," said the ghost. "You are the first living person I've seen since the staff was dismissed."
That didn't mean as much as it could have, but it was something. Kaya looked at Teysa's body again, refusing to allow herself the luxury of denial. "Who leads the Orzhov now?" she asked.
"Master Teysa remains our guildmaster," said the ghost. "Our charter makes no distinction between her current state and any other."
"I didn't kill her."
"We are aware." As the ghost spoke, more figures appeared around the edges of the room, half-sketched and unclear. "We will tell the lawmages and investigators who are bound to come that this was not a power struggle between past and present leaders; your innocence proves itself."
Kaya scoffed, stuffing the crumpled Phyrexian note into her pocket. Stealing evidence was wrong, but allowing anyone else to see it before she knew what had really been going on was somehow even worse. Despite all the evidence to the contrary, maybe Teysa had been innocent—of this at least, if she'd never been innocent of anything else in her life.
"Not everyone's going to think that," she said. "Teysa stole the guild out from under me while I was off-plane. Some people are going to assume I came to get my own back."
"Orzhov's dead know you didn't, and as she is still our master, we are all that matters here."
"Tell that to the law." Kaya knew a verity circle would clear her in an instant—but she didn't want to be questioned in the first place. She didn't want to be standing here, next to the body of her friend, with a note in Phyrexian script in her pocket. She wanted …
She wanted to run. That was the problem, and that was why she #emph[couldn't] run. Even if she didn't owe her presence to Ravnica, she owed it to Teysa.
She owed it to herself.
"When they come here, we will," the ghost who had come to her call averred.
Kaya sighed. "Then I'd best go tell them they need to be on their way. I know I don't give the orders, but please, don't let anyone in here unless it's the Agency or a representative from the Senate? Teysa deserves to be left with a little dignity."
The ghost hesitated before she replied, "We can do that."
"Thank you," Kaya said and walked past the ghosts, leaving the room—leaving Teysa—behind. As before, her feet phased with every step, passing cleanly through the ceramic shards littering the rug. When she reached the door, she paused, but didn't look back.
In the end, Kaya just kept walking.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The Agency headquarters were in chaos when Kaya arrived, having taken a hired carriage to get her there more quickly. She frowned at the scene, investigators swarming like hornets whose nest had just been kicked. They formed clumps, trading news and angry words, then split apart and came together again in new formations. It didn't look like much work was getting done. Whatever had them so upset seemed to take priority over everything else.
Kaya tipped her driver before heading for the waiting mounts intended to take guests up to the building, careful to avoid the densest clusters of agitated agents. None of the investigators she knew were in the crowd, and this wasn't the place to announce Teysa's murder. A few people glanced at her with varying degrees of curiosity and suspicion. She kept moving, riding her borrowed steed to the entrance and heading inside.
The security desk was currently unoccupied, and the halls buzzed with the same furious energy as the street. Kaya frowned again. Maybe something had happened while she was at Karlov Manor—something more than the death of a guild leader. If the Agency knew about Teysa, she never would have been able to make it up the stairs without someone at least asking her what she needed.
As there was no one to question her presence, she continued onward to Ezrim's office. The door was ajar, and raised voices came from inside, all talking over one another, until nothing distinct could be understood.
"Quiet!" snapped Ezrim, booming voice cutting across the commotion. "Yes, we have good reason to be angry, and yes, we were demeaned by people who have proven themselves as unprofessional as they accused us of being, but this serves nothing! Etrata is still missing. The Azorius seized our investigation right out from under us, locking us out of the investigative process as much as possible, only to lose our only suspect. Yelling at each other changes neither of these things."
"So what #emph[does] change them?" asked a voice Kaya didn't recognize.
"Doing. Our. Jobs." Ezrim spoke each word as if it were unbreakable law.
Commotion broke out again, louder than before, and Kaya began to turn away. She couldn't burst in and demand the position she'd previously declined; she needed to follow the rules. Flouting them in front of an archon was a good way to get ejected from the building, and she needed to be here. Still silent, she made her way back the way she had come.
The clusters of furiously arguing investigators had rearranged themselves into entirely new formations. Kaya scanned them as she walked, pausing when she caught a glimpse of a familiar head of dark hair. Kellan, the agent who had helped catch Etrata during the party. He was holding his own in an argument against three other investigators, clearly unhappy, but not yet moved to anger.
He was perfect.
"Apologies," said Kaya, inserting herself into their group and taking Kellan's arm. "I need him."
Kellan looked confused but didn't resist her pulling him away. The other investigators promptly closed the gap made by his absence, continuing their argument without missing a beat.
"Thank you for the save," he said, once they were far enough down the hall that the others wouldn't hear. "People are mad, and they're starting to say things they don't mean."
"What happened?"
"Detective Proft went to speak with the prisoner in Azorius custody. When he got there, she was gone. They can't tell us where she went. A few of them have even gone so far as to imply that Proft may have had something to do with her disappearance." Kellan sounded personally offended by this challenge to his colleague's honor. Then he paused, frowning. "Did you need something?"
#figure(image("004_Episode 4: Justice Before Mercy/01.png.jpg", width: 100%), caption: [Art by: <NAME>atos], supplement: none, numbering: none)
"Yes," said Kaya. "I need you to get me in to see Ezrim."
"He's a bit busy right now."
"Please. It's important."
Kellan blinked. "All right," he said. "He'll probably welcome the interruption."
When they reached the partially open door, Kellan knocked, a quick rap of his knuckles that silenced the ongoing argument. "Can I help you?" called Ezrim.
"Planeswalker Kaya is here, and says she needs to speak with you," said Kellan.
"Clear the room," barked Ezrim.
Several disgruntled Agency investigators trickled out of the office, some directing glares at Kaya and Kellan. More quietly, Ezrim called, "You may come in now."
Beckoning Kellan to follow, Kaya stepped into the office. Ezrim was settled behind his desk rather than astride his mount—which answered a few questions about archons, even as it raised several more—which was lounging on the pillows, watching the scene with sharp eyes. The office was otherwise in reasonable condition, with only a few out-of-place papers to indicate anything had happened.
"Close the door," said Ezrim.
Kellan did as asked, while Kaya stepped forward to face Ezrim.
"I changed my mind," she said. "I would like to take point on this investigation."
Silence stretched between them. Finally, Ezrim said, "You realize the situation has changed."
"I do. The investigator made me aware."
"Then you understand this will be substantially more difficult than it would have been when I first asked you."
"Yes."
"There is a chance the Azorius—"
"<NAME> has been murdered."
Ezrim stopped, shocked into silence.
Kaya took a step forward. "I found her body. I'm willing to submit to questioning within a verity circle to confirm I was not responsible. I'd gone to meet her. She had something she wanted to talk about." The note felt like it was burning a hole in her pocket. But handing it over to someone else, even Ezrim, would feel like admitting Teysa had conspired against the city, and she couldn't do that.
At least this way someone attached to the investigation would know about it, even if she wasn't admitting it to anyone until she absolutely must.
On the other side of the office, Kellan made a small, confused sound. Kaya and Ezrim turned toward him. Kellan's cheeks reddened as he looked away from their combined gazes.
"You had something to add, investigator?" rumbled Ezrim.
"No. Yes. I mean, it's just that—<NAME> was the head of the Orzhov."
"Yes," said Kaya. "Believe me, I knew that better than anyone else you could ask."
"So, if she's dead, she's a ghost now," said Kellan, with almost painful earnestness. "Shouldn't you be able to—you know—summon her and ask her who killed her?"
"There are a few problems with that," said Kaya. "First off, I'm not a necromancer. I can interact with ghosts, and I can sort of become a ghost without dying, which is a useful trick. I can talk to ghosts, but I can't summon them just because. I can ask politely, when I'm dealing with Orzhov ghosts, and I already tried calling Teysa." In the study, Teysa's skin still warm, her blood still red …
Kaya shook off the memory. "I know she warded her own soul; it's standard practice for high-ranking Orzhov. It keeps their rivals from calling them back and binding them after they die. I'm not a medium. I can't break through her wards. Teysa will appear when she wants to. Until then, she's out of the picture."
Kellan frowned. "Why wouldn't she want us to know who killed her?"
"Quite a few reasons. Maybe she doesn't know. Maybe it was one of her own. The Orzhov aren't always great at involving the other guilds in intra-guild affairs. If she was careless enough for someone to get the drop on her, this is how their leadership has changed before." Kaya fixed her attention back on Ezrim. "An answer, please."
"I asked you to lead the investigation, not give me orders."
"That's why I said 'please.'"
Ezrim sighed. "You know I'll have to tell the Azorius about the death of Guildmaster Karlov."
"I know."
"This can't stay a private Orzhov matter. Not with two high-ranking guild officials dead in less than a week."
"I know that, too."
"If their investigation finds something you don't like, or determines Guildmaster Karlov took her own life as part of some Orzhov power play—"
"She didn't," said Kaya, with absolute conviction. "If the Azorius find something I don't like, I'll accept it, and we'll go from there. I've had a lot of experience accepting things I don't like. But Teysa did not orchestrate her own murder."
"Very well," said Ezrim. "You returned before I could locate someone else to head the investigation. The position's yours. Your first task is to speak with the only other member of guild leadership known to have been at the party who has yet to check in with us—Judith of the Rakdos."
"Given the unique nature of her position, she may have interpreted your call as not applying to her," said Kaya, delicately.
Ezrim snorted. "She's happy to serve as speaker for her guild in all other circumstances. She knew we wanted to talk to her. You begin with her. Inspector Kellan, you'll accompany her. Make sure everything proceeds according to protocol. We #emph[will] solve this, and the Azorius will regret defaming us."
Kaya exchanged a look with Kellan. An investigation beginning in Rakdos territory was an investigation of interest, if nothing else.
"Yes, sir," she said.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"I guess we're partners now," said Kellan as he walked Kaya back toward the door, sounding entirely too happy about the idea. She frowned at him. He shrugged. "This is big. It's big, and it's interesting, and I joined the Agency because I like interesting things."
"I thought it was because you wanted to learn more about your father."
"He's an interesting thing." Kellan smiled lopsidedly. "When you and Detective Proft caught that assassin, it was the most interesting thing I'd seen in weeks. Murder isn't interesting. It's tragic and sad. But a foot chase through a crowded party, that's fascinating. I'm just glad I could help."
Kaya gave him a sidelong look, fighting the urge to answer his smile with one of her own. There was something about him that lifted her spirits, something untroubled and untainted by the terrible events of the last year. It was easy to take him at face value. That was something she didn't encounter nearly often enough. It was … soothing.
The commotion in the halls was still going, and Kellan skirted a new path around the edges of the building to avoid the worst of it, taking them past a large room with shimmering sheets of static force instead of walls. The space inside the static was filled with shelves, each loaded with its own assortment of containment capsules.
Kellan saw her looking. "That's where we put evidence relating to ongoing investigations," he said. "If the case is solved, the evidence gets processed, neutralized when necessary, and removed from our care. Until that happens, we keep it here, where it can't hurt anyone."
Kaya blinked. "What keeps people from just walking in and taking it?"
"Anyone breeching the walls will trigger an alarm, and the walls will turn solid to trap them inside," said Kellan. "No one who tried it would be able to get out of the vault. Even someone with your abilities would find themselves stuck with an entire building full of angry agents between them and the exit."
"You mean the phasing, yes?"
"Of course."
"Because I doubt that thing will stop a Planeswalker from leaving Ravnica entirely."
Kellan shrugged. "If we start thinking in terms of needing to stop Planeswalkers, there's no security left on the plane," he said. "Ravnica learned that when the invasion came."
Kaya winced at his tone. "I'm sure it's not a real concern. I was just curious. I'm sorry."
"It's nothing," he said, shaking off his momentary unhappiness as if it had never happened. He indicated one of the containment capsules. "That's the main reason I'd worry right now. That's where we're containing the Gruul god we detained until we've finished wrapping up the case, and can prove to the Boros that it's not going to rampage again. If that broke open inside the building, well …" He whistled, long and low. "It wouldn't be pretty."
"No, I wouldn't think so," said Kaya.
Then she paused, a frown crossing her face. Kellan looked at her curiously.
"What is it?"
"A ghost just entered the building."
Kellan's eyes widened. "Is it <NAME>?"
"No, I don't think so. Teysa might come here, but I think she'd come to me directly. Whoever it is, they're this way." She sped up, walking faster for the door, and Kellan followed, matching her step for step.
In the entrance chamber stood a very familiar, very dead man, darker skinned than Kaya or Kellan, with gray short-cropped hair and decorative drapes in Boros colors attached to his semi-transparent armor. All of him was semi-transparent, really, making it easy to guess why the last of the gossiping agents had cleared out of the room to let him have it.
Kaya inclined her head respectfully toward him. "Master Kos," she said. "To what do we owe this honor?"
"I didn't realize you'd joined the Agency," said the ghostly figure. "Planning to start a cross-planar franchise?"
#figure(image("004_Episode 4: Justice Before Mercy/02.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"I'm helping with the investigation into Zegana's murder," said Kaya. "I'm neutral enough in the eyes of the guilds that it seemed like a good use of available resources."
The ghost snorted, looking unimpressed.
"This is Investigator Kellan of the Agency," said Kaya, indicating the man beside her. "Kellan, this is <NAME>. He was one of the Boros's best investigators when he was alive, and death didn't change that. Master Kos, we were just on our way to follow up with a potential person of interest. Can we help you with something?"
"The Boros Legion has asked me to work alongside the Agency doing whatever they feel is necessary to catch the party or parties responsible." He grimaced. "Because one thing every dead man likes is being sent to get in the way of someone else's investigation. Didn't like it when I was in charge, don't like it now that Aurelia's running the show. Can't even do the polite thing and offer to get the coffee."
"You'll want to speak to Ezrim," said Kaya, sympathetically. "I get it. This isn't easy for any of us. But we're going to find the answers, and while that won't bring back the dead, it will hopefully settle the guilds."
"Nothing brings back the dead," said Agrus. "Doesn't mean we don't want answers."
"If you'll excuse us, we're going to go find them," said Kaya. "I'm sure we'll see you when we get back."
"Looks like I'm haunting your house for now," said Agrus.
Kaya and Kellan continued on and out the door.
"Do you know where we're going?" asked Kellan as they descended the stairs.
Kaya glanced around to make sure no one not wearing the Agency shield was in earshot, then said, very quietly, "If we're going to speak with Judith, we need to head for Hellbender. Apparently, that's where all the 'cool' people are spending their evenings right now. Judith has never been anywhere but the center of the celebration if she had any choice in the matter."
"How are we going to get there?"
"Carriage." Kaya stepped up to the street and raised her hand, flagging the first unoccupied hackney with dromads to come trotting down the way.
Kellan looked nervous as he followed her into the vehicle. She smiled at him, trying not to feel like she was betraying Teysa by going to a nightclub when her friend was yet unburied.
"Come on, kid," she said. "Let's crack this case."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The carriage let them out in front of a grandiose structure in Plaza West, too big for its neighbors and crowding them out through presence alone. A lanky teen in red and black lounged on the rail beside the scalloped marble steps. A toothpick bounced between his lips as he chewed on the end. He pulled it free at their approach, twirling it between his fingers before flicking it toward the street. Sneering, he focused on Kaya.
"Pretty Orzhov lady, you have no business here," he said.
"Aw, you think I'm pretty?" she half-simpered.
Kellan, who hadn't known her long but had known her long enough to realize how out of character this was, shot her an alarmed look. His alarm only grew when she took two long steps closer to the Rakdos boy, producing a knife from inside her tunic. Its edges spat purple light as she grabbed the back of the boy's shirt and yanked him toward her. Kaya's look of delight faded into one of cold efficiency.
"That's not going to work," she said.
"Calling you pretty doesn't work?" asked Kellan.
"That's not what I meant." She nodded toward her hip. Kellan looked lower.
The Rakdos boy had a knife of his own, one that was currently buried in Kaya's faintly purple-tinted stomach.
"Can't stab what's not solid," she said. "I, however, can stab you as much as I want. Judith would probably offer me honorary guild membership if I made sure the splatter was artistic enough. She in?"
The boy's eyes widened. "She is," he said. Kaya let him go, stepping back. Her knife disappeared back into her clothing, her middle turning solid again.
The boy tucked his own knife away, looking at her with a wary unhappiness that seemed to mask a degree of surprised amazement. "You didn't have to threaten me," he said. "I'd have let you in if you just paid the cover charge."
"Yeah, but like you said, I'm a pretty Orzhov lady. I don't pay anyone outside the guild if I don't have to," said Kaya. It was too early for a crowd to have gathered inside Hellbender. A glance was enough to tell them that the place, while run-down enough to come across as seedy, was dazzling at night, its high ceiling strewn with hanging glass spheres that would refract and split light once the candles were set aflame. Most of them were clear; others were red, or a purple so dark it would be almost like they were throwing black light across the gathered crowd. The dance floor, now splintered in the daylight coming through the narrow windows, was wide and level enough that it was doubtless very popular with the kind of people who just wanted to cram themselves in until they could barely move, drink, and dance before the sunrise stopped them.
Kaya had never been one of those people, even when she was younger and less jaded by the Multiverse. Sometimes she envied them a little. What must it be like, to be able to forget the world outside of your immediate needs? To have no responsibilities or obligations?
The Rakdos traded in violence and in joy, and maybe they had the right idea.
A vast bar took up one entire wall. There was no one there, but bottles gleamed dimly through the shadows, inviting their approach. Kellan, who was sticking close to Kaya, swallowed hard.
"I don't think there's anyone here," he said.
"Oh, she's here," said Kaya, crossing her arms. "This is Judith. She's just waiting to make an entrance."
There was a small, curved stage at the far end of the room, and warm, deeply amused laughter echoed from the shadows behind the half-drawn curtain. Kaya walked toward it, Kellan beside her, and stopped about six feet away, waiting patiently for the laughter to stop.
It finally tapered off, and Judith herself stepped around the curtain to center stage. As always, she was dressed in red skin-tight leather and flowing velvet draperies, making her as striking as a moving piece of scenery. Teysa had enjoyed investing in her home and in little luxuries like the moving topiaries. Judith had never felt the need to invest in anything other than herself.
"We're not open yet," she said, crossing her own arms in obvious mockery of Kaya, a smirk on her perfectly shaped, perfectly red lips. "How did you get in here?"
"Hello, Judith," said Kaya. "We didn't get much of a chance to talk at the party. I was surprised to see that Teysa sent you an invitation. I would have expected her to show more discretion in her guest list."
"Well, you know Teysa." Judith waved her hand carelessly. "Always aware of the angles. A little spectacle is … what's that word your people like to use so proudly? Profitable. Yes. A little spectacle is a #emph[lot] of money, as long as it's on your side. Upset the people who call the scene changes and," she made a small #emph[tsk] sound, "you can find yourself literally as well as creatively bankrupt."
"Not everything's about money."
Judith let her hands fall theatrically to her sides and stared at Kaya. "Now I #emph[know] a former Orzhov guildmaster didn't say that! Just like I know you didn't come here because we'd failed to catch up properly at Teysa's little attempt at a party. Why are you here?"
"Ezrim sent us," blurted Kellan.
Kaya shot him a sharp look. He ducked his head. "Sorry," he mumbled. "I didn't know what else to say."
Kaya swallowed a sigh. According to Kellan, Oko was fey, making Kellan half-faerie. Lies would be difficult for him, if they were possible at all—or maybe it was just his relentless do-gooder thing. That made working for the Agency a fascinating career choice for him. He must have known how to talk his way around an answer, when not put on the spot by someone as artfully intimidating as Judith, who had honed the power of her presence to a razored edge.
"Ah," said Judith. "This is about my little disagreement with Teysa, then?"
"Yes," said Kaya, before Kellan could say anything. Disagreement? This was the first she was hearing of it.
"I hardly think an argument over interest rates gives me cause to murder a Simic guildmaster," said Judith. "Besides, don't you have your killer?"
Neither of them answered. Judith studied Kellan's face before bursting into laughter.
"The high and mighty Azorius #emph[lost] her," she said, utterly delighted. "Oh, this is too good. But no, I didn't kill anyone. I submitted to their little verity game before I left the party. For once in my life, I can honestly say that I didn't do anything wrong."
"No one said you did," said Kaya.
"But you're here, which means someone #emph[thinks] I did. You're missing pieces. There's more to this story than you know."
"What's that supposed to mean?"
Judith's lips stretched in a long, thin smile. She waited to reply, clearly savoring the suspense. "You may have your killer in Etrata—that doesn't mean you're done. Go to Vitu-Ghazi. You need to read the Guildpact in its original form, and the tree shelters it. That will clarify things, I think."
"Why—" began Kaya.
Judith raised a hand. "No. That's quite enough. You can go now. I've seen you."
#figure(image("004_Episode 4: Justice Before Mercy/03.png.jpg", width: 100%), caption: [Art by: <NAME>uir], supplement: none, numbering: none)
Recognizing a dismissal, Kaya turned away, Kellan following as she made for the door. She paused before exiting, looking back over her shoulder. Judith was still at center stage, watching them go. For some reason, she looked smug, like everything was following her script once again.
Kaya and Kellan slipped out into the fading light of day.
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/features_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test number width.
#text(number-width: "proportional")[0123456789] \
#text(number-width: "tabular")[3456789123] \
#text(number-width: "tabular")[0123456789]
|
https://github.com/DaAlbrecht/lecture-notes | https://raw.githubusercontent.com/DaAlbrecht/lecture-notes/main/computer_networks/ipv4.typ | typst | MIT License | #import "../template.typ": *
#set table(
fill: (x, y) =>
if x == 0 or y == 0 {
gray.lighten(40%)
},
align: right,
)
#show table.cell.where(x: 0): strong
#show table.cell.where(y: 0): strong
= IPv4 (Internet Protocol version 4)
An Internet Protocol address (IP address) is a numerical *32-bit* label such as 172.16.17.32 that is assigned to a device connected to a computer network that uses the Internet Protocol.
IP Addresses serve two main functions:
- host or network interface identification
- location addressing.
== IP Address management
The allocation of internet addresses is clearly regulated.
This task is handled by Internet Registries (IR).
The central organization in the internet is the Internet Assigned Number Authority (IANA).
Regional Internet Registries (RIRs) receive address spaces from IANA and serve large geographic regions.
Local Internet Registries (LIRs), typically Internet Service Providers (ISPs), receive address spaces from the RIRs and are responsible for distributing them to end users such as businesses and organizations.
#figure(
image("../resources/ICANN.jpg", width: 60%),
caption: [IPv4 Address Allocation],
) <ipv4_address_allocation>
#pagebreak()
== IPv4 Address format
IPv4 addresses are 32-bit binary numbers, which are typically represented in dotted decimal notation.
This means that the 32-bit address is divided into four 8-bit octets, which are then converted to decimal numbers and separated by periods.
#example[
The binary address:
```
11000000.10101000.00000001.00000001
|--------|--------|--------|--------|
| 192 | 168 | 1 | 1 |
|--------|--------|--------|--------|```
is represented as: 192.168.1.1
]
An IPv4 address consists of two parts:
- the network addresse: identifies the network to which the device is connected
- the host address: identifies the device on that network.
== IPv4 Address Classes
IPv4 addresses are divided into five classes:
- A - C: used for unicast addresses
- D: used for multicast addresses
- E: reserved for future use
#table(
columns: (auto,auto,auto,auto),
align: (center + horizon,center+horizon,left+horizon,left+horizon),
table.header([Class], [Leading Bits], [Range], [Default Subnet Mask]),
[A], [0], [1.0.0.0 to 172.16.31.10], [/8 (255.0.0.0)],
[B], [10], [172.16.58.3 to 172.16.58.3], [/16 (255.255.0.0)],
[C], [110], [192.0.0.0 to 192.168.3.11], [/24 (255.255.255.0)],
[D], [1110], [244.0.0.0 to 172.16.58.3], [Reserved for multicast addresses],
[E], [11110], [244.0.0.0 to 254.255.255.255], [Reserved for future use],
)
#pagebreak()
== Routing
IP addresses are classified into several classes of operational characteristics:
- unicast
- multicast
- anycast
- broadcast
=== Unicast
Unicast is the most common form of IP addressing.
It is used to identify a single network interface.
When a packet is sent to a unicast address, it is delivered to the network interface that has that address.
=== Multicast
Multicast is used to send a packet to a group of devices.
The packet is sent to a multicast group address, and all devices that are part of that group receive the packet.
=== Anycast
Anycast is used to send a packet to a group of devices but only one of the devices in the group receives the packet.
The device that receives the packet is the one, the router determines to be the closest to the sender.
=== Broadcast
Broadcast is used to send a packet to all devices on a network.
The packet is sent to the broadcast address, and all devices on the network receive the packet.
== Private IP Addresses
Private IP addresses are reserved for use in private networks and are not routable on the public internet.
They are defined in RFC 1918 and are used to conserve public IP addresses.
#table(
columns: (auto,auto,auto,auto),
align: (center + horizon,center+horizon,left+horizon,left+horizon),
table.header([Name], [CIDR block], [Address Range], [Number of Addresses]),
[24-bit block], [10.0.0.0/8], [10.0.0.0 – 10.255.255.255], [16,777,216],
[20-bit block], [172.16.0.0/12], [172.16.0.0 – 172.31.255.255], [1,048,576],
[16-bit block], [192.168.0.0/16],[192.168.0.0 – 192.168.255.255], [65,536],
)
#pagebreak()
== Subnetting
The classification of IP addresses over time led to address wastage.
The two-level addressing system (network number and host number) caused problems when organizations wanted to structure their internal networks, as each subdivision required a new network number.
This increased the size of routing tables in backbone routers.
In 1985, RFC 950 introduced subnets to address these organizational issues and reduce the load on global internet routing tables.
Subnet addressing allowed for better organization of internal networks by splitting the host address into two parts:
- subnet number
- host number
creating a three-tier hierarchy (network number, subnet number, host number).
Without subnets, routers identified the target address class from the first bits of the IP address.
With subnets, routers need additional information, provided by a network mask, to identify the target network and host address.
The network mask is a 32-bit field where each bit corresponds to a bit in the IP address, indicating whether it is part of the network number.
When a router receives a packet, it uses the network mask to determine the destination network and host parts of the address.
The router performs a logical AND operation between the IP packet's destination address and the network mask in its forwarding table to find the best route.
== Subnet Mask
The subnet mask is a 32-bit number that is used to divide an IP address into network and host parts.
It is used by routers to determine the network number of an IP address.
The subnet mask is written in the same format as an IP address, with four octets separated by periods or using
CIDR notation.
Example 1:
#example[
ip address: `192.168.1.10`
Subnet Mask: 255.255.255.0
Can be written with the CIDR notation as *`192.168.1.10/24`*
]
#pagebreak()
=== Special Network Addresses
There are three types of network addresses:
- Network Address: The address with all host bits set to 0
- Broadcast Address: The address with all host bits set to 1
- General purpose address: An address that is neither a network nor a broadcast address
#example[
IPv4 Address: 192.168.1.0/24
#show raw: set text(font: "Berkeley Mono", size: 9pt, spacing: 100%)
```
+-----------------+-----------------+-----------------+-----------------+
| Network | First | Last | Address |
| Address | Usable | Usable | Broadcast |
| | IP | IP | |
| 192.168.1.0 | 192.168.1.1 | 192.168.1.254 | 192.168.1.255 |
+-----------------+-----------------+-----------------+-----------------+
```]
=== Examples of Subnetting
#example[
Given the IP address `10.0.1.1` and the subnet mask `/16`
- The subnet "magic" happens in the 2nd octet
- There are 2^16 = 65536 addresses in this subnet
- There are 255 possible subnets
#table(
columns: (auto,auto,auto,auto),
align: (center + horizon,center+horizon,left+horizon,left+horizon),
table.header([nth subnet], [Network Address], [Usable IP Range], [Broadcast Address]),
[1], [10.0.0.0], [10.0.0.1 - 10.0.255.254], [10.0.255.255],
[2], [10.1.0.0], [10.1.0.1 - 10.1.255.254], [10.1.255.255],
[3], [10.2.0.0], [10.2.0.1 - 10.2.255.254], [10.2.255.255],
[4], [10.3.0.0], [10.3.0.1 - 10.3.255.254], [10.3.255.255],
[255], [10.255.0.0], [10.255.0.1 - 10.255.255.254], [10.255.255.255]
)
]
== VLSM (Variable Length Subnet Masking)
VLSM is a technique that allows for the creation of subnets with different sizes.
This is useful when you have different requirements for the number of hosts in each subnet.
The requirements for VLSM are:
- A network address
- The number of hosts required for each subnet
VLSM works by dividing an already existing subnet into smaller subnets.
#pagebreak()
== IPv4 Header
The IPv4 header is a 20-byte header that is added to the beginning of an IP packet.
The fields in the header are send using big-endian byte order.
The IPv4 header consists of the following fields:
- Version: The version of the IP protocol being used (4 for IPv4)
- IHL (Internet Header Length): The length of the header in 32-bit words
- Type of Service: The type of service requested by the packet
- Total Length: The total length of the packet, including the header
- Identification: A unique identifier for the packet
- Flags: Flags used for fragmentation
- Fragment Offset: The offset of the fragment in the original packet
- Time to Live: The maximum number of hops the packet can take
- Protocol: The protocol used in the data portion of the packet
- Header Checksum: A checksum of the header
- Source Address: The source IP address of the packet
- Destination Address: The destination IP address of the packet
- Options: Optional fields that can be included in the header
#figure(
image("../resources/IPv4_Packet-en.svg.png", width: 80%),
caption: [IPv4 Header],
) <ipv4_header>
== IPv4 Packet Fragmentation
IPv4 packets can be fragmented when they are too large to be transmitted over a network.
When a packet is fragmented, it is divided into smaller packets, called fragments, that can be reassembled at the destination.
The fragmentation process is handled by routers along the path of the packet.
When a router receives a packet that is too large for the next hop, it fragments the packet into smaller packets and forwards them individually.
The fragments are reassembled at the destination using the identification field in the header to identify which fragments belong to the same packet.
#pagebreak()
== IPv4 Address Resolution Protocol (ARP)
ARP is a protocol used to map an IP address to a MAC address.
When a device wants to send a packet to another device on the same network, it needs to know the MAC address of the destination device.
ARP works by broadcasting a request for the MAC address of the destination device.
The device with the matching IP address responds with an Unicast message containing its MAC address to the requesting device.
== ARP Table
The ARP table is a table that maps IP addresses to MAC addresses.
When a device receives a packet, it checks the ARP table to see if it has the MAC address of the destination device.
If the MAC address is not in the ARP table, the device sends an ARP request to find the MAC address.
#example[
ARP Table:
```
+-----------------+-------------------+
| IP Address | MAC Address |
+-----------------+-------------------+
| 192.168.1.1 | AA:BB:CC:DD:EE:FF |
| 192.168.1.2 | FF:EE:DD:CC:BB:AA |
| 192.168.1.3 | 11:22:33:44:55:66 |
+-----------------+-------------------+```
]
After some time, the ARP table clears the entries to prevent stale entries from causing problems.
|
https://github.com/antonWetzel/prettypst | https://raw.githubusercontent.com/antonWetzel/prettypst/master/test/default/comments.typ | typst | MIT License | //test
#import "headings.typ": *; //test
//test
#test(
"some",
// "args",
)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/bugs/grid-2-01.typ | typst | Other | #set page(height: 60pt)
#lorem(5)
- #lorem(5)
|
https://github.com/Isaac-Fate/booxtyp | https://raw.githubusercontent.com/Isaac-Fate/booxtyp/master/src/theorems/theorem.typ | typst | Apache License 2.0 | #import "./new-theorem-template.typ": new-theorem-template
#import "../colors.typ": color-schema
#let theorem = new-theorem-template(
"Theorem",
fill: color-schema.orange.light,
stroke: color-schema.orange.primary,
)
|
https://github.com/katamyra/Notes | https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS3001/Sections/Section1.typ | typst | #set text(
font: "New Computer Modern",
size: 11pt
)
#set par(
justify: true,
leading: 0.68em,
)
#set heading(numbering: "1.a")
= _Introduction_
My name is <NAME>. I am a CS major as an Info and Intel major and this is my second semester here.
== Ethical Question
_Suppose theres an AI model that can relatively accurately detect if someone is feeling depressed or on the edge of suicide. Would it be immoral or infringing on peoples emotional privacy to install this AI into company zoom meetings or other software in order to try to help these people ahead of time?_
= _Stop Sign_
To be truthfully honest, yeah I would not stop at the stop sign. I think the line is that I wouldnt blow past a red light no matter what but I would for a stop sign.
= _Section Discussion Question_
How many years after a new medical machine or technology comes out would you guys need before you would trust to use it yourself?
= _People in the Therac controversy_
*My person: #highlight(fill: rgb("#E5DAFC"), [Programmer of Therac-25])*
== What the Person Did
They created the Therac-25 and directly wrote the code that lead to all the errors.
Some of the errors that occured include
+ *Race errors* which are very hard to fix or even notice in the first place
+ They copied code from previous therac models assuming it worked but the only reason it likely worked before was because there were hardware locks making sure nothing could go wrong
+ Data Overflow
- one of the really massive overdoses of radiation is was caused by a data overflow that was not correctly handled in software
+ Lack of Proper Testing
- lacked comprehensive testing
== What that person failed to do
They failed to do enough comprehensive testing to make their code work. #underline[Furthermore, they should have done more testing when the machines were harming people, rather than claiming that the machines could not cause theset problems.]
== What they could have done differently
They should have done more testing but also designed their code not only to be safe on a software level, but also on a hardware level. They should have created hardware safeties to make sure people weren't hurt.
They also could have written better documentation and training and having a more holistic and rigorous approach to software development, especially in these types of critical applications.
== How they affected what happened
They caused people to die due to having faulty software.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/foundations-12.typ | typst | Other | // Test successful assertions.
#assert(5 > 3)
#assert.eq(15, 15)
#assert.ne(10, 12)
|
https://github.com/jeffa5/typstfmt | https://raw.githubusercontent.com/jeffa5/typstfmt/main/.github/ISSUE_TEMPLATE/erroneous-input-report.md | markdown | MIT License | ---
name: Erroneous input report
about: The input contained errors
title: "[Input]"
labels: input
assignees: ''
---
**To Reproduce**
Code snippet:
```typst
<your problematic snippet here, or upload the file>
```
**Version**
`X.X.X`
**Additional context**
|
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/class-handouts/class-wood_115-woodturning.typ | typst | #import "./environment/env-protohaven-class_handouts.typ": *
#show: doc => class_handout(
title: "Woodturning a Mallet",
instructors: ("<NAME>",),
category: "Wood",
number: "115",
clearances: ("Wood Lathe","Dust Collection"),
authors: ("<NAME>", "<NAME>"),
draft: true,
doc
)
= Welcome
Welcome to the wood turning class at Protohaven!
#include "community_subsections/shop_rules.typ"
#pagebreak()
= Woodturning Safety
- Use a full face shield (Safety glasses at a minimum) whenever the lathe is turned on.
- Tie back long hair, do not wear gloves, and avoid loose clothing or objects that may catch on rotating parts or accessories.
- Always check the speed of the lathe before turning it on. Use slower speeds for larger diameter or rough pieces, and higher speeds for smaller diameter and pieces that are balanced. Always start a piece at a slower speed until the work piece is balanced. If the lathe is shaking or vibrating, lower the speed. If the work piece vibrates, always stop the machine to check the reason.
- Check that all locking devices on the tailstock and tool rest assembly (rest and base) are tight before operating the lathe.
- Position the tool rest close to work, about one inch away from the material. Check tool rest position often and as wood is removed, turn off the lathe and re-position the rest.
- Rotate your work piece by hand to make sure it clears the tool rest and bed before turning the lathe's motor on. Be certain that the work piece turns freely and is firmly mounted. A handwheel on the outboard side of the headstock simplifies this process of spinning the lathe by hand before turning on the switch.
- Be aware of what the turners call the _red zone_ or _firing zone._ This is the area directly behind and in front of the work piece - the areas most likely for a piece to travel as it comes off the lathe. A good safety habit is to step out of this zone when turning on the lathe. When observing others turn stay out of the area.
- Hold turning tools securely on the tool rest, holding the tool in a controlled and comfortable manner. Always contact the tool rest with the tool before contacting the wood.
- Turn the lathe off before adjusting the tool rest or tool rest base (banjo).
- Remove the tool rest before sanding or polishing operations.
- Never leave the lathe running unattended. Turn the power off. Do not leave the lathe until it comes to a complete stop.
If you feel unsure of something, feel free to ask!
(Source: https://www.woodturners.org/)
#pagebreak()
= Introduction
== Learning Objectives
== Woodturning Terminology
When you read about woodturning or talk with woodturners, these are some terms you're likely to encounter.
/ Bevel: The area beneath the cutting edge of a scraper or gouge. The bevel on a gouge is always held in contact with the wood.
/ Blank: A piece of wood rounded smooth or cut into a section for lathe use.
/ Burl: An unusual growth on a tree, producing swirls and other interesting grain patterns.
/ Heartwood: The fully developed wood surrounding the core, usually darker than sapwood (see below) and really dense.
/ Moisture content: Percentage of water weight to total weight. Moisture content is usually 30 to 40 percent or more when wood is freshly cut (aka "green"). Dry wood typically has moisture content of less than seven to eight percent.
/ Sapwood: This surrounds heartwood and is usually softer. It transports sap from roots to leaves. It's a different color than the heartwood.
/ Spalted wood: Wood in the process of fungal decay that shows as black lines in the grain. Woodturners prize spalted wood because the black lines add an artistic element to the turning.
= Classroom Activities
= Tools
#include "tool_subsections/woodshop_dust_collection.typ"
// #include "tool_subsections/turning_tools.typ"
#include "tool_subsections/lathe_wood.typ"
= Resources
|
|
https://github.com/jamesrswift/chemicoms-paper | https://raw.githubusercontent.com/jamesrswift/chemicoms-paper/main/tests/example/test.typ | typst | #import "/src/lib.typ": template, elements;
#import "credit.typ": *
#set page(paper: "us-letter", margin: (left: 10mm, right: 10mm, top: 12mm, bottom: 15mm))
#show: template.with(
title: [Effects of $#sym.beta$-Cyclodextrin, Triacetin, Propylene Glycol, and Ethanol on the Release of Aroma Compounds from Aqueous Solutions],
abstract: lorem(75),
venue: place(image("rgb.svg", height: 34pt), dy:-0.25cm),
header: (
article-color: rgb(86,111,127),
article-type: "Preprint",
article-meta: [Not Peer-Reviewed],
),
authors: (
(
name: "<NAME>",
),
(
name: "<NAME>",
),
(
name: "<NAME>",
corresponding: true,
orcid: ""
),
),
dates: (
(type: "Received Date", date: datetime.today()),
(type: "Revised Date", date: datetime.today()),
(type: "Accepted Date", date: datetime.today())
),
doi: "00.0000/XXXXXXXXXX",
citation: [<NAME>, <NAME> and <NAME>, _ChemR#sym.chi;iv_, 2024, *3*, 1---3],
// fonts: (
// //body: "Calibri"
// )
)
#let lorem-pars(n, each: 4) = {
let sentences = lorem(n * each * 30).split(". ")
range(n)
.map(i => sentences.slice(i * each, count: each).join(". ") + [.])
.join(parbreak())
}
= Introduction
#lorem-pars(1) @gree00
$ sum_(k=0)^n k = 1 + ... + n $
#elements.float(align: bottom, [\*Corresponding author])
#lorem-pars(4) @netwok2020
#elements.float(
align: bottom,
figure(
image("Caffeine_structure.svg.png", width:25%),
caption: [The structure of caffeine in skeletal format, showing the nitrogens and oxygens. All carbons are represented as vertices, and hydrogens are filled onto these vertices according to valence. @smit54]
)
)
= Methodology
#lorem-pars(2)
== Materials
#lorem(20)
== Chemicals
#lorem(50)
== Samples
#lorem(75)
== Methods
#lorem(250)
=== Measurement
#lorem(250)
= Results and Discussion
#lorem-pars(7)
= Conclusions
#lorem(150)
#set heading(numbering: none)
= CRediT authorship contribution statement
#CRediT("<NAME>",
credits.concept,
credits.dataCuration,
credits.analysis,
credits.investigation,
credits.visualization,
credits.methodology,
credits.validation,
credits.writingDraft)
#CRediT("<NAME>",
credits.dataCuration,
credits.analysis,
credits.investigation,
credits.visualization)
#CRediT("<NAME>",
credits.concept,
credits.supervision,
credits.writingReview)
= Conflicts of Interest
The authors have no conflicts of interest to declare. All co-authors have seen and agree with the contents of the manuscript and there is no financial interest to report.
= Acknowledgements
#lorem(20)
= Notes and References
#set par(justify: true, first-line-indent: 0pt);
#lorem(20)
#bibliography(title:none, style:"ieee", "references.bib") |
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/互联网原理与技术/作业/理论7.typ | typst | The Unlicense | #import "../../template.typ": *
#import "@preview/tablem:0.1.0": tablem
#show: project.with(
title: "理论 7",
authors: (
"absolutex",
)
)
#set heading(numbering: none)
// P3、P7
= 理论作业7
== P3 假设图7-6中的接收方希望接收由发送方2发送的数据。说明通过使用发送方2的代码,(经计算)接收方的确能够将发送方2的数据从聚合信道信号中恢复出来。
$d_1^2=(0+2+0+2+0+0+2+2)/8=1$
$d_2^2=(2+0+2+0+2+2+0+0)/8=1$
== P7 假设一个802.11b站点被配置为始终使用RTS/CTS序列预约信道。假设该节点突然要发送1500字节的数据,并且所有其他站点此时都是空闲的。作为SIFS和DIFS的函数,忽略传播时延并假设无比特差错,计算发送该帧和收到确认需要的时间。
$T_总=T_"DIFS"+ 3T_"SIFS"+ T_"RTS"+ T_"CTS"+T_"DATA"+ T_"ACK"$ |
https://github.com/noahjutz/AD | https://raw.githubusercontent.com/noahjutz/AD/main/notizen/algorithmen/eratosthenes.typ | typst | #import "/config.typ": theme
#let sieve(d, n: 51) = table(
columns: 10,
align: center,
"", ..range(2, n).map(i =>{
if d == 0 {
return str(i)
}
if i == d {
table.cell(fill: theme.secondary_light, str(i))
} else if range(2, d).any(j => calc.rem(i, j) == 0 and i != j) {
table.cell(fill: theme.bg_light, str(i))
} else if calc.rem(i, d) == 0 {
table.cell(fill: theme.primary_light, str(i))
} else if i < d {
strong(str(i))
} else {
str(i)
}
})
)
#sieve(2) |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/valkyrie/0.1.0/src/types/tuple.typ | typst | Apache License 2.0 | #import "../base-type.typ": base-type, assert-base-type-array
#import "../context.typ": context
/// Valkyrie schema generator for an array type with positional type reqruiements. If all entries have the same type, see @@array.
/// - name (internal):
/// - ..args (schema): Type requirments. Position of argument *MUST* match position of entry in tuple being validated. *SHOULD* not contain named arguments.
/// -> schema
#let tuple(
name: "tuple",
..args
) = {
// Does not accept named arguments
assert( args.named().len() == 0, message: "Dictionary only accepts named arguments")
args = args.pos()
assert-base-type-array(args)
return (:..base-type(),
name: name,
tuple-schema: args,
validate: (self, tuple, ctx: context(), scope: () ) => {
// assert type
if not (self.assert-type)(self, tuple, scope: scope, ctx: ctx, types: (type(()),)){
return none
}
// Check elements
for (key, schema) in self.tuple-schema.enumerate(){
tuple.at(key) = (schema.validate)(schema, tuple.at(key), ctx: ctx, scope: (..scope, str(key)))
}
return tuple
}
)
}
|
https://github.com/jneug/schule-typst | https://raw.githubusercontent.com/jneug/schule-typst/main/tests/lt/test.typ | typst | MIT License | #import "../../src/schule.typ": lt
#import lt: *
#import "@preview/cetz:0.2.2"
#show: lerntheke.with(
/* @typstyle:off */
titel: "Base template test",
reihe: "TYPST-TEST",
datum: "15.06.2024",
nummer: "1",
fach: "Typst",
kurs: "101",
autor: (
name: "<NAME>",
kuerzel: "Ngb",
),
version: "2024-06-15",
)
#hilfekarte(
label: <die-lerntheke>,
infotext: ["Malvorlage Wissenschaft lernen" von #link("http://www.schulbilder.org", "Schulbilder.org")],
)[
= Die Lerntheke
#wrap-content(
align: right,
image(width: 5cm, "images/0.1-LT-Abb_Lernen.jpg"),
)[
Anstatt alle zusammen im Klassenverbund zu lernen, arbeitet bei einer Lerntheke jeder in seinem eigenen Tempo an *Lernstationen*. Jede Lernstation besteht aus einer Karte, wie du sie gerade in der Hand hältst.
#v(1em)
Du entscheidest selber, welche Stationen du bearbeiten möchtest und wie. Aber denk daran, dass du am Ende trotzdem eine Klassenarbeit schreiben musst. Versuch also die Stationen in deinem Tempo zu bearbeiten, und nicht sofort die Lösungen abzuschreiben.
#v(1em)
Die Karten dieser Lerntheke zeigen dir, wie du an der Lerntheke arbeiten kannst, welche Hilfsmittel es gibt und wie die Stationenkarten aufgebaut sind.
]
#v(1fr)
#align(
center,
text(1.8em)[
Viel Spaß und Erfolg beim Lernen!
],
)
#v(1fr)
]
#rueckseite(titel: "Arbeitsweise")[
#align(center)[Hier findest du in der Regel die *Lösung einer Station*.]
Zu Beginn erstellt du in deinem Heft eine Tabelle, in der du deinen Fortschritt festhältst. Die Tabelle enthält folgende Spalten:
#align(
center,
cetz.canvas({
import cetz.draw: *
content((0, 0), image(width: 10cm, "images/0.1-LT-Abb_Tabelle.jpg"))
let arrow(from, to, fill, body) = {
let name = "arrow-" + fill.to-hex()
line(from, to, stroke: 2pt + fill, mark: (end: "stealth"), name: name)
content(
(rel: (0, -.3), to: name + ".start"),
text(fill, 1.2em, body),
anchor: "north",
)
}
arrow((-6, -2), (-4, -1), rgb("#187f1e"))[
*Nummer der Station,\ an der Du arbeitest.*
]
arrow((-1.6, -3.5), (-1, -1.3), rgb("#015887"))[
*Datum, an dem du mit der\ Station fertig geworden bist.*
]
arrow((5, -2), (3.3, -1.2), rgb("#cd362c"))[
*Falls du dich für die Station\ als Experte eingetragen hast,\ mache hier ein Kreuz.*
]
}),
)
// #align(center, image(width: 10cm, "images/0.1-LT-Abb_Tabelle.jpg"))
// #align(center, image(width: 100%, "images/0.1-LT-Abb_Tabelle_2.jpg"))
]
#hilfekarte(titel: "Die Stationenkarten", label: <stationenkarten>)[
#align(
center,
cetz.canvas({
import cetz.draw: *
content((0, 0), image(width: 8cm, "images/0.1-LT-Abb_Beispielkarte.jpg"))
let marker(loc, name) = circle(loc, radius: .02, fill: none, stroke: none, name: name)
marker((3.2, 2.25), "icon")
marker((-3.3, 2.25), "number")
marker((-0.1, 2.25), "title")
marker((3.53, 1.1), "help-marker")
marker((-2, -1.5), "body")
marker((2.7, -2.4), "footer")
let shadowed(loc, body, name: "shadowed", width: auto, fill: auto) = {
content(
loc,
{
place(
top + left,
dx: 2pt,
dy: 2pt,
block(
width: width,
inset: .5em,
fill: luma(75%),
radius: 4pt,
hide(par(leading: .66em, text(.88em, tracking: -.5pt, body))),
),
)
block(
width: width,
inset: .5em,
stroke: 1.5pt + fill,
fill: white,
radius: 4pt,
par(leading: .66em, text(.88em, tracking: -.5pt, body)),
)
},
name: name,
)
}
let annotation(marker, rel, fill: rgb("#cc0100"), radius: .4, type: "circle", width: 5cm, body) = {
let name = marker + "-annotation"
let from = (rel: rel, to: marker)
let to = marker
if type == "circle" {
circle(to, radius: radius, stroke: 1.5pt + fill, fill: fill.transparentize(70%), name: name + "-circle")
shadowed(from, body, name: name + "-body", width: width, fill: fill)
line(name + "-body", name + "-circle", stroke: 1.5pt + fill, fill: fill)
} else {
shadowed(from, body, name: name + "-body", width: width, fill: fill)
line(name + "-body", marker, mark: (end: "stealth"), stroke: 1.5pt + fill, fill: fill)
}
}
annotation("number", (-4, -1))[
Jede Station hat eine *Nummer*. Die Stationen können, _müssen aber nicht_ in dieser Reihenfolge bearbeitet werden. Überleg dir am besten eine _eigene Reihenfolge_.
]
annotation("icon", (3, 1), width: 2.2cm)[
/ #icon.einzel: Solo
/ #icon.partner: Doppel
/ #icon.gruppe: Gruppe
]
annotation("help-marker", (3, -.5), width: 4cm)[
Diese Symbole zeigen dir an, auf welchen Hilfekarten du bei Problemen nachsehen kannst.
]
annotation("footer", (3.8, -.5), width: 4.5cm, type: "arrow")[
Hier stehen manchmal klein die Lösungen zur Karte, anstatt auf der Rückseite. Oder hier stehen Informationen zu den verwendeten Bildern.
]
annotation("title", (-2, 2), width: 10cm, type: "arrow")[
Die Farbe der Kopfzeile zeigt die Art der Station an:
/ #text(theme.cards.type1)[Grün]: #text(theme.cards.type1)[Grundlagen lernen]
/ #text(theme.cards.type2)[Gelb]: #text(theme.cards.type2)[Anwendung der Grundlagen]
/ #text(theme.cards.type3)[Rot]: #text(theme.cards.type3)[Komplexe Aufgaben, die mehrere Grundlagen verknüpfen]
]
annotation("body", (-2, -2.2), width: 10cm, type: "arrow")[
Das wichtigste jeder Station sind die Aufgaben.
Lies sie sorgfältig und bearbeite sie möglichst eigenständig. Zur Kontrolle findest du auf der Rückseite die Lösung.
]
}),
)
]
#rueckseite()[
#align(center, [Hier findest du in der Regel die *Lösung einer Station*.])
Bei manchen Stationen ist die Lösung aber auch _klein auf die Vorderseite gedruckt_, oder ist zum Beispiel als Kontrollwort in der Aufgabe angegeben.
Du solltest dich bemühen die Stationen möglichst _eigenständig_ zu lösen. Hast du Probleme, kannst
du zunächst die _Hilfekarten_ (siehe @hilfekarten) zu Rate ziehen. Danach kannst du auf dem Expertenposter
(siehe @expertenposter) nachsehen, ob dir vielleicht schon jemand bei der Station helfen kann. Bist du immer
noch unsicher, dann kann dir die Lehrperson (siehe @lehrperson) bestimmt weiterhelfen
]
#hilfekarte(titel: "Hilfekarten", label: <hilfekarten>)[
// #hilfe-marker(3)
#hilfe-marker(<die-lerntheke>, <stationenkarten>)
Hilfekarten erkennst du an der #text(theme.cards.help)[violetten Kopfzeile]. Die Nummern der Hilfekarten beginnen mit einem "H" (z.B. H1, H2, ...).
#align(
center,
block(
width: 80%,
height: 1.5cm,
_card-header(
"Addition von Brüchen",
counter: none,
fill: theme.cards.help,
no: "H2",
icon: emoji.ringbuoy,
),
),
)
Die Nummern der Hilfekarten, die du für deine Station nutzen kannst, findest du in den #text(theme.cards.help)[violetten Symbolen] am oberen Rand der Stationskarte.
#align(
center,
cetz.canvas({
import cetz.draw: *
line((-2, 0), (2, 0))
content((0, 0), _help-token("H1"))
content((1.2, 0), _help-token("H2"))
}),
)
]
#rueckseite(titel: "Rückseiten")[
#align(center, text(1.2em)[Auf der Rückseite einer Karte findest du in der Regel die *Lösungen der Aufgaben*.])
Hilfekarten haben normalerweise keine Lösung. Aber wenn auf der Vorderseite nicht genug Platz war, stehen auf der Rückseite manchmal weitere Informationen.
#v(1em)
#align(center, [So wie hier. #emoji.face.grin])
]
#hilfekarte(titel: "Das Expertenposter", label: <expertenposter>)[
#wrap-content(
align: right,
image(width: 4.5cm, "images/0.1-LT-Abb_Expertenposter.jpg"),
)[
Hast du eine Station bearbeitet und _fühlst dich so sicher_ dabei, dass du anderen Schülerinnen und Schülern die Lösung _erklären_ kannst, dann trag dich auf dem Expertenposter als _Experte oder Expertin_ ein.
Zu jeder Station kann es _zwei ExpertInnen_ geben.
Kommst du bei einer Station nicht weiter, und helfen dir die Hilfekarten auch nicht, dann guck auf dem Expertenposter nach, ob es schon einen Experten oder eine Expertin für die Station gibt. Frag denjenigen oder diejenige nach Hilfe.
]
]
#leer()
#hilfekarte(
titel: "Die Lehrperson",
label: <lehrperson>,
infotext: ["Malvorlage Lehrer und Schüler" von #link("http://www.schulbilder.org", "Schulbilder.org").],
)[
Haben dir die Hilfekarten und die Experten / Expertinnen zu deiner Station nicht weitergeholfe (oder falls es keine Hilfen oder ExpertInnen gibt), dann kannst du natürlich auch deine Lehrperson um Hilfe bitten.
#wrap-content(
align: left,
image(width: 4cm, "images/0.1-LT-Abb_Lehrer.jpg"),
)[
Aber am meisten lernt man, wenn man _erstmal selber versucht_, eine Station zu lösen. _Also denk zunächst gut nach, wie du vorgehen kannst, bevor du zum Lehrer kommst._ Bestimmt kommt dir dabei schon eine gute Idee für die Lösung.
Hast du eine Station gelöst, kannst du dein Ergebnis mit den _Lösungen auf der Rückseite_ überprüfen. Hast du dann noch Fragen, beantwortet sie dir der Lehrer gerne.
]
]
#leer()
#karte1[
= Meine Karte
#aufgabe()[
Test
#loesung[
Foo bar
]
]
]
#loesungskarte()
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/117.%20determination.html.typ | typst | determination.html
The Anatomy of Determination
Want to start a startup? Get funded by
Y Combinator.
September 2009Like all investors, we spend a lot of time trying to learn how to
predict which startups will succeed. We probably spend more time
thinking about it than most, because we invest the earliest.
Prediction is usually all we have to rely on.We learned quickly that the most important predictor of success is
determination. At first we thought it might be intelligence.
Everyone likes to believe that's what makes startups succeed. It
makes a better story that a company won because its founders were
so smart. The PR people and reporters who spread such stories
probably believe them themselves. But while it certainly helps to
be smart, it's not the deciding factor. There are plenty of people
as smart as <NAME> who achieve nothing.In most domains, talent is overrated compared to determination—partly
because it makes a better story, partly because it gives onlookers
an excuse for being lazy, and partly because after a while determination
starts to look like talent.I can't think of any field in which determination is overrated, but
the relative importance of determination and talent probably do
vary somewhat. Talent probably matters more in types of work that
are purer, in the sense that one is solving mostly a single type
of problem instead of many different types. I suspect determination
would not take you as far in math as it would in, say, organized
crime.I don't mean to suggest by this comparison that types of work that
depend more on talent are always more admirable. Most people would
agree it's more admirable to be good at math than memorizing long
strings of digits, even though the latter depends more on natural
ability.Perhaps one reason people believe startup founders win by being
smarter is that intelligence does matter more in technology startups
than it used to in earlier types of companies. You probably do
need to be a bit smarter to dominate Internet search than you had
to be to dominate railroads or hotels or newspapers. And that's
probably an ongoing trend. But even in the highest of high tech
industries, success still depends more on determination than brains.If determination is so important, can we isolate its components?
Are some more important than others? Are there some you can
cultivate?The simplest form of determination is sheer willfulness. When you
want something, you must have it, no matter what.A good deal of willfulness must be inborn, because it's common to
see families where one sibling has much more of it than another.
Circumstances can alter it, but at the high end of the scale, nature
seems to be more important than nurture. Bad circumstances can
break the spirit of a strong-willed person, but I don't think there's
much you can do to make a weak-willed person stronger-willed.Being strong-willed is not enough, however. You also have to be
hard on yourself. Someone who was strong-willed but self-indulgent
would not be called determined. Determination implies your willfulness
is balanced by discipline.That word balance is a significant one. The more willful you are,
the more disciplined you have to be. The stronger your will, the
less anyone will be able to argue with you except yourself. And
someone has to argue with you, because everyone has base impulses,
and if you have more will than discipline you'll just give into
them and end up on a local maximum like drug addiction.We can imagine will and discipline as two fingers squeezing a
slippery melon seed. The harder they squeeze, the further the seed
flies, but they must both squeeze equally or the seed spins off
sideways.If this is true it has interesting implications, because discipline
can be cultivated, and in fact does tend to vary quite a lot in the
course of an individual's life. If determination is effectively
the product of will and discipline, then you can become more
determined by being more disciplined.
[1]Another consequence of the melon seed model is that the more willful
you are, the more dangerous it is to be undisciplined. There seem
to be plenty of examples to confirm that. In some very energetic
people's lives you see something like wing flutter, where they
alternate between doing great work and doing absolutely nothing.
Externally this would look a lot like bipolar disorder.The melon seed model is inaccurate in at least one respect, however:
it's static. In fact the dangers of indiscipline increase with
temptation. Which means, interestingly, that determination tends
to erode itself. If you're sufficiently determined to achieve great
things, this will probably increase the number of temptations around
you. Unless you become proportionally more disciplined, willfulness
will then get the upper hand, and your achievement will revert to
the mean.That's why Shakespeare's Caesar thought thin men so dangerous. They weren't
tempted by the minor perquisites of power.The melon seed model implies it's possible to be too disciplined.
Is it? I think there probably are people whose willfulness is
crushed down by excessive discipline, and who would achieve more
if they weren't so hard on themselves. One reason the young sometimes
succeed where the old fail is that they don't realize how incompetent
they are. This lets them do a kind of deficit spending. When they
first start working on something, they overrate their achievements.
But that gives them confidence to keep working, and their performance
improves. Whereas someone clearer-eyed would see their initial
incompetence for what it was, and perhaps be discouraged from
continuing.There's one other major component of determination: ambition. If
willfulness and discipline are what get you to your destination,
ambition is how you choose it.I don't know if it's exactly right to say that ambition is a component
of determination, but they're not entirely orthogonal. It would
seem a misnomer if someone said they were very determined to do
something trivially easy.And fortunately ambition seems to be quite malleable; there's a lot
you can do to increase it. Most people don't know how ambitious
to be, especially when they're young. They don't know what's hard,
or what they're capable of. And this problem is exacerbated by
having few peers. Ambitious people are rare, so if everyone is
mixed together randomly, as they tend to be early in people's lives,
then the ambitious ones won't have many ambitious peers. When you
take people like this and put them together with other ambitious
people, they bloom like dying plants given water. Probably most
ambitious people are starved for the sort of encouragement they'd
get from ambitious peers, whatever their age.
[2]Achievements also tend to increase your ambition. With each step
you gain confidence to stretch further next time.So here in sum is how determination seems to work: it consists of
willfulness balanced with discipline, aimed by ambition. And
fortunately at least two of these three qualities can be cultivated.
You may be able to increase your strength of will somewhat; you can
definitely learn self-discipline; and almost everyone is practically
malnourished when it comes to ambition.I feel like I understand determination a bit better now. But only
a bit: willfulness, discipline, and ambition are all concepts almost
as complicated as determination.
[3]Note too that determination and talent are not the whole story.
There's a third factor in achievement: how much you like the work.
If you really love working on something,
you don't need determination to drive you; it's what you'd do anyway.
But most types of work have aspects one doesn't like, because most
types of work consist of doing things for other people, and it's
very unlikely that the tasks imposed by their needs will happen to
align exactly with what you want to do.Indeed, if you want to create the most wealth,
the way to do it is to focus more on their needs than your interests,
and make up the difference with determination.Notes[1]
Loosely speaking. What I'm claiming with the melon seed model
is more like determination is proportionate to wd^m - k|w - d|^n,
where w is will and d discipline.[2]
Which means one of the best ways to help a society generally
is to create events and institutions that bring ambitious
people together. It's like pulling the control rods out of a
reactor: the energy they emit encourages other ambitious people,
instead of being absorbed by the normal people they're usually
surrounded with.Conversely, it's probably a mistake to do as some European countries
have done and try to ensure none of your universities is significantly
better than the others.[3]
For example, willfulness clearly has two subcomponents,
stubbornness and energy. The first alone yields someone who's
stubbornly inert. The second alone yields someone flighty.
As willful people get older or otherwise lose their energy, they
tend to become merely stubborn.
Thanks to <NAME>, <NAME>, and <NAME>
for reading drafts of this.Italian TranslationPortuguese TranslationRussian Translation
|
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/must_know/spacing.md | markdown | MIT License | # Using spacing
Most time you will pass spacing into functions. There are special function fields that take only _size_.
They are usually called like `width, length, in(out)set, spacing` and so on.
Like in CSS, one of the ways to set up spacing in Typst is setting margins and padding of elements.
However, you can also insert spacing directly using functions `h` (horizontal spacing) and `v` (vertical spacing).
> Links to reference: [h](https://typst.app/docs/reference/layout/h/), [v](https://typst.app/docs/reference/layout/v/).
```typ
Horizontal #h(1cm) spacing.
#v(1cm)
And some vertical too!
```
# Absolute length units
> Link to [reference](https://typst.app/docs/reference/layout/length/)
Absolute length (aka just "length") units are not affected by outer content and size of parent.
```typ
#set rect(height: 1em)
#table(
columns: 2,
[Points], rect(width: 72pt),
[Millimeters], rect(width: 25.4mm),
[Centimeters], rect(width: 2.54cm),
[Inches], rect(width: 1in),
)
```
## Relative to current font size
`1em = 1 current font size`:
```typ
#set rect(height: 1em)
#table(
columns: 2,
[Centimeters], rect(width: 2.54cm),
[Relative to font size], rect(width: 6.5em)
)
Double font size: #box(stroke: red, baseline: 40%, height: 2em, width: 2em)
```
It is a very convenient unit, so it is used a lot in Typst.
## Combined
```typ
Combined: #box(rect(height: 5pt + 1em))
#(5pt + 1em).abs
#(5pt + 1em).em
```
# Ratio length
> Link to [reference](https://typst.app/docs/reference/layout/ratio/)
`1% = 1% from parent size in that dimension`
```typ
This line width is 50% of available page size (without margins):
#line(length: 50%)
This line width is 50% of the box width: #box(stroke: red, width: 4em, inset: (y: 0.5em), line(length: 50%))
```
# Relative length
> Link to [reference](https://typst.app/docs/reference/layout/relative/)
You can _combine_ absolute and ratio lengths into _relative length_:
```typ
#rect(width: 100% - 50pt)
#(100% - 50pt).length \
#(100% - 50pt).ratio
```
# Fractional length
> Link to [reference](https://typst.app/docs/reference/layout/fraction/)
Single fraction length just takes _maximum size possible_ to fill the parent:
```typ
Left #h(1fr) Right
#rect(height: 1em)[
#h(1fr)
]
```
There are not many places you can use fractions, mainly those are `h` and `v`.
## Several fractions
If you use several fractions inside one parent, they will take all remaining space
_proportional to their number_:
```typ
Left #h(1fr) Left-ish #h(2fr) Right
```
## Nested layout
Remember that fractions work in parent only, don't _rely on them in nested layout_:
```typ
Word: #h(1fr) #box(height: 1em, stroke: red)[
#h(2fr)
]
``` |
https://github.com/TC-Fairplay/member-listing | https://raw.githubusercontent.com/TC-Fairplay/member-listing/main/members-list.typ | typst | MIT License | #let members-list(csv-file, juniors-letter, doc) = {
let member-type = if juniors-letter == "" { "Aktive" } else { "JuniorInnen " + juniors-letter }
let get-header() = {
locate(loc => if loc.page() > 1 { [TC Fairplay #h(1fr) Mitgliederliste #member-type] })
};
set page(
paper: "a4",
margin: (x: 1.5cm, y: 2cm),
header: get-header(),
footer: [Stand: 23. Mai 2023 #h(1fr) #counter(page).display()],
)
set text(font: "Liberation Sans")
grid(
columns: (1fr, auto),
[
#text(size: 14pt, [TC Fairplay])\
#text(size: 12pt, [Mitgliederliste #member-type])
],
image("fairplay_logo.svg", height: 1cm)
)
block(
width: 100%,
fill: luma(90%),
inset: 8pt)[
*Bitte unbedingt beachten:*
#show "TC Fairplay": it => [#emph([#it])]
#if juniors-letter != "" {[
Bei den JuniorInnen #juniors-letter (jünger als 18 Jahre) wird nur der Name und der Vorname publiziert.
Die Kontaktdaten müssen über die JuniorInnen und/oder über die Eltern eingeholt werden.
]}
Die nachstehend publizierte Mitgliederliste des TC Fairplay ist ausschliesslich zur Nutzung durch die Clubmitglieder bestimmt. Es ist den Clubmitgliedern untersagt, die Mitgliederliste oder Teile davon an Drittpersonen weiterzugeben.
Die Mitgliederliste darf nur für persönliche Kontakte im Zusammenhang mit dem
TC Fairplay verwendet werden. Die Nutzung der Mitgliederliste zur Verbreitung von persönlichen Interessen im Sinne von politischen Äusserungen, Spendenaufrufen, Meinungsbildungen, Umfragen etc. ist verboten.
]
let results = csv("data/" + csv-file)
results.insert(0, [*Name, Vorname*])
if juniors-letter == "" {
results.insert(1, ([*Mobile*]))
}
columns(2,
table(
columns: if juniors-letter == "" { (1fr, auto) } else { (100%) },
stroke: luma(75%),
fill: (_, row) => if calc.even(row) { luma(95%) } else { white },
align: (col, _) => if (col == 1) { right } else { left },
// right-align column "Mobile"
..results.flatten(),
)
)
}
|
https://github.com/coco33920/.files | https://raw.githubusercontent.com/coco33920/.files/mistress/typst_templates/moderncv.typst/moderncv.typ | typst | /*
* Customizations on this template:
*
* - headings (h1..h4)
*
* - `datebox` function: provides content with stacked year above (big) and month below (tinier)
*
* - `daterange` function: two `datebox`es separated by an em dash
*
* - `xdot`: function, adds a trailing dot to a string only if it's not already present
*
* - `cvgrid`: basic layout function that wraps a grid. Controlled by two parameters `left_column_size` (default: 25%) and `grid_column_gutter` (default: 8pt) which control the left column size and the column gutter respectively.
*
* - `cvcol`: used to write in the rightmost column only. Builds on `cvgrid`
*
* - `cventry`: used to write a CV entry. Builds on `cvgrid`
*
* - `cvlangauge`: used to write a language entry. Builds on `cvgrid`
*
*/
#let left_column_size = 25%
#let grid_column_gutter = 8pt
#let main_color = rgb(147, 14, 14)
#let heading_color = main_color
#let job_color = rgb("#737373")
#let icon(codepoint) = {
box(
height: 0.8em,
baseline: 0.05em,
image(codepoint)
)
h(0.1em)
}
#let language_box(language_name,language_colour,language_icon) = {
box(
height: auto,
width: auto,
inset: 0.5em,
radius: 0.5cm,
fill: language_colour.lighten(60%),
stroke: language_colour.darken(20%) + 2pt,
stack(dir: ltr,icon(language_icon),language_name)
)
}
#let project(
title: "",
author: [],
phone: "",
email: "",
github: "",
left_column_size: left_column_size,
grid_column_gutter: grid_column_gutter,
main_color: main_color,
heading_color: heading_color,
job_color: job_color,
link_color: rgb("#55cdfc"),
pronouns: "",
address: "",
body
) = {
set document(author: author, title: title)
set page(numbering: none)
set text(lang: "fr", fallback: true)
show math.equation: set text(weight: 400)
show heading.where(level: 1): element => [
#v(0em)
#box(
inset: (right: grid_column_gutter, bottom: 0.1em),
rect(fill: main_color, width: left_column_size, height: 0.25em)
)
#text(element.body, size: 1em,fill: heading_color, weight: 400)
]
show heading.where(level: 2): element => [
#text(element.body + ",", size: 0.8em)
]
show link: set text(fill:link_color)
show heading.where(level: 3): element => [
#text(element.body, size: 1em, weight: 400, style: "italic")
]
show heading.where(level: 4): element => block[#text(element.body, size: 1em, weight: 400, fill: heading_color)]
set list(marker: box(circle(radius: 0.2em, stroke: heading_color), inset: (top: 0.15em)))
set enum(numbering: (n) => text(fill: heading_color, [#n.]))
grid(
columns: (1fr, 1fr),
box[
// Author information.
#text([#author], weight: 400, 2.5em)
#v(-1.2em)
// Title row.
#block(text(weight: 400, 1.5em, title, style: "italic", fill: job_color))
],
align(right + top)[
// Contact information
#set text(job_color,size:10pt,style:"italic")
#set block(below: 0.5em)
#if address != "" {
align(top)[
#address
]
}
#v(0.25em)
#if pronouns != "" {
align(top)[
#pronouns
]
}
#v(0.125em)
#if github != "" {
align(top)[
#box(height: 1em, baseline: 20%)[#pad(right: 0.4em)[#image("icons/github.svg")]]
#link("https://github.com/" + github)[#github]
]
}
#if phone != "" {
align(top)[
#box(height: 1em, baseline: 20%)[#pad(right: 0.4em)[#image("icons/phone-solid.svg")]]
#link("tel:" + phone)[#phone]
]
}
#if email != "" {
align(top)[
#box(height: 1em, baseline: 20%)[#pad(right: 0.4em)[#image("icons/envelope-regular.svg")]]
#link("mailto:" + email)
]
}
]
)
// Main body.
set par(justify: true, leading: 0.3em)
body
}
#let datebox(month: "", year: []) = box(
align(center,
stack(
dir: ttb,
spacing: 0.2em,
text(size: 1em, [#year]),
text(size: 0.75em, month),
)
)
)
#let daterange(start: (month: "", year: []), end: (month: "", year: [])) = box(
stack(dir: ltr,
spacing: 0.4em,
datebox(month: start.month, year: start.year),
[--],
datebox(month: end.month, year: end.year)
)
)
#let cvgrid(..cells) = pad(bottom: 0.3em)[#grid(
columns: (left_column_size, auto),
row-gutter: 0em,
column-gutter: grid_column_gutter,
..cells
)]
#let cvcol(content) = cvgrid([], content)
#let xdot(s) = {
if s.ends-with(".") {
s
} else {
s + "."
}
}
#let cventry(
description,
start: (month: "", year: ""),
end: (month: "", year: ""),
place: "",
role: []
) = cvgrid(
align(center, daterange(start: start, end: end)),
[
== #role
=== #xdot(place)
],
[],
description
)
#let cvlanguage(
language: [],
description: [],
certificate: [],
) = cvgrid(
align(right, language),
[#description #h(3em) #text(style: "italic", certificate)],
)
#let cvprogramming(
language: [],
description: [],
icon_name: "",
language_name: "",
language_colour: "",
certificate: [],
) = cvgrid(
align(right,language_box(language_name,language_colour,icon_name)),
[#description #h(3em) #text(style: "italic", certificate)],
)
|
|
https://github.com/topdeoo/Course-Slides | https://raw.githubusercontent.com/topdeoo/Course-Slides/master/Seminar/2024-03-07/main.typ | typst | #import "../../theme/iTalk.typ": *
#import "@preview/algo:0.3.3": algo, i, d, comment, code
#show: nenu-theme.with(
short-title: "LNS",
short-date: "2024-03-07",
short-author: "Virgil"
)
#let argmax = math.op("arg max", limits: true)
#let argmin = math.op("arg min", limits: true)
#title-slide(
title: "(Adaptive) Large Neighborhood Search",
authors: (
name: "凌典",
email: "<EMAIL>"
),
logo: image("../template/fig/nenu-logo-title.png", width: 30%),
institution: "Northeast Normal University",
date: "2024-03-07"
)
#slide(
session: "Introduction",
title: "Neighborhood Search"
)[
邻域搜索算法(或称为局部搜索算法)是一类非常常见的改进算法,其在每次迭代时通过搜索当前解的“邻域”找到更优的解。
邻域搜索算法设计中的关键是邻域结构的选择,即邻域定义的方式。 根据以往的经验,邻域越大,局部最优解就越好,这样获得的全局最优解就越好。
但与此同时,邻域越大,每次迭代搜索邻域所需的时间也越长。出于这个原因,除非能够以非常有效的方式搜索较大的邻域,否则启发式搜索也得不到很好的效果。
]
#slide(
session: "Introduction",
title: "VLSN"
)[
从熟知的邻域搜索算法 (Neighborhood Search) 出发,当一个邻域搜索算法搜索的邻域规模随着实例规模的增长而呈指数增长时,我们引申出了 Very Large Scale Neighborhood Search(VLSN) 算法。
#only((2, 3))[
VLSN 分为四种类型#footnote[#link("https://backend.orbit.dtu.dk/ws/portalfiles/portal/5293785/Pisinger.pdf")["<NAME> and <NAME>",Large neighborhood search.]]:
#only(2)[
- 可变深度邻域搜索(Variable-depth methods)
#grid(
columns: 2,
column-gutter: 1em,
[
以启发式的方式搜索一个参数化的更深邻域族 $ N_1,N_2,dots,N_k$ 。一个典型的例子是 1-交换邻域 $N_1$,其中改变一个变量/位置。
],
image("fig/VDNS.png", width: 90%, fit: "contain")
)
]
#only(3)[
- 基于网络流的改进方法(Network-flows based improvement algorithms)
- 基于多项式时间可解子类限制的方法(Efficiently solvable special cases)
- 大邻域搜索(Large Neighborhood Search, LNS)
]
]
// #only(4)[
// 一个简单的 VLSN 例子如下:
// 考虑
// ]
]
#slide(
session: "Problem",
title: "Problem Example"
)[
#only((1, 2, 3))[考虑一个 CVRP 问题,我们有一个车队,每辆车都有一个容量限制,我们需要将一些货物从一个中心点运送到一些客户点。我们的目标是最小化总行驶距离,并保证每个客户点都被访问且满足容量限制。]
#only(2)[
形式化的来说,考虑一个无向图 $G = <V, E>$,其中$c_e in RR(forall e in E)$, $V = {0, dots, n}$,顶点 $0$ 为中心点,顶点 $i$ 为客户点。
每个客户点 $i$ 都有一个需求 $q_i$,有 $m$ 辆车,每辆车都有一个容量限制 $Q$。我们需要找到 $m$ 条路线,每条路线的起点均为中心点,使得车辆恰好访问每个客户一次,并满足每条路线上客户的需求总和小于或等于 $Q$,$m$ 条路线经过的边成本之和最小。
]
#only((3))[
一个简单的实例及可行解如下:
#image("fig/CVRP-sample.png", width: 40%, fit: "contain")
]
]
#slide(
session: "Introduction",
title: "LNS"
)[
LNS 是一种元启发式搜索算法,其拓展版本为自适应大邻域搜索(Adaptive Large Neighborhood Search, ALNS)。
大多数的NS算法会明确定义邻域,在 LNS 中,邻域由 `destroy` 和 `repair` 隐式定义。
#only((2, 3))[
- `destroy`#footnote[通常包含随机元素,使得每次都会破坏解的不同部分]: 从当前解中移除一部分元素,得到一个部分解
- `repair`: 从被 `destroy` 的部分解中,重构出一个可行解
]
#only(3)[
于是,解 $X$ 的邻域 $N(X)$ 被定义为:$N(X) = {"repair"("destroy"(X))}$。
]
]
#slide(
session: "LNS",
title: "CVRP Example"
)[
例如先前的 `CVRP` 问题,我们考虑:
- `destroy` 为删除当前解 $X$ 中 `15%` 的客户点#footnote[随机选择`15%` 的点删除],并缩短被删除客户的路线。
- `repair` 为使用启发式的贪心来构建可行解。
#grid(
columns: 3,
column-gutter: 0em,
rows: 2,
row-gutter: 1.5em,
image("fig/CVRP-1.png", fit: "contain", width: 70%),
image("fig/CVRP-2.png", fit: "contain", width: 70%),
image("fig/CVRP-3.png", fit: "contain", width: 70%),
[
原始解 $X$
],
[
`destroy` 后的解 $d(X)$
],
[
`repair` 后的解 $r(d(X))$
]
)
]
#slide(
session: "LNS",
title: "Framework",
)[
#grid(
columns: 2,
column-gutter: 1em,
algo(
title: "LNS",
parameters: ("X: a feasible solution",),
row-gutter: .8em,)[
$X_"best" arrow.l X$\
while not terminate do#i\
$X_t arrow.l "repair"("destroy"(X))$\
if accept($X_t, X$) then#i\
$X arrow.l X_t$#d\
if cost($X_t$) < cost($X_"best"$) then#i\
$X_"best" arrow.l X_t$#d#d\
return $X_"best"$
],
[
#only(1)[
在设计算法时,显然我们需要从两个方面来进行考量:
+ `accept` 的设计
+ `destroy` 和 `repair` 的设计
]
#only(2)[
`accept` 函数的设计有多种选择:
+ 简单的爬山算法型,只接受更优解
+ 模拟退火型#footnote[也有使用 `RRT` 等方法],在接受更优解的同时,也会以一定概率接受更差解
换而言之,在 `accept` 这个过程中,我们可以引入一个启发式的算法来决定是否接受新解。
]
#only((3, 4))[
#only(3)[对于 `destroy` 设计,最重要的就是对删除程度的把握。
程度小会导致搜索空间小,无法跳出局部最优解;程度大则会导致算法退化。因此这是一个消耗时间与解质量的 trade-off。
常见的做法是:
+ 逐步提升删除的程度
+ 每次迭代时,从一个依赖于实例大小的区间中随机选择删除程度
]
#only(4)[
注意,在先前提到过 `destory` 需要包含随机元素
这是为了保证 `destory` 必须保证覆盖到解空间的各个部分#footnote[或者至少是全局最优解所在的那一部分],从而避免算法陷入局部最优解。
]
]
#only(5)[
对于 `repair` 设计有极大的自由度,我们有以下几种选择:
- `repair` 能够从部分解中构建出当前状态下的最优解
- `repair` 是启发式算法。
当然,我们也可以设计基于特定问题的 `repair` 方法,甚至使用MIP或约束求解器。
]
#only(6)[
在 `LNS` 框架中,`destroy` 和 `repair` 在求解时是唯一的,这意味着我们只能够搜索一种邻域结构,显然这是 `LNS` 的一个局限
如果我们能够同时搜索多种邻域结构,那么我们就能够更好的探索解空间。
]
]
)
]
#slide(
session: "ALNS",
title: "Introduction"
)[
根据上面所说的局限,于是我们有了 `Adaptive LNS` (i.e. ALNS)
在此自适应算法中,我们允许在一次搜索中探索多个邻域结构(使用多组不同的 `destroy` 和 `repair`),搜索的邻域结构是通过解的质量而动态变化的。
]
#slide(
session: "ALNS",
title: "Framework"
)[
#grid(
columns: (55%, 45%),
column-gutter: .7em,
algo(
title: "ALNS",
parameters: ("X: a feasible solution",),
row-gutter: .6em,
)[
$X_"best" arrow.l X$\
$rho^-, rho^+ arrow.l (1,dots, 1)$\
while not terminated do#i\
select $d in Omega^-, r in Omega^+$ using $rho^-, rho^+$\
$X_t arrow.l r(d(X, d))$\
if accept($X_t, X$) then#i\
$X arrow.l X_t$#d\
if $"cost"(X_t) < "cost"(X_"best")$ then#i\
$X_"best" arrow.l X_t$#d\
update $rho^+, rho^-$#d\
return $X_"best"$
],
[
#only(1)[
- $Omega^-, Omega^+$ 分别表示 `destroy` 和 `repair` 方法的集合
- $rho^-, rho^+$ 分别表示集合中方法的权重集合
- 以概率 $phi.alt_j^- = rho_j^-/(sum_(k=1)^(|Omega^-|)rho_k^-)$ 从 $Omega^-$ 中选择 $d_j$,$r_j$ 同理。
]
#only((2, 3, 4))[
#only(2)[
而权重 $rho^-, rho^+$ 根据 `destory`, `repair` 方法在搜索过程中的表现而动态调整。
]
#only((2, 3))[
$
psi = max cases(
omega_1 "if " "cost"(X_t) < "cost"(X_"best"),
omega_2 "if " "cost"(X_t) < "cost"(X),
omega_3 "if accept",
omega_4 "if not accept"
)
$
]
#only(2)[
其中 $omega_1 gt.eq omega_2, gt.eq omega_3 gt.eq omega_4 gt.eq 0$
]
#only((3, 4))[
假设 $d_a$ 与 $r_b$ 为此次被选中的 `destroy` 和 `repair` 方法,那么我们有:
$rho^-_a = lambda rho_a^- + (1-lambda)psi$
$rho^+_b = lambda rho_b^+ + (1 - lambda)psi$
#only(4)[
显然,只有被选中的 `destroy` 和 `repair` 方法的权重会被更新,从而选择对解空间探索更好的邻域结构。
]
]
]
]
)
]
#slide(
session: "ALNS",
title: "Different destroy and repair"
)[
#only(1)[
在上面的讨论中,我们认为 `destroy` 和 `repair` 是可以任意搭配的
但存在着以下情况:
+ 某一个 `destroy` 只和某一个 `repair` 搭配效果很好
+ 一个 `repair` 方法可能做出了某些假设,导致其只能搭配某些 `destroy` 方法
]
#only(2)[
对于第一种情况,我们考虑将 `destroy` 和 `repair` 方法组合成一个 `operator`,并对这个算子进行分配权重与调整。
#grid(
columns: (1.2fr, 1.2fr),
image("fig/ALNS-combine.png", fit: "contain", width: 80%),
image("fig/ALNS-combine-phi.png", fit: "contain", width: 80%),
)
]
#only(3)[
对于第二种情况,我们采用耦合邻域来解决:
定义子集 $K_i subset.eq Omega^+$,使得采取 `destory` 函数 $d_i$ 时,`repair` 函数只能从 $K_i$ 中选择。
当 $K_i = emptyset.rev$ 时,有两种策略来解决:
+ $d_i$ 同时负责 `destroy` 和 `repair`
+ 采用普通的启发式策略进行 `repair`
]
]
#slide(
session: "ALNS",
title: "Design"
)[
由于 `ALSN` 在 `accept` 函数上的设计与 `LNS` 相差不大,我们主要关注 `destroy` 和 `repair` 方法的设计。
]
#slide(
session: "ALNS Design",
title: "Destroy"
)[
+ 随机选择应该删除的部分 (`random destory`)
+ 尝试移除 $q$ 个“关键”变量,即具有较高成本或破坏当前解结构的变量(`worst destroy` / `critical destroy`)
+ 可以选择一些相关的变量,#pin(1)这些变量在保持解的可行性的同时易于互换#pin(2) (`related destroy`)
#only(2)[
#pinit-highlight(1, 2)
对于CVRP,可以定义每对客户之间的相关性,例如客户之间的距离,也可以包括客户需求(需求相似的客户被认为是相关的)。
因此,`destory` 方法将选择具有高度相关度量的一组客户。
]
#only((beginning: 3))[
4. 基于历史信息选择 $q$ 个变量并删除,历史信息可以是统计某个给定变量(或一组变量)的设置导致错误解的频率(`history based destroy`)
]
]
#slide(
session: "ALNS Design",
title: "Repair"
)[
+ 贪心算法的各类改进变体
+ 近似 / 精确算法,精确算法可以以解的质量为代价来对时间进行松弛,以求解的更快,例如目前有许多 `repair` 方法使用 MIP 求解器进行。
]
#slide(
session: "Application",
title: "Application"
)[
#only(1)[
#rotate(
90deg
)[
#image("fig/VRP.png", fit: "contain", width: 100%, height: 160%)
]
]
#only(2)[
#rotate(
90deg
)[
#image("fig/VRP-2.png", fit: "contain", width: 100%, height: 160%)
]
]
#only(3)[
#rotate(
90deg
)[
#image("fig/non-VRP.png", fit: "contain", width: 100%, height: 160%)
]
]
]
#slide(
session: "(A)LNS",
title: "Conclusion & Discussion"
)[
1. Hybrid Neighborhoods
邻域搜索复杂性的增加意味着局部搜索算法可以执行更少的迭代。 Gutin 和 Karapetyan 通过实验比较了多维分配问题的许多小型和大型邻域,包括它们的各种组合。事实证明,大小邻域的某些组合可以提供最佳结果。
2. ML for Adaptive
机器学习等技术是否可以用于改进 ALNS 的自适应层。更聪明的动态选择 `destory` 和 `repair` 可能会改善启发式,并且让算法中的其他参数适应当前的实例,例如 `accept` 函数的参数。
] |
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/i18n/zh/docusaurus-plugin-content-docs/current/external/pdfpc.md | markdown | ---
sidebar_position: 1
---
# pdfpc
[pdfpc](https://pdfpc.github.io/) 是一个 "对 PDF 文档具有多显示器支持的演示者控制台"。这意味着,您可以使用它以 PDF 页面的形式显示幻灯片,并且还具有一些已知的出色功能,就像 PowerPoint 一样。
pdfpc 有一个 JSON 格式的 `.pdfpc` 文件,它可以为 PDF slides 提供更多的信息。虽然您可以手动编写此它,但你也可以通过 Touying 来管理。
## 加入 Metadata
Touying 与 [Polylux](https://polylux.dev/book/external/pdfpc.html) 保持一致,以避免 API 之间的冲突。
例如,你可以通过 `#pdfpc.speaker-note("This is a note that only the speaker will see.")` 加入 notes。
## pdfpc 配置
为了加入 pdfpc 配置,你可以使用
```typst
#let s = (s.methods.append-preamble)(self: s, pdfpc.config(
duration-minutes: 30,
start-time: datetime(hour: 14, minute: 10, second: 0),
end-time: datetime(hour: 14, minute: 40, second: 0),
last-minutes: 5,
note-font-size: 12,
disable-markdown: false,
default-transition: (
type: "push",
duration-seconds: 2,
angle: ltr,
alignment: "vertical",
direction: "inward",
),
))
```
加入对应的配置,具体配置方法可以参考 [Polylux](https://polylux.dev/book/external/pdfpc.html)。
## 输出 .pdfpc 文件
假设你的文档为 `./example.typ`,则你可以通过
```sh
typst query --root . ./example.typ --field value --one "<pdfpc-file>" > ./example.pdfpc
```
直接导出 `.pdfpc` 文件。
借助 Touying 与 Polylux 的兼容性,你可以让 Polylux 也支持直接导出,只需要加入下面的代码即可。
```
#import "@preview/touying:0.2.1"
#locate(loc => touying.pdfpc.pdfpc-file(loc))
``` |
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/references/ref_label.typ | typst | Apache License 2.0 | // compile: true
#set heading(numbering: "1.")
= Labeled <title_label>
@title_label
/* position after */ @title_label
@title_label |
https://github.com/SoraShu/HITsz-Lab-report-Template | https://raw.githubusercontent.com/SoraShu/HITsz-Lab-report-Template/main/template/main.typ | typst | // set PDF document metadata
#set document(title: "摸鱼与摸鱼工程实验一", author: "张三")
#import "@local/hitsz-lab-report-template:1.0.0": *
#show: project.with(
logopath: "./asset/hitsz_logo.jpg",
subject: "摸鱼与摸鱼工程",
labname: "实验一\n系统性摸鱼设计",
kwargs: (
"学院": "计算机科学与技术学院",
"姓名": "张三",
"学号": "1145141919810",
"专业": "计算机科学与技术",
"日期": "2050 年 2 月 30 日",
),
// 段首缩进, 2em 意为缩进两个字符
firstlineindent: 2em,
// 黑体字体设置
heiti: ("Noto Sans CJK SC", "Times New Roman"),
// 宋体字体设置
songti: ("Noto Serif CJK SC", "Times New Roman"),
// 等宽字体设置
mono: ("FiraCode Nerd Font Mono", "Sarasa Mono SC","Courier New", "Courier", "Noto Serif CJK SC"),
)
= h1
== h1.1
#lorem(30)
== h1.2
#lorem(30)
= h2
== h2.1
#lorem(30)
== h2.2
#lorem(30)
|
|
https://github.com/OrangeX4/typst-sympy-calculator | https://raw.githubusercontent.com/OrangeX4/typst-sympy-calculator/main/tests/cal.typ | typst | MIT License | #let hidden(content) = {}
#let cmat(..args) = {
let mat = if (type(args.pos().at(0)) != "array") { (args.pos(),) } else { args.pos() }
let mat_t = ()
for j in range(mat.at(0).len()) {
mat_t.push(())
for i in range(mat.len()) {
mat_t.at(j).push(mat.at(i).at(j))
}
}
math.mat(..mat_t)
}
// define accents
#let acc(x) = math.accent(x, math.grave)
// define operators
#let add = math.op("add")
#let f = math.op("f")
// define symbols
#let xy = math.italic("xy")
#let mail = symbol("🖂", ("stamped", "🖃"),)
```py
# typst-calculator
# ↑ the line is necessary for typst-calculator recognizing
@func()
def convert_add(a, b):
return a + b
```
#hidden[
```typst-calculator
# ↑ or you can just use `typst-calculator` but not `py` or `python`
@func_mat()
def convert_cmat(matrix):
return sympy.Matrix(matrix).T
```
]
|
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/05-group-theory/04-homomorphism.typ | typst | Other | #import "../../utils/core.typ": *
#import "../../packages/commute.typ": *
== Гомоморфизмы
#ticket(step-fn: x => x - 4, post-step-fn: x => x + 4)[Гомоморфизм, образ и ядро]
#def[
Пусть $G$, $G'$ --- группы.
Отображение $phi: G --> G'$ называется _гомоморфизмом_, если для любых $g_1, g_2 in G$ выполнено $ phi(g_1 g_2) = phi(g_1) phi(g_2). $
]
#examples[
+ $GL_n (K) limits(-->)^(det) K^*$
+ $S_n limits(-->)^sgn ZZ*$
+ $R^*_+ limits(-->)^ln RR$
+ $g maps g^k$, где $g in G$ --- Абелева группа, $k in ZZ$.
+ $H < G$, $i_H: H --> G$: $h maps h$ --- гомоморфизм из подгруппы в группу.
+ $H nsubg G$, $pi_H: G --> G fg H$: $g maps g H$ --- проекция группы на подгруппу.
]
#def[
Пусть $phi : G --> G'$ --- гомоморфизм. Тогда:
- $Ker phi = {g in G bar phi(g) = e}$ --- _ядро гомоморфизма_.
- $Im phi = {phi(g) bar g in G}$ --- _образ гомоморфизма_.
]
#lemma[
Пусть $phi: G --> G'$ --- гомоморфизм. Тогда:
+ $phi(e) = e$
+ $forall g in G: phi(g^(-1)) = (phi(g))^(-1)$
]
#proof[
+ #[$
e e = e ==> phi(e) phi(e) = phi(e) ==> phi(e) = e
$]
+ #[$
g mul g^(-1) = e ==> phi(g) mul phi(g^(-1)) = phi(e) = e ==> phi(g^(-1)) = (phi(g))^(-1)
$]
]
#pr[
Пусть $phi: G --> G'$ --- гомоморфизм. Тогда
+ $Ker phi nsubg G$
+ $Im phi < G'$
]
#proof[
+ Докажем $Ker phi nsubg G$
- $phi(e) = e ==> e in Ker(phi)$
- $g_1 g_2 in Ker(phi) ==> phi(g_1 g_2) = phi(g_1)phi(g_2) = e mul e = e$
- $g in Ker(phi) ==> phi(g^(-1)) = (phi(g))^(-1) = e^(-1) = e$
- Пусть $h in Ker phi$, $g in G$.
$
phi(g h g^(-1)) = phi(g) phi(h) phi(g^(-1)) = phi(g) compose e compose phi(g)^(-1) = e ==> g h g^(-1) in Ker phi.
$
]
#examples[
- Если $H < G'$, то $Im i_H = H$, где $i_H$ --- гомоморфизм из подгруппы в группу.
- Если $H nsubg G$, то $Ker pi_H = H$, где $pi_H$ --- проекция группы на подгруппу.
]
#def[
- _Мономорфизм_ --- инъективный гомоморфизм.
- _Эпиморфизм_ --- сюръективный гомоморфизм.
- _Изоморфизм_ --- биективный гомоморфизм.
]
#def[
Если между группами существует изоморфизм, то говорят, что они _изоморфны_. Обозначается $G iso G'$.
]
#lemma[
$phi: G --> G'$ --- гомоморфизм. Тогда $phi$ инъективный тогда и только тогда, когда $Ker phi = {e}$.
]
#proof[
"$==>$": если $phi$ --- инъективный, то
$ abs(Ker phi) = abs(phi^(-1)(e)) <= 1 ==> Ker phi = {e} $
"$<==$": Пусть $Ker phi = {e}$. Если $phi(g_1) = phi(g_2)$, то $phi(g_1 g_2^(-1)) = e$, что равносильно $g_2 g_1^(-1) in Ker phi = {e}$, откуда $g_1 = g_2$.
]
#ticket[Канонические гомоморфизмы. Индуцированный гомоморфизм, разложение гомоморфизма]
#notice[
Попробуем понять что-то про общую структуру гомоморфизмов, а точнее про то как превратить их в изоморфизм.
]
#pr[
Пусть $phi: G --> G'$ --- гомоморфизм; $H nsubg G, space H subset Ker phi, H' < G', space H' supset Im phi$. Тогда определим гомоморфизм $wave(phi): $
$
G fg H &--> H' \
g H &maps phi(g)
$
]
#proof[
Проверим, что операция корректна, то есть что элементы из одного класса смежности перейдут в один и тот же элемент:
Пусть $g_1 H = g_2 H ==> g_2 = g_1 h, space h in H subset Ker phi$, тогда:
$
phi(g_2) = phi(g_1)phi(h) = phi(g_1).
$
Теперь проверим, то что $wave(phi)$ --- гомоморфизм:
$
wave(phi)(g_1 g_2 H) = phi(g_1 g_2) = phi(g_1) phi(g_2) = wave(phi)(g_1 H) wave(phi)(g_2 H).
$
]
#notice[
Пусть $wave(phi)$ --- как выше. Тогда $phi = i_H compose wave(phi) compose pi_H$, где:
$
i_(H'): H' < G', H' --> G': h' maps h' #[--- проекция подгруппы на группу]\
pi_H: H nsubg G, G --> G fg H: g maps g H #[--- проекция группы на подгруппу]
$
#align(center)[#commutative-diagram(
node((0, 0), $G$),
node((0, 2), $G'$),
node((1, 0), $G fg H$),
node((1, 2), $H'$),
arr((0, 0), (0, 2), $phi$),
arr((0, 0), (1, 0), $pi_H$),
arr((1, 0), (1, 2), $wave(phi)$, "dashed"),
arr((1, 2), (0, 2), $i_(H')$, "inj"),
)]
]
#ticket[Теорема о гомоморфизме]
#th(name: [о гомоморфизме])[
Пусть $phi: G --> G'$ --- гомоморфизм. Тогда индуцированный гомоморфизм $wave(phi)$
$
G fg Ker phi &--> Im phi\
g Ker phi &maps phi(g)
$
является изоморфизмом.
aka гомоморфный образ группы изоморфен факторгруппе по ядру гомоморфизма по закону коммунизма.
]
#proof[\
"Сюръективность":
$Im wave(phi) = Im phi ==> wave(phi)$ --- сюръективно.
"Инъективность":
Пусть $g Ker phi in Ker wave(phi) ==> wave(phi)(g Ker phi) = e$, тогда $g in Ker phi ==> g Ker phi = e Ker phi$. \
Таким образом $Ker wave(phi) = {e Ker phi} ==> wave(phi)$ --- инъективно.
]
#example[
Пусть $CC^* limits(-->)^phi RR^*_+$: $z maps abs(z)$. Такое ядро $Ker phi$ обозначается $TT$, оно равно ${z in C^* bar abs(z) = 1}$. Значит $CC^* fg TT iso RR^*$ по теореме о гомоморфизме.
А еще можно сказать, что $TT iso RR fg ZZ$.
]
#ticket[Применение теоремы о гомоморфизме к классификации циклических групп]
#th(name: "О классификации цилических групп")[
Пусть $G$ --- циклическая группа.
+ Если $abs(G) = oo ==> G iso ZZ$.
+ Если $abs(G) = n ==> G iso ZZ \/n ZZ$
]
#proof[
Пусть $G = gen(g)$. Рассмотрим отображение $phi$:
$
ZZ &limits(-->)^(phi) G \
k &maps g^k
$
$g^(k+l) = g^k g^l,$ то есть $phi$ --- гомоморфизм, $Im phi = G$.\
Утверждается, что подгруппы $ZZ$ имеют вид $n ZZ, "где" n = 0,1,2,...$. Мы уже исследовали их, когда говорили про теорию идеалов. Подгруппы $ZZ$ --- идеалы (нетрудно проверяется), поэтому они имеют такой вид.
Осталось посмотреть что будет, если $Ker phi = n ZZ, n in NN$. Тогда по теореме о гомоморфизме $G iso ZZ fg Ker phi = ZZ fg n ZZ$. Если же $Ker phi = 0 ZZ = {0}$, то $G iso ZZ fg Ker phi = ZZ fg {0} iso ZZ$.
]
#ticket[Теорема о произведении подгрупп]
#th(name: [О произведении подгрупп])[
Пусть $H nsubg G$, $K < G$. Тогда
+ $H K < G$.
+ $H nsubg H K$, $H sect K nsubg K$
+ $H K fg H iso K fg (H sect K)$
]
#proof[
Заметим, что $K H = limits(union.big)_(k in K) k H = limits(union.big)_(k in K) H k = H K$.
+ #[
$H K != empty$ \
$(H K)(H K) = H (K H) K = H H K K = H K$\
$(H K)^(-1) = K^(-1) H^(-1) = K H = H K$\
]
+ #[
Если $H nsubg G$, то $H nsubg H K$. Это тривиально.
Второе утверждение следует из доказательтва третьего.
]
+ #[
Рассмотрим
$
phi: K &--> H K fg H \
k &maps k H
$
Тогда $phi(k_1 k_2) = (k_1 k_2) H = k_1 H k_2 H = phi(k_1) phi(k_2)$, значит $phi$ --- гомоморфизм.
Проверим, что $Im phi = H K fg H$. Рассмотрим $a in H K fg H$. $a = (k h) H = k H = phi(k) ==> a in Im phi$.
$Ker phi = {k in K bar k H = e H} = {k in K bar k in H} = K sect H = H sect K nsubg K$.
Тогда по теореме о гомоморфизме, $K fg (H sect K) iso H K fg H$.
]
]
|
https://github.com/chendaohan/bevy_tutorials_typ | https://raw.githubusercontent.com/chendaohan/bevy_tutorials_typ/main/31_ime_input/ime_input.typ | typst | #set page(fill: rgb(35, 35, 38, 255), height: auto, paper: "a3")
#set text(fill: color.hsv(0deg, 0%, 90%, 100%), size: 22pt, font: "Microsoft YaHei")
#set raw(theme: "themes/Material-Theme.tmTheme")
= 1. IME 输入
Bevy 支持 IME(输入法编辑器),这是人们在使用中文等语言进行文本输入时所使用的方法,也是非键盘文本输入方法(如手写识别)工作的方式。然而,这需要你进行一些特殊处理。
如果你希望所有国际用户能够像在其操作系统上的其他 GUI 应用程序中那样,以他们的语言输入文本,你应该支持 IME。如果你希望为残障用户或喜欢使用手写识别等替代文本输入方法的用户提供良好的可访问性,你也应该支持 IME。这应该是在支持通过键盘输入文本的基础上进行的,因为大多数用户将通过键盘输入文本。
= 2. IME 的工作原理
IME 通过使用一个特殊的“缓冲区”来工作,该缓冲区显示当前正在进行的文本建议,并允许用户预览和撰写文本的下一部分,然后再确认它。文本建议由操作系统提供,但你的应用程序需要为用户显示它们。
例如,假设你的 UI 中有一个文本输入框。你显示用户已经输入的文本,光标位于末尾。
如果启用了 IME,你将收到 Ime::Preedit 事件,用于“待定”文本。你应该在文本输入框中显示该“未确认”的文本,但使用不同的格式使其在视觉上有所区别。
当用户确认他们想要的输入时,你将收到一个 Ime::Commit 事件,其中包含最终文本。然后,你应该丢弃任何先前的“未确认”文本,并将新文本附加到实际的文本输入字符串中。
= 3. 如何在你的 Bevy 应用程序中支持 IME
首先,你需要在应用程序期望文本输入时通知操作系统。你也不希望 IME 在游戏过程中意外激活。
每当你希望用户输入文本时,你需要在窗口上启用“IME 模式”。完成后,禁用它。
如果用户没有使用 IME,启用“IME 模式”时不会发生任何事情。你仍然会像往常一样收到键盘事件,并可以通过这种方式接受文本输入。
如果用户有 IME,你将收到一个 Ime::Enabled 事件。
然后,你可以处理 Ime::Preedit 事件以获取待定/未确认的文本,并处理 Ime::Commit 事件以获取最终/确认的文本。
```rs
fn ime_input(mut input_text: Query<&mut Text, With<InputText>>, mut ime_reader: EventReader<Ime>) {
let Ok(mut text) = input_text.get_single_mut() else {
return;
};
for ime in ime_reader.read() {
match ime {
Ime::Preedit {
window: _,
value,
cursor: _,
} => {
text.sections[1].value = value.into();
}
Ime::Commit { window: _, value } => {
text.sections[0].value.push_str(value);
text.sections[1].value.clear();
}
_ => (),
}
}
}
```
在实际应用程序中,你将希望在屏幕上显示“预编辑”文本,并使用不同的格式显示光标。在“提交”时,你可以将提供的文本附加到通常接受文本输入的实际字符串中。 |
|
https://github.com/extua/october | https://raw.githubusercontent.com/extua/october/main/calendar.typ | typst | MIT No Attribution | #let calendar(year: "", body) = {
set document(title: str(year) + " calendar")
for month in range(1, 13) [
#let month_date = datetime(
year: year,
month: month,
day: 1,
)
#let monthly_days = ()
#for day in range(0, 31) [
#let month_accumulator = (month_date + duration(days: day))
#if month_accumulator.month() != month {
break
}
#monthly_days.push(month_accumulator)
]
#align(center)[
#heading(level: 1)[
#text(size: 27pt)[#month_date.display("[month repr:long] [year]")
]
]
]
#let first_monday = {
int(monthly_days.first().display("[weekday repr:monday]"))
}
#show table.cell.where(y: 0): strong
#pad(
y: 20pt,
table(
columns: (1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr),
rows: (0.4fr, 1fr, 1fr, 1fr, 1fr, 1fr),
inset: 12pt,
table.header(
[Monday],
[Tuesday],
[Wednesday],
[Thursday],
[Friday],
[Saturday],
[Sunday],
),
..range(1, first_monday).map(empty_day => []),
..monthly_days.map(day => [#day.display("[day padding:none]")])
),
)
#pagebreak(weak: true)
]
}
|
https://github.com/linhduongtuan/DTU-typst-presentation | https://raw.githubusercontent.com/linhduongtuan/DTU-typst-presentation/main/Readme.md | markdown | # DTU-typst-presentation
- To continue the topic of using Typst as an alternative for typesetting, I created this repository for creating a template for presentation slides using Typst, which is somewhat similar to Beamer in LaTeX.
- If you are interested in using Typst to compose your thesis, I can recommend my thesis template from my previous repository, called [BKHN-Thesis_template_typst](https://github.com/linhduongtuan/BKHN-Thesis_template_typst).
- I imagine that Duy Tan University has guidelines and regulations for composing presentation slides. So I created this template based on my imagination, which may not be reality. However, this tutorial should help someone modify it for their own tasks, or at least it should serve as learning materials for Typst, and for the Rust language furthermore.
# License
The Duy Tan University Typst slide template is free to use and modify under the MIT License. It was created by <NAME> (see the link for this repository below) and is available under the same license.
For more information, please see the LICENSE file in this repository.
### For further reference:
- *If you want to learn how to create a thesis template, please refer to [my other repository](https://github.com/linhduongtuan/BKHN-Thesis_template_typst).*
- *If you want to learn how to create a scientific poster, please refer to [my other repository](https://github.com/linhduongtuan/VNUHCM-typst-poster).*
### Acknowledgements
1. Thanks to <NAME> for creating the [Typst-slides template](https://github.com/andreasKroepelin/typst-slides/blob/main/LICENSE), which served as the basis for this template.
2. Thanks to @SesameMan for constructing the [typst-slides-nankai](https://github.com/sesameman/typst-slides-nankai), which I borrowed some code from.
3. Thanks to @Survari, who provided tutoring for Typst not only for creating presentation slides but also for other tasks like designing letter templates, thesis templates, and more. You can find his contributions at [typst-seminar](https://github.com/survari/typst-seminar). I referenced certain elements from this repository, such as translating why we should use Typst from German to Vietnamese.
|
|
https://github.com/cloudsftp/zivi.typ | https://raw.githubusercontent.com/cloudsftp/zivi.typ/latest/example.typ | typst | Apache License 2.0 | #import "zivi.typ": *
#show: zivi.with(
author: "Zivi",
title: "A Typst Template",
github: "cloudsftp",
website: "https://cloudsftp.de",
birthday: "2000 BC",
email: "<EMAIL>",
last_updated: "August 2023",
)
= Education
#cventry(
start: (month: "April", year: 2100),
end: (month: "October", year: 2102),
role: "M.Sc. Computer Science",
institution: "University of Stuttgart",
logo: "uni_stgt.svg",
place: "Stuttgart, Germany",
)[
#thesis(grade: "1.0", url: "https://google.com")[
This is a Great Topic and I worked Hard on my Thesis. But it has a very long title. I hope it fits nicely into the box.
]
]
#cventry_long_role(
start: (month: "September", year: 2097),
end: (month: "October", year: 2100),
role: "B.Sc. Computer Science with a title that is entirely too long",
institution: "University of Stuttgart",
logo: "uni_stgt.svg",
place: "Stuttgart, Germany",
)[
- #lorem(6)
- Bachelor Thesis:
#thesis(grade: 1.5)[This is a Great Topic and I worked Hard on my Thesis]
- Final grade: *2.0*
]
= Work Experience
#cventry(
start: (month: "December", year: 2101),
end: (month: "", year: "Present"),
role: [Junior Frobnication Engineer],
place: "WeDontWork Inc.",
lorem(40)
)
= Side Projects
#cventry(
start: (month: "December", year: 2099),
end: (month: "", year: "Present"),
role: [Quux Master],
place: "MasterQuuxers.mars",
lorem(40)
)
#project(
start: (month: "March", year: 2098),
end: (month: "August", year: 2099),
name: "<NAME>",
role: "Full-bar frobnicator",
lorem(40)
)
#project(
start: (month: "March", year: 2098),
name: "<NAME>",
role: "Full-bar frobnicator",
lorem(40)
)
= Languages
#cvlanguage(
language: [Martian],
description: [Mother tongue]
)
#cvlanguage(
language: [Klingon],
description: [C64 level],
certificate: [Earth Klingon Certificate -- Certificate in Advanced Klingon (CAK64)]
)
#pagebreak()
= Technical Skills
#cvcol[
==== Programming Languages
#grid(
columns: (1fr, 1fr, 1fr),
row-gutter: 0.5em,
[- Java],
[- C],
[- C++],
[- Python],
[- Martian],
[- English],
[- ChatGPT],
[- Ancient Greek],
[- Legalese]
)
]
#cvcol[
==== Environments
- Earth (development and server management)
- Wind (development)
- Fire (development)
]
#cvcol[
==== Misc
Various university-related and personal projects, some available on my GitHub profile.
]
= Other
#cvcol[
- Best Pizza Cook Central Mars City 2091 Championship Winner
- Coffee Conossieur
- If You Are Reading This You Are Awesome
]
|
https://github.com/Roger-luo/InvitationLetter.jl | https://raw.githubusercontent.com/Roger-luo/InvitationLetter.jl/main/assets/main.typ | typst | MIT License | #let letter(
year: none,
dates: none,
venue: none,
sender_name: none,
sender_street: none,
sender_city: none,
sender_country: none,
sender_postcode: none,
sender_phone: none,
sender_email: none,
receiver_name: none,
) = [
#set page(
paper: "a4",
margin: (top: 8cm, bottom: 2.5cm, left: 2.5cm, right: 2cm),
header: [
#grid(
columns: (5cm, 5cm),
gutter: 6cm,
grid(
columns: (4cm, auto),
gutter: 3pt,
image("juliacon.svg", width: 4cm),
text(font: "Futura", align(horizon + left)[#year])
),
text(font: "Futura", align(horizon + right)[Conference Invitation])
)
#align(left)[
#text(size: 12pt, style: "italic")[the largest annual conference organized around\ the Julia programming language.]
]
]
)
#let url = "https://juliacon.org/" + str(year)
#set text(size: 12pt)
Dear #receiver_name,
On behalf of the Organizing Committee of the #strong[JuliaCon #year], I am pleased to invite you to participate in the conference scheduled from #strong(dates) at the #strong(venue).
Updated information about the conference can be found at #link(url, text(font: "Monaco", size: 9pt, url)).
#strong[JuliaCon #year] is the largest annual conference organized around the Julia programming language. Julia is a free and open-source language with over 10 million downloads, and is used in areas as diverse as machine learning, finance, engineering, and spaceflight. JuliaCon brings together users, developers, and researchers to share their ideas and experiences and learn about the latest developments.
To facilitate your attendance, we are pleased to provide this official invitation letter to support your visa application process. #strong[JuliaCon #year] has gained significant recognition in both scientific and industrial communities, and we are confident that your participation will further enhance its reputation.
We are looking forward to seeing you in #venue.
\
\
\
\
\
\
\
\
\
\
#pad(right: 2cm)[
#align(right)[
#block(align(horizon + left)[
[signature]
#sender_name
#par(
leading: 0.3em,
)[
tel: #sender_phone\
email: #sender_email\
#sender_street\
#sender_city\
#sender_country, #sender_postcode
]
])
]
]
]
#letter(
year: 2024,
dates: "July 9th-12th, 2024",
venue: [Philips Stadion, Eindhoven, Netherlands],
sender_name: "[Sender Name]",
sender_street: "123 Main Street",
sender_city: "Anytown",
sender_country: "USA",
sender_postcode: "12345",
sender_phone: "+1 234 567 890",
sender_email: "<EMAIL>",
receiver_name: "[Receiver Name]",
)
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/must_know/project_struct.md | markdown | MIT License | # Project structure
## Large document
Once the document becomes large enough, it becomes harder to navigate it. If you haven't reached that size yet, you can ignore that section.
For managing that I would recommend splitting your document into _chapters_. It is just a way to work with this, but once you understand how it works, you can do anything you want.
Let's say you have two chapters, then the recommended structure will look like this:
```typ
#import "@preview/treet:0.1.1": *
#show list: tree-list
#set par(leading: 0.8em)
#show list: set text(font: "DejaVu Sans Mono", size: 0.8em)
- chapters/
- chapter_1.typ
- chapter_2.typ
- main.typ 👁 #text(gray)[← document entry point]
- template.typ
```
<div class="info">
The exact file names are up to you.
</div>
Let's see what to put in each of these files.
### Template
In the "template" file goes _all useful functions and variables_ you will use across the chapters. If you have your own template or want to write one, you can write it there.
```typ -norender
// template.typ
#let template = doc => {
set page(header: "My super document")
show "physics": "magic"
doc
}
#let info-block = block.with(stroke: blue, fill: blue.lighten(70%))
#let author = "@sitandr"
```
### Main
**This file should be compiled** to get the whole compiled document.
```typ -norender
// main.typ
#import "template.typ": *
// if you have a template
#show: template
= This is the document title
// some additional formatting
#show emph: set text(blue)
// but don't define functions or variables there!
// chapters will not see it
// Now the chapters themselves as some Typst content
#include("chapters/chapter_1.typ")
#include("chapters/chapter_1.typ")
```
### Chapter
```typ -norender
// chapter_1.typ
#import "../template.typ": *
That's just content with _styling_ and blocks:
#infoblock[Some information].
// just any content you want to include in the document
```
## Notes
Note that modules in Typst can see only what they created themselves or imported. Anything else is invisible for them. That's why you need `template.typ` file to define all functions within.
That means chapters _don't see each other either_, only what is in the template.
## Cyclic imports
**Important:** Typst _forbids_ cyclic imports. That means you can't import `chapter_1` from `chapter_2` and `chapter_2` from `chapter_1` at the same time!
But the good news is that you can always create some other file to import variable from.
|
https://github.com/EpicEricEE/typst-droplet | https://raw.githubusercontent.com/EpicEricEE/typst-droplet/master/src/extract.typ | typst | MIT License | #import "util.typ": attach-label, space, splittable, to-string
// Regex for valid characters in front of the dropped capital.
#let regex-before = regex({
"["
"\"'" // Dumb quotes
"\p{C}" // Control characters
"\p{Pi}" // Initial punctuation
"\p{Ps}" // Opening punctuation
"\p{Z}" // Spaces and separators
"¹²³\u2070-\u209F" // Superscripts and subscripts
"]+"
})
// Regex for valid characters behind the dropped capital.
#let regex-after = regex({
"["
"\." // Full stop
"\"'" // Dumb quotes / apostrophe
"\p{C}" // Control characters
"\p{Pf}" // Final punctuation
"\p{Pe}" // Closing punctuation
"\p{Z}" // Spaces and separators
"\p{M}" // Combining marks
"¹²³\u2070-\u209F" // Superscripts and subscripts
"]+"
})
// Extracts the first letter of the given content.
//
// The first letter may be none if the content does not contain any letters.
// If the first child cannot be split further, that child is returned as the
// first letter.
//
// Returns: A tuple of the first letter and the rest.
#let extract-first-letter(body) = {
// Handle string content.
if type(body) == str {
let letter = body.clusters().at(0, default: none)
if letter == none {
return (none, body)
}
let rest = body.clusters().slice(1).join()
return (letter, rest)
}
// Handle text content.
if body.has("text") {
let (text, ..fields) = body.fields()
if "label" in fields { fields.remove("label") }
let label = if body.has("label") { body.label }
let func(it) = if it != none { body.func()(..fields, it) }
let (letter, rest) = extract-first-letter(body.text)
return attach-label((letter, func(rest)), label)
}
// Handle content with "body" field.
if body.func() in splittable {
let (body: text, ..fields) = body.fields()
if "label" in fields { fields.remove("label") }
let label = if body.has("label") { body.label }
let func(it) = if it != none { body.func()(..fields, it) }
let (letter, rest) = extract-first-letter(text)
return attach-label((letter, func(rest)), label)
}
// Handle styled content.
if body.has("child") {
let (child, styles, ..fields) = body.fields()
if "label" in fields { fields.remove("label") }
let label = if body.has("label") { body.label }
let func(it) = if it != none { body.func()(it, styles) }
let (letter, rest) = extract-first-letter(child)
return attach-label((letter, func(rest)), label)
}
// Handle enumeration items (interpreted as text, e.g. "5. Body" or "+ Body")
if body.func() == enum.item {
let (body, ..fields) = body.fields()
let number = fields.at("number", default: none)
return if number == none {
("+", body)
} else if number < 10 {
(str(number), "." + body)
} else {
(str(number).first(), str(number).slice(1) + "." + body)
}
}
// Handle list items (interpreted as text, e.g. "- Body")
if body.func() == list.item {
return ("-", body.body)
}
// Handle sequences.
if body.has("children") {
let child-pos = body.children.position(c => {
c.func() not in (space, parbreak)
})
if child-pos == none {
// There is no non-empty child, so no letter.
return (none, body)
}
let child = body.children.at(child-pos)
let (letter, rest) = extract-first-letter(child)
if body.children.len() > child-pos {
rest = (rest, ..body.children.slice(child-pos+1)).join()
}
return (letter, rest)
}
// Handle unbreakable content.
return (body, none)
}
// Extracts the dropped capital from the given content.
//
// The dropped capital contains the first real letter (or number) of the
// content, but can be preceded by opening punctuation characters, and followed
// by a sequence of closing punctuation characters.
//
// For example, the dropped capital of "Hello, world!" is "H", and the
// dropped capital of "1. Hello, world!" is "1." including the dot.
//
// Returns: A tuple of the dropped capital and the rest.
#let extract(body) = {
let (letter, rest) = extract-first-letter(body)
if letter == none {
return (none, body)
}
// We can only append punctuation characters if the first letter can be
// converted to a string, but not if it's e.g. a 'box' or 'image'.
if to-string(letter) != none {
// Append opening punctuation characters until the first "real" letter.
while to-string(letter).last().match(regex-before) != none {
let (next-letter, new-rest) = extract-first-letter(rest)
if next-letter == none { break }
letter += next-letter
rest = new-rest
}
// Append closing punctuation characters.
let (next-letter, new-rest) = extract-first-letter(rest)
while next-letter != none and to-string(next-letter).match(regex-after) != none {
letter += next-letter
rest = new-rest
(next-letter, new-rest) = extract-first-letter(rest)
}
}
return (letter, rest)
}
|
https://github.com/danbalarin/typst-templates | https://raw.githubusercontent.com/danbalarin/typst-templates/main/README.md | markdown | # Typst templates
This repository contains custom templates for [Typst](https://typst.app/).
## Usage
To use a template, simply copy the template's content and paste it into the Typst editor.
Note that some templates may contain more than one file.
|
|
https://github.com/AliothCancer/AppuntiUniversity | https://raw.githubusercontent.com/AliothCancer/AppuntiUniversity/main/DispositiviMedicali.typ | typst | #import "style.typ": apply_style
#apply_style[
// DOCUMENT CONTENT STARTING POINT
#align(center + horizon, text(30pt)[
*Dispositivi medicali itps*
])
#let date = datetime(year: 2024, month: 09, day: 13).display("[day] [month repr:long] [year]")
#align(center, date)
#pagebreak()
#outline(indent: auto, depth: 4)
#pagebreak()
#include "capitoli_dispositivi/01ValvoleCardiache.typ"
#include "capitoli_dispositivi/02ExeValvole.typ"
#include "capitoli_dispositivi/03ProtesiVascolari.typ"
]
|
|
https://github.com/MattiaOldani/Informatica-Teorica | https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/appunti.typ | typst | // Titolo e indice
#import "template.typ": *
#show: project.with(
title: "Informatica teorica"
)
#pagebreak()
// Introduzione
#include "capitoli/00_introduzione.typ"
#pagebreak()
// Teoria della calcolabilità
#parte("Teoria della calcolabilità")
#pagebreak()
// Capitoli di teoria della calcolabilità
#include "capitoli/calcolabilità/01_richiami_matematici.typ"
#pagebreak()
#include "capitoli/calcolabilità/02_sistemi_di_calcolo.typ"
#pagebreak()
#include "capitoli/calcolabilità/03_richiami_matematici.typ"
#pagebreak()
#include "capitoli/calcolabilità/04_cardinalità.typ"
#pagebreak()
#include "capitoli/calcolabilità/05_potenza_computazionale.typ"
#pagebreak()
#include "capitoli/calcolabilità/06_dati_NN.typ"
#pagebreak()
#include "capitoli/calcolabilità/07_programmi_NN.typ"
#pagebreak()
#include "capitoli/calcolabilità/08_richiami_matematici.typ"
#pagebreak()
#include "capitoli/calcolabilità/09_calcolabilità.typ"
#pagebreak()
#include "capitoli/calcolabilità/10_sistemi_di_programmazione.typ"
#pagebreak()
#include "capitoli/calcolabilità/11_problemi_decisione.typ"
#pagebreak()
#include "capitoli/calcolabilità/12_riconoscibilità_automatica_insiemi.typ"
#pagebreak()
// Teoria della complessità
#parte("Teoria della complessità")
#pagebreak()
// Capitoli di teoria della complessità
#include "capitoli/complessità/13_richiami_matematici.typ"
#pagebreak()
#include "capitoli/complessità/14_dtm.typ"
#pagebreak()
#include "capitoli/complessità/15_utilizzare_le_dtm.typ"
#pagebreak()
#include "capitoli/complessità/16_richiami_matematici.typ"
#pagebreak()
#include "capitoli/complessità/17_risorsa_tempo.typ"
#pagebreak()
#include "capitoli/complessità/18_risorsa_spazio.typ"
#pagebreak()
#include "capitoli/complessità/19_tempo_vs_spazio.typ"
#pagebreak()
#include "capitoli/complessità/20_zona_grigia.typ"
#pagebreak()
#include "capitoli/complessità/21_ndtm.typ"
#pagebreak()
#include "capitoli/complessità/22_p_vs_np.typ"
#pagebreak()
#include "capitoli/complessità/23_situazione_finale.typ"
|
|
https://github.com/Seanwanq/Typst-Course-Report-Template | https://raw.githubusercontent.com/Seanwanq/Typst-Course-Report-Template/main/main.typ | typst | #import "@preview/tablex:0.0.8": *
#import "template.typ": *
#import "sourcerer.typ": *
#show: MSTemplate.with(
reportName: "Template homework",
authorName: "<NAME>",
courseName: "Modeling and Simulations",
professor: "Prof. dr. it. <NAME> and Dr. <NAME>",
date: "April 25th, 1974",
IsComplexEquationNumberingOn: true,
ShowProfessorName: false,
)
= The basics
The easiest way to edit a Typst file is using #link("https://typst.app")[typst.app] online
editor, a browser based editor that already has all the required packages
installed. Try importing this project to typst online editor and edit there.
After opening this project in typst online editor, the first thing to edit is
the information about you and the course. You can change that above. For
example, the title can be changed in `#Title(reportName: "Template homework")`.
== Images <section>
The inclusion of figures needs to be inside the environment _figure_. You can
see an example below.
#FigureBlock(
captionAlign: "l",
)[
#figure(
placement: none,
image("figures/swallow.jpg", width: 60%),
caption: [
Figure caption edited here. The position of the image can be controlled by
changing the `h` above. Use `t` for top of the page, `b` to bottom of the page,
`h` to fix the position of the image, and `auto` to let typst decide. The
alignment of caption can also be adjusted, by changing the `captionAlign` above,
`l` indicates left, `r` indicates right, and `c` indicates
center@FigureFunctionTypst.
],
) <figure>
]
=== Sub figures
Multi figures can also be combined using the `subfigure` environment.
#FigureBlock(
captionAlign: "c",
)[
#figure(
placement: auto,
caption: [Pictures of animals.],
)[
#grid(
columns: (1fr, 1fr, 1fr),
gutter: 10pt,
)[
#subfigure(image("figures/gull.jpg"), caption: [A gull], lbl: <fig:gull>)
][
#subfigure(image("figures/tiger.jpg"), caption: [A tiger], lbl: <fig:tiger>)
][
#set align(bottom)
#subfigure(image("figures/mouse.jpg"), caption: [A mouse], lbl: <fig:mouse>)
]
]<fig:parent>
]
For more information see #link(
"https://typst.app/docs/reference/model/figure/",
)[Typst>Reference>Model>Figure].
*Remark:* It is hard to place the iages and tables exactly where we want.
Sometimes it is better to let Typst win.
== Math mode
Euqations can be embedded in the text with `$...$`. For example, $a^2 = b^2 +c^2$.
And can be highlighted with
$
alpha^2 = beta^2 + gamma^2
$
$
sum_x^2
$<eq-1>
Code like `<eq-1>` added labels to equations, figures, tables, etc. For
equation, only those with labels will show reference numbering on the right.
This method enables the referencing of equations using @eq-1. The same is true
for figures (@figure, @fig:gull), tables (@table1), sections (@section),
etc@ReferenceFunctionTypst...
For more information see #link("https://typst.app/docs")[Typst documents] and #link(
"https://sitandr.github.io/typst-examples-book/book/about.html",
)[Typst example book].
= Code snippets
To include code snippets we use a 3#super[rd] party library called `codly`.
Import the library at the beginning of the document@CodlyREADMEMd:
#code(lang: "Typst", ```typ
#import "codly.typ": *
```)
And then you can write code like the example.
#figure(
code(lang: "C", ```c
// Simple C program to display "hello world"
// Header file for input output functions
#include <stdio.h>
// main functions
// where the excution of program begins
int main()
{
// prints hello world
printf("hello world");
return 0;
}
```),
kind: "code",
supplement: [Listing],
caption: [A code listing.],
placement: auto,
)<code1>
For more information see #link(
"https://github.com/typst/packages/tree/main/packages/preview/codelst/2.0.0",
). To refer it, use `@code1` to get @code1.
= Lists
The inclusion of list, such as enumerate or bullet points are very easy to make.
== Enumerate
+ Point 1;
+ Subpoint 1;
+ Subpoint 2;
+ Subsubpoint 1;
+ Point 2;
+ Point 3.
Without an empty line between, it will be:
+ Point 1;
+ Point 2;
+ Point 3.
== Bullet points
- Bullet 1;
- Subbullet 1;
- Subsubbullet 1;
- Bullet 2;
- Bullet 3.
Without an empty line between, it will be:
- Bullet 1;
- Bullet 2;
- Bullet 3.
= Tables
Tables are generated with a 3#super[rd] party library called `tablex`. Import it
at the top of the document using:
// ```typ
// #import "@preview/tablex:0.0.8": *
// ```
Below is an example of a table.
#show figure.where(kind: table): set figure.caption(position: top)
#figure(tablex(
auto-lines: false,
columns: 3,
(),
vlinex(),
vlinex(),
(),
[A1],
[B1],
[C1],
hlinex(),
[A2],
[B2],
[C2],
), kind: table, supplement: "Table", caption: [Table caption]) <table1>
For more complex configurations, please refer to #link("https://github.com/PgBiel/typst-tablex").
#bibliography("Typst.bib", title: "References", style: "gb-7714-2005-numeric")
|
|
https://github.com/ludwig-austermann/typst-timetable | https://raw.githubusercontent.com/ludwig-austermann/typst-timetable/main/timetable.typ | typst | MIT License | #import "@preview/tablex:0.0.5": tablex, rowspanx
#import "lib/helper.typ" as lib
#import "lib/default-blocks.typ"
#let timetable(
all-data,
language: "en",
date: datetime.today().display("[day].[month].[year]"),
show-header: true,
show-alternatives: true,
show-description: true,
tablex-args: (:),
event-cell: default-blocks.event-cell,
time-cell: default-blocks.time-cell,
color-theme: "tab",
) = {
let lang-dict = if type(language) == str {
lib.load-language(language)
} else { language }
let colors = if type(color-theme) == str {
lib.load-color-theme(color-theme)
} else { color-theme }
let (times, courses, description, slots, alts) = lib.process-timetable-data(all-data, colors)
let final-data = times.enumerate().map(
time => (
time-cell(time.at(1), lang-dict),
lib.weekdays.enumerate().map(d => slots.at(d.at(0)).at(time.at(0))).map(ev =>
if ev == none {
[]
} else if ev.at("occupied", default: false) {
()
} else {
let cell = event-cell(
ev,
show-time: time.at(1).at("show-time", default: false),
unique: ev.at("unique", default: true)
)
if ev.duration > 0 { rowspanx(ev.duration + 1, cell) } else { cell }
}
).flatten()
).flatten()
).flatten()
// Title
if show-header {
text(16pt, strong(lang-dict.title + " " + all-data.general.period))
" " + lang-dict.of + " " + all-data.general.person
if date != none {
h(1fr)
date
}
}
// Main Timetable
tablex(
columns: (auto, 1fr, 1fr, 1fr, 1fr, 1fr),
stroke: (
paint: gray,
thickness: 0.5pt,
dash: "dashed"
),
..tablex-args,
[], ..lang-dict.weekdays.map(day => align(center, day)),
..final-data,
)
show link: underline
// Alternatives
if show-alternatives and alts.len() > 0 {
text(14pt, lang-dict.alternatives + ":")
v(-12pt)
table(
columns: (1fr, 1fr, 1fr, 1fr, 1fr),
column-gutter: 5pt,
//stroke: gray + 0.5pt,
stroke: none,
..alts.map(
ev => event-cell(ev, show-time: true, show-day: true)
)
)
}
// Abbreviations
if show-description {
text(14pt, lang-dict.description + ":")
v(-6pt)
style(sty => {
let h = measure([Hello], sty).height
table(
columns: description.len() + 2,
stroke: (
paint: gray,
thickness: 0.5pt,
dash: "dashed"
),
..tablex-args, // at the moment tablex does not span the whole width
none, none, ..description.map(d => strong(d.title)),
..courses.filter(
c => not c.at("hide-description", default: false)
).map(
c => (
rect(fill: c.color, width: h, height: h),
strong(c.abbrv),
..description.map(
d => (d.contentfn)(c.at(d.id, default: "")) // wraps content in link or other stuff
)
)
).flatten()
)
})
}
}
|
https://github.com/Nrosa01/TFG-2023-2024-UCM | https://raw.githubusercontent.com/Nrosa01/TFG-2023-2024-UCM/main/Memoria%20Typst/capitulos/2.1.AutomatasCelulares.typ | typst | #import "../utilities/gridfunc.typ": *
#import "../data/gridexamples.typ": *
#import "../data/data.typ": *
En este capítulo se hablará sobre el concepto de automátas celulares, su historia y su relevancia en la ciencia y matemáticas. Además, se presentarán algunos ejemplos de autómatas celulares relevantes en la investigación científica. Posteriormente se hablará sobre los simuladores de arena, su impacto y su relación con los autómatas celulares.
== Autómatas celulares
Los autómatas celulares @cellular_automata_thomasmli son un modelo matemático discreto que se representa como una matriz n-dimensional de celdas. Este modelo puede ser de cualquier número de dimensiones, aunque los más comunes son los autómatas celulares de una y dos dimensiones. Cada celda en esta matriz puede existir en uno de varios estados posibles, que son finitos en número. Existe un consenso sobre la definición teórica de automátas celulares que los describe como modelos deterministas, sin embargo, en su aplicación práctica, los autómatas celulares pueden ser tanto deterministas como estocásticos. Esto es debido a que la naturaleza de ciertos sistemas dependen de variables aleatorias, por lo que resulta más adecuado modelarlos como sistemas estocásticos.
El cambio de estado de una celda se determina en función de los estados de las celdas vecinas y se produce en unidades discretas de tiempo, denominadas generaciones @ca_andrew. En este contexto, el término "vecinos" hace referencia a las celdas que se encuentran adyacentes a una celda específica.
En el caso particular de los autómatas celulares de dos dimensiones, existen dos tipos de vecindades que se utilizan comúnmente: la vecindad de Moore y la vecindad de Neumann @ca_karl_johannes. En la vecindad de Moore, se consideran como vecinos las ocho celdas que rodean a una celda central, incluyendo las celdas diagonales. En la vecindad de Neumann, por otro lado, solo se consideran como vecinos las cuatro celdas que están directamente arriba, abajo, a la izquierda y a la derecha de la celda central.
Finalmente, para definir completamente un autómata celular, se requiere una "regla" que se aplica a cada celda. Esta regla establece cómo cambiará el estado de una celda en la siguiente generación, basándose en los estados actuales de la celda y sus vecinos. Dicho de otro modo, la regla es la que transforma el sistema de celdas de su estado actual al estado siguiente en cada generación.
Para ilustrar mejor el concepto de autómata celular se muestra un ejemplo a continuación. Este es un automáta celular de 2 dimensiones. Cada celda puede tener dos posible estados: `Apagada` o `Encendida`. La regla de este sistema es que si la celda está `Apagada` y cualquier de sus vecinos está `Encendida` entonces pasa a estar `Encendida` en la siguiente iteración. Por el contrario, si la celda está `Encendida` y cualquiera de sus vecinos está `Apagado` entonces pasará al estado `Apagado`. En resumen, los estados alternan periódicamente.
#pagebreak()
A continuación se muestra un ejemplo de este sistema con 3 iteraciones:
#grid_example("Ejemplo de autómata celular sencillo", (state_01_ex1, state_02_ex1, state_03_ex1))
Una característica distintiva de los autómatas celulares es su evolución "simultánea" o en bloque. En este modelo matemático, todas las celdas cambian de estado al mismo tiempo, de una generación a la siguiente. Esta simultaneidad en la evolución es fundamental para la dinámica del autómata celular, contribuyendo a su robustez y predictibilidad.
Muchos automátas celulares pueden representarse como una máquina de Turing @petzold-2008. Una máquina de Turing es un modelo matemático de un dispositivo que manipula símbolos en una cinta de acuerdo con una serie de reglas. Aunque las máquinas de Turing son abstractas y teóricas, se consideran un modelo fundamental de la computación y han sido utilizadas para demostrar la existencia de problemas no computables.
A su vez, la Máquina de Turing puede ser vista como un autómata que ejecuta un procedimiento efectivo formalmente definido. Este procedimiento se lleva a cabo en un espacio de memoria de trabajo que, teóricamente, es ilimitado. A su vez, algunos autómatas celulares pueden ser vistos como máquinas de Turing.
A continuación, se procede a examinar su trayectoria histórica y su significativa contribución a la ciencia y las matemáticas.
=== Historia
El concepto de autómatas celulares tiene sus raíces en las investigaciones llevadas a cabo por <NAME> en la década de 1940. <NAME> fue un matemático húngaro-estadounidense, principalmente reconocido por la arquitectura de computadoras que lleva su nombre. Además de esto, realizó muchas contribuciones en diversos campos: Participó en el proyecto Manhattan, contribuyó de forma notable a la teoría de juegos, a la teoría de conjuntos y en física cuántica. Además de esto realizó importantes contribuciones en la teoría de autómatas y sistemas auto-replicantes @theory_self_replication.
<NAME> se enfrentó al desafío de diseñar sistemas auto-replicantes, y propuso un diseño basado en la autoconstrucción de robots. Sin embargo, esta idea se encontró con obstáculos debido a la complejidad inherente de proporcionar al robot un conjunto suficientemente amplio de piezas para su replicación. A pesar de estos desafíos, el trabajo de <NAME> en este campo fue fundamental y marcó un punto de inflexión significativo.Según @von2017general, su trabajo seminal en este campo fue documentado en un artículo científico de 1948 titulado "The general and logical theory of automata".
<NAME>, un matemático polaco y colega de <NAME>, conocido por su trabajo en la teoría de números y su contribución al diseño de la bomba de hidrógeno, propuso durante este período una solución alternativa al desafío de la auto-replicación. Ulam sugirió la utilización de un sistema discreto para crear un modelo reduccionista de auto-replicación. Su enfoque proporcionó una perspectiva que ayudó a avanzar en el campo de los autómatas celulares.
En 1950, Ulam y <NAME> desarrollaron un método para calcular el movimiento de los líquidos, concebido como un conjunto de unidades discretas cuyo movimiento se determinaba según los comportamientos de las unidades adyacentes. Este enfoque innovador sentó las bases para el nacimiento del primer autómata celular conocido.
Los descubrimientos de <NAME> y Ulam propiciaron que otros matemáticos e investigadores contribuyeran al desarrollo de los automátas celulares. Sin embargo, no fue hasta 1970 que se popularizaron de cara al público general. En este año, <NAME>, divulgador de ciencia y matemáticas estadounidense, escribió un artículo @gardner_article en la revista Scientific American sobre un automáta celular específico: el juego de la vida de Conway. Su artículo generó un gran interés en los autómatas celulares y los sistemas dinámicos, lo que llevó a un aumento significativo en la investigación y experimentación en este campo. En el siguiente apartado se hablará en más detalle sobre el juego de la vida de Conway y otros autómatas celulares relevantes.
=== Ejemplos
A continuación se mostrarán diversos ejemplos de automátas celulares, comenzando por el conocido `Juego de la Vida de Conway` @ca_andrew. Posteriormente, se presentarán: los autómatas de Wolfram, la Hormiga de Langton, el autómata de contacto y el autómata de Greenberg-Hastings.
==== Juego de la vida
El Juego de la Vida, concebido por el matemático británico <NAME>, es un autómata celular bidimensional que se desarrolla en una cuadrícula teóricamente infinita de células cuadradas. Cada una de estas células puede estar en uno de dos posibles estados: `viva` (negra) o `muerta` (blanca).
El Juego de la Vida es un ejemplo de un sistema que exhibe comportamiento complejo a partir de reglas simples. Estas reglas, que determinan el estado de una célula en la siguiente generación, son las siguientes:
- Si una célula viva está rodeada por más de tres células vivas, muere por sobrepoblación.
- Si una célula viva está rodeada por dos o tres células vivas, sobrevive.
- Si una célula viva está rodeada por menos de dos células vivas, muere por soledad.
- Si una célula muerta está rodeada por exactamente tres células vivas, se vuelve viva.
Para el conteo de células vivas adyacentes se considera una vencidad de Moore --- es decir, se tienen en cuenta las ocho células que rodean a una célula central.
Como se mencionó anteriomente, estas reglas se aplican simultáneamente a todas las células en la cuadrícula --- es decir, todos los cambios de estado ocurren al mismo tiempo en cada paso de tiempo.
#grid_example("Ejemplo del Juego de la Vida", (game_of_life_01, game_of_life_02, game_of_life_03), vinit: 1pt)
A pesar de su aparente simplicidad, el Juego de la Vida es capaz de generar una diversidad notable de patrones y estructuras. Algunos de estos patrones son estático. Un patrón estático es aquel en el que las células que lo forman mantienen su estado de generación en generación @ca_andrew. Un ejemplo de esto es el "bloque", que consiste en un cuadrado de 2x2 células vivas rodeadas por célular muertas o viceversas, y el "bote", que se asemeja a una forma de L compuesta por cinco células vivas. La @static_structures muestra ejemplos de estructuras estáticas en el Juego de la Vida.
#grid_example("Estructuras estáticas en el juego de la vida", (game_of_life_block, game_of_life_hive, game_of_life_bread, game_of_life_boat, game_of_life_bath), vinit: 1pt, ref: "static_structures")
Existen también patrones oscilatorios, que alternan entre dos o más configuraciones. Un ejemplo sencillo de esto es el "blinker", una formación lineal de tres células vivas que oscila entre una orientación horizontal y vertical. La @oscillatory_structures muestra un ejemplo de estructura oscilatoria en el Juego de la Vida.
#grid_example("Blinker, estructura oscilatoria del juego de la vida", (game_of_life_blinker1, game_of_life_blinker2, game_of_life_blinker1), vinit: 1pt, ref: "oscillatory_structures")
Adicionalmente, se pueden observar patrones que se desplazan a lo largo de la cuadrícula, a los que se les denomina "naves espaciales". El más simple de estos es el "planeador", un patrón de cinco células que se mueve en una trayectoria diagonal a través de la cuadrícula.
#grid_example("Planeador, estructura moviente del juego de la vida", (game_of_life_glider1, game_of_life_glider2, game_of_life_glider3, game_of_life_glider4, game_of_life_glider5), vinit: 1pt)
El Juego de la Vida ha sido objeto de considerable estudio en el campo de la teoría de la complejidad. Ha demostrado ser un modelo útil para explorar conceptos como la autoorganización, la emergencia de la complejidad en sistemas dinámicos, y la computación universal (la capacidad de simular una máquina de Turing) @ca_andrew @cellular_automata_thomasmli. A pesar de su aparente simplicidad, el Juego de la Vida esconde una riqueza de comportamientos complejos y sorprendentes, y continúa siendo un área activa de investigación y experimentación.
==== Autómatas de Wolfram
Los Autómatas de Wolfram @ca_karl_johannes, ideados por el físico y matemático <NAME>, son un conjunto de reglas que rigen el comportamiento de autómatas celulares unidimensionales con estados binarios. Estos autómatas consisten en una línea de celdas, cada una de las cuales puede estar en uno de dos estados: 0 o 1.
Cada regla en el conjunto de autómatas de Wolfram determina cómo cambia el estado de una celda en función de su estado actual y los estados de sus vecinos inmediatos (la celda a la izquierda y la celda a la derecha). Dado que cada celda y sus dos vecinos pueden estar en uno de dos estados, hay $2^3 = 8$ configuraciones posibles para una celda y sus vecinos.
Cada regla se puede representar como un número binario de 8 bits, donde cada bit corresponde a una de las 8 configuraciones posibles de una celda y sus vecinos. Por lo tanto, hay $2^8$ = 256 reglas posibles, numeradas del 0 al 255.
Aunque los autómatas de Wolfram son unidimensionales, a menudo se visualizan en dos dimensiones para mostrar cómo evolucionan con el tiempo. En esta visualización, cada generación (o iteración) del autómata se representa como una nueva fila debajo de la fila anterior. Esto permite ver cómo los estados de las celdas cambian con el tiempo y cómo emergen patrones a partir de las reglas simples del autómata.
A continuación se muestra la regla 30 @wolfram_30 de Wolfram tras ejecutar 15 iteraciones de este:
#align(center + horizon)[Regla 30 de Wolfram]
#grid_example("", (rule30_01, rule30_02, rule30_03, rule30_04, rule30_05, rule30_06, rule30_07, rule30_08), vinit: 0pt)
#grid_example("Ejemplo autómata de Wolfram", (rule30_15gens,), vinit: 0pt)
==== Hormiga de Langton
La "hormiga de Langton" @ca_karl_johannes @langtonOnline, es una máquina de Turing bidimensional de 4 estados, se describe de manera sencilla de la siguiente manera. Se considera un tablero cuadriculado donde cada casilla puede ser negra o blanca, y también puede contener una hormiga. Esta hormiga tiene cuatro direcciones posibles: norte, este, oeste y sur. Su movimiento sigue reglas simples: gira 90 grados a la derecha cuando está sobre una casilla negra, y 90 grados a la izquierda cuando está sobre una casilla blanca, tras lo cual 'avanza' en dicha dirección. Además, al 'dejar' una casilla, ésta cambia de color. El proceso comienza con una sola hormiga en una casilla blanca. Al principio, su movimiento parece caótico, pero después de un cierto número de pasos, se vuelve predecible, repitiendo un patrón cada cierto tiempo. En este punto, la parte del rastro de la hormiga que está en casillas negras crece de manera periódica, extendiéndose infinitamente por el tablero.
En el autómata celular de la hormiga de Langton, se tienen 10 estados posibles. Estos se derivan de 2 colores de celda (blanco y negro), y la presencia de la hormiga. Cuando la hormiga está ausente, se consideran los 2 estados de color. Cuando la hormiga está presente, se consideran 4 direcciones posibles (norte, este, oeste y sur) para cada color de ceSlda. Por lo tanto, se tienen 2 estados (colores) cuando la hormiga está ausente, y 2 (colores) \* 4 (direcciones) = 8 estados cuando la hormiga está presente. En total, se tienen 2 + 8 = 10 estados.
Cabe destacar que la hormiga no se mueve en sí misma, sino que cambia el estado de las celdas en las que se encuentra @ca_karl_johannes. Cuando la hormiga está en una celda, esa celda cambia de color y la hormiga desaparece. Sin embargo, una de las celdas adyacentes notará que la celda vecina tenía una hormiga orientada en su dirección, lo que provocará que su estado cambie para incluir la hormiga en la siguiente iteración.
Para una mejor comprensión, se pueden considerar dos celdas adyacentes: una celda blanca sin hormiga y, a su derecha, otra celda blanca con una hormiga orientada hacia arriba. En un autómata celular, el estado de una celda es dependiente de sus vecinos. En este escenario, la celda vacía detecta que su celda vecina contiene una hormiga orientada hacia arriba y es de color blanco. De acuerdo con las reglas de la hormiga de Langton, la hormiga debería girar a la izquierda, que es la ubicación de la celda vacía. Como resultado, el estado de la celda vacía cambiará a ser blanca pero ahora con una hormiga orientada hacia la izquierda. Simultáneamente, la celda que originalmente contenía la hormiga cambiará su estado a estar vacía y se tornará de color negro.
#grid_example("Ejemplo simple de la hormiga de Langton", (langton_ant_01, langton_ant_02, langton_ant_03, langton_ant_04, langton_ant_05, langton_ant_06), vinit: 1pt)
A partir de las 10.000 generaciones aproximadamente, la hormiga de Langton muestra un comportamiento periódico que se repite en un ciclo de 104 generaciones. Este es el resultado en la generación 11.000:
#grid_example("Ejemplo completo de la hormiga de Langton", (langton_ant_final,), vinit: 1pt)
// #align(center + horizon)[
// #grid(
// fill: (x, y) => rgb(
// if angton.at(x + y * 80) == 0 { white }
// else { black }
// ),
// stroke: rgb(100, 100, 100) + 0.03em,
// columns: (3.25pt,) * 80,
// rows: (3.25pt,) * 80,
// align: center + horizon,
// )
// ]
==== Autómata de Contacto
Un autómata de contacto @ca_karl_johannes puede es uno de los modelos más simples de la propagación de una enfermedad infecciosa. Este autómata está compuesto por 2 estados: `celda infectada` (negra) y `celda no infectada` (blanca). Las reglas son las siguiente: Una celda infectada nunca cambia, una celda no infectada se vuelve una celda infectada si cualquiera de las 8 celdas adyacente es una infectada. Existe una versión no determinista en la que la una celda no infectada se infecta pero con una probabilidad _P_. Este modelo es muy útil en la investigación de la propagación de enfermedades infecciosas, ya que en una situación real existen variables aleatorias como se mencionó anteriormente.
#grid_example("Ejemplo de autómata de contacto determinista", (state_01_contact_automata, state_02_contact_automata, state_03_contact_automata), vinit: 10pt)
==== Autómata de Greenberg-Hastings
Los autómatas de Greenberg-Hastings @ca_karl_johannes son modelos bidimensionales compuestos por células que pueden estar en uno de tres estados: reposo, excitado y refractario. Estos autómatas son particularmente útiles para simular patrones de propagación de la actividad eléctrica en tejidos cardiacos, así como otros fenómenos de propagación y ondas.
La evolución de las células en un autómata de Greenberg-Hastings se rige por reglas locales que determinan la activación y desactivación de las células en función de su estado actual y el estado de sus vecinos. Estas reglas son las siguientes:
- Reposo: una célula en estado de reposo se mantendrá en reposo a menos que al menos uno de sus vecinos esté en estado excitado. En ese caso, la célula pasará al estado excitado en el siguiente paso de tiempo.
- Excitado: una célula en estado excitado se moverá al estado refractario en el siguiente paso de tiempo, independientemente del estado de sus vecinos.
- Refractario: una célula en estado refractario se moverá al estado de reposo en el siguiente paso de tiempo, independientemente del estado de sus vecinos.
Estas reglas simples permiten la propagación de la excitación a través del autómata, creando patrones de propagación que pueden ser analizados y estudiados.
Los automátas celulares han sido una influencia en el mundo del videojuego. Existen diversos juegos y hasta géneros basados en autómatas celulares. El siguiente apartado tratará sobre los simuladores de arena y su relación con los autómatas celulares. |
|
https://github.com/Fabioni/Typst-TUM-Thesis-Template | https://raw.githubusercontent.com/Fabioni/Typst-TUM-Thesis-Template/main/template/utils.typ | typst | MIT No Attribution | #let inwriting = true
#let draft = true
#assert(not(inwriting and not(draft)), message: "If inwriting is true, draft should be true as well.")
#let todo(it) = [
#if inwriting [
#text(size: 0.8em)[#emoji.pencil] #text(it, fill: red, weight: 600)
]
]
#let silentheading(level, body) = [
#heading(outlined: false, level: level, numbering: none, bookmarked: true)[#body]
]
|
https://github.com/deadManAlive/ui-thesis-typst-template | https://raw.githubusercontent.com/deadManAlive/ui-thesis-typst-template/master/main.typ | typst | #import "primer/primer.typ": main, primer
#import "primer/pre.typ": pre
#show: doc => primer(doc)
#pre
#main()[
#include "chapters/ch1.typ"
#pagebreak(weak: true)
#include "chapters/ch2.typ"
#pagebreak(weak: true)
#bibliography("sources.bib", style: "ieee", title: [Daftar Pustaka])
] |
|
https://github.com/layandreas/typst-resume | https://raw.githubusercontent.com/layandreas/typst-resume/main/cv_andreas_lay_en.typ | typst | #import "alta-typst.typ": alta, term, skill, styled-link
#alta(
name: "<NAME>",
links: (
(name: "email", link: "mailto:<EMAIL>"),
(name: "website", link: "https://layandreas.github.io/personal-blog/", display: "layandreas.github.io/personal-blog/"),
(name: "github", link: "https://github.com/layandreas", display: "@layandreas"),
(name: "linkedin", link: "https://www.linkedin.com/in/andreas-l-684252a4", display: "<NAME>"),
),
tagline: [Senior Data Scientist with strong expertise in ML, Statistics, Time Series Forecasting & Software Engineering],
[
== Experience
=== Senior Data Scientist \
REWE Group\
#term[Since Aug 2019][Cologne, Germany]
- Architecture & development of analytical applications including dockerized deployment in Google Cloud
- Setting up CI/CD pipelines: Cloud Run, Cloud Build Github Actions
- Data engineering: Setting up streamed / scheduled ELT jobs using dbt, Snowflake, Kafka & BigQuery
- Modelling & implementation of time series forecasts + optimization algorithms
- Infrastructure-as-code: Automatized deployment of cloud resources using Terraform
- Architecture & implementation of custom analytics platform in Google Cloud: Load balancing, authentication, app deployment templates, CI/CD pipelines
- Modelling of fraud probability for ECOM business
- Building of customer segmentation workflow using Apache Beam and Dataflow
- Supporting ECOM business units in their decisions with high-quality data analysis and modelling
- Support of testing team in designing and evaluating A/B tests on website and app
=== Credit Risk Modeler \
Deutsche Bank AG (formerly Deutsche Postbank AG)\
#term[Oct 2015 --- Sep 2019][Bonn, Germany]
- Modelling of loan default probability and credit loss rates for the retail customers portfolio used for lending decisions and capital requirements
- Setting up and deployment of automatized model monitoring to ensure model stability and performance
- Project work with respect to fully integrating Postbank into Deutsche Bank Group
=== Market Risk Management Intern \
DZ Bank AG Singapore Branch \
#term[Sep 2014 --- Jan 2015][Singapore]
- Analysis of market risk positions for Capital Markets as well as Treasury portfolios (Value-at-Risk, risk factor sensitivity analysis)
- Daily P&L reporting and corresponding analysis using Murex
== Scholarships
=== Friedrich Ebert Foundation \
Academic merit scholarship granted by the Friedrich Ebert Foundation for the duration of a two year master's programme
#colbreak()
== Education
=== MSc in Quantitative Economics \
University of Tübingen\
#term[Oct 2013 --- Sep 2015][Tübingen, Germany]
GPA: 1.6#super[\*]
=== BSc in International Economics \
University of Tübingen\
#term[Oct 2009 --- May 2013][Tübingen, Germany]
GPA: 1.6#super[\*]
=== Exchange Student \
National Taiwan University \
#term[Aug 2011 --- Feb 2012][Taipei, Taiwan]
=== Abitur (A-Levels) \
Saarlouiser Gymnasium am Stadtgarten \
#term[Graduation: May 2009][Saarlouis, Germany]
GPA: 1.7#super[\*]
_#super[\*]On a scale from 1.0 to 4.0 where 1.0 is the best_
== Skills
=== Programming / IT
_Languages_ \
Python • R • SAS • SQL • HCL • VBA • Stata • Matlab
_Frameworks_ \
scikit-learn • xgboost • pandas • numpy • plotly • django • fastapi • pytorch • Streamlit
_Tooling_ \
Google Cloud Platform • git • Github • Gitlab • docker • terraform • dagster • nginx • dbt • Jira • Confluence
_Databases & Streaming_ \
BigQuery • Snowflake • PostgreSQL • Oracle • Teradata • Db2 • Kafka • Beam • GCP Pub/Sub
=== Languages
German (native speaker) • English (fluent) • Spanish (conversational) • Mandarin Chinese (basic)
],
)
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/046%20-%20Streets%20of%20New%20Capenna/002_The%20Contract%20Breaker.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Contract Breaker",
set_name: "Streets of New Capenna",
story_date: datetime(day: 28, month: 03, year: 2022),
author: "<NAME>",
doc
)
Most people take one look at someone like Perrie and think "head basher," but Perrie's rise through the Brokers has given him more interesting assignments, and more complex fights, than just basic bashing heads. It's their poor imagination that stops them from seeing the mind in that enormous head on those cable-thick neck muscles.
#figure(image("002_The Contract Breaker/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Perrie pulls up the tall, armored tips of his collar and ignores the whispers swirling in the dark light of the velvet-walled lounge around him. "Broker~enforcer~watch out~Junash: you better get out of here."
Perrie has just ducked under the door frame to enter, careful not to catch his horn on the frame's varnished mahogany top. The padded door shuts behind him as he scans the lounge. He's not looking for Junash—apparently a harried aven with wings that droop sadly behind him as he runs out the back—Perrie's here for a maniacal little street brawler by the name of Krent.
There's security in the corner. Two leonin. Their brass-engraved eyeglasses reflect the purple light, enchanted into the form of liquid rope that's draped corner to corner across the lounge. Security's fuzzy ears flick toward Perrie. They look relaxed, but wary.
Perrie gives them the nod. Muscle to muscle. He isn't here to be a problem, just looking. But the one on the left recognizes Perrie. His ears flatten, and he bares his fangs.
"Oh, buddy," Perrie rumbles. "That's a #emph[baaad] idea."
Here in the Mezzio, the lounges are neutral territory. All the families need to cut loose and relax somewhere, right? The Cabaretti own most of the lounges, though.
That makes this place #emph[neutral-ish] , Perrie supposes.
Perrie wonders if these Cabaretti bouncers are truly ready to come at a Broker enforcer on an errand?
Apparently so: the two leonin split up and cut through the flashy dancers lost in the warm flush of each other's company as they rhythmically tap their feet against their partners' and smile too widely at each other.
The leonin to Perrie's left pulls out a loaded violin. Red light shimmers up and down its strings as the light catches it.
For a moment, it's just the three of them. Two leonin, cat-like and towering over the dancers shrinking away from them all as they realize something's wrong, and Perrie. Perrie the enforcer; a rhox, gray and hulking, his tiny eyes examining the situation, his great single horn tilting as he smiles slightly.
Perrie raises his hands. "You gonna point that my way? All I've done is walk in, haven't even had time for refreshment—"
"We know who you are." The bouncer on the right licks his lips. Nerves. Perrie can see the faintest ridge of fur standing up on the bouncer's neck.
A small weaselly man darts around the varnished bar top and shoves his way through the padded double doors behind all the drinks.
"There we are," Perrie mutters. He takes a step forward, and the two bouncers close rank in front of him.
"You can't come in here after the customers," they say.
"If you weren't hassling me, there'd be nothing to disturb your customers about," Perrie says slowly and calmly. "I'm just passing through."
"Got a reputation to keep here."
Perrie knows all about reputations. He's been focused on the exit, following his target. But now he's paying all his attention on these two jumped-up cats. Some people just couldn't leave well enough alone. These two have something to prove. And Perrie, several steps ahead of them, knows that if he doesn't answer the challenge, word'll get out that Perrie's gone soft. Then things will get harder for him.
From the gaudy, clouded Park Heights balanced on their girders overlooking the city, to the Mezzio where the lights danced up and down the swept lines of building facades, to the Caldaia's Halo smoke–spewing stacks, people were all just trying to get on with it. Hustle hard during the day, dance the night away. Perrie's no different. He has a job to do. And these cats are getting in the way.
A bead of light splits the wood paneling on the nearby wall to reveal a door concealed by magic. A craggy-faced elf in a dapper metal-edged suit steps out, looks over at Perrie, and then weaves through the crowd as if playing the smoothest game of hopscotch Perrie's ever seen.
"Ari, Leonard, it's okay. Let him through." The elf brushes the cuffs of his pinstriped suit and smiles at everyone.
"But Mister—"
The elf's eyes flash. "I hired the two of you because in a pinch you might—I repeat might—be able to stand against an enforcer. But I'm not paying to find out tonight."
The leonin grumble a bit, but visibly back down.
Perrie nods at the elf and shoulders his way past the two bouncers.
"The buzzies say you're on the outs with the Brokers," the bouncer on the right snarls. "Rumors say you've been judged a contract-breaker. Something to do with a kid. You're soft. How long before an enforcer shows up to render a verdict on #emph[you] , Perrie?"
"Other families have wiggle room, but a Broker breaking contract?" the other bouncer laughs. "There is no room for interpreting #emph[those] . You're washed up, Perrie."
Perrie pauses right by the door. This is one of those moments, isn't it? Since Perrie's fallen into a strange limbo with the Brokers, he's been careful. No unnecessary mix-ups, no fights. But after all that laying low, Perrie's feeling taut, like something's been growing deep inside of him for the last few days and is ready to burst out.
The leonin have fixed him with all-black eyes, pupils fully dilated. The ears are back, their bodies almost vibrating.
Okay. Time to pop this blister, Perrie thinks.
"Good kitty," he says softly to the bouncer on his right with a wink.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Perrie leans against a smooth limestone wall in the alley across from the lounge. He pats the inner pockets of his coat to check if an old, shattered pocket watch he's carried since his boxing days is okay. It's still in one piece.
A flash of light makes him wince, and a young leonin in a pinstripe vest walks out of the glare to stand by Perrie's elbow as sparks fall to the ground and dance in the garbage.
"Rigo," Perrie grunts.
Rigo pats down his vest. He flicks a few errant sparks off with professional satisfaction, pushes a short swoop of hair off to his right, and flicks his ears.
"Heard there was commotion. I knew it would be you. The two bouncers asleep on the pavement over there. That you?"
"Yeah." Perrie spits blood into the gutter. The cold stone feels good against his head. He knows he's gonna have some serious bruises in the morning. Worse—one of the leonin got a claw up under his suit and into his thick skin. He'll need to get that looked at. But word will get out that Perrie's still a brawler and not someone to be tangled with.
Rigo, his face pinched, fuzzy and broad, scratches his chin and chuckles. Canines flash. "Feel better with that out of your system?"
"I'll still catch up to Krent," Perrie sighs. He turns around to look at the solicitor. Rigo's street-smart, has an ear to the ground with a network of street urchins. He knows how it goes in the alleys and shadows. "It had to be taken care of."
Rigo laughs. "Can't help yourself, can you?"
"Word'll get out that I'm still more trouble to bother than it's worth." Perrie changes the subject. "You know where I stand with leadership?"
"Tired of the grunt-work assignments?" Rigo chuckles and ignores Perrie's request to share anything he might know. "You shouldn't take it out on the bouncers. They're just the help, Perrie."
"Hrmh," Perrie grunts. He once saw Falco toss a man out a Park Heights window. For months after that, Perrie had been nervous about going up to the top of Nido Sanctuary to report to the boss.
"You can forget Krent," Rigo says. "They sent some new kid to sniff him out."
"Krent's a heavy hitter." Perrie took a deep breath, winced as his ribs stabbed at him.
"Kid'll be fine." Rigo taps an ear. "Reports say he's doing his bit."
Perrie reaches up to feel his left ear. The Amplifier is still snug against his ear canal, whispering to him. But it's all static and muffled. He fiddles about with it, cursing his thick fingers.
The words become distinguishable again. Updates. Orders. Calls for action. Once he'd been assigned Krent, Perrie stopped paying much attention. The fight must have knocked it the wrong way around.
#emph[Perrie: wait for Rigo and further orders] , the Amplifier whispers, along with other orders for Brokers in the streets. #emph[Stand down, Perrie. Stand down.]
"I've never been called off a mission before," Perrie notes. Feels like a noose closing on him, if he's honest.
Rigo shrugs. "First time for everything."
"Not how it works with Brokers." Letter of the law. Order. Everything in its place. From Falco on down, one could count on the Brokers' obsession with procedures.
"You're choosing #emph[now] to worry about the letter of the law?" One of Rigo's thick eyebrows arches with amusement. "Didn't worry you when you balked about that kid."
Rigo pulls out a small vial of Halo and swirls it around in front of his face. Time to go. Perrie feels a lump in his stomach, and it's not just from the bruises the leonin left him with; Rigo is taking him back to Nido Sanctuary. Back to face judgment. Falco's let him twist in the wind long enough, apparently.
He could run right now. The Brokers could send solicitors after him, but Perrie's the meanest skull-cracking enforcer they have. They probably couldn't stop his escape.
#emph[Probably.]
Perrie steps forward. The glow of Halo casts dappled swirls of light around the alley, and spotlights dance in the sky overhead, signs that the upper crust of Park Heights are out having a good time.
"You haven't eaten anything recently, have you?" Rigo checks.
"Just get this over with," Perrie says, and a flash of white light envelops them as Rigo teleports them off to their headquarters.
#figure(image("002_The Contract Breaker/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Time to face the boss.
Falco stands by the doors to the balcony where the wind tussles his feathers slightly. His wings loom over him, like supplicants that arch to hold a crown over a king's head. For an aven, Falco dominates the room. Perrie gets a glimpse of how contract breakers must feel when he arrives, making a dent in the chatter and atmosphere as he takes up space with his muscle and bulky coat.
"I have a job for you, Perrie," Falco says, no pleasantries, no greeting. No need for him to say it's an important one. The fact that he sent Rigo to deliver Perrie here personally, that says everything.
Falco steps heavily past winged metal patterns on the room's wall that glint with the light from the many upwardly aimed sconces.
#figure(image("002_The Contract Breaker/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"What about the boy?" Perrie asks after a long moment.
Falco slams a fist into a nearby table. Contracts flutter to the floor. "I'm giving you a job, and you want to ask about your failure?"
"He's a child." Perrie stands firm on the other side of the room, though his eyes can't help but drift to the big windows behind Falco's desk. Perrie's seen people thrown out of them. This conversation could be a death sentence.
But while a contract's a contract, fair is also fair.
"Have you ever seen what happens to a plane where order falls apart, Perrie?" Falco clasps his hand behind his back and walks forward.
Perrie swallows. "He didn't know what he was signing. He was a child."
"That #emph[child] sells newspapers across from a major Obscura meeting point."
Perrie doesn't flinch at Falco's fury. "You know what they do to someone spying on them. Child or not."
"When contracts fail, the stitches that bind the plane together loosen and the fabric of society frays. Then it all comes down around us." Falco steps in front of Perrie. "You know the prophecy demands we hold this city together against what's coming. Are you turning your back to it?"
Perrie looks down at his boots. "I know we're going to need all those contracts and pacts cashed in." Every signed promise, every binding contract, all the whispers and pledges given in the dark, they are all for a reason.
He doesn't understand all the ins and outs. He can't read, he can't make out the tiny letters with his eyes, so he's always been grateful for the Amplifier in his ear and the gossip around the fountains. Over the years, Perrie's learned that something big is coming. That the Brokers have been getting ready for years, building an army of obligations and promises that most of the pledgers are magically bound to respect, even if those same spells hide that memory from them.
Legions of people, waiting to be activated, and most don't even know it.
"I haven't made a judgement on the case, yet," Falco says softly. "But I may have a way for you to prove yourself useful to the cause."
"I serve the law." Perrie slaps his chest in a salute, then winces.
"We've banked so much Halo even Ziatora noticed that the street supply is affected. She's worked hard to sniff out where it's going. Got a Riveteer in her pocket that stole plans to the newest Halo honeycomb storage before we could fully wipe their memory. I'm sending Kros after them, but I want someone to go with, provide muscle."
"Kros?" Perrie sighs. He doesn't work with partners. And he certainly doesn't want Kros breathing down his neck, reporting every little mistake back to Falco.
"Kros informs me the Riveteer's under a gag order," Falco says. "But she has actual parchment plans. She might not be able to speak to anyone about them, she probably doesn't remember why she's on the run until he looks down at the plans. Then she understands what she has and starts running again. Go. Find this contract breaker. Get the plans back. Leave the Riveteer alive. But make them wish they're dead. Dump the contract breaker in front of the Treza so that Ziatora gets the message. Even that dragon needs to know that you can't break a contract with us."
A faint rustle in the air behind Perrie tells him Kros has slipped into the room. Every Broker is a solicitor, all equal before the law. But Falco rules the family, and there are various other roles that need filled. Perrie enforces contracts, and Kros styles himself as a ranger straight out of Old Capenna, exploring the city's nooks and crannies. He finds the remains of forgotten places the family can use to set up aviaries that solicitors use as hideouts when needed. He started out as a middleman, though. A defense contractor who liked well-tailored clothes and receptions on balcony's high above the city where big deals could be made on a handshake and a smile. Kros's probably standing in a shadowy part of the room, hoping to step out at the right moment in a faint haze of blue to startle Perrie. He loves the flash and drama of it all.
#figure(image("002_The Contract Breaker/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
That works on new recruits, green under the collar. Not Perrie. He's clocked Kros out of the corner of an eye. All trench coat and shiny, well-polished shoulder armor, high-end leonin haircut carefully styled to rakishly fall back toward his shoulders. More flash than substance, Perrie feels. A real Broker should have tarnish streaks from being outside, working contracts in the streets.
There's a decision here Perrie needs to make. Stay and wait for a ruling and find out just how doomed he is, or hustle and prevent the Riveteers from figuring out what his family is up to. Maybe when he gets back, he'll find Falco inclined to rule favorably. Or at least not murderously.
Perrie nods to where Kros hides in the shadow as he makes a decision. "Let's go find us a Riveteer, Kros. Sounds like time isn't waiting on us."
When he turns, the sour look on Kros's face wipes away the exhaustion making Perrie's bones creak at the moment.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"I'm not happy about this mission, either," Kros snaps as they take a car across the Mezzio, just another chitinous, scarab-like vehicle dodging its way down the lanes of street between the swooping scaffolding of city skyscrapers that led to the girders of Park Heights. The driver is a Broker who keeps an ear on passenger conversations for the organization.
Perrie looks out at a well-heeled crowd in line for a theatrical production standing on the corner of King's Street and Butchers.
"Drink this." Kros hands Perrie an elixir as they cross a bridge that seems to float in the air. Perrie's stomach flutters, he isn't one for heights, even if that's all New Capenna is. A city perched on girders, hovering over the land the people in it once walked.
So many uses for Halo. Perrie wonders about that a lot. How dependent has the city become on it in such a short time. "I don't need—"
"If you aren't tip-top, you aren't useful to me. This isn't any Riveteer we're after. Jolene, she's a demolitionist."
They call them bulldozers on Perrie's street. Jolene could, no doubt, pull a whole building down on them if they aren't careful.
"You may have heard her called the 'Plunder Queen.' We showed up to give her some~legal assistance when she got herself caught breaking into a jewelry shop's vault. Thought an iron-clad construction contract would cover us, but she's wilier than we realized. Perrie, drink up already."
Perrie tosses back the elixir in a single swallow. He doubles over as the healing effects painfully reknit broken bone.
At least his headache eases.
He watches people in fedoras slouch down the street and wonders about their lives. That one going home with bread tucked under his arm, was that to a family waiting for their dad to finish a late shift at a factory in the Caldaia? His coat glitters with Halo effusion from the stacks.
The driver takes them down a ramp, deeper into the bowels of New Capenna, where Broker power fades further into the shadows. No gleaming corner offices down here. It's the industrial heart of the city, the foundry on which New Capenna sits that breathes for the city. The streets and lights above them now are where respectable families scheme and shake their hands on pacts made in their Park Height aeries. But down here, the city's bellows labor day and night, groaning under the weight of the structures above.
#figure(image("002_The Contract Breaker/05.jpg", width: 100%), caption: [Art by: <NAME> <NAME>], supplement: none, numbering: none)
Down here, work gets done, Perrie thinks.
Men in flat caps and threadbare shift clothes glare at the shiny insect panels of the vehicle. Perrie and Kros stand out with their clean pinstripes, carefully tailored armor inserts that evoke class and martial leanings, and the clear wealth of the personal transport.
"What are the chances we get jumped just for being down here in this rolling beetle of a machine?" Perrie grunts.
"I'm not wasting Halo on travel. I need to hold onto every little bit we can carry. We'll need it," Kros says. He taps the driver. "The factory, there."
Several minutes later, they stand inside the slumped girders of a rotting building. The stained-glass windows feature cubist portraits of angels that stand on guard before a stylized impression of New Capenna's skyline, but a third of the colored glass has been shattered, likely by looters, or vagrants tossing rocks at them.
Kros pulls a crowbar out of his jacket and levers a manhole cover open.
"In there?" Perrie looks dubiously down into the dark. Something smells bad down there. Like it died, crawled down several blocks of city gutters, then slipped through a drain and died again once down there. And it's still dying. "Kros, where are we going?"
"Outside," Kros says. "Ever been?"
Perrie stares at Kros. The man has held the headline back from him.
"My mom's people," Perrie says. "They got in during the second exodus. The Riveteers tightened it all up after that. Just heard stories."
Mom still lives in the same dingy apartment down in the Verts, not far away from the basement rings Perrie got his start boxing in. The Pulverizer, they called him. Printed it up on broadsheets plastered all up and down the lower parts of town.
Simpler days. Before death and misfortune, before Falco took him in. Perrie misses it, sometimes. But never misses being hungry all the time.
"The Riveteer, she's down there?" Perrie eyes the manhole dubiously. They don't get along. Like a pair of annoying siblings, Kros and Perrie came up in the Brokers together, running errands for the older, grizzled solicitors. This could be a prank. Kros messing with him.
The darkness on the other side of the manhole is emptiness, and maybe a faint shimmer of some leftover spell. And maybe, beyond that, one could squint and see the old ruins of something that used to exist down on the ground before New Capenna.
Kros buttons up his jacket and pulls on a pair of heavy gloves. "Took me years to find this, but the Riveteers know more of them. They find weak spots during demolition or construction."
"Weak spots?"
"Hidden tunnels. Ladders. Gaps in the structure." Kros swings down through the hole in the floor into the dark. If it's a prank, he's committed to it fully.
Perrie stares at the shadows below. "And Jolene's really out #emph[there] ?"
"Too many solicitors sniffing around every nook and cranny in New Capenna looking for her. Falco made it the number-one priority."
"I never heard anything over the Amplifier." Perrie drops slowly down, barely able to fit through the round hole, and kicks his feet around to find the ledge. He doesn't want to let go and drop forever.
Kros grabs the back of Perrie's coat and pulls him over. "Solicitors Falco trusts, and that he told in person, face to face."
They crouch on a ledge near the bulk of a city girder. A rusted set of ladder steps leads down and away into the dark void below.
"Down we go!"
Kros starts climbing down, and Perrie eyes the steps warily, not sure if they'll hold the weight of a full-grown rhox enforcer.
#figure(image("002_The Contract Breaker/06.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Perrie doesn't want to climb a ladder down to the ground his ancestors fled from, the hammer slung over his shoulder clanking and banging against every other rung. He's had an hour to grumble about it all as they slowly made their way down, and Kros hasn't responded once. Too focused on making sure he didn't get rust on his coat, Perrie thinks.
But if he wants to get back into Falco's good graces, and get his life back to normal, Perrie is going to have to push on here. Kros is one of Falco's most trusted advisors. There's a good chance, Perrie thinks, that he can fix everything that went wrong. Because right now, there's not a single solicitor in New Capenna that will look at Perrie without disgust on their face.
He's broken a contract. It is simple as that.
What had he been thinking, crossing Falco like that? The aven family boss is so unbendingly strict, only the stupid and suicidal break contracts. Even other family bosses make sure to follow the letter of Falco's law.
Kros is the only hope for Perrie's restoration. If he gives a good report to Falco, maybe Perrie won't find out what it was like for an enforcer to be on the other side of an enforcement action.
Perrie shudders.
He can't ever put himself in a position like this again. He should be knocking heads to collect debts, warning transgressors, and finding new contacts to bind to their legal needs.
That is the way it's supposed to work. You're in a bad situation, things looking grim, and there's a flash of white light near the commotion. A dapper-suited citizen sidles out of the shadows, asks if you need help, and offers to make it all go away.
For a small favor, one you didn't even have to remember.
"Here we go," Kros mutters.
Perrie looks down to see the dark outlines of an ancient castle. The walls have long since fallen, slumped into a pile of rubble. The girder they're climbing down splits the castle in two, like a metal spear thrown into the structure's heart.
When they let go of the last few rungs and hit the ground on their feet, Kros lightly, and Perrie with a solid thud, Kros smiles. "Welcome to the old country."
He seems at ease with all this, but Perrie squints as he looks around. Slumped rubble and old walls loom out of a passing mist that's sandwiched between the underbelly of New Capenna above and the ground below. Light from over a distant hill is just a thin sliver of horizon.
"Can you track?" Kros asks.
Perrie pulls a monocle from his breast pocket and settles it onto his right eye. Gauzy skeins of color waft about the ruins and cobblestones of the old plane.
"Faint sign, that way," Perrie nods. "It's a fresh trace, could be Jolene."
The moment Jolene broke contract and ran, it sent up a magic flare brighter than a spotlight outside the Grand Opera House. Broker solicitors would have been able to trace it easily with the right tools, like Perrie's monocle. Down here, outside New Capenna, far from Nido Sanctuary, Perrie has only the faintest smudge of color to follow.
Kros has what looks like a pair of opera glasses in his hands. "I see it, too."
A short, furry form dressed in a leather jacket steps out onto the pocked, weed-infested cobblestones. Raccoonfolk. Perrie glances around at the flashes of eyes in the shadows of the ruined walls all about them.
"Kros~"
The man already has his hands up, and his gloves shimmer with blue light. There's a faint, arrogant smile on the edges of his lips.
"Not from the city," Perrie mutters. The knee-stabbers won't hold back, he guesses. There aren't unspoken rules about inter-family dust-ups down here. These raccoonfolk are feral, not like the chatty street urchins and day laborers in the city above.
And maybe that's why Kros has that ghastly grin on his face. Maybe that's what it takes to become one of Falco's inner circle.
"Hey there, buddy," Kros says in an even but somewhat curious tone. "We're looking for a friend."
He has a small portrait on paper. Kros holds the uncannily lifelike representation up in the air for the raccoonfolk to see.
"Our friend—"
Twenty furred, snarling, and clearly starving raccoonfolk attack.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Perrie's been breaking kneecaps and bruising faces a long time. Sometimes cracking limbs here and there. Regular city-folk always worried about families tossing citizens out the window. #emph[Kite rides] , they called it.
Truth is, it almost never happens to common folk.
And there isn't #emph[that] much brawling. Perrie spends most of his time tracking, sniffing around for potential new contracts, and walking the streets so that people see a Broker enforcer out keeping order.
As raccoonfolk pour over them, Perrie kisses the rings on his fingers for the first time in weeks. He hasn't even broken them out for the bouncers. Light plays across his hands into the shape of brass knuckles. More light flows over his right fist to form a gauntlet, with tendrils of light running back up Perrie's massive arms
"Ya gotta embrace who the plane wants you to be, I guess," Perrie grumbles, and starts swinging.
It's satisfying, in a deep, animalistic way. Every punch connects, and he can feel bone give. With every meaty thwack, every crushing punch, raccoonfolk scatter. They may have seen a rhox fight before, but they've never seen one radiant with the glow of a magic like this.
Perrie isn't just a bruiser, he thinks of himself as a master tactician. He knows when to avoid the knockout so that he can drag a body in front of him as a shield. He can see the way the fight shapes up on old cobblestones, as if watching from above.
The raccoonfolk regroup and swarm for another attack, looking only for the blood they can draw with knives and claws, and Perrie is thinking four or five moves ahead.
There's a leader here.
There's always a leader. And if you watch the rhythm of the fight, spot where the gaps are and who they're protecting, you can feel the locus of power. Like a spider sitting in the center of a web.
It's a dance. And when the scrappy, scarred leader of their attackers suddenly realizes Perrie isn't faltering or overwhelmed but has been using open spaces and moments in the fighting to get closer to him, he panics and runs rather than ending up on the receiving end of Perrie's fists.
For the first time in days, Perrie smiles widely.
That had been a small war, and the lesser general had run for the hills.
"Quit gloating, we have work to do," Kros says from the shadows of a slumped wall. He cleans blood off a long dagger and tucks it away under his coat again.
Perrie's smile fades, and he looks at Kros with enough raw malice that Kros fiddles with the edge of his vest. "When you're ready."
Perrie sweeps his hand out, like a butler indicating the way into a waiting room.
Kros starts to take a step forward, and the entire wall he's been using as cover slumps down onto him with a horrifying groan. Rocks tumble out, mortar dust fills the air, and there's nothing more than a hill of debris where the solicitor had once stood just a split second ago.
"Kros?" Perrie's somewhat stunned. Kros might annoy him, they might have years of almost sibling-like rivalry, but for a moment he can't move. Kros's fast, quick to spot any attacks, and is usually gone before his attacker understands what happened.
"Kros!"
Falco's not going to let Perrie back up the Broker command structure if he got Kros killed. Perrie's now thinking about the more horrible things Falco might do to him, which is a mistake. The cobblestones under Perrie's feet vibrate.
Demolition magic.
The road cracks open underneath Perrie.
No one ever expects the big brawlers to move too quickly, but Perrie can sprint. And he moves now like his life depends on it.
Because it does.
Rubble strikes his thick skin, knocking the breath out of him. Old boulders roll down the road. There's nothing but chaos and dust in the air as Perrie forgets tactics or next steps, he's just whipping about in random directions to avoid getting crushed.
Their prey knew they'd be coming. Set up a trap.
Probably told the raccoonfolk where to find some soft strangers, ripe for mugging.
Perrie has his eyepiece out as he tries to get out of defense and grab some of the initiative in the fight. Where is this damn Riveteer?
Too much chaos. It's hard to get a read.
But his ears twitch. Footsteps?
Perrie arrows off the street into the ruins of an old stable and inn. There's still a faint smell of horse in the air, even though it's been centuries since the old city was fully populated.
#emph[There] . A cough. The flying dust has irritated someone's throat.
Even in a battle, little things like this are often the difference between victory and defeat. Perrie pulls his hammer out from where its awkwardly slung under his coat. He'll need it to face someone this powerful.
The hammer hums with anticipation.
Perrie tightens his grip, his eyes narrow as he turns, his ears flicking with each tiny sound. His pinstripe suit is tattered and ripped. It flaps as he slams his hammer through the nearest wall. It might not be demolition magic, but the result is the same: Perrie destroys the wall.
The Riveteer in the debris and dust has gauntleted, jeweled metal fists that glow. Perrie catches the first punch, feels it shatter bones in his hand, and swings the hammer up. Jolene dodges, tries to grab at the hammer, and hits him in the forearm with a magically charged punch that chatters his teeth.
#figure(image("002_The Contract Breaker/07.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Perrie headbutts her.
She flies back and hits the wall, gauntlets up, ready for him.
Perrie raises the hammer. "We both swing at the same time, we can bring it all down on us. I know I can walk away, can you?"
Jolene looks around at the walls and ancient, rotted beams. For a split second, she almost takes the step forward and starts the fight. Something blinks behind her eyes, a faint whisp of a spell.
"You've got something that belongs to us."
She says nothing. Just waits. Way too calmly.
"Yes, she certainly does," Kros says from behind Perrie. Of course, he's not dead. Perrie should be relieved. Falco won't call for an execution. Perrie's chances of living through all this just shot way up.
But he's still annoyed he's done the hard work as Kros—
Perrie glances at his old rival and sees the blood dripping from a gash on Kros's head. The man isn't gliding gracefully out of the shadows, he's limping up to them. Every breath Kros takes is a rattle.
Looks like Kros barely got out of that alive.
"But that's not all she's got," Kros says.
The air crackles with energy and forms as Kros throws coherent energy out into the air. Perrie's expecting explosions or pain, but instead a veil of heaviness he hasn't noticed falls away and Jolene gasps.
She looks utterly disoriented.
"Obscura spell," Kros wheezes. He grabs Perrie's shoulder to steady himself.
"It's not the Riveteers?" The Obscura would have sunk a ton of costly magic into forcing a Riveteer under their thumb like that. Perrie shudders with sympathy, even though he'd been about to crack her skull just a split second ago.
"I don't have the plans anymore," Jolene says. "Even under Obscura compulsion, I'm not that stupid."
"Then, I have questions to ask you," Kros whispers. He lets go of Perrie's shoulder and wobbles forward. He barely acknowledges Perrie, just drags a leg awkwardly past. His fingers glow with magic.
A magical deposition. Perrie shudders.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"We have a problem," Kros says later as he lets go of Jolene's forehead. Wisps of his blue magic dance around her eyes. Kros can wipe memories, a useful solicitor skill for setting up contracts that the person who signed doesn't even remember.
Even more useful to them right now is that he can use the same skills to go digging for memories in depositions.
Kros stumbles when he steps back toward Perrie. He's been doing battle in Jolene's mind, no doubt. And Kros, injured, has had to fight to get something.
"Plans?" Perrie asks.
Kros sits down on a chunk of rubble after pushing aside an old, termite-filled wooden beam. He takes a deep breath.
Perrie glances at Jolene. She's tied up, and after Kros's magic, in no mood to talk. Her eyes are glazed and distant. He's a little impressed. She's a short, heavily muscled Riveteer, and she has almost killed them both.
"They abducted her from her own apartment," Kros says. "Forced her into being an Obscura agent, working for the Riveteers."
"So~" Perrie's confused. "We can still get the plans, wipe her memory, and go back to Falco. Right?"
Even as he says it, he knows it won't be that simple. He's just trying to get Kros to reassure him that everything's going to be all right.
"Obscura make a point of knowing everything that's happening. They've been trying to figure where Halo is going missing, and it led them to Riveteers working on construction for us. They've been feeding Riveteers false information, saying that Brokers have been hurting their workers. We dump what seems like yet another beaten-up Riveteer on the streets, with her memory wiped, we start a war." Kros leans back against a leaning pillar and closes his eyes. "This is all a trap, she's the bait."
"The Obscura know that Falco's hoarding Halo?" The stuff is almost currency at this point. Some of the other families had to start sniffing around about shortages in the city. But Falco wasn't expecting it to happen this soon.
"They've figured out that we're doing it, but they don't know why. They're trying to knock us back into our place," Kros says. "Obscura think that they're the heirs to the city just because they know everything. They're always trying to make sure everything remains the same. Arrogant idiots."
"What do we do?" Perrie looks at Jolene. "Falco said—"
"I know what Falco said," Kros covers his face with his hands. "But we do that, we launch a war between the Riveteers and us."
"Isn't that what Falco wants?"
"No! He wants to show that a contract is a contract. He's not ready for a war. Not yet. It's still too early."
There's a larger plan in the air. Something Perrie's not privy to. He's never been told why Falco's fanatically hoarding as much Halo as the Brokers can get their hands on. But he can feel the pieces moving about, and he sees the empty spaces. It's something big, whatever it is.
Maybe even historic. They've hidden a lot of Halo.
"A war with the Riveteers will destroy everything we've been working toward," Kros says. "It's the Obscura we need to be worried about."
"We go and tell Falco," Perrie nods.
"Falco ordered us to do a job," Kros responds.
Perrie stares a moment. "Even if—"
"You of all people," Kros shouts, "should know how absolute your instructions are with Falco."
And Kros wouldn't risk his spot at the top of the organization.
Perrie's still shocked. "People will die if we start a war. A lot of people."
He imagines whole buildings falling. Explosions. Fights in subterranean caverns. Teams of Riveteers bursting out of walls or ducts to kill them. Because it won't be brawling for territory, the bosses would play for keeps.
Falco would need a general, then. A master tactician. It could be a way back into Falco's good graces.
But a lot of innocent lives would get caught in the crossfire.
Perrie sighs and stands up. "You're too hurt to travel. Stay here with the Riveteer, I'll send someone back to help."
"Perrie, you can't go back to Falco empty-handed. He'll—"
Perrie laughs. "How many lives will I save if I do?"
Kros looks at the ground. "You're risking your life. You understand that, right?"
"I know," Perrie says. "I know."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Perrie still has a wobble in his step and the afterimage of Rigo's transportation magic in his eyes when he's shoved into Falco's office. The corridors here brim with Brokers getting ready for a war. Everyone's packing magical heat, and they're all jumpy.
#figure(image("002_The Contract Breaker/08.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
If the streets are as wound up as this, all it'll take is a single wrong glance, an ill word, and the Riveteers and Brokers would slash each other's throats.
"I see no plans, I see no Kros," Falco growls. The hand-carved doors to the balcony are wide open. The swooping buttresses of other buildings loom in the night outside, and alabaster gargoyles glare across at Perrie.
He swallows.
"Is Kros alive?" Falco turns his back and looks out at the heights.
"He's making his way back. With the Riveteer, Jolene." Perrie's faced off against some of the most dangerous people in New Capenna. Right now, he's afraid that if he breathes too deeply, it'll disturb Falco, so he's holding his breath.
Falco's voice drops several octaves. "But no plans."
"It was a trap." Perrie lets out the deep breath. Slowly, strategically. "We can get the plans back, but they aren't as important as who really stole them."
Falco still has his back to him. He flutters his wings, and the snapping crack startles Perrie.
"Obscura?" Falco asks.
"How did you—" Perrie should know by now that Falco has his ways.
Falco steps out onto the balcony, out into the garish light of Park Heights. The city glitters out below him from there. "Take a step outside into the fresh air with me."
Perrie's been relieved of his hammer and knuckles, but he still has brawn. And that isn't much against a boss like Falco, he thinks, as his shoulders slump.
Perrie tentatively crosses the threshold and stands on Falco's balcony for the first time in his life. Falco spreads his wings slightly to let the air ruffle his feathers. He closes his eyes.
"Do you know some people who join me out here are so overcome with emotion," Falco says, "that they sometimes slip and just~fall right off the edge?"
Perrie's not sure what to say to that. Is he being threatened? Is he about to join them? He'd do his best to take the boss with him, he knew that for sure. But Falco isn't acting like someone about to move against him.
"Don't worry, Perrie. Your mind isn't that weak. People don't realize you're a tactician. But I've seen you in action." Falco smiles over his shoulder. "You're no one's fool."
Falco leans against the railing and waves his hand at all New Capenna. He looks, Perrie thinks for the first time, tired. Ancient.
#figure(image("002_The Contract Breaker/09.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"There's a war coming, Perrie. All this, every solicitor, every pact we bound someone to, all that Halo we have hidden away across the city, it's just preparation. I'm going to need you in the days ahead. But, we have a loose end dangling between us."
Perrie lets out another deep breath. "The boy?"
"No one can break a contract." Falco folds his arm behind his back. "No one. There are smaller sacrifices we must make if we're to save the city. You know how this works. You left those two leonin bouncers looking at the sky earlier because you saw the bigger picture. Take your step up into leadership, or—"
The "or" dangles in the air above the balcony, much like Perrie assumes he will, shortly.
Perrie looks Falco in the eye and shoves his hands into his pockets. Falco stands on the edge by the railing, arms behind his back, vulnerable, almost taunting Perrie. Try it, the Broker boss seems to be saying with his body language.
All Perrie's ever wanted is right here. He can agree that the boy broke a contract and deserves the same punishment as any other citizen of New Capenna that crosses the Brokers. He does that, Falco's dangling a promotion in front of him. Join the inner circle to help the boss fight a war he's been planning for many long years.
Or defy Falco and go flying~with no wings.
"I stand by what I said last week," Perrie says slowly. "There's words on a paper that you sign and agree to, and then there's what's right. The boy broke his contract, but he was just a scared kid, trying not to get stepped on by either organization."
"If the child had done what I'd asked, you wouldn't have been down under the city getting made a fool of by the Obscura," Falco hisses. "If he'd done his job, we'd likely be a step ahead, instead of stuck with a mess and possible bloodshed."
"Likely," Perrie repeats.
"Likely." Falco carefully folds his wings back and takes a step forward.
"Is it worth winning anything if we have to harm children to do it?" Perrie steps forward as well, hands still in his coat pockets. He looks up at Falco with defiance. "Because it isn't to me."
"I have brawlers," Falco says. "I don't need more."
Perrie waits, as stony and still a statue as the gargoyles staring at them from the other building's facade.
"I have tacticians smarter than you, many of them," Falco continues.
"Then use them," Perrie snaps.
Falco laughs. He turns abruptly to stalk back inside his offices. "I need something different from you, Perrie. I still need you to go see that boy for me. I still need you to protect Broker reputations, or everything we built falls apart."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Perrie opens a car door, and the orphan in the raggedy clothes stares at the ornate building they've pulled up in front of.
"Will I be locked in a room again?" he asks mournfully.
Perrie puts a hand on his shoulder. "No."
A small door in the brick facade opens. A woman in the all-black uniform of a warden waves at Perrie, and he hustles the child in front of him. They both look around the street to see if anyone has noticed.
"All clear," the woman says.
"I'm scared," the boy whispers to Perrie. "Before you came for me, Yomu said you were going to hurt me. Badly. For crossing the Brokers."
Tears slide down the kid's grubby cheeks. He's terrified, shaking in his scrap boots. Perrie notices pieces of newspaper stick out near his ankles. The kid has no socks.
"Just go with this nice lady, you'll be safe. This is a place for orphans like you. It's a school. I'll visit. I'll be by tomorrow." The lie hurts Perrie.
The boy takes off the oversized flat cap from his curly hair and gives it to Perrie. "You should have this. For helping. I won't need it, now, I guess. They'll never let me near papers again."
The woman in all black puts a soft, friendly arm around the boy, and he lets himself get moved into another room past the vestibule. Several older women in black gowns swoop into the doorway after them.
A flash of radiance lights the room, and Perrie sees a circle of black-dressed figures surrounding the child like a flock of ravens. The light fades, and the first warden returns to Perrie. "It's done."
He passes her a parcel tied off in brown twine. "Thank you, warden."
"He won't remember a thing before today," the warden says. "We'll take good care of him."
They had to. They had a contract with the Brokers, now. A boarding school for the Park Height elite might not know too much about the shadowy streets, but even up here, they would know better than to break a contract.
Perrie slides into the back seat of the car.
"What I need right now, Perrie," Falco had said, back as Perrie re-entered the room from the balcony, "is neither a brawler, nor a planner."
Perrie pulls his hammer out from under his coat. He looks at the unsuspecting, dapper people out and about their day as the driver takes him toward a street fight with Obscura. The first of what Falco suspected were many scuffles over territory in New Capenna in the next month. At least the Riveteers are staying out of it, thanks to Perrie's work.
"What I need," Falco had said, intensely, "is a #emph[conscience] ."
The car, beetle-black skin absorbing New Capenna's lights, slides past the hustle and bustle of the city with Perrie inside. Outside, those in the know whisper, "There goes a Broker enforcer. One of the most dangerous ones."
Perrie looks down at the cap in his hand thoughtfully. Then he slides it into one of his inner coat pockets, right next to a shattered old watch he never leaves without.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/container-00.typ | typst | Other | // Test box in paragraph.
A #box[B \ C] D.
// Test box with height.
Spaced \
#box(height: 0.5cm) \
Apart
|
https://github.com/mkhoatd/Typst-CV-Resume | https://raw.githubusercontent.com/mkhoatd/Typst-CV-Resume/main/CV/typstcv.typ | typst | MIT License | #let date_colour= rgb("#666666")
#let primary_colour= rgb("#2b2b2b")
#let headings_colour= rgb("#6A6A6A")
#let subheadings_colour= rgb("#333333")
// Set font type for all text
#let fonttype = "macfont"
#let font_head = {
if fonttype == "macfont" {
"Helvetica Neue"
} else if fonttype == "openfont" {
"PT Sans"
} else {
"Times New Roman"
}
}
#let font_section = {
if fonttype == "macfont" {
"Helvetica"
} else if fonttype == "openfont" {
"PT Sans"
} else {
"Times New Roman"
}
}
#let font_subsection = {
if fonttype == "macfont" {
"Helvetica"
} else if fonttype == "openfont" {
"PT Sans"
} else {
"Times New Roman"
}
}
#let font_term = {
if fonttype == "macfont" {
"Heiti TC"
} else if fonttype == "openfont" {
"PT Sans"
} else {
"Times New Roman"
}
}
#let font_descript = {
if fonttype == "macfont" {
"Heiti SC"
} else if fonttype == "openfont" {
"PT Sans"
} else {
"Times New Roman"
}
}
#let font_jobdetail = {
if fonttype == "macfont" {
"Helvetica"
} else if fonttype == "openfont" {
"PT Sans"
} else {
"Times New Roman"
}
}
#let font_info = {
if fonttype == "macfont" {
"Helvetica"
} else if fonttype == "openfont" {
"PT Sans"
} else {
"Times New Roman"
}
}
#let font_keyword = {
if fonttype == "macfont" {
"Helvetica"
} else if fonttype == "openfont" {
"PT Sans"
} else {
"Times New Roman"
}
}
#let font_bib = {
if fonttype == "macfont" {
"Helvetica"
} else if fonttype == "openfont" {
"PT Sans"
} else {
"Times New Roman"
}
}
#let font_award = {
if fonttype == "macfont" {
"Helvetica"
} else if fonttype == "openfont" {
"PT Sans"
} else {
"Times New Roman"
}
}
// Section Headings (Education, Experience, etc)
#let section(title) = {
text(16pt,font: font_section, fill: headings_colour, weight: "light", )[#upper[#title]\ ]
}
// Subsection Headings (University, Company, etc)
#let subsection(content) = {
text(12pt,font: font_subsection, fill: subheadings_colour,weight: "bold", )[#upper[#content] ]
}
// Time period and location
#let term(period, location) = {
if location == [] or location == "" {
text(10pt,font: font_term, fill: headings_colour, weight: "medium", )[#period\ ]
} else {
text(10pt,font: font_term, fill: headings_colour, weight: "medium", )[#period | #location \ ]
}
}
// Description of a job, degree, etc
#let descript(content) = {
text(12pt, font: font_descript, fill: subheadings_colour,weight: "semibold",)[#content\ ]
}
// Job title
#let jobtitle(firm, title) = {
text(12pt,font: font_subsection, fill: subheadings_colour,weight: "bold", )[#upper[#firm] ]
text(12pt, font: font_descript, fill: subheadings_colour,weight: "semibold",)[| #title\ ]
}
//job details
#let jobdetail(content) = {
text(10pt,font: font_info, fill: primary_colour,weight: "light", baseline: 0em )[#set enum(tight:false,spacing:0em,indent: 0em, body-indent: 0em)
#content ]
}
// Details
#let info(content) = {
text(11pt,font: font_info, fill: primary_colour,weight: "light", )[#content\ ]
}
#let sectionsep = {
[#v(5pt)]
}
#let subsectionsep = {
[#v(2pt)]
}
#let awarddetail(time,award,organise) = {
set text(10pt,font: font_award, fill: primary_colour,weight: "light",top-edge: "baseline",bottom-edge: "baseline",baseline: 0pt)
grid(
columns: (auto,auto,auto),
gutter: 1em,
time,
award,
organise,
)
}
#let biblist(contents) = {
for ids in contents [
#id.title (#id.year)
]
}
#let keyword(content) = {
text(12pt, font: font_keyword, fill: headings_colour,weight: "light",)[#content\ ]
}
// last update
#let lastupdate(lastupdated, date)= {
if lastupdated == "true" {
set text(10pt,font: font_info, fill: primary_colour,weight: "light",)
block(
width: 100%,
height: 1.5em,
align(right,{[Last updated: #date]}),
)
}
}
#let main(
name: "",
address: "",
lastupdated: "",
date:"",
contacts: (),
bibfile: (),
left,
right,
) = {
// show contact details
let display(contacts) = {
set text(11pt,font:font_term,fill:headings_colour, weight: "medium",top-edge:"baseline",bottom-edge:"baseline",baseline: 2pt)
contacts.map(contact =>{
if contact.link == none [
contact.text
] else {
link(contact.link)[#{contact.text}]
}
}
).join(" | ")
}
set page(
margin: (
left: 1.25cm,
right: 1.25cm,
top: 3.2cm,
bottom: 1.5cm,
),
header:{
// Head Name Section
text(25pt,font: font_head,fill:primary_colour, weight:"light",top-edge:"baseline",bottom-edge:"baseline",baseline: 12pt)[#align(center,[#name])]
align(center)[#display(contacts)]
line(length: 100%, stroke:0.5pt + primary_colour)
},
header-ascent: 1em,
footer: [
#lastupdate(lastupdated, date)
],
)
//Main Body
grid(
columns: (1fr,2fr),
column-gutter: 2em,
left,
right,
)
}
// Chicago style
// Ball, Ray, <NAME>, <NAME>, and <NAME>. "Earnings, retained earnings, and book-to-market in the cross section of expected returns." Journal of Financial Economics 135, no. 1 (2020): 231-254.
// Sumiyana, Sumiyana. "Different characteristics of the aggregate of accounting earnings between developed and developing countries: Evidence for predicting future GDP." Journal of international studies 13, no. 1 (2020): 58-80.
#let chicago(contents) = {
set text(10pt,font: font_bib, fill: primary_colour,weight: "light", )
for (i, id) in contents.enumerate() {
grid(
columns: (auto,auto),
column-gutter: 0.4em,
{"["
str(i+1)
"]"},{
for author in id.author {
if author.len() == 1 [
#author.at("family"), #author.at("given").
] else {
if author.at("family") == id.author.first().at("family") [
#author.at("family"), #author.at("given")
] else if author.at("family") == id.author.last().at("family") [
and #author.at("given"), #author.at("family").
] else [
#author.at("given"), #author.at("family"),
]
}
}
[\" #id.title.\" #emph(id.container-title) ]
if "volume" in id [#id.volume, ]
if "issue" in id [no. #id.issue ]
[(#id.issued.date-parts.at(0).first())]
if "page" in id [: #id.page.] else[. ]
if "DOI" in id and "URL" in id {
[doi: ]
emph(link(id.DOI))
[\ ]
} else if "URL" in id {
[url: ]
emph(link(id.URL))
[\ ]
} else if "DOI" in id {
[doi: ]
emph(link(id.DOI))
[\ ]
}
}
)
}
}
// APA style
// <NAME>., <NAME>., <NAME>., & <NAME>. (2020). Earnings, retained earnings, and book-to-market in the cross section of expected returns. Journal of Financial Economics, 135(1), 231-254.
// <NAME>. (2020). Different characteristics of the aggregate of accounting earnings between developed and developing countries: Evidence for predicting future GDP. Journal of international studies, 13(1), 58-80.
#let apa(contents) = {
set text(10pt,font: font_bib, fill: primary_colour,weight: "light", )
for (i, id) in contents.enumerate() {
grid(
columns: (auto,auto),
column-gutter: 0.4em,
row-gutter: 0em,
{"["
str(i+1)
"]"},{
for author in id.author {
if author.len() == 1 [
#author.at("family"), #author.at("given").first().
] else {
if author.at("family") == id.author.first().at("family") [
#author.at("family"), #author.at("given").first().,
] else if author.at("family") == id.author.last().at("family") [
& #author.at("family"), #author.at("given").first().
] else [
#author.at("family"), #author.at("given").first().,
]
}
}
[(#id.issued.date-parts.at(0).first()). ]
[ #id.title. #emph(id.container-title)]
if "volume" in id [, #id.volume]
if "issue" in id [(#id.issue)]
if "page" in id [, #id.page.] else[. ]
if "DOI" in id and "URL" in id {
[ doi: ]
emph(link(id.DOI))
[\ ]
} else if "URL" in id {
[url: ]
emph(link(id.URL))
[\ ]
} else if "DOI" in id {
[doi: ]
emph(link(id.DOI))
[\ ]
}
}
)
}
} |
https://github.com/ad-si/invoice-maker | https://raw.githubusercontent.com/ad-si/invoice-maker/master/readme.md | markdown | ISC License | # Invoice Maker
Generate beautiful invoices from a simple data record.
<a href="./fixtures/expected-en.pdf">
<img
alt="Example invoice"
src="./images/example-invoice.png"
height="768"
>
</a>
## Features
- **Simple, yet Powerful**
- Write invoices as simple `.typ` or `.yaml` files
- No need to install anything but [Typst]
- Support for cancellations, discounts, and taxes
- **Multilingual**
- Integrated support for English and German
- Easy to add more languages by adding a translation dictionary
(Check out this example:
[custom-language.typ](./examples/custom-language.typ))
- **Customizable**
- User your own banner image
- Customize the colors and fonts
- **Elegant**
- Modern design with a focus on readability
- PDFs with a professional look
- **Stable**
- Visual regression tests to ensure consistent output
- **Free and Open Source**
- ISC License
[Typst]: https://typst.app
## Installation & Usage
1. Download the [invoice-maker.typ](./invoice-maker.typ) file
1. Create a new `invoice.typ` file.
E.g. based on one of the examples below:
- [English example](./examples/en.typ)
- [German example](./examples/de.typ)
- [YAML example](./examples/load-yaml.typ)
1. Run typst to generate the invoice:
```sh
typst compile invoice.typ
```
1. Use the generated `invoice.pdf` file 🎉
## Development
Run Tests:
```sh
make test
```
## Legacy Version
Invoice Maker was originally implemented with TypeScript and Pandoc
as seen in [`./typescript_pandoc`](./typescript_pandoc).
This version is still in maintenance mode, but will not receive new features.
|
https://github.com/Shuenhoy/modern-zju-thesis | https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/README.md | markdown | MIT License | # 浙江大学 Typst 学位论文模板 `modern-zju-thesis`
* **警告:** 本模板目前处于实验性阶段,请谨慎使用,对输出结果应进行检查和确认。在实验性阶段本模板可能会不加预告地对接口进行破坏性更改。
## 使用方法
1. 本模板尚未发布至 Typst Universe,请先以 Git Submodule 等方式使用。一种可能的目录结构为:
* `/`
* `templates/`
* `modern-zju-thesis/`
* `fonts/`
* `main.typ`
* `ref.bib`
2. 安装所需字体:`FangSong` `Kaiti` `SimHei` `SimKai` `TimesNewRoman`。 亦可通过本仓库目录 `scripts/get-fonts.sh` 将该字体下载至 `fonts` 路径。若采用后者,则需要在 Typst 的命令中添加 `--font-path <path-to-fonts-dir>` 选项来指定字体目录。
3. 在`main.typ`填入下列内容,亦可从本仓库目录 `examples` 下得到稍复杂的样例,和本科生模板样例。
```typ
#import "./templates/modern-zju-thesis/lib.typ": graduate-general
#import graduate-general: *
#let info = (
title: ("毕业论文/设计题目", ""),
title-en: ("Graduation Thesis Title", ""),
grade: "2014级",
student-id: "学号",
author: "姓名",
department: "学院",
major: "专业",
degree: "博士",
supervisor: "指导教师",
submit-date: "递交日期",
)
#let doc = graduate-general(info: info, twoside: true)
#show: doc.style
#doc.pages.cover
#doc.pages.title-zh
#doc.pages.title-en
#doc.pages.decl
#show: frontmatter
#let individual = doc.pages.individual
#individual("致 谢")[]
#individual("摘 要")[]
#individual("Abstract")[]
#doc.pages.outline
#doc.pages.figure-outline
#doc.pages.table-outline
#show: mainmatter
= Hello
== World
#individual("参考文献", outlined: true)[
#bibliography("ref.bib", style: "gb-7714-2015-numeric", title: none)
]
#individual("附录", outlined: true)[
#appendix(level: 1)[
== 一个附录 <app1>
@app1
== 另一个附录
]
]
#individual("作者简历", outlined: true)[
*基本信息:*
- 姓名:
- 性别:
- 民族:
- 出生年月:
- 籍贯:
*教育经历:*
- 2199.09 - 2203.06:浙江大学攻读学士学位
*攻读#(info.degree)学位期间主要的研究成果:*
]
```
4. 编译 `typst compile main.typ` 或 `typst compile --font-dir fonts main.typ`
## 已知问题
* 本科模板不支持双语参考文献(英文文献未能显示“et al.”而是“等”)。
* 本科模板仅能以 `@name` 的形式引用参考文献,而不能使用 `cite(<name>)` 的形式,否则分部分参考文献编号会有错误。
* Prose citations (即 LaTeX 的 `\citep`,例如 `Alec et al. [5]`) 格式不正确。
* 本模板的部分样式可能与 `zjuthesis` 不同,有待根据学校官方文件分辨哪部分不同是需要处理的。
* 目前仅包含计算机学院本科(论文)与研究生通用模板。
## 致谢
* https://github.com/TheNetAdmin/zjuthesis
* https://github.com/nju-lug/modern-nju-thesis
## License
* MIT License |
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/brainstorm-drivetrain-config.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: "Brainstorm: Drivetrain Configuration",
type: "brainstorm",
date: datetime(year: 2023, month: 6, day: 19),
author: "<NAME>",
witness: "Violet Ridge",
)
= Gear Ratio, Wheel Size, and Cartridge Type
Now that we had decided on our type of drivetrain we can decide the other
components. We decided on 4 combinations of gear ratio, wheel sizes and motor
cartridge, which are detailed below:
#v(40pt)
#grid(
columns: (1fr, 1fr),
gutter: 5pt,
[
== 6:3, 4" Wheels, Green Cartridges
- 400 RPM
- 6.96 feet/second
- 14" long
#pro-con(pros: [
- very fast
- large wheels make traversal easier
], cons: [
- low torque
])
],
image("/assets/drivetrain/6_3-4.png"),
[
== 3:5, 3.25" Wheels, Blue Cartridges
- 360 RPM
- 5.1 feet/second
- 14" long
#pro-con(pros: [
- higher torque
], cons: [
- small wheels make traversal difficult
- slow
])
],
image("/assets/drivetrain/3_5-3_25.png"),
[
== 3:5, 4" wheels, blue cartridges
- 360 RPM
- 6.47 feet/second
- 14" long
#admonition(
type: "warning",
)[
This drivetrain was never fully designed because we discovered that the gears
did not fully mesh. This is an early sign of our working paying off, if we had
just started building right away we would not have caught this error.
]
#pro-con(pros: [
- speed
- compact gears
], cons: [
- low torque
])
],
image("/assets/drivetrain/3_5-4.png"),
[
== 4:7, 4" wheels, blue cartridges
- 342 RPM
- 5.96 feet/second
- 14" long
#pro-con(pros: [
- speed
- large wheels make traversal easier
], cons: [
- low torque
])
],
image("/assets/drivetrain/drivetrain-cad-side.png"),
)
|
https://github.com/dasayan05/typst-ai-conf-templates | https://raw.githubusercontent.com/dasayan05/typst-ai-conf-templates/master/README.md | markdown | MIT License | # AI conference templates in [Typst](https://typst.app/)
<h3 align="center">🔨 <strong>Work-in-progress (WIP)</strong> 🔨</h3>
<h4 align="center"> ✨ Contributions are welcome ✨ </h4>
<br />
<center>
<strong>Please note that Typst is in it's early stage and not yet as feature-rich as LaTeX, hence it may still take some time for these templates to be usable in practice.
</strong><br /><br />
</center>
Templates for AI conferences (or many other conference) are historically written only in LaTeX, which is old and hard to use. [Typst](https://typst.app/) is a modern typesetting system with a much more familiar programming model. As the community grows, we may want to use Typst for writing papers in the conferences. Please note that **this is an individual effort to port the templates, but not "officially" supported by the conferences**. Also, this repo is still work in progress and might not yet match the exact specification (e.g. margin, styling) of the conference.
### The goal of this project is roughly
1. Port AI conference templates in Typst
2. Make them look and feel similar to their LaTeX versions
3. Follow the exact specifications provided by the conference
---
### List of conferences
- [X] NeurIPS
- [ ] ICML
- [ ] ICLR
- [X] CVPR
- [ ] ICCV
- [ ] ECCV
- (more to come)
---
### Interface
The idea is to have a (roughly) fixed `#show: ...` rule for each conference. Putting the following at the beginning of the paper will act as a "template" ..
```
// Replace <conf> with the conference name
// #import "<conf>.typ": manuscript
#import "neurips.typ": manuscript
#show: manuscript.with(
title: [Formatting Instructions For NeurIPS 2023],
authors: (
[
*Author 1*\
Affiliation 1\
Address 1\
...
],
[
*Author 2*\
Affiliation\
Address\
...
],
...
),
abstract: [
The abstract paragraph should be indented $1/2$~inch (3~picas) ..
]
)
```
### Example Outputs
- NeurIPS
<center>
<img src="assets/neurips_front.png" />
</center>
- CVPR
<center>
<img src="assets/cvpr_front_anon.png" />
<img src="assets/cvpr_front.png" />
</center>
|
https://github.com/haokee-git/CppGuide | https://raw.githubusercontent.com/haokee-git/CppGuide/main/main.typ | typst | #import "template.typ": *
#show: project.with(
title: "C++ 入门教程",
authors: (
"好渴鹅",
),
)
#let quote(body) = {
rect(fill: luma(240), stroke: (left: 0.1em))[#body]
}
= 前言
这是好渴鹅完全独立自主编写的一本如何入门 C++ 的指南,采用 Typst 文档系统系统构建,仅供学习,请勿用于商业用途。
其实现在市面上不管是博客啊还是实体书等等等等,都有非常多专门教学 C++ 的,但它们各有优缺点:网上的教程虽然不乏有一些很好的文章,但是只是太过于碎片化了,很多专门用来教学 C++ 的网站也没有对知识进行详细的分类与讲解:实体书呢则是知识板块分类较为详细,但是往往较为昂贵。
因此,好渴鹅就编写了这本《C++ 入门教程》电子书,希望能够给予想要零基础学习 C++ 的人们一点点帮助。俗话说得好:“前人栽树,后人乘凉。”或许我种的树没有那么茂盛、那么郁郁葱葱,但是我相信一定会有更多的“前人”为后人栽下希望的树苗。
同时,好渴鹅在编写文档的时候难免也会出现一些错误或漏洞。如果你找到了漏洞并且想用你那善良的心修复的话,请发邮件到 <EMAIL>,好渴鹅将会在七个工作日内给予回复。
个人网站:#text(fill: blue)[#link("https://haokee-wiki.netlify.app")[Haokee-Wiki]]
#align(right)[
——好渴鹅
]
= 配置环境
打开你的电脑,如何写代码并运行呢?不要着急,你可能还没有安装 C++ 环境。本章节主要讲解了如何在自己的电脑上安装不同的代码编辑器和编译器或集成开发环境,读者可以自行选择喜欢的软件安装。
== Visual Studio (Windows)
Visual Studio 是微软推出的一个强大的集成开发环境,可用于构建适用于多种平台和语言的应用程序。以下是官网的介绍:
#quote[
Visual Studio 是一款功能强大的开发人员工具,可用于在一个位置完成整个开发周期。 它是一种全面的集成开发环境 (IDE),可用于编写、编辑、调试和生成代码,然后部署应用。 除了代码编辑和调试之外,Visual Studio 还包括编译器、代码完成工具、源代码管理、扩展和许多其他功能,以改进软件开发过程的每个阶段。
凭借 Visual Studio 中的各种功能和语言支持,你可以从编写第一个“Hello World”程序进化到开发和部署应用。 例如,生成、调试和测试 .NET 和 C++ 应用,在 Web 设计器视图中编辑 ASP.NET 页面,使用 .NET 开发跨平台移动和桌面应用,或在 C\# 中生成响应式 Web UI。
]
总的来说,就是非常厉害的一个集成开发环境,不管你是初学者还是 C++ 老手,都可以愉快地使用 Visual Studio 来进行开发。让我们安装吧!
打开 #link("https://visualstudio.microsoft.com/zh-hans/")[#text(fill: blue)[官网]],下载 Community 版本(现在应该是 Visual Studio 2022)。下载完之后,双击下载完的 exe,它就会自动帮你安装安装器。过了一会,就可以来到安装界面,有很多选项可以勾选。我们勾选“使用 C++ 的桌面开发”,(如果你的 C 盘不够用的话点开安装位置,把安装目录最前面的 C 改成 D 或其它盘),然后点击安装就行了。
过了大约两年半,软件大概就安好了。如何这时它告诉你要重启的话你就重启,重启完之后在开始菜单里面找到 Visual Studio (2022) 打开,跟着引导走,就可以来到项目界面。点击创建新项目,勾选“C++ Windows 控制台应用程序”,填好项目名和目录(其它的尽量不要乱改),点击创建就可以创建新项目了。
创建完之后,会来到编辑界面,此时就可以开始写代码了。
== MinGW (Windows)
MinGW 是什么?MinGW 其实是一个在 Windows 上运行的编译器的名称,用来把 C++ 代码编译成机器可以直接运行的程序。
我们知道,计算机的处理方式是二进制,那么我们的机器码也是二进制的,只有机器码才可以让计算机做出事情。但是,机器码它反人类啊!你想一想,光是让计算机执行一个加法就需要好多代码,因为计算机只能对位进行具体的操作,因此我们肯定是不可能直接写机器码的。
因此,后人开发了汇编语言,这种语言使用了很多英文符号,把英文符号转化为对应的二进制机器码就可以让计算机运行。但是汇编语言及其复杂,只是写起来简单一些,但是代码仍然很长。
这时,高级语言就出现了,如:C/C++、Python、Java、C\#……这种语言的代码构成就很简单了,而运行的方式就是需要一个翻译器,把代码翻译成机器码。一般有编译式和解释式,编译式就是直接编译成机器码,然后输出文件,最后点击文件就可以直接运行了;解释式就是相当于运行时逐句翻译,可以更好地面对运行时的错误,但是牺牲了速度。(*补充:*Java 等 JVM 语言是编译式和解释式的结合)
那为什么我们刚刚安装 Visual Studio 的时候没有安装编译器呢?因为 Visual Studio 是一个自带编译器的集成开发环境,因此不需要自己手动安装编译器。但是如果你想要安装 VS Code 或 CLion(较新版本自带编译器,但是功能不全)等不自带编译器的编辑器或 IDE 的话,那么就需要自己安装编译器了。
叭叭了一大堆,让我们开始安装吧!
首先转到 #text(fill: blue)[#link("https://sourceforge.net/projects/mingw-w64/files/mingw-w64/mingw-w64-release/")[MinGW-w64 - sourceforge]],然后一直往下翻看到 MinGW-W64 Online Installer,也就是在线安装器,但是*不要点*,下载下面的 #text(fill: blue)[#link("https://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/mingw-builds/8.1.0/threads-posix/seh/x86_64-8.1.0-release-posix-seh-rt_v6-rev0.7z")[x86_64-posix-seh]],然后解压就行了。
#align(center)[
#image(
"image/download-mingw64.png",
width: 40%,
)
]
接下来,假如你刚刚解压到了 `C:\mingw64` 目录,没有解压到这里也没关系,把接下来的这个目录都替换成自己的目录就行了。
然后打开文件资源管理器,点击此电脑,按 `Alt + Enter` 或者右键点属性,就会来到设置页面。往下滑,找到高级系统设置,点击环境变量,找到系统变量中的 Path 变量,双击点进去,然后将 `C:\mingw64\bin` 这个目录添加进去。
点击确定,一直推到文件资源管理器之后按 `Win + R` 打开运行窗口,然后输入 cmd 回车,接着在弹出来的黑框框内输入 `g++ -v`,如果它给你了一大段版本信息,就说明你的编译器已经配置好了。
== GNU (Linux)
对于 Linux 用户,可以直接在命令行下运行该命令安装 GNU 编译器,命令仍为 G++。
#align(center)[
```bash
$ sudo apt install g++
```
]
然后使用 `g++ -v` 就可以检测是否安装完毕了。十分简单。
== XCode (MacOS)
XCode 是苹果官方的集成开发环境,用于开发 Objective-C 和 Swift(包括普通的 C++)。但是它自带了 G++ 编译器因此非常方便,只需要安装几个 G。
首先,打开终端输入 `g++ -v` 看一看有没有报错,如果有的话再安装,没有的话就不用重新安装一遍了。
然后打开 MacOS 自带的 App Store,搜索 XCode,点击获取,过一会就安装完成了。再重新打开终端,就可以发现命令没有报错了。
== CLion (Windows/Linux/MacOS)
如果你想要更好的跨平台体验的话,那么 JetBrains 家的 CLion 就是一个比较好的选择。安装完编译器之后,我们找到 JetBrains 的 #text(fill: blue)[#link("https://www.jetbrains.com/clion/")[官网安装地址]],选择自己的系统进行安装就可以了。
安装完之后,它可能会告诉你没有许可证,你可以点击试用三十天,那么你就可以免费使用三十天了。如果你用的机房电脑有系统盘还原的话,那么可以每次安装都免费试用三十天。
正式进入软件,点击“New Project”就可以来到创建项目的页面。填上项目的名称和目录就可以了,其他的选项尽量不要乱动。创建完之后就可以来到编辑页面了。开始打代码吧!
= 基础语法
== 引入
=== 向世界问好
作为一个刚装完环境的小白,你想不想立马编出一个可爱的小程序,并让它向世界问好呢?打开 IDE,输入以下的代码:
#align(center)[
```cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello world!" << endl;
return 0;
}
```
]
然后运行,如果没有错误的话,程序将会弹出一个黑框框窗口,然后在该窗口里面打印 `Hello world!` 这一串文本。
如果 IDE 出现了报错没能启动程序,那么大概率是你有某些地方写错了,请一个一个字母对照看出现了那些问题(缩进不用检查),如果眼睛不好的建议直接复制。*注意 C++ 的每一行有实际含义的代码都是需要打上分号的。*
如果黑框框是一闪而过的话,那么大概率是你的 IDE 的配置有问题,不过在 ```cpp return 0;``` 的前面加上以下这一行就行了。
#align(center)[
```cpp
system("pause");
```
]
好的,现在我们来一行一行看程序是如何打印出 `Hello world!` 的。
第一行:`#` 后面跟着的是预处理命令,表示编译器会在编译的时候就预处理的命令。```cpp #include``` 表示我们需要包含指定的头文件,也就是导入编译器的开发人员预先定义的文件,这样子我们就不用什么都自己写了。`iostream` 就是 C++ 里面推荐用来进行输入输出的头文件,使用 `< >` 包裹表示这是系统头文件而非自己定义的。
第二行:这是一行空行,为了让代码更美观、阅读起来更好看。
第三行:```cpp using``` 表示使用,```cpp namespace``` 表示命名空间,`std` 是命名空间的名字,连起来就是使用一个名叫 `std` 的命名空间。这是为了方式标准库当中的类、变量与自己定义的重名的。但是我们暂时不需要自己自己定义,因此我们就使用这个语句,不写的话所有标准库里面的东西就都需要加上 `std::` 前缀。
第四行:这是一行空行,为了让代码更美观、阅读起来更好看。
第五行:这是定义 `main` 函数的地方,`main` 函数就是程序的入口,所有的语句都会一条一条执行。前置 ```cpp int``` 表示该函数的返回值为整数(Integer)类型,若为 $0$ 则表示程序运行正常。`()` 空括号表示我们的 `main` 函数不接受任何参数,但这并不代表 `main` 不能接受参数,因此这个空括号*不可以不写*。大括号包裹的就是函数体,里面是需要运行的语句。
第六行:这是输出 `Hello world!` 的核心代码。`cout` 就是 C++ 当中的标准输出(默认是控制台),输出的内容用 `<<` 一个一个连接,```cpp "Hello world!"``` 就是一个名叫 `Hello world!` 的字符串。为什么是字符串呢?就比如 `cout`,没有用引号包起来就表示这是运行的语句,用引号抱起来就是可以输出的字符串了。后面跟着输出 `endl` 就表示换行并立即刷新缓冲区,刷新缓冲区是为了让输出更快地显现在控制台上,但是运行效率会变慢,因此可以考虑使用带有 `\n` 的字符串,也就是换行符。不过我们的程序并没有对效率有很高的要求,因此可以不删。
第七行:这是用来退出主函数也就是程序的,```cpp return 0``` 就是返回 $0$ 的意思,也对应了前面所说的内容。
第八行:与前面的主函数的大括号成对。
是不是恍然大悟呢?没有听懂也没关系,可以自行上网了解。也可以将引号内的字符换成其他的,达到输出其它内容的效果。
=== 代码习惯
养成好的代码习惯跟固定的代码风格是非常重要的。不过,代码风格没有美丑之分,适合自己的才是最好的,但是一定要养成。现在好渴鹅来简单讲解一下好的代码习惯。
首先,*要有良好的缩进*。就像刚才的代码里的主函数一样,大括号括起来的函数体都是锁进了啷个空格的,这样子才能分的清层次。除非你的眼力真的很好。一般都是空 $4$ 个空格或者 $2$ 个空格,但是*尽量不要用 Tab*。因为 Tab(制表符)的长度是不固定的,虽然大多数编辑器都是等同于 $4$ 个的长度,但是有些会是 $8$ 个空格,因此为了代码的美观,请尽量不要使用 tab。
然后,在比较拥挤的地方,尽量要*空开一个空格*,至少要看上去美观一些,但是不要空太多空格。空空格的好处也是读起来更美观。当然,如果你真的喜欢把代码挤在一起的话,那当我没说。
古语有云:“写代码是一门艺术。”我们都是艺术家,但是“画”并不是给自己看的,而是给别人看的,让别人领会你的“画”的美丽。因此养成好的代码习惯比学习算法更加重要。
=== A+B 问题
到现在,我们只能在控制台上打印一些简单的东西,那能不能让用户在控制台上输入某些东西呢?其实非常简单,我们可以使用 `cin` 来输入,而输入的内容就需要用 `>>` 来连接,与 `cout` 恰恰相反,是不是非常形象?
但是在输入之前,我们遇到了一个问题:我们如何存储输入的信息呢?非常简单,我们可以使用变量来存储信息。例如,在主函数里面 `return 0;` 前面加入如下代码可以创建一个能够表达 $-2^31~2^31-1$ 的整数,而它的名称叫 `x`。
#align(center)[
```cpp
int x;
```
]
现在,尝试输出这个 $x$,看一看值为多少。(```cpp //``` 后面的内容是注释,是给人看的,编译器不会管。多行注释可以使用 ```cpp /*...*/``` 表示。)
#align(center)[
```cpp
cout << x; // 也可以加 endl 或 '\n' 换行
```
]
多运行几遍,可以看到基本上都不是 $0$,而且有很大慨率是不一样的。这是因为在主函数里面定义的变量不会默认赋初始值。解决这个问题很简单,可以把定义变量的代码放在主函数的外面或者像这样在定义的时候就直接赋 $0$。
#align(center)[
```cpp
int x = 0;
```
]
当然,你也可以单独写一行 ```cpp x = 0``` 来赋值。既然是 A+B 问题,那么我们就需要定义两个变量了,$a$ 和 $b$,用逗号隔开。不过不用进行初始化,因为我们会输入它们。
#align(center)[
```cpp
int a, b;
```
]
然后我们输入他们,并输出它们的和(使用 ```cpp +``` 运算符),最后用 `\n` 换行。
#align(center)[
```cpp
cin >> a >> b;
cout << a + b << '\n';
```
]
最后运行该程序,就可以发现黑框框没有了输出,这是因为程序在等你的输入。现在,我们在黑框框内输入 `1 1`(将两个 $1$ 用空格隔开),然后回车——程序立马输出了 `2`。可以看到,我们的程序成功地算出了 $1+1=2$。当然,你也可以输入其它的整数,但是记住不能超过 $-2^31~2^31-1$,不然则会因为溢出而运算错误。
值得注意的是,C++ 中的输入不用在意使用的是换行隔开还是空格隔开,只要你输入了足够数量的数,那么就会结束输入。因此你也可以使用换行输入的模式输入两个 `1`,但是记得输入完要回车。
== 变量与运算符
=== 数据类型
在前面的代码当中,我们已经学会了如何定义 ```cpp int``` 类型的变量。但是,数据类型远远不止 ```cpp int``` 那些,还有更多其他的数据类型。
#align(center)[
#table(
columns: (auto, auto, auto),
align: horizon,
inset: 8pt,
table.header(
[*数据类型名称*], [*含义*], [*字节数量*]
),
```cpp int```, [存储 $-2^31~2^31-1$ 范围内的整数], [$4$ 字节],
```cpp short```, [存储 $-65,536~65,535$ 范围内的整数,操作方法与 ```cpp int``` 一样], [$2$ 字节],
```cpp bool```, [布尔类型,值为 true (0) 或 false (1)], [$1$ 字节],
```cpp float```, [单精度浮点类型,位数较少], [$4$ 字节],
```cpp double```, [双精度浮点类型,位数较多], [$8$ 字节],
```cpp char```, [字符型], [$1$ 字节],
)
]
可以看到,表示的数据类型非常多。让我们来实验一下:
#align(center)[
```cpp
int a = 1;
bool b = true;
float c = 1.145141919810;
double d = 1.1145141919810;
char e = '!';
cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << e;
```
]
(此处输出的 `' '` 就是表示一个空格,用于隔开输出信息)输出的内容如下:
```cpp
1 1 1.14514 1.14514 !
```
非常的有趣,我们可以发现几个特征:
- ```cpp char``` 类型变量虽然在定义的时候赋值为的是 ```cpp true```,但是输出的时候却转到了 ```cpp int``` 的格式——也就是 $1$。
- ```cpp float``` 型变量与 ```cpp double``` 型变量好像似乎没有什么差别,都输出了 $6$ 位有效数字,而且都是一样的。可是 ```cpp double``` 类型不应该表示的 ```cpp float``` 类型更加精确吗?
对于第二个问题,其实答案非常简单。只是因为我们的 `cout` 输出默认不会保留那么多的有效位数,因此输出的时候它们看起来是一模一样的。后面好渴鹅会讲如何保留多少多少位小数。
但是,如果是进行除法运算,那么 ```cpp float``` 与 ```cpp double``` 之间的差别可就大了。我们都来计算 $display(1/700)$ 的值,```cpp float``` 保留二十位小数部分输出的值为 $0.001,428,571,413,271,129,13$,而 ```cpp double``` 输出的值为 $0.001,428,571,428,571,428,57$,可以显而易见地看出差别。
那么如何保留制定小数位数呢?非常简单,首先需要像引入 `iostream` 头文件一样地引入 `iomanip` 头文件:(但是引入 `iostream` 的语句不要删)
#align(center)[
```cpp
#include <iomanip>
```
]
然后在输出的时候在变量前面输出 `fixed` 和 `setprecision(要保留的位数)`。例如,如果你想输出 $x$ 并保留 $20$ 位,那么大概可以这样写:
#align(center)[
```cpp
cout << fixed << setprecision(20) << x;
```
]
需要注意的是,如果要同时保留多个数的小数位数,那么需要在每一个输出变量的前面都加上如此繁琐的语句。那么,有没有更简单的保留小数位数的方法呢?可以参考后面的 C 风格输入输出。
=== 类型修饰符
以下,是所有的类型修饰符:
#align(center)[
#table(
columns: (auto, auto),
align: horizon,
inset: 8pt,
table.header(
[*类型修饰符名称*], [*含义*]
),
```cpp signed```, [表示有符号的类型],
```cpp unsigned```, [表示无符号的类型],
```cpp long```, [表示额外加长类型的长度]
)
]
*注意:*```cpp signed``` 和 ```cpp unsigned``` 可以单独使用,也就是说 ```cpp signed int = signed```,```cpp unsigned``` 同理。```cpp int``` 默认就是 ```cpp signed``` 的。```cpp long``` 可以用来修饰 ```cpp int``` 或 ```cpp double``` 类型,修饰 ```cpp int``` 类型可以单独使用,```cpp int``` 可以加两个,```cpp double``` 可以加一个。
```cpp long int``` 类型是 $4$ 或 $8$ 个字节的,取决于编译器和操作系统。```cpp long long int``` 是强制 $8$ 个字节的,表示范围为 $-2^63~2^63-1$。
=== 常量
在 C++ 当中,常量是一种特殊的变量,采用 `const` 前缀定义。常量必须是在定义的时候就必须初始化,并且初始化的值不能是变量表达式。(不同于 Java 中的 ```java final```,Java 中的 ```java final``` 是只能赋一次值)
那你可能会问,常量有什么用,直接用变量表示常量不久行了吗?话虽然是这么说,但是编译器一般都会对常量进行特殊优化。比如取模操作,可以把模数定义为常量,这样子运算速度就会快很多。
#align(center)[
```cpp
int x = 1, y = 2;
const int a = x + y; // 不行,不能赋值为变量
const int b; // 不行,必须初始化
const int c = 100;
c = 1000; // 不行,不能做运算
```
]
=== 变量的运算
变量有很多种运算符,以下是表格:
#align(center)[
#table(
columns: (auto, auto),
align: horizon,
inset: 8pt,
table.header(
[*运算符*], [*含义*]
),
$+$, [对两个操作数进行加法或正号],
$-$, [对两个操作数进行减法或负号],
$*$, [对两个操作数进行乘法],
[/], [对两个操作数进行除法],
$%$, [对两个操作数取模],
[+= 及其他], [运算并赋值运算符],
[$++$], [前后缀自增运算符],
[$--$], [前后缀自减运算符],
[$==$], [等于运算符],
[!=], [不等于运算符],
[&&], [逻辑与运算],
[||], [逻辑或运算],
[$!$], [逻辑非运算],
[&], [位与运算],
[|], [位或运算],
[$~$], [位取反],
[^], [异或运算],
[$<<$], [左移运算符],
[$>>$], [右移运算符],
[$::$], [域运算符],
[.], [成员访问运算符],
[->], [成员访问运算符(指针)]
)
]
现在我们来一个一个学习使用。
==== 算术运算符
其实就是加减乘除和取模(整数除法得来的余数),可以参考下面的代码:
#align(center)[
```cpp
#include <iostream>
using namespace std;
int a = 114, b = 514;
int main() {
cout << a + b << '\n'
<< a - b << '\n'
<< a * b << '\n'
<< a / b << '\n'
<< a % b << '\n';
return 0;
}
```
]
输出结果:
#align(center)[
```cpp
628
-400
58596
0
114
```
]
==== += 等运算符
这些运算符没有具体的名称,但是效果十分简单:
#align(center)[
```cpp
a += b
a = a + b // 等同于
```
]
其它运算符也是一样的道理。注意这些运算符是*向右结合*的!例子:
#align(center)[
```cpp
int a = 1, b = 1;
a += b += 1;
```
]
此时,$a=3,b=2$ 而非 $a=2,b=3$。可以看出首先进行运算的是 ```cpp b += 1```,然后进行了 ```cpp a += b``` 的运算。C++ 当中也有很多运算符的优先级十分恶心,参见下面的介绍。
==== 自增减运算符
自增减是初学者最容易弄错的运算符之一了。别看 ```cpp a++``` 和 ```cpp ++a``` 之间相差不多,但是实际使用中却又很大不同。
#align(center)[
```cpp
int a = 1, b = 1;
cout << a++ << ' ' << ++b;
```
]
可以看到,输出是 $1$ 和 $2$,说明 `a++` 是先返回 $a$ 本身,然后在把 $a$ 改成 $a+1$;而 ```cpp ++a``` 则是先把 $a$ 改成 $a+1$,然后在返回 $a$ 本身。但是*注意*,```cpp a++``` 的实际实现是先拷贝一个跟 $a$ 一样的数,然后再把 $a$ 改成 $a+1$,最后返回拷贝过去的数。因此,实际上返回的数是不能够更改的。例如:
#align(center)[
```cpp
a++++ // 不行
++++a // 可以
(++a)++ // 可以
++a++ // 未定义的行为
```
]
自减运算符同理。
==== 等于运算符
等于运算符(==)是初学者最容易弄错的运算符之二了。为什么呢? 因为计算机中的单等于号(`=`)和数学中的等于号($=$)虽然外形相似,但是实际上却有很大的差别。
在计算机当中,`=` 表示赋值并返回复制后的值。例如 ```cpp cout << (a = b)``` 表示将 $a$ 的值赋为 $b$,并返回 $a$ 赋值后的值来输出。而判断两个变量是否等于的运算符是双等于号 = =。比如,若 `a = 1, b = 1`,那么 `a` == `b` 的返回值就为真(true)。
需要注意的是,在本文当中,为了是观看体验更佳,使用了 JetBrains Mono 字体的连字功能,因此在代码块当中 == 实际上会显示成 `==`。其实只需要注意一下用途就行了。
不等于运算符就比较形象了,写作 !=。就比如刚刚的例子,`a` != `b` 的返回值就为假(```cpp false```),因为 $a$ 和 $b$ 实际上是等于的。
需要注意的是,本文当中 != 在代码块里面会显示成 `!=`,注意一下即可。
*补充:*一般情况下,```cpp (a != b)``` 等价于 ```cpp !(a == b)```。
==== 逻辑运算
- *逻辑与运算:*如果两边都为真,那么返回真,否则返回假;
- *逻辑或运算:*如果两边有任意一个为真,那么返回真,否则返回假。
- *逻辑非运算:*如果操作数为真则返回假,假则返回真。
一般用与 if 表达式当中,可以参照后面的内容。
==== 位运算
位运算就稍微牵扯到了计算机基本原理方面了。在 C++ 当中,我们的所有变量都是由二进制所构成的。为了让用户更加地接近于底层,C++ 提供了很多直接对位进行操作的运算。
- *位与运算:*把两个数的位都给对齐,逐个进行操作。对于每一个位,如果两个参数都为 $1$,那么答案的对应位也为 $1$,否则为 $0$;
- *位或运算:*把两个数的位都给对齐,逐个进行操作。对于每一个位,如果有大于等于 $1$ 个参数对应位为 $1$,那么答案的对应位也为 $1$,否则为 $0$;
- *位取反运算:*对操作数的每一个位都取反,$0$ 变成 $1$,$1$ 变成 $0$;
- *异或运算:*把两个数的位都给对齐,逐个进行操作。对于每一个位,如果两个参数不一样,那么答案的对应位就为 $1$,否则为 $0$;
- *左移运算:*把所有位往左移指定位数,高位舍去;
- *右移运算:*把所有位往右移指定位数,低位舍去;
需要注意的是位运算的优先级非常低,大部分时候都需要加上括号提高优先级。关于位运算的更多奇技淫巧请参照“更多技巧”小节。
==== 其他运算符
使用比较广泛的是 ```cpp sizeof``` 运算符,可以装入一个任意类型的参数,参数为单个变量时可以不加括号。返回的就是参数的字节长度。值得注意的是,```cpp int``` 等本身就存在的数据类型或自己定义的数据类型也可以用 ```cpp sizeof``` 来求长度。
例如:```cpp sizeof(int) == 4```,定义 ```cpp int a``` 后 ```cpp sizeof(a) = 4```。塞入数组可以查看整个数组所有元素的字节长度之和。
其他运算符现在还根本用不到,到后面的时候会零零散散地讲解。
== 输入与输出
=== C++ 风格
C++ 使用 cin 进行标准输入,cout 进行标准输出,clog 进行日志输出,cerr 进行错误输出。存在与 `iostream` 头文件,std 命名空间里面。
那你可能会问了,输入只有一个 cin,为啥输出不仅有 cout 还有 clog 和 cerr 呢?其实解释起来非常简单。
你知道什么是输出缓冲区吗?如果是对每一个输出都直接打印到控制台上面的话,那么效率就会极其低下。因此,C++ 的创始人想了个办法:我搞一个数组存输出的内容,等数组满了在一起打印到控制台上面不久行了吗?
因此就有了不同的输出对象。cout 就是普通的输出,一般会在输入的时候或者缓冲区满了的时候进行刷新;clog 是专门用来输出日志的,因为一般程序的日志都会很多,因此使用 cout 会比较慢,而 clog 只会在缓冲区满了的时候自动刷新,因此需要手动刷新,效率也最高;cerr 是用来输出错误的,没有缓冲区的设计让他可以在程序异常的时候更好地及时输出错误信息。
刷新缓冲区的办法就是输出 flush。注意 endl 不仅会换行还会刷新缓冲区,这也就解释了为什么前面说使用 endl 换行效率极其低下。
=== C 风格
在古老的 C 语言中,输入和输出是使用 scanf 和 printf 函数来完成的。它们的格式如下:
#align(center)[
```cpp
scanf/printf(format: char *, ...)
```
]
format 就是将要格式化的字符串,后面任意多的参数就是要格式化进字符串里面的参数。格式化字符串当中有非常多的控制符需要记住:
#align(center)[
#table(
columns: (auto, auto),
inset: 8pt,
table.header(
[控制符], [作用]
),
[%d], [用来格式化一个整数],
[%c], [用来格式化一个字符],
[%f], [用来格式化一个单精度浮点数],
[%lf], [用来格式化一个双精度浮点数],
[%s], [用来格式化一个 C 风格字符串],
[%x], [格式化整数为十六进制],
[%o], [格式化整数位八进制],
[%ld], [格式化一个长整型],
[%lld], [格式化一个 long long 型],
[%Ix], [格式化 x 位的整数],
)
]
还有很多很多,在此不再描述。具体用法可以参照下面的:
#align(center)[
```cpp
scanf("%d", &x); // 读入x,注意取地址符
printf("%d", x); // 输出x
```
]
然后输入或输出其他不同类型的变量参照上面的格式表就行了,是不是非常简单。虽然很快就能学会,但是在普通时候,C 风格的输入输出比 C++ 的要繁琐许多,在此介绍两个 C 风格输入输出可以较好地操作的使用场景。
需要注意的是,C++ 的缓冲区默认会与 C 进行绑定,这样子就可以一会用 C++ 一会用 C 进行混合使用了,但是速度也会大打折扣。取消绑定的方法为 ```cpp ios::sync_with_stdio(0)```(或填 ```cpp false```),但是取消之后就不可以进行混合输入或混合输出了。
还有另外一个优化则是 ```cpp cin.tie(0)``` 和 ```cpp cout.tie(0)```(或传入空指针)。正常情况下 C++ 的 cin 和 cout 是互相绑定的,也就代表着输出完之后如果有输入就会立马刷新输入的缓冲区好让用户接受输入信息,但是这样子也会降低输入/输出效率。增加上上面几行后,你就可以发现,有些代码的输出就会留到最下面。
这时,C++ 的输入输出的效率就比 C 要高了。
*P.S:*取地址符是 $100%$ 需要的。那你可能会问,同样是输入,为什么 C++ 不需要取地址符呢?因为 C++ 对 C 进行了改良,加入了“引用”,正好可以弥补指针滥用的危险(特别是初学者)。而 C 还没有引用,因此就必须传入地址而非值(后面会讲)。
==== 大量文本格式化
例如需要输出 `(a + b) = c` 这类的题目输出,就可以看出明显差别:
#align(center)[
```cpp
cout << '(' << a << " + " << b << ") = " << c << '\n'; // C++
printf("(%d + %d) = %d\n", a, b, c); // C
```
]
可以看到,在这个使用场景下,C 风格输入输出不仅比 C++ 风格输入输出的代码要短,而且可读性还很高。
==== 保留小数位数/设置宽度
前面说过了,保留三位小数 C++ 需要 ```cpp << fixed << setprecision(3)```,但是 C 风格输入输出就只需要把控制符 %lf 改为 %.3lf 就行了。设置宽度同理,C++ 需要 ```cpp << setw(3)```(还要加 `iomanip` 头文件),而 C 风格输入输出就只需要把控制符改为 %3d 就行了。
=== 文件输入输出
程序的输入输出不仅有标准的输入输出操作,还有对文件的输入输出操作。在 C++ 当中,有三种文件操作是最为常用的。
==== fstream
使用该库之前,需要包含头文件 ```cpp fstream```,然后就可以定义自己的输入输出了。`ifstream` 是用来文件输入的,`ofstream` 是用来文件输出的。比如 ```cpp ifstream fin("text.txt")``` 可以打开一个名叫 `text.txt` 的文件并读入。输入输出的方式就跟 `cin` 和 `cout` 一样啦。
注意如果定义了自己的文件流的话,那么就不要再傻乎乎地使用 ```cpp cin.tie(0)``` 啦,要用 ```cpp 自己定义的文件流.tie(0)```。
还有,如果在程序运行的中途不需要继续读写文件了,那么记得调用 ```cpp .close()``` 函数,释放文件的各种缓存,也方便其他程序调用。
以下是一个小的例子:
#align(center)[
```cpp
ifstream fin("test.in");
ofstream fout("test.out");
int x;
fin >> x; // 读入test.in里面的数
fout << x; // 写入到test.out里面
fin.close(); // 释放缓存
fout.close();
```
]
==== freopen
这个也是算法竞赛当中比较推荐的一种,原理就是直接修改标准输入/输出的文件指针,从而达到重定向文件输入输出的效果。
格式:
#align(center)[
```cpp
freopen(文件名: char *, 读写方式: char *, 文件指针: FILE *)
```
]
文件名就是想要定向到的文件,读写方式为 "r" 或 "w",文件指针就是 `stdin` 或 `stdout`,这也是我们之前一直说的标准输入输出。
#align(center)[
```cpp
freopen("test.in", "r", stdin);
freopen("test.out", "w", stdout);
int x;
cin >> x;
cout << x;
fclose(stdin);
fclose(stdout);
```
]
==== fopen
这个是用得相对比较少的 C 风格传统文件读写,但是比较复杂,需要使用 `fscanf` 和 `fprintf,读者可以自上网了解。`
#align(center)[
```cpp
FILE *in = fopen("test.in");
FILE *out = fopen("test.out");
int x;
fscanf(in, "%d", &x);
fsprintf(out, "%d", x);
fclose(in);
fclose(out);
```
]
== 分支结构
在之前的程序中,我们的语句都是一条一条顺序执行的。但是,在本小节就要打破这个规律了。假如要你编写下面一个程序:如果 $x=100$,输出 $1$,否则输出 $0$。是不是在之前都没有学过这种语法?那么快来学习吧!
=== if 语句
```cpp if``` 语句是最简单的分支结构。分支结构就是根据不同的条件去做不同的事。格式为 ```cpp if (条件) { }```,大括号里面就跟主函数一样塞一些语句去运行。对于上面的例子,我们可以这样子做:
#align(center)[
```cpp
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
if (x == 100) {
cout << 1;
}
if (x != 100) {
cout << 0;
}
return 0;
}
```
]
但是,我们可以发现,虽然我们可以判断 $x=100$ 了,但是判断 $x=100$ 不为真还得再写一个 $x!=0$。万一判断条件很复杂怎么办?这是,就需要请出我们的 ```cpp if-else``` 语句了。它的格式如下:
#align(center)[
```cpp
if (条件) {
语句;
} else {
语句;
}
```
]
这种语句的逻辑为:如果条件为真,那么执行 ```cpp if``` 里面的内容,否则执行 ```cpp else``` 里面的内容。那么,刚才的程序就可以简写为以下形式:
#align(center)[
```cpp
if (x == 100) {
cout << 1;
} else {
cout << 0;
}
```
]
那么,如果有多个 ```cpp if``` 只能满足其中一个,并且需要判断是不是都不满足呢?那么就可以使用我们的 ```cpp if-else``` 语句(```cpp else``` 可以不需要)。
比如,现在需要你编写一个判断 $x$ 的函数,如果 $x$ 为整数,输出 $1$;如果 $x$ 为负数,输出 $-1$;否则输出 $0$。我们当然可以使用三个 ```cpp if``` 进行判断,但是这样子可读性就会很糟糕。可以这样写:
#align(center)[
```cpp
if (x > 0) {
cout << 1;
} else if (x < 0) {
cout << -1;
} else {
cout << 0;
}
```
]
当然,你也可以将 ```cpp else``` 改成 ```cpp else if (x == 0)```,但是 $x>0$ 和 $x<0$ 就排除了 $x!=0$ 的所有剩余情况了,因此这种情况直接使用 ```cpp else``` 会更好一点。
还有更复杂的情况,那么就是 ```cpp if``` 的嵌套。比如现在给你两个数,一个是 `iq` 表示智商($0$ 或 $1$),一个是 `id` 表示情商($0$ 或 $1$)。然后根据生活经验判断并输出 `"2B", "3B", "ZB", "Clever"`,那么我们就需要使用到 ```cpp if``` 的嵌套了,因为嵌套的可读性要更高(不是盲目地嵌套)。
比如可以这样写,而不是写四个 `if` 排一起。
#align(center)[
```cpp
if (iq == 1) {
if (id == 1) {
cout << "Clever";
} else {
cout << "2B";
}
} else {
if (id == 1) {
cout << "ZB";
} else {
cout << "3B";
}
}
```
]
我们还可以使用之前的逻辑运算符。比如需要判断 $a=100$ 和 $b=10$ 是否同时满足条件,那么就可以使用 ```cpp a == 100 && b == 10``` 来进行判断。
=== switch 语句
```cpp switch``` 语句是比较冷门的一种分支语句,但是当判断条件比较多的时候,```cpp switch``` 语句说不定比一大串的 ```cpp if-else``` 效果会更好。格式:
#align(center)[
```cpp
switch (需要判断的数) {
case 判断数1:
语句;
break;
case 判断数2:
语句;
break;
default:
语句;
}
```
]
翻译成 ```cpp if``` 语句就是下面这样子的:
#align(center)[
```cpp
if (需要判断的数 == 判断数1) {
语句;
} else if (需要判断的数 == 判断数2) {
语句;
} else {
语句;
}
```
]
可以看到,```cpp switch``` 语句是逐条判断是否等于指定数的,并在判断成功时候运行语句吧并退出。```cpp default``` 就相当于 ```cpp if-else``` 里面的 ```cpp else```。
*易错点:*首先,```cpp case``` 里面必须加上 ```cpp break``` 语句,这个语句的作用可以在循环结构里面找到,如果不加的话那么就会发生奇奇怪怪的错误;其次,`判断数` 必须是常量,变量统统不行。而且,```cpp switch``` 语句还只能判断基础数据类型,因此非常鸡肋。
好吧,有时候还是很有用的。
== 循环结构
如果你遇到了一个问题,给定 $n$,打印 $(1, n)$ 当中的所有整数,那么你该如何求解?难道一行一行地输出?因为在之前的所有学过的知识当中,我们并没有学过循环处理的语法,根本没有充分利用到计算机超快的运算速度。接下来,好渴鹅就会详细讲解关于 C++ 循环结构的知识。
=== while 语句
```cpp while``` 在英语当中是“当”的意思,而在 C++ 里面就是当某个条件成立时不断运行语句。语法为 ```cpp while (条件)```。其中,条件是一个布尔表达式,为真或假。注意,如果条件一直为真而循环里面没有退出语句的话,那么就会一直进行循环,这种循环被称为“死循环”。
例如,以下代码就是一个“死循环”,会一直打印 ```cpp "Hello world!"```:
#align(center)[
```cpp
while (true) {
cout << "Hello world!" << endl;
}
```
]
而对于上面的例题,我们只需要使用一个“循环变量” $i$ 即可完成操作。代码:
#align(center)[
```cpp
cin >> n;
int i = 1;
while (i <= n) {
cout << i << ' ';
i++;
}
```
]
如果输入 $n=5$ 的话,那么循环步骤为:
#align(center)[
- $i=1$,满足 $i<=n$,输出 $i$,$i<-i+1$;
- $i=2$,满足 $i<=n$,输出 $i$,$i<-i+1$;
- $i=3$,满足 $i<=n$,输出 $i$,$i<-i+1$;
- $i=4$,满足 $i<=n$,输出 $i$,$i<-i+1$;
- $i=5$,满足 $i<=n$,输出 $i$,$i<-i+1$;
- $i=4$,不满足 $i<=n$,退出循环。
]
可以看到我们成功完成了任务。
=== do-while 语句
你肯定会问,```cpp do-while``` 语句跟 ```cpp while``` 语句到底是有什么区别呢?不久多了一个 ```cpp do``` 吗?没错,区别仅仅在 ```cpp do``` 上面,但是它们的执行方式确有很大区别。
```cpp while``` 语句是当条件成立就一直执行,而 ```cpp do-while``` 语句则是先执行在判断是否满足条件。举个简单的例子,如果条件一开始就不成立,那么 ```cpp while``` 循环就不会执行,但是 ```cpp do-while``` 循环则会至少进行一遍。比如将上面的代码改成 ```cpp do-while``` 循环:
#align(center)[
```cpp
cin >> n;
int i = 1;
do {
cout << i << ' ';
i++;
} while (i <= n);
```
]
你就会发现 $n+1$ 也输出出来的。因此,使用 ```cpp do-while``` 循环在这种情况下必须将 $<=$ 改成 $<$。而这样也不严谨,因为当 $n<1$ 的时候也会输出。你是不是觉得 ```cpp do-while``` 循环一无是处呢?也不一定,在特定环境下,```cpp do-while``` 循环可以更好地处理问题。
=== for 语句
```cpp for``` 循环应该是所有循环语句里面最复杂的那个了。语法为 `for (表达式一; 表达式二; 表达式三)`。首先在循环开始之前,执行表达式一的内容,然后当表达式二成立的时候执行循环体里面的内容,每一次执行完之后就执行表达式三,然后一直循环。大概是这样子的:
#align(center)[
#image("image/for-loop.png", width: 40%)
]
就比如上面的代码,可以简化成如下的形式:
#align(center)[
```cpp
cin >> n;
for (int i = 1; i <= n; i++) {
cout << i << ' ';
}
```
]
可以看到,变量 $i$ 放到了第一个表达式里面进行定义,判断条件没有变,循环变量的增量则是放在了第三个表达式里面。其实,只要是循环最后面的若干条指令都可以全部放进第三个表达式里面。
注意 ```cpp for``` 循环定义的循环变量只能够在循环里面使用,而 ```cpp while``` 循环在循环体外面定义的循环变量则在后面的循环中也可以使用。
=== break 与 continue
如果在循环当中不需要继续循环了呢?我们只需要使用一个布尔类型的变量,在需要跳出循环的时候将其赋为真,然后在循环条件里面判断就行了。
但是如果是在循环当中想要跳出怎么办?用上面的方法必须在循环重置的时候才会跳出,循环后面的语句还会继续执行。因此我们可以使用 ```cpp break``` 关键字,这会跳出最里层的循环。例如,当 $i$ 为质数时跳出。(假设 ```cpp isPrime(x)``` 可以判断 $x$ 是否为质数)
#align(center)[
```cpp
int i = 1;
while (true) {
if (isPrime(i)) {
break;
}
i++;
}
```
]
而 ```cpp continue``` 呢则是重置当前的循环(同样需要判断条件),后面的所有语句都省略。注意 ```cpp for``` 循环的增量在 ```cpp continue``` 之后还是需要执行的。
就比如,输入 $n$ 个数,当输入的数为偶数时,就直接输出,否则把这个数逐位反转之后输出。代码怎么写?
首先,我们知道直接输出对比反转之后输出那肯定是直接输出简单很多,因此我们使用一个 ```cpp if``` 来判断输入的数是否是偶数(偶数的基本判断条件是是 $2$ 的倍数,也就是对 $2$ 取模为 $0$),如果是的话那么就直接输出,然后 ```cpp continue```,也就是跳过循环后面的所有语句。
接下来我们再考虑如何对一个数反转输出,注意听好了。首先,我们知道,一个数对 $10$ 取模可以得到这个数的最后一位(十进制下),这里使用了十进制的基本原理;而对一个数除以 $10$ 可以去掉最后一位(十进制下)。因此,当这个数不等于 $0$ 时,我们就不断执行这个操作,就可以对这个数的每一位倒序输出了。
#align(center)[
```cpp
cin >> n;
for (int i = 1, x; i <= n; i++) {
cin >> x;
if (x % 2 == 0) {
cout << x << '\n';
continue;
}
for (; x; x /= 10) {
cout << x % 10;
}
cout << '\n';
}
```
]
*补充:*在最外层的 ```cpp for``` 循环的第一个表达式里面,我们不仅定义了循环变量 $i$,还定义了用于输入的局部变量 $x$。内层的 ```cpp for``` 循环可能对于初学者来说有些难以看懂,其实这也是 ```cpp for``` 循环的常用用法,转化成 ```cpp while``` 是这样的(在布尔表达式里面直接写整数等同于判断这个整数不等于 $0$):
#align(center)[
```cpp
while (x) {
cout << x % 10 << ' ';
x /= 10;
}
```
]
== 数组
现有这么一道题,给定 $n$ 个数,然后倒序输出他们。以我们之前所学的知识是完全做不出来的,因为在之前我们都是使用一个变量来表示一个值,但若是 $n$ 很大呢?那我们就没有办法了,这时候就需要使用一种名为“数组”的类型。
=== 定义与使用
定义长度为 $n$ 的数组 $a$ 可以采取以下的格式(在 C++ 11 之前 $n$ 必须是常量,否则可能发生编译错误):
#align(center)[
```cpp
type a[n];
```
]
那么如何访问呢?可以通过 `a[i]` 来访问数组当中下标为 $i$ 的元素。为什么是下标 $i$ 而不是第 $i$ 个元素呢?其实是因为 C++ 当中长度为 $n$ 的数组下标的范围是*从零开始*的,即 $[0,n-1]$,因此访问数组 $a$ 的第一个元素得写 ```cpp a[0]```而非 ```cpp a[1]```。
数组的存储在内存当中一定是连续的,而非像普通的变量一样可能会存储在内存的不同地方。这样的设计是为了方便申请内存和加快缓存速度。
回到刚刚的题目,是不是就非常简单了。我们可以使用 ```cpp for``` 循环正序输入元素,再用 ```cpp for``` 循环倒序输出元素。代码:
#align(center)[
```cpp
int main() {
int n;
cin >> n;
int a[n];
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = n; i >= 1; i--) {
cout << a[i] << ' ';
}
return 0;
}
```
]
*补充:*为了更贴合人类使用,在一般的使用过程中一般都会把数组的长度设为 $n+1$,然后将 $a_1$ 当做第一个元素。一般我们都会定义长度为常量的数组,相对来说会要更稳定一些。数组也要尽量定义在函数的外面,使用堆而非栈,可以开更大的数组。
=== 多维数组
在一些特殊的情况下,例如需要输入矩阵的时候,就需要使用多维数组了。二维数组是最简单的多维数组。例如以下的例题:
给定一个 $n times n$ $(1<=n<=1000)$ 的数组 $a$,将其的行和列反转后输出,通俗一点就是每一行变成列,每一列变成一行,原来的 $a_(i,j)$ 就变成了 $a_(j,i)$。
这时候就需要使用我们的二维数组了,定义方式和一维数组差不多,为 `type a[n][n]`。使用 `a[i][j]` 即可访问数组 $a$ 的第 $i$ 行第 $j$ 列(也可以颠倒,这对于使用来说不重要)。
那么上面的代码就很简单了,输出的时候只需要第 $i$ 行变成第 $i$ 列,第 $j$ 列变成第 $i$ 行就可以了。注意输出完一行之后要换行。
#align(center)[
```cpp
const int kMaxN = 1001; // 数组大小,注意我们是从一开始的,因此要加一
int a[kMaxN][kMaxN], n; // 数组和整数定义
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> a[i][j];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << a[j][i] << ' ';
}
cout << '\n';
}
return 0;
}
```
]
== 函数
在 C++ 当中,主函数是程序的入口,代码都会逐行运行。但是如果有一些语句重复了很多次,那么就可以使用函数来进行封装,提高代码的可读性(读起来不会骂人)和复用性(重构起来不会骂人)。
C++ 在标准库当中定义了很多的内置函数,只需要几行命令引入并调用就行了,比如算数平方根、三角函数等数学函数。我们也可以自定义函数,来实现自己想要的功能。
函数还有很多常用的叫法,比如方法、程序等等,英文为 Function。
=== 标准库
假如有一道题,是这样的:输入一个实数 $x$ $(x>=0)$,要求得到 $sqrt(x)$ 并输出。$sqrt(x)$ 为 $x$ 的算数平方根,意思是得到一个 $y$ 使得 $y^2=x$。由于在实数范围内没有数的平方是负数,因此 $sqrt(x)$ 必须大于等于 $0$。
那么我们就可以调用 C++ `cmath` 库当中预定义的 `sqrt` 函数(英文全程为 Square Root)来求出算术平方根。代码如下:
#align(center)[
```cpp
#include <iostream>
#include <cmath>
using namespace std;
double x;
int main() {
cin >> x;
cout << sqrt(x) << '\n';
return 0;
}
```
]
C++ 还有更多常用的内置函数,在后面中会对其中的一些进行使用,也可以上网搜索更多 C++ 的内置函数。
=== 自定义函数
在 C++ 当中,不仅可以使用内置函数,还可以自己定义函数。语法如下,其实也跟 `main` 函数差不多:
#align(center)[
```cpp
return-type function-name(type args, ...) {
function-body;
return return-value;
}
```
]
比如,定义一个名叫 `times2` 的函数,并传入参数 $x$,返回 $x$ 的两倍就可以这样定义:
#align(center)[
```cpp
int times2(int x) {
return 2 * x;
}
```
]
然后就可以调用这个函数了,例如 `int x = times2(1)` $x$ 就会等于 $2$,因为*实际参数* $1$ 传到 `time2` 里面会变成*形式参数* $x$,然后我们返回了 $2 times x$,因此在外面的变量 $x$ 就接受了这个值,即 $2$。
函数除了返回普通的类型,还可以返回特殊的类型 ```cpp void```,这个类型称之为*无类型*,这代表着函数只是一个过程,没有任何返回值,因此返回语句可以不写。如果需要在特定地方结束的话,可以使用 ```cpp return;``` 或 ```cpp return void();``` 语句退出。
一般纯过程的函数都会改变外部变量,不然这个函数是没有任何意义的。例如,以下函数就是一个纯过程的函数:
#align(center)[
```cpp
void seyHello() {
cout << "Hello world!" << endl;
}
```
]
=== 函数递归
调用本身函数的函数就叫做递归函数,递归函数可以让代码变得更加简洁,但是可能会带来较大的内存负担并拖累程序的运行速度。
比如,你需要定义一个函数 $f(x)$,使得可以计算 $x!$ 并返回。($x!$ 为 $x$ 的阶乘,等同于 $1 times 2 times dots times x$ 或 $limits(product)_(i=1)^(n)i$)怎么办?是不是可以使用我们之前学过的循环结构!
#align(center)[
```cpp
int f(int x) {
int fac = 1;
for (int i = 1; i <= x; i++) {
fac *= i;
}
return i;
}
```
]
但是这样子代码根本就不简洁。考虑数学上的递归,是不是有 $x! = (x-1)! times x$ ?但是这样子会地址递归下去,因此我们需要设立递归边界。因为 $1! =1$,因此我们就把递归边界设为 $x=1$。代码:
#align(center)[
```cpp
int f(int x) {
if (x == 1) {
return 1;
}
return f(x - 1) * x;
}
```
]
让我们来模拟以下调用 $f(3)$ 递归的操作:
- *第一个函数*传入了参数 $x=3$。由于 $x!=1$,因此返回 $f(x-1) times x$,调用第二个函数。
- *第二个函数*传入了参数 $x=2$。由于 $x!=1$,因此返回 $f(x-1) times x$,调用第三个函数。
- *第三个函数*传入了参数 $x=1$。由于 $x=1$,因此返回 $1$,回到第二个函数。
- *第二个函数* $x=2$,$f(x-1)$ 已经计算完了等于 $1$,因此返回 $1 times 2=2$,回到第一个函数。
- *第一个函数* $x=3$,$f(x-1)$ 已经计算完了等于 $2$,因此返回 $2 times 3=6$,递归完成。
是不是非常烧脑?其实我们只需要掌握 $x! = (x-1)! times x$ 就行了,这个公式是这样推导出来的:
$ x! &= 1 times 2 times dots times x \
&= [1 times 2 times dots (x-1)] times x \
&= (x-1)! times x $
在递归时只需要将其转为 $f(x)=f(x-1) times x$,并设好边界条件(不然会一直计算 $f(x-1)$)就行了。是不是恍然大悟?
=== 数组传参
需要特别注意的是,C++ 的数组是在所有数据类型当中最特殊的那一个,其他数据类型当做形式参数的时候都会值拷贝,唯独数组是直接引用传递。这就代表着在函数内部改变数组的值在外面也会起到作用。这样看来,数组是不是就跟后面所学的指针一样,只是一个指向数组头部的指针呢?也不是,因为在 ```cpp sizeof``` 的时候,数组返回了整个数组的大小,而指针只返回了指针本身存储在内存当中的大小。
因此,使用数组传参的时候一定要多加小心,防止出现非预期的错误。
== 指针
=== 指针的认识
什么是指针?其实,在 C++ 当中的变量,全都是存储在内存里面的,而内存都会有一个“地址”用于访问值。C++ 编译器就处理了变量对应的地址,使得你使用变量就可以访问这个变量的地址上面的值。
而指针就是专门指向一个地址进行访问的,可以使一些复杂的数据结构变得更简单、灵活,并且指针还可以申请堆上面的内存。
在 C 语言当中是没有引用的,而函数传参都是直接转递值,这就代表着在函数里面更改参数的值在外面不会起作用。这种情况下,就需要使用指针来直接操作地址了。
指针本身只是一个指向数据的数据类型,本身也是变量,所以还有指向指针的指针——双重指针,这都是比较复杂的内容了。虽然它很难,在实际操作中极易造成内存溢出,但是只要你认真学习,一定能够熟练掌握。
=== 使用指针
定义指针的方法特别简单。在过去,我们定义一个 ```cpp int``` 类型的变量是不是直接 ```cpp int a;``` 就行了呢?指针的定义也不复杂,指向一个 ```cpp int``` 类型的地址的指针可以使用 ```cpp int *p;``` 来定义。
注意星号只对后面的一个变量起作用,这就代表着 ```cpp int *p, a;``` 这种定义方法只有 $p$ 是指针,$a$ 就只是普通的变量。因此,在定义的时候,尽量将星号写在靠近变量名的那边而非类型的那边。
想要让你的指针指向一个指定的变量的地址,我们需要用到取地址符 `&`。诶,这好像有点似曾相识?没错,就是位与运算,但是当只有一个操作数的时候就变成了取地址符。
比如以下代码:
#align(center)[
```cpp
int a = 1;
int *p = &a;
```
]
这段代码首先定义了一个 ```cpp int``` 类型的普通变量 $a$,并将其初始化为 $1$。然后定义了一个指向 ```cpp int``` 的指针 $p$,并把它指向的地址初始化为 $a$ 的地址。
想要通过指针指向的地址访问这个地址上面的元素,需要使用解引用符 `*`。你没有看错,就是乘法的那个星号,但是跟取地址符一样,若只有一个操作数的话就变成了解引用符。
比如,上面的代码增添上下面这一句:
#align(center)[
```cpp
cout << *p << '\n';
```
]
就能发现程序输出的值为 $1$,因为指针 $p$ 指向的地址是变量 $a$ 的地址,而 $a$ 的值此时为 $1$,因此就会输出 $1$。需要注意的是,由于指针是直接操作内存,因此更改解引用后的指针的值就等同于直接修改变量:
#align(center)[
```cpp
int a = 1, *p = &a;
*p = 2;
cout << a << '\n';
```
]
可以看到,程序输出了 $2$。因为 $p$ 指向的是 $a$ 的地址,而我们将这个地址上面的数修改成了 $2$,因此输出 $a$ 的时候值就会也变成 $2$。
当你只想要使用指针,而不是再定义一个毫无意义的变量来供指针指向的话,可以使用 `new` 关键字来申请一个空间。比如:
#align(center)[
```cpp
int *p = new int;
```
]
这样子 $p$ 就可以指向一个新申请的空间,而这个空间是“匿名”的。
=== 连续空间
在刚才的尝试当中,我们的指针都是只指向了一个元素的,那么,如何让指针指向多个元素呢?其实这是不可能的,但是我们可以指向一段连续元素的头,这样子就可以达到指向多个元素的效果。
申请一段连续空间的语句是 ```cpp new```,例如以下代码:
#align(center)[
```cpp
int *a = new int[5];
```
]
这段代码就是定义了一个指向 ```cpp int``` 的指针 $a$,并申请了长度为 $5$ 的连续 ```cpp int``` 空间给它,这样子它就能称为一个“数组”了,同样可以使用中括号访问元素。
#align(center)[
```cpp
a[1] = 1;
cout << a[1] << '\n';
```
]
需要注意的是,```cpp new``` 一般都是申请的堆空间,因此程序在运行时不会自动清理,需要手动销毁。销毁单个指针指向的元素为 ```cpp delete```, 销毁指向的连续一段空间为 ```cpp delete[]```。例如,销毁 $a$ 指向的连续一段的空间的代码为:
#align(center)[
```cpp
delete[] a;
```
]
=== 函数指针
=== 引用
== 更多技巧
=== 位运算拓展
这里是关于位运算的更多奇技淫巧。
位运算一般都是有三种作用,例如:
- 题目当中明确说明了需要使用位运算。
- 用来表示集合,但是如果位数较多需要使用 STL `bitset`。
- 用高效的指令集取代某些低效的算法,例如求 $2^n$。
值得一提的是,大部分 Noip 系列的比赛都会在编译时默认开启最大速度优化,也就是 O2。这时用 ```cpp >> 1``` 除以二反而没有任何速度提升,因为编译器已经将 ```cpp / 2``` 优化成 ```cpp >> 1``` 了。
==== 计算 $2^n$
因为在二进制当中是逢二进一的,因此 $1$ 后面跟 $n$ 个 $0$ 就等同于 $2^n$。这点我们人类使用的十进制也是有所体现的,在十进制当中 $1$ 后面跟 $n$ 个 $0$ 就等同于 $10^n$。
因此,我们对 $1$ 左移 $n$ 位,使得后面空出 $n$ 个 $0$,也可以达到 $2^n$ 的效果。如果需要快速计算 $n times 2^m$,那么不用计算完 $2^m$ 再去乘 $n$,实际上直接将 $n$ 左移 $m$ 位就行了。
#align(center)[
```cpp
int pow2(int n) {
return 1 << n;
}
int pow2(int n, int m) {
return n << m;
}
```
]
如果是要计算 $n/2^m$ 的话,那么直接将 $n$ 右移 $m$ 位就行了。但是需要注意的是,这个的结果是向下取整而非向 $0$ 取整的,在使用过程中需要注意。
==== 判断奇偶性
假如给你一个 $n$,要你判断 $n$ 是否是偶数,你会怎么做?是不是对 $2$ 取模,然后判断是不是 $0$ 啊?实际上也可以对 $1$ 按位取与。因为 $1$ 的前面都是 $0$,因此结果的前面也全都是零;如果 $n$ 的最后一位为 $1$ 的话,那么结果就是 $1$,否则就是 $0$。这也利用了二进制的基本性质。
#align(center)[
```cpp
bool isEven(int x) {
return x & 1 == 0;
}
bool isOdd(int x) {
return x & 1 == 1;
}
```
]
==== 表示集合
位运算让我们能够用整数来表示集合。例如,在 C++ 当中 ```cpp int``` 类型通常都是 $32$ 位的,这让我们能够用它来表示范围仅有 $1~32$ 的集合。虽然看起来位数并不多,但是奈何不住它快啊!常见的集合表示方法都是用一个二叉树来,既耗内存又没有速度优势,而我们使用整形来表示集合可以很快地进行集合相关的操作,必要时还可以当下标使用。
需要注意的是,整数的位数是从右往左的,最后一位是第 $0$ 位;而我们这里所说的位数虽然也是从右往左,但是最后一位是第 $1$ 位。
比如想要让 $x$ 的第 $i$ 位变成 $1$,那么只需要执行 ```cpp x |= 1 << (i - 1)``` 就行了。这句话的原理就是,$1$ 占了最后一位,我们左移 $i-1$ 位就可以让这个 $1$ 变到第 $i$ 位,然后让 $x$ 或上去,因为其它位或 $0$ 都没变,而这一位或 $1$ 就一定能变成 $1$。
同理,想要让第 $i$ 位变成 $0$ 只需要执行 ```cpp x &= 0xffffffff - (1 << (i - 1))```。注意 ```cpp 0xffffffff``` 是一个十六进制数,而这个数字在 $2$ 进制里面正好为 $32$ 个 $0$(感兴趣的可以学习一下十六进制转二进制),我们减去 ```cpp 1 << (i - 1)``` 是为了让第 $i$ 位变成 $0$,这样子就变成了除了第 $i$ 位全都是 $1$ 的了。而任何数和 $1$ 与都是不变的,任何数和 $0$ 与都会直接变成 $0$。因此,该操作就能成功地将第 $i$ 位改成 $0$。
如果是要取交集的话,那么位运算就已经自带位与运算了;如果是要取并集,就可以使用位或运算。总之,用整数来表示集合还是有很多好处的,但是需要有更好的水平才行,
= 算法基础
== 引入
=== 复杂度
时间复杂度和空间复杂度是衡量一个算法在运行效率和空间效率上的重要标准。
同一个算法在不同的计算机、操作系统上面运行的速度会有一定差别,而实际测量算法执行速度非常麻烦,因此通常我们都不会考虑一个算法具体执行了多久的时间,而是算法运行大约需要的基本操作次数。基本操作次数通常包括,加减乘除、赋值与访问等。
不说太多没用的,我们直接来说时间复杂度。例如,有一个算法是有两层循环,每一层循环都是 $1~n$,那么这个算法的时间复杂度就为 $O(n^2)$,用大 $O$ 表示。循环内部可能还会有一些运算,但是如果全部都是常数级的运算的话,那么就可以忽略它们。
在更多时候,算法可能会不止进行一次。在这种情况下每一次进行算法的平均复杂度就叫做均摊复杂度。
空间复杂度既是对算法所用空间的描述。例如,一个算法使用了长度为 $n$ 的数组,那么这个算法的空间复杂度就是 $O(n)$ 的;若使用了 $n times m$ 的二维数组,那么这个算法的空间复杂度就是 $O(n times m)$ 的。
=== 最大数问题
现在我们就尝试来设计一个最最简单的算法吧。给定 $n$ $(n>=2)$ 和长度为 $n$ 的数组 $a$,要求设计一个函数 $max(a,n)$,返回 $a_1~a_n$ 当中的最小值。
让我们来思考一下。首先,$max$ 函数是具有结合律的。我们可以把它看做一个二元运算符 $xor$,$a xor b xor c$ 一定等于 $a xor (b xor c)$。因此,$limits(max)_(i=1)^n a_i=max(limits(max)_(i=1)^(n-1)a_i,a_n)$,也就是 $a_1~a_n$ 的最大值等于 $a_1~a_(n-1)$ 的最大值和 $a_n$。而 $a_1~a_(n-1)$ 的最大值又等于 $a_1~a_(n-2)$ 当中的最大值和 $a_(n-1)$ 的最大值。因此我们只需要从头望后扫一遍,每次看一看新来的那个数是否比之前的数大,如果是的话就把之前的数改为这个数就行了。
由于只需要 $1~n$ 的循环,因此该算法的时间复杂度是 $O(n)$ 的。由于 $a$ 数组是通过传参传来的,因此该算法的空间复杂度是 $O(1)$ 的,即不使用额外非常数空间。
#align(center)[
```cpp
int max(int a[], int n) {
int mx = a[1];
for (int i = 1; i <= n; i++) {
if (a[i] > mx) {
mx = a[i];
}
}
return mx;
}
```
]
当然,该算法也可以使用递归实现,因为 $limits(max)_(i=1)^n a_i=max(limits(max)_(i=1)^(n-1)a_i,a_n)$。
#align(center)[
```cpp
int max(int a[], int n) {
if (n == 1) {
return a[1];
}
return max(max(a, n - 1), a[n]);
}
```
]
可以看到,我们使用了同名的 $max$ 函数,但是这里并没有任何影响。因为标准库当中的 $max$ 函数两个参数必须都是同一类型的参数,而我们定义的 $max$ 的参数列表不一样。
=== 平均数问题
写完最大数问题,趁着火苗正旺,赶紧来写一下平均数问题吧。给定你一个长度为 $n$ 的整数数组 $a$,你需要实现一个函数 $"ave"(a,n)$,表示求 $a_1~a_n$ 的平均数,返回 `double` 类型。定义 $a_1~a_n$ 的平均值为 $limits(sum)_(i=1)^n a_i times 1/n=(a_1+a_2+dots+a_n) times 1/n$。
很简单,我们只需要照着式子写就行了。先求出 $a$ 的和。然后将这个数除以 $n$ 就行了。
#align(center)[
```cpp
double ave(int a[], int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += a[i];
}
return 1.0 * sum / n;
}
```
]
注意 ```cpp int``` 类型和 ```cpp double``` 类型的乘积是 ```cpp double``` 类型,因此最后一行的代码(```cpp 1.0 * sum```)实际上就是将 `sum` 转化为 ```cpp double``` 类型,而 ```cpp double``` 类型除以 ```cpp int``` 类型仍然为 ```cpp double``` 类型,也就是小数除法。
== 枚举
=== 暴力枚举
枚举是一种通过暴力枚举状态来猜测可能得解的一种解题策略。通常来说,我们可以限定枚举的范围让它的复杂度更高。虽然这是一种非常基础的算法,但是后面的很多算法都是基于枚举来实现的。
#quote[
好渴鹅想要吃一条美味程度为 $n$ 的鱼。现在好渴鹅一共有 $10$ 种调料,每一种调料都可以放 $1~3$ 克,而一条烤鱼的美味值就是所放调料的克数之和。你需要输出所有美味值为 $n$ 的方案,具体就是输出每一种调料放多少克。
]
我们可以枚举每一种调料放多少克,最后如果加起来正好等于 $n$ 了就输出。
#align(center)[
```cpp
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
for (int k = 1; k <= 3; k++) {
for (int l = 1; l <= 3; l++) {
for (int p = 1; p <= 3; p++) {
for (int o = 1; o <= 3; o++) {
for (int u = 1; u <= 3; u++) {
for (int m = 1; m <= 3; m++) {
for (int y = 1; y <= 3; y++) {
for (int t = 1; t <= 3; t++) {
if (i + j + k + l + p + o + u + m + y + t == n) {
cout << i << ' ' << j << ' ' << k << ' ' << l << ' ' << p << ' ' << o << ' ' << u << ' ' << m << ' ' << y << ' ' << t << '\n';
}
}
}
}
}
}
}
}
}
}
}
```
]
这里使用了我们之前循环结构里面的循环嵌套,也就是枚举第一个的所有可能,在其之上枚举第二个的所有可能,……,直到枚举完最后一个的所有可能。这样子的方法非常直观,并且能够枚举出所有情况,完全正确。
根据之前学习的复杂度,我们能够求出这个算法的时间复杂度是 $O(3^n)=O(1)$ 的,但是如果所放克数可以是 $1~k$ 的话,那么该算法的时间复杂度就会为 $O(k^n)$,但是这样子枚举出所有情况真的好吗?有没有可能枚举了多余的元素呢?
=== 减小枚举范围
我们发现,当已放调料的克数已经大于 $n$ 的时候,在往下面枚举已经是没有意义的了。因为所有调料的所放克数都必须是 $1~3$ 的整数,所以后面放完调料的总克数一定会比 $n$ 要更大。因此在这种情况下,我们直接 ```cpp break``` 退出循环即可。或者是在循环的时候就不遍历那么多,直接用循环条件限制就行了。
#align(center)[
```cpp
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= min(3, n - i); j++) {
for (int k = 1; k <= min(3, n - i - j); k++) {
for (int l = 1; l <= min(3, n - i - j - k); l++) {
for (int p = 1; p <= min(3, n - i - j - k - l); p++) {
for (int o = 1; o <= min(3, n - i - j - k - l - p); o++) {
for (int u = 1; u <= min(3, n - i - j - k - l - p - o); u++) {
for (int m = 1; m <= min(3, n - i - j - k - l - p - o - u); m++) {
for (int y = 1; y <= min(3, n - i - j - k - l - p - o - u - m); y++) {
for (int t = 1; t <= min(3, n - i - j - k - l - p - o - u - m - y); t++) {
if (i + j + k + l + p + o + u + m + y + t == n) {
cout << i << ' ' << j << ' ' << k << ' ' << l << ' ' << p << ' ' << o << ' ' << u << ' ' << m << ' ' << y << ' ' << t << '\n';
}
}
}
}
}
}
}
}
}
}
}
```
]
值得一提的是,当循环来到了最后一层,最后一种调料的克数已经能够确定了,因此就可以直接进行判定。请读者自行补充。
== 贪心
=== 排序法
贪心算法是用计算机来模拟我们人类在面对问题时做出决策的过程的一种算法。并且,它在进行决策的时候总是目光短浅地选择最优的操作,来尽可能地取得最优解。
并不是所有的题目都可以由贪心实现,但是贪心是众多算法的基础。比如搜索中的“最优化剪枝”还有 Dijkstra 算法的中心思想,里面都有一些贪心的元素。
贪心算法往往比较简单,因为人类本身就是贪心的。就比如接下来的一道题:
#quote[
给定 $n$ 个数,你现在要选择最多 $m$ 个数 ,使得选择的数相加和最大。输出这个最大的相加和。(可能会有负数)
]
这个问题,就跟你做作业一样,选择一定数量的作业,那么我们每一次都选择量最少的作业,那么最后选择的作业加起来一定也是最少的。本题也一样,每一次都选择最大的那一个数,那么加起来一定也是最多的。
注意这里可能会有负数,但是加负数是没有用的。那么如果我们加到了负数,就说明后面的数都是负数了,那么我们就不加,直接退出即可。
代码当中使用了 `algorithm` 库当中的排序函数 `sort`,并使用了 `greater<int>()` 函数返回的大于号比较器实现从大到小排序。具体可以看附录。这里简单讲解一下:
```cpp sort(begin, end, comp)``` 就表示对 `[begin, end)` 之间的所有元素进行排序,比较器为 `comp`。如果不传入该参数的话,就是默认从小到大排序。
#align(center)[
```cpp
int solution() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
sort(a + 1, a + n + 1, greater<>()); // 尖括号内可以省略
for (int i = 1; i <= m; i++) {
ans += a[i] * (a[i] > 0);
}
return ans;
}
```
]
#quote[
现在有 $n$ 个人排队接水,第 $i$ 个人接水的时间为 $a_i$。现在要你重新排这 $n$ 个人的位置,使得这 $n$ 个人的平均等待时间最少。输出重新排列后的顺序以及平均等待时间。
]
首先,看到这题,我们的人脑很快就可以想出一个解法:叫打水更快的人站到前面不就行了,这样子后面的人等的不也少了吗?可是,这个解法怎么证明是对的呢?
我们可以设总的打水时间为 $S$。显然 $S$ 越小,平均值 $S/n$ 也会越小,因此我们需要最小化 $S$。排列完之后,第 $i$ 个人需要等待前面所有人和自己大水的所有时间,因此第 $i$ 个人总的等待时间就为 $limits(sum)_(j=1)^i a_j$。所以:
$ S=sum_(i=1)^n sum_(j=1)^i a_j=(a_1)+(a_1+a_2)+dots+(a_1+a_2+dots+a_n) $
我们发现,$a_1$ 需要相加 $n$ 次,而 $a_2$ 需要相加 $n-1$ 次,但是 $a_n$ 却只需要相加 $1$ 次。那么结果很显然了,让小的加更多次显然是更优秀的。因此我们需要吧时间短的排在前面。
代码使用了结构体和自定义 STL 排序,具体请看类与对象当中的“结构体”章节。
=== 后悔法
== 排序
=== 比较排序
==== 选择排序
==== 冒泡排序
==== 插入排序
==== 归并排序
==== 快速排序
==== 堆排序
=== 非比较排序
==== 桶排序/计数排序
==== 基数排序
== 数学
=== 快速幂
=== 质数判断
=== 质数筛
==== 埃氏筛
==== 欧拉筛
=== 最大公因数
=== 杨辉三角
== 二分
=== 序列二分
=== 二分答案
=== 三分
== 前缀和与差分
=== 前缀和
=== 差分
== 双指针
=== 快慢指针
=== 滑动窗口
=== 对撞指针
== 搜索
=== 深度优先搜索
=== 广度优先搜索
=== 剪枝
=== 折半搜索
= 类与对象
== 类的定义
== 成员与成员函数
== 构造函数与析构函数
== 静态成员
== 重载运算符
== 友元函数
== 继承
== 虚函数
== 抽象
= 附录
== 关于命令行的使用
大部分操作系统都是有图形化的,图形化对于普通用户来说是十分便利的,不需要学习过多复杂的指令等。但是,很多时候命令行的操作对于图形化应用来说会要更简单,而且很多服务器只有命令行。因此,学会命令行的使用非常重要。
=== 打开命令行
不同系统打开命令行的方式是不一样的。
- *Windows 系统:*在开始菜单栏搜索命令提示符就可以打开了,命令提示符就是 Windows 系统下的命令行。
- *Linux 系统:*在大多数的 Linux 发行版当中,使用 `Ctrl + Alt + T` 组合键就可以方便地打开命令行。
- *MacOS:*使用启动台,或是聚焦搜索可以直接打开。
=== Cmd 与 PowerShell 的区别
非 Windows 用户可以忽略。
- *外观方面:*在 Cmd 窗口当中所有文字的颜色都是一模一样的,没有语法高亮,而在 PowerShell 关键字等不同的文字就会被高亮成不同的颜色。
- *命令方面:*Cmd 窗口是 Windows 独有的,很多 Linux 常用的命令都没有支持;而 PowerShell 就可以支持,例如 `ls` 等命令。还有一个显著的区别是在 Cmd 下运行命令默认会索引到当前目录,而 PowerShell 则不会,这导致假设你需要运行 `main.exe` 在 PowerShell 下必须写为 `./main.exe`(或反斜杠)。
- *其他区别:*PowerShell 是基于 .NET 面向对象的,集成了更多的功能。Cmd 是默认在所有 Windows 里面集成的,而 PowerShell 在最新几代里面才会集成。
以下所有命令均为在 Linux 下可以正常执行的,Windows 可能会造成一定差异。
=== 基本命令
- `cd` 用于切换当前工作目录,可以输入相对路径或绝对路径。
- `ls` 查看当前目录下的所有文件。
- `mkdir` 用于在当前工作目录下创建文件夹。
- `rm` 删除目录或文件
- `mv` 移动目录。
- `cp` 拷贝目录。
- `touch` 新增文件,另一种受欢迎的办法是使用 `vim` 创建。
- `vim`(在老版 Linux 中只有 `vi`)编辑文件,没有则创建。
- `sudo` 暂时获得 Root 权限,需要输入密码。
还有更多命令可以上网搜索,一般情况下上面的命令就已经完全够用了。
=== GCC 基本命令
在命令行中,若已安装 GCC,则可以编译 C 或 C++ 文件(C++ 文件需要使用 `g++` 命令编译)。比如,编译 `main.cpp` 文件并输出二进制文件到当前目录下的代码为(不用输入 `$`,`$` 是输入命令的提示符):
#align(center)[
```bash
$ g++ main.cpp
```
]
该操作会在当前目录下生成可执行文件,一般名称为 `a.out`,可以通过 `ls` 命令查看。若想执行该可执行文件,可以使用键入 `./a.out` 完成操作。
若想自定义输出的可执行文件的名称,可以添加 `-o` 参数,后面跟着要重命名的名称。例如,一下操作可以编译 `main.cpp` 源文件,并在当前目录下生成 `app` 可执行文件。
#align(center)[
```bash
$ g++ main.cpp -o app
```
]
在正式的比赛当中,为了让程序的运行速度更快,一般都会在编译时开启优化。比如可以加入 `-O2` 参数来开启最大速度优化。以下代码可以在对 `main.cpp` 源文件进行编译,并输出 `main.exe` 可执行文件的情况开启 `-O2`。
#align(center)[
```bash
$ g++ main.cpp -o main.exe -O2
```
]
同样,`g++` 默认的 C++ 版本一般都是编译器所支持的最高版本,而不同的版本之间可能会有一些细微的差别。CCF(中国计算机协会)规定了 C++ 标准应为 ISO C++ 14,并开启 O2 优化。为了获得跟 CCF 类似的体验,可以使用如下的编译指令:
#align(center)[
```bash
$ g++ main.cpp -o main.exe -std=c++14 -O2
```
]
== STL
=== 算法库
==== algorithm
==== numeric
=== 容器库
==== array
==== vector
==== list
==== forward_list
==== set
==== map
==== deque
==== unordered_set
==== unordered_map
==== stack
==== queue
==== priority_queue
== C++ 11 新特性
=== 语言方面
==== auto & decltype
==== 左右值
==== 范围 for
==== Lambda 表达式
==== constexpr
=== 类与对象方面
==== final & override
==== default & delete
==== explicit
==== 模板的改进 |
|
https://github.com/ralphmb/My-Dissertation | https://raw.githubusercontent.com/ralphmb/My-Dissertation/main/other/bradleyterry.typ | typst | Creative Commons Zero v1.0 Universal | #heading([Bradley-Terry models], numbering:none, outlined:false)
/* CHECK OUT KUK 1995 @kuk1995 */
In this section we will take a new approach to the problem of modelling football match results.
A paper by #cite(<koning>, form:"prose") uses an ordered probit model to assess team strengths and home advantage.
Using $D^(*)$ as a latent variable for match result, the author fits a model as $D^(*) = alpha_(i) - alpha_(j) + h_(i j) + nu_(i j)$, where $alpha_(k)$ is a term representing the relative strength of team $k$, $h_(i j)$ represents a home advantage factor when $i$ plays at home against $j$, and $nu_(i j)$ are normal errors. The model is thus treating the outcome of a game as being related to the difference in "strength" between the two teams, with some extra detail through the error and home advantage terms.
This is very similar to a Bradley-Terry model (BT model), and in the following section we will see if these are useful for modelling match outcomes for our data. The BT model adapts logistic regression to treat the response variable as a difference of "strength" values: $"logit"(Pr(i>j)) = alpha_i - alpha_j$
A more common use of regression in sports involves taking information about the strengths of each and using it to predict match outcome, whereas BT models use data on match outcome to assign strengths to teams.
/*Here we will investigate whether the models are useful, and if they are, train them on a subset of the data and try to predict the rest*/
In addition to sports modelling, these models are often used for ranking items based on a series of pairwise comparisons. /*#highlight([Reference here?])*/
/* references needed here? */
The usual BT model isn't equipped to deal with ties in the data so as in the logistic regression section, the outcomes here will be 'home win' and 'not home win'.
An advantage of these models over the previous approach is that we aren't using any predictive variables, only match results against dummy variables for the teams, hence the low information content of our data won't hamper model performance.
We can fit a basic model using `BTm()` in the `BradleyTerry2` package in R.
For this section we are including every match result, including games involving promoted teams and matches with red cards.
```R
bt_mod <- BTm(outcome = result_bin,
player1 = factor(match_unique$team),
player2 = factor(match_unique$opponent))
summary(bt_mod)
```
Which finds the following list of team specific "strengths".
#table(
columns:2,
table.cell([Coefficients:], align: center, colspan: 2),
[Arsenal], [1.964],
[<NAME>], [1.173],
[Brentford], [1.054],
[Brighton & HA], [1.054],
[Chelsea], [0.242],
[Crystal Palace], [0.359],
[Everton], [0.476],
[Fulham], [ 0.476],
[Leeds United], [ -0.392],
[Leicester City], [-0.126],
[Liverpool], [1.294],
[Manchester City], [2.469],
[Manchester United], [1.546],
[Newcastle United], [1.679],
[Nottingham Forest], [0.122],
[Southampton], [-0.687],
[Tottenham Hotspur], [1.173],
[West Ham United], [0.122],
[Wolverhampton Wanderers], [0.359],
)
Notice the absence of AFC Bournemouth among the teams listed, they are treated as the reference team with strength 0.
The values given seem to make some sense, with stronger teams such as Manchester City and Liverpool having higher coefficients and weaker teams such as Leeds having negative ones.
All of the coefficients here have a standard error in the range $(0.49, 0.58)$. This is of course quite high, given many of the teams have coefficients of a magnitude lower than this. The high variance in these estimates is because each pairwise matchup occurs only twice, each team plays every other at home and away. Including multiple seasons worth of data may assuage this somewhat, as the results of more matchups could be included, however as teams move between leagues and their prowess changes over time this would add complications.
We can use the results of this fit to find predicted win chances for different teams. Taking Newcastle United (H) and Leicester City as examples:
$ Pr("N.U. Win" ) = 1/(1+e^(-1.679 + 0.126 )) = 0.825 $
Due to the fact that home teams win about half of their games and the outcomes are being grouped as "home win" vs "not home win", there's an argument against including a home advantage parameter here: the data support a roughly even rate of home wins and away "wins".
Supposing teams $i,j$ play one another with $i$ at home, and $alpha_i - alpha_j = Delta alpha$ is small, then the basic BT model (without additional parameters) will predict
$ Pr(i "wins") = (1 + exp( alpha_i - alpha_j))^(-1) approx 1/2 - (Delta alpha)/4 $
And indeed if we choose to fit one with a constant home advantage factor, R estimates $h = -0.08$ with s.e. $0.11$, which is very close to zero. An interaction between home advantage and team strength might make one useful however, and we see evidence of that in the exploratory analysis section.
#heading([Including Ties], numbering:none, outlined:false)
/*#highlight([Kuk 1995 - Modelling Paired Comparison Data has a discussion of these models in relation to football, worth adding a reference to this?])*/
As alluded to earlier, modifications can be made to the BT model such that ties can be included. A number of methods of accomplishing this have been suggested @bradtertiesfit.
These more general models often use a different parametrisation. Instead of estimating $alpha$ terms whose difference gives the odds, terms $p_i$ are estimated such that $sum_(i) p_(i) = 1$, and probabilities are calculated in different ways, shown below.
One method for generalisation proceeds by estimating a tie-chance parameter $p_0$, as well as team-strength parameters $p_1, ... , p_n$.
The chances of each outcome are then written as:
$
Pr(i "beats" j) &= (p_(i))/(p_(i) + p_(j) + p_(0)) \
Pr(i "ties" j) &= (p_(0))/(p_(i) + p_(j) + p_(0))
$
Another option (the Davidson model @bradleyties) treats the probability of teams $i,j$ tying as proportional to the geometric mean of the parameters estimated for each team:
$
Pr(i "beats" j) &= (p_(i))/(p_(i) + p_(j) + nu sqrt(p_(i)p_(j))) \
Pr(i "ties" j) &= (nu sqrt(p_(i)p_(j)))/(p_(i) + p_(j) + nu sqrt(p_(i)p_(j)))
$
With $nu$ representing a 'tendency towards ties'.
The Davidson model can be extended to include a multiplicative home advantage parameter @fulldavidson. For team $i$ playing at home, team $j$ away:
$
Pr(i "beats" j) &= (gamma p_(i))/(gamma p_(i) + p_(j) + nu sqrt(p_(i)p_(j))) \
Pr(i "ties" j) &= (nu sqrt(p_(i)p_(j)))/(gamma p_(i) + p_(j) + nu sqrt(p_(i)p_(j))) \
Pr(j "beats" i) &= (p_(j))/(gamma p_(i) + p_(j) + nu sqrt(p_(i)p_(j))) \
$
A number of R packages exist for fitting models like these. `VGAM::brat` and related functions can fit ties-allowed models of the first kind.
The problem with a ties-allowed model like this for our case is that the home advantage effect ought to then be accounted for, as including including all three match outcomes removes the home/away symmetry.
After searching for a while we came across the `bpcs` package. While quite laborious to get working, this package allows one to fit ties-allowed models with a home advantage factor, along the lines of the third model type listed.
In the table below we list estimated strength parameters for each team with 95% highest posterior density bounds, as well as the estimates for the home advantage correction $gamma$ and the tie-factor $nu$. All values are given in $log(...)$ form, as this transforms them onto the linear scale which is used for estimation.
#table(
columns:4,
[Parameter], [Mean], [2.5%], [97.5%],
[Wolves], [-0.600], [-2.070], [0.840],
[Leeds], [-1.830], [-3.390], [-0.320],
[South'ton], [-2.320], [-3.940], [-0.780],
[Not'ham], [-0.970], [-2.490], [0.470],
[Chelsea], [-0.780], [-2.260], [0.690],
[Man City], [2.860], [1.220], [4.520],
[Liverpool], [0.990], [-0.510], [2.510],
[Crystal P.], [-0.570], [-2.040], [0.920],
[Brighton], [0.600], [-0.900], [2.100],
[Fulham], [-0.390], [-1.860], [1.070],
[West Ham], [-1.000], [-2.490], [0.490],
[Newcastle], [1.620], [0.100], [3.140],
[Everton], [-0.430], [-2.000], [0.970],
[Arsenal], [2.090], [0.450], [3.630],
[Tottenham], [0.770], [-0.690], [2.260],
[Brentford], [0.580], [-0.850], [2.150],
[<NAME>.], [0.780], [-0.740], [2.270],
[Leicester], [-1.440], [-3.000], [0.080],
[<NAME>.], [1.440], [-0.050], [3.040],
[Bournemouth], [-1.200], [-2.720], [0.290],
[gm], [-3.760], [-4.750], [-2.800],
[nu], [0.080], [-0.130], [0.290]
)
As in the previous section the bounds on these values are quite wide, due to the number of matchups between any pair of teams being limited to 2.
The constant effect $ln(gamma)$ is quite strongly negative, indicating an advantage towards the home team.
Due to how we fit the model this reads more clearly as any "away-disadvantage" term, as will be shown momentarily.
The tie-parameter $ln(nu)$ is very close to zero, and the 95% bounds on it do include zero.
This indicates that tie chance $prop nu sqrt(p_i p_j)$ is mostly determined by the respective team strengths.
Taking a pair of teams as an example we can calculate win/draw/loss probabilities.
As before using Leicester City playing away vs Newcastle United, we find team strength values of $gamma p_("LC") = exp(-3.76)exp(-1.44) = 0.0054, p_("NU") = exp(1.62) = 5.05$ respectively.
Note that we multiply the away team win chance by $gamma$.
The tie term is $exp(0.08) sqrt( 0.237 times 5.05) = 1.18$, so the denominator in each case will be $0.0054 + 0.237 + 5.05= 6.24$
$
Pr("Leic win") &= 0.0054 / 6.24 = 0.00087\
Pr("Tie") &= 1.18 / 6.24 = 0.19\
Pr("N.U. win") &= 5.05 / 6.24 = 0.81\
$
Despite the possibly-unrealistic small chance of Leicester pulling through, this roughly matches the win chance for Newcastle we found in the previous section, 0.825.
/*#highlight([Could add a team ranking based on the scores here, maybe compare it to the team ranking based on last-season points.])*/
/* Should I add a team ranking here based on these results? Compare to points-based team ranking etc. */
#heading([Model Performance], numbering:none, outlined:false)
In this section we will test the forecasting accuracy of these models.
At the moment the models we've been looking at have been trained on the full 380 matches in the season, but for this section we will restrict this to the first 350 games, and test on the remaining 30.
/*#highlight([Should I instead select the testing games from uniformly throughout the season? Makes it less applicable in actual-life betting scenarios but will remove any bias due to time-dependence in match results])*/
/* Should I instead select the testing games from uniformly throughout the season? Makes it less applicable in actual-life betting scenarios but will remove any bias due to time-dependence in match results*/ This is of course a fairly small sample size for testing, but given the bounds on the parameter estimates are already very wide, there's likely a steep tradeoff between more testing precision and model accuracy.
We'll train both the regular BT model using `BTm` , as well as the constant-effect Davidson model using `bpc`.
The testing dataset includes 30 games, of which 13 were home wins, 5 were ties and 12 were away wins.
For the Bradley Terry model, we can tabulate the predicted vs actual results. Using a cutoff at $p = 0.5$:
#table(
columns:4,
[],table.cell([Actual], colspan: 3, align:center),
table.cell(rotate([Pred], -90deg), rowspan:3, align: horizon, inset: (x:2pt, y:5pt)),
[], [Home Win], [Not],
[Home Win], [3], [4],
[Not], [10], [13]
)
We can see that the model is very keen to predict good results for the away team. Why exactly this happens we aren't too confident. The sample size is naturally very small, both for training and testing, so biased/innaccurate parameters are a possibility, as is a biased sample. Perhaps a different choice of cutoff could improve results, though as far as we're aware there's no theoretical justification for doing this.
We can do the same for the three outcome model:
#table(
columns:5,
[], table.cell([Actual], colspan: 4, align:center),
table.cell(rotate([Pred], -90deg), rowspan:4, align: horizon, inset: (x:2pt, y:5pt)),
[], [Home Win], [Tie], [Away Win],
[Home Win], [6], [1], [5],
[Tie], [7], [4], [7],
[Away Win], [0], [0], [0]
)
As we can see, this model has the opposite behaviour. The low sample size makes it quite fraught to extrapolate from any results here, but the model seems fairly capable of predicting ties, assessing 4/5 correctly. Home wins are predicted either correctly or as ties, though the model has around even odds of choosing correctly.
Away wins are where the model seems to struggle most. No match was predicted as an away win, and the model barely prefers predicting actual away wins as ties.
In this case the culprit is likely the away-disadvantage constant $gamma$. As we saw just above when fitting the first Davidson model, the magnitude of $ln(gamma)$ is far higher than any of the other constants, hence the $gamma p_(j)$ terms in the numerator of away-team win chance are going to be overly small. \
Between the negative results in the logistic regression section and now here, we seem to be struggling to find a good model for the win and loss patterns in football. As mentioned in the ordered logistic regression section, some degree of this is likely due to to poor information content in our data, but the failure to find a good predictive model in this section might suggest finding a new approach entirely. \
Bradley-Terry based models with covariates included do exist and might be useful, depending on the choice of covariate. They would likely still run into the issue of sample size. If we wanted more useful results here, it might be wise to include data from previous leagues, perhaps weighted such that more recent matches have higher influence. |
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%2018_155%20-%20Differential%20Analysis%201/Assignments/Assignment%203.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 3", name: "<NAME>", doc)
#show: latex
#show: NumberingAfter
#show: thmrules
#let col(x, clr) = text(fill: clr)[$#x$]
#let pb() = {
pagebreak(weak: true)
}
#set page(numbering: "1")
#let bar(el) = $overline(#el)$
#set enum(numbering: "a)")
*Sources consulted* \
Classmates: . \
Texts: Class Notes.
= Question
== Statement
Let $Omega$ be a bounded open set in $RR^d$ with $C^infinity$-smooth boundary. Show that
$
Delta bb(1)_Omega = sum_(i = 1)^d diff_(x_i) dot nu_i d S
$
where $nu$ is the normal to $diff Omega$.
== Solution
Let $phi$ be any smooth test function, then we have
$
pair(Delta bb(1)_Omega, phi)
= sum_(i=1)^d pair(diff_i diff_i bb(1)_Omega, phi)
= - sum_(i=1)^d pair(diff_i bb(1)_Omega, diff_i phi)
= sum_(i=1)^d pair(bb(1)_Omega, diff_i diff_i phi)
= pair(bb(1)_Omega, Delta phi)
= integral_Omega Delta phi
$
But now we use divergence theorem to get that
$
integral_Omega Delta phi = integral_(diff Omega) (nu dot nabla phi) d S = sum integral_(diff Omega) nu_i diff_i phi d S = pair(sum_(i=1)^d diff_(x_i) dot nu_i d S, phi)
$
= Question
== Statement
Solve the system of equations in $D' (RR^n)$:
$
u dot x_i = 0, quad i = 1,...,n
$
== Solution
I claim that the only solution is $u = c dot delta_0$ for some constant $c$, we prove this by induction. Assume this is true for $d - 1$, then let $phi$ be a test function. Next fix $phi.alt$ to be a bump function on $RR$ with $phi.alt = 1$ on $[-1,1]$ and $phi.alt = 0$ on $[-2,2]^c$. We now define a new test function
$
psi (x) := phi(x_1,...,x_d) - phi.alt(x_d) phi(x_1,...,x_(d-1),0)
$
which namely satisfies $psi(x) = 0$ if $x_d = 0$. Now $psi(x) / x_d$ is clearly a smooth function everywhere away from $x_d = 0$ and the fact that $psi(x) = 0$ when $x_d = 0$ also gives us that $psi(x) / x_d$ is smooth at $x_d = 0$ so $psi(x) / x_d$ is also a test function.
We now have
$
pair(u, phi)
&= pair(u, psi) + pair(u, phi.alt(x_d) phi(x_1,...,x_(d-1), 0))
\ &= pair(u, x_d psi/x_d) + pair(u, phi.alt(x_d) phi(x_1,...,x_(d-1), 0))
\ &= pair(underbrace(u x_d, 0), psi/x_d) + pair(u, phi.alt(x_d) phi(x_1,...,x_(d-1), 0))
\ &= pair(u, phi.alt(x_d) phi(x_1,...,x_(d-1), 0)).
$
We now can define a map $g : C_c^infinity (RR^(d-1)) -> C_c^infinity (RR^d)$ by $g(phi)(x) = phi(x_1,...,x_(d-1)) phi.alt(x_d)$.
Now we can define a distribution $v$ in $D'(RR^(d-1))$ through $pair(v, f) = pair(u, g(f))$ and the calculations above should demonstrate that the behaviour of $u$ is entirely captured in that of $v$. But now clearly $v dot x_i = 0$ for all $i <= d - 1$ so by induction $v = c dot delta_0$, hence we have $u = c dot delta_0$ and so we are done. The base case was covered in class.
= Question
== Statement
Show that $x_+^a - (-x)_+^a -> "P.V" 1/x$ in $D'(RR)$ as $a -> -1 + 0i$.
== Solution
Let $phi$ be a test function and we recall from assignment 1 that we can rewrite
$
pair(x_+^a - (-x)_+^a, phi)
&= 1/(a+1) pair(diff_x (x_+^(a+1) - (-x)_+^(a+1)), phi)
\ &= -1/(a+1) integral_(0)^infinity t^(a+1) (phi'(t)- phi'(-t)) d t
\ &= -1/(a+1) integral_(0)^infinity exp((a+1)ln(t)) (phi'(t) - phi'(-t)) d t
\ &= -1/(a+1) integral_(0)^infinity (phi'(t) - phi'(-t)) d t
\ &- integral_(0)^infinity ln(t) (phi'(t) - phi'(-t)) d t
\ &- integral_(0)^infinity O(a+1) (phi'(t) - phi'(-t)) d t
$
now the first term is equal to $1/(a+1) (phi(0) - phi(0)) = 0$. The third term goes to $0$ as $a+1 -> 0$. The second term is thus the only one which survives the limit and we have
$
integral_(0)^infinity ln(t) (phi'(t) - phi'(-t)) d t
&= lim_(epsilon -> 0) integral_(epsilon)^infinity ln(t) (phi'(t) - phi'(-t)) d t
\ &= lim_(epsilon -> 0) integral_(epsilon)^infinity 1/t (-phi(t) + phi(-t)) d t = -pair("P.V" 1/x, phi)
$
which is precisely the desired result.
|
|
https://github.com/jonathan-iksjssen/jx-style | https://raw.githubusercontent.com/jonathan-iksjssen/jx-style/main/0.2.0/rp-example.typ | typst | #import "@jx/jx-style:0.2.0": *
#show: docu.with(
docutype: "paper",
rp-authors: (
(lastname: "Icśsen", firstname: "<NAME>"),
),
rp-title: "Applications of PINGAS in HoH SiS Foundation Repair",
rp-header: "Icśsen (2025)",
rp-subtitle: "They do doo in the foundation work.",
rp-school: "University of Medleshire",
rp-submittedTo: "cs188",
rp-subject: "Computing Fundamentals",
section: "BSIT-1L",
font: "<NAME>",
colsc: "sky",
flags: ("oldnum"),
date: datetime(year: 2036, month: 6, day: 17).display("[day padding:none] [month repr:short]. [year repr:full]")
)
= PINGAS
#lorem(50)
$ frac("Je m'en bats les couilles.",frac(#emoji.flag,twinfantasy))= sum^twinfantasy_#emoji.abacus 2 d d d d d $
#render-date(2024,9,14) |
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/utils/states.typ | typst | // touying slide counters
#let slide-counter = counter("touying-slide-counter")
#let last-slide-counter = counter("touying-last-slide-counter")
#let last-slide-number = locate(loc => last-slide-counter.final(loc).first())
#let touying-progress(callback) = locate(loc => {
let ratio = calc.min(1.0, slide-counter.at(loc).first() / last-slide-counter.final(loc).first())
callback(ratio)
})
// sections
#let sections-state = state("touying-sections-state", ((kind: "section", title: none, short-title: none, loc: none, count: 0, children: ()),))
#let _new-section(short-title: auto, id: auto, title) = locate(loc => {
sections-state.update(sections => {
sections.push((kind: "section", title: title, short-title: short-title, loc: loc, count: 0, children: ()))
sections
})
})
#let _new-subsection(short-title: auto, id: auto, title) = locate(loc => {
sections-state.update(sections => {
let last-section = sections.pop()
last-section.children.push((kind: "subsection", title: title, short-title: short-title, loc: loc, count: 0, children: ()))
sections.push(last-section)
sections
})
})
#let _sections-step(repetitions) = locate(loc => {
sections-state.update(sections => {
let last-section = sections.pop()
if last-section.children.len() == 0 or last-section.children.last().kind == "slide" {
last-section.children.push((kind: "slide", loc: loc, count: repetitions))
last-section.count += 1
sections.push(last-section)
} else {
// update for subsection
let last-subsection = last-section.children.pop()
last-subsection.children.push((kind: "slide", loc: loc, count: repetitions))
last-subsection.count += 1
last-section.count += 1
last-section.children.push(last-subsection)
sections.push(last-section)
}
sections
}
)})
#let touying-final-sections(callback) = locate(loc => {
callback(sections-state.final(loc))
})
#let touying-outline(enum-args: (:), padding: 0pt) = touying-final-sections(sections => {
pad(padding, enum(
..enum-args,
..sections.filter(section => section.loc != none)
.map(section => [#link(section.loc, section.title)<touying-link>] + if section.children.filter(it => it.kind != "slide").len() > 0 {
let subsections = section.children.filter(it => it.kind != "slide")
enum(
..enum-args,
..subsections.map(subsection => [#link(subsection.loc, subsection.title)<touying-link>])
)
})
))
})
#let current-section-title = locate(loc => {
let sections = sections-state.at(loc)
sections.last().title
})
#let touying-progress-with-sections(callback) = locate(loc => {
callback((
current-sections: sections-state.at(loc),
final-sections: sections-state.final(loc),
current-slide-number: slide-counter.at(loc).first(),
last-slide-number: last-slide-counter.final(loc).first(),
))
}) |
|
https://github.com/zenor0/simple-neat-typst-cv | https://raw.githubusercontent.com/zenor0/simple-neat-typst-cv/master/cv/utils/packages.typ | typst | MIT License | // 统一在此文件导入包,方便后续更新
#import "@preview/a2c-nums:0.0.1": int-to-cn-num
#import "@preview/cuti:0.2.1": show-cn-fakebold, fakebold
#import "@preview/sourcerer:0.2.1": code
#import "@preview/lovelace:0.2.0": *
#import "@preview/gentle-clues:0.8.0": *
#import "@preview/codly:0.2.0": * |
https://github.com/AnsgarLichter/hka-thesis-template | https://raw.githubusercontent.com/AnsgarLichter/hka-thesis-template/main/supplementary/statutoryDeclaration.typ | typst | #import "/metadata.typ": *
#heading(outlined: false, numbering: none, "Declaration of Originality")
I declare that I have composed the #lower(degree)'s thesis myself and without use of any other than the cited sources and aids. Sentences or parts of sentences quoted literally are marked as such; other references with regard to the statement and scope are indicated by full details of the publications concerned. The thesis in the same or similar form has not been submitted to any examination body and has not been published. This thesis was not yet, even in part, used in another examination or as a course performance. Furthermore I declare that the submitted written (bound) copies of the #lower(degree)'s thesis and the version submitted in digital format are consistent with each other in contents.
#pad(
top: 5em,
table(
columns: (1fr, 1fr),
gutter: 1em,
align: center,
stroke: none,
inset: (
x: 20pt
),
line(length: 100%), line(length: 100%),
[(Place, Date)], author,
)
) |
|
https://github.com/nath-roset/suiviProjetHekzamGUI | https://raw.githubusercontent.com/nath-roset/suiviProjetHekzamGUI/master/typ%20sources/definitions.typ | typst | Apache License 2.0 | = Definitions :
(*HYPOTHÈSES DE DÉBUT DE PROJET*)
- *cadrage* : en pourcentage, métrique qui mesure la qualité de la numérisation par page
- *fichier source* : fichier texte suivant la #link("https://typst.app/docs/reference")[spécification] du langage Typst , ideally with a *.typ* extension
- *projet* : Un projet dans ce contexte est un *dossier* (?) contenant AU MOINS un fichier source et AU MOINS un fichier de configuration pour le projet (?) au format ??? (TOML ? JSON ?)
- *sujet* : fichier pdf obtenu en compilant un fichier source avec Typst, peut comprendre plusieurs pages
- *programme* : <NAME> complet#link("https://github.com/hekzam")[(GUI + parser + generator)], supposé fonctionnel
- *page*: image extraite d'un fichier pdf; scan d'une page associé à une copie d'un sujet
- *copie*: ensemble de feuilles regroupées, l'ensemble formant une copie d'examen associée à un étudiant |
https://github.com/mcanouil/generate-quarto-invoices | https://raw.githubusercontent.com/mcanouil/generate-quarto-invoices/main/README.md | markdown | MIT License | # Generate Quarto Invoices
This is a simple script to generate biweekly invoices using Quarto/Typst.
It first generates YAML files for each invoice, then generates the invoices from one single Quarto document.
## Usage
```bash
generate-invoices.py \
--name="Consulting" \
--task="A very important job" \
--details="A description of the tasks" \
--amount="1,234.56" \
--recipient="Company-Inc" \
--first="2024-01-15"\
--last="2024-01-31" \
--template="template.qmd"
```
Under the hood, this will generate a YAML file for each invoice, then generate the invoices from one single Quarto document using the `quarto render` command.
```bash
quarto render template.qmd --metadata-file input/202401-001.yml --output output/INVOICE-N202401-001-Company-Inc.pdf
```
## Requirements
- Python 3.12.1: <https://www.python.org/>
- Quarto 1.4.534 <https://quarto.org>
- Invoice (Typst) 1.1.1: <https://github.com/mcanouil/quarto-invoice>
|
https://github.com/Quaternijkon/notebook | https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.menu/.menu-数据结构/menu-哈希表.typ | typst | == 哈希表<哈希表>
#import "../../../../lib.typ":*
#xquotation(
first: [
], second: [
]
)
#pagebreak()
#include "../../.chapter-数据结构/哈希表/同构字符串.typ"
#pagebreak()
#include "../../.chapter-数据结构/哈希表/两数之和.typ" |
|
https://github.com/MLAkainu/Network-Comuter-Report | https://raw.githubusercontent.com/MLAkainu/Network-Comuter-Report/main/components/footer.typ | typst | Apache License 2.0 | #import "../metadata.typ": meta
#locate(loc => {
set text(font: "Iosevka NF", size: 10pt)
show: block.with(
stroke: (top: 1pt),
inset: (top: 1em)
)
// skip first page footer
if loc.page() == 1 {
return
}
let current-page = counter(page).at(loc).at(0)
let total-pages = counter(page).final(loc).at(0)
let semester-of-year = calc.rem(meta.semester, 10)
// change this when you come from the 2100s
let year-from = calc.round(meta.semester / 10) + 2000
let year-to = year-from + 1
stack(
dir: ltr,
[Báo cáo môn #meta.course-name - Học kỳ #semester-of-year năm học #year-from - #year-to],
1fr,
[Trang #current-page/#total-pages]
)
}) |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/spread-03.typ | typst | Other | // Test spreading array and dictionary.
#{
let more = (3, -3, 6, 10)
test(calc.min(1, 2, ..more), -3)
test(calc.max(..more, 9), 10)
test(calc.max(..more, 11), 11)
}
#{
let more = (c: 3, d: 4)
let tostr(..args) = repr(args)
test(tostr(a: 1, ..more, b: 2), "(a: 1, c: 3, d: 4, b: 2)")
}
|
https://github.com/monaqa/typscrap.nvim | https://raw.githubusercontent.com/monaqa/typscrap.nvim/master/class/layout.typ | typst | #import "component.typ": href, code, scrap, colors
#import "states.typ"
#import "layout/telomere.typ"
#let document(
show_toc: false,
link_converters: href.default_link_converters,
show_telomere: true,
confidential: none,
body
) = {
// text & paragraph
set text(font: "IBM Plex Sans JP", size: 10.5pt)
set par(justify: true, leading: 0.85em)
// inline elements
show emph: set text(font: ("Noto Serif", "IBM Plex Sans JP Medm"), fill: colors.fg.r1)
show link: href.pretty_link.with(link_converters: link_converters)
// heading
let heading_box(
it,
full: false,
y_pad: 0pt,
inset_bottom: 0pt,
strk: none,
weight: 600,
size: 1em,
) = {
let font_name = if weight == 500 {
"IBM Plex Sans JP Medm"
} else if weight == 600 {
"IBM Plex Sans JP Smbld"
} else if weight == 450 {
"IBM Plex Sans JP Text"
} else {
"IBM Plex Sans JP"
}
pad(y: y_pad, {
block(
breakable: false,
inset: (bottom: inset_bottom),
stroke: (bottom: if full {none} else {strk}),
text(weight: weight, size: size, font: font_name, it),
)
if full and strk != none {
place(bottom, line(length: 100%, stroke: strk))
}
}
)
}
show heading.where(level: 1): (it) => {
[#metadata((date: none)) <meta-tick>]
pagebreak(weak: true)
heading_box(it, full: true, y_pad: 16pt, weight: 200, size: 22pt)
}
show heading.where(level: 2): heading_box.with(
full: true,
y_pad: 3pt,
inset_bottom: 5pt,
strk: 0.8pt + black,
weight: 300,
size: 18pt,
)
show heading.where(level: 3): heading_box.with(
y_pad: 3pt,
inset_bottom: 5pt,
strk: 1.5pt + black,
size: 14pt,
)
show heading.where(level: 4): heading_box.with(y_pad: 2pt, inset_bottom: 3pt, size: 12pt, strk: (thickness: 1.2pt, dash: (2pt, 1pt)), weight: 500)
show heading.where(level: 5): heading_box.with(inset_bottom: 4pt, weight: 700)
show heading.where(level: 6): heading_box.with(inset_bottom: 3pt, strk: 0.5pt, weight: 300)
set outline(depth: 3, indent: 1em, title: [目次])
show outline: it => {
show heading.where(level: 1): _ => heading_box(y_pad: 5pt)[目次]
it
}
// list & enum & term
set list(
indent: 0.8em,
marker: place(center, dy: 0.25em)[#circle(radius: 1.5pt, fill: black)],
)
// raw
show raw: set text(font: (
"CommitMono-height105",
"Hack Nerd Font",
"Noto Sans Mono CJK JP",
"IBM Plex Sans JP",
))
// たぶんデフォルトで 0.8em みたいな何かがかかってるので、1.2 倍して 0.96em っぽくしとく
show raw.where(block: false): set text(size: 1.2em)
show raw.where(block: false): it => box(
outset: (x: 0.8pt, y: 3pt),
radius: 1.5pt,
fill: luma(90%),
it
)
show raw.where(block: true): set par(leading: 0.6em, justify: false)
show raw.where(block: true): (it) => {
if it.lang == "sh" {
code.console_block(it)
} else {
code.normal_raw_block(it)
}
}
// page
set page(
header: context {
let slug = states.slug.final()
place(left + bottom, scrap(slug, href: false))
if confidential != none {
let confidential_mark = {
let color = red.darken(20%)
box(
stroke: color + 2pt,
inset: (x: 3pt, y: 4pt),
align(center, text(fill: color, size: 9pt)[*#confidential*])
)
}
place(right + bottom, confidential_mark)
}
},
footer: locate((loc) => {
let align_dir = left
if calc.odd(counter(page).at(loc).at(0)) {
align_dir = right
}
set align(align_dir)
set text(8pt)
counter(page).display("1")
}),
)
set quote(block: true)
show quote.where(block: true): set block(spacing: 1.2em)
show quote.where(block: true): block.with(
stroke: (left: 2pt + gray),
outset: (left: -4pt, y: 5pt),
above: 1.2em,
below: 1.5em,
)
if show_toc {
outline(indent: 1em)
pagebreak()
}
body
[#metadata((date: none)) <meta-tick>]
}
|
Subsets and Splits