repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/lib.typ | typst | Apache License 2.0 | /// Create a `codepoint` object.
///
/// You can convert a to content `codepoint` using its `show` field:
/// ```example
/// #codepoint("¤").show
/// ```
#let codepoint(code) = {
if type(code) != int {
code = str.to-unicode(code)
}
import "ucd/index.typ"
let data = index.get-data(code)
let (block, codepoint-data) = data
let it = (
code: code,
name: codepoint-data.at(0, default: none),
general-category: codepoint-data.at(1, default: none),
canonical-combining-class: codepoint-data.at(2, default: none),
block: block,
)
(
..it,
"show": {
let str-code = upper(str(it.code, base: 16))
while str-code.len() < 4 {
str-code = "0" + str-code
}
raw("U+" + str-code)
sym.space.nobreak
if it.name == none {
"<unused>"
} else if it.name.starts-with("<") {
it.name
} else {
// The character appears bigger without increasing line height.
text(size: 1.2em, top-edge: "x-height", str.from-unicode(it.code))
sym.space
smallcaps(lower(it.name))
}
},
)
}
|
https://github.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024 | https://raw.githubusercontent.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024/master/expt02/main.typ | typst | #set text(lang: "zh", cjk-latin-spacing: auto, font: "Noto Serif CJK SC")
#set page(numbering: "1", margin: (left: 1.4cm, right: 1.9cm))
#show figure.caption: set text(font: "Zhuque Fangsong (technical preview)")
#show "。": "."
#show heading: set text(font: "Noto Sans CJK SC", size: 1.15em)
#import "../expt01/blockcode.typ": bc
#show raw.where(block: true): bc
#show raw.where(): set text(size: 1.15em, font: "JetBrains Mono")
#let FT = $cal(F)$
#let IFT = $FT^(-1)$
= 数字图像处理 第二次实验
== 实验 1(P185例4.23)
使用陷波滤波减少莫尔(波纹)模式。@img1 是来自扫描报纸的图像,它显示了突出的莫尔模式,设计一个 Butterworth 陷波带阻滤波器消除图像中的莫尔条纹。
#figure(
caption: "莫尔模式的取样过的报纸图像",
image("Images/1.png"),
)<img1>
Butterworth 带阻滤波器的公式为
$ H(u, v) = 1 / (1 + (display((D(u, v)W) / (D^2(u, v) - D_0^2)))^(2 n)) $
=== 频率域滤波的基本步骤
1. 已知一幅大小为 $M times N$ 的输入图像 $f(x,y)$,取填充零后的尺寸 $P >= 2M - 1$ 和 $ >= 2N - 1$,一般 $P=2M$ 和 $Q=2N$。
2. 使用零填充、镜像填充或复制填充,形成大小为 $P times Q$ 的填充后的图像 $f_p (x,y)$。
3. 将 $f(x,y)$ 乘以 $(-1)^{x+y}$,使傅里叶变换位于 $P times Q$ 大小的频率矩形的中心。
4. 计算步骤3得到的图像的 DFT,即 $F(u,v)$。
5. 构建一个实对称滤波器传递函数 $H(u,v)$,其大小为 $P times Q$,中心在 $(P/2, Q/2)$ 处。
6. 采用对应像素相乘得到 $G(u,v) = H(u,v)F(u,v)$,即 $G(i,k) = H(i,k) F(i,k)$,$i=0,1,2,...,M-1$ 和 $k=0,1,2,...,N-1$。
7. 计算 $G(u,v)$ 的 IDFT 得到滤波后的图像(大小为 $P times Q$)
$ g_p (x,y) = { Re [IFT [G(u,v)]] }(-1)^(x+y). $
8. 最后,从 $g_p (x,y)$ 的左上象限提取一个大小为 $M times N$ 的区域,得到与输入图像大小相同的滤波后的结果 $g(x,y)$。
=== 图像预处理
在代码中,我们首先获取输入图像 `img` 的宽度 `img.width` 和高度 `img.height`,分别对应 $M$ 和 $N$。由于所用的 FFT 实现仅支持 2 的幂次大小,通过 `min2power` 函数计算出大于等于图像尺寸且最接近 2 的幂的数的2倍,作为填充后的图像尺寸 `dims[0]` 和 `dims[1]`,分别对应 $P$ 和 $Q$。
```javascript
dims[0] = min2power(img.width)[1];
dims[1] = min2power(img.height)[1];
```
代码中提供了两种填充方式:黑色填充和原图重复填充。
/ *黑色填充*: 通过设置 `ctxs[ai].fillStyle = 'black'` 并调用 `ctxs[ai].fillRect(0, 0, canvases[ai].width, canvases[ai].height)`,将四个画布 `canvases[ai]` 全部填充为黑色。
/ *原图重复填充*: 通过多次调用 `ctxs[0].drawImage`,将原图 `img` 重复绘制到画布 `canvases[0]` 上,覆盖整个画布区域。
```javascript
if (useBlack) {
ctxs[ai].fillStyle = 'black';
ctxs[ai].fillRect(0, 0, canvases[ai].width, canvases[ai].height);
} else {
ctxs[0].drawImage(img, img.width, 0, img.width, img.height);
ctxs[0].drawImage(img, 0, img.height, img.width, img.height);
ctxs[0].drawImage(img, img.width, img.height, img.width, img.height);
}
```
=== 傅里叶变换和中心化
在实验中,我们没有使用书中的方法,而是先进行傅里叶变换,再在频域中心化。
```javascript
function FFT2D(imageData) {
const width = imageData.width;
const height = imageData.height;
const data = imageData.data;
// 1. 将图像数据转换为复数形式
const complexData = [];
for (let i = 0; i < data.length; i += 4) {
complexData.push(new Complex(data[i], 0)); // 只取红色通道,其他通道类似
}
// 2. 对每一行进行一维 FFT
const rowTransforms = [];
for (let y = 0; y < height; y++) {
const row = complexData.slice(y * width, (y + 1) * width);
const rowTransform = [];
FFT(row, rowTransform);
rowTransforms.push(rowTransform);
}
// 3. 对每一列进行一维 FFT
const transform = [];
for (let x = 0; x < width; x++) {
const col = rowTransforms.map(row => row[x]);
const colTransform = [];
FFT(col, colTransform);
transform.push(...colTransform); // 展开列变换结果
}
// 4. 中心化频谱
const shiftedTransform = Fourier.shift(transform, [height, width]);
return shiftedTransform;
}
```
1. *图像数据转换*:首先,我们将图像数据(通常是 RGBA 格式)转换为复数形式,以便进行傅里叶变换。这里为了简化,只取了红色通道,其他通道处理方式类似。
2. *逐行一维 FFT*:接着,我们对图像的每一行进行一维快速傅里叶变换(FFT)。`FFT` 函数实现了基-2 快速傅里叶变换算法,将时域信号转换为频域表示。
3. *逐列一维 FFT*:然后,对每一列进行一维 FFT。这里我们遍历每一列,将各行的对应位置的复数取出,组成一个新的数组,再对其进行 FFT。
4. *频谱中心化*:最后,我们使用 `Fourier.shift` 函数(即 `shiftFFT`)将频谱进行平移,使得零频分量位于中心。中心化后的频谱图像更易于理解和分析。原始频谱中零频分量位于左上角,平移后低低频分量位于中心,高频分量向外辐射,符合我们对频率分布的直观认知。
```js
function halfShiftFFT(transform, dims) {
var ret = [];
var N = dims[1];
var M = dims[0];
// 处理上半部分
for (var n = 0, vOff = N/2; n < N; n++) {
// 遍历每一列的上半部分
for (var m = 0; m < M/2; m++) {
// 计算当前元素的索引
var idx = vOff*dims[0] + m;
// 将变换后的结果添加到结果数组中
ret.push(transform[idx]);
}
// 更新偏移量
vOff += vOff >= N/2 ? -N/2 : (N/2)+1;
}
// 处理下半部分
for (var n = 0, vOff = N/2; n < N; n++) {
// 遍历每一列的下半部分
for (var m = M/2; m < M; m++) {
// 计算当前元素的索引
var idx = vOff*dims[0] + m;
// 将变换后的结果添加到结果数组中
ret.push(transform[idx]);
}
// 更新偏移量
vOff += vOff >= N/2 ? -N/2 : (N/2)+1;
}
// 返回结果数组
return ret;
}
```
具体实现上,`shiftFFT` 先通过 `halfShiftFFT` 函数将每行频谱左右两半交换,使零频分量移到行中。再通过 `flipRightHalf` 函数将图像右半部分翻转,使零频分量移到整个图像中心。整个过程是两次 `halfShiftFFT` 调用,中间夹杂一次 `flipRightHalf`,确保零频分量最终位于正中。
=== 施加滤波器
代码中通过 `drawCanvas1` 将频谱画在了界面上。首先遍历频域数据,找到其中的最大振幅 `maxMagnitude`,然后遍历每个像素,计算最大振幅的对数 `logOfMaxMag`,其中 `cc` 是一个用于调整对比度的常数。
因此,本实验中可通过在频谱上交互式操作施加 Butterworth 陷波带阻滤波器。鼠标悬浮在频谱上可以看到对应位置的坐标。点击对应位置可设置下方输入框中的 $(u_0, v_0)$。设置 $D_0$ 后点击“施加滤波器”按钮可以应用滤波器。此时可以看到在图像上对应位置由亮变暗。根据卷积运算的性质,可多次施加不同的滤波器。
界面和最终的滤波器公式 $H_"NR"$ 如@step2 所示。
#figure(caption: "施加1次滤波器后,正在对称位置施加第二次滤波器", image("step-2.svg", width: 73%))<step2>
每次施加滤波器,我们都创建了一个 $P times Q$ 的滤波器,为一个值都是 $0" ~ " 1$ 的双精度浮点数的二维数组,最后与图片上的每一个像素点乘。滤波器的实现如下:
```js
function mask(data, dims, u0, v0, D0=9, n=2) {
var M = dims[0];
var N = dims[1];
var halfM = M / 2;
var halfN = N / 2;
for (var u = 0; u < M; u++) {
for (var v = 0; v < N; v++) {
var idx = u * N + v;
var Dminus = Math.sqrt(Math.pow(u - halfN - u0, 2) + Math.pow(v - halfM - v0, 2))
var Dplus = Math.sqrt(Math.pow(u - halfN + u0, 2) + Math.pow(v - halfM + v0, 2))
var h = 1 / (1 + Math.pow(D0 / (Dminus + 1e-6), 2*n)) * 1 / (1 + Math.pow(D0 / (Dplus + 1e-6), 2*n));
data[idx] = data[idx].times(h);
}
}
}
```
#figure(caption: "施加了8次陷波带阻滤波器后的频谱", image("8.png", width: 61%))<f8次>
分析频谱中亮点,最终施加了8次陷波带阻滤波器,如@f8次 所示。
其 $(u_0, v_0)$ 分别在 $(81, plus.minus 87), (minus 92, plus.minus 78), (82, plus.minus 174), (minus 92, plus.minus 165) $ 附近,呈对称分布。
=== 傅里叶反变换
#figure(caption: "最终结果", image("result-1.png"))<res1>
#let chess = figure(caption: "重复填充的频谱", image("chess-pad.png", width: 47%))
由于要展示原理,所以实验并没有做最后取坐上角图片进行裁剪。
== 实验 2(P186例4.24)
#figure(
caption: "近似周期性干扰的土星环图像,图像大小为674×674像素",
image("Images/2.png", width: 52%),
)<img2>
使用陷波滤波增强恶化的卡西尼土星图像。@img2 显示了部分环绕土星的土星环的图像。太空船第一次进入该行星的轨道时由“卡西尼”首次拍摄了这幅图像。垂直的正弦模式是在对图像数字化之前由叠加到摄影机视频信号上的AC信号造成的。这是一个想不到的问题,它污染了来自某些任务的图像。设计一种陷波带阻滤波器,消除干扰信号。
使用与实验 1 中相似的办法,仅如@img2-3 所示施加 4 个滤波器便可取得较好的效果。
#figure(
caption: "处理后的频谱",
image("2/png (3).png", width: 61%),
)<img2-3>
#figure(
caption: "结果和 diff",
stack(
dir: ltr,
spacing: 1em,
image("2/png (4).png", width: 47%),
image("2/png (5).png", width: 47%),
)
)<img2-4>
== 实验总结
=== 实验 2 的其他方法
书中提到,由于干扰信号是 AC 信号,为周期的垂直噪声,因此可通过@r2 所示的一个垂直限波带阻函数隔离纵轴上的频率。填写宽度、v span 值可设置其宽度和中心区域跳过的范围。
#figure(
caption: "垂直限波带阻函数处理后的频谱",
image("2/r3.png", width: 61%),
)<r2>
#figure(
caption: "结果和 diff",
stack(
dir: ltr,
spacing: 1em,
image("2/r2.png", width: 47%),
image("2/rdiff.png", width: 47%),
)
)<img2-4>
滤波器实现如下:
```js
function mask2(data, dims, u0=-1, w=4, vspan=20) {
var M = dims[0];
var N = dims[1];
var halfM = M / 2;
var halfN = N / 2;
u0 += halfM;
w = parseInt((w / 2).toString());
for (var u = u0 - w; u <= u0 + w; u++) {
let idxBase = u * N;
for (var v = 0; v < halfN - vspan; v++) {
data[idxBase + v] = new Fourier.Complex(0, 0);
}
for (var v = halfN + vspan; v < N; v++) {
data[idxBase + v] = new Fourier.Complex(0, 0);
}
}
}
```
#stack(
dir: ltr,
spacing: 3%,
box(width: 50%)[
=== 图像填充
用零填充图像会增加其大小,但不会改变其灰度级内容,导致填充后图像的平均灰度级低于原始图像,频谱中的 $F(0,0)$ 小于原始图像中的 $F(0,0)$。图像整体对比度较低。同时,用 0 填充图像会在原始图像的边界处引入明显的间断。这个过程会引入强烈的水平和垂直边缘,图像在这些边缘处突然结束,然后继续为 0 值。频谱中,这些急剧的过渡对应于沿水平轴和垂直轴的亮的线。
使用重复图像填充在重复次数较多时会创造出更多的规律性频率分布,效果不如零填充好。
], chess
)
#"\n"
== 附:实验代码使用方式
解压后,用浏览器打开 `index.html` 即可。界面如下:
|
|
https://github.com/barddust/Kuafu | https://raw.githubusercontent.com/barddust/Kuafu/main/src/Meta/feynman.typ | typst | = 费曼学习法
== 什么是费曼学习法
费曼学习法(Feynman's Technique),简而言之:*通过输出倒逼输入*。为了学习,把学习任务当作一个教学任务,即不是为了学会这个知识,而是为了把这个知识教会别人。将学习者的身份,转化为教学者的身份。
之前我确实存在一个误区,一个看起来厉害的老师,至少会说一些让人听不懂的话。而费曼学习法要求教师必须做到把一个完全的新手教会,如此才能说明该老师的知识能力和教学水平。
尤其在我做了老师之后,教了一遍学生,自己对这个知识点的理解更加深入,同时也会在上课过程中自己发现或学生提出一些问题,指出知识编排等内容的不足,然后重新去优化教学过程,最终实现教学相长。
== 为什么需要费曼学习法
- 自己制定教学计划,区分重难点,即何处需要慢慢推理,何处只需轻轻略过;避免传统课堂上与老师步调不一致的情况;
- 要教会别人,则需要自己对这个知识的掌握程度足够深入,为了达到这一点,学习者会去广纳输入;避免传统课堂上片面的知识输入,没有全局或者单元的学习;
- 为了更好地输入,所学的知识必须是体系化的,如此便能系统而全面的理解和掌握所需的知识
== 费曼学习法如何操作
=== 自我学习
输入的过程当然时必须的,主动学习的过程肯定时构建知识和教学的基础。结合相关的学习方法和笔记方法,形成第一版的讲义,或者是笔记。
=== 编写讲义
在第一篇笔记出现之后,就着手编写讲义。编写讲义的核心:*简单*,它体现在两个方面。
第一,使用的语言足够简单,且自己思考和寻找恰当的*例子和比喻*。同时更多的以图和表的形式,即所谓的可视化的方式,将知识内容进行呈现。
第二,使用全局或大单元编写。讲义编写时,不应片面地,这个章节就写这个章节的内容,需要进行系统而全面的整合,因此前文就可以提及或预告后文。如果发现当前知识还需要用到后面知识补充,或者当前笔记可以对之前的讲义进行补充,则应毫不犹豫地回过头去重写和完善当初的讲义,以达到动态更新的目的。
== 参考
+ Maki 关于费曼学习法的讲座:#link("https://www.bilibili.com/video/BV1uD4y1r7hZ/")[第12讲 费曼学习法\_哔哩哔哩\_bilibili]
+ #link("https://sspai.com/post/61411")[《别逗了,费曼先生!》以及费曼学习法 - 少数派]
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/weave/0.2.0/tests/tests.typ | typst | Apache License 2.0 | #import "../lib.typ": *
#pipe(
5,
(
x => x + 1,
x => x + 2,
x => assert(x == 8),
),
)
#compose(
"y",
(
c => assert(c == "xyz"),
c => c + "z",
c => "x" + c,
),
)
#let pipeline = pipe_.with((
c => c + "c",
c => "a" + c,
))
#assert(pipeline("b") == "abc")
#let composed = compose_.with((
c => "a" + c,
c => c + "c",
))
#assert(composed("b") == "abc")
#assert(
compose_((
emph,
strong,
underline,
strike,
))[This is a very long content with a lot of words]
==
emph(
strong(
underline(
strike[This is a very long content with a lot of words]
)
)
)
)
|
https://github.com/Fr4nk1inCs/typst-homework | https://raw.githubusercontent.com/Fr4nk1inCs/typst-homework/master/complicated/homework.typ | typst | MIT License | #let homework(course: "课程作业", number: int(0), name: "姓名", id: "PB2XXXXXXX",
code_with_line_number: true, body) = {
// Set the document's basic properties.
let author = name + " " + id
let title = course + " " + str(number)
set document(author: (author, ), title: title)
set page(
numbering: "1",
number-align: center,
// Running header.
header-ascent: 14pt,
header: locate(loc => {
let i = counter(page).at(loc).first()
if i == 1 { return }
set text(size: 8pt)
grid(
columns: (50%, 50%),
align(left, title),
align(right, author),
)
}),
)
set text(font: "Source Han Serif SC", lang: "zh")
show math.equation: set text(font: "New Computer Modern Math", weight: 400)
// Set paragraph spacing.
show par: set block(above: 1.2em, below: 1.2em)
set par(leading: 0.75em)
// Title row.
align(center)[
#block(text(weight: 700, 1.75em, title))
#v(0.25em)
#author
#v(0.25em)
]
// Main body.
set par(justify: true)
// Code
show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
show raw.where(block: true): block.with(
width: 100%,
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
// Code block line numbers
show raw.where(block: true): it => {
if not code_with_line_number { return it }
let lines = it.text.split("\n")
let length = lines.len()
let i = 0
let left_str = while i < length {
i = i + 1
str(i) + "\n"
}
grid(
columns: (auto, 1fr),
align(
right,
block(
inset: (
top: 10pt,
bottom: 10pt,
left: 0pt,
right: 5pt
),
left_str
)
),
align(left, it),
)
}
body
}
#let question_name = "题"
#let answer_name = "解: "
#let question(number, problem, answer) = {
rect(width: 100%, inset: 10pt, radius: 4pt)[
#strong(question_name + " " + str(number) + ".")
#problem
]
[#strong(answer_name) #answer]
}
|
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/biology/lec4.typ | typst | #import "template.typ": *
#show: template.with(
title: "Lecture 4",
subtitle: "7.016"
)
= Why Learn About Proteins?
There are a couple valuable aspects of learning protein structures:
- We can learn about the function
- Develop drugs
- Understand how mutations impact the protein
- Synthetic Proteins
#define(
title: "Residue"
)[
In the context of a protein, a residue refers to a singular unit in a polymer, such as the amino.
]
= Reactions
The transition state of a reaction is the peak at the top when the reaction "happens". If free energy is lost, then we consider it a spontaneous (exergonic) reaction. The opposite side is endergonic (non-spontaneous) reactions.
The activation energy is the difference between the starting energy and the transition state ($E_a$). Having a catalyst does not change the $Delta G$, but it decreases the activation energy.
= Enzymes
Most biological catalysts are proteins called enzymes.
To control the pace at which enzymes react, *inhibitors* will control the way in which substrates bind to the enzyme.
/ Reversible: A temporarily blocker on the enzyme that can be let go later.
/ Irreversible: A permanent blocker - a new one must be acquired to bind to a substrate.
/ Allosteric: Doesn't bind directly to the site, alters the enzymes ability and functionality to interact with the substrates.
|
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/num/output-exponent-marker/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": num, metro-setup
#set page(width: auto, height: auto)
#num(output-exponent-marker: "e", e: 2)[1]
#num(output-exponent-marker: "E", e: 2)[1] |
https://github.com/rabotaem-incorporated/calculus-notes-2course | https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/04-parametric-and-curves/03-euler-integrals.typ | typst | #import "../../utils/core.typ": *
== Эйлеровы интегралы
#def(label: "def-euler-integrals")[
_Эйлеровым интегралом первого рода_, или _Гамма-функцией_, называется
$
Gamma(p) = integral_0^(+oo) x^(p-1) e^(-x) dif x,
space p > 0
$
_Эйлеровым интегралом второго рода_, или _Бета-функцией_, называется
$
Beta(p, q) = integral_0^1 x^(p-1) (1-x)^(q - 1) dif x,
space p, q > 0
$
]
#pr(label: "euler-integrals-converge")[
Интегралы сходятся.
]
#proof[
У $Gamma$-функции есть две особенности: в нуле, и на $+oo$.
- В нуле: $x^(p-1)e^(-x) tilde x^(p-1)$ - сходится т. к. $p - 1 > -1$
- На бесконечности: с некоторого места, можно подпереть интеграл $x^(p - 1) e^(-x/2)$, а $x^(p-1)e^(-x/2) --> 0$.
У $Beta$-функции тоже две особенности: в нуле и в единице.
- В нуле: $x^(p-1)(1-x)^(q-1) tilde x^(p - 1)$
- В единице: $x^(p-1)(1-x)^(q-1) tilde (1-x)^(q - 1)$
]
#props(name: [$Gamma$-функции], label: "gamma-props")[
+ #sublabel("plus-1")
$Gamma(p + 1) = p Gamma(p)$
+ #sublabel("factorial")
$Gamma(n) = (n-1)!$
+ #sublabel("1/2")
$Gamma(1/2) = sqrt(pi)$
+ #sublabel("plus-1/2")
$Gamma(n + 1/2) = (2n-1)!!/2^n sqrt(pi)$
+ #sublabel("inf-continious")
#sublabel("derivative")
$Gamma(p) in C^(oo)(RR)$, причем $ Gamma^((n))(p) = integral_0^(+oo) x^(p-1) ln^n (x) e^(-x) dif x. $
+ #sublabel("convex")
$Gamma(p)$ строго выпукла
+ #sublabel("limits")
$Gamma(p) -->_(p->+oo) +oo$ и $Gamma(p) tilde_(p->0) 1/p$
+ #sublabel("growth-speed")
При $p --> +oo$,
$ Gamma(p) tilde sqrt((2pi)/p) e^(-p) p^(p) $
]
#proof[
+ $
Gamma(p + 1) =^rf("def-euler-integrals")
integral_0^(+oo) x^p e^(-x) dif x =
-x^p e^(-x) |_(x=0)^(x=+oo) + integral_0^(+oo) p x^(p-1) e^(-x) =^rf("def-euler-integrals")
p Gamma(p).
$
+ $
Gamma(1) =^rf("def-euler-integrals")
integral_0^(+oo) e^(-x) dif x = 1.
$
+ $
Gamma(1/2) =^rf("def-euler-integrals")
integral_0^(+oo) x^(-1/2) e^(-x) dif x
=^(y = sqrt(x)) 2 integral_0^ (+oo) e^(-y^2) dif y
= 2 dot 1/2 integral_(-oo)^(+oo) e^(-y^2) dif y
=^rf("gaussian-integral")
sqrt(pi).
$
+ 1#rf("gamma-props", "plus-1") + 3#rf("gamma-props", "1/2")
+ По индукции. База --- определенение $Gamma$#rf("def-euler-integrals"). Переход:
Продифференцируем штуку под интегралом из предположния индукции:
$
(x^(p-1) ln^n (x) e^(-x))'_p =
(x^(p-1))'_p ln^n (x) e^(-x) =
(e^(ln x dot (p-1)))'_p ln^n (x) e^(-x) newline(=)
e^(ln x dot (p-1)) ln^(n + 1) (x) e^(-x) =
x^(p-1) ln^(n + 1) (x) e^(-x).
$
Чтобы сказать, что производная из интеграла --- интеграл производной, нужно проверить локальное условие лебега#rf("parametric-derivative"). В качестве окрестности $p$ возьмем произвольный интервал $(alpha, beta)$, где $0 < alpha < p < beta$.
Как и у самой $Gamma$, у производной есть особенности в $0$ и на бесконечноти, поэтому оценивать сверху интеграл будем только там. На произвольном отрезке не содержащем особенностей, функция и так суммируема, как ограниченная#rf("weierstrass").
На бесконечности: $ln(x) < x ==> x^(p-1) ln^n (x) e^(-x) <= x^(beta + n - 1) e^(-x)$, а интеграл этой штуки не больше $Gamma(beta + n)$, поэтому она суммируема.
В нуле: для любого $eps > 0$, $x^eps ln(x) -->_(x-->0+) 0$ (можете пролопиталить). Значит $abs(ln(x)) <= c x^(-eps)$ для какой-то константы $c$. Тогда
$ x^(p - 1) ln^n (x) e^(-x) <= c^n x^(alpha - n eps - 1), $
Для любого $alpha > 0$ и $n$ можно выбрать $eps$ так, что $alpha - n eps - 1 > -1$. Значит есть сходимость.
Нашли мажоранту, значит можно дифференцировать под интегралом, значит индукционных переход доказан.
+ Вторая производная#rf("gamma-props", "derivative") $integral_0^(+oo) x^(p-1) ln^2 (x) e^(-x) dif x$ положительна.
+ Предел при $p --> +oo$ очевиден,
так как $Gamma$ ведет себя как факториал#rf("gamma-props", "factorial"),
и монотонно возрастает начиная с какого-то $p$,
потому что монотонно возрастает где-то ($24 = Gamma(5) > Gamma(3) = 2$, например),
и выпукла#rf("gamma-props", "convex").
На самом деле возрастание начиная с $p = 1$ но это сложнее.
Чтобы оценить рост в нуле, оценим $Gamma$ через $Gamma(1)$.
$
p Gamma(p) = Gamma(p + 1) -->_(p -> 0) Gamma(1) = 1 ==> Gamma(p) tilde 1/p.
$
+ Потом#rf("gamma-growth").
]
#props(name: [$Beta$-функции], label: "beta-props")[
+ #sublabel("symm")
$ Beta(p, q) = Beta(q, p) $
+ #sublabel("zero-inf-integral")
$ Beta(p, q) = integral_0^(+oo) t^(p-1)/(1+t)^(p+q) dif t $
]
#proof[
+ $
Beta(p, q) =^rf("def-euler-integrals")
integral_0^1 x^(p-1) (1-x)^(q-1) dif x =^(y = 1-x)
-integral_1^0 y^(q-1) (1-y)^(p-1) dif y =^rf("def-euler-integrals")
Beta(q, p).
$
+ $
Beta(p, q) =^rf("def-euler-integrals")
integral_0^1 x^(p-1) (1-x)^(q-1) dif x =^(x = t/(t + 1))
integral_0^(+oo) (t/(t+1))^(p-1) (1/(t + 1))^(q - 1) (dif t)/((1 + t)^2).
$
]
#th(label: "beta-through-gamma")[
$
Beta(p, q) = (Gamma(p) Gamma(q)) / Gamma(p + q)
$
]
#proof[
$
Gamma(p) Gamma(q) =^rf("def-euler-integrals")
integral_0^(+oo) x^(p - 1) e^(-x) dif x dot
integral_0^(+oo) y^(q - 1) e^(-x) dif y
=^rf("independent-2d-prod")
integral_0^(+oo) integral_0^(+oo) x^(p-1) y^(q - 1) e^(-x - y) dif x dif y
newline(=^(u = x + y))
integral_0^(+oo) integral_y^(+oo) (u-y)^(p-1) y^(q - 1) e^(-u) dif u dif y
=^rf("tonelli")
integral_0^(+oo) integral_0^u (u-y)^(p-1) y^(q-1) e^(-u) dif y dif u
newline(=^(y = v u))
integral_0^(+oo) integral_0^1 (u - u v)^(p-1) (u v)^(q-1) e^(-u) u dif v dif u
=
integral_0^(+oo) integral_0^1 u^p (1 - v)^(p-1) u^(q-1) v^(q-1) e^(-u) dif v dif u
newline(=^rf("independent-2d-prod"))
integral_0^(+oo) u^(p+q-1) e^(-u) integral_0^1 (1-v)^(p-1) v^(q-1) dif v dif u
=^rf("def-euler-integrals")
Beta(p, q) Gamma(p + q).
$
]
#follow(name: "формула дополнения", label: "gamma-complement")[
$
Gamma(p) Gamma(1 - p) = pi/sin(pi p), space 0 < p < 1
$
]
#proof[
$
Gamma(p) Gamma(1 - p) =
Beta(p, 1 - p) Gamma(1) =^rf("beta-props", "zero-inf-integral")
integral_0^(+oo) t^(p-1)/(1 + t) dif t =
pi/sin(pi p).
$
Интеграл посчитаем потом. Андрей сказал, что нужен комплексный анализ, а нас пока травмировать не будут.
]
#follow(name: "формула удвоения", label: "gamma-double")[
$
Gamma(p) Gamma(p + 1/2) = sqrt(pi)/2^(2p - 1) Gamma(2p)
$
]
#proof[
Для начала рассмотрим $Beta(p, p)$:
$
Beta(p, p)
=^rf("def-euler-integrals")
integral_0^1 (x(1-x))^(p-1) dif x
=
2 integral_0^(1/2) (x(1-x))^(p-1) dif x
=^(y = 1/2 - x)
2 integral_0^(1/2) (1/2 - y)^(p - 1) (1/2 + y)^(p - 1) dif y
newline(=)
2 integral_0^(1/2) (1/4 - y^2)^(p-1) dif y
=^(z = 2y)
integral_0^1(1/4 - 1/4z^2)^(p-1) dif z
=^(t = z^2)
1/(2^(2p-1)) integral_0^1 (1-t)^(p-1) t^(1/2 - 1) dif t
=^rf("def-euler-integrals")
Beta(p, 1/2)/2^(2p - 1).
$
Тогда
$
(cancel(Gamma(p)) Gamma(p)) / Gamma(2p) =
(cancel(Gamma(p)) overbrace(Gamma(1/2), sqrt(pi)))/(Gamma(p + 1/2) 2^(2p - 1))
==>
Gamma(p) Gamma(p + 1/2) = sqrt(pi)/(2^(2p - 1)) Gamma(2p).
$
]
#th(label: "gamma-plus-const-growth")[
$
Gamma(t + a) tilde t^a Gamma(t), space t --> +oo, a > 0
$
]
#proof[
Давайте снова начнем со случайного с виду факта:
$
Beta(a, t) = (Gamma(a) Gamma(t))/Gamma(t + a) tilde_(t -> +oo) Gamma(a)/t^a.
$
Докажем его:
$
Beta(a, t) =^rf("def-euler-integrals")
integral_0^1 x^(a-1) (1-x)^(t - 1) dif x =^(y = t x)
integral_0^t y^(a - 1) t^(1 - a) (1 - y/t)^(t-1) 1/t dif y newline(=)
1/t^a integral_0^(+oo) y^(a-1) (1-y/t)^(t-1) bb(1)_[0, t] dif y.
$
Заметим, что подынтегральное выражение имеет предел:
$
y^(a-1) (1-y/t)^(t-1) bb(1)_[0, t] -->_(t-->+oo) y^(a-1) e^(-y)
$
При больших $t$, $y^(a-1) (1-y/t)^(t-1) < 2 y^(a-1) e^(-y)$ --- а это суммируемая мажоранта. Значит можно перейти к пределу:
$
lim_(t -> +oo) t^a Beta(a, t)
=
lim_(t -> +oo) integral_0^(+oo) y^(a-1) (1-y/t)^(t-1) bb(1)_[0, t] dif y
=^rf("parametric-limit")
integral_0^(+oo) y^(a-1) e^(-y) dif y
=^rf("def-euler-integrals")
Gamma(a).
$
Доказали случайный с виду факт.
Теперь поймем, что
$
(cancel(Gamma(a)) Gamma(t))/Gamma(t + a) tilde_(t -> +oo) cancel(Gamma(a))/t^a
==>
Gamma(t + a) tilde_(t -> +oo) t^a Gamma(t).
$
]
#follow(label: "gamma-plus-const-growth-uniform")[
Если $1 < a < 2$, то стремление равномерное (не зависимое от параметра $a$)
$
Gamma(t + a)/(t^a Gamma(t)) arrows.rr 1.
$
]
#proof[
Судя по доказательству теоремы, для равномерной сходимости нужно, чтобы $Beta(a, t) dot t^a - Gamma(a)$ равномерно сходилось к нулю. Тогда равномерную сходимость можно будет дотянуть до конца доказательства. Рассмотрим модуль их разности, расписав $Gamma(a)$ по определению:
$
abs((integral_0^t y^(a-1) (1-(y/t))^(t-1) dif y) - Gamma(a)) =^rf("def-euler-integrals")
abs(integral_0^t y^(a-1) (1-(y/t))^(t-1) dif y - integral_0^(+oo) y^(a - 1) e^(-y) dif y)
newline(<=)
integral_t^(+oo) y^(a-1) e^(-y) dif y + integral_0^t y^(a-1) abs((1-y/t)^(t-1) - e^(-y)) dif y.
$
Оценим интегралы еще сильнее. Первый интеграл не больше $integral_t^(+oo) y e^(-y) dif y$, так как $1 < a < 2$. Второй интеграл можно разбить на два: от $0$ до $1$, и от $1$ до $+oo$. В первом интеграле $y^(a - 1) <= 1$, а во втором, $y^(a - 1) <= y$. Получили слеюдущую оценку сверху, не зависющую от $a$:
$
integral_t^(+oo) y e^(-y) dif y + integral_0^1 abs((1-y/t)^(t-1) - e^(-y)) dif y + integral_1^t y abs((1-y/t)^(t-1) - e^(-y)) dif y.
$
Первый интеграл сходится к $0$, так как экспонента быстро убывает. Во втором и третьем интеграле под модулем записано определение экспоненты (без предела) минус экспонента, а оно стремиться к нулю, поэтому второй интеграл тоже стремиться к нулю. Ну а третий стремиться к нулю по той же причине, что и в доказательстве теоремы: домножим на $bb(1)_([1, t])$, сделаем предельный переход#rf("gamma-plus-const-growth") --- под интегралом окажется $y dot abs(e^(-y) - e^(-y)) = 0$.
]
#follow(label: "gamma-growth")[
$ Gamma(p) tilde_(p-->+oo) sqrt((2pi)/p) e^(-p) p^(p). $
]
#proof[
Для целых $p$ это просто формула Стирлинга#rf("stirling").
Для остальных рассмотрим $p = n + a$, $1 < a < 2$:
$
Gamma(p) =
Gamma(n + a) tilde^rf("gamma-plus-const-growth")
Gamma(n) dot n^a =^rf("gamma-props", "factorial")
(n-1)! dot n^a =
n! dot n^(a-1) tilde^rf("stirling")
sqrt(2 pi n) (n/e)^n n^(a-1) newline(=)
sqrt(2 pi) dot n^(1/2 + n + (a - 1)) dot e^(-n) =
sqrt(2 pi) dot n^(p - 1/2) dot e^(-n) =
sqrt((2 pi)/n) dot n^p dot e^(-n) tilde
sqrt((2 pi)/p) dot n^p dot e^(-n) newline(=)
sqrt((2 pi)/p) dot (p^p dot (n/p)^p) dot (e^(-p) dot e^(p - n)) =
sqrt((2 pi)/p) p^p e^(-p) dot ((n/p)^p dot e^a) =
sqrt((2 pi)/p) p^p e^(-p) dot e^(p ln n/p + a).
$
Надо доказать, что $p ln n/p + a --> 0$. Действительно,
$
p ln n/p + a = p ln (1 - a/p) + a = p (-a/p + O(p^(-2))) + a = O(p^(-1)) arrows.rr 0.
$
Отмечу, что везде сходимость равномерная. В первом переходе по следствию#rf("gamma-plus-const-growth-uniform"), в конце так как получившееся выражение зависит только от $p$. Экспонента равномерно сходится к единице, так как показатель равномерно сходится к нулю.
Это важно, так как если бы скорость роста для разных $a$ была бы разной, мы бы не могли считать предельных переходы по $n$ по $p$ взаимозаменяемыми. Ну, то есть представьте себе, что чем меньше $a$, тем медленнее сходимость. Тогда если бы мы подставляли $p = n + (1 + 1/n)$, не факт, что предел был бы. Но благодаря равномерности, для любого $eps$ начиная с какого-то $n = N$ по всем $a$ можно оценить сверху через $eps$ значение любого выражения, а значит и для любого $p > n + 2$.
]
#follow(name: "<NAME>", label: "euler-gauss")[
$
Gamma(p) =
lim_(n->+oo) (n^p n!)/(p(p + 1)(p + 2)...(p + n))
$
]
#proof[
По свойствам гамма-функции#rf("gamma-props", "factorial")#rf("gamma-props", "plus-1") знаем, что
$
n!/(p(p+1)...(p+n)) =
(Gamma(p)Gamma(n + 1))/Gamma(p + n + 1)
$
Тогда
$
lim_(n->+oo) (n^p n!)/(p(p + 1)(p + 2)...(p + n)) =
lim_(n->+oo) (n^p dot Gamma(p)Gamma(n + 1))/Gamma(p + n + 1) =^rf("gamma-props", "plus-1")
lim_(n->+oo) (n^p dot Gamma(p)Gamma(n) dot n)/(Gamma(p + n)(n + p)).
$
Так как $n^p Gamma(n) tilde Gamma(n + p)$#rf("gamma-plus-const-growth") при $n -> +oo$:
$
lim_(n->+oo) (n^p dot Gamma(p)Gamma(n) dot n)/(Gamma(p + n)(n + p)) =
lim_(n->+oo) (Gamma(n + p) Gamma(p) dot n)/(Gamma(n + p)(n + p)) =
lim_(n->+oo) (Gamma(p) dot n)/(n + p) = Gamma(p) dot lim_(n -> +oo) n/(n + p) = Gamma(p).
$
]
#follow(label: "wallis", name: "<NAME>")[
$
lim_(n -> +oo) (2n)!!/(2n - 1)!! 1/sqrt(2n + 1) = sqrt(pi / 2).
$
]
#proof[
Подставляем $p = 1/2$ в формулу#rf("euler-gauss"):
$
Gamma(1/2) =
lim_(n -> +oo) (sqrt(n) dot n!)/(1/2 dot 3/2 dot ... dot (n + 1/2)) =
lim_(n -> +oo) (sqrt(n) dot n! dot 2^(n + 1))/(1 dot 3 dot ... dot (2n + 1))
=
lim_(n -> +oo) (2 sqrt(n) dot (2n)!!)/(2n + 1)!!
newline(==>)
Gamma(1/2) =^rf("gamma-props", "1/2") sqrt(pi) = lim_(n -> +oo) (2 sqrt(n) dot (2n)!!)/(2n + 1)!! =
lim_(n -> +oo) (2n)!!/(2n - 1)!! dot (2sqrt(n))/(2n + 1) = \
lim_(n -> +oo) (2n)!!/(2n - 1)!! dot sqrt(2)/sqrt(2n+1) dot sqrt((2n)/(2n+1)) ==>
lim_(n -> +oo) (2n)!!/(2n - 1)!! dot 1/(sqrt(2n + 1)) = sqrt(pi/2).
$
]
#examples[
+ $
product_(k = 0)^n (3k + 1) =
1 dot 4 dot 7 dot ... dot (3n + 1) =
3^(n+1) dot 1/3 dot (1 + 1/3) dot ... dot (n + 1/3) tilde (3^(n+1) n^(1/3) n!)/Gamma(1/3).
$
+ $
integral_0^(+oo) e^(-x^p) dif x, p > 0 =^(y = x^p)
integral_0^(+oo) 1/p y^(1/p - 1) e^y dif y =
1/p Gamma(1/p) =
Gamma(1 + 1/p).
$
+ $
integral_0^(pi/2) sin^(p-1) x cos^(q - 1) x dif x =^(y = sin^2 x)
1/2 integral_0^1 y^((p-2)/2) (1-y)^((q-2)/2) dif y =
1/2 Beta(p/2, q/2).
$
В частности
$
integral_0^(pi/2) sin^(p-1) x dif x = 1/2 Beta(p/2, 1/2) = 1/2 (Gamma(p/2)sqrt(pi))/Gamma((p + 1)/2).
$
4. $V_n (r)$ - объем $n$-мерного шара радиуса $r$.
Распишем объем через объем единичного шара $C_n$: $V_n (r) = r^n C_n$. Воспользуемся принципом Кавальери#rf("cavalieri") и "откусим" одну координату:
$
C_n = integral_(-1)^1 V_(n-1) (sqrt(1-x^2)) dif x =
integral_(-1)^1 (1-x^2)^((n-1)/2) C_(n-1) dif x =
2 integral_0^1 (1-x^2)^((n-1)/2) C_(n-1) dif x
newline(=^(x = sin phi))
2 C_(n-1) integral_0^(pi/2) cos^n phi dif phi =
C_(n-1) (Gamma((n+1)/2)sqrt(pi))/Gamma((n + 2)/2).
$
Значит по индукции,
$
C_n = C_1 (pi^((n-1)/2) Gamma(3/2))/Gamma((n+2)/2) = pi^(n/2)/Gamma(n/2+1).
$
] |
|
https://github.com/fufexan/cv | https://raw.githubusercontent.com/fufexan/cv/typst/metadata.typ | typst | /* Personal Information */
#let firstName = "Mihai-Cristian"
#let lastName = "Fufezan"
#let personalInfo = (
github: "fufexan",
email: "<EMAIL>",
linkedin: "mihai-fufezan",
homepage: "fufexan.net",
)
#let headerQuoteInternational = (
"": [Third year Computer Engineering student with a passion for developing great
programs and managing systems. Enjoys finding the intersection between fast,
correct and elegant code.],
"ro": [Student ETTI în anul trei, cu o pasiune pentru dezvoltarea de programe
grozave și gestionarea sistemelor. Se străduiește să găsească intersecția
între cod rapid, corect și elegant.],
)
/* Layout settings */
// Optional: skyblue, red, nephritis, concrete, darknight
#let awesomeColor = "skyblue"
#let profilePhoto = "./avatar.png"
// INFO: value must matches folder suffix; i.e "zh" -> "./modules_zh"
#let varLanguage = ""
// Decide if you want to put your company in bold or your position in bold
#let varEntrySocietyFirst = false
// Decide if you want to display organisation logo or not
#let varDisplayLogo = true
#let cvFooterInternational = (
"": "Curriculum vitae",
"ro": "Curriculum vitae",
)
#let letterFooterInternational = (
"": "Cover letter",
"ro": "Scrisoare de intenție",
)
|
|
https://github.com/MatheSchool/typst-g-exam | https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/src/g-question.typ | typst | MIT License | #import"./global.typ": *
/// Show a question.
///
/// *Example:*
/// ```
/// #g-question(points:2)[This is a question]
/// ```
///
/// - points (none, float): Points of the question.
/// - points-position (none, left, right): Position of points. If none, use the position defined in G-Exam.
/// - body (string, content): Body of question.
#let g-question(
points: none,
points-position: none,
body) = {
assert(points-position in (none, left, right),
message: "Invalid point position")
__g-question-number.step(level: 1)
[#hide[]<end-g-question-localization>]
__g-question-point.update(p =>
{
if points == none { 0 }
else { points }
})
context {
let __g-question-points-position = points-position
if __g-question-points-position == none {
__g-question-points-position = __g-question-points-position-state.final()
}
let __g-question-text-parameters = __g-question-text-parameters-state.final()
let __decimal-separator = __g-decimal-separator.final()
if __g-question-points-position == left {
v(0.1em)
{
__g-question-number.display(__g-question-numbering)
if(points != none) {
__g-paint-tab(points:points, decimal-separator: __decimal-separator)
h(0.2em)
}
}
set text(..__g-question-text-parameters)
body
}
else if __g-question-points-position == right {
v(0.1em)
if(points != none) {
place(right,
dx: 13%,
float: false,
__g-paint-tab(points: points, decimal-separator: __decimal-separator))
}
__g-question-number.display(__g-question-numbering)
set text(..__g-question-text-parameters)
body
}
else {
v(0.1em)
__g-question-number.display(__g-question-numbering)
set text(..__g-question-text-parameters)
body
}
}
}
/// Show a sub-question.
///
/// *Example:*
/// ```
/// #g-subquestion(points:2)[This is a sub-question]
/// ```
///
/// - points (none, float): Points of the sub-question.
/// - points-position (none, left, right): Position of points. If none, use the position defined in G-Exam.
/// - body (string, content): Body of sub-question.
#let g-subquestion(
points: none,
points-position: none,
body) = {
assert(points-position in (none, left, right),
message: "Invalid point position")
__g-question-number.step(level: 2)
let subg-question-points = 0
if points != none { subg-question-points = points }
__g-question-point.update(p => p + subg-question-points )
context {
let __g-question-points-position = points-position
if __g-question-points-position == none {
__g-question-points-position = __g-question-points-position-state.final()
}
let __g-question-text-parameters = __g-question-text-parameters-state.final()
let __decimal-separator = __g-decimal-separator.final()
// [#type(body)]
// [#body.fields()]
// [#type(body.children)]
// [#body.at("children", default: "j")]
// if body.children.
if body.has("text") {
set par(hanging-indent: 1em)
}
if __g-question-points-position == left {
v(0.1em)
{
h(0.7em)
__g-question-number.display(__g-question-numbering)
if(points != none) {
__g-paint-tab(points: points, decimal-separator: __decimal-separator)
h(0.2em)
}
}
set text(..__g-question-text-parameters)
body
}
else if __g-question-points-position == right {
v(0.1em)
if(points != none) {
place(right,
dx: 13%,
float: false,
__g-paint-tab(points: points, decimal-separator: __decimal-separator))
}
{
h(0.7em)
__g-question-number.display(__g-question-numbering)
}
set text(..__g-question-text-parameters)
body
}
else {
v(0.1em)
{
h(0.7em)
__g-question-number.display(__g-question-numbering)
}
set text(..__g-question-text-parameters)
body
}
}
}
|
https://github.com/elteammate/typst-compiler | https://raw.githubusercontent.com/elteammate/typst-compiler/main/src/z-test2.typ | typst | #import "reflection-lexer.typ": *
#import "reflection-parser.typ": *
#import "pprint.typ": *
#let tokens = lex_file("test2.typ")
// #for i, x in tokens {
// [ #i: #x \ ]
// }
// #postprocess_lexed(tokens)
#pprint(typst_parse(tokens))
|
|
https://github.com/storopoli/invoice | https://raw.githubusercontent.com/storopoli/invoice/main/main.typ | typst | MIT License | #import "invoice-maker.typ": *
#show: invoice.with(
//banner-image: image("banner.png"),
data: toml("invoice.toml"),
styling: ( font: none ), // Explicitly use Typst's default font
)
|
https://github.com/jens-hj/ds-exam-notes | https://raw.githubusercontent.com/jens-hj/ds-exam-notes/main/lectures/8.typ | typst | #import "../lib.typ": *
#show link: it => underline(emph(it))
#set math.equation(numbering: "(1)")
#set enum(full: true)
#set math.mat(delim: "[")
#set math.vec(delim: "[")
#set list(marker: text(catppuccin.latte.lavender, sym.diamond.filled))
#show heading.where(level: 1): it => text(size: 22pt, it)
#show heading.where(level: 2): it => text(size: 18pt, it)
#show heading.where(level: 3): it => {
text(size: 14pt, mainh, pad(
left: -0.4em,
gridx(
columns: (auto, 1fr),
align: center + horizon,
it, rule(stroke: 1pt + mainh)
)
))
}
#show heading.where(level: 4): it => text(size: 12pt, secondh, it)
#show heading.where(level: 5): it => text(size: 12pt, thirdh, it)
#show heading.where(level: 6): it => text(thirdh, it)
#show emph: it => text(accent, it)
#show ref: it => {
//let sup = it.supplement
let el = it.element
if el == none {
it.citation
}
else {
let eq = math.equation
// let sup = el.supplement
if el != none and el.func() == eq {
// The reference is an equation
let sup = if it.fields().at("supplement", default: "none") == "none" {
[Equation]
} else { [] }
// [#it.has("supplement")]
show regex("\d+"): set text(accent)
let n = numbering(el.numbering, ..counter(eq).at(el.location()))
[#sup #n]
}
else if it.citation.has("supplement") {
if el != none and el.func() == eq {
show regex("\d+"): set text(accent)
let n = numbering(el.numbering, ..counter(eq).at(el.location()))
[#el.supplement #n]
}
else {
text(accent)[#it]
}
}
}
}
=== General
- Use ideas from previous weeks
==== Purpose
- Process _big data_ with reasonable _cost and time_
- Large scale processing on data not stored on a single computer
==== Idea
- Distribute the data as it is initially stored.
- _Each node_ can then perform computation on the data it stores without mocing the data for the intial processing.
- *Don't* move data to the computation
- *Do* move the computation to where the data is
==== Examples
- Google File System
- MapReduce: Simplified Data Processing on Large Clusters
==== History
Used to be #ra is like this now
- Low data volume #ra High data volume
- Big complex computations #ra Many simpler computations
_Improvements to the individual machine #ra able to perform the processing itself._
- Moore's law
=== Hadoop File system
- Storing data on the cluster
- For _large_ files
- Files _split into blocks_ of certain size #ra distribute across nodes in cluster
- Similar concept as we saw in `RAID`
- Each _block is replicated_ multiple times
- Main goal to _optimise for speed_
- Has some _reliability_, but not a main goal
- Unlikely to be built with SSDs #ra too expensive
#report-block[
OH?! The storage system I have implemented is a simple HDFS??
]
==== NFS vs HDFS
NFS < v4.1 - before multiple servers
#image("../img/8/hdfs-vs-nfs.png", width: 70%)
==== Basic concepts
- Redundant storage for MASSIVE amounts of data
- HDFS works best with a _small number_ of _large files_
- Millions as opposed to billions of iles
- Typically 100MB or more per file
- Terabytes or Petabytes of data
- Files in HDFS are write once!
- Optimised for streaming reads of large files and not random reads
#ra operate disks at absolute top speed
*More*
- _Very large_ distributed file system
- 10k nodes, 100 million files, 10PB
- Don't assume _specific_ hardware: Assumes commodity hardware
- Files are _replicated_ to handle hardware failure
- *Optimised for batch processing*
- Data locations exposed so that _computations can move to where data resides_
- Provides very _high aggregate bandwidth_
*More more*
- Tolerate node failure without data loss
- _Detect failures and recover from them_
- Data coherency
- Write-once #ra read-many access model
- Client can _only_ append to existing files
- _Computation is near the data_
- Portability; built using Java
*Summary*
#image("../img/8/hdfs-basics.png", width: 50%)
- Built for large scale processing, not quick access
#image("../img/8/hdfs-diag.png", width: 60%)
==== Blocks
*Large blocks*
- Size of either 64MB or 128MB
- Minimise seek costs
- *Benefit:* can take advantage of any disks in the cluster
- Simplified the storage subsystem: amount of metadata storage per file is reduced
- Good for replication schemes
==== Master/worker pattern
*Name/Coordinator Node*
- Manage filesystem metadata
- Where are chunks corresponding to a file
- Configuration
- Replication engine
*Data/Worker nodes:*
- Workhorse of the file system: store and retrieve
- Stores metadata of a block (e.g. CRC checksums)
- Serves data and metadata to clients
*Data/Worker nodes:*
- Two files:
+ Data
+ Metadata: checksums, generation stamp (timestamp?)
- Startup handshake
- After handshake
*Namenode metadata* \
_In memory_
- List of files
- List of blocks for each file
- List of datanodes for each block
- File attributes, e.g. creation time, replication factor
- Transaction log
#report-block[
Well it looks like it is a very very abstract and simple implementation of HDFS if anything.
Some things line up:
- Replication schemes
- Master/worker pattern
- Coordinator keeps track of metadata
]
==== Resiliancy
Have secondary coordinator/name-node
==== HDFS Client
- Code library that exports the HDFS interface
- Allows user application to access the file system
- *Intelligent client*
- Client can find location of blocks
- Client accesses data directly from worker/data-nodes
==== Read Operation
#image("../img/8/hdfs-read.png", width: 70%)
#report-block[
*Difference to my implementation:* \
_Clearly_ my client does not simply use the Name/coordinator-node to access metadata and then connect to data/worker-nodes itself.
Make sure to understand whether what I have done is _RPCs_ or not \
#ra Maybe it's a simplified custom way of doing RPCs
*Remember:* \
It said nowhere on the project description that it should be a HDFS implementation
]
==== Write Operation
- Once written, cannot be altered, _only append_
- HDFS Client: lease for the file
- Renewal of lease
- Lease: _soft_ limit or _hard_ limit
- Single-writer, multiple-reader model
#image("../img/8/hdfs-write.png", width: 70%)
- Bring traffic down by letting the nodes talk to each other
- Circumvents network limitation on client side, as instead of talking to multiple nodes, it just sends once, thus _handing off_ the network load to the nodes
#report-block[
My data nodes do not talk to each other at all \
#ra All happens from the coordinator to the data nodes
]
==== Replication
- Multiple nodes for reliability
- Aditionally, data transfer brandwidth is multiplied
- Computation is near data
- Replication factor, default: $k=3$
*Block placement:*
- After placement you have a certain structure, and knowdledge thereof
- Place intentionally to be robust and reliable
- Spread across multiple racks
- Nodes of rack share switch
- Balance with speed
*Balancer:*
- Balasnce disk space usage
- Optimise by minimising inter-rack copying
*Strategy:*
- *Current Strategy*
- One replica on local node
- Second replica on remote rack
- Third replica on same remote rack
- Additional replicas are randomly placed
- Clients read from nearest replicas
- Would like to make this policy _pluggable_?
- Something you can edit and change.
==== Data Pipelining
- Client retrieves list of data/worker-nodes on which to place replicas of a block
- Client writes block to the first data/worker-node
- This node handles handing over to the next node
- When all replicas are written, the client moves on to write the next block in file
==== Balancer
*Goal:*
- Percentage full on data/worker-nodes should be _balanced_
*Interesting when:*
- New nodes are added
- Rebalancing? Maybe when new nodes are added or simply slowly balance by using that node more.
- Rebalancer gets throttles when more network bandwidth is needed elsewhere
- Typically a command line tool run by and operator
==== Block Scanner
- Periodically scan and verify checksums
- *Check for:*
- Verfication succeeded?
- Corrupt block?
- Verfication of data correctness
*Checksums*
- Computs CRC32 for ever 512 bytes
- Make sure nothing is missing
- Data/worker nodes store checksums
- *File Access:*
- Client retrieves the data and checksums from the data/worker-node
- If _validation fails_ #ra client tries other replicas
#report-block[
No checksums, data correctness is in my system
]
==== Heartbeat
- Data/worker-nodes sends heartbeat to name/coordinator-node
- once every 3 seconds
- Name/coordinator-node uses heartbets to detect whether a node has failure
==== Beyond One Node Failure
*A lot of failures:*
- Full racks
- Fire
- Power outages
_{HDFS, GFS, Windows Azure, RAMCloud} uses random placement_ \
#ra Random not so good no no no
=== Copysets & Random Replica Placement
#report-block[
Yay finally something in the report, I must already know this.
But here are notes on what I missed or maybe _misinterpreted_ from the slides:
]
==== 1% of nodes fail concurrently:
- Chance of data loss doens't mean that percentage of data is lost
- It is a percentage of the probability of data loss, so at least 1 chunk lost
#gridx(
columns: 2,
image("../img/8/t-trade.png"),
image("../img/8/g-recov-buddy.png"),
image("../img/8/g-buddy.png")
)
==== Random
- Basically every failure is a loss
Probability of a given chunk is lost:
$
mat(delim: "(", F; R) / mat(delim: "(", N; R)
$
Where $F$ nodes out of $N$ have been lost, with replication factor $R$
==== Minimum Copysets
- Only loss if all nodes in specific copyset dies
- Once you lose something, you will lose _a lot_ \
#ra Less nodes left to recover (only the last nodes left in the copyset, instead of from many random nodes) \
#ra Thus much longer recovery time
#report-block[
Scatter-width? \
#ra Daniel didn't mention in the lecture
]
==== Buddy
- Combining random with the idea of creating separate groups
- Isolated random replication groups
- A copyset is always within one buddy group
- However, placed randomly within the group
=== MapReduce
- Fast overview
==== Overview
- Distribute computation across nodes
==== Features
- Automatic parallelisation and distribution \
#ra Bad for little data, good for massive data
- Provides a clean abstraction for programmers to use
*Fault Tolerance:*
- System detects laggard tasks
- Speculatively executes parallel tasks on the same slice of data
==== Phases
+ Map
+ (Shuffle & Sort)
+ Reduce
*Mapper:*
+ *Input:* Data _key/value pairs_
- The key is often discarded
+ *Outputs:* _zero or more_ key/value pairs
- For every key identify what the value is
*Shuffle & Sort:*
+ Output from the mapper is _sorted by key_
_All values with the *same key* are guaranteed to go to the *same machine*_ \
#ra Hadoop overhead here?
*Reduce:*
+ Called once for each unique key
+ *Input:* List of all values associated with a key
+ *Outputs:* Zero or more final key/value pairs
- Usually reduced to 1 output per unique key input
*Example:* Count words of same type
#image("../img/8/map-reduce.png")
- Already at the splitting stage when stuff has been chunked and split into nodes.
- What the mapping and reduction does is defined base on what function you want to compute.
- In this case the mapping could actually also reduce the data by counting each value up, if a key is repeated.
Steps:
+ *Mapping:* Take each word and write it's value of 1 such that you can count them in reduction stage.
+ *Shuffle:* Move data around such that data for a single key is in a single node.
+ *Reduction:* Here reduce over each key bu summing values.
#report-block[
This definitely looks like something I should have thought about in the report:
#image("../img/8/compute-time.png")
] |
|
https://github.com/RY997/Thesis | https://raw.githubusercontent.com/RY997/Thesis/main/common/metadata.typ | typst | MIT License | // Enter your thesis data here:
#let titleEnglish = "Leveraging Generative AI for Adaptive Exercise Generation"
#let titleGerman = "Nutzung Generativer KI für die Adaptive Generierung von Aufgaben"
#let degree = "Master"
#let program = "Informatics"
#let supervisor = "Prof. Dr. <NAME>"
#let advisors = ("<NAME>, M.Sc.",)
#let author = "<NAME>"
#let startDate = "15. August 2023"
#let submissionDate = "15. February 2024" |
https://github.com/floriandejonckheere/utu-thesis | https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/chapters/06-automated-modularization/02-artifacts.typ | typst | #import "@preview/acrostiche:0.3.1": *
#import "/helpers.typ": *
=== SDLC artifact
The identified #acr("SDLC") artifact categories used as input for the microservice candidate identification algorithm are described in @slr_artifacts.
The categories are adapted from a study by #cite_full(<bajaj_etal_2021>).
#figure(
table(
columns: (auto, auto, auto),
inset: 10pt,
stroke: (x: none),
align: (left, left, left),
[*Artifact*], [*Type*], [*Publications*],
"Requirements documents and models", // e.g., functional and non-functional requirements, use cases, BPMN
"Static",
[
#artifacts.at("requirements").map(p => ref(label(p))).join()
],
"Design documents", // e.g., API specifications, UML, ERD
"Static",
[
#artifacts.at("design").map(p => ref(label(p))).join()
],
"Codebase", // e.g., source code, revision history
"Static",
[
#artifacts.at("codebase").map(p => ref(label(p))).join()
],
"Execution data", // e.g., log files, execution traces
"Dynamic",
[
#artifacts.at("execution").map(p => ref(label(p))).join()
],
),
caption: [SDLC artifact categories]
) <slr_artifacts>
Of the four categories, requirements documents and models, design documents, and codebase are static artifacts, while execution data is a dynamic artifact.
Hybrid approaches using both static and dynamic analysis are categorized according to the artifact used in the respective analysis.
#pagebreak()
As @slr_artifacts_chart illustrates, the majority of the #total(artifacts) identified approaches use the codebase as input for the algorithm (#count(artifacts, "codebase")\; #percentage(artifacts, "codebase")), followed by execution data (#count(artifacts, "execution")\; #percentage(artifacts, "execution")).
#count(artifacts, "requirements") publications (#percentage(artifacts, "requirements")) use requirements documents an models, and #count(artifacts, "design") (#percentage(artifacts, "design")) use design documents.
#figure(
include("/figures/06-automated-modularization/artifacts.typ"),
caption: [SDLC artifact categories]
) <slr_artifacts_chart>
==== Requirements documents and models
In software engineering, requirements documents and models are used to formally describe the requirements of a software system following the specification of the business or stakeholder requirements @software_requirements_specification.
They include functional and non-functional requirements, use cases, user stories, and business process models.
Approaches using requirements documents and models as input for the microservice candidate identification algorithm often times need to pre-process the documents to extract the relevant information, as they are not always in a machine-readable format.
In many cases, requirements documents and models for legacy systems are no longer available or outdated @bajaj_etal_2021, which makes this approach less suitable for automated microservice candidate identification.
#cite_full(<amiri_2018>) and #cite_full(<daoud_etal_2020>) modeled a software system as a set of business processes using the industry standard #acr("BPMN"), adopting the machine-readable XML representation as input for the algorithm.
#cite_full(<yang_etal_2022>) tackled requirements engineering using problem frames.
Problem frames are a requirements engineering method, which emphasizes the integration of real-world elements into the software system @jackson_2000.
Some approaches use schematic requirements documents in XML format as input for the algorithm, as described by #cite_full(<saidi_etal_2023>).
The authors used domain-driven design techniques to extract functional dependencies from the software design as starting point in microservice candidate identification.
#cite_full(<li_etal_2023>) employed an intermediate format containing a precise definition of business functionality, generated from validated requirements documents.
==== Design documents
Design documents created by software architects are machine-readable representations of the software system.
They describe the software functionalities in detail and are used to guide the implementation of the software system.
Design documents include #acr("API") specifications, #acr("UML") diagrams (such as class diagrams and sequence diagrams), and #acr("ERD").
Techniques using design documents either use a domain-driven approach, or a data-driven approach.
Domain-driven approaches use domain-specific knowledge to identify microservice candidates, while data-driven approaches use knowledge about data storage and data flow to identify microservice candidates.
Similar to requirements documents and models, design documents for legacy systems are often not available or outdated, although some design documents can be reconstructed from the software system (e.g., reverse engineering #acr("ERD")s from the database schema).
For example, #cite_full(<al_debagy_martinek_2020>) proposed a data-driven method based on the analysis of the external #acr("API") exposed by the application, specified in the OpenAPI#footnote[#link("https://www.openapis.org/")[https://www.openapis.org/]] format.
The method extracts the information from the specification file and converts it into a vector representation for further analysis.
#cite_full(<zhou_xiong_2022>) used readily available design documents as well, in the form of #acr("UML") class diagrams, use cases, and object sequence diagrams as starting point for the microservice candidate identification algorithm.
The decomposition tool proposed by #cite_full(<hasan_etal_2023>) used design documents as well, although the specifications are inferred from the source code of the software system, and do not require pre-existing design documents.
#cite_full(<quattrocchi_etal_2024>) took a different approach to the problem, using a data-driven approach combined with a domain-driven approach.
Software architects describe the software system using a custom architecture description language, and the tool developed by the authors is able to identify microservice candidates based on the given description.
The tool can be prompted to generate different, more efficient decompositions when given additional domain-driven requirements.
#cite_full(<wei_etal_2020>) used a similar approach, gathering a list of features from the software architect, and proposing a microservice decomposition based on pre-trained feature tables.
==== Codebase
A third category of #acr("SDLC") artifacts is the codebase of the software system.
This can be the source code of the software system, or a binary distribution (e.g. a JAR file).
For example, the implementation by #cite_full(<agarwal_etal_2021>) accepts either source code or compiled binary code for analysis.
As the source code of the software system is the most detailed representation of how the software system works, it is most often used as input for the microservice candidate identification algorithm.
The source code can be analyzed using static analysis (i.e., without executing the software system), dynamic analysis (i.e., during the execution of the software system or test suite), or a combination of both.
Dynamic analysis has the advantage that it can be used if the source code is not available.
Additionally, the revision history of the source code can also be used as source for valuable information about the behaviour of the software system.
#cite_full(<mazlami_etal_2017>) proposed the use of the revision history of the source code to identify couplings between software components, based on a prior publication by #cite_full(<gall_etal_2003>).
The authors suggested multiple strategies that can be used to extract information from the revision history.
Others have built upon this approach, using the revision history to identify the authors of the source code, and use this information to drive the identification algorithm @lourenco_silva_2023, @santos_paula_2021
#cite_full(<escobar_etal_2016>) used the source code of the software system to construct an #acr("AST"), and mapped the dependencies between the business and data layer.
#cite_full(<kamimura_etal_2018>) used a more data-driven approach, and statically traced data access calls in the source code.
Many publications @selmadji_etal_2020, @wu_zhang_2022, @zaragoza_etal_2022, @santos_silva_2022, @agarwal_etal_2021, @cao_zhang_2022, @santos_paula_2021, @kalia_etal_2021 construct a dependency graph from Java source code, and use the graph as input for a clustering algorithm.
#cite_full(<bandara_perera_2020>) mapped object-oriented classes in the source code to specific microservices, but required a list of microservices to be specified before the decomposition can be performed.
#cite_full(<filippone_etal_2021>) concentrated on #acr("API") controllers as entrypoints into the software system.
A later paper by the same authors @filippone_etal_2023 built on top of this approach by using the API endpoints as entrypoints, and then ascending into the source code by making a distinction between the presentation and logic layer.
Likewise, #cite_full(<zaragoza_etal_2022>) made a distinction between presentation, business, and data layer in their analysis.
Most of the publications tracing dependencies between software components do it at the level of the software component (classes or packages).
As #cite_full(<mazlami_etal_2017>) remarked, using a more granular approach at the level of methods (or functions) and attributes has the potential to improve the quality of the decomposition.
#cite_full(<carvalho_etal_2020>) used a more granular approach, identifying dependencies between methods in the source code.
On the other hand, #cite_full(<kinoshita_kanuka_2022>) did not automatically extract information from the source code, but relied on a software architect to decompose the software system on the basis of business capabilities.
#cite_full(<romani_etal_2022>) proposed a data-centric microservice candidate identification method based on knowledge gathered from the database schema.
The authors extracted table and column methods from the database schema, and used the semantically enriched information as input for the identification algorithm.
#cite_full(<hao_etal_2023>) constructed access patterns from both the database schema (static) and the database calls during execution of the software system (dynamic).
A unique approach to constructing a call graph was proposed by #cite_full(<nitin_etal_2022>), who made a distinction between context-insensitive and context-sensitive dependency graphs.
While the former captures the dependencies between software components using simple method calls, the latter also includes the context (i.e., the arguments) of the method call in the dependency graph.
==== Execution data
Information about the behaviour of the system can also be collected during the runtime of the software system.
Execution data includes log files, execution traces, and performance metrics.
This category is often combined with static analysis on source code, as the execution data can provide additional information to the identification algorithm.
In dynamic languages such as Java, dynamic analysis can trace access patterns that static analysis cannot (e.g., due to late binding and polymorphism).
Additionally, execution data can be collected when the source code of the software system is not available, by using software probes or monitoring tools.
Examples of approaches that used execution traces are proposed by #cite_full(<jin_etal_2021>) and #cite_full(<eyitemi_reiff_marganiec_2020>).
Using software probes inserted into the bytecode of respectively Java and .NET applications, the authors were able to monitor execution paths.
#cite_full(<zhang_etal_2020>) collected the execution traces of the software system, in combination with performance logs.
#cite_full(<ma_etal_2022>) used a data-centric approach based on the analysis of database access requests.
==== Hybrid approach
Some publications suggest a hybrid approach using both static and dynamic analysis.
For instance, #cite_full(<wu_zhang_2022>), #cite_full(<carvalho_etal_2020>), and #cite_full(<cao_zhang_2022>) collected information statically from the source code (entity classes and databases), as well as dynamically from the execution of the software system (execution traces).
The approach proposed by #cite_full(<lourenco_silva_2023>) uses either static of the source code or dynamic analysis of the system execution to gather access patterns.
#cite_full(<hao_etal_2023>) used both static and dynamic analysis, albeit aimed at the database schema and database calls, respectively.
|
|
https://github.com/rabotaem-incorporated/calculus-notes-2course | https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/02-measure-theory/04-lebesgue-measure.typ | typst | #import "../../utils/core.typ": *
== <NAME>
#th(label: "stdvol-sfinite")[
Классический объем#rf("volume-examples", "stdvol") $lambda_m$ на ячейках#rf("def-cell") $Pp^m$#rf("def-R-cells") --- $sigma$-конечная#rf("def-sfinite") мера#rf("def-measure", "measure").
]
#proof[
Надо проверить счетную полуаддитивность#rf("measure-semiadditive") на $Pp^m$: $ (a, b] subset Union_(n = 1)^oo (a_n, b_n] ==> lambda_m (a, b] <= sum_(n = 1)^oo lambda_m (a_n, b_n], $
где $a, b, a_n, b_n in RR^m$.
Возьмем $eps > 0$ и $[a', b] subset (a, b]$ так, чтобы $lambda_m (a', b] > lambda_m (a, b] - eps$, и возьмем $(a_n, b'_n) supset (a_n, b_n]$ так, чтобы $lambda_m (a_n, b'_n] < lambda_m (a_n, b_n] + eps / 2^n$. Тогда
$
[a', b] subset (a, b] subset Union_(n = 1)^oo (a_n, b_n] subset Union_(n = 1)^oo (a_n, b'_n).
$
У нас написано какое-то покрытие компакта#rf("def-compact")#rf("R-compact"). Выберем конечное подпокрытие,
$
(a', b] subset [a', b] subset Union_(i=1)^N (a_n_i, b'_n_i) subset Union_(i=1)^N (a_n_i, b'_n_i].
$
Оцениваем меру:
$
lambda_m (a, b] - eps < lambda_m (a', b] <=^rf("volume-props", "semiadditive")
sum_(i = 1)^N lambda_m (a_n_i, b'_n_i] < \ < sum_(i = 1)^N (lambda_m (a_n_i, b_n_i] + eps / 2^(n_i)) < sum_(n = 1)^oo lambda_m (a_n, b_n] + eps.
$
Значит $lambda_m (a, b] < 2 eps + sum_(n = 1)^oo lambda_m (a_n, b_n]$. Устремим $eps$ к нулю и получим требуемое.
]
#def(label: "def-lmeasure")[
_<NAME>_ $lambda_m$ --- это стандартное продолжение#rf("def-standard-continuation") классического объема#rf("volume-examples", "stdvol") с полукольца#rf("def-semiring") ячеек#rf("def-cell") $Pp^m$#rf("def-R-cells") (можно брать $Pp_QQ^m$#rf("def-R-cells")) на $sigma$-алгебру#rf("def-salgebra") $Ll^m$, где $Ll^m$ --- _лебеговская $sigma$-алгебра_.
]
#notice(label: "lmeasure-through-inf")[
Если $A in Ll^m$, то
$
lambda_m A
=^(rf("def-external-measure") rf("def-standard-continuation"))
inf {sum_(k = 1)^oo lambda_m P_k: P_k in Pp^m and A subset Union_(k = 1)^oo P_k}.
$
]
#props(label: "lmeasure-props")[
1. #sublabel("open-measurable")
Открытые множества измеримы и
#sublabel("open-measure-positive")
мера непустого открытого множества положительна.
2. #sublabel("closed-measurable")
Замкнутые множества измеримы и
#sublabel("point-zero")
мера одноточечного множества равна нулю.
3. #sublabel("bounded-finite")
Мера измеримого ограниченного множества конечна.
4. #sublabel("measurable-union-of-finite")
Всякое измеримое множество --- это дизъюнктное объединение счетного числа множеств конечной меры.
5. #sublabel("between-measurable-measurable")
Пусть $E subset RR^m$. Если $forall eps > 0 space exists "измеримые множества" A_eps, B_eps$, такие, что $A_eps subset E subset B_eps$ и $lambda(B_eps without A_eps) < eps$, то $E$ измеримо.
_Это свойство верно для любой полной меры на $sigma$-алгебре, не только для меры Лебега._
6. #sublabel("eps-bounded-measurable")
Пусть $E subset RR^m$. Если $forall eps > 0$, найдется $B_eps supset E$, такое, что $lambda B_eps < eps$, то $E$ измеримо, и $lambda E = 0$.
7. #sublabel("union-of-zero-zero")
Счетное объединение множеств нулевой меры имеет меру 0.
8. #sublabel("countable-zero")
Счетное множество имеет нулевую меру.
9. #sublabel("zero-empty-interior")
Множество нулевой меры имеет пустую внутренность.
10. #sublabel("zero-cube-cover-eps-bounded")
Если $e$ --- множество нулевой меры, то $forall eps$ существуют такие кубические ячейки $Q_j$, что $e subset Union_(j=1)^oo Q_j$ и $sum_(j=1)^oo lambda Q_j < eps$.
11. #sublabel("plane-zero")
Пусть $m >= 2$, $H_j (c) = {x in RR^m : x_j = c}$ --- $(m - 1)$---мерная гиперплоскость. Тогда $lambda_m H_j (c) = 0$.
12. #sublabel("plane-union-subset-zero")
Любое множество, содержащееся в счетном объединении таких плоскостей, имеет нулевую меру.
13. #sublabel("measure-cell")
$lambda (a, b)^rf("def-cell") = lambda (a, b] = lambda [a, b]$.
]
#proof[
1. $Ll_m supset Bb(Pp^m) =^rf("borel-set-over-cells") Bb^m$, а $Bb^m$ содержит все открытые множества#rf("borel-set"). Если $G$ --- непустое открытое, то $exists a in G ==> exists overline(B)_r(a) subset G$. А еще $lambda_m G >= lambda_m ("кубическая ячейка"^rf("def-cell"))^rf("volume-examples", "stdvol") > 0$, и эта ячейка лежит в найденном $overline(B)_r(a)$.
2. Если есть одна точка, то можем взять ячейку#rf("def-cell") со стороной $epsilon$, тогда $ lambda(dot) <= lambda("ячейка со стороной " epsilon) =^rf("volume-examples", "stdvol") epsilon^n. $
3. Очевидно#rf("volume-examples", "stdvol")#rf("volume-props", "monotonous").
4. $RR^m = usb_(k = 1)^oo P_k$, где $P_k$ --- ячейка с единичными сторонами. Тогда $E = usb_(k = 1)^oo (P_k sect E)$, а $lambda(E sect P_k) <=_rf("volume-props", "monotonous") lambda P_k = 1$.
5.
$A := Union_(n=1)^oo A_(1/n)$ и $B := Sect_(n=1)^oo B_(1/n) ==> A subset E subset B$.
$
B without A subset B_(1/n) without A_(1/n)
==>^rf("volume-props", "monotonous")
lambda(B without A) <= lambda(B_(1/n) without A_(1/n)) < 1/n
==>
lambda(B without A) = 0
$
$
E without A subset B without A
==>_("полнота")^rf("def-complete-measure")
E without A space #[--- измеримо]
==>
E = (E without A)union.sq A space #[--- измеримо]. $
6. $A_eps = nothing$, подставляем А-шки в предыдущее свойство#rf("lmeasure-props", "eps-bounded-measurable") --- фиксируем результат. Если $E subset B_eps ==>^rf("volume-props", "monotonous") lambda E <= lambda B_eps < eps$.
7. Верно для любой меры на $sigma$-алгебре#rf("def-salgebra").
8. Так как это счетное объединение одноточечных множеств по предыдущему свойству#rf("lmeasure-props", "countable-zero").
9. Если $Int A$ --- не пустое, то $A supset Int A ==> lambda A >=^rf("volume-props", "monotonous") lambda Int A >^rf("lmeasure-props", "open-measure-positive") 0$, так как $Int A$ открыто.
10. $0 = lambda e =^rf("lmeasure-through-inf") inf {sum_(n = 1)^oo lambda P_n : P_n in Pp_QQ^m and e in Union_(n = 1)^oo P_n}$. Выберем такие $P_n$, что $sum_(n=1)^oo lambda P_n < eps$. Рассмотрим $P_n$. У нее длины сторон --- рациональные числа. Нарежем на кубики со стороной $1 / "НОК всех знаменателей"$.
11. Рассмотрим $A_n := (-n; n]^m sect H_j (c)$. Тогда $H_j (c) = Union_(n = 1)^oo A_n$. Достаточно проверить#rf("bottom-up-continious"), что $lambda A_n = 0$. $ A_n subset (-n; n] times (-n; n] ... times (-n; n] times (c - eps, c] times ... times (-n; n] $
Тогда $lambda A_n <= (2n)^(m - 1) eps ==>^("св-во 6") lambda A_n = 0$.
12. Свойство 11)#rf("lmeasure-props", "plane-zero")
7)#rf("lmeasure-props", "union-of-zero-zero")
\+ монотонность#rf("volume-props", "monotonous").
13. Знаем, что $(a, b) subset (a, b] subset [a, b]$, $[a, b] without (a, b) subset$ конечное объединение гиперплоскостей, поэтому $lambda([a, b] without (a, b)) =^rf("lmeasure-props", "plane-union-subset-zero") 0$.
]
#notice(label: "lmeasure-notes")[
1. #sublabel("unmeasurable-exist")
Существуют неизмеримые множества. Более того, любое множество положительной меры содержит неизмеримое подмножество.
2. #sublabel("uncountable-zero-exist")
Существуют несчетные множества нулевой меры. Например, при $m >= 2$ подойдет гипер-плоскость. При $m = 1$ подходит канторово множество (это про отрезок из которого выкидывают середину, и потом из оставшихся отрезков выкидывают середины и т.д. рекурсивно).
У канторова множества $K$ мера удовлетворяет
$ lambda K + 1/3 + 2 dot 1/9 + 4 dot 1/27 + ... = 1, $
откуда $lambda K = 0$.
Само множество несчетное: выкинем рациональные числа (их троичная запись неоднозначна). В троичной записи чисел из канторова множества нет единиц. Тогда есть биекция между $K$ и $[0, 1]$ заменой двоек на единицы и переинтерпретацией троичной записи как двоичной (можно вернуть рациональные числа для аккуратности).
]
#th(name: "регулярность меры Лебега", label: "lmeasure-regular")[
Пусть $E$ --- измеримое. Тогда $forall eps > 0$ существует открытое $G$ такое, что $E subset G$ и $lambda(G without E) < eps$.
]
#proof[
Пусть $lambda E < +oo$. Знаем, что
$
lambda E =^rf("lmeasure-through-inf") inf {sum_(k = 1)^oo lambda P_k : P_k #[--- ячейки] and E subset Union_(k = 1)^oo P_k}.
$
Возьмем такое покрытие $E subset Union_(n=1)^oo (a_n, b_n]$, что $sum_(n=1)^oo lambda (a_n, b_n] < lambda E + eps$.
Возьмем $(a_n, b'_n) supset (a_n, b_n]$, т.ч. $lambda (a_n, b'_n) < lambda (a_n, b_n] + eps/(2^n) $.
Пусть $G = Union_(n=1)^oo (a_n, b'_n)$ --- открытое, $G supset E$.
$lambda G <=^rf("volume-props", "monotonous''") sum_(n=1)^oo lambda (a_n, b'_n) <= sum_(n=1)^oo (lambda (a_n, b_n] + eps/(2^n)) = eps + sum_(n=1)^oo lambda (a_n, b_n] < 2eps + lambda E$.
Поэтому $lambda (G without E) = lambda G - lambda E < 2 eps$.
Пусть $lambda E = +oo$. Тогда#rf("def-sfinite")#rf("stdvol-sfinite") $E = usb_(n = 1)^oo E_n$, где $lambda E_n < +oo$. Возьмем открытое $G_n supset E_n$, такое, что $lambda (G_n without E_n) < eps / 2^n$. Тогда $G := Union_(n = 1)^oo G_n$ подходит.
$
G without E subset Union_(n = 1)^oo (G_n without E_n) ==> lambda (G without E) <=^rf("measure-semiadditive") sum_(n = 1)^oo lambda (G_n without E_n) < sum_(n = 1)^oo eps/2^n = eps.
$
]
#follow(label: "lmeasure-regular-follow")[
1. #sublabel("regular-but-with-closed") Для любого измеримого множества найдется замкнутое $F subset E$ такое, что $lambda(E without F) < eps$.
2. $E$ --- измеримое. Тогда
#sublabel("lmeasure-through-open")
$ lambda E = inf{lambda G: G #[--- открытое и ] G supset E} $
#sublabel("lmeasure-through-closed")
$ lambda E = sup{lambda F: F #[--- замкнутое и ] F subset E} $
#sublabel("lmeasure-through-compact")
$ lambda E = sup{lambda K: K #[--- компакт и ] K subset E} $
3. #sublabel("measurable-through-compact-tower") $E$ --- измеримо. Тогда существует такая последовательность компактов $K_1 subset K_2 subset ...$, вложенных друг в друга, и $e$ --- множество нулевой меры, что $E = Union_(n=1)^oo K_n union e$.
]
#proof[
1. Давайте возьмем $X without E$ и по нему открытое $G$, которое накрывает $X without E$, такое, что $lambda(underbrace(G without (X without E), E without (X without G))) < eps$. Положим $F = X without G$. Оно подходит.
2. Про компакты: давайте рассмотрим $K_n := [-n, n]^m sect F$, где $F$ --- замкнутое. Тогда это компакт#rf("R-compact"). $K_1 subset K_2 subset ...$ и $Union_(n=1)^oo K_n = F ==>_("непр.\nснизу")^rf("bottom-up-continious") lambda K_n --> lambda F$.
3. Пусть $lambda E < +oo$.
Найдется#rf("lmeasure-regular-follow", "lmeasure-through-compact")
$tilde(K)_n subset E$, такое, что $lambda tilde(K)_n + 1/n > lambda E$, $Union_(n=1)^oo tilde(K)_n subset E$.
$
lambda E >=^rf("measure-semiadditive")
lambda(Union_(n=1)^oo tilde(K)_n) >=
lambda tilde(K)_n > lambda E - 1/n
==>
lambda(Union tilde(K)_n) = lambda E
==>
lambda (underbrace(E without Union tilde(K)_n, e)) = 0. $
Пусть $lambda E = +oo$. Тогда#rf("def-sfinite")#rf("def-lmeasure") $E = usb_(n = 1)^oo E_n$, где $lambda E_n < +oo$, $E_n = Union_(j = 1)^oo K_(n j) union e_n$, $e = Union_(n = 1)^oo e_n$, $E = Union_(n = 1)^oo Union_(j = 1)^oo K_(n j) union e_n$ ($lambda e =^rf("lmeasure-props", "union-of-zero-zero") 0$). $E = Union_(n=1)^oo Union_(j=1)^oo K_(n j) union e$.
]
#th(label: "lmeasure-shift-invariant")[
При сдвиге множества, его измеримость сохраняется, его мера не меняется.
]
#proof[
$mu E := lambda (E + v)$ --- новая мера, где $v$ --- вектор, на который мы сдвигаем. Тогда $mu$ и $lambda$ совпадают на ячейках#rf("def-cell"), а по единственности продолжения меры#rf("standard-continuation-unique"), $mu = lambda$. Отмечу, что они определились на одних и тех же множествах: в принципе интуитивно #strike[но не очевидно. Чуть позже появится более общая теорема, которая это объяснит.] и очевидно.
]
#th(label: "shift-invariant-is-lmeasure")[
Пусть $mu$ --- мера, заданная на $Ll^m$#rf("def-lmeasure") и такая, что:
1. $mu$ инварианта относительно сдвига.
2. $mu$ конечна на ячейках#rf("def-cell") (или более сильно, $mu$ конечна на ограниченных измеримых множествах).
Тогда $exists k in [0, +oo)$, такое, что $mu = k lambda$ (то есть $mu E = k lambda E space forall E in Ll^m$).
]
#proof[
$Q := (0, 1]^m space k := mu Q$
- Случай 1 ($k = 1$): надо доказать, что $mu = lambda$. По единственности продолжения#rf("standard-continuation-unique") достаточно проверить, что $mu P = lambda P space forall P in Pp_(QQ)^m$.
$P$ разбивается на кубические ячейки со стороной $1/n$, где $n$ --- это НОК знаменателей длин сторон $P$. Поэтому нам достаточно проверить, что $ mu (0, 1/n]^m = lambda (0, 1/n]^m = 1/n^m. $ Представим $Q = usb_(k=1)^(n^m)$ (сдвиги $(0, 1/n]^m)$. Значит, что $ 1 = mu Q = n^m dot mu (0, 1/n]^m ==> mu (0, 1/n]^m = 1/n^m =^rf("volume-examples", "stdvol") lambda (0, 1/n]^m. $
- Случай 2 ($k > 0$): возьмем $tilde(mu) := 1/k mu$, то есть $(tilde(mu) E = (mu E) / k)$. $tilde(mu) Q = 1$, $tilde(mu)$ --- мера, инвариантна относительно сдвигов, поэтому $tilde(mu) = lambda$.
- Случай 3 ($k = 0$): $RR^m = usb_(k=1)^oo$ сдвиги $Q$, поэтому $mu RR^m = 0 ==> mu = 0 dot lambda$.
]
#th(label: "cdiff-image-measurable")[
Пусть $G subset RR^m$ --- открытое, $Phi: G --> RR^m$ непрерывно диффериенцируемо.
1. Если $lambda e = 0$, то $lambda(Phi(e)) = 0$.
2. Если $E subset G$ измеримо, то $Phi(E)$ --- измеримо.
]
#proof[
1. *Случай 1*: $e subset P subset Cl P subset G$, $P$ --- ячейка.
$Cl P$ --- компакт, а $norm(Phi'(x))$ непрерывна на $Cl P$, поэтому $norm(Phi'(x))$ ограничена на $Cl P$. Пусть $norm(Phi'(x)) <= M space forall x in Cl P$, поэтому если $x, y in Cl P$, то#rf("lagrange") $norm(Phi(x) - Phi(y)) <= norm(Phi'(xi)) norm(x - y) <= M norm(x - y)$. Покроем#rf("lmeasure-props", "zero-cube-cover-eps-bounded") $e$ кубическими ячейками $Q_j$ так, что $sum lambda Q_j < eps$ и пусть $h_j$ длина стороны $Q_j$. $
x, y in Q_j ==>
norm(x - y) <= sqrt(m) dot h_j ==>
norm(Phi(x) - Phi(y)) <= M sqrt(m) dot h_j ==> \ ==>
Phi(Q_j) "содержится в шаре радиуса" M sqrt(m) h_j.
$
Тогда $Phi(Q_j)$ накрылось кубиком со стороной $M sqrt(m) h_j$:
$
Phi(e) subset Union_(j = 1)^oo Phi(Q_j) subset Union_(j = 1)^oo ("кубик со стороной" 2 M sqrt(m) h_j).
$
$
lambda("кубик со стороной" 2 M sqrt(m) h_j) =^#rf("volume-examples", "stdvol") (2 M sqrt(m) h_j)^m = (2M sqrt(m))^m lambda Q_j.
$ Тогда сумма мер кубиков равна $sum (2M sqrt(m))^m lambda Q_j < (2 M sqrt(m))^m eps$, значит#rf("lmeasure-props", "eps-bounded-measurable") $Phi(e)$ измеримо и $lambda(Phi(e)) = 0$.
*Случай 2*: $e subset G$, $G = usb_(k=1)^oo P_k$, такие, что $P_k in Pp_(QQ)^m$ и $P_k subset Cl P_k subset G$. $ e = usb_(k=1)^oo (P_k sect e), space P_k sect e subset P_k ==>_("сл. 1") lambda(Phi(P_k sect e)) = 0 ==> lambda(Phi(underbrace(usb(P_k sect e), e))) = 0. $
2. $E = e union Union_(n=1)^oo K_n$, где $K_n$ --- компакт и $lambda e = 0$. Поэтому $Phi(E) = underbrace(Phi(e), "измеримо") union Union_(n=1)^oo Phi(K_n)$, последнее --- компакты#rf("continious-image-compact"), поэтому измеримы#rf("lmeasure-props", "closed-measurable").
]
#notice[
Для просто диффериенцируемых отображений это неверно.
]
#th(label: "lmeasure-move-invariant")[
<NAME> инвариантна относительно движения.
]
#proof[
Пусть $U: RR^m --> RR^m$ --- поворот (линейное отображение), пусть $mu E := lambda(U(E))$, $E in Ll^m$
- $mu$ конечна#rf("lmeasure-props", "bounded-finite") на ограниченных множествах, так как ограниченые множества переходят в ограниченные.
- $mu$ инвариантна относительно сдвигов#rf("lmeasure-shift-invariant") $forall v in RR^m$, так как можно повернуть, сдвинуть (возможно, на другой вектор, после отображения), и повернуть обратно.
- $mu(E + v) = lambda (U(E + v)) = lambda(U(E) + U(v)) =^rf("lmeasure-shift-invariant") lambda(U(E)) = mu E$, поэтому#rf("shift-invariant-is-lmeasure") $mu = k lambda$, но единичный шар переходит в себя при повороте (движение сохраняет расстояние между точками), поэтому на нем $mu = lambda ==> k = 1$.
]
#th(name: "Об изменении меры Лебега при линейном отображении", label: "lin-map-lmeasure")[
Пусть $T: RR^m --> RR^m$ --- линейное отображение, тогда $lambda(T(E)) = abs(det(T)) dot lambda E$
]
#proof[
$mu E := lambda(T(E))$ --- инвариантна относительно сдвигов, по той же причине что и в предыдущей теореме, и конечна на ограниченных множествах, поэтому#rf("shift-invariant-is-lmeasure") $mu = k lambda$, где $k = lambda(T((0, 1]^m)) = abs(det T).$
]
#pr(name: "Существование неизмеримого множества", label: "unmeasurable-exist")[
Рассмотрим $lambda$ на $RR$. Будем говорить, что $x sim y$ если $x - y in QQ$. Это отношение эквивалентности, $RR$ разбивается на классы. Выберем по одному элементу из каждого класса, который попадает в $[0, 1)$. $A$ --- множество выбранных элементов. Тогда $A$ неизмеримо.
]
#proof[
Пусть множество $A$ --- измеримо. Рассмотрим случаи.
Пусть $lambda A = 0$. Тогда $ [0, 1) subset Union_(r in QQ) (A + r) = RR. $ Но $lambda (A + r) =^rf("lmeasure-move-invariant") lambda A = 0$, а так как справа написано счетное объединение множеств нулевой меры, $lambda RR = 0$. Противоречие.
Пусть $lambda A > 0$. Рассмотрим $ usb_(r in Q \ 0 < r < 1) (A + r) subset (0, 2). $ Значит, $ 2 = lambda (0, 2) >= sum_(r in QQ \ 0 < r < 1) lambda (A + r) = +oo. $
Снова противоречие.
Значит множество $A$ неизмеримо.
]
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/linebreak-obj_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test punctuation after math equations.
#set page(width: 85pt)
We prove $1 < 2$. \
We prove $1 < 2$! \
We prove $1 < 2$? \
We prove $1 < 2$, \
We prove $1 < 2$; \
We prove $1 < 2$: \
We prove $1 < 2$- \
We prove $1 < 2$– \
We prove $1 < 2$— \
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/funarray/0.3.0/examples/doc.typ | typst | Apache License 2.0 | #import "@preview/idwtet:0.2.0"
#set page(header: text(gray, 9pt)[`funarray` package documentation])
#show: idwtet.init.with(
code-font-size: 11pt,
eval-scope: (
funarray: (
value: {import "../funarray.typ" as funarray; funarray},
code: "#import \"@preview/funarray:0.3.0\""
)
))
= `funarray` Package
This package provides some convinient functional functions for typst to use on arrays. Let us import the package and define
```typst
#import "@preview/funarray:0.3.0"
```
== chunks
The chunks function translates the array to an array of array. It groups the elements to chunks of a given size and collects them in an bigger array.
```typst-ex
#let a = (1, "not prime", 2, "prime", 3, "prime", 4, "not prime", 5, "prime")
#funarray.chunks(a, 2)
```
== unzip
The unzip function is the inverse of the zip method, it transforms an array of pairs to a pair of vectors.
```typst-ex
#let a = (
(1, "not prime"),
(2, "prime"),
(3, "prime"),
(4, "not prime"),
(5, "prime"),
)
#funarray.unzip(a)
```
== cycle
The cycle function concatenates the array to itself until it reaches a given size.
```typst-ex
#let a = range(5)
#funarray.cycle(a, 8)
```
Note that there is also the functionality to concatenate with `+` and `*` in typst.
== windows and circular-windows
This function provides a running window
```typst-ex
#let a = range(5)
#funarray.windows(a, 3)
```
whereas the circular version wraps over.
```typst-ex
#let a = range(5)
#funarray.circular-windows(a, 3)
```
== partition and partition-map
The partition function seperates the array in two according to a predicate function. The result is an array with all elements, where the predicate returned true followed by an array with all elements, where the predicate returned false.
```typst-ex
#let a = (
(1, "not prime"),
(2, "prime"),
(3, "prime"),
(4, "not prime"),
(5, "prime"),
)
#let (primes, nonprimes) = funarray.partition(a, x => x.at(1) == "prime")
#primes
```
There is also a partition-map function, which after partition also applies a second function on both collections.
```typst-ex
#let a = (
(1, "not prime"),
(2, "prime"),
(3, "prime"),
(4, "not prime"),
(5, "prime"),
)
#let (primes, nonprimes) = funarray.partition-map(
a,
x => x.at(1) == "prime",
x => x.at(0)
)
#primes
```
== group-by
This functions groups according to a predicate into maximally sized chunks, where all elements have the same predicate value.
```typst-ex
#let f = (0,0,1,1,1,0,0,1)
#funarray.group-by(f, x => x == 0)
```
== flatten
Typst has a `flatten` method for arrays, however that method acts recursively. For instance
```typst-ex
#(((1,2,3), (2,3)), ((1,2,3), (1,2))).flatten()
```
Normally, one would only have flattened one level. To do this, we can use the typst array concatenation method `+`, or by folding, the `sum` method for arrays:
```typst-ex
#(((1,2,3), (2,3)), ((1,2,3), (1,2))).sum()
```
To handle further depth, one can use flatten again, so that in our example:
```typst-ex
#{
(
((1,2,3), (2,3)), ((1,2,3), (1,2))
).sum().sum() == (
((1,2,3), (2,3)), ((1,2,3), (1,2))
).flatten()
}
```
== take-while and skip-while
These functions do exactly as they say.
```typst-ex
#let f = (0,0.5,0.2,0.8,2,1,0.1,0,-2,1)
#funarray.take-while(f, x => x < 1)
#funarray.skip-while(f, x => x < 1)
```
= Unsafe functions
The core functions are defined in `funarray-unsafe.typ`. However, assertions (error checking) are not there and it is generally not being advised to use these directly. Still, if being cautious, one can use the imported `funarray-unsafe` module in `funarray(.typ)`. All function names are the same.
To do this from the package, do as follows:
```typst-ex
#funarray.funarray-unsafe.chunks(range(10), 3)
``` |
https://github.com/BeiyanYunyi/Architectural-Technology-and-Art-Paper | https://raw.githubusercontent.com/BeiyanYunyi/Architectural-Technology-and-Art-Paper/main/nju-thesis/utils/metavalue.typ | typst | MIT License | #let prefix = "metavalue:"
// 设置一个类似全局变量的 metavalue
#let metavalue(key, value) = [
#metadata(value) #label(prefix + key)
]
// 查询该 metavalue,默认取最后一个,没找到则回调 none
#let query-metavalue(key, callback) = {
locate(loc => {
let last = query(label(prefix + key), loc).at(-1, default: none)
if (last != none) {
callback(last.value)
} else {
callback(none)
}
})
} |
https://github.com/v411e/optimal-ovgu-thesis | https://raw.githubusercontent.com/v411e/optimal-ovgu-thesis/main/template.typ | typst | MIT License | #import "components.typ": body-font, sans-font, small-heading, number-until-with, variable-pagebreak, author-fullname
#import "titlepage.typ": oot-titlepage
#import "acknowledgement.typ": oot-acknowledgement
#import "abstract.typ": oot-abstract
#import "disclaimer.typ": oot-disclaimer
#import "expose.typ": oot-expose
#let optimal-ovgu-thesis(
title: "",
author: none,
lang: "en",
is-doublesided: none,
body,
) = {
set document(title: title, author: author-fullname(author))
set page(
margin: (left: 30mm, right: 30mm, top: 27mm, bottom: 27mm),
numbering: "1",
number-align: center,
)
set text(
font: body-font,
size: 11pt,
lang: lang
)
show math.equation: set text(weight: 400)
show figure.caption: emph
show figure.where(
kind: table
): set figure.caption(position: top)
show figure.where(
kind: raw
): set figure.caption(position: top)
set table(
stroke: gray
)
show heading: set text(font: sans-font)
show heading.where(level: 1): h => [
#variable-pagebreak(is-doublesided)
#h
]
// Apply custom numbering to headings
set heading(numbering: number-until-with(3, "1.1"))
// Make nested headings apply small-heading style
show heading.where(level: 4) : small-heading()
show heading.where(level: 5) : small-heading()
show heading.where(level: 6) : small-heading()
show heading.where(level: 7) : small-heading()
show par: set block(spacing: 1em)
set par(
justify: true,
leading: 1em, // Set the space between lines in text
first-line-indent: 1em
)
show raw.where(block: true): it => align(start, block(
fill: luma(250),
stroke: 0.6pt + luma(200),
inset: 8pt,
radius: 3pt,
width: 100%,
it
))
show raw.where(block: true): set text(size: 8pt)
show raw.where(block: true): set par(leading: 0.6em)
// Table of contents
set outline(indent: 2em)
show outline: outline => [
#show heading: heading => [
#text(font: body-font, 1.5em, weight: 700, heading.body)
#v(15mm)
]
#outline
#variable-pagebreak(is-doublesided)
]
body
}
|
https://github.com/pku-typst/awesome-PKU-Typst | https://raw.githubusercontent.com/pku-typst/awesome-PKU-Typst/main/README.md | markdown | MIT License | # Awesome PKU Typst [](https://awesome.re)
> 这是一个收集北京大学 Typst 相关资源的项目。欢迎贡献。
[English](./README-en.md) | 简体中文
## 内容
待完善
|
https://github.com/cnaak/blindex.typ | https://raw.githubusercontent.com/cnaak/blindex.typ/main/README.md | markdown | MIT License | # Blindex: Index-making of Biblical literature citations in Typst
Blindex (`blindex:0.1.0`) is a Typst package specifically designed for the generation of
indices of Biblical literature citations in documents. Target audience includes theologians and
authors of documents that frequently cite biblical literature.
## Index Sorting Options
The generated indices are gathered and sorted by Biblical literature books, which can be ordered
according to various Biblical literature book ordering conventions, including:
- `"LXX"` -- The Septuagint;
- `"Greek-Bible"` -- Septuagint + New Testament (King James);
- `"Hebrew-Tanakh"` -- The Hebrew (Torah + Neviim + Ketuvim);
- `"Hebrew-Bible"` -- The Hebrew Tanakh + New Testament (King James);
- `"Protestant-Bible"` -- The Protestant Old + New Testaments;
- `"Catholic-Bible"` -- The Catholic Old + New Testaments;
- `"Orthodox-Bible"` -- The Orthodox Old + New Testaments;
- `"Oecumenic-Bible"` -- The Jewish Tanakh + Old Testament Deuterocanonical + New Testament;
- `"code"` -- All registered Biblical literature books: All Protestant + All Apocripha.
## Biblical Literature Abbrevations
It is common practice among theologians to refer to biblical literature books by their
abbreviations. Practice shows that abbreviation conventions are language- and tradition-
dependent. Therefore, `blindex` usage reflects this fact, while offering a way to input
arbitrary language-tradition abbreviations, in the `lang.typ` source file.
### Language and Traditions (Variants)
The `blindex` implementation generalizes the concept of __tradition__ (in the context of
biblical literature book abbreviation bookkeeping) as language **variants**, since the software
can have things such as a "default" of "n-char" variants.
As of the current release, supported languages include the following few ones:
Language | Variant | Description | Name
--- | --- | --- | ---
English | 3-char | A 3-char abbreviations | `en-3`
English | Logos | Used in `logos.com` | `en-logos`
Portuguese (BR) | Protestant | Protestant for Brazil | `br-pro`
Portuguese (BR) | Catholic | Catholic for Brazil | `br-cat`
Additional language-variations can be added to the `lang.typ` source file by the author and/or
by pull requests to the `dev` branch of the (UNFORKED!) development repository
`https://github.com/cnaak/blindex.typ`.
## Low-Level Indexing Command
The `blindex` library has a low-level, index entry marking function `#blindex(abrv, lang,
entry)`, whose arguments are (abbreviation, language, entry), as in:
```typst
"the citation..." #blindex("1Thess", "en", [1.1--3]) citation's typesetting...
```
Following the usual index making strategy in Typst, this user `#blindex` command only adds the
index-marking `#metadata` in the document, without producing any visible typeset output.
Biblical literature index listings can be generated (typeset) in arbitrary amounts and locations
throughout the document, just by calling the user `#mkIndex` command:
```typst
#mkIndex()
```
Optional arguments control style and sorting convention parameters, as exemplified below.
## Higher-Level Quoting-Indexing Commands
The library also offers higher-level functions to assemble the entire (i) citation typesetting,
(ii) index entry, (iii) citation typesetting, and (iv) bibliography entrying (with some
typesetting (styling) options), of the passage. Such commands are `#iQuot(...)` and
`#bQuot(...)`, respectively for **inline** and **block** quoting of Biblical literature, with
automatic indexing and bibliography citation. Mandatory arguments are identical for either
command:
```typst
paragraph text...
#iQuot(body, abrv, lang, pssg, version, cited)
more text...
// Displayed block quote of Biblical literature:
#bQuot(body, abrv, lang, pssg, version, cited)
```
In which:
- `body` (`content`) is the quoted biblical literature text;
- `abrv` (`string`) is the book abbreviation according to the
- `lang` (`string`) language-variant (see above);
- `pssg` (`content`) is the quoted text passage --- usually chapter and verses --- as they will
appear in the text and in the biblical literature index;
- `version` (`string`) is a translation identifier, such as `"LXX"`, or `"KJV"`; and
- `cited` (`label`) is the corresponding bibliography entry label, which can be constructed
through:
`label("bib-key")`, where `bib-key` is the bibliographic entry key, in the bibliography database
--- whether `bibTeX` or `Hayagriva`.
## Higher-Level Example
```typst
#set page(paper: "a7", fill: rgb("#eec"))
#import "@preview/blindex:0.1.0": *
The Septuagint (LXX) starts with #iQuot([ΕΝ ἀρχῇ ἐποίησεν ὁ Θεὸς τὸν οὐρανὸν καὶ τὴν γῆν.],
"Gen", "en", [1.1], "LXX", label("2012-LXX-SBB")).
#pagebreak()
Moreover, the book of Odes begins with: #iQuot([ᾠδὴ Μωυσέως ἐν τῇ ἐξόδῳ], "Ode", "en", [1.0],
"LXX", label("2012-LXX-SBB")).
#pagebreak()
= Biblical Citations
Books are sorted following the LXX ordering.
#mkIndex(cols: 1, sorting-tradition: "LXX")
#pagebreak()
#bibliography("test-01-readme.yml", title: "References", style: "ieee")
```
The listing of the bibliography file, `test-01-readme.yml`, as shown in the example, is:
```yml
2012-LXX-SBB:
type: book
title:
value: "Septuaginta: Edição Acadêmica Capa dura – Edição de luxo"
sentence-case: "Septuaginta: edição acadêmica capa dura – edição de luxo"
short: Septuaginta
publisher: Sociedade Bíblica do Brasil, SBB
editor: <NAME>
affiliated:
- role: collaborator
names: [ "<NAME>", ]
pages: 2240
date: 2012-01-11
edition: 1
ISBN: 978-3438052278
language: el
```
This example results in a 4-page document like this one:

## Citing
This package can be cited with the following bibliography database entry:
```yml
blindex-package:
type: Web
author: <NAME>.
title:
value: "Blindex: Index-making of Biblical literature citations in Typst"
short: "Blindex: Index-making in Typst"
url: https://github.com/cnaak/blindex.typ
version: 0.1.0
date: 2024-08
```
|
https://github.com/akrantz01/resume | https://raw.githubusercontent.com/akrantz01/resume/main/main.typ | typst | MIT License | #import "template/heading.typ": header
#import "template/layout.typ": load-layout
#import "template/overrides.typ": apply-overrides
#import "template/sections.typ": sections
#let layout = load-layout(sys.inputs.at("layout", default: none))
#let data = apply-overrides(
yaml("data.yml"),
layout.at("overrides", default: (:)),
)
#let author = {
let value = data.author.links.find(link => link.type == "email")
if value != none {
data.author.name + " <" + value.email + ">"
} else {
data.author.name
}
}
#set document(
title: eval(layout.title, mode: "markup", scope: (author: data.author.name)),
author: author,
keywords: ("resume", "cv"),
)
#set page(
paper: "a4",
margin: (x: 0.5cm, y: 0.5cm),
)
#set text(
size: 9.75pt,
font: "Montserrat",
)
#set list(indent: 0.5em, marker: [•])
#show link: underline
#show link: set underline(offset: 1.5pt)
#header(data.author.name, settings: layout.settings, links: data.author.links)
#sections(layout, data)
#place(
bottom + center,
dx: 1.5em,
block[
#set text(size: 4pt, font: "Fira Code Retina")
Last updated on #datetime.today().display()
],
)
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/docs/guide/gallery.typ | typst | MIT License | #import "../../src/quill.typ": *
#set page(width: 18cm, height: auto, margin: 0mm)
#let gallery = {
set raw(lang: "typc")
table(
align: center + horizon,
columns: (1fr, 1fr, 1.3fr, 1.1fr, 1fr, 1.48fr),
column-gutter: (0pt, 0pt, 2.5pt, 0pt, 0pt),
[Normal gate], quantum-circuit(1, gate($H$), 1), raw("gate($H$), $H$"),
[Round gate], quantum-circuit(1, gate($X$, radius: 100%), 1), raw("gate($X$, \nradius: 100%)"),
[D-shaped gate], quantum-circuit(1, gate($Y$, radius: (right: 100%)), 1), raw("gate($Y$, radius: \n(right: 100%))"),
[Meter], quantum-circuit(1, meter(), 1), raw("meter()"),
[Meter with \ label], quantum-circuit(1, meter(label: $lr(|±〉)$), 1), raw("meter(label: \n$lr(|±〉)$)"),
[Phase gate], quantum-circuit(1, phase($α$), 1), raw("phase($α$)"),
[Control], quantum-circuit(1, ctrl(0), 1), raw("ctrl(0)"),
[Open control], quantum-circuit(1, ctrl(0, open: true), 1), raw("ctrl(0, open: true)"),
[Target], quantum-circuit(1, targ(), 1), raw("targ()"),
[Swap target], quantum-circuit(1, swap(0), 1), raw("swap(0)"),
[Permutation \ gate], quantum-circuit(1, permute(2,0,1), 1, [\ ], 3, [\ ], 3), raw("permute(2,0,1)"),
[Multi-qubit \ gate], quantum-circuit(1, mqgate($U$, n: 3), 1, [\ ], 3, [\ ], 3), raw("mqgate($U$, n: 3)"),
[lstick], quantum-circuit(lstick($|psi〉$), 2), raw("lstick($|psi〉$)"),
[rstick], quantum-circuit(2, rstick($|psi〉$)), raw("rstick($|psi〉$)"),
[Multi-qubit \ lstick], quantum-circuit(row-spacing: 10pt, lstick($|psi〉$, n: 2), 2, [\ ], 3), raw("lstick($|psi〉$, \nn: 2)"),
[Multi-qubit \ rstick], quantum-circuit(row-spacing: 10pt,2, rstick($|psi〉$, n: 2, brace: "]"),[\ ], 3), raw("rstick($|psi〉$, \nn: 2, brace: \"]\")"),
[midstick], quantum-circuit(1, midstick("yeah"),1), raw("midstick(\"yeah\")"),
[Wire bundle], quantum-circuit(1, nwire(5), 1), raw("nwire(5)"),
[Controlled \ #smallcaps("z")-gate], quantum-circuit(1, ctrl(1), 1, [\ ], 1, ctrl(0), 1), [#raw("ctrl(1)") \ + \ #raw("ctrl(0)")],
[Controlled \ #smallcaps("x")-gate], quantum-circuit(1, ctrl(1), 1, [\ ], 1, targ(), 1), [#raw("ctrl(1)") \ + \ #raw("targ()")],
[Swap \ gate], quantum-circuit(1, swap(1), 1, [\ ], 1, targX(), 1), [#raw("swap(1)") \ + \ #raw("targX()")],
[Controlled \ Hadamard], quantum-circuit(1, mqgate($H$, target: 1), 1, [\ ], 1, ctrl(0), 1), [#raw("mqgate($H$,target:1)") \ + \ #raw("ctrl(0)")],
[Plain\ vertical\ wire], quantum-circuit(1, ctrl(1, show-dot: false), 1, [\ ], 3), raw("ctrl(1, show-dot: false)"),
[Meter to \ classical], quantum-circuit(1, meter(target: 1), 1, [\ ], setwire(2), 1, ctrl(0), 1), [#raw("meter(target: 1)") \ + \ #raw("ctrl(0)")],
[Classical wire], quantum-circuit(setwire(2), 3), raw("setwire(2)"), [Styled wire], quantum-circuit(setwire(1, stroke: green), 3), raw("setwire(1, stroke: green)"),
[Labels],
quantum-circuit(scale: 100%,
1, gate($Q$, label: (
(content: "b",pos:top),
(content:"b",pos:bottom),
( content: "a",
pos: left + top ),
( content: "c",
pos: right + top,
dy: 0pt, dx: 50% ),
)), 1
),
[#set text(size: .6em);```typc
gate($Q$, label: (
(content: "b",pos:top),
(content:"b",pos:bottom),
( content: "a",
pos: left + top ),
( content: "c",
pos: right + top,
dy: 0pt, dx: 50% ),
))
```
],
[Gate inputs \ and outputs],
quantum-circuit(scale: 80%,
1, mqgate($U$, n: 3, width: 5em,
inputs: (
(qubit: 0, n: 2, label: $x$),
(qubit: 2, label: $y$)
),
outputs: (
(qubit: 0, n: 2, label: $x$),
(qubit: 2, label: $y ⊕ f(x)$)
),
), 1, [\ ], 3, [\ ], 3
),
[#set text(size: .6em);```typc
mqgate($U$, n: 3, width: 5em,
inputs: (
(qubit:0, n:2, label:$x$),
(qubit:2, label: $y$)
),
outputs: (
(qubit:0, n:2, label:$x$),
(qubit:2, label:$y⊕f(x)$)
)
)```]
)
}
#rect(
stroke: none,
radius: 3pt,
inset: (x: 6pt, y: 6pt),
fill: white,
gallery
) |
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Maths_Expertes_Ex_29_05_2024.typ | typst | #import "@preview/bubble:0.1.0": *
#import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge
#import "@preview/cetz:0.2.2": canvas, draw, tree
#import "@preview/cheq:0.1.0": checklist
#import "@preview/typpuccino:0.1.0": macchiato
#import "@preview/wordometer:0.1.1": *
#import "@preview/tablem:0.1.0": tablem
#show: bubble.with(
title: "Maths Expertes",
subtitle: "29/05/2024",
author: "<NAME>",
affiliation: "<NAME>",
year: "2023/2024",
class: "Terminale B",
logo: image("JOJO_magazine_Spring_2022_cover-min-modified.png"),
)
#set page(footer: context [
#set text(8pt)
#set align(center)
#text("page "+ counter(page).display())
]
)
#set heading(numbering: "1.1")
#show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em)
= Exercice 4
==
$ U_n = A^n U_0 $
$ U_n = mat(3^n, 0; 0, 2^n;) times mat(1; 1) = mat(3^n;2^n) $
$ forall k gt 1 , lim_(n arrow +infinity) k^n = +infinity $
Ainsi $lim_(n arrow +infinity) 3^n = +infinity$
et $lim_(n arrow +infinity) 2^n = +infinity$
Par conséquent $(U_n)$ diverge
==
#linebreak()
$mat(0;0)$ est un état stable car $A times mat(0;0) = mat(0;0)$
= Exercice 6
==
$ U_(n+1) = mat(0, 1; -0.6, 0.2;) U_n $
$ U_n = mat(a_(n-1); a_n) $
==
$ U_n = A^(n-1) U_1 $
$ U_5 = mat(a_4; a_5) = A^5 U_1 = mat(4.4; 5.68) $
Ainsi $a_5=5.68$
|
|
https://github.com/Quaternijkon/Typst_Lab_Report | https://raw.githubusercontent.com/Quaternijkon/Typst_Lab_Report/main/theme.typ | typst | // #import "@preview/chic-hdr:0.4.0": *
#import "lib.typ": *
#let Heiti = ("Times New Roman", "Heiti SC", "Heiti TC", "SimHei")
#let Songti = ("Times New Roman", "Songti SC", "Songti TC", "SimSun")
#let Zhongsong = ("Times New Roman", "STZhongsong", "SimSun")
#let Xbs = ("Times New Roman", "FZXiaoBiaoSong-B05", "FZXiaoBiaoSong-B05S")
#let indent() = {
box(width: 2em)
}
#let info_key(body) = {
rect(width: 100%, inset: 2pt, stroke: none, text(font: Zhongsong, size: 16pt, body))
}
#let info_value(body) = {
rect(
width: 100%,
inset: 2pt,
stroke: (bottom: 1pt + black),
text(font: Zhongsong, size: 16pt, bottom-edge: "descender")[ #body ],
)
}
#let project(
course: "COURSE",
lab_name: "LAB NAME",
stu_name: "NAME",
stu_num: "1234567",
major: "MAJOR",
department: "DEPARTMENT",
date: (2077, 1, 1),
show_content_figure: false,
watermark: "",
body,
) = {
set page("a4",
margin: (x: 1.5cm,y: 2cm)
)
// 封面
align(center)[
#image("./assets/ustc-name.svg", width: 70%)
#v(1em)
// #set text(
// size: 26pt,
// font: Zhongsong,
// weight: "bold",
// )
// 课程名
#text(size: 25pt, font: Xbs)[
_#course _课程实验报告
]
// #v(1em)
// 报告名
#text(size: 22pt, font: Xbs)[
_#lab_name _
]
// #v(0.5em)
#image("./assets/USTC-NO-TEXT.svg", width: 60%)
// #v(0.5em)
// 个人信息
#grid(
columns: (40pt, 270pt,40pt),
rows: (40pt, 40pt),
gutter: 0pt,
info_key("学院"),
info_value(department),
rect(
width: 100%,
inset: 2pt,
stroke: (bottom: 1pt + black),
text(font: Zhongsong, size: 16pt, bottom-edge: "descender", fill: white)[#department.at(0)],
),
info_key("专业"),
info_value(major),
rect(
width: 100%,
inset: 2pt,
stroke: (bottom: 1pt + black),
text(font: Zhongsong, size: 16pt, bottom-edge: "descender", fill: white)[#major.at(0)],
),
info_key("姓名"),
info_value(stu_name),
rect(
width: 100%,
inset: 2pt,
stroke: (bottom: 1pt + black),
text(font: Zhongsong, size: 16pt, bottom-edge: "descender", fill: white)[#stu_name.at(0)],
),
info_key("学号"),
info_value(stu_num),
rect(
width: 100%,
inset: 2pt,
stroke: (bottom: 1pt + black),
text(font: Zhongsong, size: 16pt, bottom-edge: "descender", fill: white)[#stu_num.at(0)],
),
)
#v(2em)
// 日期
#text(font: Zhongsong, size: 14pt)[
#date.at(0) 年 #date.at(1) 月 #date.at(2) 日
]
]
pagebreak()
// 水印
set page(background: rotate(-60deg,
text(240pt, fill: rgb("#034ea110"), font:"Times New Roman")[
#strong()[#watermark]
]
),
)
// 目录
show outline.entry.where(level: 1): it => {
v(12pt, weak: true)
strong(it)
}
show outline.entry: it => {
set text(
font: Xbs,
size: 12pt,
)
it
}
outline(
title: text(font: Xbs, size: 16pt, fill: rgb("#034ea1"))[目录],
indent: auto,
)
if show_content_figure {
text(font: Xbs, size: 10pt)[
#i-figured.outline(title: [图表])
]
}
pagebreak()
set page(
columns: 2,
header: [
#set text(8pt)
#course -- #lab_name
#h(1fr) #text(font:Xbs,fill:rgb("#034ea1"))[USTC]
],
// number-align: right,
// numbering: "壹 / 壹",
)
set page(
footer: context {
// 获取当前页码
let i = counter(page).at(here()).first()
// 根据奇偶页设置对齐方式
let is-odd = calc.odd(i)
let aln = if is-odd { right } else { left }
// 获取所有一级和二级标题
let level1_headings = heading.where(level: 1)
let level2_headings = heading.where(level: 2)
// 检查当前页是否包含一级标题
if query(level1_headings).any(it => it.location().page() == i) {
// 仅显示页码
return align(aln)[#text(fill: rgb("#034ea1"), size: 2em)[#i]]
}
// 检查当前页是否包含二级标题
if query(level2_headings).any(it => it.location().page() == i) {
// 获取当前的一级标题(在当前位置之前的最后一个)
let previous_level1 = query(level1_headings.before(here())).last()
let gap = 0.5em // 调整间距
let chapter = upper(text(size: 0.68em, previous_level1.body))
// 显示页码和一级标题
if is-odd {
return align(aln)[
#grid(
columns: (40em,2em),
[#chapter],
text(fill: rgb("#034ea1"))[#i],
)
]
} else {
return align(aln)[
#grid(
columns: (2em,40em),
text(fill: rgb("#034ea1"))[#i],
[#chapter],
)
]
}
}
// 当前页既不包含一级标题也不包含二级标题
// 获取当前的一级和二级标题
let previous_level1 = query(level1_headings.before(here())).last()
let previous_level2_query = query(level2_headings.before(here()))
let previous_level2 = if previous_level2_query.len() > 0 {
previous_level2_query.last()
} else {
none
}
// let gap = 0.01em // 调整间距
let chapter = upper(text(size: 0.68em, previous_level1.body))
// 检查是否存在二级标题
if previous_level2 != none {
let section = upper(text(size: 0.6em, previous_level2.body)) // 二级标题字号更小
// 显示页码、一级标题和二级标题,二级标题在一级标题下方
if is-odd {
return align(aln)[
#grid(
columns: (40em,2em),
rows: (1fr,1fr,1fr),
gutter: 0pt,
[#chapter],
grid.cell(
rowspan: 2,
align(horizon)[#text(fill: rgb("#034ea1"))[#i]]
),
[#section],
)
]
} else {
return align(aln)[
#grid(
columns: (2em,40em),
rows: (1fr,1fr,1fr),
gutter: 0pt,
grid.cell(
rowspan: 2,
align(horizon)[#text(fill: rgb("#034ea1"))[#i]]
),
[#chapter],
[#section],
)
]
}
} else {
// 如果没有二级标题,仅显示页码和一级标题
if is-odd {
return align(aln)[
#grid(
columns: (40em,2em),
[#chapter],
text(fill: rgb("#034ea1"))[#i],
)
// #chapter
// #v(gap)
// #i
]
} else {
return align(aln)[
#grid(
columns: (2em,40em),
text(fill: rgb("#034ea1"))[#i],
[#chapter],
)
// #i
// #v(gap)
// #chapter
]
}
}
},
)
// 页眉页脚设置
// show: chic.with(
// chic-header(
// left-side: smallcaps(
// text(size: 10pt, font: Xbs)[
// #course -- #lab_name
// ],
// ),
// right-side: text(size: 10pt, font: Xbs)[
// #chic-heading-name(dir: "prev")
// ],
// side-width: (60%, 0%, 35%),
// ),
// chic-footer(
// center-side: text(size: 11pt, font: Xbs)[
// #chic-page-number()
// ],
// ),
// chic-separator(1pt),
// // chic-separator(on: "header", chic-styled-separator("bold-center")),
// chic-separator(on: "footer", stroke(dash: "loosely-dashed", paint: gray)),
// chic-offset(40%),
// chic-height(2cm),
// )
// 正文设置
set heading(numbering: "1.1")
set figure(supplement: [图])
show heading: i-figured.reset-counters.with(level: 2)
show figure: i-figured.show-figure.with(level: 2)
show math.equation: i-figured.show-equation
set text(
font: Songti,
// font:"Linux Libertine",
size: 12pt,
)
set par( // 段落设置
justify: false,
leading: 1.04em,
first-line-indent: 2em,
)
show heading: it => box(width: 100%)[ // 标题设置
#v(0.45em)
#set text(font: Xbs)
#if it.numbering != none {
counter(heading).display()
}
#h(0.75em)
#it.body
#v(5pt)
]
show link: it => { // 链接
set text(fill: rgb("#034ea1"))
it
}
show: gentle-clues.with( // gentle块
headless: false, // never show any headers
breakable: true, // default breaking behavior
header-inset: 0.4em, // default header-inset
content-inset: 1em, // default content-inset
stroke-width: 2pt, // default left stroke-width
border-radius: 2pt, // default border-radius
border-width: 0.5pt, // default boarder-width
)
show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em) // 复选框
// 代码段设置
show: codly-init.with()
codly(
display-icon: false,
stroke-color: luma(200),
zebra-color: luma(240),
enable-numbers: true,
breakable: true,
)
show raw.where(lang: "pintora"): it => pintorita.render(it.text)
body
} |
|
https://github.com/MALossov/YunMo_Doc | https://raw.githubusercontent.com/MALossov/YunMo_Doc/main/contents/4Conclusion.typ | typst | Apache License 2.0 | = 总结
== 可扩展之处
在项目的实施中,尽管我们取得了一系列令人满意的成果,但我们也深刻认识到一些未能达到的目标,这为未来的可扩展性提供了一些有益的方向。以下是一些未能实现的目标以及对应的可扩展性考虑:
- 更高级的图像检测功能: 尽管我们实现了基本的人体检测功能,但在未来的扩展中,可以考虑集成更高级的图像检测算法,如物体识别、行为分析等,以提升监控系统的智能化水平。
- 单FPGA多路摄像头: 当前的设计虽然支持多路摄像头接入,但考虑到监控系统可能需要更大规模的部署,未来的扩展方向可以包括优化硬件设计,实现单一FPGA处理多路摄像头输入,提高系统整体的可伸缩性。
- SD卡存储: 在实际应用中,对于长时间的监控数据存储是一个重要考虑因素。未来的系统可扩展性可以包括将存储介质扩展至SD卡,以满足更大容量的数据存储需求。
- 更高分辨率和图像压缩: 针对监控系统对于图像清晰度和网络传输效率的不断追求,未来可考虑进一步提高系统支持的分辨率和优化图像压缩算法,以适应更高要求的监控场景。
== 心得体会
在项目的完成过程中,我们不仅仅实现了基本的视频监控功能,更加深入地思考并解决了实际应用中可能遇到的挑战。以下是我们在项目中的一些心得体会:
- 创新与实用的平衡: 通过引入云墨模式、通用滤波模块等创新特性,我们在提高系统性能的同时,注重了实际应用的实用性。创新点的引入并非为了炫技,而是为了解决实际场景中可能遇到的问题,提高系统的适用性。
- 用户体验至上: 在设计阶段我们特别关注了用户体验,通过单键操作、模式切换状态机等设计,使系统更加易用。用户可以方便地切换模式,增加了系统的操作便捷性,提升了用户体验。
- 丰富的互联网和厂商支持必不可少:高云优秀的器件资源和IP核支持为我们的项目提供了强大的基础,极大地降低了我们的工作难度和压力。我们能够充分利用高云半导体提供的先进技术,更专注于项目的创新和功能实现,使我们的设计更加高效、稳定。而网络上关于高云的资料也不少,让我们能够快速迁移。
在总结这一阶段的工作时,我们对于项目的成果感到欣喜,同时也意识到在不断发展的技术领域中,我们需要不断学习和创新,以更好地满足未来监控系统的需求。这次比赛是一个宝贵的经验,让我们更深刻地理解了团队协作和项目管理的重要性。希望我们的努力能够为未来的监控系统领域带来一些有益的启示。
#pagebreak()
= 参考文献 |
https://github.com/eduardz1/UniTO-typst-template | https://raw.githubusercontent.com/eduardz1/UniTO-typst-template/main/template/main.typ | typst | MIT License | #import "@preview/modern-unito-thesis:0.1.0": template
// Your acknowledgments (Ringraziamenti) go here
#let acknowledgments = [
I would like to thank you for using my template and the team of typst for the great work they have done and the awesome tool they developed. Remember that it's best practice to thank the people you worked with before thanking your family and friends.
]
// Your abstract goes here
#let abstract = [
In this theis, we will talk about this template I made for the University of Turin, remember that the abstract should be concise and clear but should also be able to give a good idea of what the thesis is about, always ask your advisor for feedback if you are unsure.
]
#show: template.with(
// Your title goes here
title: "My Beautiful Thesis",
// Change to the correct academic year, e.g. "2024/2025"
academic-year: [2023/2024],
// Change to the correct subtitle, i.e. "Tesi di Laurea Triennale",
// "Master's Thesis", "PhD Thesis", etc.
subtitle: "Bachelor's Thesis",
// Change to your name and matricola
candidate: (
name: "<NAME>",
matricola: 947847
),
// Change to your supervisor's name
supervisor: (
"Prof. <NAME>"
),
// Add as many co-supervisors as you need or remove the entry
// if none are needed
co-supervisor: (
"Dott. <NAME>",
"Dott. <NAME>"
),
// Customize with your own school and degree
affiliation: (
university: "Università degli Studi di Torino",
school: "Scuola di Scienze della Natura",
degree: "Corso di Laurea Triennale in Informatica",
),
// Change to "it" for the Italian template
lang: "en",
// University logo
logo: image("imgs/logo.svg", width: 40%),
// Hayagriva bibliography is the default one, if you want to use a
// BibTeX file, pass a .bib file instead (e.g. "works.bib")
bibliography: bibliography("works.yml"),
// See the `acknowledgments` and `abstract` variables above
acknowledgments: acknowledgments,
abstract: abstract,
// Add as many keywords as you need, or remove the entry if none
// are needed
keywords: [keyword1, keyword2, keyword3]
)
// I suggest adding each chapter in a separate typst file under the
// `chapters` directory, and then importing them here.
#include "chapters/introduction.typ"
#include "chapters/example.typ"
#include "chapters/conclusions.typ"
|
https://github.com/WinstonMDP/knowledge | https://raw.githubusercontent.com/WinstonMDP/knowledge/master/equiv_classes.typ | typst | #import "cfg.typ": cfg
#show: cfg
= Классы эквивалентности
$tilde$ - эквивалентность $:= med tilde$ - симметричный предпорядок.
Класс эквивалентности $x$ по $tilde med := {y | y tilde x}$.
Фактор-множество $x$ по $tilde med := x \/ tilde med := {y subset.eq x | exists z in x
space y - "класс эквивалентности" z "по" tilde}$.
|
|
https://github.com/Myriad-Dreamin/shiroa | https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/github-pages/docs/format/supports/cross-ref-sample.typ | typst | Apache License 2.0 | #import "/github-pages/docs/book.typ": book-page
#show: book-page.with(title: "Typst Supports - Cross Reference in other pages")
= Sample page for cross reference in other pages
#lorem(50)
== Subsection
#lorem(50)
== -sub option
#lorem(50)
== A sentence...
#lorem(50)
== Math equation $f = lambda x . x$ in heading
#lorem(50)
|
https://github.com/oldrev/tids | https://raw.githubusercontent.com/oldrev/tids/master/demo-ds.zh.typ | typst | Apache License 2.0 | #import "tids.zh.typ": tids
#import "@preview/gentle-clues:0.6.0": warning
#let metadata = (
title: [FXC1117 通量电容器],
product: "FXC1117",
product_url: "https://github.com/oldrev/tids",
)
#let features = [
- 容量: 1.21 GC
- 输入电压: 88 kV
- 封装:提供 QFN-24 和 BGA-19999 封装
- 材料:先进钽合金半导体
- 频率响应超过 1.21 PHz
- 温度范围: -40°C 到 65535°C
- 稳定性: 高度稳定,适用于极端环境
- 输出电容支持多层陶瓷电容
]
#let applications = [
通量电容器是一种先进的电子元件,广泛应用于以下领域:
- 时间旅行技术
- 能源转换
- 电子设备优化
- 空间变形技术
- 量子通信
- 军事渗透用人形终结者
#figure(
rect(image("./assets/741.svg"), stroke: 0.5pt), caption: "典型应用电路"
)
]
#let desc = [
通量电容器是一项革命性的电子技术,利用先进的合金和绝缘材料,使其能够在极端条件下运作。其高容量和高工作电压使其成为时间旅行技术和能源转换领域的理想选择。
此外,通量电容器还可以应用于电子设备优化、空间变形技术和量子通信等领域。其稳定性和频率响应使其成为未来电子元件领域中的创新产物。
]
#let rev_list = (
(rev: [REV2], date: [2024/12/12], body: [
- #lorem(10)
- #lorem(8)
- #lorem(8)
]),
(rev: [REV1], date: [2012/12/12], body: [
- #lorem(10)
- #lorem(18)
- #lorem(18)
- #lorem(18)
]),
)
#show: doc => tids(
ds_metadata: metadata,
features: features,
applications: applications,
desc: desc,
rev_list: rev_list,
doc: doc
)
= 硬件规格
== 接口与功能
<接口与功能>
#lorem(30)
#lorem(30)
== 电气规格
<电气规格>
#table(
columns: (auto, auto, auto, auto, auto, auto, 1fr),
align: (col, row) => (left,center,right,right,right,left,left,).at(col),
table.header([*参数*], [*符号*], [*最小值*], [*典型值*], [*最大值*], [*单位*], [*条件*]),
[额定电压], [$V_(upright("IN"))$], [5], [—], [24], [V], [—],
[额定电流], [$I$], [100], [150], [1,000], [mA], [使用 5V 供电],
[控制信号高电平输出电压], [$V_(upright("OH"))$], [4.5], [—], [—], [V], [—],
[控制信号低电平输出电压], [$V_(upright("OL"))$], [—], [—], [0.5], [V], [—],
[控制信号输出高电平拉电流], [$I_(upright("OH"))$], [—], [20], [—], [mA], [—],
)
== 绝对最大额定值
<绝对最大额定值>
在超过绝对最大额定值范围内的情况下使用设备可能造成设备永久损坏。
#table(
columns: (auto, auto, auto, auto, auto, 1fr),
align: (col, row) => (left,center,right,right,center,left).at(col),
table.header([*参数*], [*符号*], [*最小值*], [*最大值*], [*单位*], [*备注*]),
[电源供电电压], [$V_(upright("IN"))$], [0], [30], [V],[],
[环境温度], [$T_A$], [-25], [85], [°C],[],
)
#warning(title: "警告")[
接入电源之前请先确认电源电压正常、已良好接地且正负极接线正确,否则可能造成设备烧毁或人身伤害。
]
#pagebreak()
= 详细说明
<详细说明>
== 总览
#lorem(200)
#lorem(200)
== 功能框图
#lorem(200)
#pagebreak()
= 应用与实现
=== 应用信息
#lorem(200)
=== 典型应用
#lorem(200)
=== 推荐外围设备
#lorem(200)
=== PCB 布局指南
#lorem(200)
#pagebreak()
= 设备与文档支持
=== 设备与技术支持
=== 技术支持资源
#lorem(200)
#pagebreak()
= 机械外形、封装与订购信息
#lorem(30)
#lorem(30)
|
https://github.com/alberto-lazari/computer-science | https://raw.githubusercontent.com/alberto-lazari/computer-science/main/game-theory/notes.typ | typst | #import "@local/unipd-doc:0.0.1": *
#show: notes()
#show: unipd-doc(
title: [Game Theory],
subtitle: [Notes],
author: [<NAME>],
date: [I Semester A.Y. 2023-2024],
)
#lecture[1 -- 04/10]
= Exam
- Written test (0-27 pts)
- Extra points:
+ No project (3 free points)
+ Group project (up to 7 pts)
- Score $>=$ 31 $=>$ 30L
= Decision problems
Can be represented with *decision trees*
== 1-player problems
#let pref = $succ.eq$
/ Preference: $a pref b -->$ $a$ is preferred over $b$
Properties:
- Complete: either $a pref b$ or $b pref a$
- Transitive: $a pref b$ and $b pref c => a pref c$
- Congruence on utility functions: $u(a) >= u(b) => a pref b$
/ Rational player: player that maximizes its utility function
== Decision trees
- Nodes are choices
- Leaves are payoffs of the choice (value/preference)
Payoffs are the sum of the results of utility function.
They basically represent the preference of a specific choice (the input)
/ Collapse: the collapsed tree is the tree of depth 1, with each edge that is a path in the original tree
= Lotteries
== Outcomes probability
Outcomes of the utility functions may not always be certain.
When randomness comes in a rational player has to choose based on the probability of preferable outcomes
/ Lottery: probability distribution $p$ over set of outcomes $X = {x_1, ..., x_n}$
Randomness can actually be modelled as an external player _Nature_ that takes choices
== VNM model
Theorem: if $pref$ on lotteries satifies:
- Rationality
- Continuity axiom
- Independence
= Decisions over time
- Players and nature alternate turns in choice
- The player will base choices over nature's ones
#lecture[2 -- 12/10]
= Static games
Players move at the same time (turn-based)
/ Normal form game: $GG = { S_1, S_2, ..., S_n; v_1, v_2, ..., v_n }$ \
It can be represented as a table
== Best response
Best possible action for a player: the one that maximizes the outcome, based on other players actions
/ Belief: other players' possible strategies
== Nash equilibrium
Joint strategy that, if played, leaves no player with regrets
Similar to Pareto efficiency, but from a different perspective:
- Pareto efficiency: global best payoff (of all the players at the same time)
- Nash equilibrium: local best payoff (of every player, egoistic)
Nash equilibrium can be broken by external factors (R in grade problem)
#lecture[5 -- 18/10]
= Electoral systems
Particular systems can advantage certain types of candidates
Systems:
- Plurality voting: relative majority
- Two-phase run-off
- Borda counting: points based on the preference (last 0 pts, second-last 1 pt, ...)
- Approval voting: most approval wins
- Instant run-off:
- Least preferred is eliminated
- Repeat until one candidate
- May lead to paradoxes (increasing preference to candidate may lead to him losing)
#lecture[6 -- 19/10]
#let maj = pref
#let iff = $<==>$
/ Majority rule: $a maj b iff$ more people prefer a to b
= Cournot duopoly
Duopolys lead to better outcome for the environment
= Tragedy of commons
Common resources get misused when private interest prevails
#lecture[08/11]
= Exercises
- Find NEs: find all best strategies. If they match in some cases there is a pure NE
- Find mixed NEs: calculate probabilities for all players. If probabilities are $0 <= p <= 1$ then there is a mixed NE
- Pareto dominant strategies
= Linear transformations
== NE invariance
NEs are invariant to (positive) linear transformations on utility functions: \
if utility $u_i (s)$ is changed with $u'_i (s) = alpha u_i (s) + x$, with $alpha > 0$ the NAs are the same
#lecture[11 -- 09/11]
= Dynamic games
There is an order in the moves: one players moves first, the other later and is aware of the previous moves
== Perfect information
No Nature moves (simultaneous) involved
= Zero-sum games
== Minmax theorem
Game $GG$ has NE in pure strategies $<==> "maximin"_i = "minimax"_i (= u_i("NE")) forall "players" i$
Same for $"minimax"^p$ theorem in mixed strategies
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/font_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test string body.
#text("Text") \
#text(red, "Text") \
#text(font: "Ubuntu", blue, "Text") \
#text([Text], teal, font: "IBM Plex Serif") \
#text(forest, font: "New Computer Modern", [Text]) \
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Templates/i-figure.typ | typst | #let _typst-numbering = numbering
#let _prepare-dict(it, level, zero-fill, leading-zero, numbering) = {
let numbers = counter(heading).at(it.location())
// if zero-fill is true add trailing zeros until the level is reached
while zero-fill and numbers.len() < level { numbers.push(0) }
// only take the first `level` numbers
if numbers.len() > level { numbers = numbers.slice(0, level) }
// strip a leading zero if requested
if not leading-zero and numbers.at(0, default: none) == 0 {
numbers = numbers.slice(1)
}
let dic = it.fields()
let _ = if "body" in dic { dic.remove("body") }
let _ = if "label" in dic { dic.remove("label") }
let _ = if "counter" in dic { dic.remove("counter") }
dic + (numbering: n => _typst-numbering(numbering, ..numbers, n))
}
#let show-equation(
it,
level: 1,
zero-fill: true,
leading-zero: true,
numbering: "(1.1)",
prefix: "eqn-",
only-labeled: false,
unnumbered-label: "-",
) = {
if (
only-labeled and not it.has("label")
or it.has("label") and (
str(it.label).starts-with(prefix)
or str(it.label) == unnumbered-label
)
or not it.block
) {
it
} else {
let equation = math.equation(
it.body,
.._prepare-dict(it, level, zero-fill, leading-zero, numbering),
)
if it.has("label") {
let new-label = label(prefix + str(it.label))
[#equation #new-label]
} else {
let new-label = label(prefix + _prefix + "no-label")
[#equation #new-label]
}
}
}
#let show-equation-refrences(
it,
level: 1,
numbering: "(1.1)"
) = {
let el = it.element
if el != none and el.func() == math.equation {
let numbers = counter(heading).at(el.location())
if numbers.len() > level { numbers = numbers.slice(0, level) }
link(el.location(), _typst-numbering(
numbering,
..numbers,
counter(math.equation).at(el.location()).at(0)
))
} else {
it
}
}
|
|
https://github.com/heloineto/utfpr-tcc-template | https://raw.githubusercontent.com/heloineto/utfpr-tcc-template/main/README.md | markdown | # UTFPR TCC Template
This is a [Typst](https://typst.app/) template for UTFPR TCC (Trabalho de Conclusão de Curso).
Features:
- Cover, title, approval, acknowledgement and abstract pages
- Table of contents, figures and boards
- ABNT Headings
Missing features:
- Tables
- ABNT References
- Hide illustration's table of contents if there is no illustration of that type |
|
https://github.com/mattheww/tyroshup | https://raw.githubusercontent.com/mattheww/tyroshup/funcalls/funcalls/index.typ | typst | #import "conf.typ": conf
#show: conf
#outline(depth: 1)
#include "general.typ"
#include "expressions.typ"
#include "glossary.typ"
|
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/blockchain/blockchain.typ | typst | #import "../template.typ": *
#import "../utils.typ": *
#show: doc => conf(author: "<NAME>", "Blockchain", "summary", doc)
#include "weeks/week1.typ"
#include "weeks/week2.typ"
#include "weeks/week3.typ"
#include "weeks/week4.typ"
#include "weeks/week5.typ"
#include "weeks/week6.typ"
#include "weeks/week7.typ"
#include "weeks/week8.typ"
#include "weeks/week9.typ"
#include "weeks/week10.typ"
#include "weeks/week11.typ"
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/block-00.typ | typst | Other | // Ref: true
// Evaluates to join of none, [My ] and the two loop bodies.
#{
let parts = ("my fri", "end.")
[Hello, ]
for s in parts [#s]
}
// Evaluates to join of the content and strings.
#{
[How]
if true {
" are"
}
[ ]
if false [Nope]
[you] + "?"
}
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/page-number-align_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 25-39 page number cannot be `horizon`-aligned
// #set page(number-align: left + horizon) |
https://github.com/yue-dongchen/LibreBitexts | https://raw.githubusercontent.com/yue-dongchen/LibreBitexts/master/Authors/Jules%20Verne/Vingt%20mille%20lieues%20sous%20les%20mers/Vingt%20mille%20lieues%20sous%20les%20mers.chapitre1.fr-en.typ | typst | Other | #import "../../../utils.typ"
#import utils: parallel-text as parallel
#import "@preview/ccicons:1.0.0": *
#set page(footer: [
#grid(
columns: (1fr, 1fr, 1fr),
align: (left, center + top, right),
[], [#counter(page).display("1")], [
#text(font: "Roboto", weight: "medium", size: 8pt)[#link("https://yue-dongchen.github.io/LibreBitexts/")[#sym.copyright LibreBitexts]\ ]
#text(14pt)[#ccicon("cc-by-nc-shield/4.0", link:true)]
])
])
#parallel[
#emph[Vingt mille lieues sous les mers]
][
#emph[Twenty Thousand Leagues Under the Seas]
]
#parallel[
<NAME>\
1869–1870
][
Translation by <NAME>, who dedicated it to the public domain\
1999
]
#parallel[
= Chapitre premier: un écueil fuyant
][
= Chapter I: A Runaway Reef
]
#parallel[
L’année 1866 fut marquée par un événement bizarre, un phénomène inexpliqué et inexplicable que personne n’a sans doute oublié. Sans parler des rumeurs qui agitaient les populations des ports et surexcitaient l’esprit public à l’intérieur des continents, les gens de mer furent particulièrement émus. Les négociants, armateurs, capitaines de navires, skippers et masters de l’Europe et de l’Amérique, officiers des marines militaires de tous pays, et, après eux, les gouvernements des divers États des deux continents, se préoccupèrent de ce fait au plus haut point.
][
The year 1866 was marked by a bizarre development, an unexplained and downright inexplicable phenomenon that surely no one has forgotten. Without getting into those rumors that upset civilians in the seaports and deranged the public mind even far inland, it must be said that professional seamen were especially alarmed. Traders, shipowners, captains of vessels, skippers, and master mariners from Europe and America, naval officers from every country, and at their heels the various national governments on these two continents, were all extremely disturbed by the business.
]
#parallel[
En effet, depuis quelque temps, plusieurs navires s’étaient rencontrés sur mer avec « une chose énorme, » un objet long, fusiforme, parfois phosphorescent, infiniment plus vaste et plus rapide qu’une baleine.
][
In essence, over a period of time several ships had encountered "an enormous thing" at sea, a long spindle-shaped object, sometimes giving off a phosphorescent glow, infinitely bigger and faster than any whale.
]
#parallel[
Les faits relatifs à cette apparition, consignés aux divers livres de bord, s’accordaient assez exactement sur la structure de l’objet ou de l’être en question, la vitesse inouïe de ses mouvements, la puissance surprenante de sa locomotion, la vie particulière dont il semblait doué. Si c’était un cétacé, il surpassait en volume tous ceux que la science avait classés jusqu’alors. Ni Cuvier, ni Lacépède, ni <NAME>, ni <NAME> n’eussent admis l’existence d’un tel monstre — à moins de l’avoir vu, ce qui s’appelle vu de leurs propres yeux de savants.
][
The relevant data on this apparition, as recorded in various logbooks, agreed pretty closely as to the structure of the object or creature in question, its unprecedented speed of movement, its startling locomotive power, and the unique vitality with which it seemed to be gifted. If it was a cetacean, it exceeded in bulk any whale previously classified by science. No naturalist, neither Cuvier nor Lacépède, neither Professor Dumeril nor Professor de Quatrefages, would have accepted the existence of such a monster sight unseen—specifically, unseen by their own scientific eyes.
]
#parallel[
À prendre la moyenne des observations faites à diverses reprises, — en rejetant les évaluations timides qui assignaient à cet objet une longueur de deux cents pieds, et en repoussant les opinions exagérées qui le disaient large d’un mille et long de trois, — on pouvait affirmer, cependant, que cet être phénoménal dépassait de beaucoup toutes les dimensions admises jusqu’à ce jour par les ichthyologistes, — s’il existait toutefois.
][
Striking an average of observations taken at different times—rejecting those timid estimates that gave the object a length of 200 feet, and ignoring those exaggerated views that saw it as a mile wide and three long—you could still assert that this phenomenal creature greatly exceeded the dimensions of anything then known to ichthyologists, if it existed at all.
]
#parallel[
Or, il existait, le fait en lui-même n’était plus niable, et, avec ce penchant qui pousse au merveilleux la cervelle humaine, on comprendra l’émotion produite dans le monde entier par cette surnaturelle apparition. Quant à la rejeter au rang des fables, il fallait y renoncer.
][
Now then, it did exist, this was an undeniable fact; and since the human mind dotes on objects of wonder, you can understand the worldwide excitement caused by this unearthly apparition. As for relegating it to the realm of fiction, that charge had to be dropped.
]
#parallel[
En effet, le 20 juillet 1866, le steamer Governor-Higginson, de Calcutta and Burnach steam navigation Company, avait rencontré cette masse mouvante à cinq milles dans l’est des côtes de l’Australie. Le capitaine Baker se crut, tout d’abord, en présence d’un écueil inconnu ; il se disposait même à en déterminer la situation exacte, quand deux colonnes d’eau, projetées par l’inexplicable objet, s’élancèrent en sifflant à cent cinquante pieds dans l’air. Donc, à moins que cet écueil ne fût soumis aux expansions intermittentes d’un geyser, le Governor-Higginson avait affaire bel et bien à quelque mammifère aquatique, inconnu jusque-là, qui rejetait par ses évents des colonnes d’eau, mélangées d’air et de vapeur.
][
In essence, on July 20, 1866, the steamer Governor Higginson, from the Calcutta & Burnach Steam Navigation Co., encountered this moving mass five miles off the eastern shores of Australia. Captain Baker at first thought he was in the presence of an unknown reef; he was even about to fix its exact position when two waterspouts shot out of this inexplicable object and sprang hissing into the air some 150 feet. So, unless this reef was subject to the intermittent eruptions of a geyser, the Governor Higginson had fair and honest dealings with some aquatic mammal, until then unknown, that could spurt from its blowholes waterspouts mixed with air and steam.
]
#parallel[
Pareil fait fut également observé le 23 juillet de la même année, dans les mers du Pacifique, par le Cristobal-Colon, de West India and Pacific steam navigation Company. Donc, ce cétacé extraordinaire pouvait se transporter d’un endroit à un autre avec une vélocité surprenante, puisque à trois jours d’intervalle, le Governor-Higginson et le Cristobal-Colon l’avaient observé en deux points de la carte séparés par une distance de plus de sept cents lieues marines.
][
Similar events were likewise observed in Pacific seas, on July 23 of the same year, by the <NAME> from the West India & Pacific Steam Navigation Co. Consequently, this extraordinary cetacean could transfer itself from one locality to another with startling swiftness, since within an interval of just three days, the Governor Higginson and the Christopher Columbus had observed it at two positions on the charts separated by a distance of more than 700 nautical leagues.
]
#parallel[
Quinze jours plus tard, à deux mille lieues de là, l’Helvetia, de la Compagnie Nationale, et le Shannon, du Royal-Mail, marchant à contrebord dans cette portion de l’Atlantique comprise entre les États-Unis et l’Europe, se signalèrent respectivement le monstre par 42° 15′ de latitude nord, et 60° 35′ de longitude à l’ouest du méridien de Greenwich. Dans cette observation simultanée, on crut pouvoir évaluer la longueur minimum du mammifère à plus de trois cent cinquante pieds anglais [1], puisque le Shannon et l’Helvetia étaient de dimension inférieure à lui, bien qu’ils mesurassent cent mètres de l’étrave à l’étambot. Or, les plus vastes baleines, celles qui fréquentent les parages des îles Aléoutiennes, le Kulammak et l’Umgullick, n’ont jamais dépassé la longueur de cinquante-six mètres, — si même elles l’atteignent.
][
Fifteen days later and 2,000 leagues farther, the Helvetia from the Compagnie Nationale and the Shannon from the Royal Mail line, running on opposite tacks in that part of the Atlantic lying between the United States and Europe, respectively signaled each other that the monster had been sighted in latitude 42 degrees 15’ north and longitude 60 degrees 35’ west of the meridian of Greenwich. From their simultaneous observations, they were able to estimate the mammal’s minimum length at more than 350 English feet; this was because both the Shannon and the Helvetia were of smaller dimensions, although each measured 100 meters stem to stern. Now then, the biggest whales, those rorqual whales that frequent the waterways of the Aleutian Islands, have never exceeded a length of 56 meters—if they reach even that.
]
#parallel[
Ces rapports arrivés coup sur coup, de nouvelles observations faites à bord du transatlantique le Pereire, un abordage entre l’Etna, de la ligne Inman, et le monstre, un procès-verbal dressé par les officiers de la frégate française la Normandie, un très sérieux relèvement obtenu par l’état-major du commodore Fitz-James à bord du Lord-Clyde, émurent profondément l’opinion publique. Dans les pays d’humeur légère, on plaisanta le phénomène, mais les pays graves et pratiques, l’Angleterre, l’Amérique, l’Allemagne, s’en préoccupèrent vivement.
][
One after another, reports arrived that would profoundly affect public opinion: new observations taken by the transatlantic liner Pereire, the Inman line’s Etna running afoul of the monster, an official report drawn up by officers on the French frigate Normandy, dead-earnest reckonings obtained by the general staff of Commodore Fitz-James aboard the Lord Clyde. In lighthearted countries, people joked about this phenomenon, but such serious, practical countries as England, America, and Germany were deeply concerned.
]
#parallel[
Partout dans les grands centres, le monstre devint à la mode ; on le chanta dans les cafés, on le bafoua dans les journaux, on le joua sur les théâtres. Les canards eurent là une belle occasion de pondre des œufs de toute couleur. On vit réapparaître dans les journaux — à court de copie — tous les êtres imaginaires et gigantesques, depuis la baleine blanche, le terrible « <NAME> » des régions hyperboréennes, jusqu’au Kraken démesuré, dont les tentacules peuvent enlacer un bâtiment de cinq cents tonneaux et l’entraîner dans les abîmes de l’Océan. On reproduisit même les procès-verbaux des temps anciens les opinions d’Aristote et de Pline, qui admettaient l’existence de ces monstres, puis les récits norwégiens de l’évêque Pontoppidan, les relations de <NAME>, et enfin les rapports de <NAME>, dont la bonne foi ne peut être soupçonnée, quand il affirme avoir vu, étant à bord du Castillan, en 1857, cet énorme serpent qui n’avait jamais fréquenté jusqu’alors que les mers de l’ancien Constitutionnel.
][
In every big city the monster was the latest rage; they sang about it in the coffee houses, they ridiculed it in the newspapers, they dramatized it in the theaters. The tabloids found it a fine opportunity for hatching all sorts of hoaxes. In those newspapers short of copy, you saw the reappearance of every gigantic imaginary creature, from "<NAME>," that dreadful white whale from the High Arctic regions, to the stupendous kraken whose tentacles could entwine a 500-ton craft and drag it into the ocean depths. They even reprinted reports from ancient times: the views of Aristotle and Pliny accepting the existence of such monsters, then the Norwegian stories of Bishop Pontoppidan, the narratives of <NAME>, and finally the reports of <NAME>—whose good faith is above suspicion—in which he claims he saw, while aboard the Castilian in 1857, one of those enormous serpents that, until then, had frequented only the seas of France’s old extremist newspaper, The Constitutionalist.
]
#parallel[
Alors éclata l’interminable polémique des crédules et des incrédules dans les sociétés savantes et les journaux scientifiques. La « question du monstre » enflamma les esprits. Les journalistes, qui font profession de science en lutte avec ceux qui font profession d’esprit, versèrent des flots d’encre pendant cette mémorable campagne ; quelques-uns même, deux ou trois gouttes de sang, car du serpent de mer, ils en vinrent aux personnalités les plus offensantes.
][
An interminable debate then broke out between believers and skeptics in the scholarly societies and scientific journals. The "monster question" inflamed all minds. During this memorable campaign, journalists making a profession of science battled with those making a profession of wit, spilling waves of ink and some of them even two or three drops of blood, since they went from sea serpents to the most offensive personal remarks.
]
#parallel[
Six mois durant, la guerre se poursuivit avec des chances diverses. Aux articles de fond de l’Institut géographique du Brésil, de l’Académie royale des sciences de Berlin, de l’Association Britannique, de l’Institution Smithsonnienne de Washington, aux discussions du The Indian Archipelago, du Cosmos de l’abbé Moigno, des Mittheilungen de Petermann, aux chroniques scientifiques des grands journaux de la France et de l’étranger, la petite presse ripostait avec une verve intarissable. Ses spirituels écrivains parodiant un mot de Linné, cité par les adversaires du monstre, soutinrent en effet que « la nature ne faisait pas de sots », et ils adjurèrent leurs contemporains de ne point donner un démenti à la nature, en admettant l’existence des Krakens, des serpents de mer, des « <NAME> », et autres élucubrations de marins en délire. Enfin, dans un article d’un journal satirique très-redouté, le plus aimé de ses rédacteurs, brochant sur le tout, poussa au monstre, comme Hippolyte, lui porta un dernier coup et l’acheva au milieu d’un éclat de rire universel. L’esprit avait vaincu la science.
][
For six months the war seesawed. With inexhaustible zest, the popular press took potshots at feature articles from the Geographic Institute of Brazil, the Royal Academy of Science in Berlin, the British Association, the Smithsonian Institution in Washington, D.C., at discussions in The Indian Archipelago, in Cosmos published by <NAME>, in Petermann’s Mittheilungen, and at scientific chronicles in the great French and foreign newspapers. When the monster’s detractors cited a saying by the botanist Linnaeus that "nature doesn’t make leaps," witty writers in the popular periodicals parodied it, maintaining in essence that "nature doesn’t make lunatics," and ordering their contemporaries never to give the lie to nature by believing in krakens, sea serpents, "Moby Dicks," and other all-out efforts from drunken seamen. Finally, in a much-feared satirical journal, an article by its most popular columnist finished off the monster for good, spurning it in the style of Hippolytus repulsing the amorous advances of his stepmother Phaedra, and giving the creature its quietus amid a universal burst of laughter. Wit had defeated science.
]
#parallel[
Pendant les premiers mois de l’année 1867, la question parut être enterrée, et elle ne semblait pas devoir renaître, quand de nouveaux faits furent portés à la connaissance du public. Il ne s’agit plus alors d’un problème scientifique à résoudre, mais bien d’un danger réel, sérieux à éviter. La question prit une tout autre face. Le monstre redevint îlot, rocher, écueil, mais écueil fuyant, indéterminable, insaisissable.
][
During the first months of the year 1867, the question seemed to be buried, and it didn’t seem due for resurrection, when new facts were brought to the public’s attention. But now it was no longer an issue of a scientific problem to be solved, but a quite real and serious danger to be avoided. The question took an entirely new turn. The monster again became an islet, rock, or reef, but a runaway reef, unfixed and elusive.
]
#parallel[
Le 5 mars 1867, le Moravian, de Montréal Océan Company, se trouvant pendant la nuit par 27° 30′ de latitude et 72° 15′ de longitude, heurta de sa hanche de tribord un roc qu’aucune carte ne marquait dans ces parages. Sous l’effort combiné du vent et de ses quatre cents chevaux-vapeur, il marchait à la vitesse de treize nœuds. Nul doute que sans la qualité supérieure de sa coque, le Moravian, ouvert au choc, ne se fût englouti avec les deux cent trente-sept passagers qu’il ramenait du Canada.
][
On March 5, 1867, the Moravian from the Montreal Ocean Co., lying during the night in latitude 27 degrees 30’ and longitude 72 degrees 15’, ran its starboard quarter afoul of a rock marked on no charts of these waterways. Under the combined efforts of wind and 400-horsepower steam, it was traveling at a speed of thirteen knots. Without the high quality of its hull, the Moravian would surely have split open from this collision and gone down together with those 237 passengers it was bringing back from Canada.
]
#parallel[
L’accident était arrivé vers cinq heures du matin, lorsque le jour commençait à poindre. Les officiers de quart se précipitèrent à l’arrière du bâtiment. Ils examinèrent l’Océan avec la plus scrupuleuse attention. Ils ne virent rien, si ce n’est un fort remous qui brisait à trois encablures, comme si les nappes liquides eussent été violemment battues. Le relèvement du lieu fut exactement pris, et le Moravian continua sa route sans avaries apparentes. Avait-il heurté une roche sous-marine, ou quelque énorme épave d’un naufrage ? On ne put le savoir ; mais, examen fait de sa carène dans les bassins de radoub, il fut reconnu qu’une partie de la quille avait été brisée.
][
This accident happened around five o’clock in the morning, just as day was beginning to break. The officers on watch rushed to the craft’s stern. They examined the ocean with the most scrupulous care. They saw nothing except a strong eddy breaking three cable lengths out, as if those sheets of water had been violently churned. The site’s exact bearings were taken, and the Moravian continued on course apparently undamaged. Had it run afoul of an underwater rock or the wreckage of some enormous derelict ship? They were unable to say. But when they examined its undersides in the service yard, they discovered that part of its keel had been smashed.
]
#parallel[
Ce fait, extrêmement grave en lui-même, eût peut-être été oublié comme tant d’autres, si, trois semaines après, il ne se fût reproduit dans des conditions identiques. Seulement, grâce à la nationalité du navire victime de ce nouvel abordage, grâce à la réputation de la Compagnie à laquelle ce navire appartenait, l’événement eut un retentissement immense.
][
This occurrence, extremely serious in itself, might perhaps have been forgotten like so many others, if three weeks later it hadn’t been reenacted under identical conditions. Only, thanks to the nationality of the ship victimized by this new ramming, and thanks to the reputation of the company to which this ship belonged, the event caused an immense uproar.
]
#parallel[
Personne n’ignore le nom du célèbre armateur anglais Cunard. Cet intelligent industriel fonda, en 1840, un service postal entre Liverpool et Halifax, avec trois navires en bois et à roues d’une force de quatre cents chevaux, et d’une jauge de onze cent soixante-deux tonneaux. Huit ans après, le matériel de la Compagnie s’accroissait de quatre navires de six cent cinquante chevaux et de dix-huit cent vingt tonnes, et, deux ans plus tard, de deux autres bâtiments supérieurs en puissance et en tonnage. En 1853, la compagnie Cunard, dont le privilège pour le transport des dépêches venait d’être renouvelé, ajouta successivement à son matériel l’Arabia, le Persia, le China, le Scotia, le Java, le Russia, tous navires de première marche, et les plus vastes qui, après le Great-Eastern, eussent jamais sillonné les mers. Ainsi donc, en 1867, la Compagnie possédait douze navires, dont huit à roues et quatre à hélices.
][
No one is unaware of the name of that famous English shipowner, Cunard. In 1840 this shrewd industrialist founded a postal service between Liverpool and Halifax, featuring three wooden ships with 400-horsepower paddle wheels and a burden of 1,162 metric tons. Eight years later, the company’s assets were increased by four 650-horsepower ships at 1,820 metric tons, and in two more years, by two other vessels of still greater power and tonnage. In 1853 the Cunard Co., whose mail-carrying charter had just been renewed, successively added to its assets the Arabia, the Persia, the China, the Scotia, the Java, and the Russia, all ships of top speed and, after the Great Eastern, the biggest ever to plow the seas. So in 1867 this company owned twelve ships, eight with paddle wheels and four with propellers.
]
#parallel[
Si je donne ces détails très succincts, c’est afin que chacun sache bien quelle est l’importance de cette compagnie de transports maritimes, connue du monde entier pour son intelligente gestion. Nulle entreprise de navigation transocéanienne n’a été conduite avec plus d’habileté ; nulle affaire n’a été couronnée de plus de succès. Depuis vingt-six ans, les navires Cunard ont traversé deux mille fois l’Atlantique, et jamais un voyage n’a été manqué, jamais un retard n’a eu lieu, jamais ni une lettre, ni un homme, ni un bâtiment n’ont été perdus. Aussi, les passagers choisissent-ils encore, malgré la concurrence puissante que lui fait la France, la ligne Cunard de préférence à toute autre, ainsi qu’il appert d’un relevé fait sur les documents officiels des dernières années. Ceci dit, personne ne s’étonnera du retentissement que provoqua l’accident arrivé à l’un de ses plus beaux steamers.
][
If I give these highly condensed details, it is so everyone can fully understand the importance of this maritime transportation company, known the world over for its shrewd management. No transoceanic navigational undertaking has been conducted with more ability, no business dealings have been crowned with greater success. In twenty-six years Cunard ships have made 2,000 Atlantic crossings without so much as a voyage canceled, a delay recorded, a man, a craft, or even a letter lost. Accordingly, despite strong competition from France, passengers still choose the Cunard line in preference to all others, as can be seen in a recent survey of official documents. Given this, no one will be astonished at the uproar provoked by this accident involving one of its finest steamers.
]
#parallel[
Le 13 avril 1867, la mer étant belle, la brise maniable, le Scotia se trouvait par 15° 12′ de longitude et 45° 37′ de latitude. Il marchait avec une vitesse de treize nœuds quarante-trois centièmes sous la poussée de ses mille chevaux-vapeur. Ses roues battaient la mer avec une régularité parfaite. Son tirant d’eau était alors de six mètres soixante-dix centimètres, et son déplacement de six mille six cent vingt-quatre mètres cubes.
][
On April 13, 1867, with a smooth sea and a moderate breeze, the Scotia lay in longitude 15 degrees 12’ and latitude 45 degrees 37’. It was traveling at a speed of 13.43 knots under the thrust of its 1,000-horsepower engines. Its paddle wheels were churning the sea with perfect steadiness. It was then drawing 6.7 meters of water and displacing 6,624 cubic meters.
]
#parallel[
À quatre heures dix-sept minutes du soir, pendant le lunch des passagers réunis dans le grand salon, un choc, peu sensible, en somme, se produisit sur la coque du Scotia, par sa hanche et un peu en arrière de la roue de bâbord.
][
At 4:17 in the afternoon, during a high tea for passengers gathered in the main lounge, a collision occurred, scarcely noticeable on the whole, affecting the Scotia’s hull in that quarter a little astern of its port paddle wheel.
]
#parallel[
Le Scotia n’avait pas heurté, il avait été heurté, et plutôt par un instrument tranchant ou perforant que contondant. L’abordage avait semblé si léger que personne ne s’en fût inquiété à bord, sans le cri des caliers qui remontèrent sur le pont en s’écriant :
][
The Scotia hadn’t run afoul of something, it had been fouled, and by a cutting or perforating instrument rather than a blunt one. This encounter seemed so minor that nobody on board would have been disturbed by it, had it not been for the shouts of crewmen in the hold, who climbed on deck yelling:
]
#parallel[
« Nous coulons ! nous coulons ! » Tout d’abord, les passagers furent très-effrayés ; mais le capitaine Anderson se hâta de les rassurer. En effet, le danger ne pouvait être imminent. Le Scotia, divisé en sept compartiments par des cloisons étanches, devait braver impunément une voie d’eau.
][
"We’re sinking! We’re sinking!" At first the passengers were quite frightened, but Captain Anderson hastened to reassure them. In fact, there could be no immediate danger. Divided into seven compartments by watertight bulkheads, the Scotia could brave any leak with impunity.
]
#parallel[
Le capitaine Anderson se rendit immédiatement dans la cale. Il reconnut que le cinquième compartiment avait été envahi par la mer, et la rapidité de l’envahissement prouvait que la voie d’eau était considérable. Fort heureusement, ce compartiment ne renfermait pas les chaudières, car les feux se fussent subitement éteints.
][
Captain Anderson immediately made his way into the hold. He discovered that the fifth compartment had been invaded by the sea, and the speed of this invasion proved that the leak was considerable. Fortunately this compartment didn’t contain the boilers, because their furnaces would have been abruptly extinguished.
]
#parallel[
Le capitaine Anderson fit stopper immédiatement, et l’un des matelots plongea pour reconnaître l’avarie. Quelques instants après, on constatait l’existence d’un trou large de deux mètres dans la carène du steamer. Une telle voie d’eau ne pouvait être aveuglée, et le Scotia, ses roues à demi noyées, dut continuer ainsi son voyage. Il se trouvait alors à trois cent mille du cap Clear, et après trois jours d’un retard qui inquiéta vivement Liverpool, il entra dans les bassins de la Compagnie.
][
Captain Anderson called an immediate halt, and one of his sailors dived down to assess the damage. Within moments they had located a hole two meters in width on the steamer’s underside. Such a leak could not be patched, and with its paddle wheels half swamped, the Scotia had no choice but to continue its voyage. By then it lay 300 miles from Cape Clear, and after three days of delay that filled Liverpool with acute anxiety, it entered the company docks.
]
#parallel[
Les ingénieurs procédèrent alors à la visite du Scotia, qui fut mis en cale sèche. Ils ne purent en croire leurs yeux. À deux mètres et demi au-dessous de la flottaison s’ouvrait une déchirure régulière, en forme de triangle isocèle. La cassure de la tôle était d’une netteté parfaite, et elle n’eût pas été frappée plus sûrement à l’emporte-pièce. Il fallait donc que l’outil perforant qui l’avait produite fût d’une trempe peu commune — et après avoir été lancé avec une force prodigieuse, ayant ainsi percé une tôle de quatre centimètres, il avait dû se retirer de lui-même par un mouvement rétrograde et vraiment inexplicable.
][
The engineers then proceeded to inspect the Scotia, which had been put in dry dock. They couldn’t believe their eyes. Two and a half meters below its waterline, there gaped a symmetrical gash in the shape of an isosceles triangle. This breach in the sheet iron was so perfectly formed, no punch could have done a cleaner job of it. Consequently, it must have been produced by a perforating tool of uncommon toughness—plus, after being launched with prodigious power and then piercing four centimeters of sheet iron, this tool had needed to withdraw itself by a backward motion truly inexplicable.
]
#parallel[
Les ingénieurs procédèrent à la visite du Scotia Tel était ce dernier fait, qui eut pour résultat de passionner à nouveau l’opinion publique. Depuis ce moment, en effet, les sinistres maritimes qui n’avaient pas de cause déterminée furent mis sur le compte du monstre. Ce fantastique animal endossa la responsabilité de tous ces naufrages, dont le nombre est malheureusement considérable ; car sur trois mille navires dont la perte est annuellement relevée au Bureau-Veritas, le chiffre des navires à vapeur ou à voiles, supposés perdus corps et biens par suite d’absence de nouvelles, ne s’élève pas à moins de deux cents !
][
This was the last straw, and it resulted in arousing public passions all over again. Indeed, from this moment on, any maritime casualty without an established cause was charged to the monster’s account. This outrageous animal had to shoulder responsibility for all derelict vessels, whose numbers are unfortunately considerable, since out of those 3,000 ships whose losses are recorded annually at the marine insurance bureau, the figure for steam or sailing ships supposedly lost with all hands, in the absence of any news, amounts to at least 200!
]
#parallel[
Or, ce fut le « monstre » qui, justement ou injustement, fut accusé de leur disparition, et, grâce à lui, les communications entre les divers continents devenant de plus en plus dangereuses, le public se déclara et demanda catégoriquement que les mers fussent enfin débarrassées et à tout prix de ce formidable cétacé.
][
Now then, justly or unjustly, it was the "monster" who stood accused of their disappearance; and since, thanks to it, travel between the various continents had become more and more dangerous, the public spoke up and demanded straight out that, at all cost, the seas be purged of this fearsome cetacean.
]
#rect[
This PDF is a work of the LibreBitexts project. You are free to download, redistribute and use it in any manner, pursuant to the terms of the Creative Commons Attribution-NonCommercial 4.0 licence.
]
|
https://github.com/sses7757/sustech-graduated-thesis | https://raw.githubusercontent.com/sses7757/sustech-graduated-thesis/main/sustech-graduated-thesis/lib.typ | typst | Apache License 2.0 | #import "@preview/anti-matter:0.0.2": anti-inner-end as mainmatter-end
#import "layouts/doc.typ": doc
#import "layouts/mainmatter.typ": mainmatter, arounds_default
#import "layouts/appendix.typ": appendix
#import "pages/fonts-display-page.typ": fonts-display-page
#import "pages/outline-page.typ": outline-page
#import "pages/nonfinal-cover.typ": nonfinal-cover
#import "pages/final-cover.typ": final-cover
#import "pages/decl-page.typ": decl-page
#import "pages/abstract.typ": abstract
#import "pages/abstract-en.typ": abstract-en
#import "pages/list-of-figures.typ": list-of-figures
#import "pages/list-of-tables.typ": list-of-tables
#import "pages/notation.typ": notation-page
#import "pages/acknowledgement.typ": acknowledgement
#import "utils/custom-cuti.typ": *
#import "utils/bilingual-bibliography.typ": bilingual-bibliography
#import "utils/custom-numbering.typ": custom-numbering
#import "utils/custom-heading.typ": heading-display, active-heading, current-heading
#import "utils/indent.typ": indent, fake-par
#import "utils/style.typ": 字体, 字号
#import "utils/state-notations.typ": notation, notations
#import "utils/multi-line-equate.typ": show-figure, equate, equate-ref
#import "@preview/unify:0.6.0": num as _num, qty as _qty, numrange as _numrange, qtyrange as _qtyrange
#let num(value) = _num(value, multiplier: "×", thousandsep: ",")
#let numrange(lower, upper) = _numrange(lower, upper, multiplier: "×", thousandsep: ",")
#let qty(value, unit, rawunit: false) = _qty(value, unit, rawunit: rawunit, multiplier: "×", thousandsep: ",")
#let qtyrange(lower, upper, unit, rawunit: false) = _qtyrange(lower, upper, unit, rawunit: rawunit, multiplier: "×", thousandsep: ",")
// 使用函数闭包特性,通过 `documentclass` 函数类进行全局信息配置,然后暴露出拥有了全局配置的、具体的 `layouts` 和 `templates` 内部函数。
#let documentclass(
doctype: "final", // "proposal" | "midterm" | "final",文章类型,默认为最终报告 final
twoside: true, // 双面模式,会加入空白页,便于打印
anonymous: false, // 盲审模式
bibliography: none, // 原来的参考文献函数
math-font: "XITS Math", // 公式字体,应预先安装在系统中或放在根目录下
slant-glteq: true, // 公式 <= >= 样式
math-breakable: false, // 多行公式可否分割到多页
arounds: arounds_default, // 公式不加空格的符号
sep-ref: true, // 是否自动将@ref与其跟随的中文字符分开处理,使用true时应避免含有中文的label或bib
fonts: (:), // 字体,应传入「宋体」、「黑体」、「楷体」、「仿宋」、「等宽」
info: (:),
) = {
// 默认参数
fonts = 字体 + fonts
info = (
title: ("基于Typst的", "南方科技大学学位论文"),
title-en: "SUSTech Thesis Template for Typst",
grade: "20XX",
student-id: "1234567890",
author: "张三",
author-en: "<NAME>",
department: "某学院",
department-en: "XX Department",
major: "某专业",
major-en: "XX Major",
field: "某方向",
field-en: "XX Field",
supervisor: ("李四", "教授"),
supervisor-en: "<NAME>",
supervisor-ii: (),
supervisor-ii-en: "",
submit-date: datetime.today(),
// 以下为研究生项
defend-date: datetime.today(),
confer-date: datetime.today(),
bottom-date: datetime.today(),
chairman: "某某某 教授",
reviewer: ("某某某 教授", "某某某 教授"),
clc: "O643.12",
udc: "544.4",
secret-level: "公开",
supervisor-contact: "南方科技大学 广东省深圳市南山区学苑大道1088号",
email: "<EMAIL>",
school-code: "518055",
degree: "MEng",
) + info
(
// 将传入参数再导出
doctype: doctype,
twoside: twoside,
anonymous: anonymous,
fonts: fonts,
info: info,
// 页面布局
doc: (..args) => {
doc(
..args,
info: info + args.named().at("info", default: (:)),
)
},
mainmatter: (..args) => {
mainmatter(
slant-glteq: slant-glteq,
math-font: math-font,
arounds: arounds,
sep-ref: true,
twoside: twoside,
display-header: true,
..args,
fonts: fonts + args.named().at("fonts", default: (:)),
)
},
mainmatter-end: (..args) => {
mainmatter-end(
..args,
)
},
appendix: (..args) => {
appendix(
..args,
)
},
// 字体展示页
fonts-display-page: (..args) => {
fonts-display-page(
twoside: twoside,
..args,
fonts: fonts + args.named().at("fonts", default: (:)),
)
},
// 封面页,通过 type 分发到不同函数
cover: (..args) => {
if doctype == "proposal" or doctype == "midterm" {
nonfinal-cover(
doctype: doctype,
anonymous: anonymous,
twoside: twoside,
..args,
fonts: fonts + args.named().at("fonts", default: (:)),
info: info + args.named().at("info", default: (:)),
)
} else if doctype == "final" {
final-cover(
doctype: doctype,
anonymous: anonymous,
twoside: twoside,
..args,
fonts: fonts + args.named().at("fonts", default: (:)),
info: info + args.named().at("info", default: (:)),
)
} else {
panic("not yet been implemented.")
}
},
// 声明页,通过 type 分发到不同函数
decl-page: (..args) => {
if doctype == "final" {
decl-page(
anonymous: anonymous,
twoside: twoside,
..args,
fonts: fonts + args.named().at("fonts", default: (:)),
)
} else if doctype == "proposal" or doctype == "midterm" {
[]
} else {
panic("not yet been implemented.")
}
},
// 中文摘要页,通过 type 分发到不同函数
abstract: (..args) => {
if doctype == "final" {
abstract(
doctype: doctype,
anonymous: anonymous,
twoside: twoside,
..args,
fonts: fonts + args.named().at("fonts", default: (:)),
info: info + args.named().at("info", default: (:)),
)
} else if doctype == "proposal" or doctype == "midterm" {
[]
} else {
panic("not yet been implemented.")
}
},
// 英文摘要页,通过 type 分发到不同函数
abstract-en: (..args) => {
if doctype == "final" {
abstract-en(
doctype: doctype,
anonymous: anonymous,
twoside: twoside,
..args,
fonts: fonts + args.named().at("fonts", default: (:)),
info: info + args.named().at("info", default: (:)),
)
} else if doctype == "proposal" or doctype == "midterm" {
[]
} else {
panic("not yet been implemented.")
}
},
// 目录页
outline-page: (..args) => {
outline-page(
twoside: twoside,
..args,
fonts: fonts + args.named().at("fonts", default: (:)),
)
},
// 插图目录页
list-of-figures: (..args) => {
list-of-figures(
twoside: twoside,
..args,
fonts: fonts + args.named().at("fonts", default: (:)),
)
},
// 表格目录页
list-of-tables: (..args) => {
list-of-tables(
twoside: twoside,
..args,
fonts: fonts + args.named().at("fonts", default: (:)),
)
},
// 符号表页
notation-page: (..args) => {
notation-page(
twoside: twoside,
..args,
)
},
// 参考文献页
bilingual-bibliography: (..args) => {
bilingual-bibliography(
bibliography: bibliography,
..args,
)
},
// 致谢页
acknowledgement: (..args) => {
acknowledgement(
anonymous: anonymous,
twoside: twoside,
..args,
)
},
)
}
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/image_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Does not fit to remaining height of page.
#set page(height: 60pt)
Stuff
#image("/assets/files/rhino.png")
|
https://github.com/BoostCookie/systemd-tshirtd | https://raw.githubusercontent.com/BoostCookie/systemd-tshirtd/main/src/tshirtd.newlogo.black.typ | typst | #set page(fill: rgb("#201a26"))
#include "common.newlogo.typ"
|
|
https://github.com/EpicEricEE/typst-droplet | https://raw.githubusercontent.com/EpicEricEE/typst-droplet/master/src/lib.typ | typst | MIT License | #import "droplet.typ": dropcap
|
https://github.com/lphoogenboom/typstThesisDCSC | https://raw.githubusercontent.com/lphoogenboom/typstThesisDCSC/master/typFiles/glossary.typ | typst | // !!!!
// STUDENTS, DO NOT EDIT THIS FILE!
// !!!!
#import "specialChapter.typ": *
#import "../acronymList.typ": acronyms
#let glossary() = {
set page(numbering: "1")
set heading(numbering: none)
show: specialChapter.with(chapterTitle: "Glossary",content: [
== List of acronyms
#let arr = ()
#for (key, value) in acronyms.pairs() {
arr.push(key)
arr.push(value)
}
#set table(
columns: 2,
align: (left, left),
stroke: none,
)
#show table.cell: it => {
if it.x == 0 {
set text(weight: "extrabold")
strong(it)
} else {
it
}
}
#table(
..arr
)
== List of Symbols
])
}
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/029_Aether%20Revolt.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("Aether Revolt", doc)
#include "./029 - Aether Revolt/001_In the Dead of Night.typ"
#include "./029 - Aether Revolt/002_Quiet Moments.typ"
#include "./029 - Aether Revolt/003_Breakthrough.typ"
#include "./029 - Aether Revolt/004_Revolution Begins.typ"
#include "./029 - Aether Revolt/005_Burn.typ"
#include "./029 - Aether Revolt/006_The Skies over Ghirapur.typ"
#include "./029 - Aether Revolt/007_Breaking Points.typ"
#include "./029 - Aether Revolt/008_Puppets.typ"
#include "./029 - Aether Revolt/009_Renewal.typ"
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/049%20-%20The%20Brothers'%20War/006_Chapter%202%3A%20Antiquities.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Chapter 2: Antiquities",
set_name: "The Brothers' War",
story_date: datetime(day: 24, month: 10, year: 2022),
author: "<NAME>",
doc
)
#emph[After Kroog was destroyed while most of its defenders were at his side, Urza vowed that none of his allies would ever need to fear for their own defense again, even while laying siege to a city far from their homes.]
—From an anonymous annotation in #emph[The Antiquities War] , by Kayla bin-Kroog, Folio Editione
#strong[Dominaria, Present Day]
Saheeli had lost count of how many times she'd tested the Temporal Anchor, starting shortly after she arrived on Dominaria just a handful of weeks ago. That first iteration, based heavily on blueprints given to her by Jodah, had been an unmitigated disaster. Apparently, the plans had belonged to an old artificer friend of Teferi's who he insisted got his contraption to work. Saheeli didn't see how. Within five minutes, she'd spotted glaring flaws in the design, many oriented around an alarming lack of protection for the occupant. So, she threw it away and started again. Sadly, her luck didn't change much with her own design.
But she couldn't give up. That wasn't an option.
Saheeli stepped back from her latest version of the Temporal Anchor, coil-shaped like the aether whorls that danced high in Kaladesh's skies. She flipped the switch on her control board, completing the circuit from the powerstone—once the power source to a legendary skyship called #emph[Weatherlight] —to the anchor's central junction. The powerstone, thrumming with intense white light, flickered as it sent energy through tightly wound copper coils into each subsystem.
Saheeli's attention remained on the key subsystem at the heart of the anchor, an artifact Teferi jokingly called a "coffin" that preserved a person's bodily operations while in stasis. In contrast to the original device detailed in Jodah's plans, Saheeli's Temporal Anchor did not transmit matter through the time stream. Instead, it projected a person's spirit backward in time, a function that Teferi insisted upon to bar the chrononaut—himself—from interfering in past events.
Safely separating a body and soul was a difficult task, one that Saheeli had no experience with. Thankfully, she had Kaya in the fold. By extending her ghostform over the coffin with Teferi inside, Kaya could render him entirely incorporeal, perfect for the anchor to do its work.
"Ready?" said Saheeli.
Kaya nodded and stepped inside the atrium where the coffin was suspended. Both Planeswalkers kept their eyes trained on the antenna array atop the anchor, an assembly that focused temporal energies at another of Teferi's artifacts, one he called the Moonsilver Key. None of these names mattered to Saheeli. The artifacts were simply components that contributed to a greater whole.
The room temperature climbed and humidity swelled as power flowed through the anchor. A sweet, pungent scent filled the air, like after a thunderstorm. Tiny dashes of electricity danced upon the anchor's filigreed edges, inching upward to the antenna array like a swarm of glowworms. A conduit of energy, like a shaft of light through smoke, began to form between the array and the Moonsilver Key.
That was Kaya's cue. Her form became hazy as violet tendrils of magical energy wrapped around her, extending over the coffin and anything that would be contained inside. A moment later, a thin red beam of energy shot from the key to the coffin, filling it with a crimson effluvium.
"It's stable!" cried Saheeli. But she spoke too soon. A shower of sparks poured out from a bank of circuitry where the powerstone wires connected to the anchor. #emph[No, no, no! Not again!]
Saheeli flipped the switch to power down the anchor, but it was too late to stop the chain reaction. Kaya leapt out of the anchor and took cover behind an ancient piece of wreckage that Saheeli had refashioned into a heat shield.
"Saheeli!" yelled Kaya. "Get away from there!"
Saheeli didn't hear her. There was still a chance to salvage this test. If she could quickly figure out what went wrong, she could fix it and cement the anchor's viability. Reaching out with her metalworking abilities, she let her consciousness ride the wires inside the machine, the current like a spirited charger, to find exact spot where the disruption started.
#emph[What the? . . .]
The power couplings hadn't simply burst. They had been torn apart. Raw energy poured out of the circuitry, bypassing the resistors that ensured proper power flow. #emph[Okay. All I need to do is repair the circuit. ] She ran over to the damaged section and focused her powers on mending the wires.
Suddenly, a pulse of white light engulfed the whole area. In the same moment, Saheeli felt her entire body grow ice cold. She couldn't breathe but found that she didn't have to. She looked down to see Kaya gripping her hand, extending her ghostform to protect them both from the explosion. Once her initial bewilderment passed, Saheeli noticed something else, some #emph[thing] hovering just a few feet away. She didn't see it as much as feel it—a presence that inspired a profound melancholy in her.
Then Kaya let her go, leaving Saheeli dizzy and gasping for air. She sat on the floor in front of the anchor trying to process what she'd just experienced. None of it made sense. She'd checked every system in the anchor before switching it on. No way a malfunction like that should have happened. And then there was that #emph[thing] .
"Kaya, you're going to think I'm crazy—"
"You're not crazy," said Kaya. "I saw it, too."
"You did? What do you think it was?"
"I know what it was, and I know what caused it." She led Saheeli, careful to step around the metal shards that had once been part of the anchor, to an innocuous-looking crate shoved underneath one of the workbenches. "There."
Saheeli pulled out the crate and uncovered it to reveal a black crystal orb encased in a cage of silver. This only confused her more. "Teferi gave it to me along with the other artifacts to create the anchor. He insisted it was important, but I couldn't figure out what it did or even what it was. So I stored it away."
"Let's find him," said Kaya. "Because I want to know why this thing is creating ghosts."
#strong[Kaladesh, Years Ago]
Saheeli recognized a piece by <NAME> in the far corner of the room, a cat-sized sculpture of living metal that changed shape in response to the sounds around it. In the center of the fine ebonywood table she sat at was a prototype model of Jitya Reyath's aether crucible, a steady trickle of raw blue aether bubbling up from its center. Both one-of-a-kind pieces had been stolen from the Ghirapur Institute of Art and Science one month before. Other baubles of similar opulence decorated the room, all tinged with the fact that they'd been liberated from their rightful owners across the city.
The thugs had taken her at the perfect time—for them at least. Like most of the population of the city, she'd attended the spring festival, replete with dancers in flowing, patterned outfits filling the streets with muslin spirals of purple, pink, and orange. All strata of society flooded public squares to share food and gossip while fleets of kites fluttered overhead. Her kidnappers merely had to wait amid the raucous chaos until she stepped in front of the right alleyway.
The next thing she knew, she woke up tied to a chair in this place. The light was minimal—small lanterns adorned the tops of tables next to luxurious couches that probably cost more than her house. The two men that had grabbed her stood on either side of her, and across the table from her sat the erstwhile host of this private soirée, clad all in black save for a faceplate of finely inlaid gold. With a single hand motion, the host ordered the men to leave. Saheeli turned her head to see where they were going when the host stopped her.
"Oh, don't look back," said the host in a deep, echoing baritone. "No matter the predicament, you must never turn away from what's most important."
"Or most dangerous."
"<NAME>, youngest artificer to ever be invited to the Institute. Daughter to Aarav and Ruby, sister to Sheela, Amika, and Sahil. A decent, law-abiding citizen of Ghirapur with a few petty violations that are common among youth. Is all this correct?"
"You know a lot about me."
"No, I know #emph[everything] about you," said the host. "But my manners~ such a disparity between us is uncivil. Let me introduce myself. I am—"
"Gonti, lord of the Night Market."
"Ha. I knew I chose the right person for this job. But then, who I am is hardly a test for your intellect. Let me give you a better one." Leaning back, Gonti unfastened the buttons on their shirt, from top to bottom, exposing their chest for Saheeli to see. She'd seen aetherborn skin up close before, finding it to have the look and feel of smooth chalk. But that's not what she saw under Gonti's shirt. Their "flesh" had the look of cracked stone, hard and strong, and embedded in their chest was a metal device made of rotating gears. "Thoughts?"
Yes, she had thoughts. There'd always been conjecture on just who Gonti was, since their reign over Ghirapur's underworld had lasted well longer than an aetherborn's lifespan. Now she had the answer. "Am I here to gawk?"
"Hardly." Gonti reached under the table and produced a small bag, which they slid over to Saheeli. She looked inside to discover a suite of tools any artificer would be envious of: diamond tipped tweezers, an array of loupes, pliers, cutters, and vices optimized for delicate tasks. "My heart," Gonti said, tapping the mechanism in his chest. "It has begun to fail. I don't believe I can adequately describe what it's like to feel yourself wasting away in real time. You're here to fix it."
Here was the criminal mastermind of the city, responsible for theft, corruption, and murder—and they brought her here to save their life? No. That wasn't happening. Saheeli could bring about more peace in Ghirapur than the Consulate ever had by doing nothing. "I think it's beyond my knowledge to help," she said. "I'm sorry."
"You disappoint me. I thought you'd be eager to explore such a rare invention. But I can't say this wasn't expected." Gonti reached into the front pocket of their shirt, pulled out a slim golden chain, and slid it across the table. Saheeli caught it and held it up to look at. Gold shaped into ivy with amethyst flowers. This was her mother's bracelet. She'd know it anywhere.
"What is the meaning of this?"
"Don't play the fool," said Gonti. "It's quite obvious. My associates have already gathered your family members inside your place of residence. If I don't send word in the allotted time, their instructions are to execute everyone. Starting with your mother."
Saheeli clutched her mother's bracelet and pressed it to her forehead. "You're a monster."
"One with little time to spare. Much like yourself."
#strong[Dominaria, Present Day]
Teferi was nowhere to be found, but Saheeli and Kaya were able to track Jodah down in one of the many unused chambers inside the tower. He sat on the ground with his legs folded, speaking into what looked like a cloud of shimmering mercury that hung in the air.
"You're such a mother," he said to the person appearing inside the cloud, a woman with tan skin and dark, red-streaked hair. "Teferi's fine. Better than fine, all things considered."
"He's still bent on going back?" asked the woman.
Jodah threw his arms up. "There isn't much of a choice."
"Time travel," she said, shaking her head. "I hope he knows what he's doing."
"It could be worse. He could have decided to go back and talk to—"
Standing in the doorway with Kaya, Saheeli cleared her throat loudly. Jodah looked up from his conversation. He put on an uneasy smile and held up his hand in a "one moment" gesture.
"Jhoira, I've got to go," he said, standing up. "Give my love to Adeliz."
"You could contact her yourself, you know."
"Yes, but then we'd have to catch up and explain our current projects. Something inevitably would come up, cutting our chat short, and by the time we could resume, so much would have happened that we'd have to do it all over again."
"You two are so alike. It's annoying."
"You mean endearing, right?"
"No," she said as the cloud began to dissipate. "Take care of yourself, Jodah."
"You, too." Jodah turned to the Planeswalkers waiting at the door. "My apologies. What can I do for you two?"
Saheeli didn't mince words: "We believe that a spirit has been sabotaging the Temporal Anchor and that it is being created by whatever this black orb is that Teferi gave me."
"Wait, wait. Slow down," Jodah said. "Exactly how does one #emph[create] ghosts? I mean apart from the obvious way of, you know, killing people."
"Maybe 'creating' is the wrong word," said Kaya. "More like strengthening a spirit that's already there. The longer a spirit is left on a physical plane, the more indistinct it becomes, like a mist in a breeze, unless something comes along to give it enough energy to fully form again. I saw a silver cord extending from the orb to the spirit. A direct channel of psychic energy."
"Assuming you're right," Jodah began, "couldn't you just move the orb out of the workshop? Even take it away to another plane?"
"It's been around for weeks," said Kaya. "The spirit has been gorging itself that whole time. It could take centuries before it dissipates enough to leave us alone."
Jodah accompanied them back to the scene of the incident to give his own impressions. When they arrived, Saheeli gingerly led Jodah around sharp debris to show him Teferi's mysterious orb. He touched the silver cage with his fingers and poked the crystal orb inside with the end of his staff. Soft lights inside the orb winked in and out of existence. He prodded a bit more before taking the orb and turning it over to look at its underside. He ran his fingers over the same small patch of silver again and again.
"<NAME>," he said, hanging his head. "What have you done now?"
"Who?" asked Kaya.
"Urza," he replied. "The man who built this tower. The Planeswalker who vanquished the Phyrexians when they invaded this plane a millennia ago. Teferi's teacher. And my ancestor."
"And you didn't say anything about it because?"
"Because family matters are rarely simple." Jodah placed the orb onto the table, uttered a spell, and gathered the others around to see part of the orb's silver cage begin to glow red. "I don't suppose you noticed the script hidden in the silver mesh."
Saheeli hadn't. But with Jodah's spell, she could plainly see a faint inscription. Even if she had seen it before, she would have dismissed the series of geometric shapes laid on top of each other—squares, triangles, and circles repeating and overlapping with no discernible pattern—as an artificer's signature.
"It's the written language of the Thran, an ancient civilization on this plane," said Jodah. "Few people alive in the last five thousand years could read their language. I can. Urza and the Tolarians under his tutelage could as well. I have little doubt that this orb is his doing."
"What does the message say?"
"#emph[Go back to the beginning and greet me properly.] "
"What does that mean?" asked Saheeli. "Could it be Urza disrupting the anchor?"
"For many reasons, I'm confident that Urza is not the spirit in question," answered Jodah. "As for the meaning of the message, all I know for sure is if Urza is involved, it's probably trouble."
Another evasive answer, Saheeli noted. While she hadn't known Jodah for as long as Teferi or certainly members of the Gatewatch, she would have liked to think the past few weeks together had engendered some manner of rapport between them. They'd eaten together, chatted over tea, exchanged stories. They were on Dominaira ostensibly working toward a common purpose of thwarting the Phyrexians—a threat that endangered countless planes, including her own. There was no room for hiding such important information.
"All the more reason to take care of this thing quickly," said Kaya. "And permanently."
"Hold on," said Saheeli. "That spirit was once a living being, right? Wouldn't it be better if we could find out what it wants?"
Kaya sunk into her seat. "Lingering spirits only want a few things—most of them bad. But I'll hear you out. What do you propose?"
"The way you talked about them before—it was as if they were energy beings."
"Sure," said Kaya. "What's the soul but energy driven by will?"
"Exactly. I think I have something that could help us deal with our visitor."
#strong[Kaladesh, Years Ago]
"Incredible," Saheeli blurted out before she could stop herself. The last thing she wanted to give Gonti was the satisfaction of being right about her. Despite the circumstances, a part of her was thrilled to examine such a marvel of engineering so closely. The heart didn't merely prolong Gonti's existence—a feat to be sure, but nothing compared to what it constituted. At the center of the heart was a honeycomb-shaped module that pulled aether directly from the atmosphere. Fresh raw aether continually circulated through Gonti, renewing their body. Forever.
In short, Gonti was immortal.
"How much longer?" Gonti asked. They lay still, a model of a patient, upon their expensive boardroom table. Gonti didn't so much as twitch as she probed and prodded them.
"It's a delicate process," said Saheeli, lifting feather-light, semi-transparent membranes inside the heart with tapered tweezers. "It requires all my concentration."
"Not all," they said. "Your dedication—to your craft, to your family—is certain. But I can also sense your rebelliousness, a scent like cut cloves." Saheeli quietly cursed. Like all the other aetherborn she'd encountered, Gonti had the ability to read emotions and interpret them as various scents. Here, with no one else around, it was impossible to hide even her deepest thoughts. "It is understandable. Conflict is the natural state of things, even within an individual."
"Easy for you to say when you steal and kill for a living."
"How amusingly naive."
Naive? Where were they when the Consulate sweeps rounded up the homeless to satisfy the aristocrats seeking scapegoats for crimes Gonti and his cronies committed? How many innocents were caught in the crossfire between warring factions of Gonti's own people squabbling over profits? And how many more lived in fear of losing their homes and livelihoods to their greed? She turned back to the heart, but like before, she couldn't stop herself from saying what was on her mind. "I wish we could live in peace without you destroying our lives."
Gonti's tone grew grim. "I remember a time when my kind were hunted like animals. People knew what we were; they just were very irritated #emph[that] we were. Do not talk of destroyed lives when you have no idea what that means."
Saheeli wanted to rebut Gonti, but what could she say? They were right. The first aetherborn were chased and killed by engineers who dismissed them as a side effect of aether refinement. A mistake. Yes, things had changed for the better, but what of the past? How does a society repair that kind of damage?
She didn't have the answers, and it wasn't her place at that moment to pursue them. All she could do was protect her family the best she could. Digging deep into Gonti's chest, she located the problem. The core of the aether heart was comprised of a revolving silver filament no bigger than a fingernail. The filament's motion governed the cadence with which the gears churned aether, much like a human heart pumped blood in regular intervals. A small fracture in the filament had developed over time—the simplest of repairs to make. Saheeli tapped her finger on the filament, its surface rippling like water until the crack was healed.
"I've fixed the damage," said Saheeli. "Do you feel any different?"
At first, Gonti was silent. Slowly, they sat up and turned to her. "I feel magnificent."
"Then tell your men to stand down."
"I already did," said Gonti as they buttoned up their shirt. "Those two I sent before we began talking conveyed the message. Your family was never in any danger. Consider it an act of faith. In you."
Saheeli began shaking—not out of anger, but of joyful relief.
Gonti hopped off the table, stopping to lament a scuff mark on the surface. They extended a hand for Saheeli to take, which she did, not wanting to anger Gonti enough to place her family back into danger. They led her to a window at the far rear of the room. Drawing back the curtains, Gonti revealed a stunning view of Ghirapur, its high spires decorated with lights for the spring festival. Down below, thousands reveled in the streets. "My city. Beautiful, isn't it? We are allied now, but make no mistake, it brought its war to me first, like it did all aetherborn. Instead of crumpling, I embraced its thick, spiny hide. To win a war, you must #emph[become] the war. That is the way of things."
#strong[Dominaria, Present Day]
Saheeli flipped the power switch on the Temporal Anchor for the second time that day. The apparatus charged up in its normal fashion—energy routing from the powerstone into the rest of the anchor, Kaya in place waiting for her part to play out. Looking around the workshop, she wondered if the spirit was lurking unseen, watching her every action.
She hoped so.
"Kaya, are you ready?" Saheeli called out.
"Yes," she said, placing her hands on the coffin. "I hope this works."
The energy conduit began to materialize between the antenna array and the Moonsilver Key. Saheeli kept still, her gaze locked on Kaya. The only movement she dared to make was to slide her finger from the power switch on her control board to a second one. Kaya became incorporeal, filling the anchor's atrium with violet wisps of magic. Everything had to seem like they were just trying another test. That was the bait.
#emph[Where are you?] Saheeli wondered.
"It's here!" yelled Kaya. "Do it now!"
Saheeli flipped the second switch, shunting power from the anchor's normal operations to a newly built subsystem. Instead of absorbing and directing the antenna's signal, the Moonsilver Key began to revolve, causing the air in the room to feel thick. A greenish fog rose from the floor as a sudden nausea bubbled up from her stomach, forcing her to lean on her worktable.
There in front of the anchor, a gray shape began to take form like frost on a pane of glass. Limbs defined themselves, as did a head and torso. Then more—the face of a man, worn and tired, his beard unshorn and wild; a heavy suit of armor emblazoned with the head of a lion.
"Who are you?" Saheeli yelled, pushing herself to her feet.
Shock streaked across the spirit's face. It turned to flee, but found itself slowed, unable to take more than a few halting steps away from the anchor. Saheeli's trap worked! By replicating the cadence of energy pumping through Gonti's aether heart, Saheeli had succeeded in giving the spirit a semblance of solidity. Without its ability to dissolve or pass through solid barriers, it would have no choice but to communicate with her.
"We don't mean to hurt you! Tell us what you want!"
The spirit hesitated, allowing her to extend her hand in a sign of friendship. It responded by shoving her to the ground, its touch frigid, like freshly turned dirt on a grave. Unbuckling a ghostly blade from its belt, the spirit raised its weapon above its head. Kaya sprang into action, diving to the floor to pull Saheeli out of harm's way. But Saheeli was never its target. The blade struck the anchor, gouging a deep gash into its side. Kaya hurled a blade at the spirit, but it had already fled out the workshop door.
"Are you alright?" she asked Saheeli. Kaya's concern didn't fully mask her frustration. She'd been doubtful about Saheeli's attempt at communication and turned out to be right.
"I'm not hurt."
"Good. Make sure the anchor is okay. I'm going after it."
Kaya bolted out the door leaving Saheeli to assess the anchor. While the damage was severe—the power stabilization subsystem had been hacked to pieces—the key and the coffin were untouched. Repairs would be extensive but doable. Saheeli sighed, but the relief was short-lived. She hurried out the door to track Kaya down, hoping to reach her before the ghost assassin. It had understood her. If the situation were calmer, a dialogue was possible.
Saheeli ran through the tunnels connecting the workshop to the tower proper, emerging into the corridor that encircled the main hall. She spotted Jodah across the way. While she and Kaya were working to modify the anchor, he'd sequestered himself with the Starfield Orb to glean any answers he could.
"Where is Kaya?" she called out.
"I saw her go upstairs," said Jodah. "Follow me!"
Saheeli and Jodah ran up to the second floor of the orniary where they saw Kaya, daggers in hand, face to face with the partially solid spirit, its own chunky, squarish blade held at the ready.
"It's disintegrating fast," said Kaya. "If we don't take care of it now, it'll be a lot harder to pin down." Kaya was right if the goal was to destroy the spirit. But Saheeli clung to the notion that a peace could be reached. She knew it was foolish. She knew it had cost them precious time. But the thought of inflicting needless harm did not sit well with her.
"My name is <NAME>," she said. "What's yours?"
"Sharaman," the spirit said, keeping its weapon raised.
"General Sharaman," said Jodah. "The leader of Urza's armies."
"Are you here on behalf of that snake?" said Sharaman, his form wavering.
"Your war is almost five thousand years over with," said Jodah. "If this is about revenge—"
"Not revenge. Preservation. You would restart Urza's war machine."
"I'm sorry for what happened to you," said Saheeli. "But the foes we fight—they are a threat to all the people of Dominaria and planes beyond."
"I served Urza faithfully for decades~ My nephews. Good boys. I cradled their corpses split apart by Mishra's dragon engines." His form became hazier as the effects of Saheeli's trap weakened. "I stood by while he ordered the sacking of Sardia and other provinces that wouldn't give over their resources. I thought that history would forgive us because we were the righteous ones." He looked straight at Saheeli. "I will not let anyone repeat the mistakes I made. If that means stopping you, I will do so."
"I~" She didn't know what to do. Sharaman wasn't just some temperamental spirit. He had lost so much—his family, his life. She had to convince him that their efforts were necessary. "Sharaman, there must be some way—"
Kaya didn't wait for Saheeli to finish. As Sharaman faded from view, she activated her ghostform and lunged at the spirit, her ethereal form swelling into a wave of death. She swung out with her dagger, parrying a strike that only she could see, then spun around with a backward stab. Saheeli watched as Kaya dropped her weapon and knelt. Kaya's lips moved, but Saheeli heard no sound. She walked to where Kaya was kneeling and waited for her to rematerialize.
Kaya stood up, visibly shaken. "I'm sorry. He didn't give us much choice."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Teferi rested his head against the padding inside of the coffin, his smiling face visible through a small porthole. He'd been in surprisingly good spirits when he came in for the test, a far cry from his pensiveness during his morning visit. Saheeli hoped that she could find the solace that he'd somehow found. A quiet walk around the tower environs, perhaps. Yes, that could help.
Saheeli did her final review of the Temporal Anchor. All subsystems checked out, both old and new. She nodded to Kaya, giving her the go-ahead to step into the anchor for what she hoped would be a successful run. Ever since the confrontation with Sharaman, Kaya's usual swagger had been missing.
"Are you sure you're okay to do this now?" asked Saheeli.
"This is too important to delay."
"That wasn't my question."
She smiled. "I wish I was more like you—a good person."
"You are a good person, Kaya," said Saheeli.
She shook her head. "Sharaman wasn't ever going to relent. That's how spirits are. Their obsessions are what root them to the physical world. Those I'd dealt with before—they were tyrants, villains, the worst of the worst. I could justify giving them the punishment they deserved. But him?"
"Did he say something to you at the end?"
"He wanted to know if he would see his family again," said Kaya. "I told him that he would." With that, Kaya stepped into the anchor and got into position. "Let's do this."
Saheeli switched on the anchor. It whirred to life. Energy channeled upward to the antenna, then through the Moonsilver Key, and finally into the coffin containing Teferi within Kaya's ghostform.
The anchor was going to work. Saheeli knew it already. Turning away for just a moment, Saheeli allowed her thoughts to wander. She thought back to that night on Kaladesh years ago, walking into her house after leaving Gonti's estate. Tables of hot food and cold drinks, maintained by servo constructs. A gaggle of her younger cousins who, by the look of their costumes, had taken part in the spring dances for the first time. The warmth she felt in her family's embrace~ A warmth that enveloped her like a single fingerstroke on the back of a hand, like measured steps upon Ravnican cobblestones, like Huatli's lips—the most perfect in all the Multiverse—forming the words, #emph[I will come dance with you.]
Unlike Gonti, Saheeli hadn't given up on peace. But if those she loved needed her to, she would become the war.
#strong[Epilogue]
Teferi had mentioned the Starfield Orb to Jodah once, explaining how he'd obtained it in one of the hidden caches Urza left behind sometime during the Phyrexian Invasion. But he downplayed the orb's significance. Maybe it had confounded him? No, it was more likely that Teferi erred on the side of wisdom by assuming the orb was too dangerous to fiddle with. Jodah would have done the same, especially after detecting the use of soul energy in the orb's enchantments. No wonder it affected spirits like it did. Urza had truly fallen into dark practices in his final days.
Jodah regretted not being forthright with the others about the orb—or Urza and the tower, for that matter. He'd done it to protect them, but he still disliked keeping secrets from his allies, Saheeli especially. In Jodah's estimation, she was the perfect collaborator for Teferi to have recruited for their efforts. Adept, yet compassionate. Unlike so many of the Planeswalkers he'd dealt with over the centuries—even the ones he held dear, like Freyalise (eventually)—Saheeli's humanity always shone through.
She was a better person than he or Teferi had been in their youth.
Hours past midnight, Jodah sat at the base of one of the outer watchtowers, the Starfield Orb on the ground in front of him. If anyone was going to put himself at risk to investigate one of Urza's many schemes, it was going to be him.
He began to cast a spell.
It was a child's magic. Jhoira was the first to show it to him back when they'd been more than the distant friends they were today. She'd grown tired, as she often did, of his pedantic complaints about this professor or that at Tolaria West. So, she cast a spell on him, shocking him into silence. Between bouts of laughing, she explained that it was the very first spell she'd learned from Teferi, one that jolted a person with a rather strong electric shock. It was infamous among the students of Tolarian Academy; the professors, too, eventually learned to refrain from shaking Teferi's hand. Yes, that included Urza.
#emph[Go back to the beginning and greet me properly.]
Jodah held his hand out, directing the shock at the orb. In a blue flash, the world vanished, replaced a moment later by the interior of an austere cottage. The room was illuminated, but there didn't seem to be any origin for the light. Jodah found himself seated at a grand table. On top, a vast array of toy figurines almost impossibly small—soldiers, some on horseback, against a squadron of mechanical dragons—were in a simulated battle.
"Urza, you old git," he said softly. "A pocket dimension." And not just any. This pocket dimension was made to resemble the cabin Urza lived in more than a thousand years before. It had been located in the Ohran Mountains on the isle of Gulmany, a fact Jodah knew because he'd paid it a visit once upon a time.
He got up to look over a tall bookshelf packed with thick manuscripts, recognizing the names of several volumes long thought lost. One caught his eye. He plucked it off the shelf and inspected the cover, sinking his fingertips into the worn grooves in the leather. #emph[Calfskin emblazoned with a lion's head—the symbol of Argive] , he noted. Flipping through the pages, he stopped on a diagram of an ornithopter, pointing out the small capital #emph[T] in the corner of the page. #emph[Stamped woodcuts of original illustrations by the artificer, Tawnos.] Then he turned to the title page.
"#emph[The Antiquities War] by <NAME>," a voice behind him announced. Jodah spun around to see a woman in padded armor, her hair pulled back from her angular face. "That's the folio edition," she said. "Produced to commemorate the first gathering of the Sages of Minorad. There are several copies of this work on the shelf, all different editions, from scroll to tome."
"I know you," said Jodah. "Xantcha. You were Urza's companion."
"In my dreams, I am Xantcha," the woman said. "But I am not her. Everything she was is contained within the golem, Karn."
"What are you, then?"
"A construct, like all you see here."
Jodah had met the real Xantcha briefly. She was curious, almost like a child, and asked him all manner of questions about Dominarian history and distant lands. Jodah remembered thinking how odd a pairing she and Urza made, but also that her presence seemed to mollify the most abrasive parts of his personality.
A door at the far side of the room opened, and stepping inside was another individual, this one a man, stout and severe, with dark hair and a harried brow. Flipping back through #emph[The Antiquities War ] again, Jodah arrived at a portrait that matched the man.
"Mishra," said Jodah. "You are a construct as well."
"You do not match the description of Teferi," Mishra said before drawing a short sword and pointing it at Jodah. "You're an intruder."
"Hold," Xantcha ordered, then turned to Jodah. "Who are you, and what is your purpose here?"
"My name is Jodah, friend of Teferi's and descendant of Urza," said Jodah. "How else would I have gained access to this place?"
That seemed to satisfy them. They stood down, allowing Jodah to continue examining the bookshelf. He placed back #emph[The Antiquities War ] and picked out a roughly bound file of pages from the very bottom shelf. This was a collection of schematics, plans—all the instructions needed to rebuild Urza's armies of Yotian soldiers and clay statues. A smaller folder within the file contained even more arcane information on familial lineages along with a grand design of disparate objects all united into a singular weapon.
"The Legacy," said Jodah. "This whole place—it's Urza's failsafe in case he perished before he could deploy it against the Phyrexians." He laughed, remembering what Teferi had said about obtaining the orb. #emph[It was like Urza targeted every weakness of mine. But I beat him!] No, no one ever beat Urza at that kind of mind game. He'd put nigh-impossible obstacles in front of the orb #emph[because ] he knew that only Teferi would have the mettle and audacity to overcome them.
Jodah closed the file and held his hand on the cover. Xantcha and Mishra had been watching him the entire time, their blank expressions never changing.
"Teferi has his hands full right now," he told them. "But when all of that has passed, and when he's ready, I will tell him about this place. In the meantime, did your master leave any final words?"
"Yes," said Mishra. "'Let us end our conflicts. We cannot afford to differ any longer.'"
|
|
https://github.com/max-niederman/CS250 | https://raw.githubusercontent.com/max-niederman/CS250/main/hw/6.typ | typst | #import "../lib.typ": *
#show: homework.with(title: "CS 250 Homework #6")
= Counting
== 1
By the multiplication principle,
there are $ 4^20 dot 5^10$
== 2
By the multiplication principle,
there are $26^3 dot 10^2$.
== 3
There are $2 dot 4 + 4 dot 2 = 16$
== 4
No, there are only $10^2 = 100$ possible combinations.
== 5
The first digit must be 2 or 4, so
$ 2 dot 4 dot 4 = 32 $
= Inclusion and Exclusion
== 1
$ (35 + 18) - 42 = #{35 + 18 - 42} $
So ten people.
== 2
*skipped*
== 3
*skipped*
== 4
*skipped*
== 5
*skipped*
= Permutations and Combinations
14
21
24
25
26
== 1
There are an odd number of men, so they must be at the ends and they must alternate. Therefore, the number of permutations is
$ 11! dot 8! $
== 2
By the multiplication principle and the binomial formula,
$
binom(17, 5) dot binom(23, 7)
= 17!/(5!12!) dot 23!/(7!16!)
$
== 3
First we choose two members from manufacturing,
then we multiply by the possible ways to choose four from out of manufacturing:
$
binom(14, 2) dot binom(7 + 4 + 5 + 2 + 3, 4)
$
== 4
First choose one of the two accountants,
then multiply by the possible ways to choose the others:
$
2 dot binom(7 + 14 + 4 + 5 + 3, 5)
$
== 5
There are $ binom(7 + 4 5 + 2 + 3, 6) $
ways to choose committees with zero manufacturing members,
and $ 14 dot binom(7 + 4 + 5 + 2 + 3, 5) $
ways to choose committees with one manufacturing member.
Subtracting from the total number of committees gives
$
binom(7 + 14 + 4 + 5 + 2 + 3, 6) - binom(7 + 4 + 5 + 2 + 3, 6) - 14 dot binom(7 + 4 + 5 + 2 + 3, 5)
$ |
|
https://github.com/syamkarni/personalCV | https://raw.githubusercontent.com/syamkarni/personalCV/main/main.typ | typst | #import "cv.typ": *
//#let cvdata = yaml("example.yml")
#let cvdata = json("data.json")
#let uservars = (
headingfont: "Linux Libertine",
bodyfont: "Linux Libertine",
fontsize: 10pt, // 10pt, 11pt, 12pt
linespacing: 6pt,
showAddress: true, // true/false show address in contact info
showNumber: true, // true/false show phone number in contact info
headingsmallcaps: false
)
#let customrules(doc) = {
set page(
paper: "us-letter", // a4, us-letter
numbering: "1 / 1",
number-align: center, // left, center, right
margin: 1.25cm, // 1.25cm, 1.87cm, 2.5cm
)
doc
}
#let cvinit(doc) = {
doc = setrules(uservars, doc)
doc = showrules(uservars, doc)
doc = customrules(doc)
doc
}
#show: doc => cvinit(doc)
#cvheading(cvdata, uservars)
#cvabout(cvdata)
#cvwork(cvdata)
#cveducation(cvdata)
#cvprojects(cvdata)
#cvskills(cvdata)
#cvaffiliations(cvdata)
#cvvdata(cvdata)
#endnote() |
|
https://github.com/mintyfrankie/brilliant-CV | https://raw.githubusercontent.com/mintyfrankie/brilliant-CV/main/docs/docs.typ | typst | Apache License 2.0 | /*
* Documentation of the functions used in the template, powered by tidy.
*/
#import "@preview/tidy:0.3.0"
#import "./docs-template.typ": *
#let version = toml("/typst.toml").package.version
#show: template.with(
title: "brilliant-cv",
subtitle: "Documentation",
authors: ("mintyfrankie"),
version: version,
)
#h(10pt)
#h(10pt)
== 1. Introduction
Brilliant CV is a Typst template for making Résume, CV or Cover Letter inspired by the famous LaTeX CV template Awesome-CV.
== 2. Setup
=== Step 1: Install Fonts
In order to make Typst render correctly, you will have to install the required fonts #link("https://fonts.google.com/specimen/Roboto")[Roboto]
and #link("https://fonts.google.com/specimen/Source+Sans+3")[Source Sans Pro] (or Source Sans 3) in your local system.
=== Step 2: Check Documentation
You are reading this documentation now, woah!
=== Step 3: Bootstrap Template
In your local system, just working like `git clone`, boostrap the template using this command:
```bash
typst init @preview/brilliant-cv:<version>
```
Replace the `<version>` with the latest or any releases (after 2.0.0).
=== Step 4: Compile Files
Adapt the `metadata.toml` to suit your needs, then `typst c cv.typ` to get your first CV!
=== Step 5: Go beyond
It is recommended to:
1. Use `git` to manage your project, as it helps trace your changes and version control your CV.
2. Use `typstyle` and `pre-commit` to help you format your CV.
3. Use `typos` to check typos in your CV if your main locale is English.
4. (Advanced) Use `LTex` in your favorite code editor to check grammars and get language suggestions.
#pagebreak()
== 3. Migration from `v1` to `v2`
With an existing CV project using the `v1` version of the template,
a migration is needed, including replacing some files / some content in certain files.
1. Delete `brilliant-CV` folder, `.gitmodules`. (Future package management will directly be managed by Typst)
2. Migrate all the config on `metadata.typ` by creating a new `metadata.toml`. Follow the example toml file in the repo,
it is rather straightforward to migrate.
3. For `cv.typ` and `letter.typ`, copy the new files from the repo, and adapt the modules you have in your project.
4. For the module files in `/modules_*` folders:
a. Delete the old import `#import "../brilliant-CV/template.typ": *`, and replace it by the import statements in the new template files.
b. Due to the Typst path handling mecanism, one cannot directly pass the path string to some functions anymore.
This concerns, for example, the logo argument in cvEntry, but also on `cvPublication` as well. Some parameter names were changed,
but most importantly, you should pass a function instead of a string (i.e. `image("logo.png")` instead of `"logo.png"`).
Refer to new template files for reference.
c. You might need to install `Roboto` and `Source Sans Pro` on your local system now,
as new Typst package discourages including these large files.
d. Run `typst c cv.typ` without passing the `font-path` flag. All should be good now, congrats!
Feel free to raise an issue for more assistance should you encounter a problem that you cannot solve on your own :)
#pagebreak()
== 4. Confuguration via `metadata.toml`
The `metadata.toml` file is the main configuration file for your CV. By changing the key-value pairs in the config file, you can
setup the names, contact information, and other details that will be displayed in your CV.
Here is an example of a `metadata.toml` file:
```toml
# INFO: value must matches folder suffix; i.e "zh" -> "./modules_zh"
language = "en"
[layout]
# Optional values: skyblue, red, nephritis, concrete, darknight
awesome_color = "skyblue"
# Skips are for controlling the spacing between sections and entries
before_section_skip = "1pt"
before_entry_skip = "1pt"
before_entry_description_skip = "1pt"
[layout.header]
# Optional values: left, center, right
header_align = "left"
# Decide if you want to display profile photo or not
display_profile_photo = true
profile_photo_path = "template/src/avatar.png"
[layout.entry]
# Decide if you want to put your company in bold or your position in bold
display_entry_society_first = true
# Decide if you want to display organisation logo or not
display_logo = true
[inject]
# Decide if you want to inject AI prompt or not
inject_ai_prompt = false
# Decide if you want to inject keywords or not
inject_keywords = true
injected_keywords_list = ["Data Analyst", "GCP", "Python", "SQL", "Tableau"]
[personal]
first_name = "John"
last_name = "Doe"
# The order of this section will affect how the entries are displayed
# The custom value is for any additional information you want to add
[personal.info]
github = "mintyfrankie"
phone = "+33 6 12 34 56 78"
email = "<EMAIL>"
linkedin = "johndoe"
# gitlab = "mintyfrankie"
# homepage: "jd.me.org"
# orcid = "0000-0000-0000-0000"
# researchgate = "John-Doe"
# extraInfo = "I am a cool kid"
# custom-1 = (icon: "", text: "example", link: "https://example.com")
# add a new section if you want to include the language of your choice
# i.e. [[lang.ru]]
# each section must contains the following fields
[lang.en]
header_quote = "Experienced Data Analyst looking for a full time job starting from now"
cv_footer = "Curriculum vitae"
letter_footer = "Cover letter"
[lang.fr]
header_quote = "Analyste de données expérimenté à la recherche d'un emploi à temps plein disponible dès maintenant"
cv_footer = "Résumé"
letter_footer = "Lettre de motivation"
[lang.zh]
header_quote = "具有丰富经验的数据分析师,随时可入职"
cv_footer = "简历"
letter_footer = "申请信"
# For languages that are not written in Latin script
# Currently supported non-latin language codes: ("zh", "ja", "ko", "ru")
[lang.non_latin]
name = "王道尔"
font = "Heiti SC"
```
#pagebreak()
== 5. Functions
#h(10pt)
#let docs = tidy.parse-module(read("/cv.typ"))
#tidy.show-module(
docs,
show-outline: false,
omit-private-definitions: true,
omit-private-parameters: true,
)
|
https://github.com/L364CY-FM/typst-thesis | https://raw.githubusercontent.com/L364CY-FM/typst-thesis/main/projektarbeit/thesis.typ | typst | MIT License | #import "templates/thesis_template.typ": *
#import "templates/cover.typ": *
#import "templates/titlepage.typ": *
#import "templates/disclaimer.typ": *
#import "acknowledgement.typ": *
#import "abstract.typ": *
#import "metadata.typ": *
#cover(
title: title,
degree: degree,
author: author,
)
#titlepage(
title: title,
degree: degree,
supervisor: supervisor,
advisors: advisors,
author: author,
startDate: startDate,
submissionDate: submissionDate
)
#disclaimer(
title: title,
degree: degree,
author: author,
location: location,
submissionDate: submissionDate
)
#acknowledgement()
#abstract()
#show: project.with(
title: title,
degree: degree,
supervisor: supervisor,
advisors: advisors,
author: author,
startDate: startDate,
submissionDate: submissionDate
)
= Einleitung
#lorem(100)
= Zitieren
Dieser Satz wurde zitiert @bruegge2004object.
= Bilder
@logo_htwk zeigt ein Beispiel für ein Bild.
#figure(
image("figures/logo.png", width: 25%),
caption: [Logo der HTWK]
) <logo_htwk>
= Tabelle
#figure(
table(
columns: (1fr, 2fr),
inset: 10pt,
align: horizon,
["Erste Spalte"], ["Zweite Spalte"],
["Dritte Spalte"], ["Vierte Spalte"],
),
caption: "Beispieltabelle"
) |
https://github.com/AquaBx/omd-tp-1 | https://raw.githubusercontent.com/AquaBx/omd-tp-1/main/compte-rendu/cr.typ | typst |
#let problem_counter = counter("problem")
#let prob(body) = {
// let current_problem = problem_counter.step()
block(fill:rgb(250, 255, 250),
width: 100%,
inset:8pt,
radius: 4pt,
stroke:rgb(31, 199, 31),
body)
}
// Some math operators
#let prox = [#math.op("prox")]
#let proj = [#math.op("proj")]
#let argmin = [#math.arg]+[#math.min]
#let logo_esir = "img/esir.png"
#let logo_univ = "img/univ.png"
#let to-string(content) = {
if content.has("text") {
content.text
} else if content.has("children") {
content.children.map(to-string).join("")
} else if content.has("body") {
to-string(content.body)
} else if content == [ ] {
" "
}
}
// Initiate the document title, author...
#let assignment_class(title, author, course_id, professor_name, due_time, body) = {
set document(title: title, author: author)
set heading(numbering: "1.")
set page(
paper:"us-letter",
header: locate(
loc => if (
counter(page).at(loc).first()==1) { none }
else if (counter(page).at(loc).first()==2) { align(right,
[*#author* | *#course_id #title* ]
) }
else {
align(right,
[*#author* | *#course_id #title* ]
)
}
),
footer: locate(
loc => {
if counter(page).at(loc).first() != 1 {
let page_number = counter(page).at(loc).first()-1
let total_pages = counter(page).final(loc).last()-1
align(center)[#page_number/#total_pages]
}
}
)
)
align(center, [
#grid(
columns: (30%,30%),
align(center, image(logo_esir, width: 100%)),
align(center, image(logo_univ, width: 100%)),
)])
block(height:25%,fill:none)
align(center, text(17pt)[
*#course_id: #title*])
align(center, text(10pt)[
A rendre le #due_time])
align(center, [_Responsable: #professor_name _])
block(height:35%,fill:none)
align(center)[*#author*]
pagebreak(weak: false)
body
}
#let title = "TP - Conception OO"
#let author = "<NAME>, <NAME>, Gr. TP1"
#let course_id = "OMD"
#let instructor = "<NAME>"
#let semester = "Semestre 6"
#let due_time = "lundi 14 octobre"
#set enum(numbering: "a)")
#show: assignment_class.with(title, author, course_id, instructor, due_time)
#set par(justify: true)
#import "@preview/codelst:2.0.0": sourcecode
#import "@preview/algo:0.3.3": algo, i, d, comment, code
#import "@preview/ctheorems:1.1.2": *
#show: thmrules.with(qed-symbol: $square$)
#let theorem = thmbox("theorem", "Théorème", fill: rgb("#EEEEEE"))
#show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
#outline(
title: [Sommaire],
indent: auto,
depth: 3,
)
#pagebreak()
= Introduction
Ce travail a pour objectif de concevoir un système de réservation pour un cinéma, en s'appuyant sur une approche orientée objet.
Pour ce faire, nous allons formaliser l'ensemble des fonctionnalités et des interactions décrites dans le cahier des charges. Elle couvre dans l'ordre :
- l'analyse fonctionnelle (diagramme de cas d'utilisation et description de chacun d'entre eux)
- l'analyse structurelle (diagrammes de séquence puis diagramme de classe)
- l'analyse comportementale (diagrammes d'état)
Toutes ces tâches permettront de modéliser l'ensemble des processus liés aux actions qui seront disponibles sur la plateforme et de s'assurer de créer une solution informatique complète.
#pagebreak()
= Analyse fonctionnelle
== Description générale
Suite à la lecture et à l'analyse du sujet, voici la description du système telle que nous l'avons interprété.
=== Système
Le système est le cinéma. Il est modélisé par deux interfaces : une borne physique située à l’entrée et une application web accessible en ligne.
=== But
Le but serait d'informatiser le système de réservation de place pour ce système (un nouveau cinéma) afin de permettre aux clients de réserver en ligne ou via une borne au cinéma, et aux employés et membres du personnel de gérer ce système de réservation de manière efficace.
=== Acteurs
Les acteurs seraient :
- L'Employé : il vérifie les informations concernant les réductions tarifaires et la disponibilité des places.
- Le Membre du personnel : il gère la répartition des films dans les salles et met à jour le système.
- Le Client sans compte : il peut consulter les films et créer un compte pour réserver.
- Le Client avec compte : il peut réserver des places, bénéficier d'avantages fidélité, et gérer ses informations personnelles.
== Diagramme de cas d'utilisation
Voici le diagramme de cas d'utilisation que nous en avons déduit :
#figure(
image("../uml/img/1-diagrammeCasUtilisation.png", width:12cm)
)
== Description des cas d'utilisation
Voici la description de chaque cas d'utilisation.
#set text(8.49pt)
#table(
columns: (0.4fr, 0.4fr, 1.1fr, 1.1fr, 1.1fr),
inset: 3pt,
// Headers
[*Cas \d'utilisation*], [*Acteurs*], [*Scénario nominal*], [*Scénario alternatif*], [*Scénario exception*],
[Modifier ses informations personnelles], [Client \ connecté], [
1. Consulte son compte
2. Clique sur un bouton "Modifier ses informations personnelles"
3. Une page apparaît avec tous les champs modifiables
4. Clique sur un bouton "Valider"
5. Une pop-up confirme la modification des informations personnelles
], [
1. Décide de ne modifier aucune information et quitte simplement la page.
2. Annule la modification en cliquant sur un bouton « Annuler ».
], [
1. L'adresse mail existe déjà : message d'erreur affiché.
2. Le client n'est pas majeur : message d'erreur affiché.
3. Problème de connexion au serveur : un message d'erreur s'affiche.
],
[Consulter son compte], [Client \ connecté], [
1. Appuie sur un bouton "Mon compte"
2. Consulte son compte
], [
1. N'a pas de réservations ou de points de fidélité, un message « Aucune information à afficher » est affiché.
], [
1. Problème de connexion au serveur : un message d'erreur s'affiche.
],
[Réserver un film #footnote[Réserver une séance (film, horaire) et un nombre de place voulu]], [Client \ connecté], [
1. Sélectionne un film et une séance
2. Choisit le nombre de places et les tarifs associés
3. Procède au paiement
4. Réservation validée si le paiement est accepté
5. Reçoit une confirmation par mail avec un billet électronique
], [
1. Accumule suffisamment de points (10) pour obtenir un billet gratuit, le système lui propose de l'utiliser avant de payer.
2. C'est l'anniversaire du client, il bénéficie donc d'une place gratuite.
3. Décide d'annuler la réservation ou de changer de film.
], [
1. Paiement refusé : Le client est informé de vérifier ses informations bancaires.
2. Plus de places disponibles : La séance est complète, réservation impossible.
3. Problème de connexion au serveur : un message d'erreur s'affiche.
],
[Créer un compte], [Client non connecté], [
1. Clique sur "Créer mon compte"
2. Remplit le formulaire de création de compte
3. Appuie sur "Valider"
4. Reçoit une confirmation par mail
], [
1. Décide de ne pas créer de compte et quitte la page.
2. Fournit des informations incomplètes : le système met en évidence les champs manquants.
], [
1. L'adresse mail existe déjà : Message d'erreur affiché.
2. Le client n'est pas majeur : Message d'erreur affiché.
3. Mot de passe invalide : Message d'erreur affiché
3. Problème de connexion au serveur : un message d'erreur s'affiche.
],
[Se \ connecter à un compte], [Client non connecté], [
1. Clique sur "Se connecter"
2. Remplit le formulaire de connexion
3. Appuie sur "Valider"
], [
1. N'a pas de compte : Il crée un compte.
2. Oublie son mot de passe : Il clique sur « Mot de passe oublié » pour le réinitialiser.
], [
1. Mauvais identifiant : Message d'erreur affiché.
2. Problème de connexion au serveur : Message d'erreur affiché.
],
[Consulter les informations de réservation], [Employé], [
1. Se connecte à son espace
2. Consulte les informations des salles et des réservations sous forme de tableau
], [
1. Peut trier et filtrer les réservations selon le titre du film, l'heure, la salle...
], [
1. Pas de réservations pour une période donnée : Message « Aucune réservation disponible ».
2. Problème de connexion au serveur : Message d'erreur affiché.
],
[Attribuer une salle à un film et une séance], [Membre du \ personnel], [
1. Se connecte à son espace
2. Consulte les séances
3. Sélectionne une séance sans salle attribuée
4. Fournit les salles disponibles
5. Choisit une salle
6. Confirme l'attribution de la salle via une pop-up
], [
1. Peut attribuer automatiquement une salle en fonction de la taille de la salle, la présence de 3D).
2. Aucune salle n'est disponible, le système décide d'annuler le processus d'attribution.
], [
1. Problème de connexion au serveur : un message d'erreur s'affiche.
]
)
#set text(11pt)
#pagebreak()
= Analyse structurelle
== Diagrammes de séquence
Nous avons réalisé trois diagrammes de séquence correspondant à différents cas d'utilisation décrits précédemment : _Créer un compte_, _Attribuer une salle à un film et un horaire_, et _Réserver un film_.
=== Cas d'utilisation "Créer un compte"
Le cas d'utilisation "Créer un compte" a été décrit ainsi dans la partie précédente :
- Acteur : Client non connecté.
- Scénario nominal :
- 1. Le client clique sur le bouton "Créer mon compte".
- 2. Il remplit le formulaire de création de compte avec ses informations.
- 3. Il valide le formulaire en cliquant sur "Valider".
- 4. Une confirmation de création de compte est envoyée par mail.
- Scénarios alternatifs :
- Le client décide d'abandonner la création du compte et quitte la page.
- Le client soumet des informations incomplètes : le système met en évidence les champs manquants.
- Scénarios d'exception :
- L'adresse mail est déjà utilisée : un message d'erreur est affiché.
- Le client est mineur : un message d'erreur est affiché.
- Le mot de passe est invalide : un message d'erreur est affiché.
- Problème de connexion au serveur : un message d'erreur est affiché (Pour des soucis de simplifications, nous ne modéliserons pas ce dernier scénario).
Un diagramme de séquence correspondant pourrait être illustré comme suit :
#figure(
image("../uml/img/2-diagrammeSéquence1.png", width: 3.22cm)
)
=== Cas d'utilisation "Attribuer une salle à un film et un horaire"
Le cas d'utilisation "Attribuer une salle à un film et un horaire" a été décrit ainsi dans la partie précédente :
- Acteur : Membre du personnel.
- Scénario nominal :
- 1. Le membre du personnel se connecte à son espace de travail sécurisé.
- 2. Il consulte la liste des séances sans salle attribuée.
- 3. Il sélectionne une séance à laquelle il faut attribuer une salle.
- 4. Le système affiche les salles disponibles.
- 5. Le membre du personnel choisit une salle adaptée à la séance.
- 6. L'attribution de la salle est confirmée par une pop-up de validation.
- Scénarios alternatifs :
- Le membre du personnel peut opter pour une attribution automatique en fonction de critères prédéfinis comme la taille de la salle ou la présence de la technologie 3D. (Pour des soucis de simplifications, nous ne modéliserons pas ce dernier scénario)
- Aucune salle n'est disponible, le système décide d'annuler le processus d'attribution.
- Scénarios d'exception :
- Problème de connexion au serveur : un message d'erreur est affiché (Pour des soucis de simplifications, nous ne modéliserons pas ce dernier scénario).
Un diagramme de séquence correspondant pourrait être illustré comme suit :
#figure(
image("../uml/img/2-diagrammeSéquence2.png", width: 10cm)
)
#pagebreak()
=== Cas d'utilisation "Réserver un film"
Le cas d'utilisation "Réserver un film" a été décrit ainsi dans la partie précédente :
- Acteur : Client connecté.
- Scénario nominal :
- 1. Le client connecté sélectionne un film et une séance
- 2. Il choisit le nombre de places et les tarifs associés
- 3. Il procède au paiement
- 4. La réservation est validée si le paiement est accepté
- 5. Reçoit une confirmation par mail avec un billet électronique
- Scénarios alternatifs :
1. Accumule suffisamment de points (10) pour obtenir un billet gratuit, le système lui propose de l'utiliser avant de payer.
2. C'est l'anniversaire du client, il bénéficie donc d'une place gratuite.
3. Décide d'annuler la réservation ou de changer de film (Pour des soucis de simplifications, nous ne modéliserons pas ce dernier scénario)
- Scénarios d'exception :
- 1. Paiement refusé : Le client est informé de vérifier ses informations bancaires.
- 2. Plus de places disponibles : La séance (comprend le film et l'horaire) est complète, réservation impossible.
- 3. Problème de connexion au serveur : un message d'erreur s'affiche. (Pour des soucis de simplifications, nous ne modéliserons pas ce dernier scénario)
Un diagramme de séquence correspondant pourrait être illustré comme suit :
#figure(
image("../uml/img/2-diagrammeSéquence3.png", width:6.5cm)
)
== Diagrammes de classe
A partir des diagrammes de séquence, nous pouvons désormais mieux imaginer un diagramme de classes possible pour ce problème.
#figure(
image("../uml/img/3-diagrammeClasses.png")
)
Voici comment nous justifions notre choix de diagramme de classes.
=== Classe abstraite Personne / Classes concrètes Acteur et Réalisateur
- Nous avons fait une classe abstraite Personne pour définir un modèle commun (nom et prénom) pour les classes `Acteur` et `Réalisateur`.
- Les classes concrètes Acteur et Réalisateur représentent les personnes impliquées dans la création du film.
- Nous avons décidé de séparer ces entités de film et aussi de séparer les acteurs et les réalisateurs, car ils ont des rôles différents dans un film et les cardinalités sont différentes (un film contient plusieurs acteurs mais un seul réalisateur). De plus, cela rend les entités Acteur et Réalisateur moins redondantes car un acteur peut jouer dans plusieurs films et un réalisateur peut également réaliser plusieurs films.
=== Classe Film
- Cette classe contient des informations sur le film, comme le titre, le réalisateur, les acteurs, la durée et le public visé.
- Nous sommes restés sur l'idée de base où chaque film a un seul réalisateur mais plusieurs acteurs, d'où la présence d'une liste pour les acteurs mais pas pour les réalisateurs.
=== Séance
- Cette classe contient des informations sur le moment de la séance (film et horaire) et le nombre de places réservées. Elle permet de gérer les horaires et la disponibilité des salles.
- Nous avons pensé à ces cardinalités entre Séance et Film car un film peut être projeté plusieurs fois dans différentes séances, mais chaque séance est liée à un seul film.
=== Classe ClientConnecté
- Cette classe représente les clients ayant un compte et étant connecté à celui-ci. Elle inclut donc les attributs spécifiés dans le compte (adresse mail, date de naissance, mot de passe, nombre de points). Nous avons des getters et des setters afin de pouvoir récupérer les informations (par exemple pour l'affichage) et des setters pour les modifier (modification des informations personnelles, changement du nombre de points). Il y a aussi des méthodes pour réserver une séance et se déconnecter.
- Nous avons pensé à ces cardinalités entre ClientConnecté et Séance car plusieurs clients connectés peuvent réserver une séance, et un client peut réserver plusieurs séances.
=== ClientNonConnecté
- Cette classe gère les actions que peut effectuer un client non connecté, comme la connexion et la création d'un compte. Le client peut se connecter soit via son identifiant et son mot de passe, soit via son email et son mot de passe. S'il n'a pas de compte, il peut s'en créer un via la méthode créerUnCompte, prenant en paramètres tout les champs nécessaires à la création d'un compte.
=== Classes Employé et MembreDuPersonnel
- La classe Employé reflète le rôle de l'employé : Il a l'autorisation consulter les détails sur une réservation via la méthode consulterReservation. En effet, c'est l'employé qui en a l'autorisation.
- La classe MembreDuPersonnel reflète le rôle du MembreDuPersonnel : Il a l'autorisation créer des séances via la méthode créerSéance. En effet, c'est le membre du personnel qui en a l'autorisation.
- Nous avons séparé ces deux classes pour distinguer les rôles opérationnels liés à la gestion des séances qui diffèrent selon les deux rôles.
=== Classe abstraite Salle / Classes concrètes Dolby, 3D et Standard
- La classe abstraite Salle permet de représenter les salles avec des caractéristiques communes (nom, prix de base de la place, nombre de places). Elle permet de généraliser les différentes types de salles (Dolby, 3D, Standard).
- Les classes concrètes Dolby, 3D et Standard représentent les différents types de salles existantes dans le cinéma.
- Nous avons décidé de séparer les types de salles (Dolby, 3D et Standard), car le type de salle peut influencer le prix de la place et le nombre de places. De plus, ce choix permet d'ajouter d'autres types de salles facilement si l'occasion se présente.
- Nous avons pensé à ces cardinalités entre Séance et Salle car une séance a lieu dans une seule salle, mais une salle peut accueillir plusieurs séances.
=== Classe Cinema
- Cette classe contient des informations générales sur le cinéma et les films projetés, ainsi que les employés et membres du personnel.
- Nous avons pensé à ces cardinalités pour Cinema car un cinéma emploie plusieurs personnes (employés et membres du personnel) et dispose de plusieurs salles. De même, plusieurs films peuvent être projetés dans le cinéma.
=== Classe Place / Classes PlaceMobiliteReduite, PlaceChomeur, PlaceEtudiant, PlaceSenior
- Cette classe représente une place réservée avec une éventuelle réduction.
- Nous avons fait le choix d'une classe concrète Place, où d'autres types de places (mobilité réduite, chômeur, étudiant, sénior, place cumulPoint qui offre une place gratuite si le client a cumulé au moins 10 point, place anniversaire si le jour de réservation est aussi le jour d'anniversaire du client) sont reliés, pour permettre de soit choisir une place "normale", soit choisir une place spéciale offrant une réduction particulière grâce à l'attribution par héritage. De plus, ce choix permet d'ajouter d'autres types de places facilement si l'occasion se présente.
=== Classe Réservation
- Cette classe contient les informations sur la réservation, comme le client et les places réservées.
- Nous avons pensé à ces cardinalités entre Réservation et Place car une réservation inclut une ou plusieurs places, et chaque place est associée à une réservation.
#pagebreak()
= Analyse comportementale
== Processus de réservation d'une séance
#figure(
image("../uml/img/4-diagrammeEtat1.png")
)
Le processus commence dans l'état initial enAttente, où l'utilisateur peut choisir d'éteindre le système en quittant le processus (état éteindre) ou de continuer avec la réservation.
Choix du Film : Si l'utilisateur souhaite réserver un film, la réservation passe à l'état FilmChoisi.
- Si le film est trouvé, l'utilisateur peut choisir un horaire, et l'état se déplace vers HoraireChoisi.
- Si le film n'est pas trouvé, l'utilisateur retourne à l'état enAttente.
Choix de l'Horaire : Dans l'état HoraireChoisi, l'utilisateur peut choisir un horaire.
- Si l'horaire est disponible, la réservation passe à l'état PlacesChoisies.
- Si l'horaire n'est pas disponible, l'utilisateur revient à l'état FilmChoisi.
Choix des Places : Dans PlacesChoisies, l'utilisateur sélectionne ses places.
- Si les places sont disponibles, le réservation passe à l'état vers TarifsChoisis.
- Si les places ne sont pas disponibles, il revient à l'état HoraireChoisi.
Choix des Tarifs : À partir de TarifsChoisis, le client peut visualiser ses tarifs spéciaux (étudiant, sénior, chômeur si applicable) ou ses avantages (jour de son anniversaire, place gratuite si 10 points cumulés ou plus...). Ensuite, il peut procéder à la transaction (état Transaction).
Transaction :
- Si le paiement est accepté, un mail est envoyé, et l'utilisateur retourne à l'état de départ (enAttente).
- Si le paiement est refusé, l'utilisateur reste dans l'état Transaction tant que le paiement n'est pas accepté.
== Processus d'authentification d'un utilisateur
#figure(
image("../uml/img/4-diagrammeEtat2.png", width: 9cm)
)
Le processus commence également dans l'état enAttente et l'utilisateur peut choisir de quitter le système.
Entrée de l'Identifiant : Lorsque l'utilisateur entre son identifiant, il y a deux possibilités.
- Si l'identifiant est correct, le système passe à identifiantCorrect.
- Si l'identifiant est incorrect, l'utilisateur reste dans l'état enAttente tant que l'identifiant est incorrect.
Entrée du Mot de Passe : À partir de l'état identifiantCorrect, l'utilisateur entre son mot de passe.
- Si le mot de passe est correct, l'utilisateur à l'état utilisateurConnecté.
- Si le mot de passe est incorrect, l'utilisateur retourne à identifiantCorrect.
Déconnexion : Une fois connecté, l'utilisateur peut choisir de se déconnecter (retour à l'état enAttente).
#pagebreak()
= Conclusion
En conclusion, grâce aux étapes précédentes, nous avons pu concevoir un système de réservation pour un cinéma en adoptant une approche orientée objet.
Les analyses fonctionnelles, structurelles et comportementales nous ont permis de modéliser les interactions entre les différents acteurs et le système.
D'abord, nous avons détaillé chaque cas d'utilisation afin de mieux comprendre les fonctionnalités du système et d'assurer leur cohérence.
Ensuite, les diagrammes de séquence, de classes et comportementaux ont été essentiels pour visualiser les processus et les relations entre les entités.
Toutes ces étapes ont été cruciales, non seulement pour répondre aux besoins des clients et des utilisateurs finaux (en garantissant une expérience utilisateur fluide avec toutes les fonctionnalités nécessaires), mais aussi pour optimiser le travail des employés et du personnel du cinéma, ainsi que celui des développeurs.
|
|
https://github.com/arthurcadore/eng-telecom-workbook | https://raw.githubusercontent.com/arthurcadore/eng-telecom-workbook/main/semester-7/COM_1/homework8/homework.typ | typst | MIT License | #import "@preview/klaro-ifsc-sj:0.1.0": report
#import "@preview/codelst:2.0.1": sourcecode
#show heading: set block(below: 1.5em)
#show par: set block(spacing: 1.5em)
#set text(font: "Arial", size: 12pt)
#set highlight(
fill: rgb("#c1c7c3"),
stroke: rgb("#6b6a6a"),
extent: 2pt,
radius: 0.2em,
)
#show: doc => report(
title: "Análise de Desempenho de Modulações Digitais",
subtitle: "Sistemas de Comunicação I",
authors: ("<NAME>",),
date: "29 de Julho de 2024",
doc,
)
= Introdução:
O objetivo deste relatório é analisar o desempenho das modulações digitais MPSK e MQAM em um sistema de comunicação digital. Para isso, foram simuladas diferentes modulações e analisados os resultados obtidos.
= Desenvolvimento e Resultados:
O desenvolvimento deste relatório foi dividido em três diferentes seções, onde foi analisado o desempenho individual de cada modulação e em seguida um comparativo entre as duas diferentes modulações.
== Desempenho de modulações MPSK
Para calcular o desempenho de modulações MPSK, foi implementado um script em MATLAB que realiza a modulação e demodulação dos sinais, calculando a taxa de erro de bit (BER) para diferentes valores de M.
O script gera dados aleatórios binários, modula os dados e adiciona ruído gaussiano branco, demodula os sinais e calcula a taxa de erro de bit para diferentes valores de SNR.
#sourcecode[```matlab
clear all; close all; clc
pkg load communications;
% Função para realizar a modulação PSK
function symbols = psk_modulate(data, M)
phase_step = 2 * pi / M;
phases = (0:M-1) * phase_step;
symbols = exp(1i * phases(data + 1));
end
% Função para realizar a demodulação PSK
function demodulated_data = psk_demodulate(symbols, M)
phase_step = 2 * pi / M;
phases = (0:M-1) * phase_step;
[~, demodulated_data] = min(abs(symbols(:) - exp(1i * phases)), [], 2);
demodulated_data = demodulated_data - 1;
end
% Define a quantidade de dados a serem gerados
data_length = 1000;
data = randi([0 1], data_length, 1); % Gera dados aleatórios binários
for M = [4, 8, 16, 32]
% Modulação PSK
psk_symbols = psk_modulate(data, M);
psk_ber = [];
for snr = 1:34
snr_linear = 10^(snr / 10);
noise_variance = 1 / (2 * snr_linear);
noise = sqrt(noise_variance) * (randn(size(psk_symbols)) + 1i * randn(size(psk_symbols)));
psk_noisy = psk_symbols + noise;
% Demodulação PSK
psk_demodulated = psk_demodulate(psk_noisy, M);
% Calcula o BER
errors = sum(psk_demodulated ~= data);
psk_ber = [psk_ber, errors / data_length];
end
% Plotando o gráfico para cada valor de M
figure;
semilogy(1:34, psk_ber, 'DisplayName', sprintf('%d-PSK', M));
xlabel('SNR [dB]');
ylabel('BER');
title(sprintf('%d-PSK BER vs SNR', M));
legend('show');
grid on;
set(gca, 'FontSize', 14);
end
```]
A seguir, são apresentados os gráficos de BER para diferentes valores de M.
=== 4-MPSK
O primeiro gráfico apresenta a taxa de erro de bit (BER) para a modulação 4-PSK. Note que a BER diminui à medida que o SNR aumenta, o que é esperado, isso pois o sinal se torna mais robusto em relação ao ruído, ou seja, fica mais distinguivel ao receptor.
#figure(
figure(
rect(image("./pictures/4psk.png")),
numbering: none,
caption: [Taxa de erro de bit (BER) para modulação 4-PSK]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
=== 8-MPSK
Já no gráfico da modulação 8-PSK, é possível observar que a BER é maior em relação à modulação 4-PSK, isso ocorre pois a modulação 8-PSK possui mais fases, o que torna o sinal mais suscetível a erros devido ao ruído, dessa forma, a curva se aproxima mais da direita da imagem, pois o sinal precisa de um SNR maior para ser distinguido do ruído.
#figure(
figure(
rect(image("./pictures/8psk.png")),
numbering: none,
caption: [Taxa de erro de bit (BER) para modulação 8-PSK]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
=== 16-MPSK
Da mesma maneira, o gráfico da modulação 16-PSK apresenta uma BER ainda maior, isso ocorre pois a modulação 16-PSK possui mais fases, o que torna o sinal mais suscetível a erros devido ao ruído, dessa forma, a curva se aproxima mais da direita da imagem, pois o sinal precisa de um SNR maior para ser distinguido do ruído.
#figure(
figure(
rect(image("./pictures/16psk.png")),
numbering: none,
caption: [Taxa de erro de bit (BER) para modulação 16-PSK]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
=== 32-MPSK
Novamente, o gráfico da modulação 32-PSK apresenta uma BER ainda maior, isso ocorre pois a modulação 32-PSK possui mais fases, o que torna o sinal mais suscetível a erros devido ao ruído, dessa forma, a curva se aproxima mais da direita da imagem, pois o sinal precisa de um SNR maior para ser distinguido do ruído.
#figure(
figure(
rect(image("./pictures/32psk.png")),
numbering: none,
caption: [Taxa de erro de bit (BER) para modulação 32-PSK]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
=== Desempenho comparativo:
Abaixo podemos observar um gráfico comparativo entre as modulações MPSK, onde é possível observar que a BER aumenta à medida que o número de fases aumenta, isso ocorre pois o sinal se torna mais suscetível a erros devido ao ruído, dessa forma, a curva se aproxima mais da direita da imagem, pois o sinal precisa de um SNR maior para ser distinguido do ruído.
Note que a modulação 4-PSK possui a menor BER, enquanto a modulação 32-PSK possui a maior BER, isso ocorre pois um sinal modulado com mais fases é mais suscetível a erros devido ao ruído.
#figure(
figure(
rect(image("./pictures/mpsk.png")),
numbering: none,
caption: [Taxa de erro de bit (BER) comparativa]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Abaixo está o script correspondente para gerar a imagem apresentada acima:
#sourcecode[```matlab
Clear all; close all; clc;
pkg load communications;
% Função para realizar a modulação PSK
function symbols = psk_modulate(data, M)
phase_step = 2 * pi / M;
phases = (0:M-1) * phase_step;
symbols = exp(1i * phases(data + 1));
end
% Função para realizar a demodulação PSK
function demodulated_data = psk_demodulate(symbols, M)
phase_step = 2 * pi / M;
phases = (0:M-1) * phase_step;
[~, demodulated_data] = min(abs(symbols(:) - exp(1i * phases)), [], 2);
demodulated_data = demodulated_data - 1;
end
figure;
hold on;
grid on;
set(gca, 'FontSize', 14);
for M = [4, 8, 16, 32]
% Define a quantidade de dados a serem gerados
data_length = 1000;
data = randi([0 M-1], data_length, 1); % Gera dados aleatórios
% Modulação PSK
psk_symbols = psk_modulate(data, M);
psk_ber = [];
for snr = 1:34
snr_linear = 10^(snr / 10);
noise_variance = 1 / (2 * snr_linear);
noise = sqrt(noise_variance) * (randn(size(psk_symbols)) + 1i * randn(size(psk_symbols)));
psk_noisy = psk_symbols + noise;
% Demodulação PSK
psk_demodulated = psk_demodulate(psk_noisy, M);
% Calcula o BER
errors = sum(psk_demodulated ~= data);
psk_ber = [psk_ber, errors / data_length];
end
semilogy(1:34, psk_ber, 'DisplayName', sprintf('%d-PSK', M));
end
xlabel('SNR [dB]');
ylabel('BER');
legend('show');
hold off;
```]
== Desempenho de modulações MQAM
Para calcular o desempenho de modulações MQAM, foi implementado um script em MATLAB que realiza a modulação e demodulação dos sinais, calculando a taxa de erro de bit (BER) para diferentes valores de M.
O script gera dados aleatórios, modula os dados e adiciona ruído gaussiano branco, demodula os sinais e calcula a taxa de erro de bit para diferentes valores de SNR.
#sourcecode[```matlab
pkg load communications; % Carrega o pacote de comunicações
% Função para realizar a modulação QAM
function symbols = qam_modulate(data, M)
% Define o número de bits por símbolo
k = log2(M);
% Define o tamanho da grade QAM
n = sqrt(M);
% Normaliza os dados
data = mod(data, M);
% Converte dados para uma matriz de símbolos
symbols = zeros(size(data));
for i = 1:numel(data)
% Mapeia os dados para uma posição na matriz QAM
x = mod(data(i), n) - (n-1)/2;
y = floor(data(i) / n) - (n-1)/2;
symbols(i) = x + 1i * y;
end
end
% Função para realizar a demodulação QAM
function demodulated_data = qam_demodulate(symbols, M)
% Define o número de bits por símbolo
k = log2(M);
% Define o tamanho da grade QAM
n = sqrt(M);
% Inicializa o vetor de dados demodulados
demodulated_data = zeros(size(symbols));
% Demodula cada símbolo
for i = 1:numel(symbols)
% Extrai a parte real e imaginária do símbolo
x = real(symbols(i));
y = imag(symbols(i));
% Mapeia para a posição da matriz QAM
x_idx = round(x + (n-1)/2);
y_idx = round(y + (n-1)/2);
% Converte para o índice de dados
demodulated_data(i) = x_idx + n * y_idx;
end
end
% Define a quantidade de dados a serem gerados
data_length = 1000;
data = randi([0 63], data_length, 1); % Gera dados aleatórios
% Loop para diferentes tamanhos de QAM
for M = [4, 16, 64]
% Modulação QAM
qam_symbols = qam_modulate(data, M);
qam_ber = [];
for snr = 1:14
snr_linear = 10^(snr / 10);
noise_variance = 1 / (2 * snr_linear);
noise = sqrt(noise_variance) * (randn(size(qam_symbols)) + 1i * randn(size(qam_symbols)));
qam_noisy = qam_symbols + noise;
% Demodulação QAM
qam_demodulated = qam_demodulate(qam_noisy, M);
% Calcula o BER
errors = sum(qam_demodulated ~= data);
qam_ber = [qam_ber, errors / data_length];
end
% Plotando o gráfico para cada valor de M
figure;
semilogy(1:14, qam_ber, 'DisplayName', sprintf('%d-QAM', M));
xlabel('SNR [dB]');
ylabel('BER');
title(sprintf('%d-QAM BER vs SNR', M));
legend('show');
grid on;
set(gca, 'FontSize', 14);
end
```]
A seguir, são apresentados os gráficos de BER para diferentes valores de M.
=== 4-MQAM
O primeiro gráfico apresenta a taxa de erro de bit (BER) para a modulação 4-QAM. Note que a BER diminui à medida que o SNR aumenta, o que é esperado, isso pois o sinal se torna mais robusto em relação ao ruído, ou seja, fica mais distinguivel ao receptor.
Porem, note que esse caimento é bastante acentuado, isso ocorre pois a modulação 4-QAM possui menos fases, o que torna o sinal mais robusto em relação ao ruído, dessa forma, a curva se aproxima mais da esquerda da imagem, pois o sinal precisa de um SNR menor para ser distinguido do ruído.
#figure(
figure(
rect(image("./pictures/4qam.png")),
numbering: none,
caption: [Taxa de erro de bit (BER) para modulação 4-QAM]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
=== 16-MQAM
Já no gráfico da modulação 16-QAM, é possível observar que a BER é maior em relação à modulação 4-QAM, isso ocorre pois a modulação 16-QAM possui mais fases, o que torna o sinal mais suscetível a erros devido ao ruído, dessa forma, a curva se aproxima mais da direita da imagem, pois o sinal precisa de um SNR maior para ser distinguido do ruído.
#figure(
figure(
rect(image("./pictures/16qam.png")),
numbering: none,
caption: [Taxa de erro de bit (BER) para modulação 16-QAM]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
=== 64-MQAM
Por fim, o gráfico da modulação 64-QAM apresenta uma BER ainda maior, isso ocorre pois a modulação 64-QAM possui mais fases, o que torna o sinal mais suscetível a erros devido ao ruído, dessa forma, a curva se aproxima mais da direita da imagem, pois o sinal precisa de um SNR maior para ser distinguido do ruído.
#figure(
figure(
rect(image("./pictures/64qam.png")),
numbering: none,
caption: [Taxa de erro de bit (BER) para modulação 64-QAM]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
=== Desempenho comparativo:
Abaixo podemos ver um comparativo entre as modulações MQAM, onde é possível observar que a BER aumenta à medida que o número de fases aumenta, isso ocorre pois o sinal se torna mais suscetível a erros devido ao ruído, dessa forma, a curva se aproxima mais da direita da imagem, pois o sinal precisa de um SNR maior para ser distinguido do ruído.
Note que a modulação 4-QAM possui a menor BER, enquanto a modulação 64-QAM possui a maior BER, isso ocorre pois um sinal modulado com mais fases é mais suscetível a erros devido ao ruído.
#figure(
figure(
rect(image("./pictures/mqam.png")),
numbering: none,
caption: [Taxa de erro de bit (BER) comparativa]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Abaixo está o script correspondente para gerar a imagem apresentada acima:
#sourcecode[```matlab
clear all; close all; clc;
pkg load communications;
% Função para realizar a modulação QAM
function symbols = qam_modulate(data, M)
% Define o número de bits por símbolo
k = log2(M);
% Define o tamanho da grade QAM
n = sqrt(M);
% Normaliza os dados
data = mod(data, M);
% Converte dados para uma matriz de símbolos
symbols = zeros(size(data));
for i = 1:numel(data)
% Mapeia os dados para uma posição na matriz QAM
x = mod(data(i), n) - (n-1)/2;
y = floor(data(i) / n) - (n-1)/2;
symbols(i) = x + 1i * y;
end
end
% Função para realizar a demodulação QAM
function demodulated_data = qam_demodulate(symbols, M)
% Define o número de bits por símbolo
k = log2(M);
% Define o tamanho da grade QAM
n = sqrt(M);
% Inicializa o vetor de dados demodulados
demodulated_data = zeros(size(symbols));
% Demodula cada símbolo
for i = 1:numel(symbols)
% Extrai a parte real e imaginária do símbolo
x = real(symbols(i));
y = imag(symbols(i));
% Mapeia para a posição da matriz QAM
x_idx = round(x + (n-1)/2);
y_idx = round(y + (n-1)/2);
% Converte para o índice de dados
demodulated_data(i) = x_idx + n * y_idx;
end
end
figure;
hold on;
grid on;
set(gca, 'FontSize', 14);
for M = [4, 16, 64]
% Define a quantidade de dados a serem gerados
data_length = 1000; % Número reduzido de amostras
data = randi([0 M-1], data_length, 1); % Gera dados aleatórios
% Modulação QAM
qam_symbols = qam_modulate(data, M);
qam_ber = [];
for snr = 1:14
snr_linear = 10^(snr / 10);
noise_variance = 1 / (2 * snr_linear);
noise = sqrt(noise_variance) * (randn(size(qam_symbols)) + 1i * randn(size(qam_symbols)));
qam_noisy = qam_symbols + noise;
% Demodulação QAM
qam_demodulated = qam_demodulate(qam_noisy, M);
% Calcula o BER
errors = sum(qam_demodulated ~= data);
qam_ber = [qam_ber, errors / data_length];
end
semilogy(1:14, qam_ber, 'DisplayName', sprintf('%d-QAM', M));
end
xlabel('SNR [dB]');
ylabel('BER');
legend('show');
hold off;
```]
= Conclusão:
Apartir dos conceitos apresentados, testes realizados e resultados obtidos, podemos concluir que a modulação MPSK é mais robusta em relação ao ruído em comparação com a modulação MQAM, isso ocorre pois a modulação MPSK possui menos fases, o que torna o sinal mais robusto em relação ao ruído, dessa forma, a curva se aproxima mais da esquerda da imagem, pois o sinal precisa de um SNR menor para ser distinguido do ruído.
Por outro lado, a modulação MQAM possui mais fases, o que torna o sinal mais suscetível a erros devido ao ruído, dessa forma, a curva se aproxima mais da direita da imagem, pois o sinal precisa de um SNR maior para ser distinguido do ruído.
Dessa forma, a escolha entre MPSK e MQAM depende do ambiente de comunicação, se o ambiente possui muito ruído, a modulação MPSK é mais indicada, por outro lado, se o ambiente possui menos ruído, a modulação MQAM é mais indicada.
= Referências Bibliográficas:
Para o desenvolvimento deste relatório, foi utilizado o seguinte material de referência:
- #link("https://www.researchgate.net/publication/287760034_Software_Defined_Radio_using_MATLAB_Simulink_and_the_RTL-SDR")[Software Defined Radio Using MATLAB & Simulink and the RTL-SDR, de <NAME>]
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Research/Winter%202024/Cartan-Hadamard%20Conjecture/Ideas.typ | typst | #import "/Templates/generic.typ": latex
#import "/Templates/notes.typ": chapter_heading
#import "@preview/ctheorems:1.1.0": *
#import "/Templates/math.typ": *
#import "/Templates/monograph.typ": frontpage
#show: latex
#show: chapter_heading
#show: thmrules
#show: symbol_replacing
#show: equation_references
= Simplifications
What we want to show is the following
#conjecture("Cartan-Hadamard")[
Let $N$ be a hypersurface in a Cartan-Hadamard manifold $M$.
We have
$
Area_M (N) >= Area_(RR^n)(B)
$
where $B$ is the ball in $RR^n$ with
$
Volume_M (N) = Volume_(RR^n) (B)
$
]<conj-cartan_hadamard>
We can make a series of simplifications due to @ghomiTotalCurvatureIsoperimetric2021.
#lemma[
If it is known that
$
cal(G)(N) := integral_N sigma_n dif S >= Area_(RR^n) (S^(n-1)) = n omega_n
$
for all hypersurfaces surfaces $N$ encompassing an Isoperimetric region, then @conj-cartan_hadamard is true.
]<lem-topological_sigma_n>
#proof[
@ghomiTotalCurvatureIsoperimetric2021[Page 36].
]
#lemma[
If it is known that @lem-topological_sigma_n holds for $diff conv (Omega)$ where $conv (Omega)$ is the convex hull of the Isoperimetric region $Omega$, then @lem-topological_sigma_n holds always.
]<lem-topological_sigma_n_convex>
#proof[
@ghomiTotalCurvatureIsoperimetric2021[Page 36].
]
We now introduce new simplifications.
#lemma[
In a Cartan-Hadamard manifold, the normal flow with velocity $f = 1$ decreases the value of $integral_N sigma_n dif S$.
]
#lemma[
For surfaces $N seq B_r (p)$ for some point $p in M$ we have
$
cal(G)(N) >= n omega_n + O(r^2)
$
]<lem-blowup_behaviour>
#pagebreak(weak: true)
#bibliography("refrences.bib")
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/lovelace/0.2.0/examples/rawtext.typ | typst | Apache License 2.0 | #import "../lib.typ": *
#set page(width: 20em, height: auto, margin: 1em)
#show: setup-lovelace
#let redbold = text.with(fill: red, weight: "bold")
#pseudocode-raw(
scope: (redbold: redbold),
```typ
#no-number
*input:* integers $a$ and $b$
#no-number
*output:* greatest common divisor of $a$ and $b$
<line:loop-start>
*if* $a == b$ *goto* @line:loop-end
*if* $a > b$ *then*
#redbold[$a <- a - b$] #comment[and a comment]
*else*
#redbold[$b <- b - a$] #comment[and another comment]
*end*
*goto* @line:loop-start
<line:loop-end>
*return* $a$
```
)
|
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/edge-snap-to/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 1em)
#import "/src/exports.typ" as fletcher: diagram, node, edge
#let label = table(
columns: (12mm, 4mm, 4mm, 4mm),
`Node`, none, `4`, none,
stroke: (x, y) => if 0 < x and x < 3 { (x: 1pt) },
)
Allow `snap-to` to be `none`.
#diagram(
node-stroke: 1pt,
edge-stroke: 1pt,
mark-scale: 50%,
node((0,0), label, inset: 0pt, corner-radius: 3pt),
edge((0.09,0), (0,1), "*-straight", snap-to: (none, auto)),
edge((0.41,0), (1,1), "*-straight", snap-to: none),
node((0,1), `Subnode`),
)
#pagebreak()
#diagram(
node(enclose: ((0,0), (0,3)), fill: yellow, snap: false),
for i in range(4) {
node((0,i), [#i], fill: white)
edge((0,i), (1,i), "<->")
},
node([B], enclose: ((1,0), (1,3)), fill: yellow),
for i in range(3) {
edge((0,i), (0,i + 1), "o..o")
},
)
#pagebreak()
#diagram(
node-stroke: 0.6pt,
node-fill: white,
node((0,1), [X]),
edge("->-", bend: 40deg),
node((1,0), [Y], name: <y>),
node($Sigma$, enclose: ((0,1), <y>),
stroke: teal, fill: teal.lighten(90%),
snap: -1, // prioritise other nodes when auto-snapping
name: <group>),
edge(<group>, <z>, "->"),
node((2.5,0.5), [Z], name: <z>),
) |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-22.typ | typst | Other | // Error: 4-5 unknown variable: x
#((x) = "")
|
https://github.com/Mc-Zen/tidy | https://raw.githubusercontent.com/Mc-Zen/tidy/main/src/tidy-parse.typ | typst | MIT License |
// Matches Typst docstring for a function declaration. Example:
//
// // This function does something
// //
// // param1 (str): This is param1
// // param2 (content, length): This is param2.
// // Yes, it really is.
// #let something(param1, param2) = {
//
// }
//
// The entire block may be indented by any amount, the declaration can either start with `#let` or `let`. The docstring must start with `///` on every line and the function declaration needs to start exactly at the next line.
// #let docstring-matcher = regex(`((?:[^\S\r\n]*/{3} ?.*\n)+)[^\S\r\n]*#?let (\w[\w\d\-_]+)`.text)
// #let docstring-matcher = regex(`([^\S\r\n]*///.*(?:\n[^\S\r\n]*///.*)*)\n[^\S\r\n]*#?let (\w[\w\d\-_]*)`.text)
#let docstring-matcher = regex(`(?m)^((?:[^\S\r\n]*///.*\n)+)[^\S\r\n]*#?let (\w[\w\d\-_]*)`.text)
// The regex explained:
//
// First capture group: ([^\S\r\n]*///.*(?:\n[^\S\r\n]*///.*)*)
// is for the docstring. It may start with any whitespace [^\S\r\n]*
// and needs to have /// followed by anything. This is the first line of
// the docstring and we treat it separately only in order to be able to
// match the very first line in the file (which is otherwise tricky here).
// We then match basically the same thing n times: \n[^\S\r\n]*///.*)*
//
// We then want a linebreak (should also have \r here?), arbitrary whitespace
// and the word let or #let: \n[^\S\r\n]*#?let
//
// Second capture group: (\w[\w\d\-_]*)
// Matches the function name (any Typst identifier)
// Matches an argument documentation of the form `/// - myparameter (str)`.
#let argument-documentation-matcher = regex(`[^\S\r\n]*/{3} - ([.\w\d\-_]+) \(([\w\d\-_ ,]+)\): ?(.*)`.text)
#let split-once(string, delimiter) ={
let pos = string.position(delimiter)
if pos == none { return string }
(string.slice(0, pos), string.slice(pos + 1))
}
/// #set raw(lang: "typc")
/// Parse a Typst argument list either at
/// - call site, e.g., `f("Timbuktu", value: 23)` or at
/// - declaration, e.g. `let f(place, value: 0)`.
///
/// This function returns a dictionary `(pos, named, count-processed-chars)` where
/// `count-processed-chars` is the number of processed characters, i.e., the
/// length of the argument list and `pos` and `named` contain the arguments.
///
///
/// This function returns `none`, if the argument list is not properly closed.
/// Note, that valid Typst code is expected.
///
/// *Example: * Calling this function with the following string
///
/// ```
/// "#let func(p1, p2: 3pt, p3: (), p4: (entries: ())) = {...}"
/// ```
///
/// and index `9` (which points to the opening parenthesis) yields the result
/// ```
/// (
/// pos: ("p1", "p5"),
/// named: (
/// p2: "3pt",
/// p3: "()",
/// p4: "(entries: ())"
/// )
/// 44,
/// )
/// ```
///
/// This function can deal with
/// - any number of opening and closing parenthesis
/// - string literals
/// We don't deal with:
/// - commented out code (`//` or `/**/`)
/// - raw strings with #raw("``") syntax that contain `"` or `(` or `)`
///
/// - text (str): String to parse.
/// - index (int): Position of the opening parenthesis of the argument list.
/// -> dictionary
#let parse-argument-list(text, index) = {
if text.len() <= index or text.at(index) != "(" { return none }
if text.len() <= index or text.at(index) != "(" { return ((:), 0) }
index += 1
let brace-level = 1
let literal-mode = none // Whether in ".."
let positional = ()
let named = (:)
let sink
let arg = ""
let is-named = false // Whether current argument is a named arg
let previous-char = none
let count-processed-chars = 1
let maybe-split-argument(arg, is-named) = {
if is-named {
return split-once(arg, ":").map(str.trim)
} else {
return (arg.trim(),)
}
}
for c in text.slice(index) {
let ignore-char = false
if c == "\"" and previous-char != "\\" {
if literal-mode == none { literal-mode = "\"" }
else if literal-mode == "\"" { literal-mode = none }
}
if literal-mode == none {
if c == "(" { brace-level += 1 }
else if c == ")" { brace-level -= 1 }
else if c == "," and brace-level == 1 {
if is-named {
let (name, value) = split-once(arg, ":").map(str.trim)
named.insert(name, value)
} else {
arg = arg.trim()
if arg.starts-with("..") { sink = arg }
else { positional.push(arg) }
}
arg = ""
ignore-char = true
is-named = false
} else if c == ":" and brace-level == 1 {
is-named = true
}
}
count-processed-chars += 1
if brace-level == 0 {
if arg.trim().len() > 0 {
if is-named {
let (name, value) = split-once(arg, ":").map(str.trim)
named.insert(name, value)
} else {
arg = arg.trim()
if arg.starts-with("..") { sink = arg }
else { positional.push(arg) }
}
}
break
}
if not ignore-char { arg += c }
previous-char = c
}
if brace-level > 0 { return none }
return (
pos: positional,
named: named,
sink: sink,
count: count-processed-chars
)
}
/// This is similar to @@parse-argument-list but focuses on parameter lists
/// at the declaration site.
///
/// If the argument list is well-formed, a dictionary is returned with
/// an entry for each parsed
/// argument name. The values are dictionaries that may be empty or
/// have an entry for the key `default` containing a string with the parsed
/// default value for this argument.
///
///
///
/// *Example* \
/// Let us take the string
/// ```typc
/// "#let func(p1, p2: 3pt, p3: (), p4: (entries: ())) = {...}"
/// ```
/// Here, we would call `parse-parameter-list(source-code, 9)` and retrieve
/// #pad(x: 1em, ```typc
/// (
/// p0: (:),
/// p1: (default: "3pt"),
/// p2: (default: "()"),
/// p4: (default: "(entries: ())"),
/// )
/// ```)
///
/// - text (str): String to parse.
/// - index (int): Index where the argument list starts. This index should
/// point to the character *next* to the function name, i.e., to the
/// opening brace `(` of the argument list if there is one (note, that
/// function aliases for example produced by `myfunc.where(arg1: 3)` do
/// not have an argument list).
/// -> none, dictionary
#let parse-parameter-list(text, index) = {
let result = parse-argument-list(text, index)
if result == none { return none }
let (pos, named, count) = result
let args = (:)
for arg in arg-strings {
if arg.len() == 1 {
args.insert(arg.at(0), (:))
} else {
args.insert(arg.at(0), (default: arg.at(1)))
}
}
return (args: args, count: count)
}
// Take the result of `parse-argument-list()` and retrieve a list of positional
// and named arguments, respectively. The values are `eval()`ed.
// #let parse-arg-strings(args) = {
// let positional-args = ()
// let named-args = (:)
// for arg in args {
// if arg.len() == 1 {
// positional-args.push(eval(arg.at(0)))
// } else {
// named-args.insert(arg.at(0), eval(arg.at(1)))
// }
// }
// return (pos: positional-args, named: named-args)
// }
/// Count the occurences of a single character in a string
///
/// - string (str): String to investigate.
/// - char (str): Character to count. The string needs to be of length 1.
/// - start (int): Start index.
/// - end (end): Start index. If `-1`, the entire string is searched.
/// -> int
#let count-occurences(string, char, start: 0, end: -1) = {
let count = 0
if end == -1 { end = string.len() }
for c in string.slice(start, end) {
if c == char { count += 1 }
}
// let i = 0
// while i < end {
// if string.at(i) == char { count += 1}
// i += 1
// }
count
}
#let parse-description-and-documented-args(docstring, parse-info, first-line-number: 0) = {
let fn-desc = ""
let started-args = false
let documented-args = ()
let return-types = none
for (line-number, line) in docstring.split("\n").enumerate(start: first-line-number) {
// Check if line is a test line -> replace it with a call to #test()
if line.starts-with("/// >>> ") {
line = "/// #test(`" + line.slice(8) + "`, source-location: (module: \""
line += parse-info.label-prefix + "\", line: " + str(line-number) + "))"
}
let arg-match = line.match(argument-documentation-matcher)
if arg-match == none {
let trimmed-line = line.trim().trim("/")
if trimmed-line.trim().starts-with("->") {
return-types = trimmed-line.trim().slice(2).split(",").map(x => x.trim())
} else {
if not started-args { fn-desc += trimmed-line + "\n"}
else {
documented-args.last().desc += "\n" + trimmed-line
}
}
} else {
started-args = true
let param-name = arg-match.captures.at(0)
let param-types = arg-match.captures.at(1).split(",").map(x => x.trim())
let param-desc = arg-match.captures.at(2)
documented-args.push((name: param-name, types: param-types, desc: param-desc))
}
}
return (
description: fn-desc,
args: documented-args,
return-types: return-types
)
}
#let parse-variable-docstring(source-code, match, parse-info) = {
let docstring = match.captures.at(0)
let name = match.captures.at(1)
let first-line-number = count-occurences(source-code, "\n", end: match.start) + 1
let (description, return-types) = parse-description-and-documented-args(docstring, parse-info, first-line-number: first-line-number)
let var-specs = (
name: name,
description: description,
)
if return-types != none and return-types.len() > 0 {
var-specs.type = return-types.first()
}
return var-specs
}
#let curry-matcher = regex(" *= *([.\w\d\-_]+)\.with\(")
#let parse-curried-function(source-code, index) = {
// let docstring = match.captures.at(0)
// let var-name = match.captures.at(1)
let line-end = source-code.slice(index).position("\n")
let k = (line-end, source-code.slice(index))
if line-end == none { line-end = source-code.len() }
else {line-end += index }
let rest = source-code.slice(index, line-end)
let match = rest.match(curry-matcher)
if match == none { return none }
let (pos, named, count) = parse-argument-list(source-code, match.end + index - 1)
return (
name: match.captures.first(),
pos: pos,
named: named
)
}
/// Parse a function docstring that has been located in the source code with
/// given match.
///
/// The return value is a dictionary with the keys
/// - `name` (str): the function name.
/// - `description` (content): the function description.
/// - `args`: A dictionary containing the argument list.
/// - `return-types` (array(str)): A list of possible return types.
///
/// The entries of the argument list dictionary are
/// - `default` (str): the default value for the argument.
/// - `description` (content): the argument description.
/// - `types` (array(str)): A list of possible argument types.
/// Every entry is optional and the dictionary also contains any non-documented
/// arguments.
///
///
///
/// - source-code (str): The source code containing some documented Typst code.
/// - match (match): A regex match that matches a documentation string. The first
/// capture group should hold the entire, raw docstring and the second capture
/// the function name (excluding the opening parenthesis of the argument list
/// if present).
/// - parse-info (dictionary):
/// -> dictionary
#let parse-function-docstring(source-code, match, parse-info) = {
let docstring = match.captures.at(0)
let fn-name = match.captures.at(1)
let first-line-number = count-occurences(source-code, "\n", end: match.start) + 1
let (description, args: documented-args, return-types) = parse-description-and-documented-args(docstring, parse-info, first-line-number: first-line-number)
// let (args, count) = parse-parameter-list(source-code, match.end)
let (pos, named, sink, count) = parse-argument-list(source-code, match.end)
let args = (:)
for arg in pos { args.insert(arg, (:)) }
for (arg, value) in named { args.insert(arg, (default: value)) }
if sink != none { args.insert(sink, (:)) }
for arg in documented-args {
if arg.name in args {
args.at(arg.name).description = arg.desc.trim("\n")
args.at(arg.name).types = arg.types
} else {
assert(
false,
message: "The parameter `" + arg.name + "` does not appear in the argument list of the function `" + fn-name + "`"
)
}
}
if parse-info.require-all-parameters {
for arg in args {
assert(
documented-args.find(x => x.name == arg.at(0)) != none,
message: "The parameter `" + arg.at(0) + "` of the function `" + fn-name + "` is not documented. "
)
}
}
return (
name: fn-name,
description: description,
args: args,
return-types: return-types
)
}
#let module-docstring-matcher = regex(`(?m)^((?:[^\S\r\n]*///.*\n)+)\n`.text)
#let parse-module-docstring(source-code, parse-info) = {
let match = source-code.match(module-docstring-matcher)
if match == none { return none }
let desc = parse-description-and-documented-args(match.captures.first(), parse-info, first-line-number: 0)
return desc.description.trim()
} |
https://github.com/swaits/typst-collection | https://raw.githubusercontent.com/swaits/typst-collection/main/README.md | markdown | MIT License | # `typst-collection`
A collection of `typst` templates and packages by [swaits](https://swaits.com/about).
## Usage
These are available for use at the [`typst` universe](https://typst.app/universe/).
## License
All content licensed under the MIT license.
|
https://github.com/maxgraw/bachelor | https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/2-theory/webxr.typ | typst | Die WebXR Device API stellt eine Sammlung von Standards dar, die das Erstellen und die Interaktion mit 3D-Szenen in virtuellen und erweiterten Realitäten ermöglichen. Diese API unterstützt eine Vielzahl von Geräten, darunter mobile Endgeräte, 3D-Headsets und Datenbrillen @webxr-spec. WebXR ersetzt die ältere WebVR API, die ausschließlich für VR-Inhalte konzipiert war. Im Gegensatz dazu ermöglicht WebXR sowohl AR- als auch VR-Inhalte und ist somit die zukünftige Standard-API für immersive Inhalte im Web. Zum Zeitpunkt dieser Arbeit befindet sich die API im W3C Candidate Recommendation Draft, wird jedoch bereits von 74,37 % der Nutzer weltweit unterstützt @can-i-use-webxr, @webxr-spec. Diese hohe Zahl ist hauptsächlich auf die Dominanz von Android-Geräten und den weit verbreiteten Einsatz von Chrome, der einen Marktanteil von 65 % hat, zurückzuführen @browser-market-share.
Bei der Überprüfung der Kompatibilität in verschiedenen Browsern zeigt sich, dass WebKit, die Browser-Engine für Safari und Safari auf iOS-Geräten, die API derzeit nicht unterstützt @can-i-use-webxr. Folglich kann die API gegenwärtig nicht auf Apple-Geräten genutzt werden.
WebXR dient hierbei nicht als direkte Render-API, sondern bietet eine Schnittstelle zur Interaktion mit den Geräten. Für das Rendering kann WebGL verwendet werden, welches im @webgl-chapter näher erläutert wird. Im Folgenden wird eine relevante Auswahl an APIs und Methoden der WebXR Device API vorgestellt, die für die Konzeption und Implementierung der Anwendung von Bedeutung sind.
=== Modell
Das Modell beschreibt ein WebXR-kompatibles Gerät, welches Informationen über diese Schnittstelle abrufen und darstellen kann. Ein XR-Device ist hierbei eine physische Einheit, die immersive Inhalte wiedergibt. Inhalte gelten als immersiv, wenn sie visuelle, auditive oder andere sensorische Ausgaben erzeugen, die die Umgebung des Benutzers simulieren oder erweitern @webxr-spec.
Einzelne XR-Devices können unterschiedliche Modi unterstützen, wobei grundlegend zwischen "immersive-vr" und "immersive-ar" unterschieden wird. Jedes XR-Gerät verfügt über eine Liste der unterstützten Modi und eine Reihe zugesicherter Funktionen für jeden Modus, die im Vorfeld festgelegt werden @webxr-spec.
=== System
Das XRSystem stellt alle WebXR-APIs zur Verfügung. Es ist verantwortlich für die Erstellung von XR-Geräten, die Verwaltung von XR-Sessions und die Bereitstellung von XR-Ansichten. Das XRSystem wird über das Attribut "xr" des Interfaces Navigator bereitgestellt wie in @navigator-listing dargestellt @webxr-spec. Das Interface repräsentiert den User Agent und ermöglicht das Abfragen von Statusinformationen und Details. Ein User Agent ist jede Software, die Webinhalte für Endbenutzer abruft und darstellt oder mithilfe von Webtechnologien implementiert ist @user-agent.
#let code = ```ts
partial interface Navigator {
[SecureContext, SameObject] readonly attribute XRSystem xr;
};
```
#figure(
code,
caption: [Navigator Interface]
) <navigator-listing>
=== Session
Eine XRSession stellt ein Objekt im WebXR Interface dar, welche für die Interaktion mit der XR-Hardware zuständig ist. Die XRSession wird durch die Methode "requestSession" eines XRSystem Objektes initialisiert. Wie in @requestSession-listing dargestellt, erwartet die Funktion den Modus der Session sowie optional ein XRSessionInit Objekt, welches die gewünschten Features definiert @webxr-spec.
#let code = ```ts
requestSession(XRSessionMode mode, optional XRSessionInit options = {});
```
#figure(
code,
caption: [requestSession Funktion]
) <requestSession-listing>
==== XRSessionMode
Jede XRSession besitzt einen Modus, der im XRSessionMode definiert ist. In dieser Arbeit liegt der Fokus auf dem Modus "immersive-ar", der vom WebXR Augmented Reality Module definiert wird. Dieses Modul stellt eine Erweiterung der WebXR Device API dar und signalisiert, dass die Sitzung Zugriff auf das verwendete Display erhält und Inhalte so darstellen kann, dass sie mit der realen Welt verschmelzen @webxr-spec @webxr-ar-module.
#let code = ```ts
enum XRSessionMode {
"inline",
"immersive-vr",
"immersive-ar"
};
```
#figure(
code,
caption: [Enum der Session-Modi]
)
==== Feature Dependencies
Einige Features einer XRSession sind möglicherweise nicht universell verfügbar. Hierbei können sowohl Hardware- als auch Softwareunterschiede der jeweiligen Geräte eine Rolle spielen. Des Weiteren stellen einige Funktionen sensible Informationen bereit, die erst nach einer expliziten Zustimmung des Nutzers abgerufen werden sollten. So stellt das Scannen eines Gesichts ein erhebliches Datenschutzrisiko dar @webxr-spec.
Um die Verfügbarkeit von Features zu überprüfen kann bei der Initialisierung einer XRSession ein Lexikon mit den gewünschten Features übergeben werden. In @XRSessionInit-listing wird das XRSessionInit Dictionary definiert, welches die Features in zwei Listen aufteilt. Im Sinne von Progressive Enhancement können Features als optional oder erforderlich definiert werden. Erforderliche Features müssen vom XR-Device unterstützt werden, um eine XRSession zu erstellen. Optionale Features können unterstützt werden @webxr-spec.
#let code = ```ts
dictionary XRSessionInit {
sequence<DOMString> requiredFeatures;
sequence<DOMString> optionalFeatures;
};
```
#figure(
code,
caption: [Das XRSessionInit Dictionary]
) <XRSessionInit-listing>
=== Spaces
Eine Grundfunktion der WebXR Device API besteht in der Bereitstellung von "Spatial Tracking". Hierbei stellt ein XRSpace ein Interface dar, das die räumlichen Beziehungen und die Anordnung von Objekten in einer virtuellen oder erweiterten Realität ermöglicht. Die API ermöglicht das Tracking von virtuellen Objekten, Nutzern sowie Eingabegeräten @webxr-spec.
Ein XRSpace stellt ein virtuelles Koordinatensystem dar, dessen Ursprung einem physischen Standort entspricht. Wie in @XRSpace-listing dargestellt, ist das bereitgestellte Interface abstrakt. Die Implementierung sowie das Tracking der Position finden nativ im XRDevice statt. Die verwendete Technologie und Methodik können sich hierbei von Gerät zu Gerät unterscheiden. Die API ermöglicht ein geräteübergreifendes, einheitliches Interface, das unabhängig von der verwendeten Technologie und Tracking-Methode ist @webxr-spec.
#let code = ```ts
[SecureContext, Exposed=Window] interface XRSpace : EventTarget {
// Implementation
};
```
#figure(
code,
caption: [Das XRSpace Interface]
) <XRSpace-listing>
==== XRReferenceSpace
Die Anforderungen an virtuelle Räume unterscheiden sich in Bezug auf die Positionierung und Orientierung der Objekte sowie die Bewegung innerhalb des Raumes. Die WebXR Device API definiert verschiedene vorgefertigte Referenzräume, die Anforderungen an die Positionierung und Orientierung der Objekte festlegen @webxr-spec.
Im Folgenden wird auf relevante Referenzräume eingegangen, die für die Implementierung der Anwendung von Bedeutung sind. Der Local-Space ist ein Raumtyp, dessen Koordinatensystemursprung nahe der ursprünglichen Position des Benutzers liegt. Dieses Koordinatensystem eignet sich optimal für Anwendungen, bei denen der Benutzer nicht weit von seinem Startpunkt entfernt ist. Eine Erweiterung des Local-Space stellt der Local-Floor-Space dar, der zusätzlich die Bodenhöhe berücksichtigt. Der Ursprung dieses Raumes wird auf Bodenniveau festgelegt, was eine präzise Platzierung von Objekten auf dem Boden ermöglicht und die Immersion in Anwendungen verstärkt, bei denen der Benutzer steht oder sich nur geringfügig bewegt. Schließlich bietet der Bounded-Floor-Space eine klar definierte Umgebung mit festgelegten Grenzen, innerhalb derer sich der Benutzer bewegen kann. Diese Grenzen werden durch ein Polygon definiert, das die Bewegungsfreiheit sicher und vorhersehbar gestaltet @webxr-spec.
=== Input
Die WebXR Device API ermöglicht es, mit kompatiblen Eingabegeräten zu interagieren, indem sie das XRInputSource Interface verwendet. Dieses Interface dient zur Repräsentation von Eingabegeräten in der XR-Umgebung. Eingabemechanismen, die nicht explizit mit dem XR-Gerät verbunden sind, wie herkömmliche Gamepads, Mäuse oder Tastaturen, werden nicht als XR-Eingabequellen betrachtet @webxr-spec @webxr-gamepad-module.
Das XRInputSource stellt hierbei ein abstraktes Interface dar, welches es ermöglicht unterschiedliche Eingabegeräte zu repräsentieren. Einzelne Eingabegeräte können sich in der Verfügbarkeit von Features oder der insgesamten Funktionalität unterscheiden. Die API definiert verschiedene Kategorien und Funktionen, wodurch die Interaktion einheitliche gestaltet werden kann.
Der XRTargetRayMode beschreibt die Methode zur Erzeugung eines Zielstrahls, wodurch die Darstellung und Interaktion dieses Strahls an das jeweilige Gerät angepasst werden kann. Die vier Modi sind „gaze“, „tracked-pointer“, „screen“ und „transient-pointer“. Der Modus „gaze“ bezeichnet einen Zielstrahl, der vom Betrachter ausgeht und der Blickrichtung folgt, häufig in Head-Mounted Displays verwendet. Der Modus „tracked-pointer“ beschreibt einen Zielstrahl, der von einem Handheld-Gerät oder Hand-Tracking-Mechanismus stammt und ergonomischen Richtlinien folgt, wobei er in die Richtung des ausgestreckten Zeigefingers zeigt. „Screen“ bezeichnet eine Eingabe, die durch Interaktion mit dem Canvas-Element erfolgt, beispielsweise durch Mausklick oder Touch-Event. „Transient-pointer“ bedeutet, dass die Eingabequelle aus Betriebssystem-Interaktionen stammt und nicht von spezifischer Hardware. Dies umfasst Benutzerabsichten, die auf sensiblen Informationen basieren, oder Eingaben von unterstützenden Technologien, ohne direkt die Nutzung solcher Technologien zu offenbaren @webxr-spec.
=== Events
Um auf Änderungen in der XR-Umgebung zu reagieren, bietet die WebXR Device API verschiedene Events, die von der XRSession und den XRInputSources ausgelöst werden. Diese Events ermöglichen es, auf Benutzereingaben zu reagieren, die Position und Orientierung von Objekten zu aktualisieren und die Interaktion mit der XR-Umgebung zu steuern @webxr-spec. |
|
https://github.com/barrel111/readings | https://raw.githubusercontent.com/barrel111/readings/main/problems/kt-problems.typ | typst | #import "@local/preamble:0.1.0": *
#import "@preview/commute:0.2.0": node, arr, commutative-diagram
#show: project.with(
course: "Algorithms",
sem: "Summer",
title: "Kleinberg-Tardos",
subtitle: "Problems",
authors: ("<NAME>",),
)
#set enum(indent: 15pt, numbering: "a.")
= Stable Matching
==
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/grid-1.typ | typst | Apache License 2.0 | // Test grid layouts.
---
#let cell(width, color) = rect(width: width, height: 2cm, fill: color)
#set page(width: 100pt, height: 140pt)
#grid(
columns: (auto, 1fr, 3fr, 0.25cm, 3%, 2mm + 10%),
cell(0.5cm, rgb("2a631a")),
cell(100%, forest),
cell(100%, conifer),
cell(100%, rgb("ff0000")),
cell(100%, rgb("00ff00")),
cell(80%, rgb("00faf0")),
cell(1cm, rgb("00ff00")),
cell(0.5cm, rgb("2a631a")),
cell(100%, forest),
cell(100%, conifer),
cell(100%, rgb("ff0000")),
cell(100%, rgb("00ff00")),
)
---
#set rect(inset: 0pt)
#grid(
columns: (auto, auto, 40%),
column-gutter: 1fr,
row-gutter: 1fr,
rect(fill: eastern)[dddaa aaa aaa],
rect(fill: conifer)[ccc],
rect(fill: rgb("dddddd"))[aaa],
)
---
#set page(height: 3cm, margin: 0pt)
#grid(
columns: (1fr,),
rows: (1fr, auto, 2fr),
[],
align(center)[A bit more to the top],
[],
)
|
https://github.com/Clamarche/typst-language-support | https://raw.githubusercontent.com/Clamarche/typst-language-support/main/README.md | markdown | # typst-language-support README
This is the README for your extension "typst-language-support". After writing up a brief description, we recommend including the following sections.
## Features
Describe specific features of your extension including screenshots of your extension in action. Image paths are relative to this README file.
For example if there is an image subfolder under your extension project workspace:
\!\[feature X\]\(images/feature-x.png\)
> Tip: Many popular extensions utilize animations. This is an excellent way to show off your extension! We recommend short, focused animations that are easy to follow.
## Requirements
If you have any requirements or dependencies, add a section describing those and how to install and configure them.
## Extension Settings
Include if your extension adds any VS Code settings through the `contributes.configuration` extension point.
For example:
This extension contributes the following settings:
* `myExtension.enable`: Enable/disable this extension.
* `myExtension.thing`: Set to `blah` to do something.
## Known Issues
Calling out known issues can help limit users opening duplicate issues against your extension.
## Release Notes
Users appreciate release notes as you update your extension.
### 1.0.0
Initial release of ...
### 1.0.1
Fixed issue #.
### 1.1.0
Added features X, Y, and Z.
---
## Working with Markdown
You can author your README using Visual Studio Code. Here are some useful editor keyboard shortcuts:
* Split the editor (`Cmd+\` on macOS or `Ctrl+\` on Windows and Linux).
* Toggle preview (`Shift+Cmd+V` on macOS or `Shift+Ctrl+V` on Windows and Linux).
* Press `Ctrl+Space` (Windows, Linux, macOS) to see a list of Markdown snippets.
## For more information
* [Visual Studio Code's Markdown Support](http://code.visualstudio.com/docs/languages/markdown)
* [Markdown Syntax Reference](https://help.github.com/articles/markdown-basics/)
**Enjoy!**
|
|
https://github.com/TOMATOFQY/MyChiCV | https://raw.githubusercontent.com/TOMATOFQY/MyChiCV/main/resume.chinese.typ | typst | MIT License | #import "chicv.chinese.typ": *
#show: chicv
#box([
= 范乾一
#fa[#phone] #fa[#weixin] (+86)132-8866-2339 |
#fa[#envelope] <EMAIL> |
#fa[#github] #link("https://github.com/TOMATOFGY")[github.com/TOMATOFGY]
// #fa[#home] #link("https://www.notion.so/tomatofgy/TOMATOFGY-s-Blog-c83179a1988543678b177bbb4fa957e1")[TOMATOFGY's Blog]
])
#h(1fr)
#box(baseline:3% ,radius: 5pt,[
#image("img/tomato.png",width:8%)
]
)
== 教育背景
#landr(
tl: "北京大学·软件与微电子学院·网络安全·在读硕士研究生·(GPA 3.60/4.00, rank 4/20)",
tr: "2021/09 - 2024/07",
)
#linebreak()
#landr(
tl: "新加坡国立大学·Computing School·暑期实习",
tr: "2019/06 - 2019/08",
)
#linebreak()
#landr(
tl: "北京邮电大学·计算机学院·计算机科学与技术·学士·(GPA 91/100, rank 12/404)",
tr: "2017/06 - 2021/06",
)
== 工作经历
#cventry(
tl: "1. 字节跳动 · AML · engine · Parameter Server Group · 研发",
tr: "2023/12 - 2024/05",
bl: "",
br: ""
)[
参与字节机器学习平台中参数服务器组件的研发.参与推荐系统模中型的训练与推理服务.
- 参与 PS 组件在不同运行环境下的优化. 以体系结构角度优化服务性能.
- 参与同步链路的优化. 平均减少服务所需带宽 20%.
]
#cventry(
tl: "2. 字节跳动 · Data · 数据平台 · 分析型数据库 · 研发实习生",
tr: "2023/03 - 2023/07",
bl: "",
br: ""
)[
参与字节旗下分析型数据库 ByConity 存储层的优化工作。
- 参与存算分离、分布式缓存、监控链路功能的设计与实现。
- 参与数据冷热分离的实现.实现了成本的降低与性能的提升。
]
#cventry(
tl: "3. 商汤科技 · 存储系统与技术部 · 缓存与数据加速组 · 研发实习生",
tr: "2022/06 - 2022/11",
)[
*参与商汤内部缓存服务开发(基于 NVMe 的分布式键值数据库)。*
- *设计 POSIX 接口*。通过 Linux FUSE,使用户无需修改访问文件系统的代码即可访问缓存,提升服务易用性。
- *设计系统调用劫持机制*。实现绕过 libfuse 直接访问缓存,提高访问效率。
- *针对云场景优化读写效率*。为 S3 等服务建立反向代理,实现读写速度提升100倍,模型训练速度提升3%。
]
#cventry(
tl: "4. 微软亚洲研究院 · 创新工程组 (IEG) · 软件开发实习生 " + iconlink("https://apps.apple.com/cn/app/%E7%89%9B%E5%8A%B2%E5%B0%8F%E8%8B%B1/id1509670731",icon:app-store),
tr: "2021/08 - 2022/06",
)[
*负责开发月活跃用户达十万级的应用的后端及 iOS 端*。
- 深度参与项目重构的设计与实现。使用 SwiftUI 替代了 UIKit 框架,提升产品迭代效率。
]
== 获奖情况
#cventry(
tl: "1. 蚂蚁集团 · 2022 OceanBase 数据库大赛" + " " + iconlink("https://open.oceanbase.com/competition/index#info") + " " + "季军 (决赛 rank 4/50,初赛 rank 11/1180)" ,
tr: "2022/10 - 2023/01"
)[
*设计并优化 OceanBase 高性能旁路导入功能*
- 设计并实现旁路导入模块,包括 CSV 文件解析,压缩算法,归并排序算法,以及 CSV2SSTable 算法。
- 运用 perf 等调优技术,捕获并优化各大小优化点。
- *实现性能大幅提升*,相较于 OceanBase 原 batch insert 方案,*性能提升 10 倍*。 #iconlink("https://zhuanlan.zhihu.com/p/605181163",icon:zhihu) #iconlink("https://zhuanlan.zhihu.com/p/617520132",icon:zhihu)
]
== 项目经历
#cventry(
tl: "1. Sourcetrail Golang Indexer " + emph("开源贡献 ") + iconlink("https://github.com/TOMATOFGY/SourcetrailGolangIndexer", icon:github),
tr: "2021/01 - 2021/06"
)[
- 为源码阅读软件 Sourcetrail 提供了对 Golang 语言的支持。利用程序静态分析技术,分析并生成 Golang 项目的函数间调用图、函数内控制流程图等,并提供可交互的图形化界面。
]
#cventry(
tl: "2. 自制操作系统内核 " + emph("课程设计"),
tr: "2020/03 - 2020/06"
)[
*负责实现一个拥有中断机制、进程调度、文件系统等常见功能的小型内核。*
- _考察了uCore\@thu, rCore\@thu, xv6\@MIT, BlogOS\@Phil-opp等常见的开源操作系统._ 负责特权级转换功能的实现;负责中断机制的实现。包含中断屏蔽、二级中页断等基本功能;负责内核内存管理功能的实现。包括 sv39 页表机制的实现、基于 BuddySystem 的内存管理;负责文件系统的实现。仿照 Linux 的虚拟文件系统架构,基于 Ext2 实现了一个简易的文件系统。
]
== 其他
- 语言:C/C++, Shell, Rust, Golang, HTML/CSS/JavaScript, Python, SQL, Swift, Obj-C, VHDL
- 工具&框架&产品:CMake; Git; GDB, Perf, Flamegraph; Docker; MySQL, Clickhouse, Redis, Memcached, LevelDB
- #box([外语:TOEFL : 102 ; CET-6 : 559]) #h(1fr) #box([ #text(fill: gray)[Last Updated on Apr 26, 2024]])
|
https://github.com/Lightbridge-KS/kittipos-cv-typst | https://raw.githubusercontent.com/Lightbridge-KS/kittipos-cv-typst/main/Kittipos-CV.typ | typst | // #import "modern-acad-cv.typ": *
#import "@preview/modern-acad-cv:0.1.0": *
#import "@preview/fontawesome:0.4.0"
#import "@preview/use-academicons:0.1.0"
// Color Setup
#let link-color = rgb("#800000") // red!50!black
#let cite-color = rgb("#4040a0") // blue!50!gray
// Set up colored links
#show link: it => [
#set text(fill: link-color)
#it
]
// Set up colored citations
#show cite: it => [
#set text(fill: cite-color)
#it
]
// set the language of the document
#let language = "en"
// loading meta data and databases (needs to be ad this directory)
#let metadata = yaml("metadata.yaml")
#let multilingual = yaml("dbs/i18n.yaml")
#let work = yaml("dbs/work.yaml")
#let education = yaml("dbs/education.yaml")
#let skills = yaml("dbs/skills.yaml")
// Not used DB
#let grants = yaml("dbs-not-use/grants.yaml")
#let refs = yaml("dbs-not-use/refs.yaml")
#let conferences = yaml("dbs-not-use/conferences.yaml")
#let talks = yaml("dbs-not-use/talks.yaml")
#let committee = yaml("dbs-not-use/committee.yaml")
#let teaching = yaml("dbs-not-use/teaching.yaml")
#let training = yaml("dbs-not-use/training.yaml")
// defining variables
#let headerLabs = create-headers(multilingual, lang: language)
#show: modern-acad-cv.with(
metadata,
multilingual,
lang: language,
font: "Fira Sans",
show-date: true
)
// Custom Function
#let certificate(certificate_link) = {
link(certificate_link)[Certificate]
}
= #headerLabs.at("work")
#cv-auto-stc(work, multilingual, lang: language)
= #headerLabs.at("education")
#cv-auto-stp(education, multilingual, lang: language)
// = #headerLabs.at("software")
= #headerLabs.at("app")
== Radiology
#pad(left: 9em, top: 1em)[
- #link("https://kittipos-sir.shinyapps.io/tirads-calculator/")[*TIRADS Calculator:*] Calculator for Thyroid Imaging Reporting & Data System @tirads-calc-app
- #link("https://github.com/Lightbridge-KS/designCTER/")[*DesignCTER:*] Generate CT protocols template in emergency department @DesignCTER
- #link("https://github.com/Lightbridge-KS/adrenal_washout_app")[*AWC:*] Calculate adrenal percentage washout in multiphase CT @AdrenalWashoutCT
]
== Physiology
#pad(left: 9em, top: 1em)[
- #link("https://kittipos.shinyapps.io/harvard-spirometer/")[*Harvard Spirometer Tracing Simulator:*] Simulate Harvard Spirometer tracing from mathematical model @HarvardSpirometer-app
]
= #headerLabs.at("software-r-pkg")
== General
#pad(left: 9em, top: 1em)[
- #link("https://lightbridge-ks.github.io/thaipdf/")[*thaipdf:*] R Markdown to PDF in Thai language (CRAN) @thaipdf
]
== Education
#pad(left: 9em, top: 1em)[
- #link("https://lightbridge-ks.github.io/moodleStats/")[*moodleStats:*] Perform quiz and item analysis on Moodle Grades Report @moodleStats
- #link("https://lightbridge-ks.github.io/moodleQuiz/")[*moodleQuiz:*] Combine and manipulate Moodle Quiz Report for grading @moodleQuiz
- #link("https://lightbridge-ks.github.io/zoomclass/")[*zoomclass:*] Analyze Zoom’s participants report and chat file @zoomclass
- #link("https://lightbridge-ks.github.io/rslab/")[*rslab:*] Calculate various respiratory physiology parameters @rslab
]
== Research
#pad(left: 9em, top: 1em)[
- #link("https://lightbridge-ks.github.io/labChartHRV/")[*labChartHRV:*] Import and manipulate LabChart’s Heart Rate Variability Data @labChartHRV
]
= #headerLabs.at("training")
== Data Science
#pad(left: 9em, top: 1em)[
- *Statistical Learning by StanfordOnline* (edX) --- #certificate("https://courses.edx.org/certificates/5547b0ad382e4372b5173f4d482d60a5")
- *Advanced R Programming by Johns Hopkins University* (Coursera) --- #certificate("https://coursera.org/share/73621d441d07e2fd00ee0ac0ec19bb38")
- *Data Analysis with R Programming by Google* (Coursera) --- #certificate("https://coursera.org/share/a7341c020f68003ae532547d73fc4ccf")
- *LangChain for LLM Application Development* short course by DeepLearning.AI --- #certificate("https://learn.deeplearning.ai/accomplishments/31ddf9a5-e5c4-4db5-aa3a-7ce89d87e3b4?usp=sharing")
]
== Others
#pad(left: 9em, top: 1em)[
- *Cell and molecular biology course for postgraduate students* (Mahidol university)
]
// #cv-auto-cats(training, multilingual, headerLabs, lang: language)
// = #headerLabs.at("grants")
// #cv-auto-stp(grants, multilingual, lang: language)
// = #headerLabs.at("pubs")
// #cv-cols(
// "",
// for lang in multilingual.lang.keys() {
// if language == lang [
// #multilingual.lang.at(lang).pubs-note
// ]
// }
// )
// == #headerLabs.at("pubs-peer")
// #cv-refs(refs, multilingual, tag: "peer", me: [Mustermensch, M.], lang: language)
// == #headerLabs.at("pubs-edited")
// #cv-refs(refs, multilingual, tag: "edited", me: [Mustermensch, M.], lang: language)
// == #headerLabs.at("pubs-book")
// #cv-refs(refs, multilingual, tag: "book", me: [Mustermensch, M.], lang: language)
// == #headerLabs.at("pubs-reports")
// #cv-refs(refs, multilingual, tag: "other", me: [Mustermensch, M.], lang: language)
// == #headerLabs.at("pubs-upcoming")
// #cv-refs(refs, multilingual, tag: "planned", me: [Mustermensch, M.], lang: language)
// = #headerLabs.at("confs")
// == #headerLabs.at("confs-conf")
// #cv-cols(
// "",
// headerLabs.at("exp-confs")
// )
// #cv-auto-list(conferences, multilingual, lang: language)
// == #headerLabs.at("confs-talks")
// #cv-auto(talks, multilingual, lang: language)
// = #headerLabs.at("committee")
// #cv-auto(committee, multilingual, lang: language)
// = #headerLabs.at("teaching")
// == #headerLabs.at("teaching-thesis")
// #if language == "de" [
// #cv-two-items[Bachelor][9][Master][2]
// ] else if language == "en" [
// #cv-two-items[Bachelor][9][Master][2]
// ] else if language == "pt" [
// #cv-two-items[Graduação][9][Pós-Graduação][2]
// ] else [
// #cv-two-items[Bachelor][9][Master][2]
// ]
// == #headerLabs.at("teaching-courses")
// #cv-table-teaching(teaching, multilingual, lang: language)
= #headerLabs.at("others")
#cv-auto-skills(skills, multilingual, metadata, lang: language)
#pagebreak()
// Bibliography
#bibliography("ref/CV.bib") |
|
https://github.com/DaAlbrecht/lecture-notes | https://raw.githubusercontent.com/DaAlbrecht/lecture-notes/main/template.typ | typst | MIT License | #let project(title: "", header:"", body) = {
let authors = ("David",);
let school = "FFHS - Fernfachhochschule Schweiz";
let degree = "BsC in Cyber Security";
let date = "2024";
set document(author: authors, title: title)
set page(numbering: "1", number-align: center, header: align(center, header))
set text(font: "Berkeley Mono", size: 11pt,spacing: 80%)
show raw: set text(font: "Berkeley Mono", size: 11pt, spacing: 100%)
set heading(numbering: "1.1")
show math.equation: set text(style: "italic")
[
#set align(center)
#text(school)
#linebreak()
#text(degree)
#linebreak()
]
// Title page.
// The page can contain a logo if you pass one with `logo: "logo.png"`.
v(0.6fr)
v(3.6fr)
text(1.1em, date)
v(1.2em, weak: true)
text(2em, weight: 700, title)
// Author information.
pad(top: 0.7em, right: 20%, grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(start, strong(author))),
))
v(2.4fr)
pagebreak()
outline(title: "Table of contents", depth: 3, indent: true)
pagebreak()
// Main body.
set par(justify: true)
body
}
#let classes = ("Definition", "Example", "Statement")
#let h1_marker = counter("h1")
#let h2_marker = counter("h2")
#let note_block(body, class: "Block", fill: rgb("#FFFFFF"), stroke: rgb("#000000")) = {
let block_counter = counter(class)
locate(loc => {
// Returns the serial number of the current block
// The format is just like "Definition 1.3.1"
let serial_num = (
h1_marker.at(loc).last(),
h2_marker.at(loc).last(),
block_counter.at(loc).last() + 1)
.map(str)
.join(".")
let serial_label = label(class + " " + serial_num)
block(fill:fill,
width: 100%,
inset:8pt,
radius: 4pt,
stroke:stroke,
body)
v(-8pt)
text(10pt, weight: "bold")[#class #serial_num #serial_label #block_counter.step()]
v(2pt)
})
}
#let example(body) = note_block(
body, class: "Example", fill: rgb("#F5F5F5"), stroke: none
)
#let definition(body) = note_block(
body, class: "Definition", fill: rgb("#F2F6FE"), stroke: rgb("#6983EE")
)
#let statement(body) = note_block(
body, class: "Statement", fill: rgb("#FEF2F4"), stroke: rgb("#EE6983")
)
#let fill_alternating(x, y) = {
if calc.even(y) {
return rgb("#F5F5F5")
}
else{
return rgb("#FFFFFF")
}
}
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/复变函数/作业/hw1.typ | typst | #import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark, proposition,der, partialDer, Spec
#import "../../template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: note.with(
title: "作业1",
author: "YHTQ",
date: none,
logo: none,
withOutlined : false,
withTitle :false,
)
(应交时间为3月8日)
#set heading(numbering: none)
= p4 Ex. 3
从几何意义上看:
$
| z - a | - | z + a | = 2 c
$
就是到复平面上 $a, -a$ 两点的距离之差等于 $2c$ 的点的轨迹。这个轨迹是双曲线的一支
= p6 Ex. 7
不妨设 $z != 0$,否则结论显然\
设 $z = r(cos theta + i sin theta), r > 0, theta in [-pi, pi)$,由题设,有:
$
cos (n theta) >= 0, forall n in NN
$
这表明:
$
theta in [-pi/2, pi/2)
=>& 2 theta in [-pi, pi) and cos (2 theta) >= 0\
=>& 2 theta in [-pi/2, pi/2)\
=>& theta in [-pi/4, pi/4)\
=>& 4 theta in [-pi, pi) and cos (4 theta) >= 0\
=>& 4 theta in [-pi/2, pi/2)\
=>& theta in [-pi/8, pi/8)\
=>& ...\
=>& 2^n theta in [-pi, pi) and cos (2^n theta) >= 0\
=>& 2^n theta in [-pi/2, pi/2)\
=>& theta in [-pi/2^n, pi/2^n)
$
显然,这表明 $theta = 0$,进而 $z = r$ 是正实数
= p17 Ex. 5
取定 $a, epsilon$,记所有满足:
$
exists z_0 = a, z_1, z_2, ..., z_n = y "满足":\
| z_(k+1) - z_k | < epsilon, k = 0, 1, 2, ..., n-1
$
的 $y$ 构成的集合为 $S$,断言:
+ $S$ 是($F$ 中的)开集。事实上,任取 $y in S$,我们有:
- $forall y' in B(y, epsilon) sect F$
- $y in S => exists z_0 = x, z_1, ..., z_n = y, | z_(k+1) - z_k | < epsilon, k = 0, 1, 2, ..., n-1$
- $|y' - y| < epsilon => exists z'_0 = x, z'_1 = z_1, ..., z'_n = y, z'_(n+1) = y':$
$
| z'_(k+1) - z'_k | < epsilon, k = 0, 1, 2, ..., n
$\
$=> y' in S$
表明 $B(y, epsilon) sect F subset S$
+ $S$ 是($F$ 中的)闭集。为此,任取 $y_n in S, y_n -> y in F$,只需证明 $y in S$\
- $y_n -> y => exists i, |y_i - y| < epsilon$
- $y_i in S => exists z_0 = x, z_1, ..., z_n = y_i:$
$
| z_(k+1) - z_k | < epsilon, k = 0, 1, 2, ..., n-1
$
- $|y - y_i| < epsilon => exists z'_0 = x, z'_1 = z_1, ..., z'_n = y_i, z'_(n+1) = y:$
$
| z'_(k+1) - z'_k | < epsilon, k = 0, 1, 2, ..., n
$\
$=> y in S$
由 $F$ 连通及 $x in S$ 知 $F = S$,证毕。
闭集的条件是不必要的,其上的证明并未用到 $F$ 是闭集的条件。\
取 $S = {x + y i | y = 1/x or y = - 1/x, x > 0}$,它是不连通的闭集,但依旧满足结论(对于任何 $x, y in S$,它们在同一分支上时结论显然,在不同分支上时,不妨设 $x$ 在上半分支。对于任意小的 $epsilon$,可以将 $x -> (3/(epsilon), 1/3 epsilon) -> (3/(epsilon), - 1/3 epsilon) -> y$ 的链连接起来)
= p20 Ex. 6
+ $R^n$ 上的所有非闭集的集合作为度量子空间都是不完备的
+ 任取 $RR -> RR$ 的连续单调函数(从而是单射) $f$:
$
d(x, y) = |f(x) - f(y)|
$
可以产生一个 $RR$ 上的度量。
- 假如 $f(RR)$ 不是闭集,那么可以取得 $x_n, f(x_n) -> eta in.not f(RR)$,我们有:
- $x_n$ 不收敛,否则 $x_n -> x => |f(x_n) - f(x)| -> 0 => f(x) = eta$ 矛盾
- 当 $n, m$ 充分大时 $|f(x_n) - f(x_m)| < epsilon$,是柯西列
因此该度量空间并不完备,可以取得很多这样的函数如 $e^x$
+ 在 $RR$ 上定义:
$
d(x, y) = cases(
|arctan(x) - arctan(y)|\, x\, y in QQ or x\, y in.not QQ,
pi "else"
)
$
为了验证它是度量,只需验证三角不等式:
- 若 $x, y, z$ 均处于情形 1,则显然
- 否则,为了验证 $d(x, y) + d(y, z) >= d(x, z)$,考虑:
- $d(x, z)$ 是情形 1,此时注意到情形 2 的距离严格大于情形 1 的距离,不等式一定成立
- $d(x, z)$ 是情形 2,此时式子左侧一定有一项是情形 2(否则 $x, y, z$ 有相同的有理性),再结合度量的非负性结论正确
同时,注意到 $arctan$ 在 $RR$ 上一致连续,因此通常度量下柯西的有理数列也是此度量下的柯西列。\
此时,任取极限为无理数的有理序列,不难验证其为柯西列但不可能收敛
= p20 Ex. 8
取 $R_n = {x_n, x_(n+1), ...}$,注意到:
- $x_n$ 是柯西列蕴含 $diam(R_n) -> 0$
- $x_n$ 有收敛子列蕴含所有的 $R_n$ 有公共聚点 $x$
足以说明 $x_n -> x$ :
- 事实上,任取 $epsilon > 0$,取得 $N$ 使得 $diam(R_N) < epsilon$
- 再由 $x$ 是 $R_N$ 聚点,取 $x' in R_N$ 使得 $d(x', x) < epsilon$
此时便有 $forall x_i in R_N, d(x_i, x) <= d(x_i, x') + d(x', x) <= 2 epsilon$,证毕
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/regression/issue21b.typ | typst | Other | #import "issue19.typ" as zeke
#zeke.nums
#import "issue20.typ": a as multiline
#multiline
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/numbers_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test the `str` function with integers.
#str(12) \
#str(1234567890) \
#str(0123456789) \
#str(0) \
#str(-0) \
#str(-1) \
#str(-9876543210) \
#str(-0987654321) \
#str(4 - 8)
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20interna/Verbali/23-11-13/23-11-13.typ | typst | #import "/template.typ": *
#show: project.with(
date: "13/11/23",
subTitle: "Meeting di retrospettiva e pianificazione",
docType: "verbale",
authors: (
"<NAME>",
),
timeStart: "15:30",
timeEnd: "17:30",
);
= Ordine del giorno
- Aggiornamento del gruppo in merito alle nuove automazioni adottate;
- Retrospettiva dello sprint 1;
- Discussione in merito alle tecnologie adottate;
- Ripartizione dei ruoli per il nuovo sprint;
- Pianificazione sprint 2.
== Automazioni e nuova repository
Il gruppo che si è dedicato nel precedente sprint ad automatizzare la repository ha
finalizzato il lavoro e ha aggiornato il gruppo riguardo alle nuove funzionalità.
La vecchia repository è stata abbandonata in favore di una nuova (questo perché riorganizzare
la vecchia repository avrebbe richiesto troppo tempo) con una nuova organizzazione dei branch,
differente rispetto alla precedente: prima era presente un branch main (per i release) e un branch develop dal quale si aprivano feature branch; ora la repository è composta da tre branch principali quali:
- main: contenente i pdf compilati e pubblicati automaticamente tramite GitHub Actions solo a seguito della verifica di uno o più reviewer;
- src: contenente i file sorgenti scritti in Typst;
- website: branch parallello contente un versione work in progress del sito del gruppo.
== Retrospettiva sullo sprint
Segue quindi la discussione in merito ai miglioramenti da attuare nei prossimi sprint e quello attuale. Lo sprint passato ha avuto due criticità fondamentali:
- una generale confusione da parte del team di documentazione in merito alla priorità da dare ai vari documenti da redigere e al loro contenuto;
- l'impossibilità di utilizzare la nuova repository bloccata dai rallentamenti subiti dal sottovalutare la mole di lavoro riguardo l'implementazione delle automazioni.
Abbiamo quindi realizzato fosse necessario che le persone adette allo sviluppo delle GitHub Action terminassero quanto prima i lavori segnandolo come task di importanza critica. \
Abbiamo poi diviso il gruppo in 3 team di lavoro distinti per lavorare sui vari documenti assegnando più persone al documento con maggiore urgenza (vedi @ruoli).
== Nuove tecnologie
Il gruppo ha continuato la riunione con una panoramica sulle nuove tecnologie adottate:
- Jira: ITS sostitutivo a GitHub, scelto per le molte funzionalità che offre come i diagrammi di Gantt o la possibilità di definire macro obbiettivi (epic) oltre le normali task. Un'altra funzionalità utile di Jira è la possibilità di definire sprint settimanali che permettono di definire obbiettivi da raggiungere entro l'arco di periodo indicato. Questa feature è fondamentale per definire la qualità del lavoro svolto, se il ritmo di lavoro è stato opportunamente calcolato/rispettato, dove risiedono le criticità della pianificazione del lavoro e permette inoltre di avere strumenti metrici come i burndown chart per monitorare lo stato di avanzamento dello sprint;
- Miro: board che verrà utilizzata durante i meeting interni per supportare processi di brainstorming o per riportare concetti o criticità durante l'analisi dello sprint appena terminato.
== Ripartizione dei ruoli <ruoli>
In seguito al diario di bordo tenutosi in data 13-11-23, il gruppo si è organizzato per portare avanti lo sviluppo dei tre documenti fondamentali, quali:
- Analisi dei Requisiti: documento di priorità maggiore. Risorse assegnate: 3 persone;
- Piano di Progetto. Risorse assegnate: 2 persone;
- Norme di Progetto: Risorse assegnate: 2 persone.
= Azioni da intraprendere
- Cominciare a redigere un glossario dei termini;
- Definire delle modalità di lavoro precise da utilizzare con Jira e un workshop per allineare le conoscenze del gruppo in merito al suo utilizzo;
- Contattare l'azienda per domande in merito all'Analisi dei Requisti (confermata per mercoledì 15/11/23).
|
|
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/random/haobin.typ | typst | #import "template.typ": *
#show: template.with(
title: "Haobin Iceberg",
subtitle: "<NAME>"
)
This document will be a comprehensive set of notes covering the content in the set of tweets by user `@binneulbinism`, linked #link("https://twitter.com/binneulbinism/status/1757853566033592793")[here]. I will attempt to be as friendly as possible to the average human, but this set of notes will mostly be fine tuned to my knowledge base, supplemented greatly by my significant other, #link("https://www.linkedin.com/in/annie-wang-184361221")[<NAME>].
As a disclaimer, I will not be covering all the content present in the source material, rather I will be picking points that I deem to be of significance. Points are organized into tiers, with higher numbers meaning deeper levels in the iceberg.
= Terminology
#twocol(
define(
title: "Tinhatting"
)[
Tinhatting in the context of this document will refer to speculating over small perhaps insignificant or unsubstantiated events, and extending them to _kiss kiss smacka smacka_ conclusions for our besties Sung Han Bin (*HB*) and Zhang Hao (*ZH*).
],
define(
title: "Additional Terms"
)[
/ BP: Boys Planet
/ tgt: Together
/ e/o: Each Other
/ BBL: Bubble (parasocial app where idols attempt to impersonate significant others)
/ wrt: With Regard To
/ repo: Report (don't know why the letters "rt" are so hard to write out)
]
)
Now let us start delving into the intricacies of the complicated world of Haobin.
= Tier 1
#note(
title: "Current Status"
)[
Haobin has good chemisty and are cute together! I'm excited to see what I can learn about them :3
]
== "Hyung is my crying button" <crybutton>
Allegedly something that HB said to ZH during their Tomboy era when he was under a lot of stress. Happened in the laundry room (where there are no cameras). Pretty cute especially considering the vibe they both give off on BP would seem to indicate HB takes on a much more hyung-like position in the relationship. Makes you wonder what else was true about BP behind the scenes that we didn't get to see as the average viewer.
== "Let's drink zero cola everyday"
During the second elimination round (when they were the top two contestants), when asked if they wanted to say anything to the other person, this is what ZH said to HB. Of course the insinuation is that he wants them to debut together. Very cute since they seemed to get super close during the Tomboy period as a whole.
#define(
title: "Haobinists"
)[
Casual and more informal term used to refer to people who ship ZH and HB.
]
#define(
title: "Zerocolas"
)[
Haobin supporters are commonly called Zerocolas due to the above. This term is generally used to refer to the Chinese part of Haobinists.
]
== BP Massage
After the event described #link(label("crybutton"))[above], ZH jokingly asks HB to give him a massage in return. As a result, HB very shockingly, and not at all jokingly gives him a massage. Footage is filmed from a camera in the corner of the room while pitch black and feels a bit like you stumbled upon your parents' years old camcorder labeled "DO NOT WATCH".
== Blue and Pink
During BP, blue and pink were used to refer to the Korean and Global groups respectively. They have now become used to refer to HB and ZH.
== Paris Selfie
#define(
title: "RPS"
)[
Copy-pasted from Google because I had no clue what this meant.
#quote(attribution: "Urban Dictionary", block: true)[
A popular although slightly controversial genre of fanfiction involving real life people. Namely actors, musicians, athletes, politicians... etc. Basically anyone who is in the public eye. RPS stories or {fics} depict a romantic and/or sexual relationship between two members of the same sex.
Different from {fanfiction} or {fanfic} which involve fictional characters.
Follows the same general traditions of fictional slash, with separate cliques, fanlistings and archives.
]
The actual *S* part is up for debate, most things I search up seem to indicate it stands for *Slash*, however my beautiful booboo partner seems to suggest it stands for *Shipping* as slash generally refers to same sex shipping, and in general is quite an outdated term.
]
#twocol(
align(horizon)[
This is the alleged offender image which caused so much ruckus among Haobinists. Supposedly this can be cited as one of the foundational moments for the start of RPS regarding Haobin.
It's pretty fucking cute.
],
align(center)[#bimg("img/paris.jpeg", width: 50%)]
)
== Dolphin Story
#define(
title: "Tingle"
)[
An ASMR show for KPOP idols.
]
While in BP, there was a random van with a dolphin on the side, and HB asked ZH what "dolphin" was in Mandarin after telling him what it was in Korean. This was at the very beginning when they didn't know each other that well, so this whole interaction was undoubtedly a very important moment for them, and one they probably remembered as one of their earliest times talking to each other.
Speeding forward a little bit, while on Tingle, they revealed that HB's contact name for ZH has a dolphin in it.
=== Tingle
This exact Tingle episode is pretty significant as it is one of the only forms of content that exist where it is just the two of them answering questions about e/o.
It also apparently includes lots of other fancervicy things like *SMELLING EACH OTHER'S BREATH*.
I imagine this is to Haobinists what Leetcode is to little children trying to get a job in CS.
== First TikTok
HB and ZH filmed their first TikTok together on *Valentine's* day. A little scandalous if you ask me... `o.O`
== Nick & Judy
#define(
title: "FPS"
)[
A made up term based on *RPS* from earlier. It stands for "Fake Persons Shipping".
]
The two of them did Nick and Judy challenge, where they essentially recreate an *FPS* between two characters from Zootopia. The chemistry was excellent and it's clear the two care a lot about each other!
= Tier 2
#note(
title: "Current Status"
)[
Oh my are we here already. Still think the two of these are CAF (cute as fuck). I say HB is the bottom and ZH is the top. I am 99% sure this is quite a controversial take but I will defend it until the day I die (at least for now).
]
== Take a Look at My GF
Haobin attempts the (to me) very cringe trend except they don't use the official audio but it's the exact same format.
== Mirrorz
Another name given to Haobinists, referring to ZH saying "it was like talking to a mirror" (obviously talking about HB). HB says a similar thing post-finale.
== "The other half of my soul"
HB $=>$ ZH
Me wiping away happy tears.
== "When Hao-hyung started playing violin"
HB's answer to one of his BBL lives about what his first impression of ZH was.
== First Conversation
Apparently happened when they were voting for visuals in BP and they revealed that they had voted for each other. This was the event that supposedly broke the ice between them.
If this is true this is really cute...
== "Look forward to a lot of Haobin in the future"
HB comment on the YouTube video of the Tomboy performance - like what else am I supposed to take away from this...?
== "Honestly you came to Tomboy because of me right?"
ZH $=>$ HB. HB shyly says yes.
== BP Finals
During the finale, staff wanted them as first and second to go up separately, but instead they went up the steps to the top 9 together... *HOLDING HANDS*
AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
= Tier 3
#note(
title: "Current Status"
)[
_pant pant pant pant_
Tier 2 was kinda short, hopefully it will pick up soon!
]
|
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/prob/homeworks/main.typ | typst | #import "/utils/template.typ": conf
#import "/utils/datestamp.typ": datestamp
#show: body => conf(
title: "Теория Вероятностей",
subtitle: "Домашние задания",
author: "<NAME>, БПИ233",
year: [2024--2025],
outline_opts: (
depth: 1,
),
body,
)
#datestamp( "2024-09-16")
#include "./to-2024-09-16.typ"
#datestamp( "2024-09-23")
#include "./to-2024-09-23.typ"
#datestamp("2024-09-30")
#include "to-2024-09-30.typ"
#datestamp("2024-10-07")
#include "to-2024-10-07.typ"
#datestamp("2024-10-13")
#include "to-2024-10-13.typ"
|
|
https://github.com/barrel111/readings | https://raw.githubusercontent.com/barrel111/readings/main/notes/external/1910SU/limits.typ | typst | #import "@local/preamble:0.1.0":*
#show: project.with(
course: "1910PREP",
sem: "Summer",
title: "Limits!",
subtitle: "",
authors: ("<NAME>",),
)
= Introduction
We start by giving an (informal) definition of what limits are. While not
mathematically precise, it captures all the intuition needed to understand the
technical definition and suffices for our needs (see Section 2.3 of Thomas's
Calculus for the precise definition).
#definition(
"Limits",
)[We say the _limit of $f(x)$ is $L$ as $x$ approaches $a$_ and write this as $ lim_(x arrow a) f(x) = L $ if
we can get $f(x)$ as close to $L$ as we want for all $x$ sufficiently close to $a$,
from both sides, without actually letting $x$ be $a$.]
Note how the concept of a limit doesn't care about what happens at the point
where the limit is being taken, $a$ (the function can even be undefined at $a$!),
but rather it is all about the behavior around the point $a$.
= Rules for Computing
There are four properties of the limit that often end up being useful for
computations.
*Assuming that the limits $lim_(x arrow a) f(x)$ and $lim_(x arrow
a) g(x)$ both exist*, we have the following facts:
+ *Constant Rule.* #h(5pt) If $c$ is some fixed real number then $lim_(x arrow a)[c f(x)] = c dot [lim_(x arrow a) f(x)]$.
+ *Sum Rule.* #h(5pt) $lim_(x arrow a) [f(x) plus.minus g(x)] = lim_(x arrow a) f(x) plus.minus lim_(x arrow a) g(x).$
+ *Product Rule.* #h(5pt) $lim_(x arrow a) [f(x) g(x)] = [lim_(x to a) f(x)][lim_(x to a) g(x)]$
+ *Quotient Rule.* #h(5pt) If $lim_(x arrow a) g(x) != 0$ then $ lim_(x arrow a) [f(x)/g(x)]= (lim_(x arrow a) f(x))/(lim_(x arrow a)g(x))$
= Continuous Functions
For certain _sufficiently nice_ functions you may have noticed that the limit at
a point is just the value that the function takes at that point. We call
functions having this property _continuous functions_.
#definition(
"Continuity at a point",
)[A function $f(x)$ is _continuous at the point $a$_ if $ lim_(x arrow a)f(x) = f(a). $]
#definition(
"Continuous function",
)[A function $f(x)$ is a _continuous function_ if it is continuous at every point
in its domain.]
For your pleasure and benefit, I present a delightful assortment of continuous
functions!
+ Polynomials (i.e. functions that are just sums of multiples of non-negative powers of $x$).
#example[$x^2$, $3x^5 - x^3 + x^2$, $x^8 + 100, 1.$ (for clarity, the last example is the
constant function $f(x) = 1$)]
+ Roots
#example[$sqrt(x), root(3, x), root(4, x).$]
+ Trigonometric functions.
#example[$sin(x)$, $cos(x)$, $tan(x)$, $csc(x)$, $sec(x)$, $cot(x).$]
+ Exponentials and Logarithms.
#example[$e^x, 2^x, ln(x), log_2(x), log_(10)(x).$]
Furthermore, if $f(x)$ and $g(x)$ are continuous functions, we may conclude that
the following functions are also continuous:
+ $f(x) + g(x), f(x) - g(x).$
+ $f(x)g(x).$
+ $f(g(x)).$
+ $f(x)/g(x)$ if $g(x) != 0$ for any $x$.
= Squeeze Theorem
Sometimes, inequalities can be helpful in computing limits too. The following
result ends up being quite useful.
#theorem(
"Squeeze Theorem",
)[Suppose that for all $x$ on $[b , c]$ (except possibly at $x = a$) we have, $ g(x) <= f(x) <= h(x). $ Also
suppose that $ lim_(x arrow a) g(x) = lim_(x arrow a) h(x) = L $ for some $a$ in $[b, c]$.
Then, $ lim_(x arrow a) f(x) = L. $]
#remark[Recall, $[b, c]$ is the shorthand for the closed interval, ${x bar b <= x <= c}$--
in words, it is the set of all real numbers betweein $b$ an $c$ (including $b$ and $c$).]
The name comes from the fact that, graphically, it appears as though the graphs
of $g$ and $h$, "squeeze" the graph of $f$ at $x = a$ to acquire the same common limit.
#figure(image("graphics/squeeze-theorem.svg", width: 40%), caption: [
Squeeze Theorem.
])
|
|
https://github.com/chilingg/kaiji | https://raw.githubusercontent.com/chilingg/kaiji/main/part1/chapter3.typ | typst | Other | #import "../template/main.typ": main_body, font_size_list, parenthese_numbers, sans_font_cfg, thin_line, font_cfg
#import "@preview/tablex:0.0.6": gridx, tablex, rowspanx, colspanx, hlinex, vlinex, cellx
#show: body => main_body(body)
#columns(2)[
// 613 活字のサイズと字づらの大きさ
= 活字尺寸与字面大小
// 613-1 基準ワクと字づらの関係
== 基准框与字面的关系
// ⑴活字のサイズと文字の正味の大きさ
// ここで活字というのは,写植も含めてのことである。金属活字の場合,その表面は普通正方形である。この一辺を角寸法といい,活字のサイズをあらわしている(単位は号,ポイント,倍など)。正方形でないとき,たとえば新聞の本文用活字の場合は活字表面の天地のほうで大きさをあらわす。
=== ⑴活字尺寸与文字实际大小
此处所说的活字也包含写植在内。金属活字的表面一般是正方形,称这个正方形为字身框,其边长表示活字的尺寸(单位是号、点、倍等)。不是正方形时,例如报纸正文用活字,用字身框的高表示大小。
// 写植では,活字表面に相当するものを仮想ボディといい,級数で示される長さは,この仮想ボディの1辺を意味しているのであって,字そのものの大きさではない。
在写植中,与活字表面相当的东西被称为假想框,级数表示的长度是指这个假想框的边长,而不是字本身的大小。
// 以上活字のサイズの単位,大きさのシステム(シリーズ)については第1巻に述べた。注意すべきことは,活字のサイズと文字のサイズとは别物であって,その関係は次章字づらのところで説明する。しかし,おおまかに言えば活字のサイズはだいたいにおいて文字の大きさをあらわすことにはなろう。
以上关于活字的尺寸单位、大小体系已在第1卷中说明。需要注意的是,活字的尺寸和文字的尺寸是两回事,其关系在下一章关于字面部分进行说明。也可以粗略地认为铅字的尺寸就是文字的大小。
// 文字のサイズを正確に表現するには,
// a.角寸法または仮想ボディをきめ,
// b.次に字づらをきめる。
#set enum(numbering: "a.", indent: 1em)
要准确地表现文字的尺寸,
+ 确定字身框或假想框,
+ 接着决定字面。
// という2段構えにせざるを得ない。それでも大きさの実感を精緻に表現することはむずかしい。
这必须分两个阶段进行。即便如此,也很难阐述真正意义上的大小。
#v(1em)
// ■活字書体を設計するときに使う〔原字用紙〕は,仕上りサイズの10-20倍の大きさである。今でも欧米風にインチ単位が使われることがある。本文用書体(8pt.-l2pt.くらい)のためには1辺2インチを40に分割した方眼紙が使われる。文字の全体の形がはっきり見え,かつ部分を正確に製図するのには,この程度の大きさが最も適切であるということが,長い経験から決められたのであろう。1辺7cm以上になるとかえって全体の姿が取らえにくくなり,書き上げるのにも手間がかかる。
■设计铅字字体时使用的〔原字用纸〕是成品尺寸的10-20倍大小。现在也有欧美风的英寸单位被使用。正文用字体(8pt.\~l2pt.左右),使用边长2英寸等分割40份的方格纸。这是由长期的经验决定的,要想清楚文字的整体形状,并准确地制字形局部,这种大小最为合适。边长超过7cm的话反而很难把握整体的面貌,写起来也很费工夫。
// 原字用紙は正方形でこれは活字表面をあらわす。その中に〔基準ワク〕を設定し,字はその中に書く。活字表面と基準ワクの間にあるスペースは,活字をべタ組にしても字と字が接触しないためにあるもので,普通はそれをばくぜんと〔マージン〕とか〔サイドベアリング〕などと言う。一方のアキをMとすれば,隣の字との字間アキは2M以上となる。縦組横組兼用であるから,上下左右を等しくする。
原字纸是正方形的,表示活字表面。定一个〔基准框〕,字写在里面。活字表面和基准框之间的余白,是为了即使排列成活字组,字与字之间也不会接触而存在的,一般将其称为〔白边、边距〕或〔side bearing〕。如果一个字的边距为M,那么与相邻字的间距为2M以上。由于要纵组横组兼用,所以上下左右相等。
#v(1em)
// 513 角寸法·基準ワク·字づら
#figure(
caption: [字身框·基准框·字面],
image("img/513.jpg")
)
#colbreak()
// 活字製作上の要求からMの最小値は普通0.08mm程度をとる。たとえば仕上りが8ptの字を2インチに製図するとすれば(18倍の大きさ),この最小マージンの幅1.5mmとなる。このとき1/20インチ=1.285mmを1目とすれば約1.2目に相当する。
由于活字制作上的要求,M的最小值通常为0.08mm左右。例如,将8pt的字制图成2英寸(18倍大),那么边距的最小宽度就是1.5mm。如果以1/20英寸=1.285mm为1目,则约等于1.2目。
#v(1em)
// ⑵基準ワクと字づらの関係
// この関係は書体によって大いに違う。楷書体などでは画数の多い字と少ない字では,字づらの大きさが大いにちがう。最大の字高あるいは字幅を基準ワクの1辺に選べば,ほとんどの漢字はそれよりも小さいから,基準ワクに接触しないことになる。明朝体・ゴシック体などでは,たとえ画数の少ない字でも最長線(616-2)は基準ワクに接触させる部分が多い。このような書体では,活字を組んだ場合基準ワクの1辺は横組縦組とも一種のラインになることを注意しておく。
=== ⑵基准框与字面的关系
这种关系因字体不同而大相径庭。例如,楷书中笔画多的字和笔画少的字,字面大小差异很大。如果选择最大的字高或字宽作为基准框的边长,大多数汉字都比它小,因此不会接触到基准框。在明朝体、黑体等字体中,即使笔画少的字,最长线(616-2)也有很大一部分与基准框接触。注意,这种字体在排版时,基准框的边与横排竖排基线是一样的。
// 今までの数値関係をはっきりさせよう。
// S=活字表面の1辺(角寸法) l=S-2M
// M=マージンの一方の幅 字高=H≤l
// l=基準ワクの1辺 字幅=W≤I
// いずれもS=100としたときの%で表わす。
明确到目前为止的数值之间的关系。
#align(center)[
#block(width: 85%)[
#set align(start)
#gridx(
columns: 2,
[S=活字表面边长(字身框)],[l=S-2M],
[M=边距长度],[字高=H≤l],
[l=基准框边长],[字宽=W≤I],
colspanx(2)[都用S=100%时的%表示。],(),
)
]
]
// 下図の左は基準ワクに触れる部分を示した。同じ書体でも〔口・目〕などは小さくなる。この図ではやや誇張してある。
下图左侧表示接触基准框的部分。同样的字体中,〔口・目〕等字会稍小一些。此图略微有些夸张了。
#v(1em)
// ■現行の活字書体について2インチに書かれた原図によって,実際の文字の大きさと角寸法の関係がどういうものであるかを研究してみよう。本文用明朝体と正楷書体を例にとると図514表514のようになる。代表的な49字をとって,上下左右のもっとも突出した部分をチェックし,その分布する範囲にスクリーンをかけてみた。平均の字づらはスクリーンの帯の外側と内側の中間にある。一見してわかることは,
■根据现行活字字体2英寸的原图,试着研究一下实际文字的大小和字身框的关系是怎样的。以正文用明朝体和正楷书体为例,如图514表514所示。选取有代表性的49个字,检查上下左右最突出的部分,在其分布的范围挂上网线。平均字面大小位于网线带的外侧和内侧之间。一看就知道,
// (1)字づらの形が漢字・ひらがな・カタカナによって違う。
// (2)どの書体についても,字づらの大きさは漢字・ひらがな・カタカナの順である。
// (3)漢字は字づらがもっとも大きく正方形に近い。
// (4)楷書体の字づらは明朝体にくらべてかなり小さい。
// (5)楷書で右下に右ハライの先端がのびていて,角寸法いっぱいになっている。
#set enum(numbering: n => [#parenthese_numbers.at(n - 1)])
+ 字面形状因汉字、平假名、片假名的不同而不同。
+ 无论哪种字体,字面从大到小依次为汉字、平假名、片假名。
+ 汉字的字面最大,最接近正方形。
+ 楷书的字面比明朝体小很多。
+ 楷书的右下撇画伸展,抵到字身框。
// これら2書体について基準ワクはスクリーンの帯の外側に外接した矩形になる。
对于这两种字体来说,字身框是网线带外围的一个矩形。
#v(2em)
#align(right)[
#block(width: 80%)[
#set align(start)
#set text(size: font_size_list.at(3))
// 基準線(またはライン)と引込み線は横組の上下。縦線の左右にある。これらを合せると正方形に近いワクとなる。基準ワク及び引込みワクと言おう。明朝体設計の基本ワク組である(p.70,108参照)。
基准线(基线)和参考线是横组的上下。纵线则在左右。这些合起来就是接近正方形的框,即基准框和参考框。这是明朝体设计的基本框架(参照track_page)。
// p.15図517を参照
#image("img/513-1.jpg", width: 60%)
参见track_page图517
]
]
]
#pagebreak()
#columns(2)[
== 字面率
// ■字づらは活字の凸部で,インクの付く部分を言ったのだが,印字された字の広がりや姿をも意味する。はっきりと面積だけを指す場合は,〔字づら面積〕と言ったほうがよい。
■字面即是活字的沾有墨水的凸面部分,也指印字的形状。如果明确指向面积,最好说〔字面面积〕比较好。
// 1個の字についで〔字づら〕とはどこをさすのか。⑴もっとも実感に近いものは,図514でスクリーンをかけた部分,つまり各々の突出部を結んだ輪郭の内側をさすことであろう。これはプラニメーターを使えば,だいたいの面積を测定できるが,不便である。⑵しかしもう一つの考え方は字高(H,上下最大幅)と字幅(W,左右最大幅)をはかり,角寸法に対する%であらわし,この両方の〔積〕で字づらを表現することである。つまりH×Wという外接矩形の面積を想定していることになる。これを〔字面率〕と言おう。
一个字的〔字面〕具体指的是什么?⑴最接近实际感受的,应该是图514中画有网线的部分,也就是连接各突出部分的轮廓内侧。用测试器可以测出大概的面积,但不方便。⑵另一种想法是测量字高(H,上下最大长度)和字宽(W,左右最大长度),以它们相对于字身框的%表示,用两者的〔积〕来表示字面。也就是说,H×W的外接矩形的面积与字身框面积之比。这叫作〔字面率〕。
#set list(marker: "●", indent: 1em)
// ⑶〔1書体の字面率〕を一つの数値で表わすことは,選ぶ字により字数によってちがうので,やっかいな問題である。
// - 特に字づらの小さい字(p.26表529),大きい字はさける。
// - 使用頻度の多いm=4,n=3に近い字(p.124図570)
⑶〔字体的字面率〕用一个数值来表示是个棘手的问题,它会因其所选的字、字数不同而产生较大差异。
- 避免使用小字面(track_page表529),尤其是在复杂的字中。
- 使用频率高的,接近m=4, n=3的字(track_page图570)。
// p.27図528のスクリーンゾーンに入るような字をえらぶ(p.84表552を参照)。選んだ字がほぼ妥当であるとき,字数によってどれほど,その〔平均字面率〕がちがってくるかの研究がある。与えられた資料,限られた字しかない場合は,その特定の字について,他の書体と比較するほかはない。
track_page图528 选择位于网线区域的字符(参见p.84表552)。当所选的字大致妥当时,根据字数的不同,研究其(平均字面率)有多大不同。若给定的资料只有有限的字,那么只能和其他字体比较。
// 字づら(場所)
// 形
// 大きさ
// 実感上の大きさ
// 数量化された面積
// 輪廓面積
// 左ぺージ
#v(1em)
#image("img/514-3.svg")
// 字づら面積の定義
// 字面率(面積%)
// 辺長%
// ⑴突出部を結んだ輪郭の内側面積
// ⑵字高H,字幅Wのとき〔H×W〕の矩形
// ⑶H-(平均的H),W-(平均的W)的とき,〔H-×W-〕の矩形
// ⑷基準ワクを一辺(l)とする正方形(l²)
// 角寸法に対とする%
// 一字について
// 一書体について
#text(tracking: 0em)[
#tablex(
columns: (1.5em,1.5em,auto,auto,6em),
auto-lines: false,
inset: 0.4em,
map-cells: cell => {
if cell.x != 2 {
cell.align = center + horizon
} else {
cell.align = horizon
cell.content = text(size: font_size_list.at(3), cell.content)
}
return cell
},
(),vlinex(),(),vlinex(),vlinex(),(),
hlinex(),
[],colspanx(2)[字面面积的定义],(),[字面率#text(size: font_size_list.at(3))[(面积%)]],[边长%],
hlinex(),
rowspanx(2)[字],[⑴],[连接突出部的轮廓的内侧面积],[
与字身框\
相对的%
],[],
(),[⑵],[字高H×字宽W的矩形面积],[同上],[H%、W%],
hlinex(),
rowspanx(2)[
字\
体
],[⑶],[#overline[H] (平均的H)×#overline[W] (平均的W)的矩形面积],[同上],[H%、W%],
(),[⑷],[以基准框为边长(l)的正方形(l²)面积],[同上],[l%],
hlinex(),
)]
#v(1em)
#text(tracking: 0em)[
// 角寸法·基準ワク·字づら
字身框·基准框·字面 <sans_font>
]
#text(tracking: -0.08em)[
#tablex(
columns: 7,
align: center+horizon,
rowspanx(2)[单位%],colspanx(3)[明朝体],(),(),colspanx(3)[正楷字体],(),(),
(),[汉字],[平假名],[片假名],[汉字],[平假名],[片假名],
[外],[80.6],[67.2],[60.0],[75.3],[48.5],[46.2],
[内],[63.4],[38.5],[34.6],[35.8],[23.1],[20.0],
[平均],[72.0],[52.9],[47.3],[55.5],[35.8],[33.1],
[基准框],[92],[90],[88],[96],[72],[72],
text(size: font_size_list.at(1))[\* <sans_font>],[100],[73.4],[65.6],[100],[64.5],[59.6],
)
]
// *漢字を100としたときの比較值
\*<sans_font> 汉字为100时的比较值
#colbreak()
#figure(
caption: [明朝体(左)·正楷字体(右)],
image("img/514-1.jpg")
)
#v(1em)
#text(tracking: 0em)[
同上明朝体(左)·正楷字体的字面 <sans_font>
// 上から漢字·ひらがな·カタカナ
#text(size: font_size_list.at(3))[从上起:汉字·平假名·片假名]
]
#image("img/514-2.jpg")
] |
https://github.com/Quaternijkon/notebook | https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-数据结构/字符串/轮转字符串.typ | typst | #import "../../../../lib.typ":*
=== #Title(
title: [轮转字符串],
reflink: "https://leetcode.cn/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/description/",
level: 2,
)<轮转字符串>
#note(
title: [
动态口令
],
description: [
某公司门禁密码使用动态口令技术。初始密码为字符串 password,密码更新均遵循以下步骤:
- 设定一个正整数目标值 target
- 将 password 前 target 个字符按原顺序移动至字符串末尾
请返回更新后的密码字符串。
],
examples: ([
输入: password = "<PASSWORD>", target = 4
输出: "<PASSWORD>"
],[
输入: password = "<PASSWORD>", target = 6
输出: "<PASSWORD>"
]
),
tips: [
$1 <= "target" < "password.length" <= 10000$
],
solutions: (
( name:[富有线性代数的美],
text:[
我们需要将 ab 变成 ba ,可以首先将ab翻转得到$b^(-1)a^(-1)$,然后将$b^(-1)a^(-1)$翻转得到ba。
- $("ab")^(-1) = b^(-1)a^(-1)$
- $(b^(-1))^(-1) = b$
- $(a^(-1))^(-1) = a$
],code:[
```cpp
class Solution {
public:
string dynamicPassword(string password, int target) {
reverse(password.begin(),password.end());
reverse(password.end()-target,password.end());
reverse(password.begin(),password.end()-target);
return password;
}
};
```
]),
),
gain:none,
)
|
|
https://github.com/abenson/report | https://raw.githubusercontent.com/abenson/report/master/report.typ | typst | // A paper or report with classification banners.
// SPDX-License Identifier: Unlicense
//Pick a color based on the classification string
#let colorForClassification(
classification,
sci,
disableColor: false
) = {
let classcolor = black
if disableColor == false and classification != none {
if sci {
classcolor = rgb("#ffcc00") // Yellow for any SCI (CLASS//SC,I//ETC)
} else if regex("CUI|CONTROLLED") in classification {
classcolor = rgb("#502b85") // Purple for C(ontrolled) U(Unclass) I(nfo)
} else if regex("UNCLASSIFIED") in classification {
classcolor = rgb("#007a33") // Green for UNCLASSIFIED[//FOUO]
} else if regex("CLASSIFIED") in classification {
classcolor = rgb("#c1a7e2") // Indetermined classified data, ca.1988
} else if regex("CONFIDENTIAL") in classification {
classcolor = rgb("#0033a0") // Blue for CONFIDENTIAL
} else if regex("TOP SECRET") in classification {
classcolor = rgb("#ff8c00") // Orange for Collateral TS
} else if regex("SECRET") in classification {
classcolor = rgb("#c8102e") // Red for SECRET
} // else, black because we don't know
}
classcolor
}
#let classificationWithColor(
classification,
sci: false
) = {
let realclass = classification
if regex("TS") in classification {
realclass = "TOP SECRET"
} else if regex("\bS") in classification {
realclass = "SECRET"
} else if regex("\bU\b") in classification {
realclass = "UNCLASSIFIED"
} else if regex("\bC\b") in classification {
realclass = "CONFIDENTIAL"
}
text(
weight: "bold",
fill: colorForClassification(realclass, sci),
classification
)
}
// Draw CUI and DCA Blocks (sorry, OCAs)
#let drawClassificationBlocks(
// Fields for DCA Block
// Required fields:
// - by: Person who conducted marking review
// Optional Fields:
// - source: Name of SCG used; if multiple, leave blank and
// include at the end of the document.
// - downgradeto: If the document will be downgraded, what class?
// - downgradeon: The date downgrade on which the downgrade can happen
// - until: Document will be declassified on this date, i.e. $date+25y, $date+75y
classified,
// Fields for CUI Block
// Required Fields:
// - controlledby: Array of controllers, ("Division 2", "Office 3")
// - categories: Categories ("OPSEC, PRVCY")
// - dissemination: Approved dissemination list ("FEDCON")
// - poc: POC Name/Contact ("Mr. <NAME>, (555) 867-5309")
cui
) = {
let dcablock = []
let cuiblock = []
if classified != none and regex("SECRET|CONFIDENTIAL|\bCLASSIFIED") in classified.overall {
dcablock = [
#set align(left)
*Classified By:* #classified.at("by", default: "MISSING!") \
*Derived From:* #classified.at("source", default: "Multiple Sources") \
#if classified.at("downgradeto", default: []) != [] {
[*Downgrade To:* #classified.downgradeto \ ]
}
#if classified.at("downgradeon", default: []) != [] {
[*Downgrade On:* #classified.downgradeon \ ]
}
#if classified.at("until", default: []) != []{
[*Declassify On:* #classified.until \ ]
}
]
dcablock = rect(dcablock)
}
if cui != none {
cuiblock = rect[
#set align(left)
*Controlled By:* #cui.at("controlledby", default: ("MISSING!",)).join(strong("\nControlled By: "))\
*Categories:* #cui.at("categories", default: "MISSING!") \
*Dissemination:* #cui.at("dissemination", default: "MISSING!") \
*POC:* #cui.at("poc", default: "MISSING!")
]
}
place(bottom, float: true,
grid( columns: ( 1fr, 1fr ),
dcablock,
align(right,cuiblock)
)
)
}
// Show the bibliography, if one is attached.
#let showBibliography(
// Print a bilbiography if given one.
// This behavior is necessary due to the way typst handles paths.
// This will likely be updated to use the new path object when added. Issue #971
biblio,
title_page: false,
) = {
if biblio != none {
if title_page {
pagebreak()
}
show bibliography: set text(1em)
show bibliography: set par(first-line-indent: 0em)
biblio
}
}
// Draw the titles on the page. Only used in report?
#let showTitles(
// Introduction for the title, i.e. "Trip Report \ for"
title_intro: none,
// The actual title: "Operation Drunken Gambler"
title: none,
// A subtitle, if needed: "... or, How I Spent My Summer Vacation"
subtitle: none,
// A version string if the document may have multiple versions
version: none,
// The author of the document
authors: (),
// A publication date
date: none
) = {
if title_intro != none {
align(center, text(14pt, title_intro))
}
if title != none {
align(center, text(25pt, title))
}
if subtitle != none {
align(center, text(17pt, subtitle))
}
if version != none {
align(center, text(version))
}
if authors != () {
align(center, authors.join(", "))
}
if date != none {
align(center, date)
}
}
// A full report format.
#let report(
title_intro: none,
title: none,
subtitle: none,
authors: (),
date: none,
classified: none,
cui: none,
version: none,
logo: none,
border: true,
title_page: false,
bib: none,
paper: "us-letter",
front: none,
keywords: (),
body
) = {
set document(
title: title,
author: authors,
keywords: keywords,
)
set par(justify: true)
set text(size: 12pt)
show link: underline
set heading(numbering: "1.1.1. ")
show heading: set text(12pt, weight: "bold")
let classification = none
// Set the classification for the document.
// If there is no classification, but a CUI block exists, then the document is CUI.
// There should be no CUI without a CUI block, but if the document is UNCLASSIFIED,
// then it should be set in `classified.overall`.
if classified != none {
classification = classified.overall
} else if cui != none {
classification = "CUI"
}
let sci = false
if classified != none {
if ("sci" in classified) {
sci = classified.sci
}
}
let classcolor = colorForClassification(classification, sci)
if classified != none and classified.at("color", default: none) != none {
classcolor = classified.color
}
if title_page {
set page(footer: none, header: none)
if border == true or type(border) == color {
let border_color = classcolor
if type(border) == color {
border_color = border
}
if border_color == color.black {
border = rect(
width: 100%-1in,
height: 100%-1in,
stroke: 6pt+border_color
)
} else {
border = rect(
width: 100%-1in,
height: 100%-1in,
stroke: 0.5in+border_color
)
}
} else {
border = none
}
set page(paper: paper, background: border)
set align(horizon)
showTitles(
title_intro: title_intro,
title: title,
subtitle: subtitle,
version: version,
authors: authors,
date: date)
// 3in provides a decent logo or a decent size gap
if logo != none {
align(center, logo)
} else {
rect(height: 3in, stroke: none)
}
if classification != none {
align(center, text(fill: classcolor, size: 17pt, strong(classification)))
}
drawClassificationBlocks(classified, cui)
}
let header = align(center, text(fill: classcolor, strong(classification)))
if title_page {
// The outline and other "front matter" pages should use Roman numerals.
let footer = grid(columns: (1fr,auto,1fr),
[],
align(center, text(fill: classcolor, strong(classification))),
align(right, context { counter(page).display("i") })
)
page(paper,
footer: none,
header: none,
background: none,
align(center+horizon,"This page intentionally left blank.")
)
set page(
paper: paper,
header: header,
footer: footer,
background: none
)
set align(top)
counter(page).update(1)
front
outline()
pagebreak(weak: true, to:"odd")
}
// Body pages should be numbered with standard Arabic numerals.
let footer = grid(columns: (1fr,auto,1fr),
[],
align(center, text(fill: classcolor, strong(classification))),
align(right, context { counter(page).display("1") })
)
set page(
paper: paper,
header: header,
footer: footer
)
counter(page).update(1)
if not title_page {
showTitles(
title_intro: title_intro,
title: title,
subtitle: subtitle,
version: version,
authors: authors,
date: date)
drawClassificationBlocks(classified, cui)
}
body
showBibliography(bib, title_page: title_page)
}
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/096.%20fundraising.html.typ | typst | fundraising.html
A Fundraising Survival Guide
Want to start a startup? Get funded by
Y Combinator.
August 2008Raising money is the second hardest part of starting a startup.
The hardest part is making something people want: most startups
that die, die because they didn't do that. But the second biggest
cause of death is probably the difficulty of raising money.
Fundraising is brutal.One reason it's so brutal is simply the brutality of markets. People
who've spent most of their lives in schools or big companies may
not have been exposed to that. Professors and bosses usually feel
some sense of responsibility toward you; if you make a valiant
effort and fail, they'll cut you a break. Markets are less forgiving.
Customers don't care how hard you worked, only whether you solved
their problems.Investors evaluate startups the way customers evaluate products,
not the way bosses evaluate employees. If you're making a valiant
effort and failing, maybe they'll invest in your next startup, but
not this one.But raising money from investors is harder than selling to
customers, because there are so few of them. There's
nothing like an efficient market. You're unlikely to have more
than 10 who are interested; it's difficult to talk to more. So the
randomness of any one investor's behavior can really affect you.Problem number 3: investors are very random. All investors, including
us, are by ordinary standards incompetent. We constantly have to
make decisions about things we don't understand, and more often
than not we're wrong.And yet a lot is at stake. The amounts invested by different types
of investors vary from five thousand dollars to fifty million, but
the amount usually seems large for whatever type of investor it is.
Investment decisions are big decisions.That combination—making big decisions about things they don't
understand—tends to make investors very skittish. VCs are notorious
for leading founders on. Some of the more unscrupulous do it
deliberately. But even the most well-intentioned investors can
behave in a way that would seem crazy in everyday life. One day
they're full of enthusiasm and seem ready to write you a check on
the spot; the next they won't return your phone calls. They're not
playing games with you. They just can't make up their minds.
[1]If that weren't bad enough, these wildly fluctuating nodes are all
linked together. Startup investors all know one another, and (though
they hate to admit it) the biggest factor in their opinion of you
is the opinion of other investors.
[2]
Talk about a recipe for
an unstable system. You get the opposite of the damping that the
fear/greed balance usually produces in markets. No one is interested
in a startup that's a "bargain" because everyone else hates it.So the inefficient market you get because there are so few players
is exacerbated by the fact that they act less than independently.
The result is a system like some kind of primitive, multi-celled
sea creature, where you irritate one extremity and the whole thing
contracts violently.Y Combinator is working to fix this. We're trying to increase the
number of investors just as we're increasing the number of startups.
We hope that as the number of both increases we'll get something
more like an efficient market. As t approaches infinity, Demo Day
approaches an auction.Unfortunately, t is still very far from infinity. What does a
startup do now, in the imperfect world we currently inhabit? The
most important thing is not to let fundraising get you down. Startups
live or die on morale. If you let the difficulty of raising money
destroy your morale, it will become a self-fulfilling prophecy.
Bootstrapping (= Consulting)Some would-be founders may by now be thinking, why deal with investors
at all? If raising money is so painful, why do it?One answer to that is obvious: because you need money to live on.
It's a fine idea in principle to finance your startup with its own
revenues, but you can't create instant customers. Whatever you
make, you have to sell a certain amount to break even. It will
take time to grow your sales to that point, and it's hard to predict,
till you try, how long it will take.We could not have bootstrapped Viaweb, for example. We charged
quite a lot for our software—about $140 per user per month—but
it was at least a year before our revenues would have covered even
our paltry costs. We didn't have enough saved to live on for a
year.If you factor out the "bootstrapped" companies that were actually
funded by their founders through savings or a day job, the remainder
either (a) got really lucky, which is hard to do on demand, or (b)
began life as consulting companies and gradually transformed
themselves into product companies.Consulting is the only option you can count on. But consulting is
far from free money. It's not as painful as raising money from
investors, perhaps, but the pain is spread over a longer period.
Years, probably. And for many types of startup, that delay could
be fatal. If you're working on something so unusual that no one
else is likely to think of it, you can take your time. <NAME> gradually built Delicious on the side while working on
Wall Street. He got away with it because no one else realized it
was a good idea. But if you were building something as obviously
necessary as online store software at about the same time as Viaweb,
and you were working on it on the side while spending most of your
time on client work, you were not in a good position.Bootstrapping sounds great in principle, but this apparently verdant
territory is one from which few startups emerge alive. The mere
fact that bootstrapped startups tend to be famous on that account
should set off alarm bells. If it worked so well, it would be the
norm.
[3]
Bootstrapping may get easier, because starting a company is getting
cheaper. But I don't think we'll ever reach the point where most
startups can do without outside funding. Technology tends to
get dramatically cheaper, but living expenses don't.The upshot is, you can choose your pain: either the short, sharp
pain of raising money, or the chronic ache of consulting. For a
given total amount of pain, raising money is the better choice,
because new technology is usually more valuable now than later.But although for most startups raising money will be the lesser
evil, it's still a pretty big evil—so big that it can easily kill
you. Not merely in the obvious sense that if you fail to raise
money you might have to shut the company down, but because the
process of raising money itself can kill you.To survive it you need a set of techniques mostly
orthogonal to the ones used in convincing investors, just as mountain
climbers need to know survival techniques that are mostly orthogonal
to those used in physically getting up and down mountains.
1. Have low expectations.The reason raising money destroys so many startups' morale is not
simply that it's hard, but that it's so much harder than they
expected. What kills you is the disappointment. And the lower
your expectations, the harder it is to be disappointed.Startup founders tend to be optimistic. This can work well in
technology, at least some of the time, but it's the wrong way to
approach raising money. Better to assume investors will always let
you down. Acquirers too, while we're at it. At YC one of our
secondary mantras is "Deals fall through." No matter what deal
you have going on, assume it will fall through. The predictive
power of this simple rule is amazing.There will be a tendency, as a deal progresses, to start to believe
it will happen, and then to depend on it happening. You must resist
this. Tie yourself to the mast. This is what kills you. Deals
do not have a trajectory like most other human interactions, where
shared plans solidify linearly over time. Deals often fall through
at the last moment. Often the other party doesn't really think
about what they want till the last moment. So you can't use your
everyday intuitions about shared plans as a guide. When it comes
to deals, you have to consciously turn them off and become
pathologically cynical.This is harder to do than it sounds. It's very flattering when
eminent investors seem interested in funding you. It's easy to
start to believe that raising money will be quick and straightforward.
But it hardly ever is.
2. Keep working on your startup.It sounds obvious to say that you should keep working on your startup
while raising money. Actually this is hard to do. Most startups
don't manage to.Raising money has a mysterious capacity to suck up all your attention.
Even if you only have one meeting a day with investors, somehow
that one meeting will burn up your whole day. It costs not just
the time of the actual meeting, but the time getting there and back,
and the time preparing for it beforehand and thinking about it
afterward.The best way to survive the distraction of meeting with investors
is probably to partition the company: to pick one founder to deal
with investors while the others keep the company going. This works
better when a startup has 3 founders than 2, and better when the
leader of the company is not also the lead developer. In the best
case, the company keeps moving forward at about half speed.That's the best case, though. More often than not the company comes
to a standstill while raising money. And that is dangerous for so
many reasons. Raising money always takes longer than you expect.
What seems like it's going to be a 2 week interruption turns into
a 4 month interruption. That can be very demoralizing. And worse
still, it can make you less attractive to investors. They want to
invest in companies that are dynamic. A company that hasn't done
anything new in 4 months doesn't seem dynamic, so they start to
lose interest. Investors rarely grasp this, but much of what
they're responding to when they lose interest in a startup is the
damage done by their own indecision.The solution: put the startup first. Fit meetings with investors
into the spare moments in your development schedule, rather than
doing development in the spare moments between meetings with
investors. If you keep the company moving forward—releasing new
features, increasing traffic, doing deals, getting written
about—those investor meetings are more likely to be productive. Not just
because your startup will seem more alive, but also because it will
be better for your own morale, which is one of the main ways investors
judge you.
3. Be conservative.As conditions get worse, the optimal strategy becomes more conservative.
When things go well you can take risks; when things are bad you
want to play it safe.I advise approaching fundraising as if it were always going badly.
The reason is that between your ability to delude yourself and the
wildly unstable nature of the system you're dealing with, things
probably either already are or could easily become much worse than
they seem.What I tell most startups we fund is that if someone reputable
offers you funding on reasonable terms, take it. There have been
startups that ignored this advice and got away with it—startups
that ignored a good offer in the hope of getting a better one, and
actually did. But in the same position I'd give the same advice
again. Who knows how many bullets were in the gun they were playing
Russian roulette with?Corollary: if an investor seems interested, don't just let them
sit. You can't assume someone interested in investing will stay
interested. In fact, you can't even tell (they can't even tell)
if they're really interested till you try to convert that interest
into money. So if you have hot prospect, either close them now or
write them off. And unless you already have enough funding, that
reduces to: close them now.Startups don't win by getting great funding rounds, but by making
great products. So finish raising money and get
back to work.
4. Be flexible.There are two questions VCs ask that you shouldn't answer: "Who
else are you talking to?" and "How much are you trying to raise?"VCs don't expect you to answer the first question. They ask it just
in case.
[4]
They do seem to expect an answer to the second. But
I don't think you should just tell them a number. Not as a way to
play games with them, but because you shouldn't have a fixed
amount you need to raise.The custom of a startup needing a fixed amount of funding is an
obsolete one left over from the days when startups were more
expensive. A company that needed to build a factory or hire 50
people obviously needed to raise a certain minimum amount. But few
technology startups are in that position today.We advise startups to tell investors there are several different
routes they could take depending on how much they raised. As little
as $50k could pay for food and rent for the founders for a year.
A couple hundred thousand would let them get office space and hire
some smart people they know from school. A couple million would
let them really blow this thing out. The message (and not just the
message, but the fact) should be: we're going to succeed no matter
what. Raising more money just lets us do it faster.If you're raising an angel round, the size of the round can even
change on the fly. In fact, it's just as well to make the round
small initially, then expand as needed, rather than trying to raise
a large round and risk losing the investors you already have if you
can't raise the full amount. You may even want to do a "rolling
close," where the round has no predetermined size, but instead you
sell stock to investors one at a time as they say yes. That helps
break deadlocks, because you can start as soon as the first one
is ready to buy.
[5]
5. Be independent.A startup with a couple founders in their early twenties can have
expenses so low that they could be profitable on
as little as $2000 per month. That's negligible as corporate
revenues go, but the effect on your morale and your bargaining
position is anything but. At YC we use the phrase "ramen profitable"
to describe the situation where you're making just enough to pay
your living expenses. Once you cross into ramen profitable,
everything changes. You may still need investment to make it big,
but you don't need it this month.You can't plan when you start a startup how long
it will take to become profitable. But if you find yourself in a
position where a little more effort expended on sales would carry
you over the threshold of ramen profitable, do it.Investors like it when you're ramen profitable. It shows you've
thought about making money, instead of just working on amusing
technical problems; it shows you have the discipline to keep your
expenses low; but above all, it means you don't need them.There is nothing investors like more than a startup that seems like
it's going to succeed even without them. Investors like it when
they can help a startup, but they don't like startups that would
die without that help.At YC we spend a lot of time trying to predict how the startups we've
funded will do, because we're trying to learn how to pick winners.
We've now watched the trajectories of so many startups that we're
getting better at predicting them. And when we're talking
about startups we think are likely to succeed, what we find ourselves
saying is things like "Oh, those guys can take care of themselves.
They'll be fine." Not "those guys are really smart" or
"those guys are working on a great idea."
[6]
When we predict good outcomes for startups, the qualities
that come up in the supporting arguments are toughness, adaptability,
determination. Which means to the extent we're correct, those are
the qualities you need to win.Investors know this, at least unconsciously. The reason they like
it when you don't need them is not simply that they like what they
can't have, but because that quality is what makes founders succeed.<NAME>
has it. You could parachute him into an island full of
cannibals and come back in 5 years and he'd be the king. If you're
<NAME>, you don't have to be profitable to convey to investors
that you'll succeed with or without them. (He wasn't, and he did.)
Not everyone has Sam's deal-making ability. I myself don't. But
if you don't, you can let the numbers speak for you.
6. Don't take rejection personally.Getting rejected by investors can make you start to doubt yourself.
After all, they're more experienced than you. If they think your
startup is lame, aren't they probably right?Maybe, maybe not. The way to handle rejection is with precision.
You shouldn't simply ignore rejection. It might mean something.
But you shouldn't automatically get demoralized either.To understand what rejection means, you have to understand first
of all how common it is. Statistically, the average VC is a rejection
machine. <NAME>, a partner at August, told me:
The numbers for me ended up being something like 500 to 800 plans
received and read, somewhere between 50 and 100 initial 1 hour
meetings held, about 20 companies that I got interested in, about
5 that I got serious about and did a bunch of work, 1 to 2 deals
done in a year. So the odds are against you. You
may be a great entrepreneur, working on interesting stuff, etc.
but it is still incredibly unlikely that you get funded.
This is less true with angels, but VCs reject practically everyone.
The structure of their business means a partner does at most 2 new
investments a year, no matter how many good startups approach him.In addition to the odds being terrible, the average investor is,
as I mentioned, a pretty bad judge of startups. It's harder to
judge startups than most other things, because great startup ideas
tend to seem wrong. A good startup idea has to be not just good but
novel. And to be both good and novel, an idea probably has to seem
bad to most people, or someone would already be doing it and it
wouldn't be novel.That makes judging startups harder than most other things one judges.
You have to be an intellectual contrarian to be a good startup
investor. That's a problem for VCs, most of whom are not particularly
imaginative. VCs are mostly money guys, not people who make things.
[7]
Angels are better at appreciating novel ideas, because most
were founders themselves.So when you get a rejection, use the data that's in it, and not what's
not. If an investor gives you specific reasons for not investing,
look at your startup and ask if they're right. If they're real
problems, fix them. But don't just take their word for it. You're
supposed to be the domain expert; you have to decide.Though a rejection doesn't necessarily tell you anything about your
startup, it does suggest your pitch could be improved. Figure out
what's not working and change it. Don't just think "investors are
stupid." Often they are, but figure out precisely where you lose
them.Don't let rejections pile up as a depressing, undifferentiated heap.
Sort them and analyze them, and then instead of thinking "no one
likes us," you'll know precisely how big a problem you have, and
what to do about it.
7. Be able to downshift into consulting (if appropriate).Consulting, as I mentioned, is a dangerous way to finance a startup.
But it's better than dying. It's a bit like anaerobic respiration:
not the optimum solution for the long term, but it can save you
from an immediate threat. If you're having trouble raising money
from investors at all, it could save you to be able to shift
toward consulting.This works better for some startups than others. It wouldn't have
been a natural fit for, say, Google, but if your company was making
software for building web sites, you could degrade fairly gracefully
into consulting by building sites for clients with it.So long as you were careful not to get sucked permanently into
consulting, this could even have advantages. You'd understand your
users well if you were using the software for them. Plus as a
consulting company you might be able to get big-name users using
your software that you wouldn't have gotten as a product company.At Viaweb we were forced to operate like a consulting company
initially, because we were so desperate for users that we'd offer
to build merchants' sites for them if they'd sign up.
But we never charged for such work, because we didn't want them to
start treating us like actual consultants, and calling us every
time they wanted something changed on their site. We knew we had
to stay a product company, because only
that scales.
8. Avoid inexperienced investors.Though novice investors seem unthreatening they can be the most
dangerous sort, because they're so nervous. Especially in
proportion to the amount they invest. Raising $20,000 from a first-time
angel investor can be as much work as raising $2 million from
a VC fund.Their lawyers are generally inexperienced too. But while the
investors can admit they don't know what they're doing, their lawyers
can't. One YC startup negotiated terms for a tiny round with
an angel, only to receive a 70-page agreement from his lawyer. And
since the lawyer could never admit, in front of his client, that
he'd screwed up, he instead had to insist on retaining all the
draconian terms in it, so the deal fell through.Of course, someone has to take money from novice investors, or there
would never be any experienced ones. But if you do, either (a)
drive the process yourself, including supplying the
paperwork, or
(b) use them only to fill up a larger round led by someone else.
9. Know where you stand.The most dangerous thing about investors is their indecisiveness.
The worst case scenario is the long no, the no that comes after
months of meetings. Rejections from investors are like design
flaws: inevitable, but much less costly if you discover them early.So while you're talking to investors, constantly look for signs of
where you stand. How likely are they to offer you a term sheet?
What do they have to be convinced of first? You shouldn't necessarily
always be asking these questions outright—that could get
annoying—but you should always be collecting data about them.Investors tend to resist committing except to the extent you push
them to. It's in their interest to collect the maximum amount of
information while making the minimum number of decisions. The best
way to force them to act is, of course, competing investors. But
you can also apply some force by focusing the discussion:
by asking what specific questions they need answered to make
up their minds, and then answering them. If you get through several
obstacles and they keep raising new ones, assume that ultimately
they're going to flake.You have to be disciplined when collecting data about investors'
intentions. Otherwise their desire to lead you on will combine
with your own desire to be led on to produce completely inaccurate
impressions.Use the data to weight your strategy.
You'll probably be talking to several investors. Focus on the ones
that are most likely to say yes. The value of a potential investor
is a combination of how good it would be if they said yes, and how
likely they are to say it. Put the most weight on the second factor.
Partly because the most important quality in an investor is simply
investing. But also because, as I mentioned, the biggest factor
in investors' opinion of you is other investors' opinion of you.
If you're talking to several investors and you manage to get one
over the threshold of saying yes, it will make the others much more
interested. So you're not sacrificing the lukewarm investors if
you focus on the hot ones; convincing the hot investors is the best
way to convince the lukewarm ones.
FutureI'm hopeful things won't always be so awkward. I hope that as startups
get cheaper and the number of investors increases, raising money
will become, if not easy, at least straightforward.In the meantime, the brokenness of the funding process offers a big
opportunity. Most investors have no idea how dangerous they are.
They'd be surprised to hear that raising money from them is something
that has to be treated as a threat to a company's survival. They
just think they need a little more information to make up their
minds. They don't get that there are 10 other investors who also
want a little more information, and that the process of talking to
them all can bring a startup to a standstill for months.Because investors don't understand the cost of dealing with them,
they don't realize how much room there is for a potential competitor
to undercut them. I know from my own experience how much faster
investors could decide, because we've brought our own time down to
20 minutes (5 minutes of reading an application plus a 10 minute
interview plus 5 minutes of discussion). If you were investing
more money you'd want to take longer, of course. But if we can
decide in 20 minutes, should it take anyone longer than a couple
days?Opportunities like this don't sit unexploited forever, even in an
industry as conservative as venture capital. So
either existing investors will start to make up their minds faster,
or new investors will emerge who do.In the meantime founders have to treat raising money as a dangerous
process. Fortunately, I can fix the biggest danger right here.
The biggest danger is surprise. It's that startups will underestimate
the difficulty of raising money—that they'll cruise through all
the initial steps, but when they turn to raising money they'll find
it surprisingly hard, get demoralized, and give up. So I'm telling
you in advance: raising money is hard.Notes[1]
When investors can't make up their minds, they sometimes
describe it as if it were a property of the startup. "You're too
early for us," they sometimes say. But which of them, if they were
taken back in a time machine to the hour Google was founded, wouldn't
offer to invest at any valuation the founders chose? An hour old
is not too early if it's the right startup. What "you're too early"
really means is "we can't figure out yet whether you'll succeed."
[2]
Investors influence one another both directly and indirectly.
They influence one another directly through the "buzz" that surrounds
a hot startup. But they also influence one another indirectly
through the founders. When a lot of investors are interested in
you, it increases your confidence in a way that makes you much more
attractive to investors.No VC will admit they're influenced by buzz. Some genuinely aren't.
But there are few who can say they're not influenced by confidence.[3]
One VC who read this essay wrote:"We try to avoid companies that got bootstrapped with consulting.
It creates very bad behaviors/instincts that are hard to erase
from a company's culture."[4]
The optimal way to answer the first question is to say that
it would be improper to name names, while simultaneously implying
that you're talking to a bunch of other VCs who are all about to
give you term sheets. If you're the sort of person who understands
how to do that, go ahead. If not, don't even try. Nothing annoys
VCs more than clumsy efforts to manipulate them.[5]
The disadvantage of expanding a round on the fly is that the
valuation is fixed at the start, so if you get a sudden rush of
interest, you may have to decide between turning some investors
away and selling more of the company than you meant to. That's a
good problem to have, however.[6]
I wouldn't say that intelligence doesn't matter in startups.
We're only comparing YC startups, who've already made it over a
certain threshold.[7]
But not all are. Though most VCs are suits at heart,
the most successful ones tend not to be. Oddly enough,
the best VCs tend to be the least VC-like.
Thanks to <NAME>, <NAME>, <NAME>,
<NAME>, and <NAME> for reading drafts of this.Russian Translation
|
|
https://github.com/danbalarin/vse-typst-template | https://raw.githubusercontent.com/danbalarin/vse-typst-template/main/lib/abstract-keywords.typ | typst | #import "macros.typ": heading-like
#let abstract-keywords(
abstract-cs: none,
keywords-cs: none,
abstract-en: none,
keywords-en: none,
separated-abstracts: false,
) = {
if abstract-cs != none [
#heading-like([Abstrakt], level: 2)
#abstract-cs
]
if keywords-cs != none [
#heading-like([Klíčová slova], level: 2)
#keywords-cs
]
if separated-abstracts == true and abstract-en != none and abstract-cs != none [
#pagebreak()
]
if abstract-en != none [
#heading-like([Abstract], level: 2)
#abstract-en
]
if keywords-en != none [
#heading-like([Keywords], level: 2)
#keywords-cs
]
pagebreak()
} |
|
https://github.com/jultty/skolar | https://raw.githubusercontent.com/jultty/skolar/main/demo/demo.typ | typst | #import "@local/skolar:0.2.0": *
#let my_properties = (
title: "Projeto de Jogo: Nefthera",
course: "Desenvolvimento de Jogos",
course_id: "DJOI5",
author: "<NAME>",
)
#generate_document(properties: my_properties)[
// you can override the template in here
#set heading(numbering: "1.a")
= #lorem(3)
#lorem(60)
$
7.32 beta +
sum_(i=0)^nabla
(Q_i (a_i - epsilon)) / 2 arrow.squiggly
v := vec(x_1, x_2, x_3)
$
#lorem(30)
#img("img/ocaml.svg", "Logo for the OCaml programming language")
#lorem(30)
#table(
columns: 5,
inset: 8pt,
align: center,
[*Process*], [_*Burst*_], [*Arrival*], [_*Turnaround*_], [*Wait*],
[P2], [1], [0], [1], [0],
[P4], [1], [0], [2], [1],
[Total], [19], [0], [35], [16],
[Média], [3.8], [0],
[#text(green)[*7*]], [#text(green)[*3.2*]],
)
#lorem(30)
= #lorem(5)
#lorem(50)
== #lorem(2)
```ocaml
start "Assembling file paths" ;
step "Filtering files not on PATH" ;;
let get_exit c = command ("which " ^ c ^ "> /dev/null") = 0
let rec filter_empty = function
| [] -> []
| h :: t -> if get_exit h then h :: filter_empty t else filter_empty t ;;
let existing_paths = filter_empty args ;;
```
#lorem(100)
== #lorem(4)
#lorem(50)
== #lorem(3)
#lorem(20)
=== #lorem(6)
#lorem(30)
=== #lorem(3)
#lorem(20)
]
|
|
https://github.com/yasemitee/Teoria-Informazione-Trasmissione | https://raw.githubusercontent.com/yasemitee/Teoria-Informazione-Trasmissione/main/template.typ | typst | #let project(title: "", body) = {
set document(title: title)
set text(font: "Source Sans Pro", lang: "it")
set text(hyphenate: false)
set par(justify: true)
set heading(numbering: "1.")
align(center)[
#block(text(weight: 700, 1.75em, title))
]
v(1.75em)
show outline.entry.where(
level: 1
): it => {
v(12pt, weak: true)
strong(it)
}
outline(indent: auto)
body
}
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/182.%20fp.html.typ | typst | fp.html
Fashionable Problems
December 2019I've seen the same pattern in many different fields: even though
lots of people have worked hard in the field, only a small fraction
of the space of possibilities has been explored, because they've
all worked on similar things.Even the smartest, most imaginative people are surprisingly
conservative when deciding what to work on. People who would never
dream of being fashionable in any other way get sucked into working
on fashionable problems.If you want to try working on unfashionable problems, one of the
best places to look is in fields that people think have already been
fully explored: essays, Lisp, venture funding � you may notice a
pattern here. If you can find a new approach into a big but apparently
played out field, the value of whatever you discover will be
multiplied by its enormous surface area.The best protection against getting drawn into working on the same
things as everyone else may be to genuinely
love what you're doing.
Then you'll continue to work on it even if you make the same mistake
as other people and think that it's too marginal to matter.Japanese TranslationArabic TranslationFrench Translation
|
|
https://github.com/ntjess/wrap-it | https://raw.githubusercontent.com/ntjess/wrap-it/main/docs/manual.typ | typst | The Unlicense | #import "@preview/tidy:0.2.0"
#import "@preview/showman:0.1.0"
#import "../wrap-it.typ"
#show raw.where(block: true, lang: "typ"): showman.formatter.format-raw.with(width: 100%)
#show raw.where(lang: "typ"): showman.runner.global-example.with(
unpack-modules: true,
scope: (wrap-it: wrap-it),
eval-prefix: "#let wrap-content(..args) = output(wrap-it.wrap-content(..args))"
)
#show <example-output>: set text(font: "New Computer Modern")
#let module = tidy.parse-module(read("../wrap-it.typ"))
#tidy.show-module(module,
style: tidy.styles.default,
first-heading-level: 1,
show-outline: false,
break-param-descriptions: true,
)
|
https://github.com/Julian-Wassmann/chapter-utils | https://raw.githubusercontent.com/Julian-Wassmann/chapter-utils/main/0.1.0/util/chapter-header.typ | typst | #import "./page-chapter.typ": page-chapter
#let page-number(
format-page: (page-number) => [Page #page-number]
) = locate(loc => {
let page-number-format = loc.page-numbering()
// show styled page-number if page-numbering is enabled
if page-number-format != none {
let page-number = counter(page).display(page-number-format)
format-page(page-number)
}
})
#let chapter-header(
format-page: (page-number) => [Page #page-number],
line-stroke: 0.3pt,
line-spacing: 0.5em,
mirror-even: false,
mirror-odd: false,
) = {
locate(loc => {
let even = calc.even(loc.page())
let mirror = if even and mirror-even or not even and mirror-odd {
true
} else {
false
}
// vertical distance between text and line
set block(spacing: line-spacing)
if mirror [
#page-number(format-page: format-page)
#h(1fr)
#page-chapter()
] else [
#page-chapter()
#h(1fr)
#page-number(format-page: format-page)
]
line(
length: 100%,
stroke: line-stroke,
)
})
} |
|
https://github.com/01mf02/jq-lang-spec | https://raw.githubusercontent.com/01mf02/jq-lang-spec/main/common.typ | typst | #import "@preview/ctheorems:1.1.0": thmplain, thmrules
#let thm(x, y, ..args) = thmplain(x, y, inset: (left: 0em, right: 0em), ..args)
#let example = thm("example", "Example")
#let lemma = thm("theorem", "Lemma")
#let theorem = thm("theorem", "Theorem")
#let proof = thm("proof", "Proof",
bodyfmt: body => [
#body #h(1fr) $square$ // Insert QED symbol
]
).with(numbering: none)
#let or_ = $quad || quad$
#let stream(..xs) = $angle.l #xs.pos().join($, $) angle.r$
#let var(x) = $\$#x$
#let cartesian = math.op($circle.small$)
#let arith = math.op($dot.circle$)
#let mod = math.op($\%$)
#let aritheq = math.op($dot.circle#h(0pt)=$)
#let fold = math.op($phi.alt$)
#let update = $models$
#let alt = $slash.double$
#let alteq = math.op($alt#h(0pt)=$)
#let defas = $#h(0pt):$
#let defend = $; thick$
#let bot = math.class("normal", sym.bot)
#let qs(s) = $quote#h(0pt)#s#h(0pt)quote$
#let oat(k) = $.[#qs(k)]$
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/transform-layout_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test relative sizing in scaled boxes.
#set page(width: 200pt, height: 200pt)
#set text(size: 32pt)
#let scaled(body) = box(scale(
x: 60%,
y: 40%,
box(stroke: 0.5pt, width: 30%, clip: true, body)
))
#set scale(reflow: false)
Hello #scaled[World]!\
#set scale(reflow: true)
Hello #scaled[World]!
|
https://github.com/maucejo/elsearticle | https://raw.githubusercontent.com/maucejo/elsearticle/main/src/elsearticle.typ | typst | MIT License | // elsearticle.typ
// Author: <NAME>
// Github: https://github.com/maucejo
// License: MIT
// Date : 07/2024
#import "_globals.typ": *
#import "_environment.typ": *
#import "_utils.typ": *
#import "_template_info.typ": *
#let elsearticle(
// The article's title.
title: none,
// An array of authors. For each author you can specify a name,
// department, organization, location, and email. Everything but
// but the name is optional.
authors: (),
// Your article's abstract. Can be omitted if you don't have one.
abstract: none,
// Journal name
journal: none,
// Keywords
keywords: none,
// For integrating future formats (1p, 3p, 5p, final)
format: "review",
// Number of columns
numcol: 1,
// Line numbering
line-numbering: false,
// The document's content.
body,
) = {
// Text
set text(size: font-size.normal, font: "New Computer Modern")
// Conditional formatting
let els-linespace = if format == "review" {linespace.review} else {linespace.preprint}
let els-margin = if format == "review" {margins.review}
else if format == "preprint" {margins.preprint}
else if format == "1p" {margins.one_p}
else if format == "3p" {margins.three_p}
else if format == "5p" {margins.five_p}
else {margins.review}
let els-columns = if format == "1p" {1}
else if format == "5p" {2}
else {if numcol > 2 {2} else {if numcol <= 0 {1} else {numcol}}}
// Heading
set heading(numbering: "1.")
show heading: it => block(above: els-linespace, below: els-linespace)[
#if it.numbering != none {
if it.level == 1 {
set par(leading: 0.75em, hanging-indent: 1.25em)
set text(font-size.normal)
numbering(it.numbering, ..counter(heading).at(it.location()))
text((" ", it.body).join())
// Update math counter at each new appendix
if isappendix.get() {
counter(math.equation).update(0)
counter(figure.where(kind: image)).update(0)
counter(figure.where(kind: table)).update(0)
}
} else {
set text(font-size.normal, weight: "regular", style: "italic")
numbering(it.numbering, ..counter(heading).at(it.location()))
text((" ", it.body).join())
}
} else {
text(size: font-size.normal, it.body)
}
]
// Equations
set math.equation(numbering: n => numbering("(1)", n) , supplement: [Eq.])
// Figures, subfigures, tables
show figure.where(kind: table): set figure.caption(position: top)
set ref(supplement: it => {
if it.func() == figure and it.kind == image {
"Fig."
} else {
it.supplement
}
})
// Page
let footer = context{
let i = counter(page).at(here()).first()
if i == 1 {
set text(size: font-size.small)
emph(("Preprint submitted to ", journal).join())
h(1fr)
emph(datetime.today().display("[month repr:long] [day], [year]"))
} else {align(center)[#i]}
}
set page(
paper: "a4",
numbering: "1",
margin: els-margin,
columns: els-columns,
// Set journal name and date
footer: footer
)
// Paragraph
let linenum = none
if line-numbering {
linenum = "1"
}
set par(justify: true, first-line-indent: indent-size, leading: els-linespace)
set par.line(numbering: linenum, numbering-scope: "page")
// Define Template info
let els-info = template_info(title, abstract, authors, keywords, els-columns)
// Set document metadata.
set document(title: title, author: els-info.els-meta)
place(
top,
float: true,
scope: "parent",
[
#els-info.els-authors
#els-info.els-abstract
]
)
// Corresponding author
hide(footnote(els-info.coord, numbering: "*"))
counter(footnote).update(0)
// bibliography
set bibliography(title: "References")
show bibliography: set heading(numbering: none)
show bibliography: set text(size: font-size.normal)
v(-2em)
body
}
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/space-02.typ | typst | Other | // Test that a run consisting only of whitespace isn't trimmed.
A#text(font: "IBM Plex Serif")[ ]B
|
https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst | https://raw.githubusercontent.com/TJ-CSCCG/tongji-undergrad-thesis-typst/main/README-EN.md | markdown | MIT License | # :page_facing_up: Tongji University Undergraduate Thesis Typst Template (STEM)
[中文](README.md) | English
> [!CAUTION]
> Since the Typst project is still in the development stage and support for some features is not perfect, there may be some issues with this template. If you encounter problems while using it, please feel free to submit an issue or PR and we will try our best to solve it.
>
> In the mean time, we also welcome you to use [our $\LaTeX$ template](https://github.com/TJ-CSCCG/tongji-undergrad-thesis).
## Sample Display
Below are displayed in order the "Cover", "Chinese Abstract", "Table of Contents", "Main Content", "References", and "Acknowledgments".
<p align="center">
<img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0001.jpg" width="30%">
<img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0002.jpg" width="30%">
<img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0004.jpg" width="30%">
<img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0005.jpg" width="30%">
<img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0019.jpg" width="30%">
<img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0020.jpg" width="30%">
</p>
## Usage Instructions
### Online Web App
#### Create Project
- Open [](https://www.overleaf.com/latex/templates/tongji-university-undergraduate-thesis-template/tfvdvyggqybn) and click `Create project in app`.
- Or select `Start from a template` in the [Typst Web App](https://typst.app), then choose `paddling-tongji-thesis`.
#### Upload Fonts
Download all font files from the [`fonts` branch](https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst/tree/fonts) and upload them to the root directory of the project in the Typst Web App. You can then start using the template.
### Local Usage
#### 1. Install Typst
Follow the [Typst official documentation](https://github.com/typst/typst?tab=readme-ov-file#installation) to install Typst.
#### 2. Download Fonts
Download all font files from the [`fonts` branch](https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst/tree/fonts) and **install them on your system**.
#### Initialization using `typst`
##### Initialize Project
```bash
typst init @preview/paddling-tongji-thesis
```
##### Compile
```bash
typst compile main.typ
```
#### Initialization using `git clone`
##### Git Clone Project
```bash
git clone https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst.git
cd tongji-undergrad-thesis-typst
```
##### Compile
```bash
typst compile init-files/main.typ --root .
```
> [!TIP]
> If you don't want to install the fonts used by the project on your system, you can specify the font path during compilation, for example:
>
> ```bash
> typst compile init-files/main.typ --root . --font-path {YOUR_FONT_PATH}
> ```
## How to Contribute to This Project?
Please see [How to pull request](CONTRIBUTING.md/#how-to-pull-request).
## Open Source License
This project is licensed under the [MIT License](LICENSE).
### Disclaimer
This project uses fonts from the FounderType font library, with copyright belonging to FounderType. This project is for learning and communication purposes only and must not be used for commercial purposes.
## Acknowledgments for Outstanding Contributions
- This project originated from [FeO3](https://github.com/seashell11234455)'s initial version project [tongji-undergrad-thesis-typst](https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst/tree/lky).
- Later, [RizhongLin](https://github.com/RizhongLin) improved the template to better meet the requirements of Tongji University undergraduate thesis, and added basic tutorials for Typst.
We are very grateful to the above contributors for their efforts, which have provided convenience and help to more students.
When using this template, if you find this project helpful for your graduation project or thesis, we hope you can express your thanks and respect in your acknowledgments section.
## Acknowledgments for Open Source Projects
We have learned a lot from the excellent open-source projects of top universities:
- [lucifer1004/pkuthss-typst](https://github.com/lucifer1004/pkuthss-typst)
- [werifu/HUST-typst-template](https://github.com/werifu/HUST-typst-template)
## Contact
```python
# Python
[
'rizhonglin@$.%'.replace('$', 'epfl').replace('%', 'ch'),
]
```
### QQ Group
- TJ-CSCCG Communication Group: `1013806782` |
https://github.com/0x1B05/algorithm-journey | https://raw.githubusercontent.com/0x1B05/algorithm-journey/main/practice/note/content/哈希表和哈希函数.typ | typst | #import "../template.typ": *
#pagebreak()
= 哈希表和哈希函数
== 哈希函数
1. 输入域无穷
2. 输出域 S 有限,比如 MD5 的返回值是 0~2 的 64 次方-1
3. 相同的输入,一定返回相同的输出(不随机)
4. 不同的输入,可能有相同的输出(哈希碰撞),但是概率非常低
5. 每一个输出都均匀离散(最重要的性质)
6. 若输入域通过哈希函数得到的输出是均匀离散的,那再 mod 一个 M,得到的输出在 0~M-1
上野是均匀离散的
=== 经典题目 1
假设有一个文件,有 40 亿无符号整数(0-2^32-1),只给 1G 内存,找出出现次数最多的数.
分析:使用 Hash 表超内存,key->4byte,value->4byte,至少 8byte.若 40
亿数字均不同,会需要 320 亿字节,大约 32G.不怕相同数出现多次,怕不同数多.
=== 经典题目 2
哈希表的实现
=== 经典题目 3
利用哈希表设计 RandomPoll 实现增删查. 设计一种结构,在该结构中有三个功能:
- insert(key):将某个 key 加入到该结构,做到不重复加入.
- delete(key):将原本在结构中的某个 key 移除.
- getRandom():等概率随机返回结构中的任何一个 key. >
要求:这三个功能的时间复杂度都为 O(1)
分析:
#tablem[
| \ | map1 | map2 | | ----- | ------- | ------- | | key | String | Integer | |
value | Integer | String |
]
1. 对于 insert 函数,只需要先判断哈希表中是否含有该 key,若无,调用 HashMap 的 put
方法即可.
2. 对于 delete
函数,删除了哈希表中的某一键值对后,只需要将最后一组键值对补充到删除的缺口上即可.
> HashMap 的 put 方法,若以前已包含了键值对,则替换圆键值对.
3. getRandom 函数,`(int)Math.random()*mapSize` 可以在 0~size-1 中随机生成一个数.
```java
public static class RandomPool{
HashMap<String,Integer> map1;
HashMap<Integer,String> map2;
int mapSize;
public RandomPool(){
map1 = new HashMap<String,Integer>();
map2 = new HashMap<Integer,String>();
mapSize = 0;
}
public boolean insert(String str){
if(!map1.containsKey(str)){
map1.put(str,++mapSize);
map2.put(mapSize,str);
return true;
}
return false;
}
public void delete(String str){
if(map1.containsKey(str)){
int deleteIndex = map1.get(str);
int lastIndex = --mapSize;
map1.put(map2.get(lastIndex),deleteIndex); //map1中用最后一组键值对填充被删掉键值对的位置
map2.put(deleteIndex,map2.get(lastIndex)); map1中用最后一组键值对填充被删掉键值对的位置
map1.remove(str);
map2.remove(lastIndex); //把最后一组键值对删除,因为该键值对已经拿去填充了
}
}
public String getRandom(){
return map2.get((int)Math.random()*mapSize);
}
}
```
=== 经典题目 3:布隆过滤器
解决类似于黑名单,爬虫等问题
特点:
1. 没有删除行为,只有加入和查询行为
2. 做到使用空间很少,允许一定程度的失误率
3. 布隆过滤器可能将白名单的用户当成了黑名单,但不会将黑名单的用户当成白名单
4. 可以通过人为设计,例如将失误率降为万分之一,但不可避免.
==== 位图
```java
public static void main(String[] args){
//a实际上占32bit
int a = 0;
//32bit * 10 -> 320bits
//arr[0] 可以表示0~31位bit
//arr[1] 可以表示32~63位bit
int[] arr = new int[10];
//想取得第178个bit的状态
int i = 178;
//定位出第178位所对应的数组元素是哪个
int numIndex = i / 32;
//定位出相应数组元素后,需要知道是数组元素的哪一位
int bitIndex = i % 32;
//拿到第178位的状态
int s = ( (arr[numIndex] >> (bitIndex)) & 1);
//把第i位的状态改成1
arr[numIndex] = arr[numIndex] | (1<<(bitIndex));
//把第i位的状态改成0
arr[numIndex] = arr[numIndex] & (~ (1 << bitIndex));
//把第i位拿出来
int bit = (arr[i/32] >> (i%32)) & 1;
}
```
https://blog.csdn.net/dreamispossible/article/details/89972545
=== 一致性哈希原理
https://blog.csdn.net/kefengwang/article/details/81628977
|
|
https://github.com/HenkKalkwater/aoc-2023 | https://raw.githubusercontent.com/HenkKalkwater/aoc-2023/master/parts/day-3-1.typ | typst | #let input = "467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598.."
#let GRID_SYMBOL = -1
#let GRID_EMPTY = -2
#let parse_grid = (input) => {
let numbers = ()
let grid = ()
let grid_row = ()
let cur_number = (number: 0, pos: ())
let x = 0
let y = 0
for char in input {
if char.match(regex("[0-9]")) != none {
cur_number = (
number: cur_number.number * 10 + int(char),
pos: cur_number.pos + ((x, y),)
)
grid_row.push(numbers.len())
} else {
// Finished reading number, push it to the number list
if cur_number.pos.len() > 0 {
numbers.push(cur_number)
cur_number = (number: 0, pos: ())
}
if char == "." {
grid_row.push(GRID_EMPTY)
} else if char != "\n" {
grid_row.push(GRID_SYMBOL)
}
}
if char == "\n" {
x = 0
y += 1
grid.push(grid_row)
grid_row = ()
} else {
x += 1
}
}
// Push last row in case of no ending newline
if x != 0 {
grid.push(grid_row)
}
(
grid: grid,
numbers: numbers,
)
}
#let grid_cell_value = (grid, x, y) => {
if x < 0 or x >= grid.first().len() or y < 0 or y >= grid.len() {
GRID_EMPTY
} else {
grid.at(y).at(x)
}
}
#let is_part_no = (grid, x, y) => {
let sur_positions = (
(-1, -1), ( 0, -1), ( 1, -1),
(-1, 0), ( 1, 0),
(-1, 1), ( 0, 1), ( 1, 1)
)
for pos in sur_positions {
if grid_cell_value(grid, x + pos.first(), y + pos.last()) == GRID_SYMBOL {
return true
}
}
false
}
#let visualise(res, numbers, part_numbers) = [
#let vis_cells = ()
#for y in range(res.grid.len()) {
let row = res.grid.at(y)
for x in range(row.len()) {
let val = grid_cell_value(res.grid, x, y)
let cell = none
if val < 0 {
if val == GRID_SYMBOL {
cell = [\*]
} else {
cell = [ ]
}
} else {
let number = res.numbers.at(val).number
cell = [ #number ]
}
vis_cells.push(cell)
}
}
#table(
columns: 4,
[*Row*], [*Col start*], [*Col end*], [*Part numbers*],
..part_numbers.map(n => {
let row = n.pos.first().last()
let x1 = n.pos.first().first()
let x2 = n.pos.last().first()
return ([#row], [#x1], [#x2], [#n.number],)
}).flatten(),
[], [], [], [*Sum*: #part_numbers.map(n => n.number).sum()]
)
#[
#set page(width: auto, height: auto)
#table(
columns: res.grid.first().len(),
align: center,
fill: (x, y) => {
let val = grid_cell_value(res.grid, x, y)
if val == GRID_SYMBOL {
rgb("#888833")
} else if val >= 0 {
for number in numbers {
for pos in number.pos {
if pos.first() == x and pos.last() == y {
if number.at("is-part", default: false) {
return rgb("#004400")
} else {
return rgb("#00440044")
}
}
}
}
none
} else {
none
}
},
..vis_cells
)
]
]
#let solve = (input) => {
let res = parse_grid(input.trim("\n"))
let numbers = res.numbers
.map(num => {
for num_pos in num.pos {
let x = num_pos.first()
let y = num_pos.last()
if is_part_no(res.grid, x, y) {
num.insert("is-part", true)
return num
}
}
num.insert("is-part", false)
num
})
let part_numbers = numbers.filter(n => n.at("is-part", default: false))
(
value: part_numbers
.map(x => x.number)
.sum(),
visualisation: visualise(res, numbers, part_numbers)
)
}
|
|
https://github.com/indicatelovelace/typstTemplates | https://raw.githubusercontent.com/indicatelovelace/typstTemplates/main/themes/dhbw-thesis/utils.typ | typst | MIT License | #import "@preview/drafting:0.1.1": *
// Get the page (counter value, not real page number) for a selector
// e. g. #page_ref(<lst:hello-world>)
#let page_ref(selector) = {
locate(loc => {
// Get the `location` of the element
let element_location = query(selector, loc)
.first()
.location()
// Get the page number, the location lies on
link(element_location)[#counter(page).at(element_location).first()]
})
}
// (name: <NAME>, number: 4532, class: A1)
// (name: <NAME>, number: 3332, class: A1, lead: <NAME>)
// (name: [<NAME>, <NAME>], number: (4532, 3332), class: (A1, A1), lead: (<NAME>))
#let authorMetadata(authors) = {
let commonKeys = authors.fold((:), (dic, auth) => {
for (key, value) in auth {
dic.insert(key, dic.at(key, default: ()) + (value,))
}
dic
})
commonKeys
}
#let flattenAuthorMetadata(dict: (:)) = {
let metadata = dict.pairs().map(pair => {
let key = pair.at(1).dedup()
(strong(pair.at(0)), key.at(0)) + key.slice(1).map(it => {
if it != none {
([], it)
}
}).flatten()
})
metadata.flatten()
}
#let reduceAuthors(authors) = {
authors = authors.sorted(key: author => author.name)
let names = ()
let matrNums = ()
let courseS = ()
let courseL = ()
let period = ()
let evaluators = ()
let submissionDate = ()
for author in authors {
names.push(author.name)
}
for author in authors {
matrNums.push(author.matriculationNumber)
}
for author in authors {
courseS.push(author.courseShort)
}
for author in authors {
courseL.push(author.courseName)
}
for author in authors {
evaluators.push(author.at("evaluator", default: none))
}
for author in authors {
period.push(author.at("period", default: none))
}
for author in authors {
submissionDate.push(author.at("submissionDate", default: none))
}
(
name: names.join(", "),
matriculationNumber: matrNums.map(str).join(", "),
courseShort: courseS.dedup().join(", "),
courseName: courseL.dedup().join(", "),
evaluator: evaluators.filter(x => x != none).first(),
period: period.filter(x => x != none).first(),
submissionDate: submissionDate.filter(x => x != none).first(),
company: none,
companyAdvisor: none,
)
}
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/foundations-06.typ | typst | Other | // Test failing assertions.
// Error: 8-51 assertion failed: two is smaller than one
#assert(2 < 1, message: "two is smaller than one")
|
https://github.com/ohmycloud/computer-science-notes | https://raw.githubusercontent.com/ohmycloud/computer-science-notes/main/Misc/py_package_and_publish.typ | typst | #import("doctemplate.typ"): conf
#show link: underline
#show "pyproject.toml": it => text(red)[#it]
#show: doc => conf(
title: "Python 模块打包和发布指南",
author: "ohmycloud",
date: datetime.today().display(),
description: "Rye Vs Poetry Vs PDM",
doc,
)
= pypi 私有服务搭建
搭建 PYPI 私服, 便于 Python 模块/命令行工具的分享, 积累通用工具类和通用模块, 强化基础设施建设。
== 软件安装
在服务器端执行如下命令安装 PYPI 服务所需的依赖模块:
```bash
pip install pypiserver
pip install passlib
```
== 账号配置
在服务器端, 在数据盘上某个目录下创建一个名为 #text(red)[packages] 的目录用于存放打包命令上传的 #text(red)[.tar.gz] 和 #text(red)[.whl] 文件。使用 `htpasswd` 命令创建 PYPI 服务的用户名和密码:
```bash
cd /mnt/data1/ && mkdir packages
htpasswd -c ~/.pypipaswd pypi
```
这会创建一个名为 #text(red)[pypi] 的用户, 在创建用户时会提示你输入这个用户的密码。
== 启动服务
在服务器端使用 pypi-server run 命令启动私有 PYPI 仓库:
```bash
nohup pypi-server run -P ~/.pypipasswd -p 8099 --fallback-url https://mirrors.aliyun.com/pypi/simple/ packages &
```
其中:
- #text(red)[-P] 指定密码文件为上面创建的 ~/.pypipasswd。
- #text(red)[-p] 指定监听端口为 8099。
- #text(red)[--fallback-url] 指定当在私有仓库找不到所需依赖模块时去该地址进行安装。
- #text(red)[packages] 是上面所创建的存储依赖文件的目录。
= nexus 私有服务搭建
== 软件安装
下载 nexus 压缩模块, 解压 到 /usr/local 目录:
```bash
tar -xvf nexus-3.53.0-01-unix.tar.gz -C /usr/local/
```
创建软链接:
```bash
ln -s /usr/local/nexus-3.53.0-01/ /usr/local/nexus
ln -s /usr/local/nexus/bin/nexus /usr/bin/
```
== 配置文件
```bash
cd /usr/local/nexus
vi bin/nexus.rc
vi etc/nexus-default.properties
vi bin/nexus.vmoptions
```
== 设置服务
```bash
vi /lib/systemd/system/nexus.service
systemctl daemon-reload
systemctl enable --now nexus.service
ss -ntlp | grep 3333
```
查看密码:
```bash
cat /usr/local/sonatype-work/nexus3/admin.password
```
浏览器打开: #link("http://127.0.0.1:3333")[http://127.0.0.1:3333] 输入 admin 的密码, 修改新的密码。
然后执行如下3个步骤配置仓库:
1) 创建 blob storage:
#image("blob_storages.png")
2) 创建新的仓库:hosted-pypi, proxy-pypi, group-pypi。
#image("repository.png")
3) 创建 nexus 用户:
#image("user.png")
设置用户名和密码, 后面上传 wheel 模块时需要使用这个用户名和密码。
= 打包工具
Python 有多个打包工具, 这里使用两种打包工具, 即 #link("https://rye-up.com/")[Rye] 和 #link("https://python-poetry.org/")[Poetry]。
== Rye
=== 安装 Rye
Rye 提供了 exe 安装格式, 是单个二进制可执行文件, 从官网下载 #link("https://github.com/mitsuhiko/rye/releases/latest/download/rye-x86_64-windows.exe")[rye-x86_64-windows.exe], 然后把 Rye 添加到系统的 Path 路径中。
=== 创建项目
使用 `rye init esc_app` 创建一个项目, 生成的项目中有一个名为 #text(red)[pyproject.toml] 的文件, 其内容如下:
```toml
[project]
name = "esc_app"
version = "0.1.0"
description = "Add your description here"
dependencies = []
readme = "README.md"
requires-python = ">= 3.8"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.rye]
managed = true
dev-dependencies = []
[tool.hatch.metadata]
allow-direct-references = true
```
执行 `rye sync`:
```
Initializing new virtualenv in /mnt/d/software/scripts/esc_app/esc_app/.venv
Python version: [email protected]
Generating production lockfile: /mnt/d/software/scripts/esc_app/esc_app/requirements.lock
Generating dev lockfile: /mnt/d/software/scripts/esc_app/esc_app/requirements-dev.lock
Installing dependencies
Looking in indexes: https://pypi.org/simple/
Obtaining file:///. (from -r /tmp/tmpcvyy5_fl (line 1))
Installing build dependencies ... done
Checking if build backend supports build_editable ... done
Getting requirements to build editable ... done
Preparing editable metadata (pyproject.toml) ... done
Building wheels for collected packages: esc_app
Building editable for esc_app (pyproject.toml) ... done
Created wheel for esc_app: filename=esc_app-0.1.0-py3-none-any.whl size=975
Stored in directory: /tmp/pip-ephem-wheel-cache-2vw7ijau/wheels/97/54/f5/
Successfully built esc_app
Installing collected packages: esc_app
Successfully installed esc_app-0.1.0
Done!
```
这会为我们自动创建虚拟环境, 下载依赖, 准备 Python 开发所需要的环境。最后的 `Done!` 说明一切准备就绪。
=== 添加依赖
执行 `rye add` 命令添加依赖:
```bash
$ rye add click==8.1.6
Added click==8.1.6 as regular dependency
$ rye add polars==0.18.6
Added polars==0.18.6 as regular dependency
$ rye add xlsx2csv==0.8.1
Added xlsx2csv==0.8.1 as regular dependency
$ rye add XlsxWriter==3.1.2
Added XlsxWriter==3.1.2 as regular dependency
```
执行 `rye add` 命令后, 会在 `pyproject.toml` 文件中增加 dependencies 配置:
```
dependencies = [
"click==8.1.6",
"polars==0.18.6",
"xlsx2csv==0.8.1",
"XlsxWriter==3.1.2",
]
```
=== 开发调试
假设我们开发了一个名为 main.py 的命令行程序, 它接收两个参数: input_path 和 sheet_name:
```python
import click
@click.command()
@click.option('--input-path', help='输入文件路径')
@click.option('--sheet-name', default='Sheet1', help='Worksheet 名称')
def peak_capacity(input_path, sheet_name):
pass
if __name__ == '__main__':
peak_capacity()
```
这是一个命令行程序, 我们在 #text(red)[pyproject.toml] 中添加命令行程序的配置:
```toml
[project.scripts]
peak = "esc_app.main:peak_capacity"
```
其中 esc_app 为 package 名, main 为命令行程序的文件名, peak_capacity 为入口函数。等号左边的 `peak` 为该命令行程序对外使用的别名, 调试的时候, 执行 `rye run` 命令运行该命令行程序:
```bash
rye run peak --input-path=input.xlsx --sheet-name=1月
```
=== 打包发布
模块/命令行程序开发完毕后, 执行 `rye build` 进行打包:
```bash
rye build
```
这会生成一个名为 #text(red)[dist] 的目录, 目录下包含两个文件:
```bash
xxx-a.b.c.tar.gz
xxx-a.b.c-py3-none-any.whl
```
rye 尚未支持发布到私服, 但是 rye 自己的发布命令使用的是 #link("https://twine.readthedocs.io")[twine], 而 twine 支持把 Python 模块发布到私服。
为了使用方便, 在 Windows 下在 %USERPROFILE% 目录下创建一个名为 #text(red)[.pypirc] 的文件, 其内容如下:
```toml
[distutils]
index-servers =
pypi
nexus
devpi
[pypi]
repository: http://127.0.0.1:8099/
username: pypi
password: <PASSWORD>
[nexus]
repository: http://127.0.0.1:3333/repository/local-pypi/
username: pypi
password: <PASSWORD>
[devpi]
repository: http://pypi.xxx.xxx/bigdata/datahouse/+simple/
username: bigdata
password: <PASSWORD>
```
index-servers 是仓库的名称, 我们要把 Python 模块上传到 pypi 和 nexus。
使用 twine 的 #text(red)[upload] 命令, 后面跟着 #raw("dist/*"), 表示把 dist 目录下的所有文件都上传到私服。--repository 指定仓库的名称, twine 一次上传到一个仓库:
```bash
twine upload dist/* --repository pypi
twine upload dist/* --repository nexus
twine upload dist/* --repository devpi
```
== Poetry
=== 安装 Poetry
```bash
# 安装 Anaconda
# 切换到 conda 环境
cmd /k "C:\ProgramData\Anaconda3\Scripts\activate.bat & powershell -NoLogo"
# 设置代理
$Env:http_proxy="http://127.0.0.1:7890";$Env:https_proxy="http://127.0.0.1:7890"
# 安装 pipx
python -m pip install pipx --user
# 安装 poetry
pipx install poetry==1.1.15
# 添加 path 路径
pipx ensurepath
# 刷新环境变量或重开一个新的终端
refreshenv
```
=== 创建项目
```bash
mkdir esc_spp && cd esc_app
poetry init
```
执行 `poetry init` 命令后会以交互式的形式创建项目。
```
This command will guide you through creating your pyproject.toml config.
Package name: esc_app
Version [0.1.0]:
Description []:
Author [None, n to skip]: ohmycloud
License []:
Compatible Python versions [^3.11]:
```
确认生成的 `pyproject.toml` 文件格式是否正确:
```toml
[tool.poetry]
name = "esc-app"
version = "0.1.0"
description = ""
authors = ["ohmycloud"]
readme = "README.md"
packages = [{include = "esc_app"}]
[tool.poetry.dependencies]
python = "^3.11"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
```
或使用 `poetry init -n` 直接创建一个项目。
=== 添加依赖
执行 `poetry add` 命令添加依赖:
```bash
poetry add polars==0.19.2
```
这会在 pyproject.toml 文件中添加依赖:
```toml
[tool.poetry.dependencies]
python = "^3.11"
polars = "0.19.2"
```
=== 开发调试
在 *pyproject.toml* 文件中添加如下配置:
```toml
[tool.poetry.scripts]
peak = "esc_app.main:peak_capacity"
```
执行 `poetry run` 命令运行命令行程序:
```bash
poetry run peak --input-path=input.xlsx --sheet-name=1月
```
=== 打包发布
首先配置仓库地址和用户名密码, 在客户机上执行如下设置:
```bash
# 配置 pypi 仓库
poetry config repositories.ohmycloud http://127.0.0.1:8099/
poetry config http-basic.ohmycloud pypi a_very_complex_password
# 配置 nexus 仓库
poetry config repositories.nexus http://127.0.0.1:3333/repository/local-pypi/
poetry config http-basic.nexus pypi a_very_complex_password
# 配置 devpi 仓库
poetry config repositories.devpi http://pypi.xxx.xxx/bigdata/datahouse/+simple/
poetry config http-basic.devpi bigdata a_very_complex_password
```
这会在 ~/.config 目录下创建一个名为 #text(red)[pypoetry] 的目录, 并生成 #text(red)[auth.toml] 和 #text(red)[config.toml] 文件。
`~/.config/pypoetry/auth.toml` 文件的内容如下:
```toml
[http-basic.nexus]
username = "pypi"
password = "<PASSWORD>"
[http-basic.ohmycloud]
username = "pypi"
password = "<PASSWORD>"
[http-basic.devpi]
username = "bigdata"
password = "<PASSWORD>"
```
`~/.config/pypoetry/config.toml` 文件的内容如下(注意 url 末尾的 `/`):
```toml
[repositories.nexus]
url = "http://127.0.0.1:3333/repository/local-pypi/"
[repositories.ohmycloud]
url = "http://127.0.0.1:8099/"
[repositories.devpi]
url = "http://pypi.xxx.xxx/bigdata/datahouse/+simple/"
```
也可以执行 `poetry config --list` 查看仓库地址。
配置完成后使用 `--dry-run` 模拟发布:
```bash
poetry build
poetry publish --repository ohmycloud --dry-run
# 如果没有使用 pypoetry 的配置文件, 则指定用户名和密码
poetry publish --repository ohmycloud -u pypi -p a_very_complex_password --dry-run
```
这会打印出该模块准备发布到 ohmycloud 仓库, 和上传进度:
```
Publishing esc_app (0.1.0) to ohmycloud
- Uploading esc_app-0.1.0-py3-none-any.whl 100%
- Uploading esc_app-0.1.0.tar.gz 100%
```
模拟发布没有问题后去掉 `--dry-run` 选项把模块发布到私有 PYPI 仓库中。
```bash
# 发布到 ohmycloud 仓库
poetry publish --repository ohmycloud
# 发布到 nexus 仓库
poetry publish --repository nexus
# 发布到 devpi 仓库
poetry publish --repository devpi
# 或使用 twine
twine upload dist/* -r devpi
```
== PDM
=== 安装 PDM
```bash
curl -sSL https://pdm-project.org/install-pdm.py | python3 -
```
=== 创建项目
```bash
mkdir my-project && cd my-project
pdm init
```
=== 添加依赖
添加依赖:
```bash
pdm add polars==0.18.15
```
=== 开发调试
在 *pyproject.toml* 文件中添加如下配置:
```toml
[tool.pdm.scripts]
peak = {call = "esc_app.main:peak_capacity"}
```
这对外暴露出了一个命令行接口, 即 peak 命令。
调试的时候, 使用 pdm 进行构建和安装后, 再使用 `pdm run` 运行命令行程序进行调试。
```bash
pdm build
pdm install
pdm run peak --input-path=input.xlsx --sheet-name=1月
```
=== 打包发布
第一次发布时, 需要配置仓库地址和用户名密码:
在用户的家目录新建一个文件: `~/.config/pdm/config.toml`, 其内容如下:
```toml
[repository.nexus]
url = "http://127.0.0.1:3333/repository/local-pypi/"
username = "pypi"
password = "<PASSWORD>"
[repository.ohmycloud]
url = "http://127.0.0.1:8099/"
username = "pypi"
password = "<PASSWORD>"
[repository.devpi]
url = "http://pypi.xxx.xxx/bigdata/datahouse/+simple/"
username = "bigdata"
password = "<PASSWORD>"
```
在 pyproject.toml 文件中, 添加如下内容:
```toml
[[tool.pdm.source]]
url = "http://127.0.0.1:3333/repository/local-pypi/"
verify_ssl = false
name = "nexus"
[[tool.pdm.source]]
url = "http://127.0.0.1:8099/"
verify_ssl = false
name = "ohmycloud"
[[tool.pdm.source]]
url = "http://pypi.xxx.xxx/bigdata/datahouse/+simple/"
verify_ssl = false
name = "devpi"
```
打包发布:
```bash
pdm publish -r nexus -v
pdm publish -r ohmycloud -v
pdm publish -r devpi -v
```
= 从私服安装模块
从私服中安装模块, 在 install 命令后面指定 `--trusted-host` 以及 `-i` 选项
```bash
# 从 pypi 仓库安装 Python 模块
pip install --trusted-host 127.0.0.1 -i http://127.0.0.1:8099/ esc_app==0.2.2
# 从 nexus 仓库安装 Python 模块
pip install --trusted-host 127.0.0.1 -i http://127.0.0.1:3333/repository/group-pypi/simple esc_app==0.2.2
# 从 devpi 仓库安装 Python 模块
pip install --trusted-host pypi.xxx.xxx -i http://pypi.xxx.xxx/bigdata/datahouse/+simple/ pdm_demo
```
= 使用 Python 模块
如果是 Python 模块, 直接导入使用:
```python
import esc_app
```
如果是命令行程序, 就像使用普通的 Python 命令行程序一样, 使用命令行程序的别名, 后跟命名参数:
```bash
peak --input-path=input.xlsx --sheet-name=1月
```
这样既可以把自己编写好的模块上传到私服供他人使用, 也可以安装使用别人编写好的模块。加上模块的版本控制, 分发和使用起来更加方便, 提升开发效率。
|
|
https://github.com/mangkoran/utm-thesis-typst | https://raw.githubusercontent.com/mangkoran/utm-thesis-typst/main/07_declaration_originality.typ | typst | MIT License | #import "@preview/tablex:0.0.7": tablex, colspanx
#import "utils.typ": empty
#let content(
title: empty[title],
author: empty[author],
) = [
#align(center)[
= Declaration
]
#align(horizon)[
I declare that this thesis entitled "#title" is the result of my own
research except as cited in the references. The thesis has not been accepted for
any degree and is not concurrently submitted in candidature of any other degree.
#tablex(
auto-lines: false,
columns: (auto, 1fr),
[Signature], [:],
[Name], [: #author],
[Date], [: #datetime.today().display()],
)
]
#pagebreak(weak: true)
]
#content()
|
https://github.com/Isaac-Fate/booxtyp | https://raw.githubusercontent.com/Isaac-Fate/booxtyp/master/src/theorems/definition.typ | typst | Apache License 2.0 | #import "new-theorem-template.typ": new-theorem-template
#import "../counters.typ": definition-counter
#import "../colors.typ": color-schema
#let definition = new-theorem-template(
"Definition",
fill: color-schema.green.light,
stroke: color-schema.green.primary,
theorem-counter: definition-counter,
)
|
https://github.com/miliog/typst-penreport | https://raw.githubusercontent.com/miliog/typst-penreport/master/typst-penreport/content/document_properties.typ | typst | MIT No Attribution | #let documentProperties(headingName, organisation, subtitle, targets) = [
#strong(headingName)
#table(
fill: (col, row) => if col == 0 { luma(240) },
columns: (auto, 1fr),
inset: 10pt,
stroke: (paint: gray, thickness: 1pt),
align: left,
[*Client*],
organisation,
[*Title*],
subtitle,
[*Targets*],
for item in targets {
item.name + "\n"
},
[*Version*],
[1.0],
[*Pentester*],
[],
)
] |
https://github.com/jonsch318/rules_typst | https://raw.githubusercontent.com/jonsch318/rules_typst/main/README.md | markdown | Apache License 2.0 | # Typst rules for [Bazel](https://bazel.buid)
Bazel rules for the [typst](https://typst.app) markup-based typesetting system.
> [!CAUTION]
> This ruleset is in early development and thus introduce
> breaking changes at any time (without warning) until a 1.0.0 release.
I try to follow the Bazel rules-template.
Roadmap:
- [] functioning simple pdf example
- [] functioning multi file pdf document
- [] functioning data dependencies
- [] packages
- [] watching
- [] font dependencies without fonts no hermetic build is possible.
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/043%20-%20Innistrad%3A%20Midnight%20Hunt/004_Sisters.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Sisters",
set_name: "Innistrad: Midnight Hunt",
story_date: datetime(day: 10, month: 09, year: 2021),
author: "<NAME>",
doc
)
Leinore found the dead snake mixed in the ashes of a campfire gone cold hours ago. It was a small thing, charred through and sooty, but it had somehow kept its shape. Leinore reached out her hand and picked it up.
#figure(image("004_Sisters/01.jpg", width: 100%), caption: [Leinore, Autumn Sovereign | Art by: Fariba Khamseh], supplement: none, numbering: none)
"Eww~" Sinnia said, the snout of her fox mask bobbing as she spoke. "Put it down."
Then, as if Leinore's touch had animated the creature, it wriggled its body and flicked its forked tongue. Leinore tossed it away with a scream. It landed back in the pit of ashes, still as anything—almost like it had never moved at all.
"Not so brave now," her sister laughed.
Her little sister always teased her with kindness. Leinore couldn't manage a smile, though. Not after the news of another missing family this morning. The ancient festival of Harvesttide, now revived, was supposed to bring hope to the people and restore the balance between light and darkness.
That's what the witches of the Dawnhart Coven promised her and the people of Kessig. "Help us bring back the light," they had said to the villagers. Even though they wore skulls on their heads and mud on their faces and looked as menacing as the monsters hiding in the woods, people agreed to help them. "Bring back the light," people whispered all around. Soon, it was more than a whisper. It was a promise and a prayer.
But more people turned up missing every morning, and the days seemed dimmer than ever.
Leinore didn't usually need cheering up. She would be the first one to get up in the morning, to prepare breakfast for her sister and her father before he left for the fields. Afterward, she would make the rounds through their small village, visiting elders who lived alone, or children whose families had been blighted by some catastrophe, supernatural or not, and share whatever baked goods she had made that day. It gave her peace to know people were happy, or at least content; a sense of order.
That order had been disturbed ever since The Travails. Now, the nights grew longer, and the days were cut too short. The winter frost came months earlier than it should have, draping Kessig like a thin veil.
Katilda, the leader of the coven, promised she could fix the imbalance if the festival was a successful one, and Leinore wanted nothing more. When the Dawnhart Coven asked her to oversee the festivities, she knew what the witches expected from her: to do what she had always been doing. She would keep the people fed, the decorations bright and the atmosphere festive. A simple job that was getting more and more difficult.
Leinore examined the empty tent in front of her. A woodsman and his family had found lodging inside for as long as the festival lasted. There were quite a few of those around, scattered in the clearings around the Celestus, sheltering travelers who arrived from all over Kessig. The creeping cold became unbearable in the late hours, even though it was only autumn.
With the blessings and charms of the hedge witches all around them, people had felt safe at first. The bravest of them slept out in the open with only the dark sky for a roof and their thick furs for covers. The moon loomed bigger and closer than ever, but the festivalgoers were less afraid of the dangers that lurked in the dark when the charms of the Dawnhart Coven were protecting them. Or at least, they had been. "Perhaps they left," Leinore mumbled. "They got tired of the cold, packed their stuff, and went home."
Sinnia shivered, though Leinore didn't think it was from the miserable weather. Her fox costume was covered in bright red maple leaves. Leinore thought she looked more like a rare and strange bird, ready to take flight.
"Their stuff is still here." Sinnia pointed at a small cloth bundle next to a shack, easy to miss under the frost and the leaves that had fallen during the night. "Besides, who would travel in the dark? I don't like this. Let's go home. They might turn up by tomorrow."
She was right, of course. This was the second family this week. Another tent left intact. Nobody could be in such a hurry that they would leave their things behind—or worse, travel through the Kessig forests during the night.
There was something else lying next to the bundle. It looked small and sinuous.
"I really hope that's not another snake." Leinore squinted. The mists were getting thicker as night approached.
Sinnia walked over the bundle and kicked around some of the frost and leaves.
"Oh, that's pretty!" Sinnia picked it up. It was a festival mask, but not like the ones the townsfolk wore at the Harvesttide. It looked more like a hedge witch's headdress, elaborate and off-putting. But that didn't make sense. The lost family was just a woodsman and his wife.
The scale-crusted mask was a deep gold. Sticks were fixed on top of it like most of the witches' headdresses, only instead of sunrays or moonbeams, they looked more like snakes coiling out from the plaster. Under the eyes of the mask, two long, wooden fangs stuck out.
"Put that down," Leinore said. Sinnia gave her a look, but it just didn't feel right to take things that weren't theirs. Even if the people had—
Something wasn't right. Leinore turned to her sister and said, "You know, we should get out of here while we still can. Go home."
Sinnia took off her fox mask and tried on the new one, causing Leinore to flinch.
"We don't know what happened to them," Leinore said slowly. "And father is always suspicious of everything since—"
She stopped. There was no point in bringing mother up. When the Cursemute—the spell that had cured so many werewolves—had broken, the creatures' bloodlust and animal instincts had carried them all off, including their mother. A small blessing: she never hurt anyone that they knew of, only returned to the woods. This made it easier for them to claim she had been killed by a bear, even if the villagers only pretended to believe this out of pity.
Sinnia shook her head. "You just don't want people to spoil your celebrations."
Leinore's face grew hot. "Please take off that mask."
But Sinnia ignored her. She tied the mask's ribbons tight over her black curls and did a small twirl. "I am pretty sure they won't be coming back to ask for it."
Leinore hated the mask. And it wasn't just the fact that Sinnia took it without permission. It made her uncomfortable. She didn't want to look at it straight in the eyes. #emph[Its eyes. Her eyes.] She shook off the strange thought. It was unnerving, that was all. No different than the witches' rituals.
"Let me talk to Katilda," Leinore softened her voice. Her sister could be headstrong sometimes but ultimately, she would listen to her. "Perhaps she can help. And #emph[please] take off that mask?"
"Fine." Sinnia took off the mask and donned the fox one again. She had made it, along with Leinore's deer mask, and was proud of both. "But I'll keep it until they come back."
#figure(image("004_Sisters/02.jpg", width: 100%), caption: [Hedgewitch's Mask | Art by: <NAME>], supplement: none, numbering: none)
She didn't believe Katilda and the coven had something to do with the missing people. There was something about the kind look in her eyes Leinore trusted. So what if they were strange? The witches had been hermits for so long it was natural to be cryptic about their rituals. Perhaps they didn't want their magic to fall into the wrong hands. And considering their power, Leinore didn't blame them. She had seen them split trees in half with a gesture or conjure water from the earth for thirsty festivalgoers.
But another thought crept about her mind. What if the rest of the coven was not as harmless as Katilda? Was the witch really in control of what was happening?
The thing slithered at the edges of her vision again, but this time it was only in her memory. There was something in the mists last night. Even now she could feel its oppressing presence all around. It felt like it was both gliding overhead—hidden somewhere in the thick canopy—and shifting under her feet, cloaking itself with dead leaves and frost. Leinore shivered and tried to tell herself it was nothing. Tomorrow, another festival day would start, and she would need to be its bright and happy face once again.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
In a city, all the roads lead to a church. Or so Leinore had heard people say. People who had traveled to places such as Thraben and seen buildings bigger than all the houses in Kessig put together.
In the Ulvenwald, all the roads led to the Celestus. The structure's golden glow pierced through branches and foliage. Its metallic rings reached the canopy overhead and even higher still. Leinore could see the glow when she was lying in her tent at night.
Around the machine, the people had set up tents and stalls for all sorts of trade. Not even the cold could stop a healthy appetite for coin. Blessed weapons were exchanged for precious family heirlooms, fur for leather, potions for magic scrolls that would keep their readers safe, or so the traders promised. If Leinore hadn't known better, she might have even believed their promises. She had seen real magic in the hands of the witches, though, and this felt nothing like it.
The people who felt unsafe sleeping in the forest had moved closer to the Celestus since last night, setting up their tents among the rest, huddling together like rabbits. The lights and the crowd must have made them feel protected. There was still laughter and music in the air, but now there was something wilder in the mix, too. Everything felt numb and dampened, and the hoarfrost sat on their shoulders like a couple of icy hands.
Leinore did her best to greet everyone she recognized despite the masks and welcome those she didn't, giving away branches of living wood for good luck. Sinnia was a few steps behind her, mimicking her sister and smiling, even though Leinore could hear her dragging her feet.
At the center of the Celestus, on top of the dais, Katilda and her coven were doing another one of their rituals. They had started simple enough, with plenty of food and beer and bright candles. There was dancing and singing that sounded more like howls, but the townsfolk did not seem to mind. Many of them, including Leinore, felt like howling themselves.
But after the first couple of days, their rituals became stranger and stranger. Beastly shapes seemed to dance inside the bonfires along with the witches. When the women opened their mouths to utter invocations, Leinore could see clumps of black dirt clinging to their teeth and staining their tongues. Ghrin-Danu's kiss, they called it.
Katilda's costume was getting more extravagant with each passing day, too. Today, along with the grassy shoulder pads and the massive headpiece meant to mirror the glory of the sun, she carried a mesh necklace made with ribbons and some sort of animal teeth. Two crimson lines were drawn under her eyes, like tears of blood.
Leinore widened her stride, leaving Sinnia behind.
#figure(image("004_Sisters/03.jpg", width: 100%), caption: [Dawnhart Rejuvenator | Art by: <NAME>], supplement: none, numbering: none)
Teeth were gathered in a heap in the middle of the coven's circle on the dais. When Leinore drew nearer to the dais, the teeth didn't look like they belonged to an animal at all.
They were very much human.
Leinore felt her stomach stir. The witches, mumbling a low chant under their breath, were binding the teeth in necklaces like charms and handing them out to the people. Some hesitated, looking at each other with plain disgust. Others grabbed the necklaces and shoved them hastily in their pockets or spat at the witches' feet and turned away.
"What is this?" Leinore managed to say.
Katilda turned up from her work. Surprise written on her face.
"They are teeth," she said plainly. "Werewolf teeth."
"They don't look like werewolf teeth." Leinore felt all the eyes on her. She glanced at the crowd, looking for Sinnia, but could not find her.
"Well," Katilda waved her arms around, slightly offended. "They shifted back into human form after death. But they still have the essence of the wolf."
Leinore tried not to think of her mother. Instead, her thoughts went to her sister, her father back in the village, the people gathered close to the dais. She was supposed to bring hope and light to the villagers and yet here she was, feeling all the light she had leaving her body.
#emph[Say something] , she said to herself. #emph[Anything.] But what could she say?
"Witch."
Leinore recognized the man by his volume alone. Jagger had always been the noisiest trapper in their village—not a good quality, for a trapper. He fancied himself important, a leader of everyone who had assembled here, regardless of how many people agreed with him. With each step he seemed to rattle. The noise was coming from the countless charms he had on him. Already a tall man, he had arrayed oxen teeth, runes, and blessed silver—or so he claimed—on top of his fur coat, to make him stand out from the crowd. A loud, angry man. He would only make things worse.
"Did you steal those from the missing villagers?"
Leinore's stomach clenched. A couple of days ago, she would have defended the witches without a shred of a doubt. But no matter how much she wanted to roll her eyes at Jagger, she wasn't sure he was wrong. Not completely.
"Missing?" another witch asked as if the news had not reached everyone.
"We are not your enemies," Katilda stepped down from the dais to face Jagger. "Harvesttide cannot succeed with witches alone. We must do this together."
"I don't trust someone who tells me nothing," spat Jagger. "You brought us here, asking us to help you. But you keep us in the dark."
"Don't trust the witches! Tell us where the missing are!" The voices were coming from all over. They demanded answers. Leinore could see the villagers growing increasingly restless, ready to burst with anger. They had come here for salvation, but they had only found the same darkness you could find in any corner of Innistrad.
"Wait a minute!" Leinore shouted at Jagger. "They didn't do anything. You have no proof."
Jagger sneered gesturing at the teeth. "Isn't this proof enough?" He was making a show of it now. "What's next? They feed us the flesh of the dead?"
"They are here to help us," Leinore made a pathetic effort. Her mind was elsewhere now. Where was Sinnia?
"By sacrificing people!" Jagger moved toward Katilda. He towered over her despite her imposing headpiece. He could easily brush her aside with a sweep of his arm. Leinore could feel the witch and the rest of the coven preparing for a fight.
"Nobody is sacrificing people," Sinnia said. Her voice came from somewhere close.
Leinore looked around but couldn't find her. Couldn't trace the fox mask among the rest of the autumn-colored masks. She was certain, though, that this was her sister's voice.
In the crowd, Leinore made out Sinnia's dress with the red and orange leaves. Her long curly hair swayed left and right as Leinore's sister walked toward her. Those at least had stayed the same—her fox mask wasn't there anymore. In its place, Sinnia wore the new mask.
"You speak as if the woods have not been full of dangers ever since we were born," Sinnia said while climbing up the dais.
Everyone stopped, even Jagger and Katilda. As if someone put them under a spell, their anger died down as fast as it had erupted.
"Anything could have taken them. So many hungry things lurk in the dark. Vengeful spirits, vampires, ghouls, werewolves."
There were voices of agreement in the crowd, now. Everyone looked at the pile of teeth as if they were seeing them for the first time. Their eyes were glassy, but they were listening to what Sinnia had to say as if she were the only one who mattered now. Leinore was staring at her sister in disbelief. Her stomach twisted from a sudden dread she could not explain.
"If anything, their demise should humble us. We can't do anything while the darkness grows. Bring back the light." Sinnia gestured at the floating candles, and they seemed to burn brighter, a new spark born inside them.
"Bring back the light!" People shouted.
Some of the people clapped. Music rose from somewhere in the back of the crowd. Jagger opened his mouth to speak but nobody was paying attention to him anymore. Neither to Katilda nor the coven. The villagers were circling Sinnia, touching her hands with adoration, gently pulling her to their company, their music, their dances.
Everyone was happy and hopeful, just like it had been on the first day. Even the cold seemed less bitter now.
So why was Leinore shivering with fear?
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
When they returned to their tent that night, Sinnia brought a fur that a trapper had gifted her and threw it at Leinore. She was still wearing the mask.
"Get warm," she said. "It's going to be a long few days."
Leinore didn't stir from her corner of the bedding. Every time the mask looked at her, she felt another presence in the tent with them. #emph[Not the mask] , she told herself. #emph[Sinnia. Every time Sinnia looks at me.]
"I thought you said we should leave," Leinore mumbled.
Sinnia took off her costume. Pieces of dried leaves fell to the ground, like a snake shedding its skin. She left her mask on. She crouched on the floor a few inches from Leinore's face. Her breath smelled of dead things, ashes, and rust. "I don't want to leave anymore. The Coiled One has spoken to me today, sister." Her voice came out deeper, raspier. Like coming from somewhere else. Someone else. When she smiled, Leinore thought she saw a forked tongue peek out of the slit between her teeth. "The light will return to Innistrad."
The oppressiveness of what Leinore felt last night returned, only this time worse.
"You feel it too?" asked Sinnia, almost too delighted to contain herself. "The Coiled One is surfacing."
The air was squeezed out of Leinore's chest by an unfolding presence inside the tent. It made her mind foggy. The leaves faintly rustled in the trees as if something was hiding, right above their heads. When she looked at Sinnia again she was lying still on her bedroll, mask still in place. Not sleeping, Leinore was sure. More like pretending to be asleep.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
It had been two nights since they found that mask. For the tenth time that night, Leinore ground a snake under her boot. It was small as a human finger, brown, and covered in bile, like the ones before. It stirred a little bit under her shoe, just enough to make her cringe, and then was still. She should have been used to them by now but wasn't. These were no ordinary snakes.
Somehow over the last few days, Sinnia had replaced Leinore as the Sovereign of Harvesttide in the eyes of the festivalgoers. She basked in the attention as they looked to her to light the first lantern of the night, to raise a toast to the noonday sun. Not only was she more confident than before, but she had a strange effect on people. Wearing that mask made people listen to her in a way they didn't listen to Leinore or even Katilda. If Leinore had not known her sister, she would swear she was one of the witches, and a very powerful one at that.
The changes to Sinnia's personality, unnatural though they may have been, were nothing compared to what she could do to people now. The first time Leinore had watched it, she had been horrified: she would touch someone on the brow, whisper something under her breath, and the villager would begin to choke. Their eyes would roll back into their head until they coughed out a small, squirming serpent. It was nightmarish—and yet the others seemed to rejoice as if every new snake was cause for celebration.
#figure(image("004_Sisters/04.jpg", width: 100%), caption: [Celebrate the Harvest | Art by: <NAME>], supplement: none, numbering: none)
The screams, "Bring back the light!" rose from the crowd. The people's faces were contorted by such wild joy that Leinore found the villagers more terrifying than any werewolf. They could not tell what was natural and what was cursed anymore, and Leinore was unsure she could either.
Leinore used every power an older sister had over a younger one to make things right again. She yelled at her, threatened to tell their father, tried to grab Sinnia and drag her back to their tent. But of course, the villagers would come between them every time. A wave of bodies crashing against hers and circling her sister's. Begging Sinnia for more miracles, more snakes. More light. To them, she was more than the Sovereign now; she was their savior. Nobody seemed too concerned this time with the group of goatherds that went missing during the night. If Sinnia told them it was alright, then it was.
Leinore needed her sister more than ever, but the Sinnia she knew was gone. The last glance Leinore stole of her that night was when Katilda offered her a headpiece from their coven in exchange for her mask. The headpiece had deer antlers instead of sinuous sticks and was painted with blood mixed with mud and leaves. Leinore was not close enough, so she could not hear what the two women said to each other. But Sinnia laughed in Katilda's face and turned away.
Leinore returned to their tent first, hid under the furs, and waited. Sinnia was up to something. Every night after she found that mask, she would leave their bed and come back only when the first weak light peered inside the tent. Not long after, she heard frozen leaves crunching under someone's footsteps. She could tell it was Sinnia by the way the atmosphere shifted, squeezing the air out of her lungs. She curled up into a tight ball and tried her best to disappear under the covers.
When Sinnia entered the tent, she went straight for their bed. Leinore had her eyes shut but she felt her sister's scrutinizing gaze on her. She kept her breath even and her face relaxed, praying that her heartbeat wouldn't betray her. It was only a few agonizing moments, but they felt like hours. When Sinnia was certain Leinore was fast asleep, she left the tent. Then she slowly slid from beneath the furs and got up, still dressed.
Leinore followed Sinnia into the night. The only thing Leinore left behind was her mask.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Tracking her sister's steps was harder than she thought. Perhaps she had waited too long for Sinnia to disappear behind the tall trees, and now her chance was gone. Leinore shuffled around the frozen undergrowth for a while, her only light coming from the distant, fading glow of the Celestus on the horizon, the candles, and the occasional lantern.
Then she heard the crawling again. Whatever it was, it was materializing. It was more than a feeling. So tangible she could now hear it. It sounded far away, but there was no denying it was the same thing she was hearing for days now, and it was coming from the northwest, toward the heart of the forest. Leinore licked her dry lips and followed the noise.
Not too long after she came out into a small camp made up of five tents, a sign that mostly loners must have been camping there. Before she even got close, she heard someone making a gurgling sound, as if their head was plunged underwater. Panic fought against any desire to help; she ducked behind a tent as two figures emerged in the distance. One she was sure belonged to her sister, Sinnia. The mask betrayed her even in the dark. But the way the two shapes stood did not make sense. It looked like Sinnia held a man by the throat as easily as if he was a dead raccoon. She was dragging him over leaves and hoarfrost, away from the small camping site and deeper into the heart of the woods.
She followed the figures to a strange clearing covered by a thick canopy of branches. Leinore stopped in her tracks as her sister kept dragging the body of this man toward an oval rock at the edge of the clearing.
No, not a rock. An egg.
It was at least as big as the man she carried and sat next to a line of many others. They were pale green and iridescent, glowing in the dark like little balls of light. Sinnia touched the egg and it gave way to her touch, opening like a leathery flower. To Leinore's horror, she watched her sister push the unconscious man into it. The egg closed around him, enveloping him like a womb.
Leinore tried to move, but her limbs felt numb and heavy. She had to try not to let her knees give. Too late, she realized her sister was not alone: a woman stood in the shadows behind the oversized eggs. With a gesture, she seemed to dismiss Sinnia away, to bring what Leinore guessed would be the next victim.
Leinore felt someone grabbing her shoulder. She tried to scream, but before any air could leave her mouth, a hand clamped over her face. In her ear, a familiar voice whispered harshly, "Don't move. Here she comes."
For a moment Leinore thought Katilda meant the woman in the shadows, but instead Katilda pointed her staff at her sister with calm determination. The edge of the wood sizzled with unnatural light, and Leinore could feel the heat on her face as the staff began to gather its killing energy. Without thinking, Leinore bit down on Katilda's hand. The witch howled in pain and let go of the staff.
"You stupid girl!" Katilda growled as she crouched in the undergrowth, fumbling for her staff. "I could have saved us."
That's when the woman left the shadows and came closer, her eyes glowing green.
#figure(image("004_Sisters/05.jpg", width: 100%), caption: [Saryth, the Viper's Fang | Art by: <NAME>], supplement: none, numbering: none)
"Katilda," the woman sounded amused. "Is that you?"
"Why didn't you aim at her?" Leinore shouted, gesturing to the unknown woman.
"Saryth isn't the one wearing the mask," Katilda said, picking up her staff. "Your sister is. All of Saryth's power is in that mask. Sinnia is consumed by it. There is no hope for her now."
The ground beneath their feet began to tremble and heave, and Leinore found herself fighting to stay standing. She could see the treetops swaying back and forth like drunk dancers.
"What's going on?"
"It's the Coiled One. Saryth called him to chase the darkness away and has been feeding him those ensorcelled townsfolk for days now." Katilda laughed bitterly. "I was a fool to not see it sooner. She will destroy us all."
The earth below her sister split apart, revealing black soil like blood in a wound. Leinore wanted to go to her, but it was hard to steady herself, let alone walk straight. Where the fissures met, dirt and trees sank and disappeared from view. Soon, there was a gaping hole inches from where Sinnia stood.
The eggs glowed brighter, and the woman whom Katilda called Saryth lifted her staff, aiming at Leinore and Katilda.
"It is time!" Saryth screamed.
A beam of energy flashed in front of Leinore's eyes, and for an instant, she saw only green. She thought she heard Sinnia scream somewhere not too far away, and a wave of despair hit her. What if the hole had swallowed her sister and she was already too late?
When her vision cleared again, she saw him coming out of the hole—or part of him. A wall of scaly flesh writhing in front of her sister. Leinore's mind froze trying to take in the entirety of it, but she could not. No matter how much she craned her neck; her human eyes were not enough to perceive it. A sickening feeling rose in her chest. She couldn't move, her muscles frozen in fear.
"Don't look at him!" she heard Katilda scream. "Listen to me: if he eats her while she wears the mask, we are doomed. I need your help."
The witch was clutching her arm, wounded by Saryth's magic. There was a nasty-looking wound where her sleeve had been torn. The cloth was drenched in blood, and pus was oozing from the raw meat underneath.
"We must destroy Sinnia. The mask won't come off by itself."
Leinore made herself stand straight. Every muscle in her body tightened.
"Don't you dare touch my sister. I'll get the mask off her."
"She is already gone, Leinore!"
"Let me try. You have to distract Saryth for me."
Katilda nodded.
"One chance." She raised her staff and green sparks flew from its tip.
Leinore stumbled across the shaking earth, heading for her sister. As she looked up at the creature, two wide black eyes emerged from the surface of the scales, impossibly large.
#emph[Don't look at it] , she thought. #emph[Get it together.]
Leinore touched her sister's arm to wake her from her stupor. Sinnia's hand was icy cold, and her eyes were burning with a bright and terrible light, a glow that seemed to Leinore unbearably old. When she looked at Leinore through the eyeholes of the mask, there was no fear, only ecstasy.
But when Leinore came closer, she heard a faint whisper from Sinnia's lips.
"Help me."
A deep rumbling sound came from the chasm, and Leinore realized she had not yet seen the creature's mouth. She grabbed Sinnia's cold arm and pulled. Sinnia let Leinore lead her passively. As they were running toward a cluster of trees, she could feel the ground fall away mere inches behind them. Out of the corner of her eye, she saw Saryth aiming her staff at Katilda now. Vines lunged from the trees, like ravenous serpents, and wrapped around the hedge witch's throat. Katilda lifted her free hand, and shale burst from the ground toward the other woman in jagged, rippling bursts. One cluster tore through the stand of trees Leinore had been running for; she threw herself and Sinnia to one side.
Katilda rose to her feet and turned to face Saryth. At her eerie whisper, a gust of wind whipped through the trees, gathering a swarm of leaves that seemed to whirl with a razor-sharp edge, attacking Saryth. She shifted her position to negate the number of deep slices on her skin, losing her balance in the process. For a moment, Leinore thought Saryth would find her footing and counterattack; Saryth's staff was buzzing with power again. But she had forgotten the many fissures, gaping around her. Instead of landing on solid ground, her left foot went straight into one.
Saryth's eyes bulged in surprise as she spread her arms, desperate to grab onto something, her staff dropping from her hand. But there was nothing to grab onto, no vines left. And in an instant, Saryth was gone—swallowed by the chasm.
Leinore grabbed Sinnia, who struggled feebly in her arms. The mask seemed to have fused itself into her skin. Leinore tried to find an edge to peel it off but there was no beginning and no ending.
The ground shuddered again as the massive serpent moved. Its passage felt like the end of the world, and it was coming for Sinnia. Far, far above them all, the Coiled One opened a mouth as wide as any chasm, ready to swallow them both.
#emph[We must destroy her.] Katilda's words echoed in Leinore's mind. She could make out the witch somewhere on the other side of the hole. Her sister's face was so calm, it made her nauseous. She had never seen anyone look so peaceful, even as the monstrous creature approached. Sinnia was still whispering something. In what she was sure would be their final moments, Leinore leaned in closer to hear.
"Rip it off~"
Leinore reached a hand to the mask and touched her sister's skin. Or what felt like her skin. Without thinking she started to pull as hard as she could. Her nails sank inside Sinnia's cheek and for the first time she screamed.
#emph[It's working.]
She pulled harder.
The mask started to rip like a piece of wet parchment. The Coiled One's breath was hot and damp above them, coming in horrible rotten waves as it bent that tremendous head toward them.
#emph[One last pull.]
Sinnia screamed, or was it the beast?
When the mask came off it turned back into the hard thing made of sticks and leaves. Sinnia's face was so red and raw, Leinore almost didn't recognize her. But that awful glow had left Sinnia's eyes.
"Sinnia?" Leinore stared at her face for a hard minute, searching for her sister.
"Thank you," Sinnia said, her voice faint. She blinked a few times, and then her stare focused on Leinore.
They were interrupted with a sound like a hurricane, a bellow of primal rage from the massive creature Saryth had unleashed. Leinore covered her ears reflexively, but it seemed to be in the throes of some kind of agony. It was retreating—actually retreating—down, down, into the chasm from which it had come. With one last hiss, the Coiled One dragged its body to the depths of the earth, pulling eggs and surrounding foliage down. The ground shook one more time before Leinore and Sinnia lost sight of it.
Leinore let the mask go. As it tumbled down the cavernous hole, she pulled her sister up with all the strength she had left, and with Katilda, they limped back to the settlement. Noises were coming from different parts of the woods; yelling, and crying, and even some laughter.
Soon, they found people stumbling around, wondering among themselves how they got there and which day of the festival it was. Members of the Dawnhart Coven were gently leading people back toward the Celestus. Nobody was spewing snakes, and there were none in the undergrowth either. Just leaves and frost under her feet. Nobody seemed to remember it, and not a soul asked about the guttural noises that shook the woods. If there weren't still so many missing, it would have been like nothing had happened.
Leinore knew that wasn't true, though. And from the look on Sinnia's face, she knew her sister would remember what had happened tonight forever. Before the festivalgoers enveloped her completely, Leinore turned and looked back into the woods. She felt it only faintly—the rustle in the trees, under the earth, as if a presence was passing her by.
The Harvesttide Sovereign shivered and turned away.
|
|
https://github.com/antonWetzel/prettypst | https://raw.githubusercontent.com/antonWetzel/prettypst/master/test/otbs/headings.typ | typst | MIT License | = Top
== Sub
#lorem(1)
== Sub 2
=== Subsub 3
#lorem(1)
== Sub 3
#lorem(1)
== Sub 4 <label>
=== Subsub 4 <label_2>
#lorem(1)
|
https://github.com/OthoDeng/Typst-notes | https://raw.githubusercontent.com/OthoDeng/Typst-notes/main/Undergrad/24fall/notes_2024fall.typ | typst | #import "@preview/dvdtyp:1.0.0": *
#import "@preview/chem-par:0.0.1": *
#show link: it => {
set text(fill: blue)
underline(it)
}
#show: dvdtyp.with(
title: "我包罗万象",
subtitle: [_2024 fall_],
author: "365",
abstract: [This note is made using #link("https://typst.app")[Typst]. It includes but not limits to Atmospheric Physics, Fluid Dynamics, Equation of Mathematics and Physics. all rights reserved],
)
#outline()
#pagebreak()
#show: chem-style
#pagebreak()
= 大气物理
== 大气成分历史
#definition("大气成分历史")[
1. $H_2$ $H e$ 阶段 => 45.6亿
2. 还原性大气 => 25亿
3. 氧化性大气 => 3.5亿
]
- 干洁大气:不含水汽和悬浮颗粒物的大气称为干洁大气;
- 相变特征:在地球大气温压条件下,水汽是唯一能发生相变的气体成分;
- 空气密度:标准状态下,干空气密度为$1.29 k g⋅m^(-3)$
- 平均分子量: 90 km以下,空气平均分子量为 28.966,不随高度变化;90km以上,随高度递减。
#theorem("CO2")[
- 二氧化碳是在地壳、大气层、海洋和生物圈之间循环的。
- 人工源:主要的人工源是矿物燃料燃烧和工业活动。
- 自然源:死亡生物体的腐败和呼吸作用也都排出二氧化碳。
- 汇:植物的光合作用,海洋能吸收大量二氧化碳。
- 对气候影响:二氧化碳有强烈的“温室效应”作用。
]
#figure(image("pic/Greenhouse effect.png",width: 15cm))
== 气溶胶
#theorem("大气气溶胶")[
- 气溶胶是指悬浮在气体中的固体和(或)液体微粒与气体载体共同组成的多相体系。
- 大气气溶胶是指大气与悬浮在其中的固体和液体微粒共同组成的多相体系。
]
对流层生成O3:光化学反应,Cl原子消耗O3(氟氯烃)
== 大气垂直结构
#definition("气温垂直递减率")[
$
gamma = - (partial T)/(partial z)
$
]
=== 对流层(troposphere)
从地面到1~2 km高度为行星边界层,其中的50~100 m以下的气层称为近地层,近地层以上到边界层顶称为上部摩擦层。
#theorem("比热显热潜热")[
- 对流层集中了约75%的大气和90%以上的水汽质量。
- 气温随高度增高而降低,北半球低纬地区平均气温直减率约 6.5 $°C⋅"km"^(-1)$ 。
- 垂直运动剧烈,有利于大气成分在垂直方向上的输送。
- 主要天气现象都在对流层内形成。
- 空气受地表影响很大,气象要素水平分布不均匀。
]
=== 平流层(stratosphere)
- 空气稀薄,能见度好,很少出现天气现象。
- 在15~35 km范围内,有厚约20 km的臭氧层。
=== 中间层(mesosphere)
垂直温度梯度大,有强烈的垂直混合,气压和密度随高度升高而降低的程度远慢于低层大气。
在这一层高纬度地区常出现极光现象。
== 基本气象要素
$ K= degree.c+273.15, degree.c=5/9 (degree.f -32) $
=== 能量、气温和热
#definition()[
- 比热 (Specific Heat):是单位质量物质的热容量,即单位质量物体改变单位温度时吸收或放出的热量。
- 显热(Sensible Heat):The heat we can feel, “sense” and measure with a thermometer.
- 潜热 (Latent Heat ) :The amount of heat exchanged that is hidden, meaning it occurs without change of temperature. 例如,水汽凝结成液态水的相变过程中释放的热量即为凝结潜热。
]
=== 温度的控制因子
最重要的影响因子当然是到达地面的太阳辐射总量,其他主要的控制因子:#highlight("1. 纬度, 2.海拔高度, 3.陆地与水体的分布, 4.洋流. ")
#pagebreak()
= 流体力学
== 研究方法
1. 理论方法
2. 计算方法(数值方法)
3. 实验方法
== 物理性质
1. 流动性
处于静止状态下不受任何剪切力,不论在如何小的剪切力下流体都形变。
2. 黏性
抗切变性或者阻碍流体相对运动的特性。
理想流体 ($mu = 0$,黏性系数)
3. 压缩性
液体不可压缩,气体可压缩。
低速流体下压力差温度差变化不大(联想$p V = rho R T$)
不可压缩流体($nabla dot bold(V) = 0$,散度为0)
=== 连续介质假设——宏观理论模型
无数质点没有间隙——流体连续介质假设
流体质点——微观足够大,宏观足够小
#theorem("克努森数 Knudsen")[
$ K n = l/L $
当$K n << 1$时流体连续介质才适用。
]
== 流体速度与加速度
=== 描述两种方法
1. Lagrange 质点/随体
类比探空气球、篮球盯人
2. Euler 场
类比水文站、篮球群防
=== 速度
1. Lagrange
用笛卡尔坐标(右手定则)
$ bold(r) = bold(r)\(x,y,z\) = x bold(i) + y bold(j) + z bold(k) $
初始位置$t_0$ 位于$(x_0,y_0,z_0)$点,#highlight("做标记")
$ bold(r) = bold(r)(x_0,y_0,z_0,t) $
分量形式:
$
cases(
bold(x) = bold(x)(x_0,y_0,z_0,t)\
bold(y) = bold(y)(x_0,y_0,z_0,t)\
bold(z) = bold(z)(x_0,y_0,z_0,t)
)
$
对$t$求导:
#definition("拉格朗日观点下速度")[
$
bold(V)(x_0,y_0,z_0,t) = dif/(dif t) bold(r)(x_0,y_0,z_0,t)
$]
2. Euler
#definition("欧拉观点下速度")[
$
bold(V) = bold(V)(x,y,z,t)
$
其分量可以写成:
$
cases(
u &= u(x,y,z,t)\
v &= v(x,y,z,t)\
w &= w(x,y,z,t)
)
$
]
- 当流场不随空间变化 => 均匀流场 $partial/(partial x) = partial/(partial y) = partial/(partial z) = 0 \/ nabla dot () = 0$
- 当流场不随时间变化 => 常定(稳定)流场 $partial/(partial t) = 0$
=== 流体加速度
#theorem("Langanrage's Method")[
$
bold(a) = dif /(dif t) bold(V) \(x_0,y_0,z_0,t\)
$
]
#theorem("Euler's Method")[
$ (dif bold(V))/(dif t) &= (partial bold(V))/(partial t) + (partial bold(V))/(partial x) (dif x)/(dif t) + (partial bold(V))/(partial y) (dif y)/(dif t) + (partial bold(V))/(partial z) (dif z)/(dif t)\
&= (partial bold(V))/(partial t) + (bold(V) dot nabla)bold(V) = ((partial )/(partial t) + bold(V) dot nabla)bold(V)\
"加速度" &= "局地加速度" + "平流加速度"
$
]
#proof[
$ bold(a) = dif /(dif t) bold(V) \(x,y,z,t\)
$
微商算符
#highlight[$ underbrace(dif/(dif t) (dot),"个体变化") = underbrace(partial/(partial t) (dot),"局地变化") + underbrace(bold(V)dot nabla(dot) #v(0.8cm),"平流变化") $对于任意矢量与标量都成立]
]
1. 流体在运动过程中所具物理量不随时间变化
$ dif/(dif t)() = 0 "或" partial/(partial t) =- bold(V) dot nabla() $
局地变化完全由平流变化引起。
2. 流体所具物理量分布均匀,或者说流体#highlight("运动方向均匀"),
$
bold(V) dot nabla() = 0 "或" partial/(partial t)() = dif/(dif t) ()
$
局地变化由个体变化引起。
== 迹线与流线
迹线方程不存在时间t,流线方程可以存在时间t
=== 迹线
某个流点各个时刻所行路径轨迹线 Lagrange 观点
#highlight("消去时间t")
=== 流线
某一固定时刻,曲线上任意一点流速方向与该点切线方向相吻合。 Euler 观点
#theorem()[
$
dif bold(r) times bold(V) &= mat(delim: "|",i,j,k;u,v,w;dif x,dif y,dif z)= 0\
&=> (dif x)/u = (dif y)/u = (dif z)/u
$
t作为常数,积分时做常数处理
]
流线只能反映方向不能反映大小
#pagebreak()
= 数理方程
#theorem("Lapalce Function")[
$
(partial ^2 u )/(partial x^2) + (partial ^2 u )/(partial y^2) +(partial ^2 u )/(partial z^2) = 0
$
Where $u = 1\/(sqrt(x^2 + y^2 +z^2))$
]
== 偏微分方程
#theorem("一阶线性微分方程解")[
The solution of $ y' + P(x)y =Q(x)$ is
$
y = e^(- integral P(x)dif x) \(integral Q(x) e^(integral P(x)dif x) dif x + C \)
$
]
#definition($Delta , nabla, "div" "and" "rot" $)[
$ Delta &eq.triple (#sym.partial ^2)/(#sym.partial x_1 ^2) + (#sym.partial ^2)/(#sym.partial x_2 ^2) + dots + (#sym.partial ^2)/(#sym.partial x_n ^2) ,"拉普拉斯算子"\
nabla &eq.triple \( (#sym.partial ^2)/(#sym.partial x_1 ^2),(#sym.partial ^2)/(#sym.partial x_2 ^2), dots , (#sym.partial ^2)/(#sym.partial x_n ^2) \) , "哈密顿算子"\
"grad" bold(A) &= nabla dot bold(A) \
"rot" bold(A) &= nabla times bold(A)
$]
$nabla(nabla U) = Delta U, "in short" => nabla^2 = Delta$
=== 弦的微小振动
1. 水平方向(仅有张力分量没有位移)
$ T(x+ delta x) = T(x) => "T"与"x""无关"
$
2. 垂直方向
$ -T sin alpha + T' sin alpha ' - rho g dif x &approx rho dif x (partial^2 u(x,t))/(partial t^2)
$
$sin alpha approx tan alpha approx dif x$
$
T/rho &underbrace(1/(dif x) [(partial u(x + dif x,t))/(partial x)-(partial u(x,t))/(partial x)]) approx (partial ^2 u(x,t))/(partial t^2)+g\
&approx (partial^2 u(x,t))/(partial x^2) $
#theorem("一维波动方程")[
$
(partial^2 u )/(partial t^2) =a^2 (partial ^2 u)/(partial x^2) + f(x,t)
$
$a^2 = T\/rho , "外力" f(x,t) = F(x,t)\/rho $
]
=== 热传导方程
#highlight("能量守恒定律:")
$ underbrace(Q_2,"V中增加热量") = underbrace(-Q_1,"边界流入热量") + underbrace(Q_3,"内部产生热量") $
#proof(
$
Q_1 = - integral^(t_2) _(t_1) integral.surf_S k (partial u)/(partial n) dif S dif t
&= -integral^(t_2) _(t_1) integral.surf_S k nabla u dot bold(n) dif S dif t \
&= - integral^(t_2) _(t_1) integral.triple_V k Delta u dif V dif t ,"高斯公式 高数下"
$
+ "高斯公式:"+$
integral.surf_S [P cos(n,x) + Q cos(n,y) + R cos(n,z)] dif S = integral.triple_V ((partial P)/(partial x) +(partial Q)/(partial y) + (partial R)/(partial z)) dif V
$
)
#theorem("三维热传导方程")[
$ u_t &= a^2 Delta u + f(x,y,z,t),"有热源"\
u_t &= a^2 Delta u ,"无热源"
$
$a^2 = k\/(c rho) , f(x,y,z,t) = F\/(c rho)$
]
=== 位势方程
$u$不随时间变化而变化,常定:$(partial u)/(partial t)=0$
== 定解问题
偏微分方程 + 特定条件
=== 初始条件(Cauchy),得出初始状态
- 弦振动
1. 固定端 $u(L,t)= 0, t>= 0$
2. 自由端 $T (partial u)/(partial x) |_x_(x=l) = 0$
3. 弹性支撑端
#pagebreak()
= 热力学
== 热力学系统平衡以及描述
大量微观粒子组成的宏观物质系统 ($10 ^(23)$数量级)
#definition("系统分类")[
$
"根据是否与外界物质/能量交换分类" ==>cases(
"孤立系"\
"闭系"\
"开系"
)
$
]
热力学平衡(Thermodynamic Equilibrium)
#definition("弛豫时间")[
系统有初始状态到平衡状态所需时间
]
热动平衡——粒子统计平均效果不变
- 均匀系——Homogeneous System
- 非均匀系——Heterogeneous System
1. 几何参量 2. 力学参量 3. 化学参量 4. 电磁参量
#definition("简单系统")[
只需要体积$V$、压强$p$可以确定系统状态
]
$ 1 "atm" = 101 325 "Pa" $
非绝热的器壁——透热壁
#theorem("Temperture")[
A、B互为热平衡系统 $<=>$ 存在相等的状态函数 $g_A (p_A,bold(V)_A) = g_B (p_B,bold(V)_B)$
有相同的冷热程度
]
纯水的三相点温度数值为273.16
#definition("温标")[
$
T_V "数值" = p/p_t times 273.16
$
]
== 物态方程 Equation of State
$P V = n R T$
温度与状态参量之间的关系
=== 物态方程有关物理量
- 体胀系数
#theorem("Volumetric expasion coefficient")[
$
alpha = 1/(V) ((partial V)/(partial T))_P
$ 压强不变,温度升高引起物体体积相对变化
]
- 压强系数
#theorem("Pressure coefficient")[
$
beta = 1/p ((partial p)/(partial T))_V
$
]
- 等温体积系数
#theorem("Isothermal compressibillity coefficient")[
$ kappa_T = - 1/V ((partial V)/(partial p))_T
$ 取负号 s.t. $kappa_T$ 为正值
]
#proof(
$ alpha = kappa_T beta p $ +
"since:" + $ ((partial V)/(partial p))_T ((partial p)/(partial T))_V ((partial V)/(partial p))_p = -1
$
)
#theorem("范式方程")[
$
(p + (a n^2)/(V^2)) (V - n b) = n R T
$
$ underbrace((a n^2)/(V^2),"引力修正"),underbrace( n b#v(2em),"斥力修正") $
]
== 功 Work
#definition("准静态过程 ")[
进行非常缓慢,每个状态都可以看作平衡态
]
体积功,外界对系统做的功
$ W = - integral_(V_1)^(V_2) p dif V $
等容过程: $W = 0$
等压过程:$W = - p Delta V$
== 热力学第一定律
#theorem()[
$ Q eq.triple U_B -U_A -W
$从外界吸收能量 = 两个状态之差 - 系统做功
]
说明第一类永动机不能实现,需要外界供给能量来对外界做功。
#pagebreak()
= 大气化学
推荐阅读:
```
Atmospheric Chemistry and Physics: From Air Pollution to Climate Change
by <NAME> & <NAME>, <NAME> & Sons, Inc., 2016
```
== Evolution
During the evolution, O2 ever peaked at ~35% (300m years ago), dropped to ~11% (250m years ago)
Oxygen (in greek: #highlight("acid former"))
== Layers of the Atmosphere
#figure(image("pic/Layeratmos.png", width: 20cm))
绝大多数化学过程发生在Tropo & Strato
#theorem("Troposhere")[
- Contains ~82% of atmosphere mass & most water vapor, clouds
- Bottom ~1.5km is “boundary layer” or “mixed layer”
- BL height increases throughout day b/c of solar heating, typically higher in summer
]
Variation of pressure with altitude
$
P(z) = P(0) e^(-z\/bold(H))
$
where $bold(H) $ is scale height $ H = (R T)/(M_a g) approx 7.4 "km" $
Mixing Ratio (混合比)
$
xi_i &= c_i/(p\/R T)\
&= (p_i\/ R T)/(p\/ R T)\
&= p_i/p
$
#problem()[
P = 1 atm, T = 298 K 下 $O_3$ 混合比为120ppb, 相当于多少$mu g \/m^3$?
$
mu g \/m^3 &= (p M_i)/(R T) times "Mixing ratio in ppm"\
mu g \/m^3 &= ((1.103 times 10^5)(48))/(8.314(298)) times 0.12
$]
== 大气成分和排放源
=== 大气污染物的直接排放源(一次来源)
1. 人为源 Anthropogenic sources
2. 天然源 Natural sources
#highlight("生物(动植物)排放")
=== 大气污染的生成(二次来源)
#definition()[
进入大气的某些一次污染物,受环境中物理的、化学的或生物的因素作用,转化生成的大气污染物则为二次污染物。]
=== 复合污染
#definition()[
复合型大气污染: 是指大气中由多种来源的多种污染物在一定的大气条件下(如温度、湿度、阳光等)发生#highlight("多种界面间的相互作用彼此耦合构成")的复杂大气污染体系。]
结果: 二次污染物,尤其是颗粒物细粒子大量增加
=== 大气污染物来源分析技术
1. 源清单 2. 扩散模型 3. 受体模型
== 大气污染物的汇机制(考点!)
1. 干沉降(dry deposition):重力沉降,与植物、建筑物或地面相碰撞而被表 面吸附或吸收的过程;大气特性、表面特性和污染物本身特性会影响干沉降速 率。
2. 湿沉降( wet deposition ):通过降水而落到地面的过程;#highlight("雨除")是被去除物 质参与了成云过程;#highlight("冲刷")是指在云层下部即降雨过程中的去除。
3. 化学过程:实际上不是真正的去除,而是污染物存在形式的转化;
4. 向平流层输送:相对于对流层而言是去除过程。
== 大气痕量组分及分类
1. 含硫化合物 (sulfur-containing)
#highlight("H2S DMS(二甲基硫)")
2. 含氮化合物 (nitrogen-containing)
3. 含碳化合物 (carbon-containing)
4. 含卤素化合物 (halogen-containing)
5. 臭氧 (ozone, O3)
6. 颗粒物 (particulate matter, PM)
=== 臭氧(O3):对流层化学
- 天然源:平流层注入(约90%的臭氧集中在平流层) 对流层光化学过程→背景浓度上升
- 人为源: VOCs /CO + NOx = O3
- 汇:
- 气相反应
- O3 +hv = O(1D) + O2(O(1D) + H2O = 2 OH)\
- O3 + NO = NO2 + O2
- 液相反应
- O3 + SO2 = H2SO4
- 干沉降
=== 颗粒物(Particular matter, PM):气溶胶化学
#definition("气溶胶 aerosol")[液体或固体微粒均匀地分散在气体中形成的相对稳定的
悬浮体系,狭义上就是指大气中的颗粒污染物。]
#highlight("气溶胶的源汇与一般大气污染物的源汇类似。")
=== 含硫化合物:H2S
#definition("H2S")[
- 源:植物腐烂(热带雨林、湿地、稻田、海洋等)
- 汇:H2S + OH = H2O + SH
]
=== 含硫化合物:DMS
#definition("DMS")[
- 天然源: 海洋、湖泊、沼泽、湿地(浮游植物藻类 的光合作用)
- 汇: DMS + OH= MSA $=> "SO"_4^(2-)$
]
=== 含硫化合物:SO2
#definition("SO2")[
- 人为源: 化石燃料的燃烧:占人为源的88%
- 天然源: 火山活动
- 汇: SO2 $=> "SO"_4^(2-)$(干、湿沉降)
]
=== 含氮氧化物
NOx = NO + NO2
NH3
=== 含碳化合物
大气中的甲烷是丰度最高的气态有机物(1.8 ppm) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.